org-export: Add tag inheritance to `org-export-get-tags'
[org-mode.git] / lisp / org.el
blob66b0e0937a2c6237c1d155cb4463bcf08544e8f4
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2012 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Bastien Guerry <bzg at gnu dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum))
77 (require 'calendar)
78 (require 'find-func)
79 (require 'format-spec)
81 (let ((load-suffixes (list ".el")))
82 (load "org-loaddefs" 'noerror nil nil 'mustsuffix))
84 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
85 ;; some places -- e.g. see the macro org-with-limited-levels.
87 ;; In Org buffers, the value of `outline-regexp' is that of
88 ;; `org-outline-regexp'. The only function still directly relying on
89 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
90 ;; job when `orgstruct-mode' is active.
91 (defvar org-outline-regexp "\\*+ "
92 "Regexp to match Org headlines.")
94 (defvar org-outline-regexp-bol "^\\*+ "
95 "Regexp to match Org headlines.
96 This is similar to `org-outline-regexp' but additionally makes
97 sure that we are at the beginning of the line.")
99 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
100 "Matches an headline, putting stars and text into groups.
101 Stars are put in group 1 and the trimmed body in group 2.")
103 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
104 (when (fboundp 'defvaralias)
105 (unless (boundp 'calendar-view-holidays-initially-flag)
106 (defvaralias 'calendar-view-holidays-initially-flag
107 'view-calendar-holidays-initially))
108 (unless (boundp 'calendar-view-diary-initially-flag)
109 (defvaralias 'calendar-view-diary-initially-flag
110 'view-diary-entries-initially))
111 (unless (boundp 'diary-fancy-buffer)
112 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
114 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
115 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
116 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
117 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
118 (declare-function org-at-clock-log-p "org-clock" ())
119 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
120 (declare-function org-clock-timestamps-up "org-clock" ())
121 (declare-function org-clock-timestamps-down "org-clock" ())
122 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
124 (declare-function orgtbl-mode "org-table" (&optional arg))
125 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
126 (declare-function org-beamer-mode "org-beamer" ())
127 (declare-function org-table-edit-field "org-table" (arg))
128 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
129 (declare-function org-id-get-create "org-id" (&optional force))
130 (declare-function org-id-find-id-file "org-id" (id))
131 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
132 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
133 (declare-function org-table-align "org-table" ())
134 (declare-function org-table-paste-rectangle "org-table" ())
135 (declare-function org-table-maybe-eval-formula "org-table" ())
136 (declare-function org-table-maybe-recalculate-line "org-table" ())
138 (autoload 'org-element-at-point "org-element")
140 (declare-function org-element-at-point "org-element" (&optional keep-trail))
141 (declare-function org-element-type "org-element" (element))
142 (declare-function org-element-context "org-element" ())
143 (declare-function org-element-contents "org-element" (element))
144 (declare-function org-element-property "org-element" (property element))
145 (declare-function org-element-paragraph-parser "org-element" (limit))
146 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion))
147 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
148 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
149 (declare-function org-element--parse-objects "org-element" (beg end acc restriction))
150 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
152 ;; load languages based on value of `org-babel-load-languages'
153 (defvar org-babel-load-languages)
155 ;;;###autoload
156 (defun org-babel-do-load-languages (sym value)
157 "Load the languages defined in `org-babel-load-languages'."
158 (set-default sym value)
159 (mapc (lambda (pair)
160 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
161 (if active
162 (progn
163 (require (intern (concat "ob-" lang))))
164 (progn
165 (funcall 'fmakunbound
166 (intern (concat "org-babel-execute:" lang)))
167 (funcall 'fmakunbound
168 (intern (concat "org-babel-expand-body:" lang)))))))
169 org-babel-load-languages))
171 (defcustom org-babel-load-languages '((emacs-lisp . t))
172 "Languages which can be evaluated in Org-mode buffers.
173 This list can be used to load support for any of the languages
174 below, note that each language will depend on a different set of
175 system executables and/or Emacs modes. When a language is
176 \"loaded\", then code blocks in that language can be evaluated
177 with `org-babel-execute-src-block' bound by default to C-c
178 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
179 be set to remove code block evaluation from the C-c C-c
180 keybinding. By default only Emacs Lisp (which has no
181 requirements) is loaded."
182 :group 'org-babel
183 :set 'org-babel-do-load-languages
184 :version "24.1"
185 :type '(alist :tag "Babel Languages"
186 :key-type
187 (choice
188 (const :tag "Awk" awk)
189 (const :tag "C" C)
190 (const :tag "R" R)
191 (const :tag "Asymptote" asymptote)
192 (const :tag "Calc" calc)
193 (const :tag "Clojure" clojure)
194 (const :tag "CSS" css)
195 (const :tag "Ditaa" ditaa)
196 (const :tag "Dot" dot)
197 (const :tag "Emacs Lisp" emacs-lisp)
198 (const :tag "Fortran" fortran)
199 (const :tag "Gnuplot" gnuplot)
200 (const :tag "Haskell" haskell)
201 (const :tag "IO" io)
202 (const :tag "Java" java)
203 (const :tag "Javascript" js)
204 (const :tag "LaTeX" latex)
205 (const :tag "Ledger" ledger)
206 (const :tag "Lilypond" lilypond)
207 (const :tag "Lisp" lisp)
208 (const :tag "Maxima" maxima)
209 (const :tag "Matlab" matlab)
210 (const :tag "Mscgen" mscgen)
211 (const :tag "Ocaml" ocaml)
212 (const :tag "Octave" octave)
213 (const :tag "Org" org)
214 (const :tag "Perl" perl)
215 (const :tag "Pico Lisp" picolisp)
216 (const :tag "PlantUML" plantuml)
217 (const :tag "Python" python)
218 (const :tag "Ruby" ruby)
219 (const :tag "Sass" sass)
220 (const :tag "Scala" scala)
221 (const :tag "Scheme" scheme)
222 (const :tag "Screen" screen)
223 (const :tag "Shell Script" sh)
224 (const :tag "Shen" shen)
225 (const :tag "Sql" sql)
226 (const :tag "Sqlite" sqlite))
227 :value-type (boolean :tag "Activate" :value t)))
229 ;;;; Customization variables
230 (defcustom org-clone-delete-id nil
231 "Remove ID property of clones of a subtree.
232 When non-nil, clones of a subtree don't inherit the ID property.
233 Otherwise they inherit the ID property with a new unique
234 identifier."
235 :type 'boolean
236 :version "24.1"
237 :group 'org-id)
239 ;;; Version
240 (require 'org-compat)
241 (org-check-version)
243 ;;;###autoload
244 (defun org-version (&optional here full message)
245 "Show the org-mode version in the echo area.
246 With prefix argument HERE, insert it at point.
247 When FULL is non-nil, use a verbose version string.
248 When MESSAGE is non-nil, display a message with the version."
249 (interactive "P")
250 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
251 (save-load-suffixes load-suffixes)
252 (load-suffixes (list ".el"))
253 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
254 (org-trash (or
255 (and (fboundp 'org-release) (fboundp 'org-git-version))
256 (load (concat org-dir "org-version")
257 'noerror 'nomessage nil 'mustsuffix)))
258 (load-suffixes save-load-suffixes)
259 (org-version (org-release))
260 (git-version (org-git-version))
261 (version (format "Org-mode version %s (%s @ %s)"
262 org-version
263 git-version
264 (if org-install-dir
265 (if (string= org-dir org-install-dir)
266 org-install-dir
267 (concat "mixed installation! " org-install-dir " and " org-dir))
268 "org-loaddefs.el can not be found!")))
269 (_version (if full version org-version)))
270 (if (org-called-interactively-p 'interactive)
271 (if here
272 (insert version)
273 (message version))
274 (if message (message _version))
275 _version)))
277 (defconst org-version (org-version))
279 ;;; Compatibility constants
281 ;;; The custom variables
283 (defgroup org nil
284 "Outline-based notes management and organizer."
285 :tag "Org"
286 :group 'outlines
287 :group 'calendar)
289 (defcustom org-mode-hook nil
290 "Mode hook for Org-mode, run after the mode was turned on."
291 :group 'org
292 :type 'hook)
294 (defcustom org-load-hook nil
295 "Hook that is run after org.el has been loaded."
296 :group 'org
297 :type 'hook)
299 (defcustom org-log-buffer-setup-hook nil
300 "Hook that is run after an Org log buffer is created."
301 :group 'org
302 :version "24.1"
303 :type 'hook)
305 (defvar org-modules) ; defined below
306 (defvar org-modules-loaded nil
307 "Have the modules been loaded already?")
309 (defun org-load-modules-maybe (&optional force)
310 "Load all extensions listed in `org-modules'."
311 (when (or force (not org-modules-loaded))
312 (mapc (lambda (ext)
313 (condition-case nil (require ext)
314 (error (message "Problems while trying to load feature `%s'" ext))))
315 org-modules)
316 (setq org-modules-loaded t)))
318 (defun org-set-modules (var value)
319 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
320 (set var value)
321 (when (featurep 'org)
322 (org-load-modules-maybe 'force)))
324 (when (org-bound-and-true-p org-modules)
325 (let ((a (member 'org-infojs org-modules)))
326 (and a (setcar a 'org-jsinfo))))
328 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
329 "Modules that should always be loaded together with org.el.
330 If a description starts with <C>, the file is not part of Emacs
331 and loading it will require that you have downloaded and properly installed
332 the org-mode distribution.
334 You can also use this system to load external packages (i.e. neither Org
335 core modules, nor modules from the CONTRIB directory). Just add symbols
336 to the end of the list. If the package is called org-xyz.el, then you need
337 to add the symbol `xyz', and the package must have a call to
339 (provide 'org-xyz)"
340 :group 'org
341 :set 'org-set-modules
342 :type
343 '(set :greedy t
344 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
345 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
346 (const :tag " crypt: Encryption of subtrees" org-crypt)
347 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
348 (const :tag " docview: Links to doc-view buffers" org-docview)
349 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
350 (const :tag " id: Global IDs for identifying entries" org-id)
351 (const :tag " info: Links to Info nodes" org-info)
352 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
353 (const :tag " habit: Track your consistency with habits" org-habit)
354 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
355 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
356 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
357 (const :tag " mew Links to Mew folders/messages" org-mew)
358 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
359 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
360 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
361 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
362 (const :tag " vm: Links to VM folders/messages" org-vm)
363 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
364 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
365 (const :tag " mouse: Additional mouse support" org-mouse)
366 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
368 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
369 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
370 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
371 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
372 (const :tag "C collector: Collect properties into tables" org-collector)
373 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
374 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
375 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
376 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
377 (const :tag "C eval: Include command output as text" org-eval)
378 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
379 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
380 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
381 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
382 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
384 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
386 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
387 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
388 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
389 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
390 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
391 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
392 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
393 (const :tag "C mtags: Support for muse-like tags" org-mtags)
394 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
395 (const :tag "C registry: A registry for Org-mode links" org-registry)
396 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
397 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
398 (const :tag "C secretary: Team management with org-mode" org-secretary)
399 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
400 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
401 (const :tag "C track: Keep up with Org-mode development" org-track)
402 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
403 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
404 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
406 (defcustom org-support-shift-select nil
407 "Non-nil means make shift-cursor commands select text when possible.
409 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
410 start selecting a region, or enlarge regions started in this way.
411 In Org-mode, in special contexts, these same keys are used for
412 other purposes, important enough to compete with shift selection.
413 Org tries to balance these needs by supporting `shift-select-mode'
414 outside these special contexts, under control of this variable.
416 The default of this variable is nil, to avoid confusing behavior. Shifted
417 cursor keys will then execute Org commands in the following contexts:
418 - on a headline, changing TODO state (left/right) and priority (up/down)
419 - on a time stamp, changing the time
420 - in a plain list item, changing the bullet type
421 - in a property definition line, switching between allowed values
422 - in the BEGIN line of a clock table (changing the time block).
423 Outside these contexts, the commands will throw an error.
425 When this variable is t and the cursor is not in a special
426 context, Org-mode will support shift-selection for making and
427 enlarging regions. To make this more effective, the bullet
428 cycling will no longer happen anywhere in an item line, but only
429 if the cursor is exactly on the bullet.
431 If you set this variable to the symbol `always', then the keys
432 will not be special in headlines, property lines, and item lines,
433 to make shift selection work there as well. If this is what you
434 want, you can use the following alternative commands: `C-c C-t'
435 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
436 can be used to switch TODO sets, `C-c -' to cycle item bullet
437 types, and properties can be edited by hand or in column view.
439 However, when the cursor is on a timestamp, shift-cursor commands
440 will still edit the time stamp - this is just too good to give up.
442 XEmacs user should have this variable set to nil, because
443 `shift-select-mode' is in Emacs 23 or later only."
444 :group 'org
445 :type '(choice
446 (const :tag "Never" nil)
447 (const :tag "When outside special context" t)
448 (const :tag "Everywhere except timestamps" always)))
450 (defcustom org-loop-over-headlines-in-active-region nil
451 "Shall some commands act upon headlines in the active region?
453 When set to `t', some commands will be performed in all headlines
454 within the active region.
456 When set to `start-level', some commands will be performed in all
457 headlines within the active region, provided that these headlines
458 are of the same level than the first one.
460 When set to a string, those commands will be performed on the
461 matching headlines within the active region. Such string must be
462 a tags/property/todo match as it is used in the agenda tags view.
464 The list of commands is: `org-schedule', `org-deadline',
465 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
466 `org-archive-to-archive-sibling'. The archiving commands skip
467 already archived entries."
468 :type '(choice (const :tag "Don't loop" nil)
469 (const :tag "All headlines in active region" t)
470 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
471 (string :tag "Tags/Property/Todo matcher"))
472 :version "24.1"
473 :group 'org-todo
474 :group 'org-archive)
476 (defgroup org-startup nil
477 "Options concerning startup of Org-mode."
478 :tag "Org Startup"
479 :group 'org)
481 (defcustom org-startup-folded t
482 "Non-nil means entering Org-mode will switch to OVERVIEW.
483 This can also be configured on a per-file basis by adding one of
484 the following lines anywhere in the buffer:
486 #+STARTUP: fold (or `overview', this is equivalent)
487 #+STARTUP: nofold (or `showall', this is equivalent)
488 #+STARTUP: content
489 #+STARTUP: showeverything"
490 :group 'org-startup
491 :type '(choice
492 (const :tag "nofold: show all" nil)
493 (const :tag "fold: overview" t)
494 (const :tag "content: all headlines" content)
495 (const :tag "show everything, even drawers" showeverything)))
497 (defcustom org-startup-truncated t
498 "Non-nil means entering Org-mode will set `truncate-lines'.
499 This is useful since some lines containing links can be very long and
500 uninteresting. Also tables look terrible when wrapped."
501 :group 'org-startup
502 :type 'boolean)
504 (defcustom org-startup-indented nil
505 "Non-nil means turn on `org-indent-mode' on startup.
506 This can also be configured on a per-file basis by adding one of
507 the following lines anywhere in the buffer:
509 #+STARTUP: indent
510 #+STARTUP: noindent"
511 :group 'org-structure
512 :type '(choice
513 (const :tag "Not" nil)
514 (const :tag "Globally (slow on startup in large files)" t)))
516 (defcustom org-use-sub-superscripts t
517 "Non-nil means interpret \"_\" and \"^\" for export.
518 When this option is turned on, you can use TeX-like syntax for sub- and
519 superscripts. Several characters after \"_\" or \"^\" will be
520 considered as a single item - so grouping with {} is normally not
521 needed. For example, the following things will be parsed as single
522 sub- or superscripts.
524 10^24 or 10^tau several digits will be considered 1 item.
525 10^-12 or 10^-tau a leading sign with digits or a word
526 x^2-y^3 will be read as x^2 - y^3, because items are
527 terminated by almost any nonword/nondigit char.
528 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
530 Still, ambiguity is possible - so when in doubt use {} to enclose the
531 sub/superscript. If you set this variable to the symbol `{}',
532 the braces are *required* in order to trigger interpretations as
533 sub/superscript. This can be helpful in documents that need \"_\"
534 frequently in plain text.
536 Not all export backends support this, but HTML does.
538 This option can also be set with the #+OPTIONS line, e.g. \"^:nil\"."
539 :group 'org-startup
540 :group 'org-export-translation
541 :version "24.1"
542 :type '(choice
543 (const :tag "Always interpret" t)
544 (const :tag "Only with braces" {})
545 (const :tag "Never interpret" nil)))
547 (if (fboundp 'defvaralias)
548 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
551 (defcustom org-startup-with-beamer-mode nil
552 "Non-nil means turn on `org-beamer-mode' on startup.
553 This can also be configured on a per-file basis by adding one of
554 the following lines anywhere in the buffer:
556 #+STARTUP: beamer"
557 :group 'org-startup
558 :version "24.1"
559 :type 'boolean)
561 (defcustom org-startup-align-all-tables nil
562 "Non-nil means align all tables when visiting a file.
563 This is useful when the column width in tables is forced with <N> cookies
564 in table fields. Such tables will look correct only after the first re-align.
565 This can also be configured on a per-file basis by adding one of
566 the following lines anywhere in the buffer:
567 #+STARTUP: align
568 #+STARTUP: noalign"
569 :group 'org-startup
570 :type 'boolean)
572 (defcustom org-startup-with-inline-images nil
573 "Non-nil means show inline images when loading a new Org file.
574 This can also be configured on a per-file basis by adding one of
575 the following lines anywhere in the buffer:
576 #+STARTUP: inlineimages
577 #+STARTUP: noinlineimages"
578 :group 'org-startup
579 :version "24.1"
580 :type 'boolean)
582 (defcustom org-insert-mode-line-in-empty-file nil
583 "Non-nil means insert the first line setting Org-mode in empty files.
584 When the function `org-mode' is called interactively in an empty file, this
585 normally means that the file name does not automatically trigger Org-mode.
586 To ensure that the file will always be in Org-mode in the future, a
587 line enforcing Org-mode will be inserted into the buffer, if this option
588 has been set."
589 :group 'org-startup
590 :type 'boolean)
592 (defcustom org-replace-disputed-keys nil
593 "Non-nil means use alternative key bindings for some keys.
594 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
595 These keys are also used by other packages like shift-selection-mode'
596 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
597 If you want to use Org-mode together with one of these other modes,
598 or more generally if you would like to move some Org-mode commands to
599 other keys, set this variable and configure the keys with the variable
600 `org-disputed-keys'.
602 This option is only relevant at load-time of Org-mode, and must be set
603 *before* org.el is loaded. Changing it requires a restart of Emacs to
604 become effective."
605 :group 'org-startup
606 :type 'boolean)
608 (defcustom org-use-extra-keys nil
609 "Non-nil means use extra key sequence definitions for certain commands.
610 This happens automatically if you run XEmacs or if `window-system'
611 is nil. This variable lets you do the same manually. You must
612 set it before loading org.
614 Example: on Carbon Emacs 22 running graphically, with an external
615 keyboard on a Powerbook, the default way of setting M-left might
616 not work for either Alt or ESC. Setting this variable will make
617 it work for ESC."
618 :group 'org-startup
619 :type 'boolean)
621 (if (fboundp 'defvaralias)
622 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
624 (defcustom org-disputed-keys
625 '(([(shift up)] . [(meta p)])
626 ([(shift down)] . [(meta n)])
627 ([(shift left)] . [(meta -)])
628 ([(shift right)] . [(meta +)])
629 ([(control shift right)] . [(meta shift +)])
630 ([(control shift left)] . [(meta shift -)]))
631 "Keys for which Org-mode and other modes compete.
632 This is an alist, cars are the default keys, second element specifies
633 the alternative to use when `org-replace-disputed-keys' is t.
635 Keys can be specified in any syntax supported by `define-key'.
636 The value of this option takes effect only at Org-mode's startup,
637 therefore you'll have to restart Emacs to apply it after changing."
638 :group 'org-startup
639 :type 'alist)
641 (defun org-key (key)
642 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
643 Or return the original if not disputed.
644 Also apply the translations defined in `org-xemacs-key-equivalents'."
645 (when org-replace-disputed-keys
646 (let* ((nkey (key-description key))
647 (x (org-find-if (lambda (x)
648 (equal (key-description (car x)) nkey))
649 org-disputed-keys)))
650 (setq key (if x (cdr x) key))))
651 (when (featurep 'xemacs)
652 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
653 key)
655 (defun org-find-if (predicate seq)
656 (catch 'exit
657 (while seq
658 (if (funcall predicate (car seq))
659 (throw 'exit (car seq))
660 (pop seq)))))
662 (defun org-defkey (keymap key def)
663 "Define a key, possibly translated, as returned by `org-key'."
664 (define-key keymap (org-key key) def))
666 (defcustom org-ellipsis nil
667 "The ellipsis to use in the Org-mode outline.
668 When nil, just use the standard three dots. When a string, use that instead,
669 When a face, use the standard 3 dots, but with the specified face.
670 The change affects only Org-mode (which will then use its own display table).
671 Changing this requires executing `M-x org-mode' in a buffer to become
672 effective."
673 :group 'org-startup
674 :type '(choice (const :tag "Default" nil)
675 (face :tag "Face" :value org-warning)
676 (string :tag "String" :value "...#")))
678 (defvar org-display-table nil
679 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
681 (defgroup org-keywords nil
682 "Keywords in Org-mode."
683 :tag "Org Keywords"
684 :group 'org)
686 (defcustom org-deadline-string "DEADLINE:"
687 "String to mark deadline entries.
688 A deadline is this string, followed by a time stamp. Should be a word,
689 terminated by a colon. You can insert a schedule keyword and
690 a timestamp with \\[org-deadline].
691 Changes become only effective after restarting Emacs."
692 :group 'org-keywords
693 :type 'string)
695 (defcustom org-scheduled-string "SCHEDULED:"
696 "String to mark scheduled TODO entries.
697 A schedule is this string, followed by a time stamp. Should be a word,
698 terminated by a colon. You can insert a schedule keyword and
699 a timestamp with \\[org-schedule].
700 Changes become only effective after restarting Emacs."
701 :group 'org-keywords
702 :type 'string)
704 (defcustom org-closed-string "CLOSED:"
705 "String used as the prefix for timestamps logging closing a TODO entry."
706 :group 'org-keywords
707 :type 'string)
709 (defcustom org-clock-string "CLOCK:"
710 "String used as prefix for timestamps clocking work hours on an item."
711 :group 'org-keywords
712 :type 'string)
714 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
715 org-scheduled-string "\\|"
716 org-deadline-string "\\|"
717 org-closed-string "\\|"
718 org-clock-string "\\)")
719 "Matches a line with planning or clock info.")
721 (defcustom org-comment-string "COMMENT"
722 "Entries starting with this keyword will never be exported.
723 An entry can be toggled between COMMENT and normal with
724 \\[org-toggle-comment].
725 Changes become only effective after restarting Emacs."
726 :group 'org-keywords
727 :type 'string)
729 (defcustom org-quote-string "QUOTE"
730 "Entries starting with this keyword will be exported in fixed-width font.
731 Quoting applies only to the text in the entry following the headline, and does
732 not extend beyond the next headline, even if that is lower level.
733 An entry can be toggled between QUOTE and normal with
734 \\[org-toggle-fixed-width-section]."
735 :group 'org-keywords
736 :type 'string)
738 (defconst org-repeat-re
739 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
740 "Regular expression for specifying repeated events.
741 After a match, group 1 contains the repeat expression.")
743 (defgroup org-structure nil
744 "Options concerning the general structure of Org-mode files."
745 :tag "Org Structure"
746 :group 'org)
748 (defgroup org-reveal-location nil
749 "Options about how to make context of a location visible."
750 :tag "Org Reveal Location"
751 :group 'org-structure)
753 (defconst org-context-choice
754 '(choice
755 (const :tag "Always" t)
756 (const :tag "Never" nil)
757 (repeat :greedy t :tag "Individual contexts"
758 (cons
759 (choice :tag "Context"
760 (const agenda)
761 (const org-goto)
762 (const occur-tree)
763 (const tags-tree)
764 (const link-search)
765 (const mark-goto)
766 (const bookmark-jump)
767 (const isearch)
768 (const default))
769 (boolean))))
770 "Contexts for the reveal options.")
772 (defcustom org-show-hierarchy-above '((default . t))
773 "Non-nil means show full hierarchy when revealing a location.
774 Org-mode often shows locations in an org-mode file which might have
775 been invisible before. When this is set, the hierarchy of headings
776 above the exposed location is shown.
777 Turning this off for example for sparse trees makes them very compact.
778 Instead of t, this can also be an alist specifying this option for different
779 contexts. Valid contexts are
780 agenda when exposing an entry from the agenda
781 org-goto when using the command `org-goto' on key C-c C-j
782 occur-tree when using the command `org-occur' on key C-c /
783 tags-tree when constructing a sparse tree based on tags matches
784 link-search when exposing search matches associated with a link
785 mark-goto when exposing the jump goal of a mark
786 bookmark-jump when exposing a bookmark location
787 isearch when exiting from an incremental search
788 default default for all contexts not set explicitly"
789 :group 'org-reveal-location
790 :type org-context-choice)
792 (defcustom org-show-following-heading '((default . nil))
793 "Non-nil means show following heading when revealing a location.
794 Org-mode often shows locations in an org-mode file which might have
795 been invisible before. When this is set, the heading following the
796 match is shown.
797 Turning this off for example for sparse trees makes them very compact,
798 but makes it harder to edit the location of the match. In such a case,
799 use the command \\[org-reveal] to show more context.
800 Instead of t, this can also be an alist specifying this option for different
801 contexts. See `org-show-hierarchy-above' for valid contexts."
802 :group 'org-reveal-location
803 :type org-context-choice)
805 (defcustom org-show-siblings '((default . nil) (isearch t))
806 "Non-nil means show all sibling heading when revealing a location.
807 Org-mode often shows locations in an org-mode file which might have
808 been invisible before. When this is set, the sibling of the current entry
809 heading are all made visible. If `org-show-hierarchy-above' is t,
810 the same happens on each level of the hierarchy above the current entry.
812 By default this is on for the isearch context, off for all other contexts.
813 Turning this off for example for sparse trees makes them very compact,
814 but makes it harder to edit the location of the match. In such a case,
815 use the command \\[org-reveal] to show more context.
816 Instead of t, this can also be an alist specifying this option for different
817 contexts. See `org-show-hierarchy-above' for valid contexts."
818 :group 'org-reveal-location
819 :type org-context-choice)
821 (defcustom org-show-entry-below '((default . nil))
822 "Non-nil means show the entry below a headline when revealing a location.
823 Org-mode often shows locations in an org-mode file which might have
824 been invisible before. When this is set, the text below the headline that is
825 exposed is also shown.
827 By default this is off for all contexts.
828 Instead of t, this can also be an alist specifying this option for different
829 contexts. See `org-show-hierarchy-above' for valid contexts."
830 :group 'org-reveal-location
831 :type org-context-choice)
833 (defcustom org-indirect-buffer-display 'other-window
834 "How should indirect tree buffers be displayed?
835 This applies to indirect buffers created with the commands
836 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
837 Valid values are:
838 current-window Display in the current window
839 other-window Just display in another window.
840 dedicated-frame Create one new frame, and re-use it each time.
841 new-frame Make a new frame each time. Note that in this case
842 previously-made indirect buffers are kept, and you need to
843 kill these buffers yourself."
844 :group 'org-structure
845 :group 'org-agenda-windows
846 :type '(choice
847 (const :tag "In current window" current-window)
848 (const :tag "In current frame, other window" other-window)
849 (const :tag "Each time a new frame" new-frame)
850 (const :tag "One dedicated frame" dedicated-frame)))
852 (defcustom org-use-speed-commands nil
853 "Non-nil means activate single letter commands at beginning of a headline.
854 This may also be a function to test for appropriate locations where speed
855 commands should be active."
856 :group 'org-structure
857 :type '(choice
858 (const :tag "Never" nil)
859 (const :tag "At beginning of headline stars" t)
860 (function)))
862 (defcustom org-speed-commands-user nil
863 "Alist of additional speed commands.
864 This list will be checked before `org-speed-commands-default'
865 when the variable `org-use-speed-commands' is non-nil
866 and when the cursor is at the beginning of a headline.
867 The car if each entry is a string with a single letter, which must
868 be assigned to `self-insert-command' in the global map.
869 The cdr is either a command to be called interactively, a function
870 to be called, or a form to be evaluated.
871 An entry that is just a list with a single string will be interpreted
872 as a descriptive headline that will be added when listing the speed
873 commands in the Help buffer using the `?' speed command."
874 :group 'org-structure
875 :type '(repeat :value ("k" . ignore)
876 (choice :value ("k" . ignore)
877 (list :tag "Descriptive Headline" (string :tag "Headline"))
878 (cons :tag "Letter and Command"
879 (string :tag "Command letter")
880 (choice
881 (function)
882 (sexp))))))
884 (defgroup org-cycle nil
885 "Options concerning visibility cycling in Org-mode."
886 :tag "Org Cycle"
887 :group 'org-structure)
889 (defcustom org-cycle-skip-children-state-if-no-children t
890 "Non-nil means skip CHILDREN state in entries that don't have any."
891 :group 'org-cycle
892 :type 'boolean)
894 (defcustom org-cycle-max-level nil
895 "Maximum level which should still be subject to visibility cycling.
896 Levels higher than this will, for cycling, be treated as text, not a headline.
897 When `org-odd-levels-only' is set, a value of N in this variable actually
898 means 2N-1 stars as the limiting headline.
899 When nil, cycle all levels.
900 Note that the limiting level of cycling is also influenced by
901 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
902 `org-inlinetask-min-level' is, cycling will be limited to levels one less
903 than its value."
904 :group 'org-cycle
905 :type '(choice
906 (const :tag "No limit" nil)
907 (integer :tag "Maximum level")))
909 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
910 "Names of drawers. Drawers are not opened by cycling on the headline above.
911 Drawers only open with a TAB on the drawer line itself. A drawer looks like
912 this:
913 :DRAWERNAME:
914 .....
915 :END:
916 The drawer \"PROPERTIES\" is special for capturing properties through
917 the property API.
919 Drawers can be defined on the per-file basis with a line like:
921 #+DRAWERS: HIDDEN STATE PROPERTIES"
922 :group 'org-structure
923 :group 'org-cycle
924 :type '(repeat (string :tag "Drawer Name")))
926 (defcustom org-hide-block-startup nil
927 "Non-nil means entering Org-mode will fold all blocks.
928 This can also be set in on a per-file basis with
930 #+STARTUP: hideblocks
931 #+STARTUP: showblocks"
932 :group 'org-startup
933 :group 'org-cycle
934 :type 'boolean)
936 (defcustom org-cycle-global-at-bob nil
937 "Cycle globally if cursor is at beginning of buffer and not at a headline.
938 This makes it possible to do global cycling without having to use S-TAB or
939 \\[universal-argument] TAB. For this special case to work, the first line
940 of the buffer must not be a headline -- it may be empty or some other text.
941 When used in this way, `org-cycle-hook' is disabled temporarily to make
942 sure the cursor stays at the beginning of the buffer. When this option is
943 nil, don't do anything special at the beginning of the buffer."
944 :group 'org-cycle
945 :type 'boolean)
947 (defcustom org-cycle-level-after-item/entry-creation t
948 "Non-nil means cycle entry level or item indentation in new empty entries.
950 When the cursor is at the end of an empty headline, i.e with only stars
951 and maybe a TODO keyword, TAB will then switch the entry to become a child,
952 and then all possible ancestor states, before returning to the original state.
953 This makes data entry extremely fast: M-RET to create a new headline,
954 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
956 When the cursor is at the end of an empty plain list item, one TAB will
957 make it a subitem, two or more tabs will back up to make this an item
958 higher up in the item hierarchy."
959 :group 'org-cycle
960 :type 'boolean)
962 (defcustom org-cycle-emulate-tab t
963 "Where should `org-cycle' emulate TAB.
964 nil Never
965 white Only in completely white lines
966 whitestart Only at the beginning of lines, before the first non-white char
967 t Everywhere except in headlines
968 exc-hl-bol Everywhere except at the start of a headline
969 If TAB is used in a place where it does not emulate TAB, the current subtree
970 visibility is cycled."
971 :group 'org-cycle
972 :type '(choice (const :tag "Never" nil)
973 (const :tag "Only in completely white lines" white)
974 (const :tag "Before first char in a line" whitestart)
975 (const :tag "Everywhere except in headlines" t)
976 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
979 (defcustom org-cycle-separator-lines 2
980 "Number of empty lines needed to keep an empty line between collapsed trees.
981 If you leave an empty line between the end of a subtree and the following
982 headline, this empty line is hidden when the subtree is folded.
983 Org-mode will leave (exactly) one empty line visible if the number of
984 empty lines is equal or larger to the number given in this variable.
985 So the default 2 means at least 2 empty lines after the end of a subtree
986 are needed to produce free space between a collapsed subtree and the
987 following headline.
989 If the number is negative, and the number of empty lines is at least -N,
990 all empty lines are shown.
992 Special case: when 0, never leave empty lines in collapsed view."
993 :group 'org-cycle
994 :type 'integer)
995 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
997 (defcustom org-pre-cycle-hook nil
998 "Hook that is run before visibility cycling is happening.
999 The function(s) in this hook must accept a single argument which indicates
1000 the new state that will be set right after running this hook. The
1001 argument is a symbol. Before a global state change, it can have the values
1002 `overview', `content', or `all'. Before a local state change, it can have
1003 the values `folded', `children', or `subtree'."
1004 :group 'org-cycle
1005 :type 'hook)
1007 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1008 org-cycle-hide-drawers
1009 org-cycle-hide-inline-tasks
1010 org-cycle-show-empty-lines
1011 org-optimize-window-after-visibility-change)
1012 "Hook that is run after `org-cycle' has changed the buffer visibility.
1013 The function(s) in this hook must accept a single argument which indicates
1014 the new state that was set by the most recent `org-cycle' command. The
1015 argument is a symbol. After a global state change, it can have the values
1016 `overview', `contents', or `all'. After a local state change, it can have
1017 the values `folded', `children', or `subtree'."
1018 :group 'org-cycle
1019 :type 'hook)
1021 (defgroup org-edit-structure nil
1022 "Options concerning structure editing in Org-mode."
1023 :tag "Org Edit Structure"
1024 :group 'org-structure)
1026 (defcustom org-odd-levels-only nil
1027 "Non-nil means skip even levels and only use odd levels for the outline.
1028 This has the effect that two stars are being added/taken away in
1029 promotion/demotion commands. It also influences how levels are
1030 handled by the exporters.
1031 Changing it requires restart of `font-lock-mode' to become effective
1032 for fontification also in regions already fontified.
1033 You may also set this on a per-file basis by adding one of the following
1034 lines to the buffer:
1036 #+STARTUP: odd
1037 #+STARTUP: oddeven"
1038 :group 'org-edit-structure
1039 :group 'org-appearance
1040 :type 'boolean)
1042 (defcustom org-adapt-indentation t
1043 "Non-nil means adapt indentation to outline node level.
1045 When this variable is set, Org assumes that you write outlines by
1046 indenting text in each node to align with the headline (after the stars).
1047 The following issues are influenced by this variable:
1049 - When this is set and the *entire* text in an entry is indented, the
1050 indentation is increased by one space in a demotion command, and
1051 decreased by one in a promotion command. If any line in the entry
1052 body starts with text at column 0, indentation is not changed at all.
1054 - Property drawers and planning information is inserted indented when
1055 this variable s set. When nil, they will not be indented.
1057 - TAB indents a line relative to context. The lines below a headline
1058 will be indented when this variable is set.
1060 Note that this is all about true indentation, by adding and removing
1061 space characters. See also `org-indent.el' which does level-dependent
1062 indentation in a virtual way, i.e. at display time in Emacs."
1063 :group 'org-edit-structure
1064 :type 'boolean)
1066 (defcustom org-special-ctrl-a/e nil
1067 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1069 When t, `C-a' will bring back the cursor to the beginning of the
1070 headline text, i.e. after the stars and after a possible TODO
1071 keyword. In an item, this will be the position after bullet and
1072 check-box, if any. When the cursor is already at that position,
1073 another `C-a' will bring it to the beginning of the line.
1075 `C-e' will jump to the end of the headline, ignoring the presence
1076 of tags in the headline. A second `C-e' will then jump to the
1077 true end of the line, after any tags. This also means that, when
1078 this variable is non-nil, `C-e' also will never jump beyond the
1079 end of the heading of a folded section, i.e. not after the
1080 ellipses.
1082 When set to the symbol `reversed', the first `C-a' or `C-e' works
1083 normally, going to the true line boundary first. Only a directly
1084 following, identical keypress will bring the cursor to the
1085 special positions.
1087 This may also be a cons cell where the behavior for `C-a' and
1088 `C-e' is set separately."
1089 :group 'org-edit-structure
1090 :type '(choice
1091 (const :tag "off" nil)
1092 (const :tag "on: after stars/bullet and before tags first" t)
1093 (const :tag "reversed: true line boundary first" reversed)
1094 (cons :tag "Set C-a and C-e separately"
1095 (choice :tag "Special C-a"
1096 (const :tag "off" nil)
1097 (const :tag "on: after stars/bullet first" t)
1098 (const :tag "reversed: before stars/bullet first" reversed))
1099 (choice :tag "Special C-e"
1100 (const :tag "off" nil)
1101 (const :tag "on: before tags first" t)
1102 (const :tag "reversed: after tags first" reversed)))))
1103 (if (fboundp 'defvaralias)
1104 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1106 (defcustom org-special-ctrl-k nil
1107 "Non-nil means `C-k' will behave specially in headlines.
1108 When nil, `C-k' will call the default `kill-line' command.
1109 When t, the following will happen while the cursor is in the headline:
1111 - When the cursor is at the beginning of a headline, kill the entire
1112 line and possible the folded subtree below the line.
1113 - When in the middle of the headline text, kill the headline up to the tags.
1114 - When after the headline text, kill the tags."
1115 :group 'org-edit-structure
1116 :type 'boolean)
1118 (defcustom org-ctrl-k-protect-subtree nil
1119 "Non-nil means, do not delete a hidden subtree with C-k.
1120 When set to the symbol `error', simply throw an error when C-k is
1121 used to kill (part-of) a headline that has hidden text behind it.
1122 Any other non-nil value will result in a query to the user, if it is
1123 OK to kill that hidden subtree. When nil, kill without remorse."
1124 :group 'org-edit-structure
1125 :version "24.1"
1126 :type '(choice
1127 (const :tag "Do not protect hidden subtrees" nil)
1128 (const :tag "Protect hidden subtrees with a security query" t)
1129 (const :tag "Never kill a hidden subtree with C-k" error)))
1131 (defcustom org-catch-invisible-edits nil
1132 "Check if in invisible region before inserting or deleting a character.
1133 Valid values are:
1135 nil Do not check, so just do invisible edits.
1136 error Throw an error and do nothing.
1137 show Make point visible, and do the requested edit.
1138 show-and-error Make point visible, then throw an error and abort the edit.
1139 smart Make point visible, and do insertion/deletion if it is
1140 adjacent to visible text and the change feels predictable.
1141 Never delete a previously invisible character or add in the
1142 middle or right after an invisible region. Basically, this
1143 allows insertion and backward-delete right before ellipses.
1144 FIXME: maybe in this case we should not even show?"
1145 :group 'org-edit-structure
1146 :version "24.1"
1147 :type '(choice
1148 (const :tag "Do not check" nil)
1149 (const :tag "Throw error when trying to edit" error)
1150 (const :tag "Unhide, but do not do the edit" show-and-error)
1151 (const :tag "Show invisible part and do the edit" show)
1152 (const :tag "Be smart and do the right thing" smart)))
1154 (defcustom org-yank-folded-subtrees t
1155 "Non-nil means when yanking subtrees, fold them.
1156 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1157 it starts with a heading and all other headings in it are either children
1158 or siblings, then fold all the subtrees. However, do this only if no
1159 text after the yank would be swallowed into a folded tree by this action."
1160 :group 'org-edit-structure
1161 :type 'boolean)
1163 (defcustom org-yank-adjusted-subtrees nil
1164 "Non-nil means when yanking subtrees, adjust the level.
1165 With this setting, `org-paste-subtree' is used to insert the subtree, see
1166 this function for details."
1167 :group 'org-edit-structure
1168 :type 'boolean)
1170 (defcustom org-M-RET-may-split-line '((default . t))
1171 "Non-nil means M-RET will split the line at the cursor position.
1172 When nil, it will go to the end of the line before making a
1173 new line.
1174 You may also set this option in a different way for different
1175 contexts. Valid contexts are:
1177 headline when creating a new headline
1178 item when creating a new item
1179 table in a table field
1180 default the value to be used for all contexts not explicitly
1181 customized"
1182 :group 'org-structure
1183 :group 'org-table
1184 :type '(choice
1185 (const :tag "Always" t)
1186 (const :tag "Never" nil)
1187 (repeat :greedy t :tag "Individual contexts"
1188 (cons
1189 (choice :tag "Context"
1190 (const headline)
1191 (const item)
1192 (const table)
1193 (const default))
1194 (boolean)))))
1197 (defcustom org-insert-heading-respect-content nil
1198 "Non-nil means insert new headings after the current subtree.
1199 When nil, the new heading is created directly after the current line.
1200 The commands \\[org-insert-heading-respect-content] and
1201 \\[org-insert-todo-heading-respect-content] turn this variable on
1202 for the duration of the command."
1203 :group 'org-structure
1204 :type 'boolean)
1206 (defcustom org-blank-before-new-entry '((heading . auto)
1207 (plain-list-item . auto))
1208 "Should `org-insert-heading' leave a blank line before new heading/item?
1209 The value is an alist, with `heading' and `plain-list-item' as CAR,
1210 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1211 which case Org will look at the surrounding headings/items and try to
1212 make an intelligent decision whether to insert a blank line or not.
1214 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1215 set, the setting here is ignored and no empty line is inserted, to avoid
1216 breaking the list structure."
1217 :group 'org-edit-structure
1218 :type '(list
1219 (cons (const heading)
1220 (choice (const :tag "Never" nil)
1221 (const :tag "Always" t)
1222 (const :tag "Auto" auto)))
1223 (cons (const plain-list-item)
1224 (choice (const :tag "Never" nil)
1225 (const :tag "Always" t)
1226 (const :tag "Auto" auto)))))
1228 (defcustom org-insert-heading-hook nil
1229 "Hook being run after inserting a new heading."
1230 :group 'org-edit-structure
1231 :type 'hook)
1233 (defcustom org-enable-fixed-width-editor t
1234 "Non-nil means lines starting with \":\" are treated as fixed-width.
1235 This currently only means they are never auto-wrapped.
1236 When nil, such lines will be treated like ordinary lines.
1237 See also the QUOTE keyword."
1238 :group 'org-edit-structure
1239 :type 'boolean)
1241 (defcustom org-goto-auto-isearch t
1242 "Non-nil means typing characters in `org-goto' starts incremental search."
1243 :group 'org-edit-structure
1244 :type 'boolean)
1246 (defgroup org-sparse-trees nil
1247 "Options concerning sparse trees in Org-mode."
1248 :tag "Org Sparse Trees"
1249 :group 'org-structure)
1251 (defcustom org-highlight-sparse-tree-matches t
1252 "Non-nil means highlight all matches that define a sparse tree.
1253 The highlights will automatically disappear the next time the buffer is
1254 changed by an edit command."
1255 :group 'org-sparse-trees
1256 :type 'boolean)
1258 (defcustom org-remove-highlights-with-change t
1259 "Non-nil means any change to the buffer will remove temporary highlights.
1260 Such highlights are created by `org-occur' and `org-clock-display'.
1261 When nil, `C-c C-c needs to be used to get rid of the highlights.
1262 The highlights created by `org-preview-latex-fragment' always need
1263 `C-c C-c' to be removed."
1264 :group 'org-sparse-trees
1265 :group 'org-time
1266 :type 'boolean)
1269 (defcustom org-occur-hook '(org-first-headline-recenter)
1270 "Hook that is run after `org-occur' has constructed a sparse tree.
1271 This can be used to recenter the window to show as much of the structure
1272 as possible."
1273 :group 'org-sparse-trees
1274 :type 'hook)
1276 (defgroup org-imenu-and-speedbar nil
1277 "Options concerning imenu and speedbar in Org-mode."
1278 :tag "Org Imenu and Speedbar"
1279 :group 'org-structure)
1281 (defcustom org-imenu-depth 2
1282 "The maximum level for Imenu access to Org-mode headlines.
1283 This also applied for speedbar access."
1284 :group 'org-imenu-and-speedbar
1285 :type 'integer)
1287 (defgroup org-table nil
1288 "Options concerning tables in Org-mode."
1289 :tag "Org Table"
1290 :group 'org)
1292 (defcustom org-enable-table-editor 'optimized
1293 "Non-nil means lines starting with \"|\" are handled by the table editor.
1294 When nil, such lines will be treated like ordinary lines.
1296 When equal to the symbol `optimized', the table editor will be optimized to
1297 do the following:
1298 - Automatic overwrite mode in front of whitespace in table fields.
1299 This makes the structure of the table stay in tact as long as the edited
1300 field does not exceed the column width.
1301 - Minimize the number of realigns. Normally, the table is aligned each time
1302 TAB or RET are pressed to move to another field. With optimization this
1303 happens only if changes to a field might have changed the column width.
1304 Optimization requires replacing the functions `self-insert-command',
1305 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1306 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1307 very good at guessing when a re-align will be necessary, but you can always
1308 force one with \\[org-ctrl-c-ctrl-c].
1310 If you would like to use the optimized version in Org-mode, but the
1311 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1313 This variable can be used to turn on and off the table editor during a session,
1314 but in order to toggle optimization, a restart is required.
1316 See also the variable `org-table-auto-blank-field'."
1317 :group 'org-table
1318 :type '(choice
1319 (const :tag "off" nil)
1320 (const :tag "on" t)
1321 (const :tag "on, optimized" optimized)))
1323 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1324 (version<= emacs-version "24.1"))
1325 "Non-nil means cluster self-insert commands for undo when possible.
1326 If this is set, then, like in the Emacs command loop, 20 consecutive
1327 characters will be undone together.
1328 This is configurable, because there is some impact on typing performance."
1329 :group 'org-table
1330 :type 'boolean)
1332 (defcustom org-table-tab-recognizes-table.el t
1333 "Non-nil means TAB will automatically notice a table.el table.
1334 When it sees such a table, it moves point into it and - if necessary -
1335 calls `table-recognize-table'."
1336 :group 'org-table-editing
1337 :type 'boolean)
1339 (defgroup org-link nil
1340 "Options concerning links in Org-mode."
1341 :tag "Org Link"
1342 :group 'org)
1344 (defvar org-link-abbrev-alist-local nil
1345 "Buffer-local version of `org-link-abbrev-alist', which see.
1346 The value of this is taken from the #+LINK lines.")
1347 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1349 (defcustom org-link-abbrev-alist nil
1350 "Alist of link abbreviations.
1351 The car of each element is a string, to be replaced at the start of a link.
1352 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1353 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1355 [[linkkey:tag][description]]
1357 The 'linkkey' must be a word word, starting with a letter, followed
1358 by letters, numbers, '-' or '_'.
1360 If REPLACE is a string, the tag will simply be appended to create the link.
1361 If the string contains \"%s\", the tag will be inserted there. If the string
1362 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1363 at that point (see the function `url-hexify-string'). If the string contains
1364 the specifier \"%(my-function)\", then the custom function `my-function' will
1365 be invoked: this function takes the tag as its only argument and must return
1366 a string.
1368 REPLACE may also be a function that will be called with the tag as the
1369 only argument to create the link, which should be returned as a string.
1371 See the manual for examples."
1372 :group 'org-link
1373 :type '(repeat
1374 (cons
1375 (string :tag "Protocol")
1376 (choice
1377 (string :tag "Format")
1378 (function)))))
1380 (defcustom org-descriptive-links t
1381 "Non-nil means Org will display descriptive links.
1382 E.g. [[http://orgmode.org][Org website]] will be displayed as
1383 \"Org Website\", hiding the link itself and just displaying its
1384 description. When set to `nil', Org will display the full links
1385 literally.
1387 You can interactively set the value of this variable by calling
1388 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1389 :group 'org-link
1390 :type 'boolean)
1392 (defcustom org-link-file-path-type 'adaptive
1393 "How the path name in file links should be stored.
1394 Valid values are:
1396 relative Relative to the current directory, i.e. the directory of the file
1397 into which the link is being inserted.
1398 absolute Absolute path, if possible with ~ for home directory.
1399 noabbrev Absolute path, no abbreviation of home directory.
1400 adaptive Use relative path for files in the current directory and sub-
1401 directories of it. For other files, use an absolute path."
1402 :group 'org-link
1403 :type '(choice
1404 (const relative)
1405 (const absolute)
1406 (const noabbrev)
1407 (const adaptive)))
1409 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1410 "Types of links that should be activated in Org-mode files.
1411 This is a list of symbols, each leading to the activation of a certain link
1412 type. In principle, it does not hurt to turn on most link types - there may
1413 be a small gain when turning off unused link types. The types are:
1415 bracket The recommended [[link][description]] or [[link]] links with hiding.
1416 angle Links in angular brackets that may contain whitespace like
1417 <bbdb:Carsten Dominik>.
1418 plain Plain links in normal text, no whitespace, like http://google.com.
1419 radio Text that is matched by a radio target, see manual for details.
1420 tag Tag settings in a headline (link to tag search).
1421 date Time stamps (link to calendar).
1422 footnote Footnote labels.
1424 Changing this variable requires a restart of Emacs to become effective."
1425 :group 'org-link
1426 :type '(set :greedy t
1427 (const :tag "Double bracket links" bracket)
1428 (const :tag "Angular bracket links" angle)
1429 (const :tag "Plain text links" plain)
1430 (const :tag "Radio target matches" radio)
1431 (const :tag "Tags" tag)
1432 (const :tag "Timestamps" date)
1433 (const :tag "Footnotes" footnote)))
1435 (defcustom org-make-link-description-function nil
1436 "Function to use for generating link descriptions from links.
1437 When nil, the link location will be used. This function must take
1438 two parameters: the first one is the link, the second one is the
1439 description generated by `org-insert-link'. The function should
1440 return the description to use."
1441 :group 'org-link
1442 :type 'function)
1444 (defgroup org-link-store nil
1445 "Options concerning storing links in Org-mode."
1446 :tag "Org Store Link"
1447 :group 'org-link)
1449 (defcustom org-url-hexify-p t
1450 "When non-nil, hexify URL when creating a link."
1451 :type 'boolean
1452 :version "24.3"
1453 :group 'org-link-store)
1455 (defcustom org-email-link-description-format "Email %c: %.30s"
1456 "Format of the description part of a link to an email or usenet message.
1457 The following %-escapes will be replaced by corresponding information:
1459 %F full \"From\" field
1460 %f name, taken from \"From\" field, address if no name
1461 %T full \"To\" field
1462 %t first name in \"To\" field, address if no name
1463 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1464 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1465 %s subject
1466 %d date
1467 %m message-id.
1469 You may use normal field width specification between the % and the letter.
1470 This is for example useful to limit the length of the subject.
1472 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1473 :group 'org-link-store
1474 :type 'string)
1476 (defcustom org-from-is-user-regexp
1477 (let (r1 r2)
1478 (when (and user-mail-address (not (string= user-mail-address "")))
1479 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1480 (when (and user-full-name (not (string= user-full-name "")))
1481 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1482 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1483 "Regexp matched against the \"From:\" header of an email or usenet message.
1484 It should match if the message is from the user him/herself."
1485 :group 'org-link-store
1486 :type 'regexp)
1488 (defcustom org-context-in-file-links t
1489 "Non-nil means file links from `org-store-link' contain context.
1490 A search string will be added to the file name with :: as separator and
1491 used to find the context when the link is activated by the command
1492 `org-open-at-point'. When this option is t, the entire active region
1493 will be placed in the search string of the file link. If set to a
1494 positive integer, only the first n lines of context will be stored.
1496 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1497 negates this setting for the duration of the command."
1498 :group 'org-link-store
1499 :type '(choice boolean integer))
1501 (defcustom org-keep-stored-link-after-insertion nil
1502 "Non-nil means keep link in list for entire session.
1504 The command `org-store-link' adds a link pointing to the current
1505 location to an internal list. These links accumulate during a session.
1506 The command `org-insert-link' can be used to insert links into any
1507 Org-mode file (offering completion for all stored links). When this
1508 option is nil, every link which has been inserted once using \\[org-insert-link]
1509 will be removed from the list, to make completing the unused links
1510 more efficient."
1511 :group 'org-link-store
1512 :type 'boolean)
1514 (defgroup org-link-follow nil
1515 "Options concerning following links in Org-mode."
1516 :tag "Org Follow Link"
1517 :group 'org-link)
1519 (defcustom org-link-translation-function nil
1520 "Function to translate links with different syntax to Org syntax.
1521 This can be used to translate links created for example by the Planner
1522 or emacs-wiki packages to Org syntax.
1523 The function must accept two parameters, a TYPE containing the link
1524 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1525 which is everything after the link protocol. It should return a cons
1526 with possibly modified values of type and path.
1527 Org contains a function for this, so if you set this variable to
1528 `org-translate-link-from-planner', you should be able follow many
1529 links created by planner."
1530 :group 'org-link-follow
1531 :type 'function)
1533 (defcustom org-follow-link-hook nil
1534 "Hook that is run after a link has been followed."
1535 :group 'org-link-follow
1536 :type 'hook)
1538 (defcustom org-tab-follows-link nil
1539 "Non-nil means on links TAB will follow the link.
1540 Needs to be set before org.el is loaded.
1541 This really should not be used, it does not make sense, and the
1542 implementation is bad."
1543 :group 'org-link-follow
1544 :type 'boolean)
1546 (defcustom org-return-follows-link nil
1547 "Non-nil means on links RET will follow the link."
1548 :group 'org-link-follow
1549 :type 'boolean)
1551 (defcustom org-mouse-1-follows-link
1552 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1553 "Non-nil means mouse-1 on a link will follow the link.
1554 A longer mouse click will still set point. Does not work on XEmacs.
1555 Needs to be set before org.el is loaded."
1556 :group 'org-link-follow
1557 :type 'boolean)
1559 (defcustom org-mark-ring-length 4
1560 "Number of different positions to be recorded in the ring.
1561 Changing this requires a restart of Emacs to work correctly."
1562 :group 'org-link-follow
1563 :type 'integer)
1565 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1566 "Non-nil means internal links in Org files must exactly match a headline.
1567 When nil, the link search tries to match a phrase with all words
1568 in the search text."
1569 :group 'org-link-follow
1570 :version "24.1"
1571 :type '(choice
1572 (const :tag "Use fuzzy text search" nil)
1573 (const :tag "Match only exact headline" t)
1574 (const :tag "Match exact headline or query to create it"
1575 query-to-create)))
1577 (defcustom org-link-frame-setup
1578 '((vm . vm-visit-folder-other-frame)
1579 (vm-imap . vm-visit-imap-folder-other-frame)
1580 (gnus . org-gnus-no-new-news)
1581 (file . find-file-other-window)
1582 (wl . wl-other-frame))
1583 "Setup the frame configuration for following links.
1584 When following a link with Emacs, it may often be useful to display
1585 this link in another window or frame. This variable can be used to
1586 set this up for the different types of links.
1587 For VM, use any of
1588 `vm-visit-folder'
1589 `vm-visit-folder-other-window'
1590 `vm-visit-folder-other-frame'
1591 For Gnus, use any of
1592 `gnus'
1593 `gnus-other-frame'
1594 `org-gnus-no-new-news'
1595 For FILE, use any of
1596 `find-file'
1597 `find-file-other-window'
1598 `find-file-other-frame'
1599 For Wanderlust use any of
1600 `wl'
1601 `wl-other-frame'
1602 For the calendar, use the variable `calendar-setup'.
1603 For BBDB, it is currently only possible to display the matches in
1604 another window."
1605 :group 'org-link-follow
1606 :type '(list
1607 (cons (const vm)
1608 (choice
1609 (const vm-visit-folder)
1610 (const vm-visit-folder-other-window)
1611 (const vm-visit-folder-other-frame)))
1612 (cons (const gnus)
1613 (choice
1614 (const gnus)
1615 (const gnus-other-frame)
1616 (const org-gnus-no-new-news)))
1617 (cons (const file)
1618 (choice
1619 (const find-file)
1620 (const find-file-other-window)
1621 (const find-file-other-frame)))
1622 (cons (const wl)
1623 (choice
1624 (const wl)
1625 (const wl-other-frame)))))
1627 (defcustom org-display-internal-link-with-indirect-buffer nil
1628 "Non-nil means use indirect buffer to display infile links.
1629 Activating internal links (from one location in a file to another location
1630 in the same file) normally just jumps to the location. When the link is
1631 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1632 is displayed in
1633 another window. When this option is set, the other window actually displays
1634 an indirect buffer clone of the current buffer, to avoid any visibility
1635 changes to the current buffer."
1636 :group 'org-link-follow
1637 :type 'boolean)
1639 (defcustom org-open-non-existing-files nil
1640 "Non-nil means `org-open-file' will open non-existing files.
1641 When nil, an error will be generated.
1642 This variable applies only to external applications because they
1643 might choke on non-existing files. If the link is to a file that
1644 will be opened in Emacs, the variable is ignored."
1645 :group 'org-link-follow
1646 :type 'boolean)
1648 (defcustom org-open-directory-means-index-dot-org nil
1649 "Non-nil means a link to a directory really means to index.org.
1650 When nil, following a directory link will run dired or open a finder/explorer
1651 window on that directory."
1652 :group 'org-link-follow
1653 :type 'boolean)
1655 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1656 "Function and arguments to call for following mailto links.
1657 This is a list with the first element being a Lisp function, and the
1658 remaining elements being arguments to the function. In string arguments,
1659 %a will be replaced by the address, and %s will be replaced by the subject
1660 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1661 :group 'org-link-follow
1662 :type '(choice
1663 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1664 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1665 (const :tag "message-mail" (message-mail "%a" "%s"))
1666 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1668 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1669 "Non-nil means ask for confirmation before executing shell links.
1670 Shell links can be dangerous: just think about a link
1672 [[shell:rm -rf ~/*][Google Search]]
1674 This link would show up in your Org-mode document as \"Google Search\",
1675 but really it would remove your entire home directory.
1676 Therefore we advise against setting this variable to nil.
1677 Just change it to `y-or-n-p' if you want to confirm with a
1678 single keystroke rather than having to type \"yes\"."
1679 :group 'org-link-follow
1680 :type '(choice
1681 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1682 (const :tag "with y-or-n (faster)" y-or-n-p)
1683 (const :tag "no confirmation (dangerous)" nil)))
1684 (put 'org-confirm-shell-link-function
1685 'safe-local-variable
1686 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1688 (defcustom org-confirm-shell-link-not-regexp ""
1689 "A regexp to skip confirmation for shell links."
1690 :group 'org-link-follow
1691 :version "24.1"
1692 :type 'regexp)
1694 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1695 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1696 Elisp links can be dangerous: just think about a link
1698 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1700 This link would show up in your Org-mode document as \"Google Search\",
1701 but really it would remove your entire home directory.
1702 Therefore we advise against setting this variable to nil.
1703 Just change it to `y-or-n-p' if you want to confirm with a
1704 single keystroke rather than having to type \"yes\"."
1705 :group 'org-link-follow
1706 :type '(choice
1707 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1708 (const :tag "with y-or-n (faster)" y-or-n-p)
1709 (const :tag "no confirmation (dangerous)" nil)))
1710 (put 'org-confirm-shell-link-function
1711 'safe-local-variable
1712 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1714 (defcustom org-confirm-elisp-link-not-regexp ""
1715 "A regexp to skip confirmation for Elisp links."
1716 :group 'org-link-follow
1717 :version "24.1"
1718 :type 'regexp)
1720 (defconst org-file-apps-defaults-gnu
1721 '((remote . emacs)
1722 (system . mailcap)
1723 (t . mailcap))
1724 "Default file applications on a UNIX or GNU/Linux system.
1725 See `org-file-apps'.")
1727 (defconst org-file-apps-defaults-macosx
1728 '((remote . emacs)
1729 (t . "open %s")
1730 (system . "open %s")
1731 ("ps.gz" . "gv %s")
1732 ("eps.gz" . "gv %s")
1733 ("dvi" . "xdvi %s")
1734 ("fig" . "xfig %s"))
1735 "Default file applications on a MacOS X system.
1736 The system \"open\" is known as a default, but we use X11 applications
1737 for some files for which the OS does not have a good default.
1738 See `org-file-apps'.")
1740 (defconst org-file-apps-defaults-windowsnt
1741 (list
1742 '(remote . emacs)
1743 (cons t
1744 (list (if (featurep 'xemacs)
1745 'mswindows-shell-execute
1746 'w32-shell-execute)
1747 "open" 'file))
1748 (cons 'system
1749 (list (if (featurep 'xemacs)
1750 'mswindows-shell-execute
1751 'w32-shell-execute)
1752 "open" 'file)))
1753 "Default file applications on a Windows NT system.
1754 The system \"open\" is used for most files.
1755 See `org-file-apps'.")
1757 (defcustom org-file-apps
1759 (auto-mode . emacs)
1760 ("\\.mm\\'" . default)
1761 ("\\.x?html?\\'" . default)
1762 ("\\.pdf\\'" . default)
1764 "External applications for opening `file:path' items in a document.
1765 Org-mode uses system defaults for different file types, but
1766 you can use this variable to set the application for a given file
1767 extension. The entries in this list are cons cells where the car identifies
1768 files and the cdr the corresponding command. Possible values for the
1769 file identifier are
1770 \"string\" A string as a file identifier can be interpreted in different
1771 ways, depending on its contents:
1773 - Alphanumeric characters only:
1774 Match links with this file extension.
1775 Example: (\"pdf\" . \"evince %s\")
1776 to open PDFs with evince.
1778 - Regular expression: Match links where the
1779 filename matches the regexp. If you want to
1780 use groups here, use shy groups.
1782 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1783 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1784 to open *.html and *.xhtml with firefox.
1786 - Regular expression which contains (non-shy) groups:
1787 Match links where the whole link, including \"::\", and
1788 anything after that, matches the regexp.
1789 In a custom command string, %1, %2, etc. are replaced with
1790 the parts of the link that were matched by the groups.
1791 For backwards compatibility, if a command string is given
1792 that does not use any of the group matches, this case is
1793 handled identically to the second one (i.e. match against
1794 file name only).
1795 In a custom lisp form, you can access the group matches with
1796 (match-string n link).
1798 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1799 to open [[file:document.pdf::5]] with evince at page 5.
1801 `directory' Matches a directory
1802 `remote' Matches a remote file, accessible through tramp or efs.
1803 Remote files most likely should be visited through Emacs
1804 because external applications cannot handle such paths.
1805 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1806 so all files Emacs knows how to handle. Using this with
1807 command `emacs' will open most files in Emacs. Beware that this
1808 will also open html files inside Emacs, unless you add
1809 (\"html\" . default) to the list as well.
1810 t Default for files not matched by any of the other options.
1811 `system' The system command to open files, like `open' on Windows
1812 and Mac OS X, and mailcap under GNU/Linux. This is the command
1813 that will be selected if you call `C-c C-o' with a double
1814 \\[universal-argument] \\[universal-argument] prefix.
1816 Possible values for the command are:
1817 `emacs' The file will be visited by the current Emacs process.
1818 `default' Use the default application for this file type, which is the
1819 association for t in the list, most likely in the system-specific
1820 part.
1821 This can be used to overrule an unwanted setting in the
1822 system-specific variable.
1823 `system' Use the system command for opening files, like \"open\".
1824 This command is specified by the entry whose car is `system'.
1825 Most likely, the system-specific version of this variable
1826 does define this command, but you can overrule/replace it
1827 here.
1828 string A command to be executed by a shell; %s will be replaced
1829 by the path to the file.
1830 sexp A Lisp form which will be evaluated. The file path will
1831 be available in the Lisp variable `file'.
1832 For more examples, see the system specific constants
1833 `org-file-apps-defaults-macosx'
1834 `org-file-apps-defaults-windowsnt'
1835 `org-file-apps-defaults-gnu'."
1836 :group 'org-link-follow
1837 :type '(repeat
1838 (cons (choice :value ""
1839 (string :tag "Extension")
1840 (const :tag "System command to open files" system)
1841 (const :tag "Default for unrecognized files" t)
1842 (const :tag "Remote file" remote)
1843 (const :tag "Links to a directory" directory)
1844 (const :tag "Any files that have Emacs modes"
1845 auto-mode))
1846 (choice :value ""
1847 (const :tag "Visit with Emacs" emacs)
1848 (const :tag "Use default" default)
1849 (const :tag "Use the system command" system)
1850 (string :tag "Command")
1851 (sexp :tag "Lisp form")))))
1853 (defcustom org-doi-server-url "http://dx.doi.org/"
1854 "The URL of the DOI server."
1855 :type 'string
1856 :version "24.3"
1857 :group 'org-link-follow)
1859 (defgroup org-refile nil
1860 "Options concerning refiling entries in Org-mode."
1861 :tag "Org Refile"
1862 :group 'org)
1864 (defcustom org-directory "~/org"
1865 "Directory with org files.
1866 This is just a default location to look for Org files. There is no need
1867 at all to put your files into this directory. It is only used in the
1868 following situations:
1870 1. When a capture template specifies a target file that is not an
1871 absolute path. The path will then be interpreted relative to
1872 `org-directory'
1873 2. When a capture note is filed away in an interactive way (when exiting the
1874 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1875 with `org-directory' as the default path."
1876 :group 'org-refile
1877 :group 'org-remember
1878 :group 'org-capture
1879 :type 'directory)
1881 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1882 "Default target for storing notes.
1883 Used as a fall back file for org-remember.el and org-capture.el, for
1884 templates that do not specify a target file."
1885 :group 'org-refile
1886 :group 'org-remember
1887 :group 'org-capture
1888 :type '(choice
1889 (const :tag "Default from remember-data-file" nil)
1890 file))
1892 (defcustom org-goto-interface 'outline
1893 "The default interface to be used for `org-goto'.
1894 Allowed values are:
1895 outline The interface shows an outline of the relevant file
1896 and the correct heading is found by moving through
1897 the outline or by searching with incremental search.
1898 outline-path-completion Headlines in the current buffer are offered via
1899 completion. This is the interface also used by
1900 the refile command."
1901 :group 'org-refile
1902 :type '(choice
1903 (const :tag "Outline" outline)
1904 (const :tag "Outline-path-completion" outline-path-completion)))
1906 (defcustom org-goto-max-level 5
1907 "Maximum target level when running `org-goto' with refile interface."
1908 :group 'org-refile
1909 :type 'integer)
1911 (defcustom org-reverse-note-order nil
1912 "Non-nil means store new notes at the beginning of a file or entry.
1913 When nil, new notes will be filed to the end of a file or entry.
1914 This can also be a list with cons cells of regular expressions that
1915 are matched against file names, and values."
1916 :group 'org-remember
1917 :group 'org-capture
1918 :group 'org-refile
1919 :type '(choice
1920 (const :tag "Reverse always" t)
1921 (const :tag "Reverse never" nil)
1922 (repeat :tag "By file name regexp"
1923 (cons regexp boolean))))
1925 (defcustom org-log-refile nil
1926 "Information to record when a task is refiled.
1928 Possible values are:
1930 nil Don't add anything
1931 time Add a time stamp to the task
1932 note Prompt for a note and add it with template `org-log-note-headings'
1934 This option can also be set with on a per-file-basis with
1936 #+STARTUP: nologrefile
1937 #+STARTUP: logrefile
1938 #+STARTUP: lognoterefile
1940 You can have local logging settings for a subtree by setting the LOGGING
1941 property to one or more of these keywords.
1943 When bulk-refiling from the agenda, the value `note' is forbidden and
1944 will temporarily be changed to `time'."
1945 :group 'org-refile
1946 :group 'org-progress
1947 :version "24.1"
1948 :type '(choice
1949 (const :tag "No logging" nil)
1950 (const :tag "Record timestamp" time)
1951 (const :tag "Record timestamp with note." note)))
1953 (defcustom org-refile-targets nil
1954 "Targets for refiling entries with \\[org-refile].
1955 This is a list of cons cells. Each cell contains:
1956 - a specification of the files to be considered, either a list of files,
1957 or a symbol whose function or variable value will be used to retrieve
1958 a file name or a list of file names. If you use `org-agenda-files' for
1959 that, all agenda files will be scanned for targets. Nil means consider
1960 headings in the current buffer.
1961 - A specification of how to find candidate refile targets. This may be
1962 any of:
1963 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1964 This tag has to be present in all target headlines, inheritance will
1965 not be considered.
1966 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1967 todo keyword.
1968 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1969 headlines that are refiling targets.
1970 - a cons cell (:level . N). Any headline of level N is considered a target.
1971 Note that, when `org-odd-levels-only' is set, level corresponds to
1972 order in hierarchy, not to the number of stars.
1973 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1974 Note that, when `org-odd-levels-only' is set, level corresponds to
1975 order in hierarchy, not to the number of stars.
1977 Each element of this list generates a set of possible targets.
1978 The union of these sets is presented (with completion) to
1979 the user by `org-refile'.
1981 You can set the variable `org-refile-target-verify-function' to a function
1982 to verify each headline found by the simple criteria above.
1984 When this variable is nil, all top-level headlines in the current buffer
1985 are used, equivalent to the value `((nil . (:level . 1))'."
1986 :group 'org-refile
1987 :type '(repeat
1988 (cons
1989 (choice :value org-agenda-files
1990 (const :tag "All agenda files" org-agenda-files)
1991 (const :tag "Current buffer" nil)
1992 (function) (variable) (file))
1993 (choice :tag "Identify target headline by"
1994 (cons :tag "Specific tag" (const :value :tag) (string))
1995 (cons :tag "TODO keyword" (const :value :todo) (string))
1996 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1997 (cons :tag "Level number" (const :value :level) (integer))
1998 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2000 (defcustom org-refile-target-verify-function nil
2001 "Function to verify if the headline at point should be a refile target.
2002 The function will be called without arguments, with point at the
2003 beginning of the headline. It should return t and leave point
2004 where it is if the headline is a valid target for refiling.
2006 If the target should not be selected, the function must return nil.
2007 In addition to this, it may move point to a place from where the search
2008 should be continued. For example, the function may decide that the entire
2009 subtree of the current entry should be excluded and move point to the end
2010 of the subtree."
2011 :group 'org-refile
2012 :type 'function)
2014 (defcustom org-refile-use-cache nil
2015 "Non-nil means cache refile targets to speed up the process.
2016 The cache for a particular file will be updated automatically when
2017 the buffer has been killed, or when any of the marker used for flagging
2018 refile targets no longer points at a live buffer.
2019 If you have added new entries to a buffer that might themselves be targets,
2020 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2021 find that easier, `C-u C-u C-u C-c C-w'."
2022 :group 'org-refile
2023 :version "24.1"
2024 :type 'boolean)
2026 (defcustom org-refile-use-outline-path nil
2027 "Non-nil means provide refile targets as paths.
2028 So a level 3 headline will be available as level1/level2/level3.
2030 When the value is `file', also include the file name (without directory)
2031 into the path. In this case, you can also stop the completion after
2032 the file name, to get entries inserted as top level in the file.
2034 When `full-file-path', include the full file path."
2035 :group 'org-refile
2036 :type '(choice
2037 (const :tag "Not" nil)
2038 (const :tag "Yes" t)
2039 (const :tag "Start with file name" file)
2040 (const :tag "Start with full file path" full-file-path)))
2042 (defcustom org-outline-path-complete-in-steps t
2043 "Non-nil means complete the outline path in hierarchical steps.
2044 When Org-mode uses the refile interface to select an outline path
2045 \(see variable `org-refile-use-outline-path'), the completion of
2046 the path can be done is a single go, or if can be done in steps down
2047 the headline hierarchy. Going in steps is probably the best if you
2048 do not use a special completion package like `ido' or `icicles'.
2049 However, when using these packages, going in one step can be very
2050 fast, while still showing the whole path to the entry."
2051 :group 'org-refile
2052 :type 'boolean)
2054 (defcustom org-refile-allow-creating-parent-nodes nil
2055 "Non-nil means allow to create new nodes as refile targets.
2056 New nodes are then created by adding \"/new node name\" to the completion
2057 of an existing node. When the value of this variable is `confirm',
2058 new node creation must be confirmed by the user (recommended)
2059 When nil, the completion must match an existing entry.
2061 Note that, if the new heading is not seen by the criteria
2062 listed in `org-refile-targets', multiple instances of the same
2063 heading would be created by trying again to file under the new
2064 heading."
2065 :group 'org-refile
2066 :type '(choice
2067 (const :tag "Never" nil)
2068 (const :tag "Always" t)
2069 (const :tag "Prompt for confirmation" confirm)))
2071 (defcustom org-refile-active-region-within-subtree nil
2072 "Non-nil means also refile active region within a subtree.
2074 By default `org-refile' doesn't allow refiling regions if they
2075 don't contain a set of subtrees, but it might be convenient to
2076 do so sometimes: in that case, the first line of the region is
2077 converted to a headline before refiling."
2078 :group 'org-refile
2079 :version "24.1"
2080 :type 'boolean)
2082 (defgroup org-todo nil
2083 "Options concerning TODO items in Org-mode."
2084 :tag "Org TODO"
2085 :group 'org)
2087 (defgroup org-progress nil
2088 "Options concerning Progress logging in Org-mode."
2089 :tag "Org Progress"
2090 :group 'org-time)
2092 (defvar org-todo-interpretation-widgets
2093 '((:tag "Sequence (cycling hits every state)" sequence)
2094 (:tag "Type (cycling directly to DONE)" type))
2095 "The available interpretation symbols for customizing `org-todo-keywords'.
2096 Interested libraries should add to this list.")
2098 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2099 "List of TODO entry keyword sequences and their interpretation.
2100 \\<org-mode-map>This is a list of sequences.
2102 Each sequence starts with a symbol, either `sequence' or `type',
2103 indicating if the keywords should be interpreted as a sequence of
2104 action steps, or as different types of TODO items. The first
2105 keywords are states requiring action - these states will select a headline
2106 for inclusion into the global TODO list Org-mode produces. If one of
2107 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2108 signify that no further action is necessary. If \"|\" is not found,
2109 the last keyword is treated as the only DONE state of the sequence.
2111 The command \\[org-todo] cycles an entry through these states, and one
2112 additional state where no keyword is present. For details about this
2113 cycling, see the manual.
2115 TODO keywords and interpretation can also be set on a per-file basis with
2116 the special #+SEQ_TODO and #+TYP_TODO lines.
2118 Each keyword can optionally specify a character for fast state selection
2119 \(in combination with the variable `org-use-fast-todo-selection')
2120 and specifiers for state change logging, using the same syntax that
2121 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2122 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2123 indicates to record a time stamp each time this state is selected.
2125 Each keyword may also specify if a timestamp or a note should be
2126 recorded when entering or leaving the state, by adding additional
2127 characters in the parenthesis after the keyword. This looks like this:
2128 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2129 record only the time of the state change. With X and Y being either
2130 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2131 Y when leaving the state if and only if the *target* state does not
2132 define X. You may omit any of the fast-selection key or X or /Y,
2133 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2135 For backward compatibility, this variable may also be just a list
2136 of keywords. In this case the interpretation (sequence or type) will be
2137 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2138 :group 'org-todo
2139 :group 'org-keywords
2140 :type '(choice
2141 (repeat :tag "Old syntax, just keywords"
2142 (string :tag "Keyword"))
2143 (repeat :tag "New syntax"
2144 (cons
2145 (choice
2146 :tag "Interpretation"
2147 ;;Quick and dirty way to see
2148 ;;`org-todo-interpretations'. This takes the
2149 ;;place of item arguments
2150 :convert-widget
2151 (lambda (widget)
2152 (widget-put widget
2153 :args (mapcar
2154 #'(lambda (x)
2155 (widget-convert
2156 (cons 'const x)))
2157 org-todo-interpretation-widgets))
2158 widget))
2159 (repeat
2160 (string :tag "Keyword"))))))
2162 (defvar org-todo-keywords-1 nil
2163 "All TODO and DONE keywords active in a buffer.")
2164 (make-variable-buffer-local 'org-todo-keywords-1)
2165 (defvar org-todo-keywords-for-agenda nil)
2166 (defvar org-done-keywords-for-agenda nil)
2167 (defvar org-drawers-for-agenda nil)
2168 (defvar org-todo-keyword-alist-for-agenda nil)
2169 (defvar org-tag-alist-for-agenda nil)
2170 (defvar org-agenda-contributing-files nil)
2171 (defvar org-not-done-keywords nil)
2172 (make-variable-buffer-local 'org-not-done-keywords)
2173 (defvar org-done-keywords nil)
2174 (make-variable-buffer-local 'org-done-keywords)
2175 (defvar org-todo-heads nil)
2176 (make-variable-buffer-local 'org-todo-heads)
2177 (defvar org-todo-sets nil)
2178 (make-variable-buffer-local 'org-todo-sets)
2179 (defvar org-todo-log-states nil)
2180 (make-variable-buffer-local 'org-todo-log-states)
2181 (defvar org-todo-kwd-alist nil)
2182 (make-variable-buffer-local 'org-todo-kwd-alist)
2183 (defvar org-todo-key-alist nil)
2184 (make-variable-buffer-local 'org-todo-key-alist)
2185 (defvar org-todo-key-trigger nil)
2186 (make-variable-buffer-local 'org-todo-key-trigger)
2188 (defcustom org-todo-interpretation 'sequence
2189 "Controls how TODO keywords are interpreted.
2190 This variable is in principle obsolete and is only used for
2191 backward compatibility, if the interpretation of todo keywords is
2192 not given already in `org-todo-keywords'. See that variable for
2193 more information."
2194 :group 'org-todo
2195 :group 'org-keywords
2196 :type '(choice (const sequence)
2197 (const type)))
2199 (defcustom org-use-fast-todo-selection t
2200 "Non-nil means use the fast todo selection scheme with C-c C-t.
2201 This variable describes if and under what circumstances the cycling
2202 mechanism for TODO keywords will be replaced by a single-key, direct
2203 selection scheme.
2205 When nil, fast selection is never used.
2207 When the symbol `prefix', it will be used when `org-todo' is called
2208 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2209 `C-u t' in an agenda buffer.
2211 When t, fast selection is used by default. In this case, the prefix
2212 argument forces cycling instead.
2214 In all cases, the special interface is only used if access keys have
2215 actually been assigned by the user, i.e. if keywords in the configuration
2216 are followed by a letter in parenthesis, like TODO(t)."
2217 :group 'org-todo
2218 :type '(choice
2219 (const :tag "Never" nil)
2220 (const :tag "By default" t)
2221 (const :tag "Only with C-u C-c C-t" prefix)))
2223 (defcustom org-provide-todo-statistics t
2224 "Non-nil means update todo statistics after insert and toggle.
2225 ALL-HEADLINES means update todo statistics by including headlines
2226 with no TODO keyword as well, counting them as not done.
2227 A list of TODO keywords means the same, but skip keywords that are
2228 not in this list.
2230 When this is set, todo statistics is updated in the parent of the
2231 current entry each time a todo state is changed."
2232 :group 'org-todo
2233 :type '(choice
2234 (const :tag "Yes, only for TODO entries" t)
2235 (const :tag "Yes, including all entries" 'all-headlines)
2236 (repeat :tag "Yes, for TODOs in this list"
2237 (string :tag "TODO keyword"))
2238 (other :tag "No TODO statistics" nil)))
2240 (defcustom org-hierarchical-todo-statistics t
2241 "Non-nil means TODO statistics covers just direct children.
2242 When nil, all entries in the subtree are considered.
2243 This has only an effect if `org-provide-todo-statistics' is set.
2244 To set this to nil for only a single subtree, use a COOKIE_DATA
2245 property and include the word \"recursive\" into the value."
2246 :group 'org-todo
2247 :type 'boolean)
2249 (defcustom org-after-todo-state-change-hook nil
2250 "Hook which is run after the state of a TODO item was changed.
2251 The new state (a string with a TODO keyword, or nil) is available in the
2252 Lisp variable `org-state'."
2253 :group 'org-todo
2254 :type 'hook)
2256 (defvar org-blocker-hook nil
2257 "Hook for functions that are allowed to block a state change.
2259 Each function gets as its single argument a property list, see
2260 `org-trigger-hook' for more information about this list.
2262 If any of the functions in this hook returns nil, the state change
2263 is blocked.")
2265 (defvar org-trigger-hook nil
2266 "Hook for functions that are triggered by a state change.
2268 Each function gets as its single argument a property list with at least
2269 the following elements:
2271 (:type type-of-change :position pos-at-entry-start
2272 :from old-state :to new-state)
2274 Depending on the type, more properties may be present.
2276 This mechanism is currently implemented for:
2278 TODO state changes
2279 ------------------
2280 :type todo-state-change
2281 :from previous state (keyword as a string), or nil, or a symbol
2282 'todo' or 'done', to indicate the general type of state.
2283 :to new state, like in :from")
2285 (defcustom org-enforce-todo-dependencies nil
2286 "Non-nil means undone TODO entries will block switching the parent to DONE.
2287 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2288 be blocked if any prior sibling is not yet done.
2289 Finally, if the parent is blocked because of ordered siblings of its own,
2290 the child will also be blocked."
2291 :set (lambda (var val)
2292 (set var val)
2293 (if val
2294 (add-hook 'org-blocker-hook
2295 'org-block-todo-from-children-or-siblings-or-parent)
2296 (remove-hook 'org-blocker-hook
2297 'org-block-todo-from-children-or-siblings-or-parent)))
2298 :group 'org-todo
2299 :type 'boolean)
2301 (defcustom org-enforce-todo-checkbox-dependencies nil
2302 "Non-nil means unchecked boxes will block switching the parent to DONE.
2303 When this is nil, checkboxes have no influence on switching TODO states.
2304 When non-nil, you first need to check off all check boxes before the TODO
2305 entry can be switched to DONE.
2306 This variable needs to be set before org.el is loaded, and you need to
2307 restart Emacs after a change to make the change effective. The only way
2308 to change is while Emacs is running is through the customize interface."
2309 :set (lambda (var val)
2310 (set var val)
2311 (if val
2312 (add-hook 'org-blocker-hook
2313 'org-block-todo-from-checkboxes)
2314 (remove-hook 'org-blocker-hook
2315 'org-block-todo-from-checkboxes)))
2316 :group 'org-todo
2317 :type 'boolean)
2319 (defcustom org-treat-insert-todo-heading-as-state-change nil
2320 "Non-nil means inserting a TODO heading is treated as state change.
2321 So when the command \\[org-insert-todo-heading] is used, state change
2322 logging will apply if appropriate. When nil, the new TODO item will
2323 be inserted directly, and no logging will take place."
2324 :group 'org-todo
2325 :type 'boolean)
2327 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2328 "Non-nil means switching TODO states with S-cursor counts as state change.
2329 This is the default behavior. However, setting this to nil allows a
2330 convenient way to select a TODO state and bypass any logging associated
2331 with that."
2332 :group 'org-todo
2333 :type 'boolean)
2335 (defcustom org-todo-state-tags-triggers nil
2336 "Tag changes that should be triggered by TODO state changes.
2337 This is a list. Each entry is
2339 (state-change (tag . flag) .......)
2341 State-change can be a string with a state, and empty string to indicate the
2342 state that has no TODO keyword, or it can be one of the symbols `todo'
2343 or `done', meaning any not-done or done state, respectively."
2344 :group 'org-todo
2345 :group 'org-tags
2346 :type '(repeat
2347 (cons (choice :tag "When changing to"
2348 (const :tag "Not-done state" todo)
2349 (const :tag "Done state" done)
2350 (string :tag "State"))
2351 (repeat
2352 (cons :tag "Tag action"
2353 (string :tag "Tag")
2354 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2356 (defcustom org-log-done nil
2357 "Information to record when a task moves to the DONE state.
2359 Possible values are:
2361 nil Don't add anything, just change the keyword
2362 time Add a time stamp to the task
2363 note Prompt for a note and add it with template `org-log-note-headings'
2365 This option can also be set with on a per-file-basis with
2367 #+STARTUP: nologdone
2368 #+STARTUP: logdone
2369 #+STARTUP: lognotedone
2371 You can have local logging settings for a subtree by setting the LOGGING
2372 property to one or more of these keywords."
2373 :group 'org-todo
2374 :group 'org-progress
2375 :type '(choice
2376 (const :tag "No logging" nil)
2377 (const :tag "Record CLOSED timestamp" time)
2378 (const :tag "Record CLOSED timestamp with note." note)))
2380 ;; Normalize old uses of org-log-done.
2381 (cond
2382 ((eq org-log-done t) (setq org-log-done 'time))
2383 ((and (listp org-log-done) (memq 'done org-log-done))
2384 (setq org-log-done 'note)))
2386 (defcustom org-log-reschedule nil
2387 "Information to record when the scheduling date of a tasks is modified.
2389 Possible values are:
2391 nil Don't add anything, just change the date
2392 time Add a time stamp to the task
2393 note Prompt for a note and add it with template `org-log-note-headings'
2395 This option can also be set with on a per-file-basis with
2397 #+STARTUP: nologreschedule
2398 #+STARTUP: logreschedule
2399 #+STARTUP: lognotereschedule"
2400 :group 'org-todo
2401 :group 'org-progress
2402 :type '(choice
2403 (const :tag "No logging" nil)
2404 (const :tag "Record timestamp" time)
2405 (const :tag "Record timestamp with note." note)))
2407 (defcustom org-log-redeadline nil
2408 "Information to record when the deadline date of a tasks is modified.
2410 Possible values are:
2412 nil Don't add anything, just change the date
2413 time Add a time stamp to the task
2414 note Prompt for a note and add it with template `org-log-note-headings'
2416 This option can also be set with on a per-file-basis with
2418 #+STARTUP: nologredeadline
2419 #+STARTUP: logredeadline
2420 #+STARTUP: lognoteredeadline
2422 You can have local logging settings for a subtree by setting the LOGGING
2423 property to one or more of these keywords."
2424 :group 'org-todo
2425 :group 'org-progress
2426 :type '(choice
2427 (const :tag "No logging" nil)
2428 (const :tag "Record timestamp" time)
2429 (const :tag "Record timestamp with note." note)))
2431 (defcustom org-log-note-clock-out nil
2432 "Non-nil means record a note when clocking out of an item.
2433 This can also be configured on a per-file basis by adding one of
2434 the following lines anywhere in the buffer:
2436 #+STARTUP: lognoteclock-out
2437 #+STARTUP: nolognoteclock-out"
2438 :group 'org-todo
2439 :group 'org-progress
2440 :type 'boolean)
2442 (defcustom org-log-done-with-time t
2443 "Non-nil means the CLOSED time stamp will contain date and time.
2444 When nil, only the date will be recorded."
2445 :group 'org-progress
2446 :type 'boolean)
2448 (defcustom org-log-note-headings
2449 '((done . "CLOSING NOTE %t")
2450 (state . "State %-12s from %-12S %t")
2451 (note . "Note taken on %t")
2452 (reschedule . "Rescheduled from %S on %t")
2453 (delschedule . "Not scheduled, was %S on %t")
2454 (redeadline . "New deadline from %S on %t")
2455 (deldeadline . "Removed deadline, was %S on %t")
2456 (refile . "Refiled on %t")
2457 (clock-out . ""))
2458 "Headings for notes added to entries.
2459 The value is an alist, with the car being a symbol indicating the note
2460 context, and the cdr is the heading to be used. The heading may also be the
2461 empty string.
2462 %t in the heading will be replaced by a time stamp.
2463 %T will be an active time stamp instead the default inactive one
2464 %d will be replaced by a short-format time stamp.
2465 %D will be replaced by an active short-format time stamp.
2466 %s will be replaced by the new TODO state, in double quotes.
2467 %S will be replaced by the old TODO state, in double quotes.
2468 %u will be replaced by the user name.
2469 %U will be replaced by the full user name.
2471 In fact, it is not a good idea to change the `state' entry, because
2472 agenda log mode depends on the format of these entries."
2473 :group 'org-todo
2474 :group 'org-progress
2475 :type '(list :greedy t
2476 (cons (const :tag "Heading when closing an item" done) string)
2477 (cons (const :tag
2478 "Heading when changing todo state (todo sequence only)"
2479 state) string)
2480 (cons (const :tag "Heading when just taking a note" note) string)
2481 (cons (const :tag "Heading when clocking out" clock-out) string)
2482 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2483 (cons (const :tag "Heading when rescheduling" reschedule) string)
2484 (cons (const :tag "Heading when changing deadline" redeadline) string)
2485 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2486 (cons (const :tag "Heading when refiling" refile) string)))
2488 (unless (assq 'note org-log-note-headings)
2489 (push '(note . "%t") org-log-note-headings))
2491 (defcustom org-log-into-drawer nil
2492 "Non-nil means insert state change notes and time stamps into a drawer.
2493 When nil, state changes notes will be inserted after the headline and
2494 any scheduling and clock lines, but not inside a drawer.
2496 The value of this variable should be the name of the drawer to use.
2497 LOGBOOK is proposed as the default drawer for this purpose, you can
2498 also set this to a string to define the drawer of your choice.
2500 A value of t is also allowed, representing \"LOGBOOK\".
2502 If this variable is set, `org-log-state-notes-insert-after-drawers'
2503 will be ignored.
2505 You can set the property LOG_INTO_DRAWER to overrule this setting for
2506 a subtree."
2507 :group 'org-todo
2508 :group 'org-progress
2509 :type '(choice
2510 (const :tag "Not into a drawer" nil)
2511 (const :tag "LOGBOOK" t)
2512 (string :tag "Other")))
2514 (if (fboundp 'defvaralias)
2515 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2517 (defun org-log-into-drawer ()
2518 "Return the value of `org-log-into-drawer', but let properties overrule.
2519 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2520 used instead of the default value."
2521 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2522 (cond
2523 ((or (not p) (equal p "nil")) org-log-into-drawer)
2524 ((equal p "t") "LOGBOOK")
2525 (t p))))
2527 (defcustom org-log-state-notes-insert-after-drawers nil
2528 "Non-nil means insert state change notes after any drawers in entry.
2529 Only the drawers that *immediately* follow the headline and the
2530 deadline/scheduled line are skipped.
2531 When nil, insert notes right after the heading and perhaps the line
2532 with deadline/scheduling if present.
2534 This variable will have no effect if `org-log-into-drawer' is
2535 set."
2536 :group 'org-todo
2537 :group 'org-progress
2538 :type 'boolean)
2540 (defcustom org-log-states-order-reversed t
2541 "Non-nil means the latest state note will be directly after heading.
2542 When nil, the state change notes will be ordered according to time."
2543 :group 'org-todo
2544 :group 'org-progress
2545 :type 'boolean)
2547 (defcustom org-todo-repeat-to-state nil
2548 "The TODO state to which a repeater should return the repeating task.
2549 By default this is the first task in a TODO sequence, or the previous state
2550 in a TODO_TYP set. But you can specify another task here.
2551 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2552 :group 'org-todo
2553 :version "24.1"
2554 :type '(choice (const :tag "Head of sequence" nil)
2555 (string :tag "Specific state")))
2557 (defcustom org-log-repeat 'time
2558 "Non-nil means record moving through the DONE state when triggering repeat.
2559 An auto-repeating task is immediately switched back to TODO when
2560 marked DONE. If you are not logging state changes (by adding \"@\"
2561 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2562 record a closing note, there will be no record of the task moving
2563 through DONE. This variable forces taking a note anyway.
2565 nil Don't force a record
2566 time Record a time stamp
2567 note Prompt for a note and add it with template `org-log-note-headings'
2569 This option can also be set with on a per-file-basis with
2571 #+STARTUP: nologrepeat
2572 #+STARTUP: logrepeat
2573 #+STARTUP: lognoterepeat
2575 You can have local logging settings for a subtree by setting the LOGGING
2576 property to one or more of these keywords."
2577 :group 'org-todo
2578 :group 'org-progress
2579 :type '(choice
2580 (const :tag "Don't force a record" nil)
2581 (const :tag "Force recording the DONE state" time)
2582 (const :tag "Force recording a note with the DONE state" note)))
2585 (defgroup org-priorities nil
2586 "Priorities in Org-mode."
2587 :tag "Org Priorities"
2588 :group 'org-todo)
2590 (defcustom org-enable-priority-commands t
2591 "Non-nil means priority commands are active.
2592 When nil, these commands will be disabled, so that you never accidentally
2593 set a priority."
2594 :group 'org-priorities
2595 :type 'boolean)
2597 (defcustom org-highest-priority ?A
2598 "The highest priority of TODO items. A character like ?A, ?B etc.
2599 Must have a smaller ASCII number than `org-lowest-priority'."
2600 :group 'org-priorities
2601 :type 'character)
2603 (defcustom org-lowest-priority ?C
2604 "The lowest priority of TODO items. A character like ?A, ?B etc.
2605 Must have a larger ASCII number than `org-highest-priority'."
2606 :group 'org-priorities
2607 :type 'character)
2609 (defcustom org-default-priority ?B
2610 "The default priority of TODO items.
2611 This is the priority an item gets if no explicit priority is given.
2612 When starting to cycle on an empty priority the first step in the cycle
2613 depends on `org-priority-start-cycle-with-default'. The resulting first
2614 step priority must not exceed the range from `org-highest-priority' to
2615 `org-lowest-priority' which means that `org-default-priority' has to be
2616 in this range exclusive or inclusive the range boundaries. Else the
2617 first step refuses to set the default and the second will fall back
2618 to (depending on the command used) the highest or lowest priority."
2619 :group 'org-priorities
2620 :type 'character)
2622 (defcustom org-priority-start-cycle-with-default t
2623 "Non-nil means start with default priority when starting to cycle.
2624 When this is nil, the first step in the cycle will be (depending on the
2625 command used) one higher or lower than the default priority.
2626 See also `org-default-priority'."
2627 :group 'org-priorities
2628 :type 'boolean)
2630 (defcustom org-get-priority-function nil
2631 "Function to extract the priority from a string.
2632 The string is normally the headline. If this is nil Org computes the
2633 priority from the priority cookie like [#A] in the headline. It returns
2634 an integer, increasing by 1000 for each priority level.
2635 The user can set a different function here, which should take a string
2636 as an argument and return the numeric priority."
2637 :group 'org-priorities
2638 :version "24.1"
2639 :type 'function)
2641 (defgroup org-time nil
2642 "Options concerning time stamps and deadlines in Org-mode."
2643 :tag "Org Time"
2644 :group 'org)
2646 (defcustom org-insert-labeled-timestamps-at-point nil
2647 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2648 When nil, these labeled time stamps are forces into the second line of an
2649 entry, just after the headline. When scheduling from the global TODO list,
2650 the time stamp will always be forced into the second line."
2651 :group 'org-time
2652 :type 'boolean)
2654 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2655 "Formats for `format-time-string' which are used for time stamps.
2656 It is not recommended to change this constant.")
2658 (defcustom org-time-stamp-rounding-minutes '(0 5)
2659 "Number of minutes to round time stamps to.
2660 These are two values, the first applies when first creating a time stamp.
2661 The second applies when changing it with the commands `S-up' and `S-down'.
2662 When changing the time stamp, this means that it will change in steps
2663 of N minutes, as given by the second value.
2665 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2666 numbers should be factors of 60, so for example 5, 10, 15.
2668 When this is larger than 1, you can still force an exact time stamp by using
2669 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2670 and by using a prefix arg to `S-up/down' to specify the exact number
2671 of minutes to shift."
2672 :group 'org-time
2673 :get #'(lambda (var) ; Make sure both elements are there
2674 (if (integerp (default-value var))
2675 (list (default-value var) 5)
2676 (default-value var)))
2677 :type '(list
2678 (integer :tag "when inserting times")
2679 (integer :tag "when modifying times")))
2681 ;; Normalize old customizations of this variable.
2682 (when (integerp org-time-stamp-rounding-minutes)
2683 (setq org-time-stamp-rounding-minutes
2684 (list org-time-stamp-rounding-minutes
2685 org-time-stamp-rounding-minutes)))
2687 (defcustom org-display-custom-times nil
2688 "Non-nil means overlay custom formats over all time stamps.
2689 The formats are defined through the variable `org-time-stamp-custom-formats'.
2690 To turn this on on a per-file basis, insert anywhere in the file:
2691 #+STARTUP: customtime"
2692 :group 'org-time
2693 :set 'set-default
2694 :type 'sexp)
2695 (make-variable-buffer-local 'org-display-custom-times)
2697 (defcustom org-time-stamp-custom-formats
2698 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2699 "Custom formats for time stamps. See `format-time-string' for the syntax.
2700 These are overlaid over the default ISO format if the variable
2701 `org-display-custom-times' is set. Time like %H:%M should be at the
2702 end of the second format. The custom formats are also honored by export
2703 commands, if custom time display is turned on at the time of export."
2704 :group 'org-time
2705 :type 'sexp)
2707 (defun org-time-stamp-format (&optional long inactive)
2708 "Get the right format for a time string."
2709 (let ((f (if long (cdr org-time-stamp-formats)
2710 (car org-time-stamp-formats))))
2711 (if inactive
2712 (concat "[" (substring f 1 -1) "]")
2713 f)))
2715 (defcustom org-time-clocksum-format "%d:%02d"
2716 "The format string used when creating CLOCKSUM lines.
2717 This is also used when org-mode generates a time duration."
2718 :group 'org-time
2719 :type 'string)
2721 (defcustom org-time-clocksum-use-fractional nil
2722 "If non-nil, \\[org-clock-display] uses fractional times.
2723 org-mode generates a time duration."
2724 :group 'org-time
2725 :type 'boolean)
2727 (defcustom org-time-clocksum-fractional-format "%.2f"
2728 "The format string used when creating CLOCKSUM lines, or when
2729 org-mode generates a time duration."
2730 :group 'org-time
2731 :type 'string)
2733 (defcustom org-deadline-warning-days 14
2734 "No. of days before expiration during which a deadline becomes active.
2735 This variable governs the display in sparse trees and in the agenda.
2736 When 0 or negative, it means use this number (the absolute value of it)
2737 even if a deadline has a different individual lead time specified.
2739 Custom commands can set this variable in the options section."
2740 :group 'org-time
2741 :group 'org-agenda-daily/weekly
2742 :type 'integer)
2744 (defcustom org-read-date-prefer-future t
2745 "Non-nil means assume future for incomplete date input from user.
2746 This affects the following situations:
2747 1. The user gives a month but not a year.
2748 For example, if it is April and you enter \"feb 2\", this will be read
2749 as Feb 2, *next* year. \"May 5\", however, will be this year.
2750 2. The user gives a day, but no month.
2751 For example, if today is the 15th, and you enter \"3\", Org-mode will
2752 read this as the third of *next* month. However, if you enter \"17\",
2753 it will be considered as *this* month.
2755 If you set this variable to the symbol `time', then also the following
2756 will work:
2758 3. If the user gives a time.
2759 If the time is before now, it will be interpreted as tomorrow.
2761 Currently none of this works for ISO week specifications.
2763 When this option is nil, the current day, month and year will always be
2764 used as defaults.
2766 See also `org-agenda-jump-prefer-future'."
2767 :group 'org-time
2768 :type '(choice
2769 (const :tag "Never" nil)
2770 (const :tag "Check month and day" t)
2771 (const :tag "Check month, day, and time" time)))
2773 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2774 "Should the agenda jump command prefer the future for incomplete dates?
2775 The default is to do the same as configured in `org-read-date-prefer-future'.
2776 But you can also set a deviating value here.
2777 This may t or nil, or the symbol `org-read-date-prefer-future'."
2778 :group 'org-agenda
2779 :group 'org-time
2780 :version "24.1"
2781 :type '(choice
2782 (const :tag "Use org-read-date-prefer-future"
2783 org-read-date-prefer-future)
2784 (const :tag "Never" nil)
2785 (const :tag "Always" t)))
2787 (defcustom org-read-date-force-compatible-dates t
2788 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2790 Depending on the system Emacs is running on, certain dates cannot
2791 be represented with the type used internally to represent time.
2792 Dates between 1970-1-1 and 2038-1-1 can always be represented
2793 correctly. Some systems allow for earlier dates, some for later,
2794 some for both. One way to find out it to insert any date into an
2795 Org buffer, putting the cursor on the year and hitting S-up and
2796 S-down to test the range.
2798 When this variable is set to t, the date/time prompt will not let
2799 you specify dates outside the 1970-2037 range, so it is certain that
2800 these dates will work in whatever version of Emacs you are
2801 running, and also that you can move a file from one Emacs implementation
2802 to another. WHenever Org is forcing the year for you, it will display
2803 a message and beep.
2805 When this variable is nil, Org will check if the date is
2806 representable in the specific Emacs implementation you are using.
2807 If not, it will force a year, usually the current year, and beep
2808 to remind you. Currently this setting is not recommended because
2809 the likelihood that you will open your Org files in an Emacs that
2810 has limited date range is not negligible.
2812 A workaround for this problem is to use diary sexp dates for time
2813 stamps outside of this range."
2814 :group 'org-time
2815 :version "24.1"
2816 :type 'boolean)
2818 (defcustom org-read-date-display-live t
2819 "Non-nil means display current interpretation of date prompt live.
2820 This display will be in an overlay, in the minibuffer."
2821 :group 'org-time
2822 :type 'boolean)
2824 (defcustom org-read-date-popup-calendar t
2825 "Non-nil means pop up a calendar when prompting for a date.
2826 In the calendar, the date can be selected with mouse-1. However, the
2827 minibuffer will also be active, and you can simply enter the date as well.
2828 When nil, only the minibuffer will be available."
2829 :group 'org-time
2830 :type 'boolean)
2831 (if (fboundp 'defvaralias)
2832 (defvaralias 'org-popup-calendar-for-date-prompt
2833 'org-read-date-popup-calendar))
2835 (defcustom org-read-date-minibuffer-setup-hook nil
2836 "Hook to be used to set up keys for the date/time interface.
2837 Add key definitions to `minibuffer-local-map', which will be a temporary
2838 copy."
2839 :group 'org-time
2840 :type 'hook)
2842 (defcustom org-extend-today-until 0
2843 "The hour when your day really ends. Must be an integer.
2844 This has influence for the following applications:
2845 - When switching the agenda to \"today\". It it is still earlier than
2846 the time given here, the day recognized as TODAY is actually yesterday.
2847 - When a date is read from the user and it is still before the time given
2848 here, the current date and time will be assumed to be yesterday, 23:59.
2849 Also, timestamps inserted in capture templates follow this rule.
2851 IMPORTANT: This is a feature whose implementation is and likely will
2852 remain incomplete. Really, it is only here because past midnight seems to
2853 be the favorite working time of John Wiegley :-)"
2854 :group 'org-time
2855 :type 'integer)
2857 (defcustom org-use-effective-time nil
2858 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2859 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2860 \"effective time\" of any timestamps between midnight and 8am will be
2861 23:59 of the previous day."
2862 :group 'org-time
2863 :version "24.1"
2864 :type 'boolean)
2866 (defcustom org-use-last-clock-out-time-as-effective-time nil
2867 "When non-nil, use the last clock out time for `org-todo'.
2868 Note that this option has precedence over the combined use of
2869 `org-use-effective-time' and `org-extend-today-until'."
2870 :group 'org-time
2871 ;; :version "24.3"
2872 :type 'boolean)
2874 (defcustom org-edit-timestamp-down-means-later nil
2875 "Non-nil means S-down will increase the time in a time stamp.
2876 When nil, S-up will increase."
2877 :group 'org-time
2878 :type 'boolean)
2880 (defcustom org-calendar-follow-timestamp-change t
2881 "Non-nil means make the calendar window follow timestamp changes.
2882 When a timestamp is modified and the calendar window is visible, it will be
2883 moved to the new date."
2884 :group 'org-time
2885 :type 'boolean)
2887 (defgroup org-tags nil
2888 "Options concerning tags in Org-mode."
2889 :tag "Org Tags"
2890 :group 'org)
2892 (defcustom org-tag-alist nil
2893 "List of tags allowed in Org-mode files.
2894 When this list is nil, Org-mode will base TAG input on what is already in the
2895 buffer.
2896 The value of this variable is an alist, the car of each entry must be a
2897 keyword as a string, the cdr may be a character that is used to select
2898 that tag through the fast-tag-selection interface.
2899 See the manual for details."
2900 :group 'org-tags
2901 :type '(repeat
2902 (choice
2903 (cons (string :tag "Tag name")
2904 (character :tag "Access char"))
2905 (list :tag "Start radio group"
2906 (const :startgroup)
2907 (option (string :tag "Group description")))
2908 (list :tag "End radio group"
2909 (const :endgroup)
2910 (option (string :tag "Group description")))
2911 (const :tag "New line" (:newline)))))
2913 (defcustom org-tag-persistent-alist nil
2914 "List of tags that will always appear in all Org-mode files.
2915 This is in addition to any in buffer settings or customizations
2916 of `org-tag-alist'.
2917 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2918 The value of this variable is an alist, the car of each entry must be a
2919 keyword as a string, the cdr may be a character that is used to select
2920 that tag through the fast-tag-selection interface.
2921 See the manual for details.
2922 To disable these tags on a per-file basis, insert anywhere in the file:
2923 #+STARTUP: noptag"
2924 :group 'org-tags
2925 :type '(repeat
2926 (choice
2927 (cons (string :tag "Tag name")
2928 (character :tag "Access char"))
2929 (const :tag "Start radio group" (:startgroup))
2930 (const :tag "End radio group" (:endgroup))
2931 (const :tag "New line" (:newline)))))
2933 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2934 "If non-nil, always offer completion for all tags of all agenda files.
2935 Instead of customizing this variable directly, you might want to
2936 set it locally for capture buffers, because there no list of
2937 tags in that file can be created dynamically (there are none).
2939 (add-hook 'org-capture-mode-hook
2940 (lambda ()
2941 (set (make-local-variable
2942 'org-complete-tags-always-offer-all-agenda-tags)
2943 t)))"
2944 :group 'org-tags
2945 :version "24.1"
2946 :type 'boolean)
2948 (defvar org-file-tags nil
2949 "List of tags that can be inherited by all entries in the file.
2950 The tags will be inherited if the variable `org-use-tag-inheritance'
2951 says they should be.
2952 This variable is populated from #+FILETAGS lines.")
2954 (defcustom org-use-fast-tag-selection 'auto
2955 "Non-nil means use fast tag selection scheme.
2956 This is a special interface to select and deselect tags with single keys.
2957 When nil, fast selection is never used.
2958 When the symbol `auto', fast selection is used if and only if selection
2959 characters for tags have been configured, either through the variable
2960 `org-tag-alist' or through a #+TAGS line in the buffer.
2961 When t, fast selection is always used and selection keys are assigned
2962 automatically if necessary."
2963 :group 'org-tags
2964 :type '(choice
2965 (const :tag "Always" t)
2966 (const :tag "Never" nil)
2967 (const :tag "When selection characters are configured" 'auto)))
2969 (defcustom org-fast-tag-selection-single-key nil
2970 "Non-nil means fast tag selection exits after first change.
2971 When nil, you have to press RET to exit it.
2972 During fast tag selection, you can toggle this flag with `C-c'.
2973 This variable can also have the value `expert'. In this case, the window
2974 displaying the tags menu is not even shown, until you press C-c again."
2975 :group 'org-tags
2976 :type '(choice
2977 (const :tag "No" nil)
2978 (const :tag "Yes" t)
2979 (const :tag "Expert" expert)))
2981 (defvar org-fast-tag-selection-include-todo nil
2982 "Non-nil means fast tags selection interface will also offer TODO states.
2983 This is an undocumented feature, you should not rely on it.")
2985 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2986 "The column to which tags should be indented in a headline.
2987 If this number is positive, it specifies the column. If it is negative,
2988 it means that the tags should be flushright to that column. For example,
2989 -80 works well for a normal 80 character screen.
2990 When 0, place tags directly after headline text, with only one space in
2991 between."
2992 :group 'org-tags
2993 :type 'integer)
2995 (defcustom org-auto-align-tags t
2996 "Non-nil keeps tags aligned when modifying headlines.
2997 Some operations (i.e. demoting) change the length of a headline and
2998 therefore shift the tags around. With this option turned on, after
2999 each such operation the tags are again aligned to `org-tags-column'."
3000 :group 'org-tags
3001 :type 'boolean)
3003 (defcustom org-use-tag-inheritance t
3004 "Non-nil means tags in levels apply also for sublevels.
3005 When nil, only the tags directly given in a specific line apply there.
3006 This may also be a list of tags that should be inherited, or a regexp that
3007 matches tags that should be inherited. Additional control is possible
3008 with the variable `org-tags-exclude-from-inheritance' which gives an
3009 explicit list of tags to be excluded from inheritance., even if the value of
3010 `org-use-tag-inheritance' would select it for inheritance.
3012 If this option is t, a match early-on in a tree can lead to a large
3013 number of matches in the subtree when constructing the agenda or creating
3014 a sparse tree. If you only want to see the first match in a tree during
3015 a search, check out the variable `org-tags-match-list-sublevels'."
3016 :group 'org-tags
3017 :type '(choice
3018 (const :tag "Not" nil)
3019 (const :tag "Always" t)
3020 (repeat :tag "Specific tags" (string :tag "Tag"))
3021 (regexp :tag "Tags matched by regexp")))
3023 (defcustom org-tags-exclude-from-inheritance nil
3024 "List of tags that should never be inherited.
3025 This is a way to exclude a few tags from inheritance. For way to do
3026 the opposite, to actively allow inheritance for selected tags,
3027 see the variable `org-use-tag-inheritance'."
3028 :group 'org-tags
3029 :type '(repeat (string :tag "Tag")))
3031 (defun org-tag-inherit-p (tag)
3032 "Check if TAG is one that should be inherited."
3033 (cond
3034 ((member tag org-tags-exclude-from-inheritance) nil)
3035 ((eq org-use-tag-inheritance t) t)
3036 ((not org-use-tag-inheritance) nil)
3037 ((stringp org-use-tag-inheritance)
3038 (string-match org-use-tag-inheritance tag))
3039 ((listp org-use-tag-inheritance)
3040 (member tag org-use-tag-inheritance))
3041 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3043 (defcustom org-tags-match-list-sublevels t
3044 "Non-nil means list also sublevels of headlines matching a search.
3045 This variable applies to tags/property searches, and also to stuck
3046 projects because this search is based on a tags match as well.
3048 When set to the symbol `indented', sublevels are indented with
3049 leading dots.
3051 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3052 the sublevels of a headline matching a tag search often also match
3053 the same search. Listing all of them can create very long lists.
3054 Setting this variable to nil causes subtrees of a match to be skipped.
3056 This variable is semi-obsolete and probably should always be true. It
3057 is better to limit inheritance to certain tags using the variables
3058 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3059 :group 'org-tags
3060 :type '(choice
3061 (const :tag "No, don't list them" nil)
3062 (const :tag "Yes, do list them" t)
3063 (const :tag "List them, indented with leading dots" indented)))
3065 (defcustom org-tags-sort-function nil
3066 "When set, tags are sorted using this function as a comparator."
3067 :group 'org-tags
3068 :type '(choice
3069 (const :tag "No sorting" nil)
3070 (const :tag "Alphabetical" string<)
3071 (const :tag "Reverse alphabetical" string>)
3072 (function :tag "Custom function" nil)))
3074 (defvar org-tags-history nil
3075 "History of minibuffer reads for tags.")
3076 (defvar org-last-tags-completion-table nil
3077 "The last used completion table for tags.")
3078 (defvar org-after-tags-change-hook nil
3079 "Hook that is run after the tags in a line have changed.")
3081 (defgroup org-properties nil
3082 "Options concerning properties in Org-mode."
3083 :tag "Org Properties"
3084 :group 'org)
3086 (defcustom org-property-format "%-10s %s"
3087 "How property key/value pairs should be formatted by `indent-line'.
3088 When `indent-line' hits a property definition, it will format the line
3089 according to this format, mainly to make sure that the values are
3090 lined-up with respect to each other."
3091 :group 'org-properties
3092 :type 'string)
3094 (defcustom org-properties-postprocess-alist nil
3095 "Alist of properties and functions to adjust inserted values.
3096 Elements of this alist must be of the form
3098 ([string] [function])
3100 where [string] must be a property name and [function] must be a
3101 lambda expression: this lambda expression must take one argument,
3102 the value to adjust, and return the new value as a string.
3104 For example, this element will allow the property \"Remaining\"
3105 to be updated wrt the relation between the \"Effort\" property
3106 and the clock summary:
3108 ((\"Remaining\" (lambda(value)
3109 (let ((clocksum (org-clock-sum-current-item))
3110 (effort (org-duration-string-to-minutes
3111 (org-entry-get (point) \"Effort\"))))
3112 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3113 :group 'org-properties
3114 :version "24.1"
3115 :type '(alist :key-type (string :tag "Property")
3116 :value-type (function :tag "Function")))
3118 (defcustom org-use-property-inheritance nil
3119 "Non-nil means properties apply also for sublevels.
3121 This setting is chiefly used during property searches. Turning it on can
3122 cause significant overhead when doing a search, which is why it is not
3123 on by default.
3125 When nil, only the properties directly given in the current entry count.
3126 When t, every property is inherited. The value may also be a list of
3127 properties that should have inheritance, or a regular expression matching
3128 properties that should be inherited.
3130 However, note that some special properties use inheritance under special
3131 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3132 and the properties ending in \"_ALL\" when they are used as descriptor
3133 for valid values of a property.
3135 Note for programmers:
3136 When querying an entry with `org-entry-get', you can control if inheritance
3137 should be used. By default, `org-entry-get' looks only at the local
3138 properties. You can request inheritance by setting the inherit argument
3139 to t (to force inheritance) or to `selective' (to respect the setting
3140 in this variable)."
3141 :group 'org-properties
3142 :type '(choice
3143 (const :tag "Not" nil)
3144 (const :tag "Always" t)
3145 (repeat :tag "Specific properties" (string :tag "Property"))
3146 (regexp :tag "Properties matched by regexp")))
3148 (defun org-property-inherit-p (property)
3149 "Check if PROPERTY is one that should be inherited."
3150 (cond
3151 ((eq org-use-property-inheritance t) t)
3152 ((not org-use-property-inheritance) nil)
3153 ((stringp org-use-property-inheritance)
3154 (string-match org-use-property-inheritance property))
3155 ((listp org-use-property-inheritance)
3156 (member property org-use-property-inheritance))
3157 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3159 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3160 "The default column format, if no other format has been defined.
3161 This variable can be set on the per-file basis by inserting a line
3163 #+COLUMNS: %25ITEM ....."
3164 :group 'org-properties
3165 :type 'string)
3167 (defcustom org-columns-ellipses ".."
3168 "The ellipses to be used when a field in column view is truncated.
3169 When this is the empty string, as many characters as possible are shown,
3170 but then there will be no visual indication that the field has been truncated.
3171 When this is a string of length N, the last N characters of a truncated
3172 field are replaced by this string. If the column is narrower than the
3173 ellipses string, only part of the ellipses string will be shown."
3174 :group 'org-properties
3175 :type 'string)
3177 (defcustom org-columns-modify-value-for-display-function nil
3178 "Function that modifies values for display in column view.
3179 For example, it can be used to cut out a certain part from a time stamp.
3180 The function must take 2 arguments:
3182 column-title The title of the column (*not* the property name)
3183 value The value that should be modified.
3185 The function should return the value that should be displayed,
3186 or nil if the normal value should be used."
3187 :group 'org-properties
3188 :type 'function)
3190 (defcustom org-effort-property "Effort"
3191 "The property that is being used to keep track of effort estimates.
3192 Effort estimates given in this property need to have the format H:MM."
3193 :group 'org-properties
3194 :group 'org-progress
3195 :type '(string :tag "Property"))
3197 (defconst org-global-properties-fixed
3198 '(("VISIBILITY_ALL" . "folded children content all")
3199 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3200 "List of property/value pairs that can be inherited by any entry.
3202 These are fixed values, for the preset properties. The user variable
3203 that can be used to add to this list is `org-global-properties'.
3205 The entries in this list are cons cells where the car is a property
3206 name and cdr is a string with the value. If the value represents
3207 multiple items like an \"_ALL\" property, separate the items by
3208 spaces.")
3210 (defcustom org-global-properties nil
3211 "List of property/value pairs that can be inherited by any entry.
3213 This list will be combined with the constant `org-global-properties-fixed'.
3215 The entries in this list are cons cells where the car is a property
3216 name and cdr is a string with the value.
3218 You can set buffer-local values for the same purpose in the variable
3219 `org-file-properties' this by adding lines like
3221 #+PROPERTY: NAME VALUE"
3222 :group 'org-properties
3223 :type '(repeat
3224 (cons (string :tag "Property")
3225 (string :tag "Value"))))
3227 (defvar org-file-properties nil
3228 "List of property/value pairs that can be inherited by any entry.
3229 Valid for the current buffer.
3230 This variable is populated from #+PROPERTY lines.")
3231 (make-variable-buffer-local 'org-file-properties)
3233 (defgroup org-agenda nil
3234 "Options concerning agenda views in Org-mode."
3235 :tag "Org Agenda"
3236 :group 'org)
3238 (defvar org-category nil
3239 "Variable used by org files to set a category for agenda display.
3240 Such files should use a file variable to set it, for example
3242 # -*- mode: org; org-category: \"ELisp\"
3244 or contain a special line
3246 #+CATEGORY: ELisp
3248 If the file does not specify a category, then file's base name
3249 is used instead.")
3250 (make-variable-buffer-local 'org-category)
3251 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3253 (defcustom org-agenda-files nil
3254 "The files to be used for agenda display.
3255 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3256 \\[org-remove-file]. You can also use customize to edit the list.
3258 If an entry is a directory, all files in that directory that are matched by
3259 `org-agenda-file-regexp' will be part of the file list.
3261 If the value of the variable is not a list but a single file name, then
3262 the list of agenda files is actually stored and maintained in that file, one
3263 agenda file per line. In this file paths can be given relative to
3264 `org-directory'. Tilde expansion and environment variable substitution
3265 are also made."
3266 :group 'org-agenda
3267 :type '(choice
3268 (repeat :tag "List of files and directories" file)
3269 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3271 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3272 "Regular expression to match files for `org-agenda-files'.
3273 If any element in the list in that variable contains a directory instead
3274 of a normal file, all files in that directory that are matched by this
3275 regular expression will be included."
3276 :group 'org-agenda
3277 :type 'regexp)
3279 (defcustom org-agenda-text-search-extra-files nil
3280 "List of extra files to be searched by text search commands.
3281 These files will be search in addition to the agenda files by the
3282 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3283 Note that these files will only be searched for text search commands,
3284 not for the other agenda views like todo lists, tag searches or the weekly
3285 agenda. This variable is intended to list notes and possibly archive files
3286 that should also be searched by these two commands.
3287 In fact, if the first element in the list is the symbol `agenda-archives',
3288 than all archive files of all agenda files will be added to the search
3289 scope."
3290 :group 'org-agenda
3291 :type '(set :greedy t
3292 (const :tag "Agenda Archives" agenda-archives)
3293 (repeat :inline t (file))))
3295 (if (fboundp 'defvaralias)
3296 (defvaralias 'org-agenda-multi-occur-extra-files
3297 'org-agenda-text-search-extra-files))
3299 (defcustom org-agenda-skip-unavailable-files nil
3300 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3301 A nil value means to remove them, after a query, from the list."
3302 :group 'org-agenda
3303 :type 'boolean)
3305 (defcustom org-calendar-to-agenda-key [?c]
3306 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3307 The command `org-calendar-goto-agenda' will be bound to this key. The
3308 default is the character `c' because then `c' can be used to switch back and
3309 forth between agenda and calendar."
3310 :group 'org-agenda
3311 :type 'sexp)
3313 (defcustom org-calendar-insert-diary-entry-key [?i]
3314 "The key to be installed in `calendar-mode-map' for adding diary entries.
3315 This option is irrelevant until `org-agenda-diary-file' has been configured
3316 to point to an Org-mode file. When that is the case, the command
3317 `org-agenda-diary-entry' will be bound to the key given here, by default
3318 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3319 if you want to continue doing this, you need to change this to a different
3320 key."
3321 :group 'org-agenda
3322 :type 'sexp)
3324 (defcustom org-agenda-diary-file 'diary-file
3325 "File to which to add new entries with the `i' key in agenda and calendar.
3326 When this is the symbol `diary-file', the functionality in the Emacs
3327 calendar will be used to add entries to the `diary-file'. But when this
3328 points to a file, `org-agenda-diary-entry' will be used instead."
3329 :group 'org-agenda
3330 :type '(choice
3331 (const :tag "The standard Emacs diary file" diary-file)
3332 (file :tag "Special Org file diary entries")))
3334 (eval-after-load "calendar"
3335 '(progn
3336 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3337 'org-calendar-goto-agenda)
3338 (add-hook 'calendar-mode-hook
3339 (lambda ()
3340 (unless (eq org-agenda-diary-file 'diary-file)
3341 (define-key calendar-mode-map
3342 org-calendar-insert-diary-entry-key
3343 'org-agenda-diary-entry))))))
3345 (defgroup org-latex nil
3346 "Options for embedding LaTeX code into Org-mode."
3347 :tag "Org LaTeX"
3348 :group 'org)
3350 (defcustom org-format-latex-options
3351 '(:foreground default :background default :scale 1.0
3352 :html-foreground "Black" :html-background "Transparent"
3353 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3354 "Options for creating images from LaTeX fragments.
3355 This is a property list with the following properties:
3356 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3357 `default' means use the foreground of the default face.
3358 `auto' means use the foreground from the text face.
3359 :background the background color, or \"Transparent\".
3360 `default' means use the background of the default face.
3361 `auto' means use the background from the text face.
3362 :scale a scaling factor for the size of the images, to get more pixels
3363 :html-foreground, :html-background, :html-scale
3364 the same numbers for HTML export.
3365 :matchers a list indicating which matchers should be used to
3366 find LaTeX fragments. Valid members of this list are:
3367 \"begin\" find environments
3368 \"$1\" find single characters surrounded by $.$
3369 \"$\" find math expressions surrounded by $...$
3370 \"$$\" find math expressions surrounded by $$....$$
3371 \"\\(\" find math expressions surrounded by \\(...\\)
3372 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3373 :group 'org-latex
3374 :type 'plist)
3376 (defcustom org-format-latex-signal-error t
3377 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3378 When nil, just push out a message."
3379 :group 'org-latex
3380 :version "24.1"
3381 :type 'boolean)
3383 (defcustom org-latex-to-mathml-jar-file nil
3384 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3385 Use this to specify additional executable file say a jar file.
3387 When using MathToWeb as the converter, specify the full-path to
3388 your mathtoweb.jar file."
3389 :group 'org-latex
3390 :version "24.1"
3391 :type '(choice
3392 (const :tag "None" nil)
3393 (file :tag "JAR file" :must-match t)))
3395 (defcustom org-latex-to-mathml-convert-command nil
3396 "Command to convert LaTeX fragments to MathML.
3397 Replace format-specifiers in the command as noted below and use
3398 `shell-command' to convert LaTeX to MathML.
3399 %j: Executable file in fully expanded form as specified by
3400 `org-latex-to-mathml-jar-file'.
3401 %I: Input LaTeX file in fully expanded form
3402 %o: Output MathML file
3403 This command is used by `org-create-math-formula'.
3405 When using MathToWeb as the converter, set this to
3406 \"java -jar %j -unicode -force -df %o %I\"."
3407 :group 'org-latex
3408 :version "24.1"
3409 :type '(choice
3410 (const :tag "None" nil)
3411 (string :tag "\nShell command")))
3413 (defcustom org-latex-create-formula-image-program 'dvipng
3414 "Program to convert LaTeX fragments with.
3416 dvipng Process the LaTeX fragments to dvi file, then convert
3417 dvi files to png files using dvipng.
3418 This will also include processing of non-math environments.
3419 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3420 to convert pdf files to png files"
3421 :group 'org-latex
3422 :version "24.1"
3423 :type '(choice
3424 (const :tag "dvipng" dvipng)
3425 (const :tag "imagemagick" imagemagick)))
3427 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3428 "Path to store latex preview images. A relative path here creates many
3429 directories relative to the processed org files paths. An absolute path
3430 puts all preview images at the same place."
3431 :group 'org-latex
3432 :version "24.3"
3433 :type 'string)
3435 (defun org-format-latex-mathml-available-p ()
3436 "Return t if `org-latex-to-mathml-convert-command' is usable."
3437 (save-match-data
3438 (when (and (boundp 'org-latex-to-mathml-convert-command)
3439 org-latex-to-mathml-convert-command)
3440 (let ((executable (car (split-string
3441 org-latex-to-mathml-convert-command))))
3442 (when (executable-find executable)
3443 (if (string-match
3444 "%j" org-latex-to-mathml-convert-command)
3445 (file-readable-p org-latex-to-mathml-jar-file)
3446 t))))))
3448 (defcustom org-format-latex-header "\\documentclass{article}
3449 \\usepackage[usenames]{color}
3450 \\usepackage{amsmath}
3451 \\usepackage[mathscr]{eucal}
3452 \\pagestyle{empty} % do not remove
3453 \[PACKAGES]
3454 \[DEFAULT-PACKAGES]
3455 % The settings below are copied from fullpage.sty
3456 \\setlength{\\textwidth}{\\paperwidth}
3457 \\addtolength{\\textwidth}{-3cm}
3458 \\setlength{\\oddsidemargin}{1.5cm}
3459 \\addtolength{\\oddsidemargin}{-2.54cm}
3460 \\setlength{\\evensidemargin}{\\oddsidemargin}
3461 \\setlength{\\textheight}{\\paperheight}
3462 \\addtolength{\\textheight}{-\\headheight}
3463 \\addtolength{\\textheight}{-\\headsep}
3464 \\addtolength{\\textheight}{-\\footskip}
3465 \\addtolength{\\textheight}{-3cm}
3466 \\setlength{\\topmargin}{1.5cm}
3467 \\addtolength{\\topmargin}{-2.54cm}"
3468 "The document header used for processing LaTeX fragments.
3469 It is imperative that this header make sure that no page number
3470 appears on the page. The package defined in the variables
3471 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3472 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3473 will be appended."
3474 :group 'org-latex
3475 :type 'string)
3477 (defvar org-format-latex-header-extra nil)
3479 (defun org-set-packages-alist (var val)
3480 "Set the packages alist and make sure it has 3 elements per entry."
3481 (set var (mapcar (lambda (x)
3482 (if (and (consp x) (= (length x) 2))
3483 (list (car x) (nth 1 x) t)
3485 val)))
3487 (defun org-get-packages-alist (var)
3489 "Get the packages alist and make sure it has 3 elements per entry."
3490 (mapcar (lambda (x)
3491 (if (and (consp x) (= (length x) 2))
3492 (list (car x) (nth 1 x) t)
3494 (default-value var)))
3496 ;; The following variables are defined here because is it also used
3497 ;; when formatting latex fragments. Originally it was part of the
3498 ;; LaTeX exporter, which is why the name includes "export".
3499 (defcustom org-export-latex-default-packages-alist
3500 '(("AUTO" "inputenc" t)
3501 ("T1" "fontenc" t)
3502 ("" "fixltx2e" nil)
3503 ("" "graphicx" t)
3504 ("" "longtable" nil)
3505 ("" "float" nil)
3506 ("" "wrapfig" nil)
3507 ("" "soul" t)
3508 ("" "textcomp" t)
3509 ("" "marvosym" t)
3510 ("" "wasysym" t)
3511 ("" "latexsym" t)
3512 ("" "amssymb" t)
3513 ("" "hyperref" nil)
3514 "\\tolerance=1000"
3516 "Alist of default packages to be inserted in the header.
3517 Change this only if one of the packages here causes an incompatibility
3518 with another package you are using.
3519 The packages in this list are needed by one part or another of Org-mode
3520 to function properly.
3522 - inputenc, fontenc: for basic font and character selection
3523 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3524 for interpreting the entities in `org-entities'. You can skip some of these
3525 packages if you don't use any of the symbols in it.
3526 - graphicx: for including images
3527 - float, wrapfig: for figure placement
3528 - longtable: for long tables
3529 - hyperref: for cross references
3531 Therefore you should not modify this variable unless you know what you
3532 are doing. The one reason to change it anyway is that you might be loading
3533 some other package that conflicts with one of the default packages.
3534 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3535 If SNIPPET-FLAG is t, the package also needs to be included when
3536 compiling LaTeX snippets into images for inclusion into HTML."
3537 :group 'org-export-latex
3538 :set 'org-set-packages-alist
3539 :get 'org-get-packages-alist
3540 :version "24.1"
3541 :type '(repeat
3542 (choice
3543 (list :tag "options/package pair"
3544 (string :tag "options")
3545 (string :tag "package")
3546 (boolean :tag "Snippet"))
3547 (string :tag "A line of LaTeX"))))
3549 (defcustom org-export-latex-packages-alist nil
3550 "Alist of packages to be inserted in every LaTeX header.
3551 These will be inserted after `org-export-latex-default-packages-alist'.
3552 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3553 SNIPPET-FLAG, when t, indicates that this package is also needed when
3554 turning LaTeX snippets into images for inclusion into HTML.
3555 Make sure that you only list packages here which:
3556 - you want in every file
3557 - do not conflict with the default packages in
3558 `org-export-latex-default-packages-alist'
3559 - do not conflict with the setup in `org-format-latex-header'."
3560 :group 'org-export-latex
3561 :set 'org-set-packages-alist
3562 :get 'org-get-packages-alist
3563 :type '(repeat
3564 (choice
3565 (list :tag "options/package pair"
3566 (string :tag "options")
3567 (string :tag "package")
3568 (boolean :tag "Snippet"))
3569 (string :tag "A line of LaTeX"))))
3572 (defgroup org-appearance nil
3573 "Settings for Org-mode appearance."
3574 :tag "Org Appearance"
3575 :group 'org)
3577 (defcustom org-level-color-stars-only nil
3578 "Non-nil means fontify only the stars in each headline.
3579 When nil, the entire headline is fontified.
3580 Changing it requires restart of `font-lock-mode' to become effective
3581 also in regions already fontified."
3582 :group 'org-appearance
3583 :type 'boolean)
3585 (defcustom org-hide-leading-stars nil
3586 "Non-nil means hide the first N-1 stars in a headline.
3587 This works by using the face `org-hide' for these stars. This
3588 face is white for a light background, and black for a dark
3589 background. You may have to customize the face `org-hide' to
3590 make this work.
3591 Changing it requires restart of `font-lock-mode' to become effective
3592 also in regions already fontified.
3593 You may also set this on a per-file basis by adding one of the following
3594 lines to the buffer:
3596 #+STARTUP: hidestars
3597 #+STARTUP: showstars"
3598 :group 'org-appearance
3599 :type 'boolean)
3601 (defcustom org-hidden-keywords nil
3602 "List of symbols corresponding to keywords to be hidden the org buffer.
3603 For example, a value '(title) for this list will make the document's title
3604 appear in the buffer without the initial #+TITLE: keyword."
3605 :group 'org-appearance
3606 :version "24.1"
3607 :type '(set (const :tag "#+AUTHOR" author)
3608 (const :tag "#+DATE" date)
3609 (const :tag "#+EMAIL" email)
3610 (const :tag "#+TITLE" title)))
3612 (defcustom org-custom-properties nil
3613 "List of properties (as strings) with a special meaning.
3614 The default use of these custom properties is to let the user
3615 hide them with `org-toggle-custom-properties-visibility'."
3616 :group 'org-properties
3617 :group 'org-appearance
3618 :version "24.3"
3619 :type '(repeat (string :tag "Property Name")))
3621 (defcustom org-fontify-done-headline nil
3622 "Non-nil means change the face of a headline if it is marked DONE.
3623 Normally, only the TODO/DONE keyword indicates the state of a headline.
3624 When this is non-nil, the headline after the keyword is set to the
3625 `org-headline-done' as an additional indication."
3626 :group 'org-appearance
3627 :type 'boolean)
3629 (defcustom org-fontify-emphasized-text t
3630 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3631 Changing this variable requires a restart of Emacs to take effect."
3632 :group 'org-appearance
3633 :type 'boolean)
3635 (defcustom org-fontify-whole-heading-line nil
3636 "Non-nil means fontify the whole line for headings.
3637 This is useful when setting a background color for the
3638 org-level-* faces."
3639 :group 'org-appearance
3640 :type 'boolean)
3642 (defcustom org-highlight-latex-fragments-and-specials nil
3643 "Non-nil means fontify what is treated specially by the exporters."
3644 :group 'org-appearance
3645 :type 'boolean)
3647 (defcustom org-hide-emphasis-markers nil
3648 "Non-nil mean font-lock should hide the emphasis marker characters."
3649 :group 'org-appearance
3650 :type 'boolean)
3652 (defcustom org-pretty-entities nil
3653 "Non-nil means show entities as UTF8 characters.
3654 When nil, the \\name form remains in the buffer."
3655 :group 'org-appearance
3656 :version "24.1"
3657 :type 'boolean)
3659 (defcustom org-pretty-entities-include-sub-superscripts t
3660 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3661 :group 'org-appearance
3662 :version "24.1"
3663 :type 'boolean)
3665 (defvar org-emph-re nil
3666 "Regular expression for matching emphasis.
3667 After a match, the match groups contain these elements:
3668 0 The match of the full regular expression, including the characters
3669 before and after the proper match
3670 1 The character before the proper match, or empty at beginning of line
3671 2 The proper match, including the leading and trailing markers
3672 3 The leading marker like * or /, indicating the type of highlighting
3673 4 The text between the emphasis markers, not including the markers
3674 5 The character after the match, empty at the end of a line")
3675 (defvar org-verbatim-re nil
3676 "Regular expression for matching verbatim text.")
3677 (defvar org-emphasis-regexp-components) ; defined just below
3678 (defvar org-emphasis-alist) ; defined just below
3679 (defun org-set-emph-re (var val)
3680 "Set variable and compute the emphasis regular expression."
3681 (set var val)
3682 (when (and (boundp 'org-emphasis-alist)
3683 (boundp 'org-emphasis-regexp-components)
3684 org-emphasis-alist org-emphasis-regexp-components)
3685 (let* ((e org-emphasis-regexp-components)
3686 (pre (car e))
3687 (post (nth 1 e))
3688 (border (nth 2 e))
3689 (body (nth 3 e))
3690 (nl (nth 4 e))
3691 (body1 (concat body "*?"))
3692 (markers (mapconcat 'car org-emphasis-alist ""))
3693 (vmarkers (mapconcat
3694 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3695 org-emphasis-alist "")))
3696 ;; make sure special characters appear at the right position in the class
3697 (if (string-match "\\^" markers)
3698 (setq markers (concat (replace-match "" t t markers) "^")))
3699 (if (string-match "-" markers)
3700 (setq markers (concat (replace-match "" t t markers) "-")))
3701 (if (string-match "\\^" vmarkers)
3702 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3703 (if (string-match "-" vmarkers)
3704 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3705 (if (> nl 0)
3706 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3707 (int-to-string nl) "\\}")))
3708 ;; Make the regexp
3709 (setq org-emph-re
3710 (concat "\\([" pre "]\\|^\\)"
3711 "\\("
3712 "\\([" markers "]\\)"
3713 "\\("
3714 "[^" border "]\\|"
3715 "[^" border "]"
3716 body1
3717 "[^" border "]"
3718 "\\)"
3719 "\\3\\)"
3720 "\\([" post "]\\|$\\)"))
3721 (setq org-verbatim-re
3722 (concat "\\([" pre "]\\|^\\)"
3723 "\\("
3724 "\\([" vmarkers "]\\)"
3725 "\\("
3726 "[^" border "]\\|"
3727 "[^" border "]"
3728 body1
3729 "[^" border "]"
3730 "\\)"
3731 "\\3\\)"
3732 "\\([" post "]\\|$\\)")))))
3734 (defcustom org-emphasis-regexp-components
3735 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3736 "Components used to build the regular expression for emphasis.
3737 This is a list with five entries. Terminology: In an emphasis string
3738 like \" *strong word* \", we call the initial space PREMATCH, the final
3739 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3740 and \"trong wor\" is the body. The different components in this variable
3741 specify what is allowed/forbidden in each part:
3743 pre Chars allowed as prematch. Beginning of line will be allowed too.
3744 post Chars allowed as postmatch. End of line will be allowed too.
3745 border The chars *forbidden* as border characters.
3746 body-regexp A regexp like \".\" to match a body character. Don't use
3747 non-shy groups here, and don't allow newline here.
3748 newline The maximum number of newlines allowed in an emphasis exp.
3750 Use customize to modify this, or restart Emacs after changing it."
3751 :group 'org-appearance
3752 :set 'org-set-emph-re
3753 :type '(list
3754 (sexp :tag "Allowed chars in pre ")
3755 (sexp :tag "Allowed chars in post ")
3756 (sexp :tag "Forbidden chars in border ")
3757 (sexp :tag "Regexp for body ")
3758 (integer :tag "number of newlines allowed")
3759 (option (boolean :tag "Please ignore this button"))))
3761 (defcustom org-emphasis-alist
3762 `(("*" bold "<b>" "</b>")
3763 ("/" italic "<i>" "</i>")
3764 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3765 ("=" org-code "<code>" "</code>" verbatim)
3766 ("~" org-verbatim "<code>" "</code>" verbatim)
3767 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3768 "<del>" "</del>")
3770 "Special syntax for emphasized text.
3771 Text starting and ending with a special character will be emphasized, for
3772 example *bold*, _underlined_ and /italic/. This variable sets the marker
3773 characters, the face to be used by font-lock for highlighting in Org-mode
3774 Emacs buffers, and the HTML tags to be used for this.
3775 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3776 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3777 Use customize to modify this, or restart Emacs after changing it."
3778 :group 'org-appearance
3779 :set 'org-set-emph-re
3780 :type '(repeat
3781 (list
3782 (string :tag "Marker character")
3783 (choice
3784 (face :tag "Font-lock-face")
3785 (plist :tag "Face property list"))
3786 (string :tag "HTML start tag")
3787 (string :tag "HTML end tag")
3788 (option (const verbatim)))))
3790 (defvar org-protecting-blocks
3791 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3792 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3793 This is needed for font-lock setup.")
3795 ;;; Miscellaneous options
3797 (defgroup org-completion nil
3798 "Completion in Org-mode."
3799 :tag "Org Completion"
3800 :group 'org)
3802 (defcustom org-completion-use-ido nil
3803 "Non-nil means use ido completion wherever possible.
3804 Note that `ido-mode' must be active for this variable to be relevant.
3805 If you decide to turn this variable on, you might well want to turn off
3806 `org-outline-path-complete-in-steps'.
3807 See also `org-completion-use-iswitchb'."
3808 :group 'org-completion
3809 :type 'boolean)
3811 (defcustom org-completion-use-iswitchb nil
3812 "Non-nil means use iswitchb completion wherever possible.
3813 Note that `iswitchb-mode' must be active for this variable to be relevant.
3814 If you decide to turn this variable on, you might well want to turn off
3815 `org-outline-path-complete-in-steps'.
3816 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3817 :group 'org-completion
3818 :type 'boolean)
3820 (defcustom org-completion-fallback-command 'hippie-expand
3821 "The expansion command called by \\[pcomplete] in normal context.
3822 Normal means, no org-mode-specific context."
3823 :group 'org-completion
3824 :type 'function)
3826 ;;; Functions and variables from their packages
3827 ;; Declared here to avoid compiler warnings
3829 ;; XEmacs only
3830 (defvar outline-mode-menu-heading)
3831 (defvar outline-mode-menu-show)
3832 (defvar outline-mode-menu-hide)
3833 (defvar zmacs-regions) ; XEmacs regions
3835 ;; Emacs only
3836 (defvar mark-active)
3838 ;; Various packages
3839 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3840 (declare-function calendar-forward-day "cal-move" (arg))
3841 (declare-function calendar-goto-date "cal-move" (date))
3842 (declare-function calendar-goto-today "cal-move" ())
3843 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3844 (defvar calc-embedded-close-formula)
3845 (defvar calc-embedded-open-formula)
3846 (declare-function cdlatex-tab "ext:cdlatex" ())
3847 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3848 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3849 (defvar font-lock-unfontify-region-function)
3850 (declare-function iswitchb-read-buffer "iswitchb"
3851 (prompt &optional default require-match start matches-set))
3852 (defvar iswitchb-temp-buflist)
3853 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3854 (defvar org-agenda-tags-todo-honor-ignore-options)
3855 (declare-function org-agenda-skip "org-agenda" ())
3856 (declare-function
3857 org-agenda-format-item "org-agenda"
3858 (extra txt &optional level category tags dotime noprefix remove-re habitp))
3859 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3860 (declare-function org-agenda-change-all-lines "org-agenda"
3861 (newhead hdmarker &optional fixface just-this))
3862 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3863 (declare-function org-agenda-maybe-redo "org-agenda" ())
3864 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3865 (beg end))
3866 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3867 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3868 "org-agenda" (&optional end))
3869 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3870 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3871 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3872 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3873 (declare-function org-indent-mode "org-indent" (&optional arg))
3874 (declare-function parse-time-string "parse-time" (string))
3875 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3876 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3877 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3878 (defvar remember-data-file)
3879 (defvar texmathp-why)
3880 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3881 (declare-function table--at-cell-p "table" (position &optional object at-column))
3883 (defvar w3m-current-url)
3884 (defvar w3m-current-title)
3886 (defvar org-latex-regexps)
3888 ;;; Autoload and prepare some org modules
3890 ;; Some table stuff that needs to be defined here, because it is used
3891 ;; by the functions setting up org-mode or checking for table context.
3893 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3894 "Detect an org-type or table-type table.")
3895 (defconst org-table-line-regexp "^[ \t]*|"
3896 "Detect an org-type table line.")
3897 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3898 "Detect an org-type table line.")
3899 (defconst org-table-hline-regexp "^[ \t]*|-"
3900 "Detect an org-type table hline.")
3901 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3902 "Detect a table-type table hline.")
3903 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3904 "Detect the first line outside a table when searching from within it.
3905 This works for both table types.")
3907 ;; Autoload the functions in org-table.el that are needed by functions here.
3909 (eval-and-compile
3910 (org-autoload "org-table"
3911 '(org-table-begin org-table-blank-field org-table-end)))
3913 ;;;###autoload
3914 (defun turn-on-orgtbl ()
3915 "Unconditionally turn on `orgtbl-mode'."
3916 (require 'org-table)
3917 (orgtbl-mode 1))
3919 (defun org-at-table-p (&optional table-type)
3920 "Return t if the cursor is inside an org-type table.
3921 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3922 (if org-enable-table-editor
3923 (save-excursion
3924 (beginning-of-line 1)
3925 (looking-at (if table-type org-table-any-line-regexp
3926 org-table-line-regexp)))
3927 nil))
3928 (defsubst org-table-p () (org-at-table-p))
3930 (defun org-at-table.el-p ()
3931 "Return t if and only if we are at a table.el table."
3932 (and (org-at-table-p 'any)
3933 (save-excursion
3934 (goto-char (org-table-begin 'any))
3935 (looking-at org-table1-hline-regexp))))
3936 (defun org-table-recognize-table.el ()
3937 "If there is a table.el table nearby, recognize it and move into it."
3938 (if org-table-tab-recognizes-table.el
3939 (if (org-at-table.el-p)
3940 (progn
3941 (beginning-of-line 1)
3942 (if (looking-at org-table-dataline-regexp)
3944 (if (looking-at org-table1-hline-regexp)
3945 (progn
3946 (beginning-of-line 2)
3947 (if (looking-at org-table-any-border-regexp)
3948 (beginning-of-line -1)))))
3949 (if (re-search-forward "|" (org-table-end t) t)
3950 (progn
3951 (require 'table)
3952 (if (table--at-cell-p (point))
3954 (message "recognizing table.el table...")
3955 (table-recognize-table)
3956 (message "recognizing table.el table...done")))
3957 (error "This should not happen"))
3959 nil)
3960 nil))
3962 (defun org-at-table-hline-p ()
3963 "Return t if the cursor is inside a hline in a table."
3964 (if org-enable-table-editor
3965 (save-excursion
3966 (beginning-of-line 1)
3967 (looking-at org-table-hline-regexp))
3968 nil))
3970 (defvar org-table-clean-did-remove-column nil)
3972 (defun org-table-map-tables (function &optional quietly)
3973 "Apply FUNCTION to the start of all tables in the buffer."
3974 (save-excursion
3975 (save-restriction
3976 (widen)
3977 (goto-char (point-min))
3978 (while (re-search-forward org-table-any-line-regexp nil t)
3979 (unless quietly
3980 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3981 (beginning-of-line 1)
3982 (when (and (looking-at org-table-line-regexp)
3983 ;; Exclude tables in src/example/verbatim/clocktable blocks
3984 (not (org-in-block-p '("src" "example"))))
3985 (save-excursion (funcall function))
3986 (or (looking-at org-table-line-regexp)
3987 (forward-char 1)))
3988 (re-search-forward org-table-any-border-regexp nil 1))))
3989 (unless quietly (message "Mapping tables: done")))
3991 ;; Declare and autoload functions from org-exp.el & Co
3993 (declare-function org-default-export-plist "org-exp")
3994 (declare-function org-infile-export-plist "org-exp")
3995 (declare-function org-get-current-options "org-exp")
3997 ;; Declare and autoload functions from org-agenda.el
3999 (eval-and-compile
4000 (org-autoload "org-agenda"
4001 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4003 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4004 (declare-function org-clock-update-mode-line "org-clock" ())
4005 (declare-function org-resolve-clocks "org-clock"
4006 (&optional also-non-dangling-p prompt last-valid))
4007 (defvar org-clock-start-time)
4008 (defvar org-clock-marker (make-marker)
4009 "Marker recording the last clock-in.")
4010 (defvar org-clock-hd-marker (make-marker)
4011 "Marker recording the last clock-in, but the headline position.")
4012 (defvar org-clock-heading ""
4013 "The heading of the current clock entry.")
4014 (defun org-clock-is-active ()
4015 "Return non-nil if clock is currently running.
4016 The return value is actually the clock marker."
4017 (marker-buffer org-clock-marker))
4019 (eval-and-compile
4020 (org-autoload "org-clock" '(org-clock-remove-overlays
4021 org-clock-update-time-maybe
4022 org-clocktable-shift)))
4024 (defun org-check-running-clock ()
4025 "Check if the current buffer contains the running clock.
4026 If yes, offer to stop it and to save the buffer with the changes."
4027 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4028 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4029 (buffer-name))))
4030 (org-clock-out)
4031 (when (y-or-n-p "Save changed buffer?")
4032 (save-buffer))))
4034 (defun org-clocktable-try-shift (dir n)
4035 "Check if this line starts a clock table, if yes, shift the time block."
4036 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4037 (org-clocktable-shift dir n)))
4039 ;;;###autoload
4040 (defun org-clock-persistence-insinuate ()
4041 "Set up hooks for clock persistence."
4042 (require 'org-clock)
4043 (add-hook 'org-mode-hook 'org-clock-load)
4044 (add-hook 'kill-emacs-hook 'org-clock-save))
4046 ;; Define the variable already here, to make sure we have it.
4047 (defvar org-indent-mode nil
4048 "Non-nil if Org-Indent mode is enabled.
4049 Use the command `org-indent-mode' to change this variable.")
4051 ;; Autoload archiving code
4052 ;; The stuff that is needed for cycling and tags has to be defined here.
4054 (defgroup org-archive nil
4055 "Options concerning archiving in Org-mode."
4056 :tag "Org Archive"
4057 :group 'org-structure)
4059 (defcustom org-archive-location "%s_archive::"
4060 "The location where subtrees should be archived.
4062 The value of this variable is a string, consisting of two parts,
4063 separated by a double-colon. The first part is a filename and
4064 the second part is a headline.
4066 When the filename is omitted, archiving happens in the same file.
4067 %s in the filename will be replaced by the current file
4068 name (without the directory part). Archiving to a different file
4069 is useful to keep archived entries from contributing to the
4070 Org-mode Agenda.
4072 The archived entries will be filed as subtrees of the specified
4073 headline. When the headline is omitted, the subtrees are simply
4074 filed away at the end of the file, as top-level entries. Also in
4075 the heading you can use %s to represent the file name, this can be
4076 useful when using the same archive for a number of different files.
4078 Here are a few examples:
4079 \"%s_archive::\"
4080 If the current file is Projects.org, archive in file
4081 Projects.org_archive, as top-level trees. This is the default.
4083 \"::* Archived Tasks\"
4084 Archive in the current file, under the top-level headline
4085 \"* Archived Tasks\".
4087 \"~/org/archive.org::\"
4088 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4090 \"~/org/archive.org::* From %s\"
4091 Archive in file ~/org/archive.org (absolute path), under headlines
4092 \"From FILENAME\" where file name is the current file name.
4094 \"~/org/datetree.org::datetree/* Finished Tasks\"
4095 The \"datetree/\" string is special, signifying to archive
4096 items to the datetree. Items are placed in either the CLOSED
4097 date of the item, or the current date if there is no CLOSED date.
4098 The heading will be a subentry to the current date. There doesn't
4099 need to be a heading, but there always needs to be a slash after
4100 datetree. For example, to store archived items directly in the
4101 datetree, use \"~/org/datetree.org::datetree/\".
4103 \"basement::** Finished Tasks\"
4104 Archive in file ./basement (relative path), as level 3 trees
4105 below the level 2 heading \"** Finished Tasks\".
4107 You may set this option on a per-file basis by adding to the buffer a
4108 line like
4110 #+ARCHIVE: basement::** Finished Tasks
4112 You may also define it locally for a subtree by setting an ARCHIVE property
4113 in the entry. If such a property is found in an entry, or anywhere up
4114 the hierarchy, it will be used."
4115 :group 'org-archive
4116 :type 'string)
4118 (defcustom org-archive-tag "ARCHIVE"
4119 "The tag that marks a subtree as archived.
4120 An archived subtree does not open during visibility cycling, and does
4121 not contribute to the agenda listings.
4122 After changing this, font-lock must be restarted in the relevant buffers to
4123 get the proper fontification."
4124 :group 'org-archive
4125 :group 'org-keywords
4126 :type 'string)
4128 (defcustom org-agenda-skip-archived-trees t
4129 "Non-nil means the agenda will skip any items located in archived trees.
4130 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4131 variable is no longer recommended, you should leave it at the value t.
4132 Instead, use the key `v' to cycle the archives-mode in the agenda."
4133 :group 'org-archive
4134 :group 'org-agenda-skip
4135 :type 'boolean)
4137 (defcustom org-columns-skip-archived-trees t
4138 "Non-nil means ignore archived trees when creating column view."
4139 :group 'org-archive
4140 :group 'org-properties
4141 :type 'boolean)
4143 (defcustom org-cycle-open-archived-trees nil
4144 "Non-nil means `org-cycle' will open archived trees.
4145 An archived tree is a tree marked with the tag ARCHIVE.
4146 When nil, archived trees will stay folded. You can still open them with
4147 normal outline commands like `show-all', but not with the cycling commands."
4148 :group 'org-archive
4149 :group 'org-cycle
4150 :type 'boolean)
4152 (defcustom org-sparse-tree-open-archived-trees nil
4153 "Non-nil means sparse tree construction shows matches in archived trees.
4154 When nil, matches in these trees are highlighted, but the trees are kept in
4155 collapsed state."
4156 :group 'org-archive
4157 :group 'org-sparse-trees
4158 :type 'boolean)
4160 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4161 "The default date type when building a sparse tree.
4162 When this is nil, a date is a scheduled or a deadline timestamp.
4163 Otherwise, these types are allowed:
4165 all: all timestamps
4166 active: only active timestamps (<...>)
4167 inactive: only inactive timestamps (<...)
4168 scheduled: only scheduled timestamps
4169 deadline: only deadline timestamps"
4170 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4171 (const :tag "All timestamps" all)
4172 (const :tag "Only active timestamps" active)
4173 (const :tag "Only inactive timestamps" inactive)
4174 (const :tag "Only scheduled timestamps" scheduled)
4175 (const :tag "Only deadline timestamps" deadline))
4176 :version "24.3"
4177 :group 'org-sparse-trees)
4179 (defun org-cycle-hide-archived-subtrees (state)
4180 "Re-hide all archived subtrees after a visibility state change."
4181 (when (and (not org-cycle-open-archived-trees)
4182 (not (memq state '(overview folded))))
4183 (save-excursion
4184 (let* ((globalp (memq state '(contents all)))
4185 (beg (if globalp (point-min) (point)))
4186 (end (if globalp (point-max) (org-end-of-subtree t))))
4187 (org-hide-archived-subtrees beg end)
4188 (goto-char beg)
4189 (if (looking-at (concat ".*:" org-archive-tag ":"))
4190 (message "%s" (substitute-command-keys
4191 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4193 (defun org-force-cycle-archived ()
4194 "Cycle subtree even if it is archived."
4195 (interactive)
4196 (setq this-command 'org-cycle)
4197 (let ((org-cycle-open-archived-trees t))
4198 (call-interactively 'org-cycle)))
4200 (defun org-hide-archived-subtrees (beg end)
4201 "Re-hide all archived subtrees after a visibility state change."
4202 (save-excursion
4203 (let* ((re (concat ":" org-archive-tag ":")))
4204 (goto-char beg)
4205 (while (re-search-forward re end t)
4206 (when (org-at-heading-p)
4207 (org-flag-subtree t)
4208 (org-end-of-subtree t))))))
4210 (declare-function outline-end-of-heading "outline" ())
4211 (declare-function outline-flag-region "outline" (from to flag))
4212 (defun org-flag-subtree (flag)
4213 (save-excursion
4214 (org-back-to-heading t)
4215 (outline-end-of-heading)
4216 (outline-flag-region (point)
4217 (progn (org-end-of-subtree t) (point))
4218 flag)))
4220 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4222 (eval-and-compile
4223 (org-autoload "org-archive"
4224 '(org-add-archive-files)))
4226 ;; Autoload Column View Code
4228 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4229 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4230 (declare-function org-columns-compute "org-colview" (property))
4232 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4233 '(org-columns-number-to-string
4234 org-columns-get-format-and-top-level
4235 org-columns-compute
4236 org-columns-remove-overlays))
4238 ;; Autoload ID code
4240 (declare-function org-id-store-link "org-id")
4241 (declare-function org-id-locations-load "org-id")
4242 (declare-function org-id-locations-save "org-id")
4243 (defvar org-id-track-globally)
4244 (org-autoload "org-id"
4245 '(org-id-new
4246 org-id-copy
4247 org-id-get-with-outline-path-completion
4248 org-id-get-with-outline-drilling))
4250 ;;; Variables for pre-computed regular expressions, all buffer local
4252 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4253 "Matches first line of a hidden block.")
4254 (make-variable-buffer-local 'org-drawer-regexp)
4255 (defvar org-todo-regexp nil
4256 "Matches any of the TODO state keywords.")
4257 (make-variable-buffer-local 'org-todo-regexp)
4258 (defvar org-not-done-regexp nil
4259 "Matches any of the TODO state keywords except the last one.")
4260 (make-variable-buffer-local 'org-not-done-regexp)
4261 (defvar org-not-done-heading-regexp nil
4262 "Matches a TODO headline that is not done.")
4263 (make-variable-buffer-local 'org-not-done-regexp)
4264 (defvar org-todo-line-regexp nil
4265 "Matches a headline and puts TODO state into group 2 if present.")
4266 (make-variable-buffer-local 'org-todo-line-regexp)
4267 (defvar org-complex-heading-regexp nil
4268 "Matches a headline and puts everything into groups:
4269 group 1: the stars
4270 group 2: The todo keyword, maybe
4271 group 3: Priority cookie
4272 group 4: True headline
4273 group 5: Tags")
4274 (make-variable-buffer-local 'org-complex-heading-regexp)
4275 (defvar org-complex-heading-regexp-format nil
4276 "Printf format to make regexp to match an exact headline.
4277 This regexp will match the headline of any node which has the
4278 exact headline text that is put into the format, but may have any
4279 TODO state, priority and tags.")
4280 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4281 (defvar org-todo-line-tags-regexp nil
4282 "Matches a headline and puts TODO state into group 2 if present.
4283 Also put tags into group 4 if tags are present.")
4284 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4285 (defvar org-ds-keyword-length 12
4286 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4287 (make-variable-buffer-local 'org-ds-keyword-length)
4288 (defvar org-deadline-regexp nil
4289 "Matches the DEADLINE keyword.")
4290 (make-variable-buffer-local 'org-deadline-regexp)
4291 (defvar org-deadline-time-regexp nil
4292 "Matches the DEADLINE keyword together with a time stamp.")
4293 (make-variable-buffer-local 'org-deadline-time-regexp)
4294 (defvar org-deadline-line-regexp nil
4295 "Matches the DEADLINE keyword and the rest of the line.")
4296 (make-variable-buffer-local 'org-deadline-line-regexp)
4297 (defvar org-scheduled-regexp nil
4298 "Matches the SCHEDULED keyword.")
4299 (make-variable-buffer-local 'org-scheduled-regexp)
4300 (defvar org-scheduled-time-regexp nil
4301 "Matches the SCHEDULED keyword together with a time stamp.")
4302 (make-variable-buffer-local 'org-scheduled-time-regexp)
4303 (defvar org-closed-time-regexp nil
4304 "Matches the CLOSED keyword together with a time stamp.")
4305 (make-variable-buffer-local 'org-closed-time-regexp)
4307 (defvar org-keyword-time-regexp nil
4308 "Matches any of the 4 keywords, together with the time stamp.")
4309 (make-variable-buffer-local 'org-keyword-time-regexp)
4310 (defvar org-keyword-time-not-clock-regexp nil
4311 "Matches any of the 3 keywords, together with the time stamp.")
4312 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4313 (defvar org-maybe-keyword-time-regexp nil
4314 "Matches a timestamp, possibly preceded by a keyword.")
4315 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4316 (defvar org-all-time-keywords nil
4317 "List of time keywords.")
4318 (make-variable-buffer-local 'org-all-time-keywords)
4320 (defconst org-plain-time-of-day-regexp
4321 (concat
4322 "\\(\\<[012]?[0-9]"
4323 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4324 "\\(--?"
4325 "\\(\\<[012]?[0-9]"
4326 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4327 "\\)?")
4328 "Regular expression to match a plain time or time range.
4329 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4330 groups carry important information:
4331 0 the full match
4332 1 the first time, range or not
4333 8 the second time, if it is a range.")
4335 (defconst org-plain-time-extension-regexp
4336 (concat
4337 "\\(\\<[012]?[0-9]"
4338 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4339 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4340 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4341 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4342 groups carry important information:
4343 0 the full match
4344 7 hours of duration
4345 9 minutes of duration")
4347 (defconst org-stamp-time-of-day-regexp
4348 (concat
4349 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4350 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4351 "\\(--?"
4352 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4353 "Regular expression to match a timestamp time or time range.
4354 After a match, the following groups carry important information:
4355 0 the full match
4356 1 date plus weekday, for back referencing to make sure both times are on the same day
4357 2 the first time, range or not
4358 4 the second time, if it is a range.")
4360 (defconst org-startup-options
4361 '(("fold" org-startup-folded t)
4362 ("overview" org-startup-folded t)
4363 ("nofold" org-startup-folded nil)
4364 ("showall" org-startup-folded nil)
4365 ("showeverything" org-startup-folded showeverything)
4366 ("content" org-startup-folded content)
4367 ("indent" org-startup-indented t)
4368 ("noindent" org-startup-indented nil)
4369 ("hidestars" org-hide-leading-stars t)
4370 ("showstars" org-hide-leading-stars nil)
4371 ("odd" org-odd-levels-only t)
4372 ("oddeven" org-odd-levels-only nil)
4373 ("align" org-startup-align-all-tables t)
4374 ("noalign" org-startup-align-all-tables nil)
4375 ("inlineimages" org-startup-with-inline-images t)
4376 ("noinlineimages" org-startup-with-inline-images nil)
4377 ("customtime" org-display-custom-times t)
4378 ("logdone" org-log-done time)
4379 ("lognotedone" org-log-done note)
4380 ("nologdone" org-log-done nil)
4381 ("lognoteclock-out" org-log-note-clock-out t)
4382 ("nolognoteclock-out" org-log-note-clock-out nil)
4383 ("logrepeat" org-log-repeat state)
4384 ("lognoterepeat" org-log-repeat note)
4385 ("nologrepeat" org-log-repeat nil)
4386 ("logreschedule" org-log-reschedule time)
4387 ("lognotereschedule" org-log-reschedule note)
4388 ("nologreschedule" org-log-reschedule nil)
4389 ("logredeadline" org-log-redeadline time)
4390 ("lognoteredeadline" org-log-redeadline note)
4391 ("nologredeadline" org-log-redeadline nil)
4392 ("logrefile" org-log-refile time)
4393 ("lognoterefile" org-log-refile note)
4394 ("nologrefile" org-log-refile nil)
4395 ("fninline" org-footnote-define-inline t)
4396 ("nofninline" org-footnote-define-inline nil)
4397 ("fnlocal" org-footnote-section nil)
4398 ("fnauto" org-footnote-auto-label t)
4399 ("fnprompt" org-footnote-auto-label nil)
4400 ("fnconfirm" org-footnote-auto-label confirm)
4401 ("fnplain" org-footnote-auto-label plain)
4402 ("fnadjust" org-footnote-auto-adjust t)
4403 ("nofnadjust" org-footnote-auto-adjust nil)
4404 ("constcgs" constants-unit-system cgs)
4405 ("constSI" constants-unit-system SI)
4406 ("noptag" org-tag-persistent-alist nil)
4407 ("hideblocks" org-hide-block-startup t)
4408 ("nohideblocks" org-hide-block-startup nil)
4409 ("beamer" org-startup-with-beamer-mode t)
4410 ("entitiespretty" org-pretty-entities t)
4411 ("entitiesplain" org-pretty-entities nil))
4412 "Variable associated with STARTUP options for org-mode.
4413 Each element is a list of three items: the startup options (as written
4414 in the #+STARTUP line), the corresponding variable, and the value to set
4415 this variable to if the option is found. An optional forth element PUSH
4416 means to push this value onto the list in the variable.")
4418 (defun org-update-property-plist (key val props)
4419 "Update PROPS with KEY and VAL."
4420 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4421 (key (if appending (substring key 0 (- (length key) 1)) key))
4422 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4423 (previous (cdr (assoc key props))))
4424 (if appending
4425 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4426 (cons (cons key val) remainder))))
4428 (defconst org-block-regexp
4429 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4430 "Regular expression for hiding blocks.")
4431 (defconst org-heading-keyword-regexp-format
4432 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4433 "Printf format for a regexp matching an headline with some keyword.
4434 This regexp will match the headline of any node which has the
4435 exact keyword that is put into the format. The keyword isn't in
4436 any group by default, but the stars and the body are.")
4437 (defconst org-heading-keyword-maybe-regexp-format
4438 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4439 "Printf format for a regexp matching an headline, possibly with some keyword.
4440 This regexp can match any headline with the specified keyword, or
4441 without a keyword. The keyword isn't in any group by default,
4442 but the stars and the body are.")
4444 (defun org-set-regexps-and-options ()
4445 "Precompute regular expressions for current buffer."
4446 (when (derived-mode-p 'org-mode)
4447 (org-set-local 'org-todo-kwd-alist nil)
4448 (org-set-local 'org-todo-key-alist nil)
4449 (org-set-local 'org-todo-key-trigger nil)
4450 (org-set-local 'org-todo-keywords-1 nil)
4451 (org-set-local 'org-done-keywords nil)
4452 (org-set-local 'org-todo-heads nil)
4453 (org-set-local 'org-todo-sets nil)
4454 (org-set-local 'org-todo-log-states nil)
4455 (org-set-local 'org-file-properties nil)
4456 (org-set-local 'org-file-tags nil)
4457 (let ((re (org-make-options-regexp
4458 '("CATEGORY" "TODO" "COLUMNS"
4459 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4460 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4461 "OPTIONS")
4462 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4463 (splitre "[ \t]+")
4464 (scripts org-use-sub-superscripts)
4465 kwds kws0 kwsa key log value cat arch tags const links hw dws
4466 tail sep kws1 prio props ftags drawers beamer-p
4467 ext-setup-or-nil setup-contents (start 0))
4468 (save-excursion
4469 (save-restriction
4470 (widen)
4471 (goto-char (point-min))
4472 (while (or (and ext-setup-or-nil
4473 (string-match re ext-setup-or-nil start)
4474 (setq start (match-end 0)))
4475 (and (setq ext-setup-or-nil nil start 0)
4476 (re-search-forward re nil t)))
4477 (setq key (upcase (match-string 1 ext-setup-or-nil))
4478 value (org-match-string-no-properties 2 ext-setup-or-nil))
4479 (if (stringp value) (setq value (org-trim value)))
4480 (cond
4481 ((equal key "CATEGORY")
4482 (setq cat value))
4483 ((member key '("SEQ_TODO" "TODO"))
4484 (push (cons 'sequence (org-split-string value splitre)) kwds))
4485 ((equal key "TYP_TODO")
4486 (push (cons 'type (org-split-string value splitre)) kwds))
4487 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4488 ;; general TODO-like setup
4489 (push (cons (intern (downcase (match-string 1 key)))
4490 (org-split-string value splitre)) kwds))
4491 ((equal key "TAGS")
4492 (setq tags (append tags (if tags '("\\n") nil)
4493 (org-split-string value splitre))))
4494 ((equal key "COLUMNS")
4495 (org-set-local 'org-columns-default-format value))
4496 ((equal key "LINK")
4497 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4498 (push (cons (match-string 1 value)
4499 (org-trim (match-string 2 value)))
4500 links)))
4501 ((equal key "PRIORITIES")
4502 (setq prio (org-split-string value " +")))
4503 ((equal key "PROPERTY")
4504 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4505 (setq props (org-update-property-plist (match-string 1 value)
4506 (match-string 2 value)
4507 props))))
4508 ((equal key "FILETAGS")
4509 (when (string-match "\\S-" value)
4510 (setq ftags
4511 (append
4512 ftags
4513 (apply 'append
4514 (mapcar (lambda (x) (org-split-string x ":"))
4515 (org-split-string value)))))))
4516 ((equal key "DRAWERS")
4517 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4518 ((equal key "CONSTANTS")
4519 (setq const (append const (org-split-string value splitre))))
4520 ((equal key "STARTUP")
4521 (let ((opts (org-split-string value splitre))
4522 l var val)
4523 (while (setq l (pop opts))
4524 (when (setq l (assoc l org-startup-options))
4525 (setq var (nth 1 l) val (nth 2 l))
4526 (if (not (nth 3 l))
4527 (set (make-local-variable var) val)
4528 (if (not (listp (symbol-value var)))
4529 (set (make-local-variable var) nil))
4530 (set (make-local-variable var) (symbol-value var))
4531 (add-to-list var val))))))
4532 ((equal key "ARCHIVE")
4533 (setq arch value)
4534 (remove-text-properties 0 (length arch)
4535 '(face t fontified t) arch))
4536 ((equal key "LATEX_CLASS")
4537 (setq beamer-p (equal value "beamer")))
4538 ((equal key "OPTIONS")
4539 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4540 (setq scripts (read (match-string 2 value)))))
4541 ((equal key "SETUPFILE")
4542 (setq setup-contents (org-file-contents
4543 (expand-file-name
4544 (org-remove-double-quotes value))
4545 'noerror))
4546 (if (not ext-setup-or-nil)
4547 (setq ext-setup-or-nil setup-contents start 0)
4548 (setq ext-setup-or-nil
4549 (concat (substring ext-setup-or-nil 0 start)
4550 "\n" setup-contents "\n"
4551 (substring ext-setup-or-nil start)))))))
4552 ;; search for property blocks
4553 (goto-char (point-min))
4554 (while (re-search-forward org-block-regexp nil t)
4555 (when (equal "PROPERTY" (upcase (match-string 1)))
4556 (setq value (replace-regexp-in-string
4557 "[\n\r]" " " (match-string 4)))
4558 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4559 (setq props (org-update-property-plist (match-string 1 value)
4560 (match-string 2 value)
4561 props)))))))
4562 (org-set-local 'org-use-sub-superscripts scripts)
4563 (when cat
4564 (org-set-local 'org-category (intern cat))
4565 (push (cons "CATEGORY" cat) props))
4566 (when prio
4567 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4568 (setq prio (mapcar 'string-to-char prio))
4569 (org-set-local 'org-highest-priority (nth 0 prio))
4570 (org-set-local 'org-lowest-priority (nth 1 prio))
4571 (org-set-local 'org-default-priority (nth 2 prio)))
4572 (and props (org-set-local 'org-file-properties (nreverse props)))
4573 (and ftags (org-set-local 'org-file-tags
4574 (mapcar 'org-add-prop-inherited ftags)))
4575 (and drawers (org-set-local 'org-drawers drawers))
4576 (and arch (org-set-local 'org-archive-location arch))
4577 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4578 ;; Process the TODO keywords
4579 (unless kwds
4580 ;; Use the global values as if they had been given locally.
4581 (setq kwds (default-value 'org-todo-keywords))
4582 (if (stringp (car kwds))
4583 (setq kwds (list (cons org-todo-interpretation
4584 (default-value 'org-todo-keywords)))))
4585 (setq kwds (reverse kwds)))
4586 (setq kwds (nreverse kwds))
4587 (let (inter kws kw)
4588 (while (setq kws (pop kwds))
4589 (let ((kws (or
4590 (run-hook-with-args-until-success
4591 'org-todo-setup-filter-hook kws)
4592 kws)))
4593 (setq inter (pop kws) sep (member "|" kws)
4594 kws0 (delete "|" (copy-sequence kws))
4595 kwsa nil
4596 kws1 (mapcar
4597 (lambda (x)
4598 ;; 1 2
4599 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4600 (progn
4601 (setq kw (match-string 1 x)
4602 key (and (match-end 2) (match-string 2 x))
4603 log (org-extract-log-state-settings x))
4604 (push (cons kw (and key (string-to-char key))) kwsa)
4605 (and log (push log org-todo-log-states))
4607 (error "Invalid TODO keyword %s" x)))
4608 kws0)
4609 kwsa (if kwsa (append '((:startgroup))
4610 (nreverse kwsa)
4611 '((:endgroup))))
4612 hw (car kws1)
4613 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4614 tail (list inter hw (car dws) (org-last dws))))
4615 (add-to-list 'org-todo-heads hw 'append)
4616 (push kws1 org-todo-sets)
4617 (setq org-done-keywords (append org-done-keywords dws nil))
4618 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4619 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4620 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4621 (setq org-todo-sets (nreverse org-todo-sets)
4622 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4623 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4624 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4625 ;; Process the constants
4626 (when const
4627 (let (e cst)
4628 (while (setq e (pop const))
4629 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4630 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4631 (setq org-table-formula-constants-local cst)))
4633 ;; Process the tags.
4634 (when tags
4635 (let (e tgs)
4636 (while (setq e (pop tags))
4637 (cond
4638 ((equal e "{") (push '(:startgroup) tgs))
4639 ((equal e "}") (push '(:endgroup) tgs))
4640 ((equal e "\\n") (push '(:newline) tgs))
4641 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4642 (push (cons (match-string 1 e)
4643 (string-to-char (match-string 2 e)))
4644 tgs))
4645 (t (push (list e) tgs))))
4646 (org-set-local 'org-tag-alist nil)
4647 (while (setq e (pop tgs))
4648 (or (and (stringp (car e))
4649 (assoc (car e) org-tag-alist))
4650 (push e org-tag-alist)))))
4652 ;; Compute the regular expressions and other local variables.
4653 ;; Using `org-outline-regexp-bol' would complicate them much,
4654 ;; because of the fixed white space at the end of that string.
4655 (if (not org-done-keywords)
4656 (setq org-done-keywords (and org-todo-keywords-1
4657 (list (org-last org-todo-keywords-1)))))
4658 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4659 (length org-scheduled-string)
4660 (length org-clock-string)
4661 (length org-closed-string)))
4662 org-drawer-regexp
4663 (concat "^[ \t]*:\\("
4664 (mapconcat 'regexp-quote org-drawers "\\|")
4665 "\\):[ \t]*$")
4666 org-not-done-keywords
4667 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4668 org-todo-regexp
4669 (concat "\\("
4670 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4671 "\\)")
4672 org-not-done-regexp
4673 (concat "\\("
4674 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4675 "\\)")
4676 org-not-done-heading-regexp
4677 (format org-heading-keyword-regexp-format org-not-done-regexp)
4678 org-todo-line-regexp
4679 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4680 org-complex-heading-regexp
4681 (concat "^\\(\\*+\\)"
4682 "\\(?: +" org-todo-regexp "\\)?"
4683 "\\(?: +\\(\\[#.\\]\\)\\)?"
4684 "\\(?: +\\(.*?\\)\\)??"
4685 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4686 "[ \t]*$")
4687 org-complex-heading-regexp-format
4688 (concat "^\\(\\*+\\)"
4689 "\\(?: +" org-todo-regexp "\\)?"
4690 "\\(?: +\\(\\[#.\\]\\)\\)?"
4691 "\\(?: +"
4692 ;; Stats cookies can be stuck to body.
4693 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4694 "\\(%s\\)"
4695 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4696 "\\)"
4697 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4698 "[ \t]*$")
4699 org-todo-line-tags-regexp
4700 (concat "^\\(\\*+\\)"
4701 "\\(?: +" org-todo-regexp "\\)?"
4702 "\\(?: +\\(.*?\\)\\)??"
4703 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4704 "[ \t]*$")
4705 org-deadline-regexp (concat "\\<" org-deadline-string)
4706 org-deadline-time-regexp
4707 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4708 org-deadline-line-regexp
4709 (concat "\\<\\(" org-deadline-string "\\).*")
4710 org-scheduled-regexp
4711 (concat "\\<" org-scheduled-string)
4712 org-scheduled-time-regexp
4713 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4714 org-closed-time-regexp
4715 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4716 org-keyword-time-regexp
4717 (concat "\\<\\(" org-scheduled-string
4718 "\\|" org-deadline-string
4719 "\\|" org-closed-string
4720 "\\|" org-clock-string "\\)"
4721 " *[[<]\\([^]>]+\\)[]>]")
4722 org-keyword-time-not-clock-regexp
4723 (concat "\\<\\(" org-scheduled-string
4724 "\\|" org-deadline-string
4725 "\\|" org-closed-string
4726 "\\)"
4727 " *[[<]\\([^]>]+\\)[]>]")
4728 org-maybe-keyword-time-regexp
4729 (concat "\\(\\<\\(" org-scheduled-string
4730 "\\|" org-deadline-string
4731 "\\|" org-closed-string
4732 "\\|" org-clock-string "\\)\\)?"
4733 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4734 org-all-time-keywords
4735 (mapcar (lambda (w) (substring w 0 -1))
4736 (list org-scheduled-string org-deadline-string
4737 org-clock-string org-closed-string))
4739 (org-compute-latex-and-specials-regexp)
4740 (org-set-font-lock-defaults))))
4742 (defun org-file-contents (file &optional noerror)
4743 "Return the contents of FILE, as a string."
4744 (if (or (not file)
4745 (not (file-readable-p file)))
4746 (if noerror
4747 (progn
4748 (message "Cannot read file \"%s\"" file)
4749 (ding) (sit-for 2)
4751 (error "Cannot read file \"%s\"" file))
4752 (with-temp-buffer
4753 (insert-file-contents file)
4754 (buffer-string))))
4756 (defun org-extract-log-state-settings (x)
4757 "Extract the log state setting from a TODO keyword string.
4758 This will extract info from a string like \"WAIT(w@/!)\"."
4759 (let (kw key log1 log2)
4760 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4761 (setq kw (match-string 1 x)
4762 key (and (match-end 2) (match-string 2 x))
4763 log1 (and (match-end 3) (match-string 3 x))
4764 log2 (and (match-end 4) (match-string 4 x)))
4765 (and (or log1 log2)
4766 (list kw
4767 (and log1 (if (equal log1 "!") 'time 'note))
4768 (and log2 (if (equal log2 "!") 'time 'note)))))))
4770 (defun org-remove-keyword-keys (list)
4771 "Remove a pair of parenthesis at the end of each string in LIST."
4772 (mapcar (lambda (x)
4773 (if (string-match "(.*)$" x)
4774 (substring x 0 (match-beginning 0))
4776 list))
4778 (defun org-assign-fast-keys (alist)
4779 "Assign fast keys to a keyword-key alist.
4780 Respect keys that are already there."
4781 (let (new e (alt ?0))
4782 (while (setq e (pop alist))
4783 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4784 (cdr e)) ;; Key already assigned.
4785 (push e new)
4786 (let ((clist (string-to-list (downcase (car e))))
4787 (used (append new alist)))
4788 (when (= (car clist) ?@)
4789 (pop clist))
4790 (while (and clist (rassoc (car clist) used))
4791 (pop clist))
4792 (unless clist
4793 (while (rassoc alt used)
4794 (incf alt)))
4795 (push (cons (car e) (or (car clist) alt)) new))))
4796 (nreverse new)))
4798 ;;; Some variables used in various places
4800 (defvar org-window-configuration nil
4801 "Used in various places to store a window configuration.")
4802 (defvar org-selected-window nil
4803 "Used in various places to store a window configuration.")
4804 (defvar org-finish-function nil
4805 "Function to be called when `C-c C-c' is used.
4806 This is for getting out of special buffers like capture.")
4809 ;; FIXME: Occasionally check by commenting these, to make sure
4810 ;; no other functions uses these, forgetting to let-bind them.
4811 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4812 (defvar org-last-state)
4813 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4815 ;; Defined somewhere in this file, but used before definition.
4816 (defvar org-entities) ;; defined in org-entities.el
4817 (defvar org-struct-menu)
4818 (defvar org-org-menu)
4819 (defvar org-tbl-menu)
4821 ;;;; Define the Org-mode
4823 ;; We use a before-change function to check if a table might need
4824 ;; an update.
4825 (defvar org-table-may-need-update t
4826 "Indicates that a table might need an update.
4827 This variable is set by `org-before-change-function'.
4828 `org-table-align' sets it back to nil.")
4829 (defun org-before-change-function (beg end)
4830 "Every change indicates that a table might need an update."
4831 (setq org-table-may-need-update t))
4832 (defvar org-mode-map)
4833 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4834 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4835 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4836 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4837 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4838 (defvar org-table-buffer-is-an nil)
4840 (defvar bidi-paragraph-direction)
4841 (defvar buffer-face-mode-face)
4843 (require 'outline)
4844 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4845 (error "Conflict with outdated version of allout.el. Load org.el before allout.el, or upgrade to newer allout, for example by switching to Emacs 22"))
4846 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
4848 ;; Other stuff we need.
4849 (require 'time-date)
4850 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
4851 (require 'easymenu)
4852 (require 'overlay)
4854 (require 'org-macs)
4855 (require 'org-entities)
4856 ;; (require 'org-compat) moved higher up in the file before it is first used
4857 (require 'org-faces)
4858 (require 'org-list)
4859 (require 'org-pcomplete)
4860 (require 'org-src)
4861 (require 'org-footnote)
4863 ;; babel
4864 (require 'ob)
4865 (require 'ob-table)
4866 (require 'ob-lob)
4867 (require 'ob-ref)
4868 (require 'ob-tangle)
4869 (require 'ob-comint)
4870 (require 'ob-keys)
4872 ;;;###autoload
4873 (define-derived-mode org-mode outline-mode "Org"
4874 "Outline-based notes management and organizer, alias
4875 \"Carsten's outline-mode for keeping track of everything.\"
4877 Org-mode develops organizational tasks around a NOTES file which
4878 contains information about projects as plain text. Org-mode is
4879 implemented on top of outline-mode, which is ideal to keep the content
4880 of large files well structured. It supports ToDo items, deadlines and
4881 time stamps, which magically appear in the diary listing of the Emacs
4882 calendar. Tables are easily created with a built-in table editor.
4883 Plain text URL-like links connect to websites, emails (VM), Usenet
4884 messages (Gnus), BBDB entries, and any files related to the project.
4885 For printing and sharing of notes, an Org-mode file (or a part of it)
4886 can be exported as a structured ASCII or HTML file.
4888 The following commands are available:
4890 \\{org-mode-map}"
4892 ;; Get rid of Outline menus, they are not needed
4893 ;; Need to do this here because define-derived-mode sets up
4894 ;; the keymap so late. Still, it is a waste to call this each time
4895 ;; we switch another buffer into org-mode.
4896 (if (featurep 'xemacs)
4897 (when (boundp 'outline-mode-menu-heading)
4898 ;; Assume this is Greg's port, it uses easymenu
4899 (easy-menu-remove outline-mode-menu-heading)
4900 (easy-menu-remove outline-mode-menu-show)
4901 (easy-menu-remove outline-mode-menu-hide))
4902 (define-key org-mode-map [menu-bar headings] 'undefined)
4903 (define-key org-mode-map [menu-bar hide] 'undefined)
4904 (define-key org-mode-map [menu-bar show] 'undefined))
4906 (org-load-modules-maybe)
4907 (easy-menu-add org-org-menu)
4908 (easy-menu-add org-tbl-menu)
4909 (org-install-agenda-files-menu)
4910 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4911 (add-to-invisibility-spec '(org-cwidth))
4912 (add-to-invisibility-spec '(org-hide-block . t))
4913 (when (featurep 'xemacs)
4914 (org-set-local 'line-move-ignore-invisible t))
4915 (org-set-local 'outline-regexp org-outline-regexp)
4916 (org-set-local 'outline-level 'org-outline-level)
4917 (setq bidi-paragraph-direction 'left-to-right)
4918 (when (and org-ellipsis
4919 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4920 (fboundp 'make-glyph-code))
4921 (unless org-display-table
4922 (setq org-display-table (make-display-table)))
4923 (set-display-table-slot
4924 org-display-table 4
4925 (vconcat (mapcar
4926 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4927 org-ellipsis)))
4928 (if (stringp org-ellipsis) org-ellipsis "..."))))
4929 (setq buffer-display-table org-display-table))
4930 (org-set-regexps-and-options)
4931 (when (and org-tag-faces (not org-tags-special-faces-re))
4932 ;; tag faces set outside customize.... force initialization.
4933 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4934 ;; Calc embedded
4935 (org-set-local 'calc-embedded-open-mode "# ")
4936 (modify-syntax-entry ?@ "w")
4937 (modify-syntax-entry ?\" "\"")
4938 (if org-startup-truncated (setq truncate-lines t))
4939 (org-set-local 'font-lock-unfontify-region-function
4940 'org-unfontify-region)
4941 ;; Activate before-change-function
4942 (org-set-local 'org-table-may-need-update t)
4943 (org-add-hook 'before-change-functions 'org-before-change-function nil
4944 'local)
4945 ;; Check for running clock before killing a buffer
4946 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4947 ;; Initialize macros templates.
4948 (org-macro-initialize-templates)
4949 ;; Initialize radio targets.
4950 (org-update-radio-target-regexp)
4951 ;; Indentation.
4952 (org-set-local 'indent-line-function 'org-indent-line)
4953 (org-set-local 'indent-region-function 'org-indent-region)
4954 ;; Filling and auto-filling.
4955 (org-setup-filling)
4956 ;; Comments.
4957 (org-setup-comments-handling)
4958 ;; Beginning/end of defun
4959 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
4960 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
4961 ;; Next error for sparse trees
4962 (org-set-local 'next-error-function 'org-occur-next-match)
4963 ;; Make sure dependence stuff works reliably, even for users who set it
4964 ;; too late :-(
4965 (if org-enforce-todo-dependencies
4966 (add-hook 'org-blocker-hook
4967 'org-block-todo-from-children-or-siblings-or-parent)
4968 (remove-hook 'org-blocker-hook
4969 'org-block-todo-from-children-or-siblings-or-parent))
4970 (if org-enforce-todo-checkbox-dependencies
4971 (add-hook 'org-blocker-hook
4972 'org-block-todo-from-checkboxes)
4973 (remove-hook 'org-blocker-hook
4974 'org-block-todo-from-checkboxes))
4976 ;; Align options lines
4977 (org-set-local
4978 'align-mode-rules-list
4979 '((org-in-buffer-settings
4980 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4981 (modes . '(org-mode)))))
4983 ;; Imenu
4984 (org-set-local 'imenu-create-index-function
4985 'org-imenu-get-tree)
4987 ;; Make isearch reveal context
4988 (if (or (featurep 'xemacs)
4989 (not (boundp 'outline-isearch-open-invisible-function)))
4990 ;; Emacs 21 and XEmacs make use of the hook
4991 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4992 ;; Emacs 22 deals with this through a special variable
4993 (org-set-local 'outline-isearch-open-invisible-function
4994 (lambda (&rest ignore) (org-show-context 'isearch))))
4996 ;; Turn on org-beamer-mode?
4997 (and org-startup-with-beamer-mode (org-beamer-mode))
4999 ;; Setup the pcomplete hooks
5000 (set (make-local-variable 'pcomplete-command-completion-function)
5001 'org-pcomplete-initial)
5002 (set (make-local-variable 'pcomplete-command-name-function)
5003 'org-command-at-point)
5004 (set (make-local-variable 'pcomplete-default-completion-function)
5005 'ignore)
5006 (set (make-local-variable 'pcomplete-parse-arguments-function)
5007 'org-parse-arguments)
5008 (set (make-local-variable 'pcomplete-termination-string) "")
5009 (when (>= emacs-major-version 23)
5010 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5012 ;; If empty file that did not turn on org-mode automatically, make it to.
5013 (if (and org-insert-mode-line-in-empty-file
5014 (org-called-interactively-p 'any)
5015 (= (point-min) (point-max)))
5016 (insert "# -*- mode: org -*-\n\n"))
5017 (unless org-inhibit-startup
5018 (when org-startup-align-all-tables
5019 (let ((bmp (buffer-modified-p)))
5020 (org-table-map-tables 'org-table-align 'quietly)
5021 (set-buffer-modified-p bmp)))
5022 (when org-startup-with-inline-images
5023 (org-display-inline-images))
5024 (when org-startup-indented
5025 (require 'org-indent)
5026 (org-indent-mode 1))
5027 (unless org-inhibit-startup-visibility-stuff
5028 (org-set-startup-visibility)))
5029 ;; Try to set org-hide correctly
5030 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5032 (when (fboundp 'abbrev-table-put)
5033 (abbrev-table-put org-mode-abbrev-table
5034 :parents (list text-mode-abbrev-table)))
5036 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5039 (defun org-find-invisible-foreground ()
5040 (let ((candidates (remove
5041 "unspecified-bg"
5042 (list
5043 (face-background 'default)
5044 (face-background 'org-default)
5045 (cdr (assoc 'background-color default-frame-alist))
5046 (cdr (assoc 'background-color initial-frame-alist))
5047 (cdr (assoc 'background-color window-system-default-frame-alist))
5048 (face-foreground 'org-hide)))))
5049 (car (remove nil candidates))))
5051 (defun org-current-time ()
5052 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5053 (if (> (car org-time-stamp-rounding-minutes) 1)
5054 (let ((r (car org-time-stamp-rounding-minutes))
5055 (time (decode-time)))
5056 (apply 'encode-time
5057 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5058 (nthcdr 2 time))))
5059 (current-time)))
5061 (defun org-today ()
5062 "Return today date, considering `org-extend-today-until'."
5063 (time-to-days
5064 (time-subtract (current-time)
5065 (list 0 (* 3600 org-extend-today-until) 0))))
5067 ;;;; Font-Lock stuff, including the activators
5069 (defvar org-mouse-map (make-sparse-keymap))
5070 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5071 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5072 (when org-mouse-1-follows-link
5073 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5074 (when org-tab-follows-link
5075 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5076 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5078 (require 'font-lock)
5080 (defconst org-non-link-chars "]\t\n\r<>")
5081 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5082 "shell" "elisp" "doi" "message"))
5083 (defvar org-link-types-re nil
5084 "Matches a link that has a url-like prefix like \"http:\"")
5085 (defvar org-link-re-with-space nil
5086 "Matches a link with spaces, optional angular brackets around it.")
5087 (defvar org-link-re-with-space2 nil
5088 "Matches a link with spaces, optional angular brackets around it.")
5089 (defvar org-link-re-with-space3 nil
5090 "Matches a link with spaces, only for internal part in bracket links.")
5091 (defvar org-angle-link-re nil
5092 "Matches link with angular brackets, spaces are allowed.")
5093 (defvar org-plain-link-re nil
5094 "Matches plain link, without spaces.")
5095 (defvar org-bracket-link-regexp nil
5096 "Matches a link in double brackets.")
5097 (defvar org-bracket-link-analytic-regexp nil
5098 "Regular expression used to analyze links.
5099 Here is what the match groups contain after a match:
5100 1: http:
5101 2: http
5102 3: path
5103 4: [desc]
5104 5: desc")
5105 (defvar org-bracket-link-analytic-regexp++ nil
5106 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5107 (defvar org-any-link-re nil
5108 "Regular expression matching any link.")
5110 (defcustom org-match-sexp-depth 3
5111 "Number of stacked braces for sub/superscript matching.
5112 This has to be set before loading org.el to be effective."
5113 :group 'org-export-translation ; ??????????????????????????/
5114 :type 'integer)
5116 (defun org-create-multibrace-regexp (left right n)
5117 "Create a regular expression which will match a balanced sexp.
5118 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5119 as single character strings.
5120 The regexp returned will match the entire expression including the
5121 delimiters. It will also define a single group which contains the
5122 match except for the outermost delimiters. The maximum depth of
5123 stacked delimiters is N. Escaping delimiters is not possible."
5124 (let* ((nothing (concat "[^" left right "]*?"))
5125 (or "\\|")
5126 (re nothing)
5127 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5128 (while (> n 1)
5129 (setq n (1- n)
5130 re (concat re or next)
5131 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5132 (concat left "\\(" re "\\)" right)))
5134 (defvar org-match-substring-regexp
5135 (concat
5136 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5137 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5138 "\\|"
5139 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5140 "\\|"
5141 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5142 "The regular expression matching a sub- or superscript.")
5144 (defvar org-match-substring-with-braces-regexp
5145 (concat
5146 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5147 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5148 "\\)")
5149 "The regular expression matching a sub- or superscript, forcing braces.")
5151 (defun org-make-link-regexps ()
5152 "Update the link regular expressions.
5153 This should be called after the variable `org-link-types' has changed."
5154 (setq org-link-types-re
5155 (concat
5156 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5157 org-link-re-with-space
5158 (concat
5159 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5160 "\\([^" org-non-link-chars " ]"
5161 "[^" org-non-link-chars "]*"
5162 "[^" org-non-link-chars " ]\\)>?")
5163 org-link-re-with-space2
5164 (concat
5165 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5166 "\\([^" org-non-link-chars " ]"
5167 "[^\t\n\r]*"
5168 "[^" org-non-link-chars " ]\\)>?")
5169 org-link-re-with-space3
5170 (concat
5171 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5172 "\\([^" org-non-link-chars " ]"
5173 "[^\t\n\r]*\\)")
5174 org-angle-link-re
5175 (concat
5176 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5177 "\\([^" org-non-link-chars " ]"
5178 "[^" org-non-link-chars "]*"
5179 "\\)>")
5180 org-plain-link-re
5181 (concat
5182 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5183 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5184 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5185 org-bracket-link-regexp
5186 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5187 org-bracket-link-analytic-regexp
5188 (concat
5189 "\\[\\["
5190 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5191 "\\([^]]+\\)"
5192 "\\]"
5193 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5194 "\\]")
5195 org-bracket-link-analytic-regexp++
5196 (concat
5197 "\\[\\["
5198 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5199 "\\([^]]+\\)"
5200 "\\]"
5201 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5202 "\\]")
5203 org-any-link-re
5204 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5205 org-angle-link-re "\\)\\|\\("
5206 org-plain-link-re "\\)")))
5208 (org-make-link-regexps)
5210 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5211 "Regular expression for fast time stamp matching.")
5212 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5213 "Regular expression for fast time stamp matching.")
5214 (defconst org-ts-regexp0
5215 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5216 "Regular expression matching time strings for analysis.
5217 This one does not require the space after the date, so it can be used
5218 on a string that terminates immediately after the date.")
5219 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5220 "Regular expression matching time strings for analysis.")
5221 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5222 "Regular expression matching time stamps, with groups.")
5223 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5224 "Regular expression matching time stamps (also [..]), with groups.")
5225 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5226 "Regular expression matching a time stamp range.")
5227 (defconst org-tr-regexp-both
5228 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5229 "Regular expression matching a time stamp range.")
5230 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5231 org-ts-regexp "\\)?")
5232 "Regular expression matching a time stamp or time stamp range.")
5233 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5234 org-ts-regexp-both "\\)?")
5235 "Regular expression matching a time stamp or time stamp range.
5236 The time stamps may be either active or inactive.")
5238 (defvar org-emph-face nil)
5240 (defun org-do-emphasis-faces (limit)
5241 "Run through the buffer and add overlays to emphasized strings."
5242 (let (rtn a)
5243 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5244 (if (not (= (char-after (match-beginning 3))
5245 (char-after (match-beginning 4))))
5246 (progn
5247 (setq rtn t)
5248 (setq a (assoc (match-string 3) org-emphasis-alist))
5249 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5250 'face
5251 (nth 1 a))
5252 (and (nth 4 a)
5253 (org-remove-flyspell-overlays-in
5254 (match-beginning 0) (match-end 0)))
5255 (add-text-properties (match-beginning 2) (match-end 2)
5256 '(font-lock-multiline t org-emphasis t))
5257 (when org-hide-emphasis-markers
5258 (add-text-properties (match-end 4) (match-beginning 5)
5259 '(invisible org-link))
5260 (add-text-properties (match-beginning 3) (match-end 3)
5261 '(invisible org-link)))))
5262 (backward-char 1))
5263 rtn))
5265 (defun org-emphasize (&optional char)
5266 "Insert or change an emphasis, i.e. a font like bold or italic.
5267 If there is an active region, change that region to a new emphasis.
5268 If there is no region, just insert the marker characters and position
5269 the cursor between them.
5270 CHAR should be either the marker character, or the first character of the
5271 HTML tag associated with that emphasis. If CHAR is a space, the means
5272 to remove the emphasis of the selected region.
5273 If char is not given (for example in an interactive call) it
5274 will be prompted for."
5275 (interactive)
5276 (let ((eal org-emphasis-alist) e det
5277 (erc org-emphasis-regexp-components)
5278 (prompt "")
5279 (string "") beg end move tag c s)
5280 (if (org-region-active-p)
5281 (setq beg (region-beginning) end (region-end)
5282 string (buffer-substring beg end))
5283 (setq move t))
5285 (while (setq e (pop eal))
5286 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5287 c (aref tag 0))
5288 (push (cons c (string-to-char (car e))) det)
5289 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5290 (substring tag 1)))))
5291 (setq det (nreverse det))
5292 (unless char
5293 (message "%s" (concat "Emphasis marker or tag:" prompt))
5294 (setq char (read-char-exclusive)))
5295 (setq char (or (cdr (assoc char det)) char))
5296 (if (equal char ?\ )
5297 (setq s "" move nil)
5298 (unless (assoc (char-to-string char) org-emphasis-alist)
5299 (error "No such emphasis marker: \"%c\"" char))
5300 (setq s (char-to-string char)))
5301 (while (and (> (length string) 1)
5302 (equal (substring string 0 1) (substring string -1))
5303 (assoc (substring string 0 1) org-emphasis-alist))
5304 (setq string (substring string 1 -1)))
5305 (setq string (concat s string s))
5306 (if beg (delete-region beg end))
5307 (unless (or (bolp)
5308 (string-match (concat "[" (nth 0 erc) "\n]")
5309 (char-to-string (char-before (point)))))
5310 (insert " "))
5311 (unless (or (eobp)
5312 (string-match (concat "[" (nth 1 erc) "\n]")
5313 (char-to-string (char-after (point)))))
5314 (insert " ") (backward-char 1))
5315 (insert string)
5316 (and move (backward-char 1))))
5318 (defconst org-nonsticky-props
5319 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5321 (defsubst org-rear-nonsticky-at (pos)
5322 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5324 (defun org-activate-plain-links (limit)
5325 "Run through the buffer and add overlays to links."
5326 (catch 'exit
5327 (let (f hl)
5328 (when (re-search-forward (concat org-plain-link-re) limit t)
5329 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5330 (setq f (get-text-property (match-beginning 0) 'face))
5331 (setq hl (org-match-string-no-properties 0))
5332 (if (or (eq f 'org-tag)
5333 (and (listp f) (memq 'org-tag f)))
5335 (add-text-properties (match-beginning 0) (match-end 0)
5336 (list 'mouse-face 'highlight
5337 'face 'org-link
5338 'htmlize-link `(:uri ,hl)
5339 'keymap org-mouse-map))
5340 (org-rear-nonsticky-at (match-end 0)))
5341 t))))
5343 (defun org-activate-code (limit)
5344 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5345 (progn
5346 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5347 (remove-text-properties (match-beginning 0) (match-end 0)
5348 '(display t invisible t intangible t))
5349 t)))
5351 (defcustom org-src-fontify-natively nil
5352 "When non-nil, fontify code in code blocks."
5353 :type 'boolean
5354 :version "24.1"
5355 :group 'org-appearance
5356 :group 'org-babel)
5358 (defcustom org-allow-promoting-top-level-subtree nil
5359 "When non-nil, allow promoting a top level subtree.
5360 The leading star of the top level headline will be replaced
5361 by a #."
5362 :type 'boolean
5363 :version "24.1"
5364 :group 'org-appearance)
5366 (defun org-fontify-meta-lines-and-blocks (limit)
5367 (condition-case nil
5368 (org-fontify-meta-lines-and-blocks-1 limit)
5369 (error (message "org-mode fontification error"))))
5371 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5372 "Fontify #+ lines and blocks, in the correct ways."
5373 (let ((case-fold-search t))
5374 (if (re-search-forward
5375 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5376 limit t)
5377 (let ((beg (match-beginning 0))
5378 (block-start (match-end 0))
5379 (block-end nil)
5380 (lang (match-string 7))
5381 (beg1 (line-beginning-position 2))
5382 (dc1 (downcase (match-string 2)))
5383 (dc3 (downcase (match-string 3)))
5384 end end1 quoting block-type ovl)
5385 (cond
5386 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5387 ;; a single line of backend-specific content
5388 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5389 (remove-text-properties (match-beginning 0) (match-end 0)
5390 '(display t invisible t intangible t))
5391 (add-text-properties (match-beginning 1) (match-end 3)
5392 '(font-lock-fontified t face org-meta-line))
5393 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5394 '(font-lock-fontified t face org-block))
5395 ; for backend-specific code
5397 ((and (match-end 4) (equal dc3 "+begin"))
5398 ;; Truly a block
5399 (setq block-type (downcase (match-string 5))
5400 quoting (member block-type org-protecting-blocks))
5401 (when (re-search-forward
5402 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5403 nil t) ;; on purpose, we look further than LIMIT
5404 (setq end (min (point-max) (match-end 0))
5405 end1 (min (point-max) (1- (match-beginning 0))))
5406 (setq block-end (match-beginning 0))
5407 (when quoting
5408 (remove-text-properties beg end
5409 '(display t invisible t intangible t)))
5410 (add-text-properties
5411 beg end
5412 '(font-lock-fontified t font-lock-multiline t))
5413 (add-text-properties beg beg1 '(face org-meta-line))
5414 (add-text-properties end1 (min (point-max) (1+ end))
5415 '(face org-meta-line)) ; for end_src
5416 (cond
5417 ((and lang (not (string= lang "")) org-src-fontify-natively)
5418 (org-src-font-lock-fontify-block lang block-start block-end)
5419 ;; remove old background overlays
5420 (mapc (lambda (ov)
5421 (if (eq (overlay-get ov 'face) 'org-block-background)
5422 (delete-overlay ov)))
5423 (overlays-at (/ (+ beg1 block-end) 2)))
5424 ;; add a background overlay
5425 (setq ovl (make-overlay beg1 block-end))
5426 (overlay-put ovl 'face 'org-block-background)
5427 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5428 (quoting
5429 (add-text-properties beg1 (min (point-max) (1+ end1))
5430 '(face org-block))) ; end of source block
5431 ((not org-fontify-quote-and-verse-blocks))
5432 ((string= block-type "quote")
5433 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5434 ((string= block-type "verse")
5435 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5436 (add-text-properties beg beg1 '(face org-block-begin-line))
5437 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5438 '(face org-block-end-line))
5440 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5441 (add-text-properties
5442 beg (match-end 3)
5443 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5444 '(font-lock-fontified t invisible t)
5445 '(font-lock-fontified t face org-document-info-keyword)))
5446 (add-text-properties
5447 (match-beginning 6) (match-end 6)
5448 (if (string-equal dc1 "+title:")
5449 '(font-lock-fontified t face org-document-title)
5450 '(font-lock-fontified t face org-document-info))))
5451 ((or (equal dc1 "+results")
5452 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5453 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5454 "+call:" "+header:" "+headers:" "+name:"))
5455 (and (match-end 4) (equal dc3 "+attr")))
5456 (add-text-properties
5457 beg (match-end 0)
5458 '(font-lock-fontified t face org-meta-line))
5460 ((member dc3 '(" " ""))
5461 (add-text-properties
5462 beg (match-end 0)
5463 '(font-lock-fontified t face font-lock-comment-face)))
5464 ((not (member (char-after beg) '(?\ ?\t)))
5465 ;; just any other in-buffer setting, but not indented
5466 (add-text-properties
5467 beg (match-end 0)
5468 '(font-lock-fontified t face org-meta-line))
5470 (t nil))))))
5472 (defun org-activate-angle-links (limit)
5473 "Run through the buffer and add overlays to links."
5474 (if (re-search-forward org-angle-link-re limit t)
5475 (progn
5476 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5477 (add-text-properties (match-beginning 0) (match-end 0)
5478 (list 'mouse-face 'highlight
5479 'keymap org-mouse-map))
5480 (org-rear-nonsticky-at (match-end 0))
5481 t)))
5483 (defun org-activate-footnote-links (limit)
5484 "Run through the buffer and add overlays to footnotes."
5485 (let ((fn (org-footnote-next-reference-or-definition limit)))
5486 (when fn
5487 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5488 (org-remove-flyspell-overlays-in beg end)
5489 (add-text-properties beg end
5490 (list 'mouse-face 'highlight
5491 'keymap org-mouse-map
5492 'help-echo
5493 (if (= (point-at-bol) beg)
5494 "Footnote definition"
5495 "Footnote reference")
5496 'font-lock-fontified t
5497 'font-lock-multiline t
5498 'face 'org-footnote))))))
5500 (defun org-activate-bracket-links (limit)
5501 "Run through the buffer and add overlays to bracketed links."
5502 (if (re-search-forward org-bracket-link-regexp limit t)
5503 (let* ((hl (org-match-string-no-properties 1))
5504 (help (concat "LINK: " hl))
5505 ;; FIXME: Above we should remove the escapes. But that
5506 ;; requires another match, protecting match data, a lot
5507 ;; of overhead for font-lock.
5508 (ip (org-maybe-intangible
5509 (list 'invisible 'org-link
5510 'keymap org-mouse-map 'mouse-face 'highlight
5511 'font-lock-multiline t 'help-echo help
5512 'htmlize-link `(:uri ,hl))))
5513 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5514 'font-lock-multiline t 'help-echo help
5515 'htmlize-link `(:uri ,hl))))
5516 ;; We need to remove the invisible property here. Table narrowing
5517 ;; may have made some of this invisible.
5518 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5519 (remove-text-properties (match-beginning 0) (match-end 0)
5520 '(invisible nil))
5521 (if (match-end 3)
5522 (progn
5523 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5524 (org-rear-nonsticky-at (match-beginning 3))
5525 (add-text-properties (match-beginning 3) (match-end 3) vp)
5526 (org-rear-nonsticky-at (match-end 3))
5527 (add-text-properties (match-end 3) (match-end 0) ip)
5528 (org-rear-nonsticky-at (match-end 0)))
5529 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5530 (org-rear-nonsticky-at (match-beginning 1))
5531 (add-text-properties (match-beginning 1) (match-end 1) vp)
5532 (org-rear-nonsticky-at (match-end 1))
5533 (add-text-properties (match-end 1) (match-end 0) ip)
5534 (org-rear-nonsticky-at (match-end 0)))
5535 t)))
5537 (defun org-activate-dates (limit)
5538 "Run through the buffer and add overlays to dates."
5539 (if (re-search-forward org-tsr-regexp-both limit t)
5540 (progn
5541 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5542 (add-text-properties (match-beginning 0) (match-end 0)
5543 (list 'mouse-face 'highlight
5544 'keymap org-mouse-map))
5545 (org-rear-nonsticky-at (match-end 0))
5546 (when org-display-custom-times
5547 (if (match-end 3)
5548 (org-display-custom-time (match-beginning 3) (match-end 3)))
5549 (org-display-custom-time (match-beginning 1) (match-end 1)))
5550 t)))
5552 (defvar org-target-link-regexp nil
5553 "Regular expression matching radio targets in plain text.")
5554 (make-variable-buffer-local 'org-target-link-regexp)
5555 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5556 "Regular expression matching a link target.")
5557 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5558 "Regular expression matching a radio target.")
5559 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5560 "Regular expression matching any target.")
5562 (defun org-activate-target-links (limit)
5563 "Run through the buffer and add overlays to target matches."
5564 (when org-target-link-regexp
5565 (let ((case-fold-search t))
5566 (if (re-search-forward org-target-link-regexp limit t)
5567 (progn
5568 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5569 (add-text-properties (match-beginning 0) (match-end 0)
5570 (list 'mouse-face 'highlight
5571 'keymap org-mouse-map
5572 'help-echo "Radio target link"
5573 'org-linked-text t))
5574 (org-rear-nonsticky-at (match-end 0))
5575 t)))))
5577 (defun org-update-radio-target-regexp ()
5578 "Find all radio targets in this file and update the regular expression."
5579 (interactive)
5580 (when (memq 'radio org-activate-links)
5581 (setq org-target-link-regexp
5582 (org-make-target-link-regexp (org-all-targets 'radio)))
5583 (org-restart-font-lock)))
5585 (defun org-hide-wide-columns (limit)
5586 (let (s e)
5587 (setq s (text-property-any (point) (or limit (point-max))
5588 'org-cwidth t))
5589 (when s
5590 (setq e (next-single-property-change s 'org-cwidth))
5591 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5592 (goto-char e)
5593 t)))
5595 (defvar org-latex-and-specials-regexp nil
5596 "Regular expression for highlighting export special stuff.")
5597 (defvar org-match-substring-regexp)
5598 (defvar org-match-substring-with-braces-regexp)
5600 ;; This should be with the exporter code, but we also use if for font-locking
5601 (defconst org-export-html-special-string-regexps
5602 '(("\\\\-" . "&shy;")
5603 ("---\\([^-]\\)" . "&mdash;\\1")
5604 ("--\\([^-]\\)" . "&ndash;\\1")
5605 ("\\.\\.\\." . "&hellip;"))
5606 "Regular expressions for special string conversion.")
5609 (defun org-compute-latex-and-specials-regexp ()
5610 "Compute regular expression for stuff treated specially by exporters."
5611 (if (not org-highlight-latex-fragments-and-specials)
5612 (org-set-local 'org-latex-and-specials-regexp nil)
5613 (require 'org-exp)
5614 (let*
5615 ((matchers (plist-get org-format-latex-options :matchers))
5616 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5617 org-latex-regexps)))
5618 (org-export-allow-BIND nil)
5619 (options (org-combine-plists (org-default-export-plist)
5620 (org-infile-export-plist)))
5621 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5622 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5623 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5624 (org-export-html-expand (plist-get options :expand-quoted-html))
5625 (org-export-with-special-strings (plist-get options :special-strings))
5626 (re-sub
5627 (cond
5628 ((equal org-export-with-sub-superscripts '{})
5629 (list org-match-substring-with-braces-regexp))
5630 (org-export-with-sub-superscripts
5631 (list org-match-substring-regexp))))
5632 (re-latex
5633 (if org-export-with-LaTeX-fragments
5634 (mapcar (lambda (x) (nth 1 x)) latexs)))
5635 (re-macros
5636 (if org-export-with-TeX-macros
5637 (list (concat "\\\\"
5638 (regexp-opt
5639 (append
5641 (delq nil
5642 (mapcar 'car-safe
5643 (append org-entities-user
5644 org-entities)))
5645 (if (boundp 'org-latex-entities)
5646 (mapcar (lambda (x)
5647 (or (car-safe x) x))
5648 org-latex-entities)
5649 nil))
5650 'words))) ; FIXME
5652 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5653 (re-special (if org-export-with-special-strings
5654 (mapcar (lambda (x) (car x))
5655 org-export-html-special-string-regexps)))
5656 (re-rest
5657 (delq nil
5658 (list
5659 (if org-export-html-expand "@<[^>\n]+>")
5660 ))))
5661 (org-set-local
5662 'org-latex-and-specials-regexp
5663 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5664 re-rest) "\\|")))))
5666 (defun org-do-latex-and-special-faces (limit)
5667 "Run through the buffer and add overlays to links."
5668 (when org-latex-and-specials-regexp
5669 (let (rtn d)
5670 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5671 limit t))
5672 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5673 'face))
5674 '(org-code org-verbatim underline)))
5675 (progn
5676 (setq rtn t
5677 d (cond ((member (char-after (1+ (match-beginning 0)))
5678 '(?_ ?^)) 1)
5679 (t 0)))
5680 (font-lock-prepend-text-property
5681 (+ d (match-beginning 0)) (match-end 0)
5682 'face 'org-latex-and-export-specials)
5683 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5684 '(font-lock-multiline t)))))
5685 rtn)))
5687 (defun org-restart-font-lock ()
5688 "Restart `font-lock-mode', to force refontification."
5689 (when (and (boundp 'font-lock-mode) font-lock-mode)
5690 (font-lock-mode -1)
5691 (font-lock-mode 1)))
5693 (defun org-all-targets (&optional radio)
5694 "Return a list of all targets in this file.
5695 When optional argument RADIO is non-nil, only find radio
5696 targets."
5697 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
5698 (save-excursion
5699 (goto-char (point-min))
5700 (while (re-search-forward re nil t)
5701 (let ((obj (org-element-context)))
5702 (when (memq (org-element-type obj) '(radio-target target))
5703 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
5704 rtn)))
5706 (defun org-make-target-link-regexp (targets)
5707 "Make regular expression matching all strings in TARGETS.
5708 The regular expression finds the targets also if there is a line break
5709 between words."
5710 (and targets
5711 (concat
5712 "\\<\\("
5713 (mapconcat
5714 (lambda (x)
5715 (setq x (regexp-quote x))
5716 (while (string-match " +" x)
5717 (setq x (replace-match "\\s-+" t t x)))
5719 targets
5720 "\\|")
5721 "\\)\\>")))
5723 (defun org-activate-tags (limit)
5724 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5725 (progn
5726 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5727 (add-text-properties (match-beginning 1) (match-end 1)
5728 (list 'mouse-face 'highlight
5729 'keymap org-mouse-map))
5730 (org-rear-nonsticky-at (match-end 1))
5731 t)))
5733 (defun org-outline-level ()
5734 "Compute the outline level of the heading at point.
5735 If this is called at a normal headline, the level is the number of stars.
5736 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5737 (save-excursion
5738 (if (not (condition-case nil
5739 (org-back-to-heading t)
5740 (error nil)))
5742 (looking-at org-outline-regexp)
5743 (1- (- (match-end 0) (match-beginning 0))))))
5745 (defvar org-font-lock-keywords nil)
5747 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5748 "Regular expression matching a property line.")
5750 (defvar org-font-lock-hook nil
5751 "Functions to be called for special font lock stuff.")
5753 (defvar org-font-lock-set-keywords-hook nil
5754 "Functions that can manipulate `org-font-lock-extra-keywords'.
5755 This is called after `org-font-lock-extra-keywords' is defined, but before
5756 it is installed to be used by font lock. This can be useful if something
5757 needs to be inserted at a specific position in the font-lock sequence.")
5759 (defun org-font-lock-hook (limit)
5760 "Run `org-font-lock-hook' within LIMIT."
5761 (run-hook-with-args 'org-font-lock-hook limit))
5763 (defun org-set-font-lock-defaults ()
5764 "Set font lock defaults for the current buffer."
5765 (let* ((em org-fontify-emphasized-text)
5766 (lk org-activate-links)
5767 (org-font-lock-extra-keywords
5768 (list
5769 ;; Call the hook
5770 '(org-font-lock-hook)
5771 ;; Headlines
5772 `(,(if org-fontify-whole-heading-line
5773 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5774 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5775 (1 (org-get-level-face 1))
5776 (2 (org-get-level-face 2))
5777 (3 (org-get-level-face 3)))
5778 ;; Table lines
5779 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5780 (1 'org-table t))
5781 ;; Table internals
5782 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5783 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5784 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5785 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5786 ;; Drawers
5787 (list org-drawer-regexp '(0 'org-special-keyword t))
5788 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5789 ;; Properties
5790 (list org-property-re
5791 '(1 'org-special-keyword t)
5792 '(3 'org-property-value t))
5793 ;; Links
5794 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5795 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5796 (if (memq 'plain lk) '(org-activate-plain-links))
5797 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5798 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5799 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5800 (if (memq 'footnote lk) '(org-activate-footnote-links))
5801 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5802 '(org-hide-wide-columns (0 nil append))
5803 ;; TODO keyword
5804 (list (format org-heading-keyword-regexp-format
5805 org-todo-regexp)
5806 '(2 (org-get-todo-face 2) t))
5807 ;; DONE
5808 (if org-fontify-done-headline
5809 (list (format org-heading-keyword-regexp-format
5810 (concat
5811 "\\(?:"
5812 (mapconcat 'regexp-quote org-done-keywords "\\|")
5813 "\\)"))
5814 '(2 'org-headline-done t))
5815 nil)
5816 ;; Priorities
5817 '(org-font-lock-add-priority-faces)
5818 ;; Tags
5819 '(org-font-lock-add-tag-faces)
5820 ;; Special keywords
5821 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5822 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5823 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5824 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5825 ;; Emphasis
5826 (if em
5827 (if (featurep 'xemacs)
5828 '(org-do-emphasis-faces (0 nil append))
5829 '(org-do-emphasis-faces)))
5830 ;; Checkboxes
5831 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5832 1 'org-checkbox prepend)
5833 (if (cdr (assq 'checkbox org-list-automatic-rules))
5834 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5835 (0 (org-get-checkbox-statistics-face) t)))
5836 ;; Description list items
5837 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5838 1 'org-list-dt prepend)
5839 ;; ARCHIVEd headings
5840 (list (concat
5841 org-outline-regexp-bol
5842 "\\(.*:" org-archive-tag ":.*\\)")
5843 '(1 'org-archived prepend))
5844 ;; Specials
5845 '(org-do-latex-and-special-faces)
5846 '(org-fontify-entities)
5847 '(org-raise-scripts)
5848 ;; Code
5849 '(org-activate-code (1 'org-code t))
5850 ;; COMMENT
5851 (list (format org-heading-keyword-regexp-format
5852 (concat "\\("
5853 org-comment-string "\\|" org-quote-string
5854 "\\)"))
5855 '(2 'org-special-keyword t))
5856 ;; Blocks and meta lines
5857 '(org-fontify-meta-lines-and-blocks)
5859 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5860 (run-hooks 'org-font-lock-set-keywords-hook)
5861 ;; Now set the full font-lock-keywords
5862 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5863 (org-set-local 'font-lock-defaults
5864 '(org-font-lock-keywords t nil nil backward-paragraph))
5865 (kill-local-variable 'font-lock-keywords) nil))
5867 (defun org-toggle-pretty-entities ()
5868 "Toggle the composition display of entities as UTF8 characters."
5869 (interactive)
5870 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5871 (org-restart-font-lock)
5872 (if org-pretty-entities
5873 (message "Entities are displayed as UTF8 characters")
5874 (save-restriction
5875 (widen)
5876 (org-decompose-region (point-min) (point-max))
5877 (message "Entities are displayed plain"))))
5879 (defvar org-custom-properties-overlays nil
5880 "List of overlays used for custom properties.")
5881 (make-variable-buffer-local 'org-custom-properties-overlays)
5883 (defun org-toggle-custom-properties-visibility ()
5884 "Display or hide properties in `org-custom-properties'."
5885 (interactive)
5886 (if org-custom-properties-overlays
5887 (progn (mapc 'delete-overlay org-custom-properties-overlays)
5888 (setq org-custom-properties-overlays nil))
5889 (unless (not org-custom-properties)
5890 (save-excursion
5891 (save-restriction
5892 (widen)
5893 (goto-char (point-min))
5894 (while (re-search-forward org-property-re nil t)
5895 (mapc (lambda(p)
5896 (when (equal p (substring (match-string 1) 1 -1))
5897 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
5898 (overlay-put o 'invisible t)
5899 (overlay-put o 'org-custom-property t)
5900 (push o org-custom-properties-overlays))))
5901 org-custom-properties)))))))
5903 (defun org-fontify-entities (limit)
5904 "Find an entity to fontify."
5905 (let (ee)
5906 (when org-pretty-entities
5907 (catch 'match
5908 (while (re-search-forward
5909 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
5910 limit t)
5911 (if (and (not (org-in-indented-comment-line))
5912 (setq ee (org-entity-get (match-string 1)))
5913 (= (length (nth 6 ee)) 1))
5914 (let*
5915 ((end (if (equal (match-string 2) "{}")
5916 (match-end 2)
5917 (match-end 1))))
5918 (add-text-properties
5919 (match-beginning 0) end
5920 (list 'font-lock-fontified t))
5921 (compose-region (match-beginning 0) end
5922 (nth 6 ee) nil)
5923 (backward-char 1)
5924 (throw 'match t))))
5925 nil))))
5927 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5928 "Fontify string S like in Org-mode."
5929 (with-temp-buffer
5930 (insert s)
5931 (let ((org-odd-levels-only odd-levels))
5932 (org-mode)
5933 (font-lock-fontify-buffer)
5934 (buffer-string))))
5936 (defvar org-m nil)
5937 (defvar org-l nil)
5938 (defvar org-f nil)
5939 (defun org-get-level-face (n)
5940 "Get the right face for match N in font-lock matching of headlines."
5941 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5942 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5943 (if org-cycle-level-faces
5944 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5945 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5946 (cond
5947 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5948 ((eq n 2) org-f)
5949 (t (if org-level-color-stars-only nil org-f))))
5952 (defun org-get-todo-face (kwd)
5953 "Get the right face for a TODO keyword KWD.
5954 If KWD is a number, get the corresponding match group."
5955 (if (numberp kwd) (setq kwd (match-string kwd)))
5956 (or (org-face-from-face-or-color
5957 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5958 (and (member kwd org-done-keywords) 'org-done)
5959 'org-todo))
5961 (defun org-face-from-face-or-color (context inherit face-or-color)
5962 "Create a face list that inherits INHERIT, but sets the foreground color.
5963 When FACE-OR-COLOR is not a string, just return it."
5964 (if (stringp face-or-color)
5965 (list :inherit inherit
5966 (cdr (assoc context org-faces-easy-properties))
5967 face-or-color)
5968 face-or-color))
5970 (defun org-font-lock-add-tag-faces (limit)
5971 "Add the special tag faces."
5972 (when (and org-tag-faces org-tags-special-faces-re)
5973 (while (re-search-forward org-tags-special-faces-re limit t)
5974 (add-text-properties (match-beginning 1) (match-end 1)
5975 (list 'face (org-get-tag-face 1)
5976 'font-lock-fontified t))
5977 (backward-char 1))))
5979 (defun org-font-lock-add-priority-faces (limit)
5980 "Add the special priority faces."
5981 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5982 (when (save-match-data (org-at-heading-p))
5983 (add-text-properties
5984 (match-beginning 0) (match-end 0)
5985 (list 'face (or (org-face-from-face-or-color
5986 'priority 'org-special-keyword
5987 (cdr (assoc (char-after (match-beginning 1))
5988 org-priority-faces)))
5989 'org-special-keyword)
5990 'font-lock-fontified t)))))
5992 (defun org-get-tag-face (kwd)
5993 "Get the right face for a TODO keyword KWD.
5994 If KWD is a number, get the corresponding match group."
5995 (if (numberp kwd) (setq kwd (match-string kwd)))
5996 (or (org-face-from-face-or-color
5997 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5998 'org-tag))
6000 (defun org-unfontify-region (beg end &optional maybe_loudly)
6001 "Remove fontification and activation overlays from links."
6002 (font-lock-default-unfontify-region beg end)
6003 (let* ((buffer-undo-list t)
6004 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6005 (inhibit-modification-hooks t)
6006 deactivate-mark buffer-file-name buffer-file-truename)
6007 (org-decompose-region beg end)
6008 (remove-text-properties beg end
6009 '(mouse-face t keymap t org-linked-text t
6010 invisible t intangible t
6011 org-no-flyspell t org-emphasis t))
6012 (org-remove-font-lock-display-properties beg end)))
6014 (defconst org-script-display '(((raise -0.3) (height 0.7))
6015 ((raise 0.3) (height 0.7))
6016 ((raise -0.5))
6017 ((raise 0.5)))
6018 "Display properties for showing superscripts and subscripts.")
6020 (defun org-remove-font-lock-display-properties (beg end)
6021 "Remove specific display properties that have been added by font lock.
6022 The will remove the raise properties that are used to show superscripts
6023 and subscripts."
6024 (let (next prop)
6025 (while (< beg end)
6026 (setq next (next-single-property-change beg 'display nil end)
6027 prop (get-text-property beg 'display))
6028 (if (member prop org-script-display)
6029 (put-text-property beg next 'display nil))
6030 (setq beg next))))
6032 (defun org-raise-scripts (limit)
6033 "Add raise properties to sub/superscripts."
6034 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6035 (if (re-search-forward
6036 (if (eq org-use-sub-superscripts t)
6037 org-match-substring-regexp
6038 org-match-substring-with-braces-regexp)
6039 limit t)
6040 (let* ((pos (point)) table-p comment-p
6041 (mpos (match-beginning 3))
6042 (emph-p (get-text-property mpos 'org-emphasis))
6043 (link-p (get-text-property mpos 'mouse-face))
6044 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6045 (goto-char (point-at-bol))
6046 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6047 comment-p (org-looking-at-p "[ \t]*#"))
6048 (goto-char pos)
6049 ;; FIXME: Should we go back one character here, for a_b^c
6050 ;; (goto-char (1- pos)) ;????????????????????
6051 (if (or comment-p emph-p link-p keyw-p)
6053 (put-text-property (match-beginning 3) (match-end 0)
6054 'display
6055 (if (equal (char-after (match-beginning 2)) ?^)
6056 (nth (if table-p 3 1) org-script-display)
6057 (nth (if table-p 2 0) org-script-display)))
6058 (add-text-properties (match-beginning 2) (match-end 2)
6059 (list 'invisible t
6060 'org-dwidth t 'org-dwidth-n 1))
6061 (if (and (eq (char-after (match-beginning 3)) ?{)
6062 (eq (char-before (match-end 3)) ?}))
6063 (progn
6064 (add-text-properties
6065 (match-beginning 3) (1+ (match-beginning 3))
6066 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6067 (add-text-properties
6068 (1- (match-end 3)) (match-end 3)
6069 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6070 t)))))
6072 ;;;; Visibility cycling, including org-goto and indirect buffer
6074 ;;; Cycling
6076 (defvar org-cycle-global-status nil)
6077 (make-variable-buffer-local 'org-cycle-global-status)
6078 (defvar org-cycle-subtree-status nil)
6079 (make-variable-buffer-local 'org-cycle-subtree-status)
6081 (defvar org-inlinetask-min-level)
6083 ;;;###autoload
6084 (defun org-cycle (&optional arg)
6085 "TAB-action and visibility cycling for Org-mode.
6087 This is the command invoked in Org-mode by the TAB key. Its main purpose
6088 is outline visibility cycling, but it also invokes other actions
6089 in special contexts.
6091 - When this function is called with a prefix argument, rotate the entire
6092 buffer through 3 states (global cycling)
6093 1. OVERVIEW: Show only top-level headlines.
6094 2. CONTENTS: Show all headlines of all levels, but no body text.
6095 3. SHOW ALL: Show everything.
6096 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6097 determined by the variable `org-startup-folded', and by any VISIBILITY
6098 properties in the buffer.
6099 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6100 including any drawers.
6102 - When inside a table, re-align the table and move to the next field.
6104 - When point is at the beginning of a headline, rotate the subtree started
6105 by this line through 3 different states (local cycling)
6106 1. FOLDED: Only the main headline is shown.
6107 2. CHILDREN: The main headline and the direct children are shown.
6108 From this state, you can move to one of the children
6109 and zoom in further.
6110 3. SUBTREE: Show the entire subtree, including body text.
6111 If there is no subtree, switch directly from CHILDREN to FOLDED.
6113 - When point is at the beginning of an empty headline and the variable
6114 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6115 of the headline by demoting and promoting it to likely levels. This
6116 speeds up creation document structure by pressing TAB once or several
6117 times right after creating a new headline.
6119 - When there is a numeric prefix, go up to a heading with level ARG, do
6120 a `show-subtree' and return to the previous cursor position. If ARG
6121 is negative, go up that many levels.
6123 - When point is not at the beginning of a headline, execute the global
6124 binding for TAB, which is re-indenting the line. See the option
6125 `org-cycle-emulate-tab' for details.
6127 - Special case: if point is at the beginning of the buffer and there is
6128 no headline in line 1, this function will act as if called with prefix arg
6129 (C-u TAB, same as S-TAB) also when called without prefix arg.
6130 But only if also the variable `org-cycle-global-at-bob' is t."
6131 (interactive "P")
6132 (org-load-modules-maybe)
6133 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6134 (and org-cycle-level-after-item/entry-creation
6135 (or (org-cycle-level)
6136 (org-cycle-item-indentation))))
6137 (let* ((limit-level
6138 (or org-cycle-max-level
6139 (and (boundp 'org-inlinetask-min-level)
6140 org-inlinetask-min-level
6141 (1- org-inlinetask-min-level))))
6142 (nstars (and limit-level
6143 (if org-odd-levels-only
6144 (and limit-level (1- (* limit-level 2)))
6145 limit-level)))
6146 (org-outline-regexp
6147 (if (not (derived-mode-p 'org-mode))
6148 outline-regexp
6149 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6150 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6151 (not (looking-at org-outline-regexp))))
6152 (org-cycle-hook
6153 (if bob-special
6154 (delq 'org-optimize-window-after-visibility-change
6155 (copy-sequence org-cycle-hook))
6156 org-cycle-hook))
6157 (pos (point)))
6159 (if (or bob-special (equal arg '(4)))
6160 ;; special case: use global cycling
6161 (setq arg t))
6163 (cond
6165 ((equal arg '(16))
6166 (setq last-command 'dummy)
6167 (org-set-startup-visibility)
6168 (message "Startup visibility, plus VISIBILITY properties"))
6170 ((equal arg '(64))
6171 (show-all)
6172 (message "Entire buffer visible, including drawers"))
6174 ;; Table: enter it or move to the next field.
6175 ((org-at-table-p 'any)
6176 (if (org-at-table.el-p)
6177 (message "Use C-c ' to edit table.el tables")
6178 (if arg (org-table-edit-field t)
6179 (org-table-justify-field-maybe)
6180 (call-interactively 'org-table-next-field))))
6182 ((run-hook-with-args-until-success
6183 'org-tab-after-check-for-table-hook))
6185 ;; Global cycling: delegate to `org-cycle-internal-global'.
6186 ((eq arg t) (org-cycle-internal-global))
6188 ;; Drawers: delegate to `org-flag-drawer'.
6189 ((and org-drawers org-drawer-regexp
6190 (save-excursion
6191 (beginning-of-line 1)
6192 (looking-at org-drawer-regexp)))
6193 (org-flag-drawer ; toggle block visibility
6194 (not (get-char-property (match-end 0) 'invisible))))
6196 ;; Show-subtree, ARG levels up from here.
6197 ((integerp arg)
6198 (save-excursion
6199 (org-back-to-heading)
6200 (outline-up-heading (if (< arg 0) (- arg)
6201 (- (funcall outline-level) arg)))
6202 (org-show-subtree)))
6204 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6205 ((and (featurep 'org-inlinetask)
6206 (org-inlinetask-at-task-p)
6207 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6208 (org-inlinetask-toggle-visibility))
6210 ((org-try-cdlatex-tab))
6212 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6213 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6214 (save-excursion (beginning-of-line 1)
6215 (looking-at org-outline-regexp)))
6216 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6217 (org-cycle-internal-local))
6219 ;; From there: TAB emulation and template completion.
6220 (buffer-read-only (org-back-to-heading))
6222 ((run-hook-with-args-until-success
6223 'org-tab-after-check-for-cycling-hook))
6225 ((org-try-structure-completion))
6227 ((run-hook-with-args-until-success
6228 'org-tab-before-tab-emulation-hook))
6230 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6231 (or (not (bolp))
6232 (not (looking-at org-outline-regexp))))
6233 (call-interactively (global-key-binding "\t")))
6235 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6236 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6237 (or (and (eq org-cycle-emulate-tab 'white)
6238 (= (match-end 0) (point-at-eol)))
6239 (and (eq org-cycle-emulate-tab 'whitestart)
6240 (>= (match-end 0) pos))))
6242 (eq org-cycle-emulate-tab t))
6243 (call-interactively (global-key-binding "\t")))
6245 (t (save-excursion
6246 (org-back-to-heading)
6247 (org-cycle)))))))
6249 (defun org-cycle-internal-global ()
6250 "Do the global cycling action."
6251 ;; Hack to avoid display of messages for .org attachments in Gnus
6252 (let ((ga (string-match "\\*fontification" (buffer-name))))
6253 (cond
6254 ((and (eq last-command this-command)
6255 (eq org-cycle-global-status 'overview))
6256 ;; We just created the overview - now do table of contents
6257 ;; This can be slow in very large buffers, so indicate action
6258 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6259 (unless ga (message "CONTENTS..."))
6260 (org-content)
6261 (unless ga (message "CONTENTS...done"))
6262 (setq org-cycle-global-status 'contents)
6263 (run-hook-with-args 'org-cycle-hook 'contents))
6265 ((and (eq last-command this-command)
6266 (eq org-cycle-global-status 'contents))
6267 ;; We just showed the table of contents - now show everything
6268 (run-hook-with-args 'org-pre-cycle-hook 'all)
6269 (show-all)
6270 (unless ga (message "SHOW ALL"))
6271 (setq org-cycle-global-status 'all)
6272 (run-hook-with-args 'org-cycle-hook 'all))
6275 ;; Default action: go to overview
6276 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6277 (org-overview)
6278 (unless ga (message "OVERVIEW"))
6279 (setq org-cycle-global-status 'overview)
6280 (run-hook-with-args 'org-cycle-hook 'overview)))))
6282 (defun org-cycle-internal-local ()
6283 "Do the local cycling action."
6284 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6285 ;; First, determine end of headline (EOH), end of subtree or item
6286 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6287 (save-excursion
6288 (if (org-at-item-p)
6289 (progn
6290 (beginning-of-line)
6291 (setq struct (org-list-struct))
6292 (setq eoh (point-at-eol))
6293 (setq eos (org-list-get-item-end-before-blank (point) struct))
6294 (setq has-children (org-list-has-child-p (point) struct)))
6295 (org-back-to-heading)
6296 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6297 (setq eos (save-excursion
6298 (org-end-of-subtree t)
6299 (unless (eobp)
6300 (skip-chars-forward " \t\n"))
6301 (if (eobp) (point) (1- (point)))))
6302 (setq has-children
6303 (or (save-excursion
6304 (let ((level (funcall outline-level)))
6305 (outline-next-heading)
6306 (and (org-at-heading-p t)
6307 (> (funcall outline-level) level))))
6308 (save-excursion
6309 (org-list-search-forward (org-item-beginning-re) eos t)))))
6310 ;; Determine end invisible part of buffer (EOL)
6311 (beginning-of-line 2)
6312 ;; XEmacs doesn't have `next-single-char-property-change'
6313 (if (featurep 'xemacs)
6314 (while (and (not (eobp)) ;; this is like `next-line'
6315 (get-char-property (1- (point)) 'invisible))
6316 (beginning-of-line 2))
6317 (while (and (not (eobp)) ;; this is like `next-line'
6318 (get-char-property (1- (point)) 'invisible))
6319 (goto-char (next-single-char-property-change (point) 'invisible))
6320 (and (eolp) (beginning-of-line 2))))
6321 (setq eol (point)))
6322 ;; Find out what to do next and set `this-command'
6323 (cond
6324 ((= eos eoh)
6325 ;; Nothing is hidden behind this heading
6326 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6327 (message "EMPTY ENTRY")
6328 (setq org-cycle-subtree-status nil)
6329 (save-excursion
6330 (goto-char eos)
6331 (outline-next-heading)
6332 (if (outline-invisible-p) (org-flag-heading nil))))
6333 ((and (or (>= eol eos)
6334 (not (string-match "\\S-" (buffer-substring eol eos))))
6335 (or has-children
6336 (not (setq children-skipped
6337 org-cycle-skip-children-state-if-no-children))))
6338 ;; Entire subtree is hidden in one line: children view
6339 (run-hook-with-args 'org-pre-cycle-hook 'children)
6340 (if (org-at-item-p)
6341 (org-list-set-item-visibility (point-at-bol) struct 'children)
6342 (org-show-entry)
6343 (org-with-limited-levels (show-children))
6344 ;; FIXME: This slows down the func way too much.
6345 ;; How keep drawers hidden in subtree anyway?
6346 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6347 ;; (org-cycle-hide-drawers 'subtree))
6349 ;; Fold every list in subtree to top-level items.
6350 (when (eq org-cycle-include-plain-lists 'integrate)
6351 (save-excursion
6352 (org-back-to-heading)
6353 (while (org-list-search-forward (org-item-beginning-re) eos t)
6354 (beginning-of-line 1)
6355 (let* ((struct (org-list-struct))
6356 (prevs (org-list-prevs-alist struct))
6357 (end (org-list-get-bottom-point struct)))
6358 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6359 (org-list-get-all-items (point) struct prevs))
6360 (goto-char end))))))
6361 (message "CHILDREN")
6362 (save-excursion
6363 (goto-char eos)
6364 (outline-next-heading)
6365 (if (outline-invisible-p) (org-flag-heading nil)))
6366 (setq org-cycle-subtree-status 'children)
6367 (run-hook-with-args 'org-cycle-hook 'children))
6368 ((or children-skipped
6369 (and (eq last-command this-command)
6370 (eq org-cycle-subtree-status 'children)))
6371 ;; We just showed the children, or no children are there,
6372 ;; now show everything.
6373 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6374 (outline-flag-region eoh eos nil)
6375 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6376 (setq org-cycle-subtree-status 'subtree)
6377 (run-hook-with-args 'org-cycle-hook 'subtree))
6379 ;; Default action: hide the subtree.
6380 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6381 (outline-flag-region eoh eos t)
6382 (message "FOLDED")
6383 (setq org-cycle-subtree-status 'folded)
6384 (run-hook-with-args 'org-cycle-hook 'folded)))))
6386 ;;;###autoload
6387 (defun org-global-cycle (&optional arg)
6388 "Cycle the global visibility. For details see `org-cycle'.
6389 With \\[universal-argument] prefix arg, switch to startup visibility.
6390 With a numeric prefix, show all headlines up to that level."
6391 (interactive "P")
6392 (let ((org-cycle-include-plain-lists
6393 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6394 (cond
6395 ((integerp arg)
6396 (show-all)
6397 (hide-sublevels arg)
6398 (setq org-cycle-global-status 'contents))
6399 ((equal arg '(4))
6400 (org-set-startup-visibility)
6401 (message "Startup visibility, plus VISIBILITY properties."))
6403 (org-cycle '(4))))))
6405 (defun org-set-startup-visibility ()
6406 "Set the visibility required by startup options and properties."
6407 (cond
6408 ((eq org-startup-folded t)
6409 (org-cycle '(4)))
6410 ((eq org-startup-folded 'content)
6411 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6412 (org-cycle '(4)) (org-cycle '(4)))))
6413 (unless (eq org-startup-folded 'showeverything)
6414 (if org-hide-block-startup (org-hide-block-all))
6415 (org-set-visibility-according-to-property 'no-cleanup)
6416 (org-cycle-hide-archived-subtrees 'all)
6417 (org-cycle-hide-drawers 'all)
6418 (org-cycle-show-empty-lines t)))
6420 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6421 "Switch subtree visibilities according to :VISIBILITY: property."
6422 (interactive)
6423 (let (org-show-entry-below state)
6424 (save-excursion
6425 (goto-char (point-min))
6426 (while (re-search-forward
6427 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6428 nil t)
6429 (setq state (match-string 1))
6430 (save-excursion
6431 (org-back-to-heading t)
6432 (hide-subtree)
6433 (org-reveal)
6434 (cond
6435 ((equal state '("fold" "folded"))
6436 (hide-subtree))
6437 ((equal state "children")
6438 (org-show-hidden-entry)
6439 (show-children))
6440 ((equal state "content")
6441 (save-excursion
6442 (save-restriction
6443 (org-narrow-to-subtree)
6444 (org-content))))
6445 ((member state '("all" "showall"))
6446 (show-subtree)))))
6447 (unless no-cleanup
6448 (org-cycle-hide-archived-subtrees 'all)
6449 (org-cycle-hide-drawers 'all)
6450 (org-cycle-show-empty-lines 'all)))))
6452 ;; This function uses outline-regexp instead of the more fundamental
6453 ;; org-outline-regexp so that org-cycle-global works outside of Org
6454 ;; buffers, where outline-regexp is needed.
6455 (defun org-overview ()
6456 "Switch to overview mode, showing only top-level headlines.
6457 Really, this shows all headlines with level equal or greater than the level
6458 of the first headline in the buffer. This is important, because if the
6459 first headline is not level one, then (hide-sublevels 1) gives confusing
6460 results."
6461 (interactive)
6462 (let ((level (save-excursion
6463 (goto-char (point-min))
6464 (if (re-search-forward (concat "^" outline-regexp) nil t)
6465 (progn
6466 (goto-char (match-beginning 0))
6467 (funcall outline-level))))))
6468 (and level (hide-sublevels level))))
6470 (defun org-content (&optional arg)
6471 "Show all headlines in the buffer, like a table of contents.
6472 With numerical argument N, show content up to level N."
6473 (interactive "P")
6474 (save-excursion
6475 ;; Visit all headings and show their offspring
6476 (and (integerp arg) (org-overview))
6477 (goto-char (point-max))
6478 (catch 'exit
6479 (while (and (progn (condition-case nil
6480 (outline-previous-visible-heading 1)
6481 (error (goto-char (point-min))))
6483 (looking-at org-outline-regexp))
6484 (if (integerp arg)
6485 (show-children (1- arg))
6486 (show-branches))
6487 (if (bobp) (throw 'exit nil))))))
6490 (defun org-optimize-window-after-visibility-change (state)
6491 "Adjust the window after a change in outline visibility.
6492 This function is the default value of the hook `org-cycle-hook'."
6493 (when (get-buffer-window (current-buffer))
6494 (cond
6495 ((eq state 'content) nil)
6496 ((eq state 'all) nil)
6497 ((eq state 'folded) nil)
6498 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6499 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6501 (defun org-remove-empty-overlays-at (pos)
6502 "Remove outline overlays that do not contain non-white stuff."
6503 (mapc
6504 (lambda (o)
6505 (and (eq 'outline (overlay-get o 'invisible))
6506 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6507 (overlay-end o))))
6508 (delete-overlay o)))
6509 (overlays-at pos)))
6511 (defun org-clean-visibility-after-subtree-move ()
6512 "Fix visibility issues after moving a subtree."
6513 ;; First, find a reasonable region to look at:
6514 ;; Start two siblings above, end three below
6515 (let* ((beg (save-excursion
6516 (and (org-get-last-sibling)
6517 (org-get-last-sibling))
6518 (point)))
6519 (end (save-excursion
6520 (and (org-get-next-sibling)
6521 (org-get-next-sibling)
6522 (org-get-next-sibling))
6523 (if (org-at-heading-p)
6524 (point-at-eol)
6525 (point))))
6526 (level (looking-at "\\*+"))
6527 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6528 (save-excursion
6529 (save-restriction
6530 (narrow-to-region beg end)
6531 (when re
6532 ;; Properly fold already folded siblings
6533 (goto-char (point-min))
6534 (while (re-search-forward re nil t)
6535 (if (and (not (outline-invisible-p))
6536 (save-excursion
6537 (goto-char (point-at-eol)) (outline-invisible-p)))
6538 (hide-entry))))
6539 (org-cycle-show-empty-lines 'overview)
6540 (org-cycle-hide-drawers 'overview)))))
6542 (defun org-cycle-show-empty-lines (state)
6543 "Show empty lines above all visible headlines.
6544 The region to be covered depends on STATE when called through
6545 `org-cycle-hook'. Lisp program can use t for STATE to get the
6546 entire buffer covered. Note that an empty line is only shown if there
6547 are at least `org-cycle-separator-lines' empty lines before the headline."
6548 (when (not (= org-cycle-separator-lines 0))
6549 (save-excursion
6550 (let* ((n (abs org-cycle-separator-lines))
6551 (re (cond
6552 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6553 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6554 (t (let ((ns (number-to-string (- n 2))))
6555 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6556 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6557 beg end b e)
6558 (cond
6559 ((memq state '(overview contents t))
6560 (setq beg (point-min) end (point-max)))
6561 ((memq state '(children folded))
6562 (setq beg (point) end (progn (org-end-of-subtree t t)
6563 (beginning-of-line 2)
6564 (point)))))
6565 (when beg
6566 (goto-char beg)
6567 (while (re-search-forward re end t)
6568 (unless (get-char-property (match-end 1) 'invisible)
6569 (setq e (match-end 1))
6570 (if (< org-cycle-separator-lines 0)
6571 (setq b (save-excursion
6572 (goto-char (match-beginning 0))
6573 (org-back-over-empty-lines)
6574 (if (save-excursion
6575 (goto-char (max (point-min) (1- (point))))
6576 (org-at-heading-p))
6577 (1- (point))
6578 (point))))
6579 (setq b (match-beginning 1)))
6580 (outline-flag-region b e nil)))))))
6581 ;; Never hide empty lines at the end of the file.
6582 (save-excursion
6583 (goto-char (point-max))
6584 (outline-previous-heading)
6585 (outline-end-of-heading)
6586 (if (and (looking-at "[ \t\n]+")
6587 (= (match-end 0) (point-max)))
6588 (outline-flag-region (point) (match-end 0) nil))))
6590 (defun org-show-empty-lines-in-parent ()
6591 "Move to the parent and re-show empty lines before visible headlines."
6592 (save-excursion
6593 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6594 (org-cycle-show-empty-lines context))))
6596 (defun org-files-list ()
6597 "Return `org-agenda-files' list, plus all open org-mode files.
6598 This is useful for operations that need to scan all of a user's
6599 open and agenda-wise Org files."
6600 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6601 (dolist (buf (buffer-list))
6602 (with-current-buffer buf
6603 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6604 (let ((file (expand-file-name (buffer-file-name))))
6605 (unless (member file files)
6606 (push file files))))))
6607 files))
6609 (defsubst org-entry-beginning-position ()
6610 "Return the beginning position of the current entry."
6611 (save-excursion (outline-back-to-heading t) (point)))
6613 (defsubst org-entry-end-position ()
6614 "Return the end position of the current entry."
6615 (save-excursion (outline-next-heading) (point)))
6617 (defun org-cycle-hide-drawers (state)
6618 "Re-hide all drawers after a visibility state change."
6619 (when (and (derived-mode-p 'org-mode)
6620 (not (memq state '(overview folded contents))))
6621 (save-excursion
6622 (let* ((globalp (memq state '(contents all)))
6623 (beg (if globalp (point-min) (point)))
6624 (end (if globalp (point-max)
6625 (if (eq state 'children)
6626 (save-excursion (outline-next-heading) (point))
6627 (org-end-of-subtree t)))))
6628 (goto-char beg)
6629 (while (re-search-forward org-drawer-regexp end t)
6630 (org-flag-drawer t))))))
6632 (defun org-cycle-hide-inline-tasks (state)
6633 "Re-hide inline task when switching to 'contents visibility state."
6634 (when (and (eq state 'contents)
6635 (boundp 'org-inlinetask-min-level)
6636 org-inlinetask-min-level)
6637 (hide-sublevels (1- org-inlinetask-min-level))))
6639 (defun org-flag-drawer (flag)
6640 "When FLAG is non-nil, hide the drawer we are within.
6641 Otherwise make it visible."
6642 (save-excursion
6643 (beginning-of-line 1)
6644 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6645 (let ((b (match-end 0)))
6646 (if (re-search-forward
6647 "^[ \t]*:END:"
6648 (save-excursion (outline-next-heading) (point)) t)
6649 (outline-flag-region b (point-at-eol) flag)
6650 (error ":END: line missing at position %s" b))))))
6652 (defun org-subtree-end-visible-p ()
6653 "Is the end of the current subtree visible?"
6654 (pos-visible-in-window-p
6655 (save-excursion (org-end-of-subtree t) (point))))
6657 (defun org-first-headline-recenter (&optional N)
6658 "Move cursor to the first headline and recenter the headline.
6659 Optional argument N means put the headline into the Nth line of the window."
6660 (goto-char (point-min))
6661 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6662 (beginning-of-line)
6663 (recenter (prefix-numeric-value N))))
6665 ;;; Saving and restoring visibility
6667 (defun org-outline-overlay-data (&optional use-markers)
6668 "Return a list of the locations of all outline overlays.
6669 These are overlays with the `invisible' property value `outline'.
6670 The return value is a list of cons cells, with start and stop
6671 positions for each overlay.
6672 If USE-MARKERS is set, return the positions as markers."
6673 (let (beg end)
6674 (save-excursion
6675 (save-restriction
6676 (widen)
6677 (delq nil
6678 (mapcar (lambda (o)
6679 (when (eq (overlay-get o 'invisible) 'outline)
6680 (setq beg (overlay-start o)
6681 end (overlay-end o))
6682 (and beg end (> end beg)
6683 (if use-markers
6684 (cons (move-marker (make-marker) beg)
6685 (move-marker (make-marker) end))
6686 (cons beg end)))))
6687 (overlays-in (point-min) (point-max))))))))
6689 (defun org-set-outline-overlay-data (data)
6690 "Create visibility overlays for all positions in DATA.
6691 DATA should have been made by `org-outline-overlay-data'."
6692 (let (o)
6693 (save-excursion
6694 (save-restriction
6695 (widen)
6696 (show-all)
6697 (mapc (lambda (c)
6698 (outline-flag-region (car c) (cdr c) t))
6699 data)))))
6701 ;;; Folding of blocks
6703 (defvar org-hide-block-overlays nil
6704 "Overlays hiding blocks.")
6705 (make-variable-buffer-local 'org-hide-block-overlays)
6707 (defun org-block-map (function &optional start end)
6708 "Call FUNCTION at the head of all source blocks in the current buffer.
6709 Optional arguments START and END can be used to limit the range."
6710 (let ((start (or start (point-min)))
6711 (end (or end (point-max))))
6712 (save-excursion
6713 (goto-char start)
6714 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6715 (save-excursion
6716 (save-match-data
6717 (goto-char (match-beginning 0))
6718 (funcall function)))))))
6720 (defun org-hide-block-toggle-all ()
6721 "Toggle the visibility of all blocks in the current buffer."
6722 (org-block-map #'org-hide-block-toggle))
6724 (defun org-hide-block-all ()
6725 "Fold all blocks in the current buffer."
6726 (interactive)
6727 (org-show-block-all)
6728 (org-block-map #'org-hide-block-toggle-maybe))
6730 (defun org-show-block-all ()
6731 "Unfold all blocks in the current buffer."
6732 (interactive)
6733 (mapc 'delete-overlay org-hide-block-overlays)
6734 (setq org-hide-block-overlays nil))
6736 (defun org-hide-block-toggle-maybe ()
6737 "Toggle visibility of block at point."
6738 (interactive)
6739 (let ((case-fold-search t))
6740 (if (save-excursion
6741 (beginning-of-line 1)
6742 (looking-at org-block-regexp))
6743 (progn (org-hide-block-toggle)
6744 t) ;; to signal that we took action
6745 nil))) ;; to signal that we did not
6747 (defun org-hide-block-toggle (&optional force)
6748 "Toggle the visibility of the current block."
6749 (interactive)
6750 (save-excursion
6751 (beginning-of-line)
6752 (if (re-search-forward org-block-regexp nil t)
6753 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6754 (end (match-end 0)) ;; end of entire body
6756 (if (memq t (mapcar (lambda (overlay)
6757 (eq (overlay-get overlay 'invisible)
6758 'org-hide-block))
6759 (overlays-at start)))
6760 (if (or (not force) (eq force 'off))
6761 (mapc (lambda (ov)
6762 (when (member ov org-hide-block-overlays)
6763 (setq org-hide-block-overlays
6764 (delq ov org-hide-block-overlays)))
6765 (when (eq (overlay-get ov 'invisible)
6766 'org-hide-block)
6767 (delete-overlay ov)))
6768 (overlays-at start)))
6769 (setq ov (make-overlay start end))
6770 (overlay-put ov 'invisible 'org-hide-block)
6771 ;; make the block accessible to isearch
6772 (overlay-put
6773 ov 'isearch-open-invisible
6774 (lambda (ov)
6775 (when (member ov org-hide-block-overlays)
6776 (setq org-hide-block-overlays
6777 (delq ov org-hide-block-overlays)))
6778 (when (eq (overlay-get ov 'invisible)
6779 'org-hide-block)
6780 (delete-overlay ov))))
6781 (push ov org-hide-block-overlays)))
6782 (error "Not looking at a source block"))))
6784 ;; org-tab-after-check-for-cycling-hook
6785 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6786 ;; Remove overlays when changing major mode
6787 (add-hook 'org-mode-hook
6788 (lambda () (org-add-hook 'change-major-mode-hook
6789 'org-show-block-all 'append 'local)))
6791 ;;; Org-goto
6793 (defvar org-goto-window-configuration nil)
6794 (defvar org-goto-marker nil)
6795 (defvar org-goto-map
6796 (let ((map (make-sparse-keymap)))
6797 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6798 (while (setq cmd (pop cmds))
6799 (substitute-key-definition cmd cmd map global-map)))
6800 (suppress-keymap map)
6801 (org-defkey map "\C-m" 'org-goto-ret)
6802 (org-defkey map [(return)] 'org-goto-ret)
6803 (org-defkey map [(left)] 'org-goto-left)
6804 (org-defkey map [(right)] 'org-goto-right)
6805 (org-defkey map [(control ?g)] 'org-goto-quit)
6806 (org-defkey map "\C-i" 'org-cycle)
6807 (org-defkey map [(tab)] 'org-cycle)
6808 (org-defkey map [(down)] 'outline-next-visible-heading)
6809 (org-defkey map [(up)] 'outline-previous-visible-heading)
6810 (if org-goto-auto-isearch
6811 (if (fboundp 'define-key-after)
6812 (define-key-after map [t] 'org-goto-local-auto-isearch)
6813 nil)
6814 (org-defkey map "q" 'org-goto-quit)
6815 (org-defkey map "n" 'outline-next-visible-heading)
6816 (org-defkey map "p" 'outline-previous-visible-heading)
6817 (org-defkey map "f" 'outline-forward-same-level)
6818 (org-defkey map "b" 'outline-backward-same-level)
6819 (org-defkey map "u" 'outline-up-heading))
6820 (org-defkey map "/" 'org-occur)
6821 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6822 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6823 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6824 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6825 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6826 map))
6828 (defconst org-goto-help
6829 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6830 RET=jump to location [Q]uit and return to previous location
6831 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6833 (defvar org-goto-start-pos) ; dynamically scoped parameter
6835 ;; FIXME: Docstring does not mention both interfaces
6836 (defun org-goto (&optional alternative-interface)
6837 "Look up a different location in the current file, keeping current visibility.
6839 When you want look-up or go to a different location in a
6840 document, the fastest way is often to fold the entire buffer and
6841 then dive into the tree. This method has the disadvantage, that
6842 the previous location will be folded, which may not be what you
6843 want.
6845 This command works around this by showing a copy of the current
6846 buffer in an indirect buffer, in overview mode. You can dive
6847 into the tree in that copy, use org-occur and incremental search
6848 to find a location. When pressing RET or `Q', the command
6849 returns to the original buffer in which the visibility is still
6850 unchanged. After RET it will also jump to the location selected
6851 in the indirect buffer and expose the headline hierarchy above.
6853 With a prefix argument, use the alternative interface: e.g. if
6854 `org-goto-interface' is 'outline use 'outline-path-completion."
6855 (interactive "P")
6856 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6857 (org-refile-use-outline-path t)
6858 (org-refile-target-verify-function nil)
6859 (interface
6860 (if (not alternative-interface)
6861 org-goto-interface
6862 (if (eq org-goto-interface 'outline)
6863 'outline-path-completion
6864 'outline)))
6865 (org-goto-start-pos (point))
6866 (selected-point
6867 (if (eq interface 'outline)
6868 (car (org-get-location (current-buffer) org-goto-help))
6869 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6870 (org-refile-check-position pa)
6871 (nth 3 pa)))))
6872 (if selected-point
6873 (progn
6874 (org-mark-ring-push org-goto-start-pos)
6875 (goto-char selected-point)
6876 (if (or (outline-invisible-p) (org-invisible-p2))
6877 (org-show-context 'org-goto)))
6878 (message "Quit"))))
6880 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6881 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6882 (defvar org-goto-local-auto-isearch-map) ; defined below
6884 (defun org-get-location (buf help)
6885 "Let the user select a location in the Org-mode buffer BUF.
6886 This function uses a recursive edit. It returns the selected position
6887 or nil."
6888 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6889 (isearch-hide-immediately nil)
6890 (isearch-search-fun-function
6891 (lambda () 'org-goto-local-search-headings))
6892 (org-goto-selected-point org-goto-exit-command)
6893 (pop-up-frames nil)
6894 (special-display-buffer-names nil)
6895 (special-display-regexps nil)
6896 (special-display-function nil))
6897 (save-excursion
6898 (save-window-excursion
6899 (delete-other-windows)
6900 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6901 (org-pop-to-buffer-same-window
6902 (condition-case nil
6903 (make-indirect-buffer (current-buffer) "*org-goto*")
6904 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6905 (with-output-to-temp-buffer "*Help*"
6906 (princ help))
6907 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6908 (setq buffer-read-only nil)
6909 (let ((org-startup-truncated t)
6910 (org-startup-folded nil)
6911 (org-startup-align-all-tables nil))
6912 (org-mode)
6913 (org-overview))
6914 (setq buffer-read-only t)
6915 (if (and (boundp 'org-goto-start-pos)
6916 (integer-or-marker-p org-goto-start-pos))
6917 (let ((org-show-hierarchy-above t)
6918 (org-show-siblings t)
6919 (org-show-following-heading t))
6920 (goto-char org-goto-start-pos)
6921 (and (outline-invisible-p) (org-show-context)))
6922 (goto-char (point-min)))
6923 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6924 (message "Select location and press RET")
6925 (use-local-map org-goto-map)
6926 (recursive-edit)
6928 (kill-buffer "*org-goto*")
6929 (cons org-goto-selected-point org-goto-exit-command)))
6931 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6932 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6933 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6934 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6936 (defun org-goto-local-search-headings (string bound noerror)
6937 "Search and make sure that any matches are in headlines."
6938 (catch 'return
6939 (while (if isearch-forward
6940 (search-forward string bound noerror)
6941 (search-backward string bound noerror))
6942 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6943 (and (member :headline context)
6944 (not (member :tags context))))
6945 (throw 'return (point))))))
6947 (defun org-goto-local-auto-isearch ()
6948 "Start isearch."
6949 (interactive)
6950 (goto-char (point-min))
6951 (let ((keys (this-command-keys)))
6952 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6953 (isearch-mode t)
6954 (isearch-process-search-char (string-to-char keys)))))
6956 (defun org-goto-ret (&optional arg)
6957 "Finish `org-goto' by going to the new location."
6958 (interactive "P")
6959 (setq org-goto-selected-point (point)
6960 org-goto-exit-command 'return)
6961 (throw 'exit nil))
6963 (defun org-goto-left ()
6964 "Finish `org-goto' by going to the new location."
6965 (interactive)
6966 (if (org-at-heading-p)
6967 (progn
6968 (beginning-of-line 1)
6969 (setq org-goto-selected-point (point)
6970 org-goto-exit-command 'left)
6971 (throw 'exit nil))
6972 (error "Not on a heading")))
6974 (defun org-goto-right ()
6975 "Finish `org-goto' by going to the new location."
6976 (interactive)
6977 (if (org-at-heading-p)
6978 (progn
6979 (setq org-goto-selected-point (point)
6980 org-goto-exit-command 'right)
6981 (throw 'exit nil))
6982 (error "Not on a heading")))
6984 (defun org-goto-quit ()
6985 "Finish `org-goto' without cursor motion."
6986 (interactive)
6987 (setq org-goto-selected-point nil)
6988 (setq org-goto-exit-command 'quit)
6989 (throw 'exit nil))
6991 ;;; Indirect buffer display of subtrees
6993 (defvar org-indirect-dedicated-frame nil
6994 "This is the frame being used for indirect tree display.")
6995 (defvar org-last-indirect-buffer nil)
6997 (defun org-tree-to-indirect-buffer (&optional arg)
6998 "Create indirect buffer and narrow it to current subtree.
6999 With a numerical prefix ARG, go up to this level and then take that tree.
7000 If ARG is negative, go up that many levels.
7002 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7003 indirect buffer previously made with this command, to avoid proliferation of
7004 indirect buffers. However, when you call the command with a \
7005 \\[universal-argument] prefix, or
7006 when `org-indirect-buffer-display' is `new-frame', the last buffer
7007 is kept so that you can work with several indirect buffers at the same time.
7008 If `org-indirect-buffer-display' is `dedicated-frame', the \
7009 \\[universal-argument] prefix also
7010 requests that a new frame be made for the new buffer, so that the dedicated
7011 frame is not changed."
7012 (interactive "P")
7013 (let ((cbuf (current-buffer))
7014 (cwin (selected-window))
7015 (pos (point))
7016 beg end level heading ibuf)
7017 (save-excursion
7018 (org-back-to-heading t)
7019 (when (numberp arg)
7020 (setq level (org-outline-level))
7021 (if (< arg 0) (setq arg (+ level arg)))
7022 (while (> (setq level (org-outline-level)) arg)
7023 (org-up-heading-safe)))
7024 (setq beg (point)
7025 heading (org-get-heading))
7026 (org-end-of-subtree t t)
7027 (if (org-at-heading-p) (backward-char 1))
7028 (setq end (point)))
7029 (if (and (buffer-live-p org-last-indirect-buffer)
7030 (not (eq org-indirect-buffer-display 'new-frame))
7031 (not arg))
7032 (kill-buffer org-last-indirect-buffer))
7033 (setq ibuf (org-get-indirect-buffer cbuf)
7034 org-last-indirect-buffer ibuf)
7035 (cond
7036 ((or (eq org-indirect-buffer-display 'new-frame)
7037 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7038 (select-frame (make-frame))
7039 (delete-other-windows)
7040 (org-pop-to-buffer-same-window ibuf)
7041 (org-set-frame-title heading))
7042 ((eq org-indirect-buffer-display 'dedicated-frame)
7043 (raise-frame
7044 (select-frame (or (and org-indirect-dedicated-frame
7045 (frame-live-p org-indirect-dedicated-frame)
7046 org-indirect-dedicated-frame)
7047 (setq org-indirect-dedicated-frame (make-frame)))))
7048 (delete-other-windows)
7049 (org-pop-to-buffer-same-window ibuf)
7050 (org-set-frame-title (concat "Indirect: " heading)))
7051 ((eq org-indirect-buffer-display 'current-window)
7052 (org-pop-to-buffer-same-window ibuf))
7053 ((eq org-indirect-buffer-display 'other-window)
7054 (pop-to-buffer ibuf))
7055 (t (error "Invalid value")))
7056 (if (featurep 'xemacs)
7057 (save-excursion (org-mode) (turn-on-font-lock)))
7058 (narrow-to-region beg end)
7059 (show-all)
7060 (goto-char pos)
7061 (run-hook-with-args 'org-cycle-hook 'all)
7062 (and (window-live-p cwin) (select-window cwin))))
7064 (defun org-get-indirect-buffer (&optional buffer)
7065 (setq buffer (or buffer (current-buffer)))
7066 (let ((n 1) (base (buffer-name buffer)) bname)
7067 (while (buffer-live-p
7068 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7069 (setq n (1+ n)))
7070 (condition-case nil
7071 (make-indirect-buffer buffer bname 'clone)
7072 (error (make-indirect-buffer buffer bname)))))
7074 (defun org-set-frame-title (title)
7075 "Set the title of the current frame to the string TITLE."
7076 ;; FIXME: how to name a single frame in XEmacs???
7077 (unless (featurep 'xemacs)
7078 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7080 ;;;; Structure editing
7082 ;;; Inserting headlines
7084 (defun org-previous-line-empty-p ()
7085 (save-excursion
7086 (and (not (bobp))
7087 (or (beginning-of-line 0) t)
7088 (save-match-data
7089 (looking-at "[ \t]*$")))))
7091 (defun org-insert-heading (&optional force-heading invisible-ok)
7092 "Insert a new heading or item with same depth at point.
7093 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7094 If point is at the beginning of a headline, insert a sibling before the
7095 current headline. If point is not at the beginning, split the line,
7096 create the new headline with the text in the current line after point
7097 \(but see also the variable `org-M-RET-may-split-line').
7099 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7100 This is important for non-interactive uses of the command."
7101 (interactive "P")
7102 (if (or (= (buffer-size) 0)
7103 (and (not (save-excursion
7104 (and (ignore-errors (org-back-to-heading invisible-ok))
7105 (org-at-heading-p))))
7106 (or force-heading (not (org-in-item-p)))))
7107 (progn
7108 (insert "\n* ")
7109 (run-hooks 'org-insert-heading-hook))
7110 (when (or force-heading (not (org-insert-item)))
7111 (let* ((empty-line-p nil)
7112 (level nil)
7113 (on-heading (org-at-heading-p))
7114 (head (save-excursion
7115 (condition-case nil
7116 (progn
7117 (org-back-to-heading invisible-ok)
7118 (when (and (not on-heading)
7119 (featurep 'org-inlinetask)
7120 (integerp org-inlinetask-min-level)
7121 (>= (length (match-string 0))
7122 org-inlinetask-min-level))
7123 ;; Find a heading level before the inline task
7124 (while (and (setq level (org-up-heading-safe))
7125 (>= level org-inlinetask-min-level)))
7126 (if (org-at-heading-p)
7127 (org-back-to-heading invisible-ok)
7128 (error "This should not happen")))
7129 (setq empty-line-p (org-previous-line-empty-p))
7130 (match-string 0))
7131 (error "*"))))
7132 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7133 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7134 pos hide-previous previous-pos)
7135 (cond
7136 ((and (org-at-heading-p) (bolp)
7137 (or (bobp)
7138 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7139 ;; insert before the current line
7140 (open-line (if blank 2 1)))
7141 ((and (bolp)
7142 (not org-insert-heading-respect-content)
7143 (or (bobp)
7144 (save-excursion
7145 (backward-char 1) (not (outline-invisible-p)))))
7146 ;; insert right here
7147 nil)
7149 ;; somewhere in the line
7150 (save-excursion
7151 (setq previous-pos (point-at-bol))
7152 (end-of-line)
7153 (setq hide-previous (outline-invisible-p)))
7154 (and org-insert-heading-respect-content (org-show-subtree))
7155 (let ((split
7156 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7157 (save-excursion
7158 (let ((p (point)))
7159 (goto-char (point-at-bol))
7160 (and (looking-at org-complex-heading-regexp)
7161 (match-beginning 4)
7162 (> p (match-beginning 4)))))))
7163 tags pos)
7164 (cond
7165 (org-insert-heading-respect-content
7166 (org-end-of-subtree nil t)
7167 (when (featurep 'org-inlinetask)
7168 (while (and (not (eobp))
7169 (looking-at "\\(\\*+\\)[ \t]+")
7170 (>= (length (match-string 1))
7171 org-inlinetask-min-level))
7172 (org-end-of-subtree nil t)))
7173 (or (bolp) (newline))
7174 (or (org-previous-line-empty-p)
7175 (and blank (newline)))
7176 (open-line 1))
7177 ((org-at-heading-p)
7178 (when hide-previous
7179 (show-children)
7180 (org-show-entry))
7181 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7182 (setq tags (and (match-end 2) (match-string 2)))
7183 (and (match-end 1)
7184 (delete-region (match-beginning 1) (match-end 1)))
7185 (setq pos (point-at-bol))
7186 (or split (end-of-line 1))
7187 (delete-horizontal-space)
7188 (if (string-match "\\`\\*+\\'"
7189 (buffer-substring (point-at-bol) (point)))
7190 (insert " "))
7191 (newline (if blank 2 1))
7192 (when tags
7193 (save-excursion
7194 (goto-char pos)
7195 (end-of-line 1)
7196 (insert " " tags)
7197 (org-set-tags nil 'align))))
7199 (or split (end-of-line 1))
7200 (newline (if blank 2 1)))))))
7201 (insert head) (just-one-space)
7202 (setq pos (point))
7203 (end-of-line 1)
7204 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7205 (when (and org-insert-heading-respect-content hide-previous)
7206 (save-excursion
7207 (goto-char previous-pos)
7208 (hide-subtree)))
7209 (run-hooks 'org-insert-heading-hook)))))
7211 (defun org-get-heading (&optional no-tags no-todo)
7212 "Return the heading of the current entry, without the stars.
7213 When NO-TAGS is non-nil, don't include tags.
7214 When NO-TODO is non-nil, don't include TODO keywords."
7215 (save-excursion
7216 (org-back-to-heading t)
7217 (cond
7218 ((and no-tags no-todo)
7219 (looking-at org-complex-heading-regexp)
7220 (match-string 4))
7221 (no-tags
7222 (looking-at (concat org-outline-regexp
7223 "\\(.*?\\)"
7224 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7225 (match-string 1))
7226 (no-todo
7227 (looking-at org-todo-line-regexp)
7228 (match-string 3))
7229 (t (looking-at org-heading-regexp)
7230 (match-string 2)))))
7232 (defun org-heading-components ()
7233 "Return the components of the current heading.
7234 This is a list with the following elements:
7235 - the level as an integer
7236 - the reduced level, different if `org-odd-levels-only' is set.
7237 - the TODO keyword, or nil
7238 - the priority character, like ?A, or nil if no priority is given
7239 - the headline text itself, or the tags string if no headline text
7240 - the tags string, or nil."
7241 (save-excursion
7242 (org-back-to-heading t)
7243 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7244 (list (length (match-string 1))
7245 (org-reduced-level (length (match-string 1)))
7246 (org-match-string-no-properties 2)
7247 (and (match-end 3) (aref (match-string 3) 2))
7248 (org-match-string-no-properties 4)
7249 (org-match-string-no-properties 5)))))
7251 (defun org-get-entry ()
7252 "Get the entry text, after heading, entire subtree."
7253 (save-excursion
7254 (org-back-to-heading t)
7255 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7257 (defun org-insert-heading-after-current ()
7258 "Insert a new heading with same level as current, after current subtree."
7259 (interactive)
7260 (org-back-to-heading)
7261 (org-insert-heading)
7262 (org-move-subtree-down)
7263 (end-of-line 1))
7265 (defun org-insert-heading-respect-content ()
7266 (interactive)
7267 (let ((org-insert-heading-respect-content t))
7268 (org-insert-heading t)))
7270 (defun org-insert-todo-heading-respect-content (&optional force-state)
7271 (interactive "P")
7272 (let ((org-insert-heading-respect-content t))
7273 (org-insert-todo-heading force-state t)))
7275 (defun org-insert-todo-heading (arg &optional force-heading)
7276 "Insert a new heading with the same level and TODO state as current heading.
7277 If the heading has no TODO state, or if the state is DONE, use the first
7278 state (TODO by default). Also with prefix arg, force first state."
7279 (interactive "P")
7280 (when (or force-heading (not (org-insert-item 'checkbox)))
7281 (org-insert-heading force-heading)
7282 (save-excursion
7283 (org-back-to-heading)
7284 (outline-previous-heading)
7285 (looking-at org-todo-line-regexp))
7286 (let*
7287 ((new-mark-x
7288 (if (or arg
7289 (not (match-beginning 2))
7290 (member (match-string 2) org-done-keywords))
7291 (car org-todo-keywords-1)
7292 (match-string 2)))
7293 (new-mark
7295 (run-hook-with-args-until-success
7296 'org-todo-get-default-hook new-mark-x nil)
7297 new-mark-x)))
7298 (beginning-of-line 1)
7299 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7300 (if org-treat-insert-todo-heading-as-state-change
7301 (org-todo new-mark)
7302 (insert new-mark " "))))
7303 (when org-provide-todo-statistics
7304 (org-update-parent-todo-statistics))))
7306 (defun org-insert-subheading (arg)
7307 "Insert a new subheading and demote it.
7308 Works for outline headings and for plain lists alike."
7309 (interactive "P")
7310 (org-insert-heading arg)
7311 (cond
7312 ((org-at-heading-p) (org-do-demote))
7313 ((org-at-item-p) (org-indent-item))))
7315 (defun org-insert-todo-subheading (arg)
7316 "Insert a new subheading with TODO keyword or checkbox and demote it.
7317 Works for outline headings and for plain lists alike."
7318 (interactive "P")
7319 (org-insert-todo-heading arg)
7320 (cond
7321 ((org-at-heading-p) (org-do-demote))
7322 ((org-at-item-p) (org-indent-item))))
7324 ;;; Promotion and Demotion
7326 (defvar org-after-demote-entry-hook nil
7327 "Hook run after an entry has been demoted.
7328 The cursor will be at the beginning of the entry.
7329 When a subtree is being demoted, the hook will be called for each node.")
7331 (defvar org-after-promote-entry-hook nil
7332 "Hook run after an entry has been promoted.
7333 The cursor will be at the beginning of the entry.
7334 When a subtree is being promoted, the hook will be called for each node.")
7336 (defun org-promote-subtree ()
7337 "Promote the entire subtree.
7338 See also `org-promote'."
7339 (interactive)
7340 (save-excursion
7341 (org-with-limited-levels (org-map-tree 'org-promote)))
7342 (org-fix-position-after-promote))
7344 (defun org-demote-subtree ()
7345 "Demote the entire subtree. See `org-demote'.
7346 See also `org-promote'."
7347 (interactive)
7348 (save-excursion
7349 (org-with-limited-levels (org-map-tree 'org-demote)))
7350 (org-fix-position-after-promote))
7353 (defun org-do-promote ()
7354 "Promote the current heading higher up the tree.
7355 If the region is active in `transient-mark-mode', promote all headings
7356 in the region."
7357 (interactive)
7358 (save-excursion
7359 (if (org-region-active-p)
7360 (org-map-region 'org-promote (region-beginning) (region-end))
7361 (org-promote)))
7362 (org-fix-position-after-promote))
7364 (defun org-do-demote ()
7365 "Demote the current heading lower down the tree.
7366 If the region is active in `transient-mark-mode', demote all headings
7367 in the region."
7368 (interactive)
7369 (save-excursion
7370 (if (org-region-active-p)
7371 (org-map-region 'org-demote (region-beginning) (region-end))
7372 (org-demote)))
7373 (org-fix-position-after-promote))
7375 (defun org-fix-position-after-promote ()
7376 "Make sure that after pro/demotion cursor position is right."
7377 (let ((pos (point)))
7378 (when (save-excursion
7379 (beginning-of-line 1)
7380 (looking-at org-todo-line-regexp)
7381 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7382 (cond ((eobp) (insert " "))
7383 ((eolp) (insert " "))
7384 ((equal (char-after) ?\ ) (forward-char 1))))))
7386 (defun org-current-level ()
7387 "Return the level of the current entry, or nil if before the first headline.
7388 The level is the number of stars at the beginning of the headline."
7389 (save-excursion
7390 (org-with-limited-levels
7391 (if (ignore-errors (org-back-to-heading t))
7392 (funcall outline-level)))))
7394 (defun org-get-previous-line-level ()
7395 "Return the outline depth of the last headline before the current line.
7396 Returns 0 for the first headline in the buffer, and nil if before the
7397 first headline."
7398 (let ((current-level (org-current-level))
7399 (prev-level (when (> (line-number-at-pos) 1)
7400 (save-excursion
7401 (beginning-of-line 0)
7402 (org-current-level)))))
7403 (cond ((null current-level) nil) ; Before first headline
7404 ((null prev-level) 0) ; At first headline
7405 (prev-level))))
7407 (defun org-reduced-level (l)
7408 "Compute the effective level of a heading.
7409 This takes into account the setting of `org-odd-levels-only'."
7410 (cond
7411 ((zerop l) 0)
7412 (org-odd-levels-only (1+ (floor (/ l 2))))
7413 (t l)))
7415 (defun org-level-increment ()
7416 "Return the number of stars that will be added or removed at a
7417 time to headlines when structure editing, based on the value of
7418 `org-odd-levels-only'."
7419 (if org-odd-levels-only 2 1))
7421 (defun org-get-valid-level (level &optional change)
7422 "Rectify a level change under the influence of `org-odd-levels-only'
7423 LEVEL is a current level, CHANGE is by how much the level should be
7424 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7425 even level numbers will become the next higher odd number."
7426 (if org-odd-levels-only
7427 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7428 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7429 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7430 (max 1 (+ level (or change 0)))))
7432 (if (boundp 'define-obsolete-function-alias)
7433 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7434 (define-obsolete-function-alias 'org-get-legal-level
7435 'org-get-valid-level)
7436 (define-obsolete-function-alias 'org-get-legal-level
7437 'org-get-valid-level "23.1")))
7439 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7440 ;; ̀org-with-limited-levels'
7441 (defun org-promote ()
7442 "Promote the current heading higher up the tree.
7443 If the region is active in `transient-mark-mode', promote all headings
7444 in the region."
7445 (org-back-to-heading t)
7446 (let* ((level (save-match-data (funcall outline-level)))
7447 (after-change-functions (remove 'flyspell-after-change-function
7448 after-change-functions))
7449 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7450 (diff (abs (- level (length up-head) -1))))
7451 (cond ((and (= level 1) org-called-with-limited-levels
7452 org-allow-promoting-top-level-subtree)
7453 (replace-match "# " nil t))
7454 ((= level 1)
7455 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7456 (t (replace-match up-head nil t)))
7457 ;; Fixup tag positioning
7458 (unless (= level 1)
7459 (and org-auto-align-tags (org-set-tags nil t))
7460 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7461 (run-hooks 'org-after-promote-entry-hook)))
7463 (defun org-demote ()
7464 "Demote the current heading lower down the tree.
7465 If the region is active in `transient-mark-mode', demote all headings
7466 in the region."
7467 (org-back-to-heading t)
7468 (let* ((level (save-match-data (funcall outline-level)))
7469 (after-change-functions (remove 'flyspell-after-change-function
7470 after-change-functions))
7471 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7472 (diff (abs (- level (length down-head) -1))))
7473 (replace-match down-head nil t)
7474 ;; Fixup tag positioning
7475 (and org-auto-align-tags (org-set-tags nil t))
7476 (if org-adapt-indentation (org-fixup-indentation diff))
7477 (run-hooks 'org-after-demote-entry-hook)))
7479 (defun org-cycle-level ()
7480 "Cycle the level of an empty headline through possible states.
7481 This goes first to child, then to parent, level, then up the hierarchy.
7482 After top level, it switches back to sibling level."
7483 (interactive)
7484 (let ((org-adapt-indentation nil))
7485 (when (org-point-at-end-of-empty-headline)
7486 (setq this-command 'org-cycle-level) ; Only needed for caching
7487 (let ((cur-level (org-current-level))
7488 (prev-level (org-get-previous-line-level)))
7489 (cond
7490 ;; If first headline in file, promote to top-level.
7491 ((= prev-level 0)
7492 (loop repeat (/ (- cur-level 1) (org-level-increment))
7493 do (org-do-promote)))
7494 ;; If same level as prev, demote one.
7495 ((= prev-level cur-level)
7496 (org-do-demote))
7497 ;; If parent is top-level, promote to top level if not already.
7498 ((= prev-level 1)
7499 (loop repeat (/ (- cur-level 1) (org-level-increment))
7500 do (org-do-promote)))
7501 ;; If top-level, return to prev-level.
7502 ((= cur-level 1)
7503 (loop repeat (/ (- prev-level 1) (org-level-increment))
7504 do (org-do-demote)))
7505 ;; If less than prev-level, promote one.
7506 ((< cur-level prev-level)
7507 (org-do-promote))
7508 ;; If deeper than prev-level, promote until higher than
7509 ;; prev-level.
7510 ((> cur-level prev-level)
7511 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7512 do (org-do-promote))))
7513 t))))
7515 (defun org-map-tree (fun)
7516 "Call FUN for every heading underneath the current one."
7517 (org-back-to-heading)
7518 (let ((level (funcall outline-level)))
7519 (save-excursion
7520 (funcall fun)
7521 (while (and (progn
7522 (outline-next-heading)
7523 (> (funcall outline-level) level))
7524 (not (eobp)))
7525 (funcall fun)))))
7527 (defun org-map-region (fun beg end)
7528 "Call FUN for every heading between BEG and END."
7529 (let ((org-ignore-region t))
7530 (save-excursion
7531 (setq end (copy-marker end))
7532 (goto-char beg)
7533 (if (and (re-search-forward org-outline-regexp-bol nil t)
7534 (< (point) end))
7535 (funcall fun))
7536 (while (and (progn
7537 (outline-next-heading)
7538 (< (point) end))
7539 (not (eobp)))
7540 (funcall fun)))))
7542 (defvar org-property-end-re) ; silence byte-compiler
7543 (defun org-fixup-indentation (diff)
7544 "Change the indentation in the current entry by DIFF.
7545 However, if any line in the current entry has no indentation, or if it
7546 would end up with no indentation after the change, nothing at all is done."
7547 (save-excursion
7548 (let ((end (save-excursion (outline-next-heading)
7549 (point-marker)))
7550 (prohibit (if (> diff 0)
7551 "^\\S-"
7552 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7553 col)
7554 (unless (save-excursion (end-of-line 1)
7555 (re-search-forward prohibit end t))
7556 (while (and (< (point) end)
7557 (re-search-forward "^[ \t]+" end t))
7558 (goto-char (match-end 0))
7559 (setq col (current-column))
7560 (if (< diff 0) (replace-match ""))
7561 (org-indent-to-column (+ diff col))))
7562 (move-marker end nil))))
7564 (defun org-convert-to-odd-levels ()
7565 "Convert an org-mode file with all levels allowed to one with odd levels.
7566 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7567 level 5 etc."
7568 (interactive)
7569 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7570 (let ((outline-level 'org-outline-level)
7571 (org-odd-levels-only nil) n)
7572 (save-excursion
7573 (goto-char (point-min))
7574 (while (re-search-forward "^\\*\\*+ " nil t)
7575 (setq n (- (length (match-string 0)) 2))
7576 (while (>= (setq n (1- n)) 0)
7577 (org-demote))
7578 (end-of-line 1))))))
7580 (defun org-convert-to-oddeven-levels ()
7581 "Convert an org-mode file with only odd levels to one with odd/even levels.
7582 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7583 file contains a section with an even level, conversion would
7584 destroy the structure of the file. An error is signaled in this
7585 case."
7586 (interactive)
7587 (goto-char (point-min))
7588 ;; First check if there are no even levels
7589 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7590 (org-show-context t)
7591 (error "Not all levels are odd in this file. Conversion not possible"))
7592 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7593 (let ((outline-regexp org-outline-regexp)
7594 (outline-level 'org-outline-level)
7595 (org-odd-levels-only nil) n)
7596 (save-excursion
7597 (goto-char (point-min))
7598 (while (re-search-forward "^\\*\\*+ " nil t)
7599 (setq n (/ (1- (length (match-string 0))) 2))
7600 (while (>= (setq n (1- n)) 0)
7601 (org-promote))
7602 (end-of-line 1))))))
7604 (defun org-tr-level (n)
7605 "Make N odd if required."
7606 (if org-odd-levels-only (1+ (/ n 2)) n))
7608 ;;; Vertical tree motion, cutting and pasting of subtrees
7610 (defun org-move-subtree-up (&optional arg)
7611 "Move the current subtree up past ARG headlines of the same level."
7612 (interactive "p")
7613 (org-move-subtree-down (- (prefix-numeric-value arg))))
7615 (defun org-move-subtree-down (&optional arg)
7616 "Move the current subtree down past ARG headlines of the same level."
7617 (interactive "p")
7618 (setq arg (prefix-numeric-value arg))
7619 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7620 'org-get-last-sibling))
7621 (ins-point (make-marker))
7622 (cnt (abs arg))
7623 (col (current-column))
7624 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7625 ;; Select the tree
7626 (org-back-to-heading)
7627 (setq beg0 (point))
7628 (save-excursion
7629 (setq ne-beg (org-back-over-empty-lines))
7630 (setq beg (point)))
7631 (save-match-data
7632 (save-excursion (outline-end-of-heading)
7633 (setq folded (outline-invisible-p)))
7634 (outline-end-of-subtree))
7635 (outline-next-heading)
7636 (setq ne-end (org-back-over-empty-lines))
7637 (setq end (point))
7638 (goto-char beg0)
7639 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7640 ;; include less whitespace
7641 (save-excursion
7642 (goto-char beg)
7643 (forward-line (- ne-beg ne-end))
7644 (setq beg (point))))
7645 ;; Find insertion point, with error handling
7646 (while (> cnt 0)
7647 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7648 (progn (goto-char beg0)
7649 (error "Cannot move past superior level or buffer limit")))
7650 (setq cnt (1- cnt)))
7651 (if (> arg 0)
7652 ;; Moving forward - still need to move over subtree
7653 (progn (org-end-of-subtree t t)
7654 (save-excursion
7655 (org-back-over-empty-lines)
7656 (or (bolp) (newline)))))
7657 (setq ne-ins (org-back-over-empty-lines))
7658 (move-marker ins-point (point))
7659 (setq txt (buffer-substring beg end))
7660 (org-save-markers-in-region beg end)
7661 (delete-region beg end)
7662 (org-remove-empty-overlays-at beg)
7663 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7664 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7665 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7666 (let ((bbb (point)))
7667 (insert-before-markers txt)
7668 (org-reinstall-markers-in-region bbb)
7669 (move-marker ins-point bbb))
7670 (or (bolp) (insert "\n"))
7671 (setq ins-end (point))
7672 (goto-char ins-point)
7673 (org-skip-whitespace)
7674 (when (and (< arg 0)
7675 (org-first-sibling-p)
7676 (> ne-ins ne-beg))
7677 ;; Move whitespace back to beginning
7678 (save-excursion
7679 (goto-char ins-end)
7680 (let ((kill-whole-line t))
7681 (kill-line (- ne-ins ne-beg)) (point)))
7682 (insert (make-string (- ne-ins ne-beg) ?\n)))
7683 (move-marker ins-point nil)
7684 (if folded
7685 (hide-subtree)
7686 (org-show-entry)
7687 (show-children)
7688 (org-cycle-hide-drawers 'children))
7689 (org-clean-visibility-after-subtree-move)
7690 ;; move back to the initial column we were at
7691 (move-to-column col)))
7693 (defvar org-subtree-clip ""
7694 "Clipboard for cut and paste of subtrees.
7695 This is actually only a copy of the kill, because we use the normal kill
7696 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7698 (defvar org-subtree-clip-folded nil
7699 "Was the last copied subtree folded?
7700 This is used to fold the tree back after pasting.")
7702 (defun org-cut-subtree (&optional n)
7703 "Cut the current subtree into the clipboard.
7704 With prefix arg N, cut this many sequential subtrees.
7705 This is a short-hand for marking the subtree and then cutting it."
7706 (interactive "p")
7707 (org-copy-subtree n 'cut))
7709 (defun org-copy-subtree (&optional n cut force-store-markers)
7710 "Cut the current subtree into the clipboard.
7711 With prefix arg N, cut this many sequential subtrees.
7712 This is a short-hand for marking the subtree and then copying it.
7713 If CUT is non-nil, actually cut the subtree.
7714 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7715 of some markers in the region, even if CUT is non-nil. This is
7716 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7717 (interactive "p")
7718 (let (beg end folded (beg0 (point)))
7719 (if (org-called-interactively-p 'any)
7720 (org-back-to-heading nil) ; take what looks like a subtree
7721 (org-back-to-heading t)) ; take what is really there
7722 (org-back-over-empty-lines)
7723 (setq beg (point))
7724 (skip-chars-forward " \t\r\n")
7725 (save-match-data
7726 (save-excursion (outline-end-of-heading)
7727 (setq folded (outline-invisible-p)))
7728 (condition-case nil
7729 (org-forward-heading-same-level (1- n) t)
7730 (error nil))
7731 (org-end-of-subtree t t))
7732 (org-back-over-empty-lines)
7733 (setq end (point))
7734 (goto-char beg0)
7735 (when (> end beg)
7736 (setq org-subtree-clip-folded folded)
7737 (when (or cut force-store-markers)
7738 (org-save-markers-in-region beg end))
7739 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7740 (setq org-subtree-clip (current-kill 0))
7741 (message "%s: Subtree(s) with %d characters"
7742 (if cut "Cut" "Copied")
7743 (length org-subtree-clip)))))
7745 (defun org-paste-subtree (&optional level tree for-yank)
7746 "Paste the clipboard as a subtree, with modification of headline level.
7747 The entire subtree is promoted or demoted in order to match a new headline
7748 level.
7750 If the cursor is at the beginning of a headline, the same level as
7751 that headline is used to paste the tree
7753 If not, the new level is derived from the *visible* headings
7754 before and after the insertion point, and taken to be the inferior headline
7755 level of the two. So if the previous visible heading is level 3 and the
7756 next is level 4 (or vice versa), level 4 will be used for insertion.
7757 This makes sure that the subtree remains an independent subtree and does
7758 not swallow low level entries.
7760 You can also force a different level, either by using a numeric prefix
7761 argument, or by inserting the heading marker by hand. For example, if the
7762 cursor is after \"*****\", then the tree will be shifted to level 5.
7764 If optional TREE is given, use this text instead of the kill ring.
7766 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7767 move back over whitespace before inserting, and move point to the end of
7768 the inserted text when done."
7769 (interactive "P")
7770 (setq tree (or tree (and kill-ring (current-kill 0))))
7771 (unless (org-kill-is-subtree-p tree)
7772 (error "%s"
7773 (substitute-command-keys
7774 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7775 (org-with-limited-levels
7776 (let* ((visp (not (outline-invisible-p)))
7777 (txt tree)
7778 (^re_ "\\(\\*+\\)[ \t]*")
7779 (old-level (if (string-match org-outline-regexp-bol txt)
7780 (- (match-end 0) (match-beginning 0) 1)
7781 -1))
7782 (force-level (cond (level (prefix-numeric-value level))
7783 ((and (looking-at "[ \t]*$")
7784 (string-match
7785 "^\\*+$" (buffer-substring
7786 (point-at-bol) (point))))
7787 (- (match-end 1) (match-beginning 1)))
7788 ((and (bolp)
7789 (looking-at org-outline-regexp))
7790 (- (match-end 0) (point) 1))))
7791 (previous-level (save-excursion
7792 (condition-case nil
7793 (progn
7794 (outline-previous-visible-heading 1)
7795 (if (looking-at ^re_)
7796 (- (match-end 0) (match-beginning 0) 1)
7798 (error 1))))
7799 (next-level (save-excursion
7800 (condition-case nil
7801 (progn
7802 (or (looking-at org-outline-regexp)
7803 (outline-next-visible-heading 1))
7804 (if (looking-at ^re_)
7805 (- (match-end 0) (match-beginning 0) 1)
7807 (error 1))))
7808 (new-level (or force-level (max previous-level next-level)))
7809 (shift (if (or (= old-level -1)
7810 (= new-level -1)
7811 (= old-level new-level))
7813 (- new-level old-level)))
7814 (delta (if (> shift 0) -1 1))
7815 (func (if (> shift 0) 'org-demote 'org-promote))
7816 (org-odd-levels-only nil)
7817 beg end newend)
7818 ;; Remove the forced level indicator
7819 (if force-level
7820 (delete-region (point-at-bol) (point)))
7821 ;; Paste
7822 (beginning-of-line (if (bolp) 1 2))
7823 (unless for-yank (org-back-over-empty-lines))
7824 (setq beg (point))
7825 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7826 (insert-before-markers txt)
7827 (unless (string-match "\n\\'" txt) (insert "\n"))
7828 (setq newend (point))
7829 (org-reinstall-markers-in-region beg)
7830 (setq end (point))
7831 (goto-char beg)
7832 (skip-chars-forward " \t\n\r")
7833 (setq beg (point))
7834 (if (and (outline-invisible-p) visp)
7835 (save-excursion (outline-show-heading)))
7836 ;; Shift if necessary
7837 (unless (= shift 0)
7838 (save-restriction
7839 (narrow-to-region beg end)
7840 (while (not (= shift 0))
7841 (org-map-region func (point-min) (point-max))
7842 (setq shift (+ delta shift)))
7843 (goto-char (point-min))
7844 (setq newend (point-max))))
7845 (when (or (org-called-interactively-p 'interactive) for-yank)
7846 (message "Clipboard pasted as level %d subtree" new-level))
7847 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7848 kill-ring
7849 (eq org-subtree-clip (current-kill 0))
7850 org-subtree-clip-folded)
7851 ;; The tree was folded before it was killed/copied
7852 (hide-subtree))
7853 (and for-yank (goto-char newend)))))
7855 (defun org-kill-is-subtree-p (&optional txt)
7856 "Check if the current kill is an outline subtree, or a set of trees.
7857 Returns nil if kill does not start with a headline, or if the first
7858 headline level is not the largest headline level in the tree.
7859 So this will actually accept several entries of equal levels as well,
7860 which is OK for `org-paste-subtree'.
7861 If optional TXT is given, check this string instead of the current kill."
7862 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7863 (re (org-get-limited-outline-regexp))
7864 (^re (concat "^" re))
7865 (start-level (and kill
7866 (string-match
7867 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7868 kill)
7869 (- (match-end 2) (match-beginning 2) 1)))
7870 (start (1+ (or (match-beginning 2) -1))))
7871 (if (not start-level)
7872 (progn
7873 nil) ;; does not even start with a heading
7874 (catch 'exit
7875 (while (setq start (string-match ^re kill (1+ start)))
7876 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7877 (throw 'exit nil)))
7878 t))))
7880 (defvar org-markers-to-move nil
7881 "Markers that should be moved with a cut-and-paste operation.
7882 Those markers are stored together with their positions relative to
7883 the start of the region.")
7885 (defun org-save-markers-in-region (beg end)
7886 "Check markers in region.
7887 If these markers are between BEG and END, record their position relative
7888 to BEG, so that after moving the block of text, we can put the markers back
7889 into place.
7890 This function gets called just before an entry or tree gets cut from the
7891 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7892 called immediately, to move the markers with the entries."
7893 (setq org-markers-to-move nil)
7894 (when (featurep 'org-clock)
7895 (org-clock-save-markers-for-cut-and-paste beg end))
7896 (when (featurep 'org-agenda)
7897 (org-agenda-save-markers-for-cut-and-paste beg end)))
7899 (defun org-check-and-save-marker (marker beg end)
7900 "Check if MARKER is between BEG and END.
7901 If yes, remember the marker and the distance to BEG."
7902 (when (and (marker-buffer marker)
7903 (equal (marker-buffer marker) (current-buffer)))
7904 (if (and (>= marker beg) (< marker end))
7905 (push (cons marker (- marker beg)) org-markers-to-move))))
7907 (defun org-reinstall-markers-in-region (beg)
7908 "Move all remembered markers to their position relative to BEG."
7909 (mapc (lambda (x)
7910 (move-marker (car x) (+ beg (cdr x))))
7911 org-markers-to-move)
7912 (setq org-markers-to-move nil))
7914 (defun org-narrow-to-subtree ()
7915 "Narrow buffer to the current subtree."
7916 (interactive)
7917 (save-excursion
7918 (save-match-data
7919 (org-with-limited-levels
7920 (narrow-to-region
7921 (progn (org-back-to-heading t) (point))
7922 (progn (org-end-of-subtree t t)
7923 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
7924 (point)))))))
7926 (defun org-narrow-to-block ()
7927 "Narrow buffer to the current block."
7928 (interactive)
7929 (let* ((case-fold-search t)
7930 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7931 "^[ \t]*#\\+end_.*")))
7932 (if blockp
7933 (narrow-to-region (car blockp) (cdr blockp))
7934 (error "Not in a block"))))
7936 (eval-when-compile
7937 (defvar org-property-drawer-re))
7939 (defvar org-property-start-re) ;; defined below
7940 (defun org-clone-subtree-with-time-shift (n &optional shift)
7941 "Clone the task (subtree) at point N times.
7942 The clones will be inserted as siblings.
7944 In interactive use, the user will be prompted for the number of
7945 clones to be produced, and for a time SHIFT, which may be a
7946 repeater as used in time stamps, for example `+3d'.
7948 When a valid repeater is given and the entry contains any time
7949 stamps, the clones will become a sequence in time, with time
7950 stamps in the subtree shifted for each clone produced. If SHIFT
7951 is nil or the empty string, time stamps will be left alone. The
7952 ID property of the original subtree is removed.
7954 If the original subtree did contain time stamps with a repeater,
7955 the following will happen:
7956 - the repeater will be removed in each clone
7957 - an additional clone will be produced, with the current, unshifted
7958 date(s) in the entry.
7959 - the original entry will be placed *after* all the clones, with
7960 repeater intact.
7961 - the start days in the repeater in the original entry will be shifted
7962 to past the last clone.
7963 In this way you can spell out a number of instances of a repeating task,
7964 and still retain the repeater to cover future instances of the task."
7965 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7966 (let (beg end template task idprop
7967 shift-n shift-what doshift nmin nmax (n-no-remove -1)
7968 (drawer-re org-drawer-regexp))
7969 (if (not (and (integerp n) (> n 0)))
7970 (error "Invalid number of replications %s" n))
7971 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7972 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
7973 shift)))
7974 (error "Invalid shift specification %s" shift))
7975 (when doshift
7976 (setq shift-n (string-to-number (match-string 1 shift))
7977 shift-what (cdr (assoc (match-string 2 shift)
7978 '(("d" . day) ("w" . week)
7979 ("m" . month) ("y" . year))))))
7980 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7981 (setq nmin 1 nmax n)
7982 (org-back-to-heading t)
7983 (setq beg (point))
7984 (setq idprop (org-entry-get nil "ID"))
7985 (org-end-of-subtree t t)
7986 (or (bolp) (insert "\n"))
7987 (setq end (point))
7988 (setq template (buffer-substring beg end))
7989 (when (and doshift
7990 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
7991 (delete-region beg end)
7992 (setq end beg)
7993 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7994 (goto-char end)
7995 (loop for n from nmin to nmax do
7996 ;; prepare clone
7997 (with-temp-buffer
7998 (insert template)
7999 (org-mode)
8000 (goto-char (point-min))
8001 (org-show-subtree)
8002 (and idprop (if org-clone-delete-id
8003 (org-entry-delete nil "ID")
8004 (org-id-get-create t)))
8005 (unless (= n 0)
8006 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8007 (kill-whole-line))
8008 (goto-char (point-min))
8009 (while (re-search-forward drawer-re nil t)
8010 (mapc (lambda (d)
8011 (org-remove-empty-drawer-at d (point))) org-drawers)))
8012 (goto-char (point-min))
8013 (when doshift
8014 (while (re-search-forward org-ts-regexp-both nil t)
8015 (org-timestamp-change (* n shift-n) shift-what))
8016 (unless (= n n-no-remove)
8017 (goto-char (point-min))
8018 (while (re-search-forward org-ts-regexp nil t)
8019 (save-excursion
8020 (goto-char (match-beginning 0))
8021 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8022 (delete-region (match-beginning 1) (match-end 1)))))))
8023 (setq task (buffer-string)))
8024 (insert task))
8025 (goto-char beg)))
8027 ;;; Outline Sorting
8029 (defun org-sort (with-case)
8030 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8031 Optional argument WITH-CASE means sort case-sensitively."
8032 (interactive "P")
8033 (cond
8034 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8035 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8037 (org-call-with-arg 'org-sort-entries with-case))))
8039 (defun org-sort-remove-invisible (s)
8040 (remove-text-properties 0 (length s) org-rm-props s)
8041 (while (string-match org-bracket-link-regexp s)
8042 (setq s (replace-match (if (match-end 2)
8043 (match-string 3 s)
8044 (match-string 1 s)) t t s)))
8047 (defvar org-priority-regexp) ; defined later in the file
8049 (defvar org-after-sorting-entries-or-items-hook nil
8050 "Hook that is run after a bunch of entries or items have been sorted.
8051 When children are sorted, the cursor is in the parent line when this
8052 hook gets called. When a region or a plain list is sorted, the cursor
8053 will be in the first entry of the sorted region/list.")
8055 (defun org-sort-entries
8056 (&optional with-case sorting-type getkey-func compare-func property)
8057 "Sort entries on a certain level of an outline tree.
8058 If there is an active region, the entries in the region are sorted.
8059 Else, if the cursor is before the first entry, sort the top-level items.
8060 Else, the children of the entry at point are sorted.
8062 Sorting can be alphabetically, numerically, by date/time as given by
8063 a time stamp, by a property or by priority.
8065 The command prompts for the sorting type unless it has been given to the
8066 function through the SORTING-TYPE argument, which needs to be a character,
8067 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8068 precise meaning of each character:
8070 n Numerically, by converting the beginning of the entry/item to a number.
8071 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8072 t By date/time, either the first active time stamp in the entry, or, if
8073 none exist, by the first inactive one.
8074 s By the scheduled date/time.
8075 d By deadline date/time.
8076 c By creation time, which is assumed to be the first inactive time stamp
8077 at the beginning of a line.
8078 p By priority according to the cookie.
8079 r By the value of a property.
8081 Capital letters will reverse the sort order.
8083 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8084 called with point at the beginning of the record. It must return either
8085 a string or a number that should serve as the sorting key for that record.
8087 Comparing entries ignores case by default. However, with an optional argument
8088 WITH-CASE, the sorting considers case as well."
8089 (interactive "P")
8090 (let ((case-func (if with-case 'identity 'downcase))
8091 start beg end stars re re2
8092 txt what tmp)
8093 ;; Find beginning and end of region to sort
8094 (cond
8095 ((org-region-active-p)
8096 ;; we will sort the region
8097 (setq end (region-end)
8098 what "region")
8099 (goto-char (region-beginning))
8100 (if (not (org-at-heading-p)) (outline-next-heading))
8101 (setq start (point)))
8102 ((or (org-at-heading-p)
8103 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8104 ;; we will sort the children of the current headline
8105 (org-back-to-heading)
8106 (setq start (point)
8107 end (progn (org-end-of-subtree t t)
8108 (or (bolp) (insert "\n"))
8109 (org-back-over-empty-lines)
8110 (point))
8111 what "children")
8112 (goto-char start)
8113 (show-subtree)
8114 (outline-next-heading))
8116 ;; we will sort the top-level entries in this file
8117 (goto-char (point-min))
8118 (or (org-at-heading-p) (outline-next-heading))
8119 (setq start (point))
8120 (goto-char (point-max))
8121 (beginning-of-line 1)
8122 (when (looking-at ".*?\\S-")
8123 ;; File ends in a non-white line
8124 (end-of-line 1)
8125 (insert "\n"))
8126 (setq end (point-max))
8127 (setq what "top-level")
8128 (goto-char start)
8129 (show-all)))
8131 (setq beg (point))
8132 (if (>= beg end) (error "Nothing to sort"))
8134 (looking-at "\\(\\*+\\)")
8135 (setq stars (match-string 1)
8136 re (concat "^" (regexp-quote stars) " +")
8137 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8138 txt (buffer-substring beg end))
8139 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8140 (if (and (not (equal stars "*")) (string-match re2 txt))
8141 (error "Region to sort contains a level above the first entry"))
8143 (unless sorting-type
8144 (message
8145 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8146 [t]ime [s]cheduled [d]eadline [c]reated
8147 A/N/T/S/D/C/P/O/F means reversed:"
8148 what)
8149 (setq sorting-type (read-char-exclusive))
8151 (unless getkey-func
8152 (and (= (downcase sorting-type) ?f)
8153 (setq getkey-func
8154 (org-icompleting-read "Sort using function: "
8155 obarray 'fboundp t nil nil))
8156 (setq getkey-func (intern getkey-func))))
8158 (and (= (downcase sorting-type) ?r)
8159 (not property)
8160 (setq property
8161 (org-icompleting-read "Property: "
8162 (mapcar 'list (org-buffer-property-keys t))
8163 nil t))))
8165 (message "Sorting entries...")
8167 (save-restriction
8168 (narrow-to-region start end)
8169 (let ((dcst (downcase sorting-type))
8170 (case-fold-search nil)
8171 (now (current-time)))
8172 (sort-subr
8173 (/= dcst sorting-type)
8174 ;; This function moves to the beginning character of the "record" to
8175 ;; be sorted.
8176 (lambda nil
8177 (if (re-search-forward re nil t)
8178 (goto-char (match-beginning 0))
8179 (goto-char (point-max))))
8180 ;; This function moves to the last character of the "record" being
8181 ;; sorted.
8182 (lambda nil
8183 (save-match-data
8184 (condition-case nil
8185 (outline-forward-same-level 1)
8186 (error
8187 (goto-char (point-max))))))
8188 ;; This function returns the value that gets sorted against.
8189 (lambda nil
8190 (cond
8191 ((= dcst ?n)
8192 (if (looking-at org-complex-heading-regexp)
8193 (string-to-number (match-string 4))
8194 nil))
8195 ((= dcst ?a)
8196 (if (looking-at org-complex-heading-regexp)
8197 (funcall case-func (match-string 4))
8198 nil))
8199 ((= dcst ?t)
8200 (let ((end (save-excursion (outline-next-heading) (point))))
8201 (if (or (re-search-forward org-ts-regexp end t)
8202 (re-search-forward org-ts-regexp-both end t))
8203 (org-time-string-to-seconds (match-string 0))
8204 (org-float-time now))))
8205 ((= dcst ?c)
8206 (let ((end (save-excursion (outline-next-heading) (point))))
8207 (if (re-search-forward
8208 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8209 end t)
8210 (org-time-string-to-seconds (match-string 0))
8211 (org-float-time now))))
8212 ((= dcst ?s)
8213 (let ((end (save-excursion (outline-next-heading) (point))))
8214 (if (re-search-forward org-scheduled-time-regexp end t)
8215 (org-time-string-to-seconds (match-string 1))
8216 (org-float-time now))))
8217 ((= dcst ?d)
8218 (let ((end (save-excursion (outline-next-heading) (point))))
8219 (if (re-search-forward org-deadline-time-regexp end t)
8220 (org-time-string-to-seconds (match-string 1))
8221 (org-float-time now))))
8222 ((= dcst ?p)
8223 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8224 (string-to-char (match-string 2))
8225 org-default-priority))
8226 ((= dcst ?r)
8227 (or (org-entry-get nil property) ""))
8228 ((= dcst ?o)
8229 (if (looking-at org-complex-heading-regexp)
8230 (- 9999 (length (member (match-string 2)
8231 org-todo-keywords-1)))))
8232 ((= dcst ?f)
8233 (if getkey-func
8234 (progn
8235 (setq tmp (funcall getkey-func))
8236 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8237 tmp)
8238 (error "Invalid key function `%s'" getkey-func)))
8239 (t (error "Invalid sorting type `%c'" sorting-type))))
8241 (cond
8242 ((= dcst ?a) 'string<)
8243 ((= dcst ?f) compare-func)
8244 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8245 (run-hooks 'org-after-sorting-entries-or-items-hook)
8246 (message "Sorting entries...done")))
8248 (defun org-do-sort (table what &optional with-case sorting-type)
8249 "Sort TABLE of WHAT according to SORTING-TYPE.
8250 The user will be prompted for the SORTING-TYPE if the call to this
8251 function does not specify it. WHAT is only for the prompt, to indicate
8252 what is being sorted. The sorting key will be extracted from
8253 the car of the elements of the table.
8254 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8255 (unless sorting-type
8256 (message
8257 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8258 what)
8259 (setq sorting-type (read-char-exclusive)))
8260 (let ((dcst (downcase sorting-type))
8261 extractfun comparefun)
8262 ;; Define the appropriate functions
8263 (cond
8264 ((= dcst ?n)
8265 (setq extractfun 'string-to-number
8266 comparefun (if (= dcst sorting-type) '< '>)))
8267 ((= dcst ?a)
8268 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8269 (lambda(x) (downcase (org-sort-remove-invisible x))))
8270 comparefun (if (= dcst sorting-type)
8271 'string<
8272 (lambda (a b) (and (not (string< a b))
8273 (not (string= a b)))))))
8274 ((= dcst ?t)
8275 (setq extractfun
8276 (lambda (x)
8277 (if (or (string-match org-ts-regexp x)
8278 (string-match org-ts-regexp-both x))
8279 (org-float-time
8280 (org-time-string-to-time (match-string 0 x)))
8282 comparefun (if (= dcst sorting-type) '< '>)))
8283 (t (error "Invalid sorting type `%c'" sorting-type)))
8285 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8286 table)
8287 (lambda (a b) (funcall comparefun (car a) (car b))))))
8290 ;;; The orgstruct minor mode
8292 ;; Define a minor mode which can be used in other modes in order to
8293 ;; integrate the org-mode structure editing commands.
8295 ;; This is really a hack, because the org-mode structure commands use
8296 ;; keys which normally belong to the major mode. Here is how it
8297 ;; works: The minor mode defines all the keys necessary to operate the
8298 ;; structure commands, but wraps the commands into a function which
8299 ;; tests if the cursor is currently at a headline or a plain list
8300 ;; item. If that is the case, the structure command is used,
8301 ;; temporarily setting many Org-mode variables like regular
8302 ;; expressions for filling etc. However, when any of those keys is
8303 ;; used at a different location, function uses `key-binding' to look
8304 ;; up if the key has an associated command in another currently active
8305 ;; keymap (minor modes, major mode, global), and executes that
8306 ;; command. There might be problems if any of the keys is otherwise
8307 ;; used as a prefix key.
8309 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8310 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8311 ;; addresses this by checking explicitly for both bindings.
8313 (defvar orgstruct-mode-map (make-sparse-keymap)
8314 "Keymap for the minor `orgstruct-mode'.")
8316 (defvar org-local-vars nil
8317 "List of local variables, for use by `orgstruct-mode'.")
8319 ;;;###autoload
8320 (define-minor-mode orgstruct-mode
8321 "Toggle the minor mode `orgstruct-mode'.
8322 This mode is for using Org-mode structure commands in other
8323 modes. The following keys behave as if Org-mode were active, if
8324 the cursor is on a headline, or on a plain list item (both as
8325 defined by Org-mode).
8327 M-up Move entry/item up
8328 M-down Move entry/item down
8329 M-left Promote
8330 M-right Demote
8331 M-S-up Move entry/item up
8332 M-S-down Move entry/item down
8333 M-S-left Promote subtree
8334 M-S-right Demote subtree
8335 M-q Fill paragraph and items like in Org-mode
8336 C-c ^ Sort entries
8337 C-c - Cycle list bullet
8338 TAB Cycle item visibility
8339 M-RET Insert new heading/item
8340 S-M-RET Insert new TODO heading / Checkbox item
8341 C-c C-c Set tags / toggle checkbox"
8342 nil " OrgStruct" nil
8343 (org-load-modules-maybe)
8344 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8346 ;;;###autoload
8347 (defun turn-on-orgstruct ()
8348 "Unconditionally turn on `orgstruct-mode'."
8349 (orgstruct-mode 1))
8351 (defvar org-fb-vars nil)
8352 (make-variable-buffer-local 'org-fb-vars)
8353 (defun orgstruct++-mode (&optional arg)
8354 "Toggle `orgstruct-mode', the enhanced version of it.
8355 In addition to setting orgstruct-mode, this also exports all
8356 indentation and autofilling variables from org-mode into the
8357 buffer. It will also recognize item context in multiline items."
8358 (interactive "P")
8359 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8360 (if (< arg 1)
8361 (progn (orgstruct-mode -1)
8362 (mapc (lambda(v)
8363 (org-set-local (car v)
8364 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8365 org-fb-vars))
8366 (orgstruct-mode 1)
8367 (setq org-fb-vars nil)
8368 (let (var val)
8369 (mapc
8370 (lambda (x)
8371 (when (string-match
8372 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8373 (symbol-name (car x)))
8374 (setq var (car x) val (nth 1 x))
8375 (push (list var `(quote ,(eval var))) org-fb-vars)
8376 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8377 org-local-vars)
8378 (org-set-local 'orgstruct-is-++ t))))
8380 (defvar orgstruct-is-++ nil
8381 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8382 (make-variable-buffer-local 'orgstruct-is-++)
8384 ;;;###autoload
8385 (defun turn-on-orgstruct++ ()
8386 "Unconditionally turn on `orgstruct++-mode'."
8387 (orgstruct++-mode 1))
8389 (defun orgstruct-error ()
8390 "Error when there is no default binding for a structure key."
8391 (interactive)
8392 (error "This key has no function outside structure elements"))
8394 (defun orgstruct-setup ()
8395 "Setup orgstruct keymaps."
8396 (let ((nfunc 0)
8397 (bindings
8398 (list
8399 '([(meta up)] org-metaup)
8400 '([(meta down)] org-metadown)
8401 '([(meta left)] org-metaleft)
8402 '([(meta right)] org-metaright)
8403 '([(meta shift up)] org-shiftmetaup)
8404 '([(meta shift down)] org-shiftmetadown)
8405 '([(meta shift left)] org-shiftmetaleft)
8406 '([(meta shift right)] org-shiftmetaright)
8407 '([?\e (up)] org-metaup)
8408 '([?\e (down)] org-metadown)
8409 '([?\e (left)] org-metaleft)
8410 '([?\e (right)] org-metaright)
8411 '([?\e (shift up)] org-shiftmetaup)
8412 '([?\e (shift down)] org-shiftmetadown)
8413 '([?\e (shift left)] org-shiftmetaleft)
8414 '([?\e (shift right)] org-shiftmetaright)
8415 '([(shift up)] org-shiftup)
8416 '([(shift down)] org-shiftdown)
8417 '([(shift left)] org-shiftleft)
8418 '([(shift right)] org-shiftright)
8419 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8420 '("\M-q" fill-paragraph)
8421 '("\C-c^" org-sort)
8422 '("\C-c-" org-cycle-list-bullet)))
8423 elt key fun cmd)
8424 (while (setq elt (pop bindings))
8425 (setq nfunc (1+ nfunc))
8426 (setq key (org-key (car elt))
8427 fun (nth 1 elt)
8428 cmd (orgstruct-make-binding fun nfunc key))
8429 (org-defkey orgstruct-mode-map key cmd))
8431 ;; Prevent an error for users who forgot to make autoloads
8432 (require 'org-element)
8434 ;; Special treatment needed for TAB and RET
8435 (org-defkey orgstruct-mode-map [(tab)]
8436 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8437 (org-defkey orgstruct-mode-map "\C-i"
8438 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8440 (org-defkey orgstruct-mode-map "\M-\C-m"
8441 (orgstruct-make-binding 'org-insert-heading 105
8442 "\M-\C-m" [(meta return)]))
8443 (org-defkey orgstruct-mode-map [(meta return)]
8444 (orgstruct-make-binding 'org-insert-heading 106
8445 [(meta return)] "\M-\C-m"))
8447 (org-defkey orgstruct-mode-map [(shift meta return)]
8448 (orgstruct-make-binding 'org-insert-todo-heading 107
8449 [(meta return)] "\M-\C-m"))
8451 (org-defkey orgstruct-mode-map "\e\C-m"
8452 (orgstruct-make-binding 'org-insert-heading 108
8453 "\e\C-m" [?\e (return)]))
8454 (org-defkey orgstruct-mode-map [?\e (return)]
8455 (orgstruct-make-binding 'org-insert-heading 109
8456 [?\e (return)] "\e\C-m"))
8457 (org-defkey orgstruct-mode-map [?\e (shift return)]
8458 (orgstruct-make-binding 'org-insert-todo-heading 110
8459 [?\e (return)] "\e\C-m"))
8461 (unless org-local-vars
8462 (setq org-local-vars (org-get-local-variables)))
8466 (defun orgstruct-make-binding (fun n &rest keys)
8467 "Create a function for binding in the structure minor mode.
8468 FUN is the command to call inside a table. N is used to create a unique
8469 command name. KEYS are keys that should be checked in for a command
8470 to execute outside of tables."
8471 (eval
8472 (list 'defun
8473 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8474 '(arg)
8475 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8476 "Outside of structure, run the binding of `"
8477 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8478 "'.")
8479 '(interactive "p")
8480 (list 'if
8481 `(org-context-p 'headline 'item
8482 (and orgstruct-is-++
8483 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8484 'item-body))
8485 (list 'org-run-like-in-org-mode (list 'quote fun))
8486 (list 'let '(orgstruct-mode)
8487 (list 'call-interactively
8488 (append '(or)
8489 (mapcar (lambda (k)
8490 (list 'key-binding k))
8491 keys)
8492 '('orgstruct-error))))))))
8494 (defun org-contextualize-keys (alist contexts)
8495 "Return valid elements in ALIST depending on CONTEXTS.
8497 `org-agenda-custom-commands' or `org-capture-templates' are the
8498 values used for ALIST, and `org-agenda-custom-commands-contexts'
8499 or `org-capture-templates-contexts' are the associated contexts
8500 definitions."
8501 (let ((contexts
8502 ;; normalize contexts
8503 (mapcar
8504 (lambda(c) (cond ((listp (cadr c))
8505 (list (car c) (car c) (cadr c)))
8506 ((string= "" (cadr c))
8507 (list (car c) (car c) (caddr c)))
8508 (t c))) contexts))
8509 (a alist) c r s)
8510 ;; loop over all commands or templates
8511 (while (setq c (pop a))
8512 (let (vrules repl)
8513 (cond
8514 ((not (assoc (car c) contexts))
8515 (push c r))
8516 ((and (assoc (car c) contexts)
8517 (setq vrules (org-contextualize-validate-key
8518 (car c) contexts)))
8519 (mapc (lambda (vr)
8520 (when (not (equal (car vr) (cadr vr)))
8521 (setq repl vr))) vrules)
8522 (if (not repl) (push c r)
8523 (push (cadr repl) s)
8524 (push
8525 (cons (car c)
8526 (cdr (or (assoc (cadr repl) alist)
8527 (error "Undefined key `%s' as contextual replacement for `%s'"
8528 (cadr repl) (car c)))))
8529 r))))))
8530 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8531 (delq
8533 (delete-dups
8534 (mapcar (lambda (x)
8535 (let ((tpl (car x)))
8536 (when (not (delq
8538 (mapcar (lambda(y)
8539 (equal y tpl)) s))) x)))
8540 (reverse r))))))
8542 (defun org-contextualize-validate-key (key contexts)
8543 "Check CONTEXTS for agenda or capture KEY."
8544 (let (r rr res)
8545 (while (setq r (pop contexts))
8546 (mapc
8547 (lambda (rr)
8548 (when
8549 (and (equal key (car r))
8550 (if (functionp rr) (funcall rr)
8551 (or (and (eq (car rr) 'in-file)
8552 (buffer-file-name)
8553 (string-match (cdr rr) (buffer-file-name)))
8554 (and (eq (car rr) 'in-mode)
8555 (string-match (cdr rr) (symbol-name major-mode)))
8556 (when (and (eq (car rr) 'not-in-file)
8557 (buffer-file-name))
8558 (not (string-match (cdr rr) (buffer-file-name))))
8559 (when (eq (car rr) 'not-in-mode)
8560 (not (string-match (cdr rr) (symbol-name major-mode)))))))
8561 (push r res)))
8562 (car (last r))))
8563 (delete-dups (delq nil res))))
8565 (defun org-context-p (&rest contexts)
8566 "Check if local context is any of CONTEXTS.
8567 Possible values in the list of contexts are `table', `headline', and `item'."
8568 (let ((pos (point)))
8569 (goto-char (point-at-bol))
8570 (prog1 (or (and (memq 'table contexts)
8571 (looking-at "[ \t]*|"))
8572 (and (memq 'headline contexts)
8573 (looking-at org-outline-regexp))
8574 (and (memq 'item contexts)
8575 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8576 (and (memq 'item-body contexts)
8577 (org-in-item-p)))
8578 (goto-char pos))))
8580 (defun org-get-local-variables ()
8581 "Return a list of all local variables in an Org mode buffer."
8582 (let (varlist)
8583 (with-current-buffer (get-buffer-create "*Org tmp*")
8584 (erase-buffer)
8585 (org-mode)
8586 (setq varlist (buffer-local-variables)))
8587 (kill-buffer "*Org tmp*")
8588 (delq nil
8589 (mapcar
8590 (lambda (x)
8591 (setq x
8592 (if (symbolp x)
8593 (list x)
8594 (list (car x) (list 'quote (cdr x)))))
8595 (if (string-match
8596 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8597 (symbol-name (car x)))
8598 x nil))
8599 varlist))))
8601 (defun org-clone-local-variables (from-buffer &optional regexp)
8602 "Clone local variables from FROM-BUFFER.
8603 Optional argument REGEXP selects variables to clone."
8604 (mapc
8605 (lambda (pair)
8606 (and (symbolp (car pair))
8607 (or (null regexp)
8608 (string-match regexp (symbol-name (car pair))))
8609 (set (make-local-variable (car pair))
8610 (cdr pair))))
8611 (buffer-local-variables from-buffer)))
8613 ;;;###autoload
8614 (defun org-run-like-in-org-mode (cmd)
8615 "Run a command, pretending that the current buffer is in Org-mode.
8616 This will temporarily bind local variables that are typically bound in
8617 Org-mode to the values they have in Org-mode, and then interactively
8618 call CMD."
8619 (org-load-modules-maybe)
8620 (unless org-local-vars
8621 (setq org-local-vars (org-get-local-variables)))
8622 (eval (list 'let org-local-vars
8623 (list 'call-interactively (list 'quote cmd)))))
8625 ;;;; Archiving
8627 (defun org-get-category (&optional pos force-refresh)
8628 "Get the category applying to position POS."
8629 (save-match-data
8630 (if force-refresh (org-refresh-category-properties))
8631 (let ((pos (or pos (point))))
8632 (or (get-text-property pos 'org-category)
8633 (progn (org-refresh-category-properties)
8634 (get-text-property pos 'org-category))))))
8636 (defun org-refresh-category-properties ()
8637 "Refresh category text properties in the buffer."
8638 (let ((case-fold-search t)
8639 (inhibit-read-only t)
8640 (def-cat (cond
8641 ((null org-category)
8642 (if buffer-file-name
8643 (file-name-sans-extension
8644 (file-name-nondirectory buffer-file-name))
8645 "???"))
8646 ((symbolp org-category) (symbol-name org-category))
8647 (t org-category)))
8648 beg end cat pos optionp)
8649 (org-unmodified
8650 (save-excursion
8651 (save-restriction
8652 (widen)
8653 (goto-char (point-min))
8654 (put-text-property (point) (point-max) 'org-category def-cat)
8655 (while (re-search-forward
8656 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8657 (setq pos (match-end 0)
8658 optionp (equal (char-after (match-beginning 0)) ?#)
8659 cat (org-trim (match-string 2)))
8660 (if optionp
8661 (setq beg (point-at-bol) end (point-max))
8662 (org-back-to-heading t)
8663 (setq beg (point) end (org-end-of-subtree t t)))
8664 (put-text-property beg end 'org-category cat)
8665 (put-text-property beg end 'org-category-position beg)
8666 (goto-char pos)))))))
8669 ;;;; Link Stuff
8671 ;;; Link abbreviations
8673 (defun org-link-expand-abbrev (link)
8674 "Apply replacements as defined in `org-link-abbrev-alist'."
8675 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8676 (let* ((key (match-string 1 link))
8677 (as (or (assoc key org-link-abbrev-alist-local)
8678 (assoc key org-link-abbrev-alist)))
8679 (tag (and (match-end 2) (match-string 3 link)))
8680 rpl)
8681 (if (not as)
8682 link
8683 (setq rpl (cdr as))
8684 (cond
8685 ((symbolp rpl) (funcall rpl tag))
8686 ((string-match "%(\\([^)]+\\))" rpl)
8687 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8688 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8689 ((string-match "%h" rpl)
8690 (replace-match (url-hexify-string (or tag "")) t t rpl))
8691 (t (concat rpl tag)))))
8692 link))
8694 ;;; Storing and inserting links
8696 (defvar org-insert-link-history nil
8697 "Minibuffer history for links inserted with `org-insert-link'.")
8699 (defvar org-stored-links nil
8700 "Contains the links stored with `org-store-link'.")
8702 (defvar org-store-link-plist nil
8703 "Plist with info about the most recently link created with `org-store-link'.")
8705 (defvar org-link-protocols nil
8706 "Link protocols added to Org-mode using `org-add-link-type'.")
8708 (defvar org-store-link-functions nil
8709 "List of functions that are called to create and store a link.
8710 Each function will be called in turn until one returns a non-nil
8711 value. Each function should check if it is responsible for creating
8712 this link (for example by looking at the major mode).
8713 If not, it must exit and return nil.
8714 If yes, it should return a non-nil value after a calling
8715 `org-store-link-props' with a list of properties and values.
8716 Special properties are:
8718 :type The link prefix, like \"http\". This must be given.
8719 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8720 This is obligatory as well.
8721 :description Optional default description for the second pair
8722 of brackets in an Org-mode link. The user can still change
8723 this when inserting this link into an Org-mode buffer.
8725 In addition to these, any additional properties can be specified
8726 and then used in capture templates.")
8728 (defun org-add-link-type (type &optional follow export)
8729 "Add TYPE to the list of `org-link-types'.
8730 Re-compute all regular expressions depending on `org-link-types'
8732 FOLLOW and EXPORT are two functions.
8734 FOLLOW should take the link path as the single argument and do whatever
8735 is necessary to follow the link, for example find a file or display
8736 a mail message.
8738 EXPORT should format the link path for export to one of the export formats.
8739 It should be a function accepting three arguments:
8741 path the path of the link, the text after the prefix (like \"http:\")
8742 desc the description of the link, if any, or a description added by
8743 org-export-normalize-links if there is none
8744 format the export format, a symbol like `html' or `latex' or `ascii'..
8746 The function may use the FORMAT information to return different values
8747 depending on the format. The return value will be put literally into
8748 the exported file. If the return value is nil, this means Org should
8749 do what it normally does with links which do not have EXPORT defined.
8751 Org-mode has a built-in default for exporting links. If you are happy with
8752 this default, there is no need to define an export function for the link
8753 type. For a simple example of an export function, see `org-bbdb.el'."
8754 (add-to-list 'org-link-types type t)
8755 (org-make-link-regexps)
8756 (if (assoc type org-link-protocols)
8757 (setcdr (assoc type org-link-protocols) (list follow export))
8758 (push (list type follow export) org-link-protocols)))
8760 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8761 (defvar org-link-to-org-use-id) ; Defined in org-id.el
8763 ;;;###autoload
8764 (defun org-store-link (arg)
8765 "\\<org-mode-map>Store an org-link to the current location.
8766 This link is added to `org-stored-links' and can later be inserted
8767 into an org-buffer with \\[org-insert-link].
8769 For some link types, a prefix arg is interpreted:
8770 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8771 For file links, arg negates `org-context-in-file-links'."
8772 (interactive "P")
8773 (org-load-modules-maybe)
8774 (setq org-store-link-plist nil) ; reset
8775 (org-with-limited-levels
8776 (let (link cpltxt desc description search txt custom-id agenda-link)
8777 (cond
8779 ((run-hook-with-args-until-success 'org-store-link-functions)
8780 (setq link (plist-get org-store-link-plist :link)
8781 desc (or (plist-get org-store-link-plist :description) link)))
8783 ((org-src-edit-buffer-p)
8784 (let (label gc)
8785 (while (or (not label)
8786 (save-excursion
8787 (save-restriction
8788 (widen)
8789 (goto-char (point-min))
8790 (re-search-forward
8791 (regexp-quote (format org-coderef-label-format label))
8792 nil t))))
8793 (when label (message "Label exists already") (sit-for 2))
8794 (setq label (read-string "Code line label: " label)))
8795 (end-of-line 1)
8796 (setq link (format org-coderef-label-format label))
8797 (setq gc (- 79 (length link)))
8798 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8799 (insert link)
8800 (setq link (concat "(" label ")") desc nil)))
8802 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8803 ;; We are in the agenda, link to referenced location
8804 (let ((m (or (get-text-property (point) 'org-hd-marker)
8805 (get-text-property (point) 'org-marker))))
8806 (when m
8807 (org-with-point-at m
8808 (setq agenda-link
8809 (if (org-called-interactively-p 'any)
8810 (call-interactively 'org-store-link)
8811 (org-store-link nil)))))))
8813 ((eq major-mode 'calendar-mode)
8814 (let ((cd (calendar-cursor-to-date)))
8815 (setq link
8816 (format-time-string
8817 (car org-time-stamp-formats)
8818 (apply 'encode-time
8819 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8820 nil nil nil))))
8821 (org-store-link-props :type "calendar" :date cd)))
8823 ((eq major-mode 'help-mode)
8824 (setq link (concat "help:" (save-excursion
8825 (goto-char (point-min))
8826 (looking-at "^[^ ]+")
8827 (match-string 0))))
8828 (org-store-link-props :type "help"))
8830 ((eq major-mode 'w3-mode)
8831 (setq cpltxt (if (and (buffer-name)
8832 (not (string-match "Untitled" (buffer-name))))
8833 (buffer-name)
8834 (url-view-url t))
8835 link (url-view-url t))
8836 (org-store-link-props :type "w3" :url (url-view-url t)))
8838 ((eq major-mode 'w3m-mode)
8839 (setq cpltxt (or w3m-current-title w3m-current-url)
8840 link w3m-current-url)
8841 (org-store-link-props :type "w3m" :url (url-view-url t)))
8843 ((setq search (run-hook-with-args-until-success
8844 'org-create-file-search-functions))
8845 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8846 "::" search))
8847 (setq cpltxt (or description link)))
8849 ((eq major-mode 'image-mode)
8850 (setq cpltxt (concat "file:"
8851 (abbreviate-file-name buffer-file-name))
8852 link cpltxt)
8853 (org-store-link-props :type "image" :file buffer-file-name))
8855 ((eq major-mode 'dired-mode)
8856 ;; link to the file in the current line
8857 (let ((file (dired-get-filename nil t)))
8858 (setq file (if file
8859 (abbreviate-file-name
8860 (expand-file-name (dired-get-filename nil t)))
8861 ;; otherwise, no file so use current directory.
8862 default-directory))
8863 (setq cpltxt (concat "file:" file)
8864 link cpltxt)))
8866 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8867 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8868 (cond
8869 ((org-in-regexp "<<\\(.*?\\)>>")
8870 (setq cpltxt
8871 (concat "file:"
8872 (abbreviate-file-name
8873 (buffer-file-name (buffer-base-buffer)))
8874 "::" (match-string 1))
8875 link cpltxt))
8876 ((and (featurep 'org-id)
8877 (or (eq org-link-to-org-use-id t)
8878 (and (org-called-interactively-p 'any)
8879 (or (eq org-link-to-org-use-id 'create-if-interactive)
8880 (and (eq org-link-to-org-use-id
8881 'create-if-interactive-and-no-custom-id)
8882 (not custom-id))))
8883 (and org-link-to-org-use-id (org-entry-get nil "ID"))))
8884 ;; We can make a link using the ID.
8885 (setq link (condition-case nil
8886 (prog1 (org-id-store-link)
8887 (setq desc (plist-get org-store-link-plist :description)))
8888 (error
8889 ;; probably before first headline, link to file only
8890 (concat "file:"
8891 (abbreviate-file-name
8892 (buffer-file-name (buffer-base-buffer))))))))
8894 ;; Just link to current headline
8895 (setq cpltxt (concat "file:"
8896 (abbreviate-file-name
8897 (buffer-file-name (buffer-base-buffer)))))
8898 ;; Add a context search string
8899 (when (org-xor org-context-in-file-links arg)
8900 (setq txt (cond
8901 ((org-at-heading-p) nil)
8902 ((org-region-active-p)
8903 (buffer-substring (region-beginning) (region-end)))))
8904 (when (or (null txt) (string-match "\\S-" txt))
8905 (setq cpltxt
8906 (concat cpltxt "::"
8907 (condition-case nil
8908 (org-make-org-heading-search-string txt)
8909 (error "")))
8910 desc (or (nth 4 (ignore-errors
8911 (org-heading-components))) "NONE"))))
8912 (if (string-match "::\\'" cpltxt)
8913 (setq cpltxt (substring cpltxt 0 -2)))
8914 (setq link cpltxt))))
8916 ((buffer-file-name (buffer-base-buffer))
8917 ;; Just link to this file here.
8918 (setq cpltxt (concat "file:"
8919 (abbreviate-file-name
8920 (buffer-file-name (buffer-base-buffer)))))
8921 ;; Add a context string
8922 (when (org-xor org-context-in-file-links arg)
8923 (setq txt (if (org-region-active-p)
8924 (buffer-substring (region-beginning) (region-end))
8925 (buffer-substring (point-at-bol) (point-at-eol))))
8926 ;; Only use search option if there is some text.
8927 (when (string-match "\\S-" txt)
8928 (setq cpltxt
8929 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8930 desc "NONE")))
8931 (setq link cpltxt))
8933 ((org-called-interactively-p 'interactive)
8934 (error "Cannot link to a buffer which is not visiting a file"))
8936 (t (setq link nil)))
8938 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8939 (setq link (or link cpltxt)
8940 desc (or desc cpltxt))
8941 (if (equal desc "NONE") (setq desc nil))
8943 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8944 (progn
8945 (setq org-stored-links
8946 (cons (list link desc) org-stored-links))
8947 (message "Stored: %s" (or desc link))
8948 (when custom-id
8949 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8950 "::#" custom-id))
8951 (setq org-stored-links
8952 (cons (list link desc) org-stored-links))))
8953 (or agenda-link (and link (org-make-link-string link desc)))))))
8955 (defun org-store-link-props (&rest plist)
8956 "Store link properties, extract names and addresses."
8957 (let (x adr)
8958 (when (setq x (plist-get plist :from))
8959 (setq adr (mail-extract-address-components x))
8960 (setq plist (plist-put plist :fromname (car adr)))
8961 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8962 (when (setq x (plist-get plist :to))
8963 (setq adr (mail-extract-address-components x))
8964 (setq plist (plist-put plist :toname (car adr)))
8965 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8966 (let ((from (plist-get plist :from))
8967 (to (plist-get plist :to)))
8968 (when (and from to org-from-is-user-regexp)
8969 (setq plist
8970 (plist-put plist :fromto
8971 (if (string-match org-from-is-user-regexp from)
8972 (concat "to %t")
8973 (concat "from %f"))))))
8974 (setq org-store-link-plist plist))
8976 (defun org-add-link-props (&rest plist)
8977 "Add these properties to the link property list."
8978 (let (key value)
8979 (while plist
8980 (setq key (pop plist) value (pop plist))
8981 (setq org-store-link-plist
8982 (plist-put org-store-link-plist key value)))))
8984 (defun org-email-link-description (&optional fmt)
8985 "Return the description part of an email link.
8986 This takes information from `org-store-link-plist' and formats it
8987 according to FMT (default from `org-email-link-description-format')."
8988 (setq fmt (or fmt org-email-link-description-format))
8989 (let* ((p org-store-link-plist)
8990 (to (plist-get p :toaddress))
8991 (from (plist-get p :fromaddress))
8992 (table
8993 (list
8994 (cons "%c" (plist-get p :fromto))
8995 (cons "%F" (plist-get p :from))
8996 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8997 (cons "%T" (plist-get p :to))
8998 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8999 (cons "%s" (plist-get p :subject))
9000 (cons "%d" (plist-get p :date))
9001 (cons "%m" (plist-get p :message-id)))))
9002 (when (string-match "%c" fmt)
9003 ;; Check if the user wrote this message
9004 (if (and org-from-is-user-regexp from to
9005 (save-match-data (string-match org-from-is-user-regexp from)))
9006 (setq fmt (replace-match "to %t" t t fmt))
9007 (setq fmt (replace-match "from %f" t t fmt))))
9008 (org-replace-escapes fmt table)))
9010 (defun org-make-org-heading-search-string (&optional string heading)
9011 "Make search string for STRING or current headline."
9012 (interactive)
9013 (let ((s (or string (org-get-heading)))
9014 (lines org-context-in-file-links))
9015 (unless (and string (not heading))
9016 ;; We are using a headline, clean up garbage in there.
9017 (if (string-match org-todo-regexp s)
9018 (setq s (replace-match "" t t s)))
9019 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
9020 (setq s (replace-match "" t t s)))
9021 (setq s (org-trim s))
9022 (if (string-match (concat "^\\(" org-quote-string "\\|"
9023 org-comment-string "\\)") s)
9024 (setq s (replace-match "" t t s)))
9025 (while (string-match org-ts-regexp s)
9026 (setq s (replace-match "" t t s))))
9027 (or string (setq s (concat "*" s))) ; Add * for headlines
9028 (when (and string (integerp lines) (> lines 0))
9029 (let ((slines (org-split-string s "\n")))
9030 (when (< lines (length slines))
9031 (setq s (mapconcat
9032 'identity
9033 (reverse (nthcdr (- (length slines) lines)
9034 (reverse slines))) "\n")))))
9035 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9037 (defun org-make-link-string (link &optional description)
9038 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9039 (unless (string-match "\\S-" link)
9040 (error "Empty link"))
9041 (when (and description
9042 (stringp description)
9043 (not (string-match "\\S-" description)))
9044 (setq description nil))
9045 (when (stringp description)
9046 ;; Remove brackets from the description, they are fatal.
9047 (while (string-match "\\[" description)
9048 (setq description (replace-match "{" t t description)))
9049 (while (string-match "\\]" description)
9050 (setq description (replace-match "}" t t description))))
9051 (when (equal link description)
9052 ;; No description needed, it is identical
9053 (setq description nil))
9054 (when (and (not description)
9055 (not (string-match (org-image-file-name-regexp) link))
9056 (not (equal link (org-link-escape link))))
9057 (setq description (org-extract-attributes link)))
9058 (setq link
9059 (cond ((string-match (org-image-file-name-regexp) link) link)
9060 ((string-match org-link-types-re link)
9061 (concat (match-string 1 link)
9062 (org-link-escape (substring link (match-end 1)))))
9063 (t (org-link-escape link))))
9064 (concat "[[" link "]"
9065 (if description (concat "[" description "]") "")
9066 "]"))
9068 (defconst org-link-escape-chars
9069 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9070 "List of characters that should be escaped in link.
9071 This is the list that is used for internal purposes.")
9073 (defconst org-link-escape-chars-browser
9074 '(?\ )
9075 "List of escapes for characters that are problematic in links.
9076 This is the list that is used before handing over to the browser.")
9078 (defun org-link-escape (text &optional table merge)
9079 "Return percent escaped representation of TEXT.
9080 TEXT is a string with the text to escape.
9081 Optional argument TABLE is a list with characters that should be
9082 escaped. When nil, `org-link-escape-chars' is used.
9083 If optional argument MERGE is set, merge TABLE into
9084 `org-link-escape-chars'."
9085 (cond
9086 ((and table merge)
9087 (mapc (lambda (defchr)
9088 (unless (member defchr table)
9089 (setq table (cons defchr table)))) org-link-escape-chars))
9090 ((null table)
9091 (setq table org-link-escape-chars)))
9092 (mapconcat
9093 (lambda (char)
9094 (if (or (member char table)
9095 (and (or (< char 32) (= char 37) (> char 126))
9096 org-url-hexify-p))
9097 (mapconcat (lambda (sequence-element)
9098 (format "%%%.2X" sequence-element))
9099 (or (encode-coding-char char 'utf-8)
9100 (error "Unable to percent escape character: %s"
9101 (char-to-string char))) "")
9102 (char-to-string char))) text ""))
9104 (defun org-link-unescape (str)
9105 "Unhex hexified Unicode strings as returned from the JavaScript function
9106 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9107 (unless (and (null str) (string= "" str))
9108 (let ((pos 0) (case-fold-search t) unhexed)
9109 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9110 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9111 (setq str (replace-match unhexed t t str))
9112 (setq pos (+ pos (length unhexed))))))
9113 str)
9115 (defun org-link-unescape-compound (hex)
9116 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9117 Note: this function also decodes single byte encodings like
9118 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9119 (save-match-data
9120 (let* ((bytes (cdr (split-string hex "%")))
9121 (ret "")
9122 (eat 0)
9123 (sum 0))
9124 (while bytes
9125 (let* ((val (string-to-number (pop bytes) 16))
9126 (shift-xor
9127 (if (= 0 eat)
9128 (cond
9129 ((>= val 252) (cons 6 252))
9130 ((>= val 248) (cons 5 248))
9131 ((>= val 240) (cons 4 240))
9132 ((>= val 224) (cons 3 224))
9133 ((>= val 192) (cons 2 192))
9134 (t (cons 0 0)))
9135 (cons 6 128))))
9136 (if (>= val 192) (setq eat (car shift-xor)))
9137 (setq val (logxor val (cdr shift-xor)))
9138 (setq sum (+ (lsh sum (car shift-xor)) val))
9139 (if (> eat 0) (setq eat (- eat 1)))
9140 (cond
9141 ((= 0 eat) ;multi byte
9142 (setq ret (concat ret (org-char-to-string sum)))
9143 (setq sum 0))
9144 ((not bytes) ; single byte(s)
9145 (setq ret (org-link-unescape-single-byte-sequence hex))))
9146 )) ;; end (while bytes
9147 ret )))
9149 (defun org-link-unescape-single-byte-sequence (hex)
9150 "Unhexify hex-encoded single byte character sequences."
9151 (mapconcat (lambda (byte)
9152 (char-to-string (string-to-number byte 16)))
9153 (cdr (split-string hex "%")) ""))
9155 (defun org-xor (a b)
9156 "Exclusive or."
9157 (if a (not b) b))
9159 (defun org-fixup-message-id-for-http (s)
9160 "Replace special characters in a message id, so it can be used in an http query."
9161 (when (string-match "%" s)
9162 (setq s (mapconcat (lambda (c)
9163 (if (eq c ?%)
9164 "%25"
9165 (char-to-string c)))
9166 s "")))
9167 (while (string-match "<" s)
9168 (setq s (replace-match "%3C" t t s)))
9169 (while (string-match ">" s)
9170 (setq s (replace-match "%3E" t t s)))
9171 (while (string-match "@" s)
9172 (setq s (replace-match "%40" t t s)))
9175 (defun org-link-prettify (link)
9176 "Return a human-readable representation of LINK.
9177 The car of LINK must be a raw link the cdr of LINK must be either
9178 a link description or nil."
9179 (let ((desc (or (cadr link) "<no description>")))
9180 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9181 "<" (car link) ">")))
9183 ;;;###autoload
9184 (defun org-insert-link-global ()
9185 "Insert a link like Org-mode does.
9186 This command can be called in any mode to insert a link in Org-mode syntax."
9187 (interactive)
9188 (org-load-modules-maybe)
9189 (org-run-like-in-org-mode 'org-insert-link))
9191 (defun org-insert-all-links (&optional keep)
9192 "Insert all links in `org-stored-links'."
9193 (interactive "P")
9194 (let ((links (copy-sequence org-stored-links)) l)
9195 (while (setq l (if keep (pop links) (pop org-stored-links)))
9196 (insert "- ")
9197 (org-insert-link nil (car l) (cadr l))
9198 (insert "\n"))))
9200 (defun org-link-fontify-links-to-this-file ()
9201 "Fontify links to the current file in `org-stored-links'."
9202 (let ((f (buffer-file-name)) a b)
9203 (setq a (mapcar (lambda(l)
9204 (let ((ll (car l)))
9205 (when (and (string-match "^file:\\(.+\\)::" ll)
9206 (equal f (expand-file-name (match-string 1 ll))))
9207 ll)))
9208 org-stored-links))
9209 (when (featurep 'org-id)
9210 (setq b (mapcar (lambda(l)
9211 (let ((ll (car l)))
9212 (when (and (string-match "^id:\\(.+\\)$" ll)
9213 (equal f (expand-file-name
9214 (or (org-id-find-id-file
9215 (match-string 1 ll)) ""))))
9216 ll)))
9217 org-stored-links)))
9218 (mapcar (lambda(l)
9219 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9220 (delq nil (append a b)))))
9222 (defvar org-link-links-in-this-file nil)
9223 (defun org-insert-link (&optional complete-file link-location default-description)
9224 "Insert a link. At the prompt, enter the link.
9226 Completion can be used to insert any of the link protocol prefixes like
9227 http or ftp in use.
9229 The history can be used to select a link previously stored with
9230 `org-store-link'. When the empty string is entered (i.e. if you just
9231 press RET at the prompt), the link defaults to the most recently
9232 stored link. As SPC triggers completion in the minibuffer, you need to
9233 use M-SPC or C-q SPC to force the insertion of a space character.
9235 You will also be prompted for a description, and if one is given, it will
9236 be displayed in the buffer instead of the link.
9238 If there is already a link at point, this command will allow you to edit link
9239 and description parts.
9241 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9242 be selected using completion. The path to the file will be relative to the
9243 current directory if the file is in the current directory or a subdirectory.
9244 Otherwise, the link will be the absolute path as completed in the minibuffer
9245 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9246 option `org-link-file-path-type'.
9248 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9249 the current directory or below.
9251 With three \\[universal-argument] prefixes, negate the meaning of
9252 `org-keep-stored-link-after-insertion'.
9254 If `org-make-link-description-function' is non-nil, this function will be
9255 called with the link target, and the result will be the default
9256 link description.
9258 If the LINK-LOCATION parameter is non-nil, this value will be
9259 used as the link location instead of reading one interactively.
9261 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9262 be used as the default description."
9263 (interactive "P")
9264 (let* ((wcf (current-window-configuration))
9265 (origbuf (current-buffer))
9266 (region (if (org-region-active-p)
9267 (buffer-substring (region-beginning) (region-end))))
9268 (remove (and region (list (region-beginning) (region-end))))
9269 (desc region)
9270 tmphist ; byte-compile incorrectly complains about this
9271 (link link-location)
9272 (abbrevs org-link-abbrev-alist-local)
9273 entry file all-prefixes auto-desc)
9274 (cond
9275 (link-location) ; specified by arg, just use it.
9276 ((org-in-regexp org-bracket-link-regexp 1)
9277 ;; We do have a link at point, and we are going to edit it.
9278 (setq remove (list (match-beginning 0) (match-end 0)))
9279 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9280 (setq link (read-string "Link: "
9281 (org-link-unescape
9282 (org-match-string-no-properties 1)))))
9283 ((or (org-in-regexp org-angle-link-re)
9284 (org-in-regexp org-plain-link-re))
9285 ;; Convert to bracket link
9286 (setq remove (list (match-beginning 0) (match-end 0))
9287 link (read-string "Link: "
9288 (org-remove-angle-brackets (match-string 0)))))
9289 ((member complete-file '((4) (16)))
9290 ;; Completing read for file names.
9291 (setq link (org-file-complete-link complete-file)))
9293 ;; Read link, with completion for stored links.
9294 (org-link-fontify-links-to-this-file)
9295 (org-switch-to-buffer-other-window "*Org Links*")
9296 (with-current-buffer "*Org Links*"
9297 (erase-buffer)
9298 (insert "Insert a link.
9299 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9300 (when org-stored-links
9301 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9302 (insert (mapconcat 'org-link-prettify
9303 (reverse org-stored-links) "\n")))
9304 (goto-char (point-min)))
9305 (let ((cw (selected-window)))
9306 (select-window (get-buffer-window "*Org Links*" 'visible))
9307 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9308 (unless (pos-visible-in-window-p (point-max))
9309 (org-fit-window-to-buffer))
9310 (and (window-live-p cw) (select-window cw)))
9311 ;; Fake a link history, containing the stored links.
9312 (setq tmphist (append (mapcar 'car org-stored-links)
9313 org-insert-link-history))
9314 (setq all-prefixes (append (mapcar 'car abbrevs)
9315 (mapcar 'car org-link-abbrev-alist)
9316 org-link-types))
9317 (unwind-protect
9318 (progn
9319 (setq link
9320 (org-completing-read
9321 "Link: "
9322 (append
9323 (mapcar (lambda (x) (concat x ":"))
9324 all-prefixes)
9325 (mapcar 'car org-stored-links))
9326 nil nil nil
9327 'tmphist
9328 (caar org-stored-links)))
9329 (if (not (string-match "\\S-" link))
9330 (error "No link selected"))
9331 (mapc (lambda(l)
9332 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9333 org-stored-links)
9334 (if (or (member link all-prefixes)
9335 (and (equal ":" (substring link -1))
9336 (member (substring link 0 -1) all-prefixes)
9337 (setq link (substring link 0 -1))))
9338 (setq link (with-current-buffer origbuf
9339 (org-link-try-special-completion link)))))
9340 (set-window-configuration wcf)
9341 (kill-buffer "*Org Links*"))
9342 (setq entry (assoc link org-stored-links))
9343 (or entry (push link org-insert-link-history))
9344 (setq desc (or desc (nth 1 entry)))))
9346 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9347 (not org-keep-stored-link-after-insertion))
9348 (setq org-stored-links (delq (assoc link org-stored-links)
9349 org-stored-links)))
9351 (if (string-match org-plain-link-re link)
9352 ;; URL-like link, normalize the use of angular brackets.
9353 (setq link (org-remove-angle-brackets link)))
9355 ;; Check if we are linking to the current file with a search option
9356 ;; If yes, simplify the link by using only the search option.
9357 (when (and buffer-file-name
9358 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9359 (let* ((path (match-string 1 link))
9360 (case-fold-search nil)
9361 (search (match-string 2 link)))
9362 (save-match-data
9363 (if (equal (file-truename buffer-file-name) (file-truename path))
9364 ;; We are linking to this same file, with a search option
9365 (setq link search)))))
9367 ;; Check if we can/should use a relative path. If yes, simplify the link
9368 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9369 (let* ((type (match-string 1 link))
9370 (path (match-string 2 link))
9371 (origpath path)
9372 (case-fold-search nil))
9373 (cond
9374 ((or (eq org-link-file-path-type 'absolute)
9375 (equal complete-file '(16)))
9376 (setq path (abbreviate-file-name (expand-file-name path))))
9377 ((eq org-link-file-path-type 'noabbrev)
9378 (setq path (expand-file-name path)))
9379 ((eq org-link-file-path-type 'relative)
9380 (setq path (file-relative-name path)))
9382 (save-match-data
9383 (if (string-match (concat "^" (regexp-quote
9384 (expand-file-name
9385 (file-name-as-directory
9386 default-directory))))
9387 (expand-file-name path))
9388 ;; We are linking a file with relative path name.
9389 (setq path (substring (expand-file-name path)
9390 (match-end 0)))
9391 (setq path (abbreviate-file-name (expand-file-name path)))))))
9392 (setq link (concat type path))
9393 (if (equal desc origpath)
9394 (setq desc path))))
9396 (if org-make-link-description-function
9397 (setq desc
9398 (or (condition-case nil
9399 (funcall org-make-link-description-function link desc)
9400 (error (progn (message "Can't get link description from `%s'"
9401 (symbol-name org-make-link-description-function))
9402 (sit-for 2) nil)))
9403 (read-string "Description: " default-description)))
9404 (if default-description (setq desc default-description)
9405 (setq desc (or (and auto-desc desc)
9406 (read-string "Description: " desc)))))
9408 (unless (string-match "\\S-" desc) (setq desc nil))
9409 (if remove (apply 'delete-region remove))
9410 (insert (org-make-link-string link desc))))
9412 (defun org-link-try-special-completion (type)
9413 "If there is completion support for link type TYPE, offer it."
9414 (let ((fun (intern (concat "org-" type "-complete-link"))))
9415 (if (functionp fun)
9416 (funcall fun)
9417 (read-string "Link (no completion support): " (concat type ":")))))
9419 (defun org-file-complete-link (&optional arg)
9420 "Create a file link using completion."
9421 (let (file link)
9422 (setq file (org-iread-file-name "File: "))
9423 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9424 (pwd1 (file-name-as-directory (abbreviate-file-name
9425 (expand-file-name ".")))))
9426 (cond
9427 ((equal arg '(16))
9428 (setq link (concat
9429 "file:"
9430 (abbreviate-file-name (expand-file-name file)))))
9431 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9432 (setq link (concat "file:" (match-string 1 file))))
9433 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9434 (expand-file-name file))
9435 (setq link (concat
9436 "file:" (match-string 1 (expand-file-name file)))))
9437 (t (setq link (concat "file:" file)))))
9438 link))
9440 (defun org-iread-file-name (&rest args)
9441 "Read-file-name using `ido-mode' speedup if available.
9442 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
9443 See `read-file-name' for a description of parameters."
9444 (org-without-partial-completion
9445 (if (and org-completion-use-ido
9446 (fboundp 'ido-read-file-name)
9447 (boundp 'ido-mode) ido-mode
9448 (listp (second args)))
9449 (let ((ido-enter-matching-directory nil))
9450 (apply 'ido-read-file-name args))
9451 (apply 'read-file-name args))))
9453 (defun org-completing-read (&rest args)
9454 "Completing-read with SPACE being a normal character."
9455 (let ((enable-recursive-minibuffers t)
9456 (minibuffer-local-completion-map
9457 (copy-keymap minibuffer-local-completion-map)))
9458 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9459 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9460 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9461 (apply 'org-icompleting-read args)))
9463 (defun org-completing-read-no-i (&rest args)
9464 (let (org-completion-use-ido org-completion-use-iswitchb)
9465 (apply 'org-completing-read args)))
9467 (defun org-iswitchb-completing-read (prompt choices &rest args)
9468 "Use iswitch as a completing-read replacement to choose from choices.
9469 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9470 from."
9471 (let* ((iswitchb-use-virtual-buffers nil)
9472 (iswitchb-make-buflist-hook
9473 (lambda ()
9474 (setq iswitchb-temp-buflist choices))))
9475 (iswitchb-read-buffer prompt)))
9477 (defun org-icompleting-read (&rest args)
9478 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9479 (org-without-partial-completion
9480 (if (and org-completion-use-ido
9481 (fboundp 'ido-completing-read)
9482 (boundp 'ido-mode) ido-mode
9483 (listp (second args)))
9484 (let ((ido-enter-matching-directory nil))
9485 (apply 'ido-completing-read (concat (car args))
9486 (if (consp (car (nth 1 args)))
9487 (mapcar 'car (nth 1 args))
9488 (nth 1 args))
9489 (cddr args)))
9490 (if (and org-completion-use-iswitchb
9491 (boundp 'iswitchb-mode) iswitchb-mode
9492 (listp (second args)))
9493 (apply 'org-iswitchb-completing-read (concat (car args))
9494 (if (consp (car (nth 1 args)))
9495 (mapcar 'car (nth 1 args))
9496 (nth 1 args))
9497 (cddr args))
9498 (apply 'completing-read args)))))
9500 (defun org-extract-attributes (s)
9501 "Extract the attributes cookie from a string and set as text property."
9502 (let (a attr (start 0) key value)
9503 (save-match-data
9504 (when (string-match "{{\\([^}]+\\)}}$" s)
9505 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9506 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9507 (setq key (match-string 1 a) value (match-string 2 a)
9508 start (match-end 0)
9509 attr (plist-put attr (intern key) value))))
9510 (org-add-props s nil 'org-attr attr))
9513 (defun org-extract-attributes-from-string (tag)
9514 (let (key value attr)
9515 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9516 (setq key (match-string 1 tag) value (match-string 2 tag)
9517 tag (replace-match "" t t tag)
9518 attr (plist-put attr (intern key) value)))
9519 (cons tag attr)))
9521 (defun org-attributes-to-string (plist)
9522 "Format a property list into an HTML attribute list."
9523 (let ((s "") key value)
9524 (while plist
9525 (setq key (pop plist) value (pop plist))
9526 (and value
9527 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9530 ;;; Opening/following a link
9532 (defvar org-link-search-failed nil)
9534 (defvar org-open-link-functions nil
9535 "Hook for functions finding a plain text link.
9536 These functions must take a single argument, the link content.
9537 They will be called for links that look like [[link text][description]]
9538 when LINK TEXT does not have a protocol like \"http:\" and does not look
9539 like a filename (e.g. \"./blue.png\").
9541 These functions will be called *before* Org attempts to resolve the
9542 link by doing text searches in the current buffer - so if you want a
9543 link \"[[target]]\" to still find \"<<target>>\", your function should
9544 handle this as a special case.
9546 When the function does handle the link, it must return a non-nil value.
9547 If it decides that it is not responsible for this link, it must return
9548 nil to indicate that that Org-mode can continue with other options
9549 like exact and fuzzy text search.")
9551 (defun org-next-link ()
9552 "Move forward to the next link.
9553 If the link is in hidden text, expose it."
9554 (interactive)
9555 (when (and org-link-search-failed (eq this-command last-command))
9556 (goto-char (point-min))
9557 (message "Link search wrapped back to beginning of buffer"))
9558 (setq org-link-search-failed nil)
9559 (let* ((pos (point))
9560 (ct (org-context))
9561 (a (assoc :link ct)))
9562 (if a (goto-char (nth 2 a)))
9563 (if (re-search-forward org-any-link-re nil t)
9564 (progn
9565 (goto-char (match-beginning 0))
9566 (if (outline-invisible-p) (org-show-context)))
9567 (goto-char pos)
9568 (setq org-link-search-failed t)
9569 (error "No further link found"))))
9571 (defun org-previous-link ()
9572 "Move backward to the previous link.
9573 If the link is in hidden text, expose it."
9574 (interactive)
9575 (when (and org-link-search-failed (eq this-command last-command))
9576 (goto-char (point-max))
9577 (message "Link search wrapped back to end of buffer"))
9578 (setq org-link-search-failed nil)
9579 (let* ((pos (point))
9580 (ct (org-context))
9581 (a (assoc :link ct)))
9582 (if a (goto-char (nth 1 a)))
9583 (if (re-search-backward org-any-link-re nil t)
9584 (progn
9585 (goto-char (match-beginning 0))
9586 (if (outline-invisible-p) (org-show-context)))
9587 (goto-char pos)
9588 (setq org-link-search-failed t)
9589 (error "No further link found"))))
9591 (defun org-translate-link (s)
9592 "Translate a link string if a translation function has been defined."
9593 (if (and org-link-translation-function
9594 (fboundp org-link-translation-function)
9595 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9596 (progn
9597 (setq s (funcall org-link-translation-function
9598 (match-string 1 s) (match-string 2 s)))
9599 (concat (car s) ":" (cdr s)))
9602 (defun org-translate-link-from-planner (type path)
9603 "Translate a link from Emacs Planner syntax so that Org can follow it.
9604 This is still an experimental function, your mileage may vary."
9605 (cond
9606 ((member type '("http" "https" "news" "ftp"))
9607 ;; standard Internet links are the same.
9608 nil)
9609 ((and (equal type "irc") (string-match "^//" path))
9610 ;; Planner has two / at the beginning of an irc link, we have 1.
9611 ;; We should have zero, actually....
9612 (setq path (substring path 1)))
9613 ((and (equal type "lisp") (string-match "^/" path))
9614 ;; Planner has a slash, we do not.
9615 (setq type "elisp" path (substring path 1)))
9616 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9617 ;; A typical message link. Planner has the id after the final slash,
9618 ;; we separate it with a hash mark
9619 (setq path (concat (match-string 1 path) "#"
9620 (org-remove-angle-brackets (match-string 2 path)))))
9622 (cons type path))
9624 (defun org-find-file-at-mouse (ev)
9625 "Open file link or URL at mouse."
9626 (interactive "e")
9627 (mouse-set-point ev)
9628 (org-open-at-point 'in-emacs))
9630 (defun org-open-at-mouse (ev)
9631 "Open file link or URL at mouse.
9632 See the docstring of `org-open-file' for details."
9633 (interactive "e")
9634 (mouse-set-point ev)
9635 (if (eq major-mode 'org-agenda-mode)
9636 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9637 (org-open-at-point))
9639 (defvar org-window-config-before-follow-link nil
9640 "The window configuration before following a link.
9641 This is saved in case the need arises to restore it.")
9643 (defvar org-open-link-marker (make-marker)
9644 "Marker pointing to the location where `org-open-at-point; was called.")
9646 ;;;###autoload
9647 (defun org-open-at-point-global ()
9648 "Follow a link like Org-mode does.
9649 This command can be called in any mode to follow a link that has
9650 Org-mode syntax."
9651 (interactive)
9652 (org-run-like-in-org-mode 'org-open-at-point))
9654 ;;;###autoload
9655 (defun org-open-link-from-string (s &optional arg reference-buffer)
9656 "Open a link in the string S, as if it was in Org-mode."
9657 (interactive "sLink: \nP")
9658 (let ((reference-buffer (or reference-buffer (current-buffer))))
9659 (with-temp-buffer
9660 (let ((org-inhibit-startup (not reference-buffer)))
9661 (org-mode)
9662 (insert s)
9663 (goto-char (point-min))
9664 (when reference-buffer
9665 (setq org-link-abbrev-alist-local
9666 (with-current-buffer reference-buffer
9667 org-link-abbrev-alist-local)))
9668 (org-open-at-point arg reference-buffer)))))
9670 (defvar org-open-at-point-functions nil
9671 "Hook that is run when following a link at point.
9673 Functions in this hook must return t if they identify and follow
9674 a link at point. If they don't find anything interesting at point,
9675 they must return nil.")
9677 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9678 (defun org-open-at-point (&optional arg reference-buffer)
9679 "Open link at or after point.
9680 If there is no link at point, this function will search forward up to
9681 the end of the current line.
9682 Normally, files will be opened by an appropriate application. If the
9683 optional prefix argument ARG is non-nil, Emacs will visit the file.
9684 With a double prefix argument, try to open outside of Emacs, in the
9685 application the system uses for this file type."
9686 (interactive "P")
9687 ;; if in a code block, then open the block's results
9688 (unless (call-interactively #'org-babel-open-src-block-result)
9689 (org-load-modules-maybe)
9690 (move-marker org-open-link-marker (point))
9691 (setq org-window-config-before-follow-link (current-window-configuration))
9692 (org-remove-occur-highlights nil nil t)
9693 (cond
9694 ((and (org-at-heading-p)
9695 (not (org-at-timestamp-p t))
9696 (not (org-in-regexp
9697 (concat org-plain-link-re "\\|"
9698 org-bracket-link-regexp "\\|"
9699 org-angle-link-re "\\|"
9700 "[ \t]:[^ \t\n]+:[ \t]*$")))
9701 (not (get-text-property (point) 'org-linked-text)))
9702 (or (org-offer-links-in-entry arg)
9703 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9704 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9705 ((and (org-at-timestamp-p t)
9706 (not (org-in-regexp org-bracket-link-regexp)))
9707 (org-follow-timestamp-link))
9708 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9709 (not (org-in-regexp org-bracket-link-regexp)))
9710 (org-footnote-action))
9712 (let (type path link line search (pos (point)))
9713 (catch 'match
9714 (save-excursion
9715 (skip-chars-forward "^]\n\r")
9716 (when (org-in-regexp org-bracket-link-regexp 1)
9717 (setq link (org-extract-attributes
9718 (org-link-unescape (org-match-string-no-properties 1))))
9719 (while (string-match " *\n *" link)
9720 (setq link (replace-match " " t t link)))
9721 (setq link (org-link-expand-abbrev link))
9722 (cond
9723 ((or (file-name-absolute-p link)
9724 (string-match "^\\.\\.?/" link))
9725 (setq type "file" path link))
9726 ((string-match org-link-re-with-space3 link)
9727 (setq type (match-string 1 link) path (match-string 2 link)))
9728 ((string-match "^help:+\\(.+\\)" link)
9729 (setq type "help" path (match-string 1 link)))
9730 (t (setq type "thisfile" path link)))
9731 (throw 'match t)))
9733 (when (get-text-property (point) 'org-linked-text)
9734 (setq type "thisfile"
9735 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9736 (1+ (point)) (point))
9737 path (buffer-substring
9738 (or (previous-single-property-change pos 'org-linked-text)
9739 (point-min))
9740 (or (next-single-property-change pos 'org-linked-text)
9741 (point-max))))
9742 (throw 'match t))
9744 (save-excursion
9745 (when (or (org-in-regexp org-angle-link-re)
9746 (and (goto-char (car (org-in-regexp org-plain-link-re)))
9747 (save-match-data (not (looking-back "\\[\\[")))))
9748 (setq type (match-string 1)
9749 path (org-link-unescape (match-string 2)))
9750 (throw 'match t)))
9751 (save-excursion
9752 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9753 (setq type "tags"
9754 path (match-string 1))
9755 (while (string-match ":" path)
9756 (setq path (replace-match "+" t t path)))
9757 (throw 'match t)))
9758 (when (org-in-regexp "<\\([^><\n]+\\)>")
9759 (setq type "tree-match"
9760 path (match-string 1))
9761 (throw 'match t)))
9762 (unless path
9763 (error "No link found"))
9765 ;; switch back to reference buffer
9766 ;; needed when if called in a temporary buffer through
9767 ;; org-open-link-from-string
9768 (with-current-buffer (or reference-buffer (current-buffer))
9770 ;; Remove any trailing spaces in path
9771 (if (string-match " +\\'" path)
9772 (setq path (replace-match "" t t path)))
9773 (if (and org-link-translation-function
9774 (fboundp org-link-translation-function))
9775 ;; Check if we need to translate the link
9776 (let ((tmp (funcall org-link-translation-function type path)))
9777 (setq type (car tmp) path (cdr tmp))))
9779 (cond
9781 ((assoc type org-link-protocols)
9782 (funcall (nth 1 (assoc type org-link-protocols)) path))
9784 ((equal type "help")
9785 (let ((f-or-v (intern path)))
9786 (cond ((fboundp f-or-v)
9787 (describe-function f-or-v))
9788 ((boundp f-or-v)
9789 (describe-variable f-or-v))
9790 (t (error "Not a known function or variable")))))
9792 ((equal type "mailto")
9793 (let ((cmd (car org-link-mailto-program))
9794 (args (cdr org-link-mailto-program)) args1
9795 (address path) (subject "") a)
9796 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9797 (setq address (match-string 1 path)
9798 subject (org-link-escape (match-string 2 path))))
9799 (while args
9800 (cond
9801 ((not (stringp (car args))) (push (pop args) args1))
9802 (t (setq a (pop args))
9803 (if (string-match "%a" a)
9804 (setq a (replace-match address t t a)))
9805 (if (string-match "%s" a)
9806 (setq a (replace-match subject t t a)))
9807 (push a args1))))
9808 (apply cmd (nreverse args1))))
9810 ((member type '("http" "https" "ftp" "news"))
9811 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9812 (org-link-escape
9813 path org-link-escape-chars-browser)
9814 path))))
9816 ((string= type "doi")
9817 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9818 (org-link-escape
9819 path org-link-escape-chars-browser)
9820 path))))
9822 ((member type '("message"))
9823 (browse-url (concat type ":" path)))
9825 ((string= type "tags")
9826 (org-tags-view arg path))
9828 ((string= type "tree-match")
9829 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9831 ((string= type "file")
9832 (if (string-match "::\\([0-9]+\\)\\'" path)
9833 (setq line (string-to-number (match-string 1 path))
9834 path (substring path 0 (match-beginning 0)))
9835 (if (string-match "::\\(.+\\)\\'" path)
9836 (setq search (match-string 1 path)
9837 path (substring path 0 (match-beginning 0)))))
9838 (if (string-match "[*?{]" (file-name-nondirectory path))
9839 (dired path)
9840 (org-open-file path arg line search)))
9842 ((string= type "shell")
9843 (let ((buf (generate-new-buffer "*Org Shell Output"))
9844 (cmd path))
9845 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9846 (string-match org-confirm-shell-link-not-regexp cmd))
9847 (not org-confirm-shell-link-function)
9848 (funcall org-confirm-shell-link-function
9849 (format "Execute \"%s\" in shell? "
9850 (org-add-props cmd nil
9851 'face 'org-warning))))
9852 (progn
9853 (message "Executing %s" cmd)
9854 (shell-command cmd buf)
9855 (if (featurep 'midnight)
9856 (setq clean-buffer-list-kill-buffer-names
9857 (cons buf clean-buffer-list-kill-buffer-names))))
9858 (error "Abort"))))
9860 ((string= type "elisp")
9861 (let ((cmd path))
9862 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9863 (string-match org-confirm-elisp-link-not-regexp cmd))
9864 (not org-confirm-elisp-link-function)
9865 (funcall org-confirm-elisp-link-function
9866 (format "Execute \"%s\" as elisp? "
9867 (org-add-props cmd nil
9868 'face 'org-warning))))
9869 (message "%s => %s" cmd
9870 (if (equal (string-to-char cmd) ?\()
9871 (eval (read cmd))
9872 (call-interactively (read cmd))))
9873 (error "Abort"))))
9875 ((and (string= type "thisfile")
9876 (run-hook-with-args-until-success
9877 'org-open-link-functions path)))
9879 ((string= type "thisfile")
9880 (if arg
9881 (switch-to-buffer-other-window
9882 (org-get-buffer-for-internal-link (current-buffer)))
9883 (org-mark-ring-push))
9884 (let ((cmd `(org-link-search
9885 ,path
9886 ,(cond ((equal arg '(4)) ''occur)
9887 ((equal arg '(16)) ''org-occur))
9888 ,pos)))
9889 (condition-case nil (let ((org-link-search-inhibit-query t))
9890 (eval cmd))
9891 (error (progn (widen) (eval cmd))))))
9893 (t (browse-url-at-point)))))))
9894 (move-marker org-open-link-marker nil)
9895 (run-hook-with-args 'org-follow-link-hook)))
9897 (defun org-offer-links-in-entry (&optional nth zero)
9898 "Offer links in the current entry and follow the selected link.
9899 If there is only one link, follow it immediately as well.
9900 If NTH is an integer, immediately pick the NTH link found.
9901 If ZERO is a string, check also this string for a link, and if
9902 there is one, offer it as link number zero."
9903 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9904 "\\(" org-angle-link-re "\\)\\|"
9905 "\\(" org-plain-link-re "\\)"))
9906 (cnt ?0)
9907 (in-emacs (if (integerp nth) nil nth))
9908 have-zero end links link c)
9909 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9910 (push (match-string 0 zero) links)
9911 (setq cnt (1- cnt) have-zero t))
9912 (save-excursion
9913 (org-back-to-heading t)
9914 (setq end (save-excursion (outline-next-heading) (point)))
9915 (while (re-search-forward re end t)
9916 (push (match-string 0) links))
9917 (setq links (org-uniquify (reverse links))))
9919 (cond
9920 ((null links)
9921 (message "No links"))
9922 ((equal (length links) 1)
9923 (setq link (list (car links))))
9924 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9925 (setq link (list (nth (if have-zero nth (1- nth)) links))))
9926 (t ; we have to select a link
9927 (save-excursion
9928 (save-window-excursion
9929 (delete-other-windows)
9930 (with-output-to-temp-buffer "*Select Link*"
9931 (mapc (lambda (l)
9932 (if (not (string-match org-bracket-link-regexp l))
9933 (princ (format "[%c] %s\n" (incf cnt)
9934 (org-remove-angle-brackets l)))
9935 (if (match-end 3)
9936 (princ (format "[%c] %s (%s)\n" (incf cnt)
9937 (match-string 3 l) (match-string 1 l)))
9938 (princ (format "[%c] %s\n" (incf cnt)
9939 (match-string 1 l))))))
9940 links))
9941 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9942 (message "Select link to open, RET to open all:")
9943 (setq c (read-char-exclusive))
9944 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9945 (when (equal c ?q) (error "Abort"))
9946 (if (equal c ?\C-m)
9947 (setq link links)
9948 (setq nth (- c ?0))
9949 (if have-zero (setq nth (1+ nth)))
9950 (unless (and (integerp nth) (>= (length links) nth))
9951 (error "Invalid link selection"))
9952 (setq link (list (nth (1- nth) links))))))
9953 (if link
9954 (let ((buf (current-buffer)))
9955 (dolist (l link)
9956 (org-open-link-from-string l in-emacs buf))
9958 nil)))
9960 ;; Add special file links that specify the way of opening
9962 (org-add-link-type "file+sys" 'org-open-file-with-system)
9963 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9964 (defun org-open-file-with-system (path)
9965 "Open file at PATH using the system way of opening it."
9966 (org-open-file path 'system))
9967 (defun org-open-file-with-emacs (path)
9968 "Open file at PATH in Emacs."
9969 (org-open-file path 'emacs))
9970 (defun org-remove-file-link-modifiers ()
9971 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9972 (goto-char (point-min))
9973 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9974 (org-if-unprotected
9975 (replace-match "file:" t t))))
9976 (eval-after-load "org-exp"
9977 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9978 'org-remove-file-link-modifiers))
9980 ;;;; Time estimates
9982 (defun org-get-effort (&optional pom)
9983 "Get the effort estimate for the current entry."
9984 (org-entry-get pom org-effort-property))
9986 ;;; File search
9988 (defvar org-create-file-search-functions nil
9989 "List of functions to construct the right search string for a file link.
9990 These functions are called in turn with point at the location to
9991 which the link should point.
9993 A function in the hook should first test if it would like to
9994 handle this file type, for example by checking the `major-mode'
9995 or the file extension. If it decides not to handle this file, it
9996 should just return nil to give other functions a chance. If it
9997 does handle the file, it must return the search string to be used
9998 when following the link. The search string will be part of the
9999 file link, given after a double colon, and `org-open-at-point'
10000 will automatically search for it. If special measures must be
10001 taken to make the search successful, another function should be
10002 added to the companion hook `org-execute-file-search-functions',
10003 which see.
10005 A function in this hook may also use `setq' to set the variable
10006 `description' to provide a suggestion for the descriptive text to
10007 be used for this link when it gets inserted into an Org-mode
10008 buffer with \\[org-insert-link].")
10010 (defvar org-execute-file-search-functions nil
10011 "List of functions to execute a file search triggered by a link.
10013 Functions added to this hook must accept a single argument, the
10014 search string that was part of the file link, the part after the
10015 double colon. The function must first check if it would like to
10016 handle this search, for example by checking the `major-mode' or
10017 the file extension. If it decides not to handle this search, it
10018 should just return nil to give other functions a chance. If it
10019 does handle the search, it must return a non-nil value to keep
10020 other functions from trying.
10022 Each function can access the current prefix argument through the
10023 variable `current-prefix-argument'. Note that a single prefix is
10024 used to force opening a link in Emacs, so it may be good to only
10025 use a numeric or double prefix to guide the search function.
10027 In case this is needed, a function in this hook can also restore
10028 the window configuration before `org-open-at-point' was called using:
10030 (set-window-configuration org-window-config-before-follow-link)")
10032 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10033 (defun org-link-search (s &optional type avoid-pos stealth)
10034 "Search for a link search option.
10035 If S is surrounded by forward slashes, it is interpreted as a
10036 regular expression. In org-mode files, this will create an `org-occur'
10037 sparse tree. In ordinary files, `occur' will be used to list matches.
10038 If the current buffer is in `dired-mode', grep will be used to search
10039 in all files. If AVOID-POS is given, ignore matches near that position.
10041 When optional argument STEALTH is non-nil, do not modify
10042 visibility around point, thus ignoring
10043 `org-show-hierarchy-above', `org-show-following-heading' and
10044 `org-show-siblings' variables."
10045 (let ((case-fold-search t)
10046 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10047 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10048 (append '(("") (" ") ("\t") ("\n"))
10049 org-emphasis-alist)
10050 "\\|") "\\)"))
10051 (pos (point))
10052 (pre nil) (post nil)
10053 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10054 (cond
10055 ;; First check if there are any special search functions
10056 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10057 ;; Now try the builtin stuff
10058 ((and (equal (string-to-char s0) ?#)
10059 (> (length s0) 1)
10060 (save-excursion
10061 (goto-char (point-min))
10062 (and
10063 (re-search-forward
10064 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10065 (setq type 'dedicated
10066 pos (match-beginning 0))))
10067 ;; There is an exact target for this
10068 (goto-char pos)
10069 (org-back-to-heading t)))
10070 ((save-excursion
10071 (goto-char (point-min))
10072 (and
10073 (re-search-forward
10074 (concat "<<" (regexp-quote s0) ">>") nil t)
10075 (setq type 'dedicated
10076 pos (match-beginning 0))))
10077 ;; There is an exact target for this
10078 (goto-char pos))
10079 ((save-excursion
10080 (goto-char (point-min))
10081 (and
10082 (re-search-forward
10083 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10084 (setq type 'dedicated pos (match-beginning 0))))
10085 ;; Found an invisible target.
10086 (goto-char pos))
10087 ((save-excursion
10088 (goto-char (point-min))
10089 (and
10090 (re-search-forward
10091 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10092 (setq type 'dedicated pos (match-beginning 0))))
10093 ;; Found an element with a matching #+name affiliated keyword.
10094 (goto-char pos))
10095 ((and (string-match "^(\\(.*\\))$" s0)
10096 (save-excursion
10097 (goto-char (point-min))
10098 (and
10099 (re-search-forward
10100 (concat "[^[]" (regexp-quote
10101 (format org-coderef-label-format
10102 (match-string 1 s0))))
10103 nil t)
10104 (setq type 'dedicated
10105 pos (1+ (match-beginning 0))))))
10106 ;; There is a coderef target for this
10107 (goto-char pos))
10108 ((string-match "^/\\(.*\\)/$" s)
10109 ;; A regular expression
10110 (cond
10111 ((derived-mode-p 'org-mode)
10112 (org-occur (match-string 1 s)))
10113 ;;((eq major-mode 'dired-mode)
10114 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10115 (t (org-do-occur (match-string 1 s)))))
10116 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10117 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10118 (goto-char (point-min))
10119 (cond
10120 ((let (case-fold-search)
10121 (re-search-forward (format org-complex-heading-regexp-format
10122 (regexp-quote s))
10123 nil t))
10124 ;; OK, found a match
10125 (setq type 'dedicated)
10126 (goto-char (match-beginning 0)))
10127 ((and (not org-link-search-inhibit-query)
10128 (eq org-link-search-must-match-exact-headline 'query-to-create)
10129 (y-or-n-p "No match - create this as a new heading? "))
10130 (goto-char (point-max))
10131 (or (bolp) (newline))
10132 (insert "* " s "\n")
10133 (beginning-of-line 0))
10135 (goto-char pos)
10136 (error "No match"))))
10138 ;; A normal search string
10139 (when (equal (string-to-char s) ?*)
10140 ;; Anchor on headlines, post may include tags.
10141 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10142 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10143 s (substring s 1)))
10144 (remove-text-properties
10145 0 (length s)
10146 '(face nil mouse-face nil keymap nil fontified nil) s)
10147 ;; Make a series of regular expressions to find a match
10148 (setq words (org-split-string s "[ \n\r\t]+")
10150 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10151 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10152 "\\)" markers)
10153 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10154 re2a (concat "[ \t\r\n]" re2a_)
10155 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10156 re4 (concat "[^a-zA-Z_]" re4_)
10158 re1 (concat pre re2 post)
10159 re3 (concat pre (if pre re4_ re4) post)
10160 re5 (concat pre ".*" re4)
10161 re2 (concat pre re2)
10162 re2a (concat pre (if pre re2a_ re2a))
10163 re4 (concat pre (if pre re4_ re4))
10164 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10165 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10166 re5 "\\)"
10168 (cond
10169 ((eq type 'org-occur) (org-occur reall))
10170 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10171 (t (goto-char (point-min))
10172 (setq type 'fuzzy)
10173 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10174 (org-search-not-self 1 re1 nil t)
10175 (org-search-not-self 1 re2 nil t)
10176 (org-search-not-self 1 re2a nil t)
10177 (org-search-not-self 1 re3 nil t)
10178 (org-search-not-self 1 re4 nil t)
10179 (org-search-not-self 1 re5 nil t)
10181 (goto-char (match-beginning 1))
10182 (goto-char pos)
10183 (error "No match"))))))
10184 (and (derived-mode-p 'org-mode)
10185 (not stealth)
10186 (org-show-context 'link-search))
10187 type))
10189 (defun org-search-not-self (group &rest args)
10190 "Execute `re-search-forward', but only accept matches that do not
10191 enclose the position of `org-open-link-marker'."
10192 (let ((m org-open-link-marker))
10193 (catch 'exit
10194 (while (apply 're-search-forward args)
10195 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10196 (goto-char (match-end group))
10197 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10198 (> (match-beginning 0) (marker-position m))
10199 (< (match-end 0) (marker-position m)))
10200 (save-match-data
10201 (or (not (org-in-regexp
10202 org-bracket-link-analytic-regexp 1))
10203 (not (match-end 4)) ; no description
10204 (and (<= (match-beginning 4) (point))
10205 (>= (match-end 4) (point))))))
10206 (throw 'exit (point))))))))
10208 (defun org-get-buffer-for-internal-link (buffer)
10209 "Return a buffer to be used for displaying the link target of internal links."
10210 (cond
10211 ((not org-display-internal-link-with-indirect-buffer)
10212 buffer)
10213 ((string-match "(Clone)$" (buffer-name buffer))
10214 (message "Buffer is already a clone, not making another one")
10215 ;; we also do not modify visibility in this case
10216 buffer)
10217 (t ; make a new indirect buffer for displaying the link
10218 (let* ((bn (buffer-name buffer))
10219 (ibn (concat bn "(Clone)"))
10220 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10221 (with-current-buffer ib (org-overview))
10222 ib))))
10224 (defun org-do-occur (regexp &optional cleanup)
10225 "Call the Emacs command `occur'.
10226 If CLEANUP is non-nil, remove the printout of the regular expression
10227 in the *Occur* buffer. This is useful if the regex is long and not useful
10228 to read."
10229 (occur regexp)
10230 (when cleanup
10231 (let ((cwin (selected-window)) win beg end)
10232 (when (setq win (get-buffer-window "*Occur*"))
10233 (select-window win))
10234 (goto-char (point-min))
10235 (when (re-search-forward "match[a-z]+" nil t)
10236 (setq beg (match-end 0))
10237 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10238 (setq end (1- (match-beginning 0)))))
10239 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10240 (goto-char (point-min))
10241 (select-window cwin))))
10243 ;;; The mark ring for links jumps
10245 (defvar org-mark-ring nil
10246 "Mark ring for positions before jumps in Org-mode.")
10247 (defvar org-mark-ring-last-goto nil
10248 "Last position in the mark ring used to go back.")
10249 ;; Fill and close the ring
10250 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10251 (loop for i from 1 to org-mark-ring-length do
10252 (push (make-marker) org-mark-ring))
10253 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10254 org-mark-ring)
10256 (defun org-mark-ring-push (&optional pos buffer)
10257 "Put the current position or POS into the mark ring and rotate it."
10258 (interactive)
10259 (setq pos (or pos (point)))
10260 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10261 (move-marker (car org-mark-ring)
10262 (or pos (point))
10263 (or buffer (current-buffer)))
10264 (message "%s"
10265 (substitute-command-keys
10266 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10268 (defun org-mark-ring-goto (&optional n)
10269 "Jump to the previous position in the mark ring.
10270 With prefix arg N, jump back that many stored positions. When
10271 called several times in succession, walk through the entire ring.
10272 Org-mode commands jumping to a different position in the current file,
10273 or to another Org-mode file, automatically push the old position
10274 onto the ring."
10275 (interactive "p")
10276 (let (p m)
10277 (if (eq last-command this-command)
10278 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10279 (setq p org-mark-ring))
10280 (setq org-mark-ring-last-goto p)
10281 (setq m (car p))
10282 (org-pop-to-buffer-same-window (marker-buffer m))
10283 (goto-char m)
10284 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10286 (defun org-remove-angle-brackets (s)
10287 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10288 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10290 (defun org-add-angle-brackets (s)
10291 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10292 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10294 (defun org-remove-double-quotes (s)
10295 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10296 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10299 ;;; Following specific links
10301 (defun org-follow-timestamp-link ()
10302 "Open an agenda view for the time-stamp date/range at point."
10303 (cond
10304 ((org-at-date-range-p t)
10305 (let ((org-agenda-start-on-weekday)
10306 (t1 (match-string 1))
10307 (t2 (match-string 2)) tt1 tt2)
10308 (setq tt1 (time-to-days (org-time-string-to-time t1))
10309 tt2 (time-to-days (org-time-string-to-time t2)))
10310 (let ((org-agenda-buffer-tmp-name
10311 (format "*Org Agenda(a:%s)"
10312 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10313 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10314 ((org-at-timestamp-p t)
10315 (let ((org-agenda-buffer-tmp-name
10316 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10317 (org-agenda-list nil (time-to-days (org-time-string-to-time
10318 (substring (match-string 1) 0 10)))
10319 1)))
10320 (t (error "This should not happen"))))
10323 ;;; Following file links
10324 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10325 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10326 (declare-function mailcap-mime-info
10327 "mailcap" (string &optional request no-decode))
10328 (defvar org-wait nil)
10329 (defun org-open-file (path &optional in-emacs line search)
10330 "Open the file at PATH.
10331 First, this expands any special file name abbreviations. Then the
10332 configuration variable `org-file-apps' is checked if it contains an
10333 entry for this file type, and if yes, the corresponding command is launched.
10335 If no application is found, Emacs simply visits the file.
10337 With optional prefix argument IN-EMACS, Emacs will visit the file.
10338 With a double \\[universal-argument] \\[universal-argument] \
10339 prefix arg, Org tries to avoid opening in Emacs
10340 and to use an external application to visit the file.
10342 Optional LINE specifies a line to go to, optional SEARCH a string
10343 to search for. If LINE or SEARCH is given, the file will be
10344 opened in Emacs, unless an entry from org-file-apps that makes
10345 use of groups in a regexp matches.
10347 If you want to change the way frames are used when following a
10348 link, please customize `org-link-frame-setup'.
10350 If the file does not exist, an error is thrown."
10351 (let* ((file (if (equal path "")
10352 buffer-file-name
10353 (substitute-in-file-name (expand-file-name path))))
10354 (file-apps (append org-file-apps (org-default-apps)))
10355 (apps (org-remove-if
10356 'org-file-apps-entry-match-against-dlink-p file-apps))
10357 (apps-dlink (org-remove-if-not
10358 'org-file-apps-entry-match-against-dlink-p file-apps))
10359 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10360 (dirp (if remp nil (file-directory-p file)))
10361 (file (if (and dirp org-open-directory-means-index-dot-org)
10362 (concat (file-name-as-directory file) "index.org")
10363 file))
10364 (a-m-a-p (assq 'auto-mode apps))
10365 (dfile (downcase file))
10366 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10367 (link (cond ((and (eq line nil)
10368 (eq search nil))
10369 file)
10370 (line
10371 (concat file "::" (number-to-string line)))
10372 (search
10373 (concat file "::" search))))
10374 (dlink (downcase link))
10375 (old-buffer (current-buffer))
10376 (old-pos (point))
10377 (old-mode major-mode)
10378 ext cmd link-match-data)
10379 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10380 (setq ext (match-string 1 dfile))
10381 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10382 (setq ext (match-string 1 dfile))))
10383 (cond
10384 ((member in-emacs '((16) system))
10385 (setq cmd (cdr (assoc 'system apps))))
10386 (in-emacs (setq cmd 'emacs))
10388 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10389 (and dirp (cdr (assoc 'directory apps)))
10390 ; first, try matching against apps-dlink
10391 ; if we get a match here, store the match data for later
10392 (let ((match (assoc-default dlink apps-dlink
10393 'string-match)))
10394 (if match
10395 (progn (setq link-match-data (match-data))
10396 match)
10397 (progn (setq in-emacs (or in-emacs line search))
10398 nil))) ; if we have no match in apps-dlink,
10399 ; always open the file in emacs if line or search
10400 ; is given (for backwards compatibility)
10401 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10402 'string-match)
10403 (cdr (assoc ext apps))
10404 (cdr (assoc t apps))))))
10405 (when (eq cmd 'system)
10406 (setq cmd (cdr (assoc 'system apps))))
10407 (when (eq cmd 'default)
10408 (setq cmd (cdr (assoc t apps))))
10409 (when (eq cmd 'mailcap)
10410 (require 'mailcap)
10411 (mailcap-parse-mailcaps)
10412 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10413 (command (mailcap-mime-info mime-type)))
10414 (if (stringp command)
10415 (setq cmd command)
10416 (setq cmd 'emacs))))
10417 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10418 (not (file-exists-p file))
10419 (not org-open-non-existing-files))
10420 (error "No such file: %s" file))
10421 (cond
10422 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10423 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10424 (while (string-match "['\"]%s['\"]" cmd)
10425 (setq cmd (replace-match "%s" t t cmd)))
10426 (while (string-match "%s" cmd)
10427 (setq cmd (replace-match
10428 (save-match-data
10429 (shell-quote-argument
10430 (convert-standard-filename file)))
10431 t t cmd)))
10433 ;; Replace "%1", "%2" etc. in command with group matches from regex
10434 (save-match-data
10435 (let ((match-index 1)
10436 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10437 (set-match-data link-match-data)
10438 (while (<= match-index number-of-groups)
10439 (let ((regex (concat "%" (number-to-string match-index)))
10440 (replace-with (match-string match-index dlink)))
10441 (while (string-match regex cmd)
10442 (setq cmd (replace-match replace-with t t cmd))))
10443 (setq match-index (+ match-index 1)))))
10445 (save-window-excursion
10446 (message "Running %s...done" cmd)
10447 (start-process-shell-command cmd nil cmd)
10448 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10449 ((or (stringp cmd)
10450 (eq cmd 'emacs))
10451 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10452 (widen)
10453 (if line (org-goto-line line)
10454 (if search (org-link-search search))))
10455 ((consp cmd)
10456 (let ((file (convert-standard-filename file)))
10457 (save-match-data
10458 (set-match-data link-match-data)
10459 (eval cmd))))
10460 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10461 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10462 (or (not (equal old-buffer (current-buffer)))
10463 (not (equal old-pos (point))))
10464 (org-mark-ring-push old-pos old-buffer))))
10466 (defun org-file-apps-entry-match-against-dlink-p (entry)
10467 "This function returns non-nil if `entry' uses a regular
10468 expression which should be matched against the whole link by
10469 org-open-file.
10471 It assumes that is the case when the entry uses a regular
10472 expression which has at least one grouping construct and the
10473 action is either a lisp form or a command string containing
10474 '%1', i.e. using at least one subexpression match as a
10475 parameter."
10476 (let ((selector (car entry))
10477 (action (cdr entry)))
10478 (if (stringp selector)
10479 (and (> (regexp-opt-depth selector) 0)
10480 (or (and (stringp action)
10481 (string-match "%[0-9]" action))
10482 (consp action)))
10483 nil)))
10485 (defun org-default-apps ()
10486 "Return the default applications for this operating system."
10487 (cond
10488 ((eq system-type 'darwin)
10489 org-file-apps-defaults-macosx)
10490 ((eq system-type 'windows-nt)
10491 org-file-apps-defaults-windowsnt)
10492 (t org-file-apps-defaults-gnu)))
10494 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10495 "Convert extensions to regular expressions in the cars of LIST.
10496 Also, weed out any non-string entries, because the return value is used
10497 only for regexp matching.
10498 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10499 point to the symbol `emacs', indicating that the file should
10500 be opened in Emacs."
10501 (append
10502 (delq nil
10503 (mapcar (lambda (x)
10504 (if (not (stringp (car x)))
10506 (if (string-match "\\W" (car x))
10508 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10509 list))
10510 (if add-auto-mode
10511 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10513 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10514 (defun org-file-remote-p (file)
10515 "Test whether FILE specifies a location on a remote system.
10516 Return non-nil if the location is indeed remote.
10518 For example, the filename \"/user@host:/foo\" specifies a location
10519 on the system \"/user@host:\"."
10520 (cond ((fboundp 'file-remote-p)
10521 (file-remote-p file))
10522 ((fboundp 'tramp-handle-file-remote-p)
10523 (tramp-handle-file-remote-p file))
10524 ((and (boundp 'ange-ftp-name-format)
10525 (string-match (car ange-ftp-name-format) file))
10526 t)))
10529 ;;;; Refiling
10531 (defun org-get-org-file ()
10532 "Read a filename, with default directory `org-directory'."
10533 (let ((default (or org-default-notes-file remember-data-file)))
10534 (read-file-name (format "File name [%s]: " default)
10535 (file-name-as-directory org-directory)
10536 default)))
10538 (defun org-notes-order-reversed-p ()
10539 "Check if the current file should receive notes in reversed order."
10540 (cond
10541 ((not org-reverse-note-order) nil)
10542 ((eq t org-reverse-note-order) t)
10543 ((not (listp org-reverse-note-order)) nil)
10544 (t (catch 'exit
10545 (let ((all org-reverse-note-order)
10546 entry)
10547 (while (setq entry (pop all))
10548 (if (string-match (car entry) buffer-file-name)
10549 (throw 'exit (cdr entry))))
10550 nil)))))
10552 (defvar org-refile-target-table nil
10553 "The list of refile targets, created by `org-refile'.")
10555 (defvar org-agenda-new-buffers nil
10556 "Buffers created to visit agenda files.")
10558 (defvar org-refile-cache nil
10559 "Cache for refile targets.")
10561 (defvar org-refile-markers nil
10562 "All the markers used for caching refile locations.")
10564 (defun org-refile-marker (pos)
10565 "Get a new refile marker, but only if caching is in use."
10566 (if (not org-refile-use-cache)
10568 (let ((m (make-marker)))
10569 (move-marker m pos)
10570 (push m org-refile-markers)
10571 m)))
10573 (defun org-refile-cache-clear ()
10574 "Clear the refile cache and disable all the markers."
10575 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10576 (setq org-refile-markers nil)
10577 (setq org-refile-cache nil)
10578 (message "Refile cache has been cleared"))
10580 (defun org-refile-cache-check-set (set)
10581 "Check if all the markers in the cache still have live buffers."
10582 (let (marker)
10583 (catch 'exit
10584 (while (and set (setq marker (nth 3 (pop set))))
10585 ;; if org-refile-use-outline-path is 'file, marker may be nil
10586 (when (and marker (null (marker-buffer marker)))
10587 (message "not found") (sit-for 3)
10588 (throw 'exit nil)))
10589 t)))
10591 (defun org-refile-cache-put (set &rest identifiers)
10592 "Push the refile targets SET into the cache, under IDENTIFIERS."
10593 (let* ((key (sha1 (prin1-to-string identifiers)))
10594 (entry (assoc key org-refile-cache)))
10595 (if entry
10596 (setcdr entry set)
10597 (push (cons key set) org-refile-cache))))
10599 (defun org-refile-cache-get (&rest identifiers)
10600 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10601 (cond
10602 ((not org-refile-cache) nil)
10603 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10605 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10606 org-refile-cache))))
10607 (and set (org-refile-cache-check-set set) set)))))
10609 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10610 "Produce a table with refile targets."
10611 (let ((case-fold-search nil)
10612 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10613 (entries (or org-refile-targets '((nil . (:level . 1)))))
10614 targets tgs txt re files f desc descre fast-path-p level pos0)
10615 (message "Getting targets...")
10616 (with-current-buffer (or default-buffer (current-buffer))
10617 (while (setq entry (pop entries))
10618 (setq files (car entry) desc (cdr entry))
10619 (setq fast-path-p nil)
10620 (cond
10621 ((null files) (setq files (list (current-buffer))))
10622 ((eq files 'org-agenda-files)
10623 (setq files (org-agenda-files 'unrestricted)))
10624 ((and (symbolp files) (fboundp files))
10625 (setq files (funcall files)))
10626 ((and (symbolp files) (boundp files))
10627 (setq files (symbol-value files))))
10628 (if (stringp files) (setq files (list files)))
10629 (cond
10630 ((eq (car desc) :tag)
10631 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10632 ((eq (car desc) :todo)
10633 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10634 ((eq (car desc) :regexp)
10635 (setq descre (cdr desc)))
10636 ((eq (car desc) :level)
10637 (setq descre (concat "^\\*\\{" (number-to-string
10638 (if org-odd-levels-only
10639 (1- (* 2 (cdr desc)))
10640 (cdr desc)))
10641 "\\}[ \t]")))
10642 ((eq (car desc) :maxlevel)
10643 (setq fast-path-p t)
10644 (setq descre (concat "^\\*\\{1," (number-to-string
10645 (if org-odd-levels-only
10646 (1- (* 2 (cdr desc)))
10647 (cdr desc)))
10648 "\\}[ \t]")))
10649 (t (error "Bad refiling target description %s" desc)))
10650 (while (setq f (pop files))
10651 (with-current-buffer
10652 (if (bufferp f) f (org-get-agenda-file-buffer f))
10654 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10655 (progn
10656 (if (bufferp f) (setq f (buffer-file-name
10657 (buffer-base-buffer f))))
10658 (setq f (and f (expand-file-name f)))
10659 (if (eq org-refile-use-outline-path 'file)
10660 (push (list (file-name-nondirectory f) f nil nil) tgs))
10661 (save-excursion
10662 (save-restriction
10663 (widen)
10664 (goto-char (point-min))
10665 (while (re-search-forward descre nil t)
10666 (goto-char (setq pos0 (point-at-bol)))
10667 (catch 'next
10668 (when org-refile-target-verify-function
10669 (save-match-data
10670 (or (funcall org-refile-target-verify-function)
10671 (throw 'next t))))
10672 (when (and (looking-at org-complex-heading-regexp)
10673 (not (member (match-string 4) excluded-entries))
10674 (match-string 4))
10675 (setq level (org-reduced-level
10676 (- (match-end 1) (match-beginning 1)))
10677 txt (org-link-display-format (match-string 4))
10678 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10679 re (format org-complex-heading-regexp-format
10680 (regexp-quote (match-string 4))))
10681 (when org-refile-use-outline-path
10682 (setq txt (mapconcat
10683 'org-protect-slash
10684 (append
10685 (if (eq org-refile-use-outline-path
10686 'file)
10687 (list (file-name-nondirectory
10688 (buffer-file-name
10689 (buffer-base-buffer))))
10690 (if (eq org-refile-use-outline-path
10691 'full-file-path)
10692 (list (buffer-file-name
10693 (buffer-base-buffer)))))
10694 (org-get-outline-path fast-path-p
10695 level txt)
10696 (list txt))
10697 "/")))
10698 (push (list txt f re (org-refile-marker (point)))
10699 tgs)))
10700 (when (= (point) pos0)
10701 ;; verification function has not moved point
10702 (goto-char (point-at-eol))))))))
10703 (when org-refile-use-cache
10704 (org-refile-cache-put tgs (buffer-file-name) descre))
10705 (setq targets (append tgs targets))
10706 ))))
10707 (message "Getting targets...done")
10708 (nreverse targets)))
10710 (defun org-protect-slash (s)
10711 (while (string-match "/" s)
10712 (setq s (replace-match "\\" t t s)))
10715 (defvar org-olpa (make-vector 20 nil))
10717 (defun org-get-outline-path (&optional fastp level heading)
10718 "Return the outline path to the current entry, as a list.
10720 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10721 routine which makes outline path derivations for an entire file,
10722 avoiding backtracing. Refile target collection makes use of that."
10723 (if fastp
10724 (progn
10725 (if (> level 19)
10726 (error "Outline path failure, more than 19 levels"))
10727 (loop for i from level upto 19 do
10728 (aset org-olpa i nil))
10729 (prog1
10730 (delq nil (append org-olpa nil))
10731 (aset org-olpa level heading)))
10732 (let (rtn case-fold-search)
10733 (save-excursion
10734 (save-restriction
10735 (widen)
10736 (while (org-up-heading-safe)
10737 (when (looking-at org-complex-heading-regexp)
10738 (push (org-match-string-no-properties 4) rtn)))
10739 rtn)))))
10741 (defun org-format-outline-path (path &optional width prefix separator)
10742 "Format the outline path PATH for display.
10743 WIDTH is the maximum number of characters that is available.
10744 PREFIX is a prefix to be included in the returned string,
10745 such as the file name.
10746 SEPARATOR is inserted between the different parts of the path,
10747 the default is \"/\"."
10748 (setq width (or width 79))
10749 (if prefix (setq width (- width (length prefix))))
10750 (if (not path)
10751 (or prefix "")
10752 (let* ((nsteps (length path))
10753 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10754 (maxwidth (if (<= total-width width)
10755 10000 ;; everything fits
10756 ;; we need to shorten the level headings
10757 (/ (- width nsteps) nsteps)))
10758 (org-odd-levels-only nil)
10759 (n 0)
10760 (total (1+ (length prefix))))
10761 (setq maxwidth (max maxwidth 10))
10762 (concat prefix
10763 (if prefix (or separator "/"))
10764 (mapconcat
10765 (lambda (h)
10766 (setq n (1+ n))
10767 (if (and (= n nsteps) (< maxwidth 10000))
10768 (setq maxwidth (- total-width total)))
10769 (if (< (length h) maxwidth)
10770 (progn (setq total (+ total (length h) 1)) h)
10771 (setq h (substring h 0 (- maxwidth 2))
10772 total (+ total maxwidth 1))
10773 (if (string-match "[ \t]+\\'" h)
10774 (setq h (substring h 0 (match-beginning 0))))
10775 (setq h (concat h "..")))
10776 (org-add-props h nil 'face
10777 (nth (% (1- n) org-n-level-faces)
10778 org-level-faces))
10780 path (or separator "/"))))))
10782 (defun org-display-outline-path (&optional file current separator just-return-string)
10783 "Display the current outline path in the echo area.
10785 If FILE is non-nil, prepend the output with the file name.
10786 If CURRENT is non-nil, append the current heading to the output.
10787 SEPARATOR is passed through to `org-format-outline-path'. It separates
10788 the different parts of the path and defaults to \"/\".
10789 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
10790 (interactive "P")
10791 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10792 (case-fold-search nil)
10793 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
10794 res)
10795 (if current (setq path (append path
10796 (save-excursion
10797 (org-back-to-heading t)
10798 (if (looking-at org-complex-heading-regexp)
10799 (list (match-string 4)))))))
10800 (setq res
10801 (org-format-outline-path
10802 path
10803 (1- (frame-width))
10804 (and file bfn (concat (file-name-nondirectory bfn) separator))
10805 separator))
10806 (if just-return-string
10807 (org-no-properties res)
10808 (message "%s" res))))
10810 (defvar org-refile-history nil
10811 "History for refiling operations.")
10813 (defvar org-after-refile-insert-hook nil
10814 "Hook run after `org-refile' has inserted its stuff at the new location.
10815 Note that this is still *before* the stuff will be removed from
10816 the *old* location.")
10818 (defvar org-capture-last-stored-marker)
10819 (defvar org-refile-keep nil
10820 "Non-nil means `org-refile' will copy instead of refile.")
10822 (defun org-copy ()
10823 "Like `org-refile', but copy."
10824 (interactive)
10825 (let ((org-refile-keep t))
10826 (funcall 'org-refile nil nil nil "Copy")))
10828 (defun org-refile (&optional goto default-buffer rfloc msg)
10829 "Move the entry or entries at point to another heading.
10830 The list of target headings is compiled using the information in
10831 `org-refile-targets', which see.
10833 At the target location, the entry is filed as a subitem of the target
10834 heading. Depending on `org-reverse-note-order', the new subitem will
10835 either be the first or the last subitem.
10837 If there is an active region, all entries in that region will be moved.
10838 However, the region must fulfill the requirement that the first heading
10839 is the first one sets the top-level of the moved text - at most siblings
10840 below it are allowed.
10842 With prefix arg GOTO, the command will only visit the target location
10843 and not actually move anything.
10845 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10846 go to the location where the last refiling operation has put the subtree.
10847 With a prefix argument of `2', refile to the running clock.
10849 RFLOC can be a refile location obtained in a different way.
10851 MSG is a string to replace \"Refile\" in the default prompt with
10852 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
10854 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10856 If you are using target caching (see `org-refile-use-cache'),
10857 you have to clear the target cache in order to find new targets.
10858 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10859 prefix argument (`C-u C-u C-u C-c C-w')."
10861 (interactive "P")
10862 (if (member goto '(0 (64)))
10863 (org-refile-cache-clear)
10864 (let* ((actionmsg (or msg "Refile"))
10865 (cbuf (current-buffer))
10866 (regionp (org-region-active-p))
10867 (region-start (and regionp (region-beginning)))
10868 (region-end (and regionp (region-end)))
10869 (region-length (and regionp (- region-end region-start)))
10870 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10871 pos it nbuf file re level reversed)
10872 (setq last-command nil)
10873 (when regionp
10874 (goto-char region-start)
10875 (or (bolp) (goto-char (point-at-bol)))
10876 (setq region-start (point))
10877 (unless (or (org-kill-is-subtree-p
10878 (buffer-substring region-start region-end))
10879 (prog1 org-refile-active-region-within-subtree
10880 (org-toggle-heading)))
10881 (error "The region is not a (sequence of) subtree(s)")))
10882 (if (equal goto '(16))
10883 (org-refile-goto-last-stored)
10884 (when (or
10885 (and (equal goto 2)
10886 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10887 (prog1
10888 (setq it (list (or org-clock-heading "running clock")
10889 (buffer-file-name
10890 (marker-buffer org-clock-hd-marker))
10892 (marker-position org-clock-hd-marker)))
10893 (setq goto nil)))
10894 (setq it (or rfloc
10895 (let (heading-text)
10896 (save-excursion
10897 (unless goto
10898 (org-back-to-heading t)
10899 (setq heading-text
10900 (nth 4 (org-heading-components))))
10902 (org-refile-get-location
10903 (cond (goto "Goto")
10904 (regionp (concat actionmsg " region to"))
10905 (t (concat actionmsg " subtree \""
10906 heading-text "\" to")))
10907 default-buffer
10908 (and (not (equal '(4) goto))
10909 org-refile-allow-creating-parent-nodes)
10910 goto))))))
10911 (setq file (nth 1 it)
10912 re (nth 2 it)
10913 pos (nth 3 it))
10914 (if (and (not goto)
10916 (equal (buffer-file-name) file)
10917 (if regionp
10918 (and (>= pos region-start)
10919 (<= pos region-end))
10920 (and (>= pos (point))
10921 (< pos (save-excursion
10922 (org-end-of-subtree t t))))))
10923 (error "Cannot refile to position inside the tree or region"))
10925 (setq nbuf (or (find-buffer-visiting file)
10926 (find-file-noselect file)))
10927 (if goto
10928 (progn
10929 (org-pop-to-buffer-same-window nbuf)
10930 (goto-char pos)
10931 (org-show-context 'org-goto))
10932 (if regionp
10933 (progn
10934 (org-kill-new (buffer-substring region-start region-end))
10935 (org-save-markers-in-region region-start region-end))
10936 (org-copy-subtree 1 nil t))
10937 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10938 (find-file-noselect file)))
10939 (setq reversed (org-notes-order-reversed-p))
10940 (save-excursion
10941 (save-restriction
10942 (widen)
10943 (if pos
10944 (progn
10945 (goto-char pos)
10946 (looking-at org-outline-regexp)
10947 (setq level (org-get-valid-level (funcall outline-level) 1))
10948 (goto-char
10949 (if reversed
10950 (or (outline-next-heading) (point-max))
10951 (or (save-excursion (org-get-next-sibling))
10952 (org-end-of-subtree t t)
10953 (point-max)))))
10954 (setq level 1)
10955 (if (not reversed)
10956 (goto-char (point-max))
10957 (goto-char (point-min))
10958 (or (outline-next-heading) (goto-char (point-max)))))
10959 (if (not (bolp)) (newline))
10960 (org-paste-subtree level)
10961 (when org-log-refile
10962 (org-add-log-setup 'refile nil nil 'findpos
10963 org-log-refile)
10964 (unless (eq org-log-refile 'note)
10965 (save-excursion (org-add-log-note))))
10966 (and org-auto-align-tags
10967 (let ((org-loop-over-headlines-in-active-region nil))
10968 (org-set-tags nil t)))
10969 (bookmark-set "org-refile-last-stored")
10970 ;; If we are refiling for capture, make sure that the
10971 ;; last-capture pointers point here
10972 (when (org-bound-and-true-p org-refile-for-capture)
10973 (bookmark-set "org-capture-last-stored-marker")
10974 (move-marker org-capture-last-stored-marker (point)))
10975 (if (fboundp 'deactivate-mark) (deactivate-mark))
10976 (run-hooks 'org-after-refile-insert-hook))))
10977 (unless org-refile-keep
10978 (if regionp
10979 (delete-region (point) (+ (point) region-length))
10980 (org-cut-subtree)))
10981 (when (featurep 'org-inlinetask)
10982 (org-inlinetask-remove-END-maybe))
10983 (setq org-markers-to-move nil)
10984 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
10986 (defun org-refile-goto-last-stored ()
10987 "Go to the location where the last refile was stored."
10988 (interactive)
10989 (bookmark-jump "org-refile-last-stored")
10990 (message "This is the location of the last refile"))
10992 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10993 no-exclude)
10994 "Prompt the user for a refile location, using PROMPT.
10995 PROMPT should not be suffixed with a colon and a space, because
10996 this function appends the default value from
10997 `org-refile-history' automatically, if that is not empty.
10998 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10999 this is used for the GOTO interface."
11000 (let ((org-refile-targets org-refile-targets)
11001 (org-refile-use-outline-path org-refile-use-outline-path)
11002 excluded-entries)
11003 (when (and (derived-mode-p 'org-mode)
11004 (not org-refile-use-cache)
11005 (not no-exclude))
11006 (org-map-tree
11007 (lambda()
11008 (setq excluded-entries
11009 (append excluded-entries (list (org-get-heading t t)))))))
11010 (setq org-refile-target-table
11011 (org-refile-get-targets default-buffer excluded-entries)))
11012 (unless org-refile-target-table
11013 (error "No refile targets"))
11014 (let* ((cbuf (current-buffer))
11015 (partial-completion-mode nil)
11016 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11017 (cfunc (if (and org-refile-use-outline-path
11018 org-outline-path-complete-in-steps)
11019 'org-olpath-completing-read
11020 'org-icompleting-read))
11021 (extra (if org-refile-use-outline-path "/" ""))
11022 (cbnex (concat (buffer-name) extra))
11023 (filename (and cfn (expand-file-name cfn)))
11024 (tbl (mapcar
11025 (lambda (x)
11026 (if (and (not (member org-refile-use-outline-path
11027 '(file full-file-path)))
11028 (not (equal filename (nth 1 x))))
11029 (cons (concat (car x) extra " ("
11030 (file-name-nondirectory (nth 1 x)) ")")
11031 (cdr x))
11032 (cons (concat (car x) extra) (cdr x))))
11033 org-refile-target-table))
11034 (completion-ignore-case t)
11035 cdef
11036 (prompt (concat prompt
11037 (or (and (car org-refile-history)
11038 (concat " (default " (car org-refile-history) ")"))
11039 (and (assoc cbnex tbl) (setq cdef cbnex)
11040 (concat " (default " cbnex ")"))) ": "))
11041 pa answ parent-target child parent old-hist)
11042 (setq old-hist org-refile-history)
11043 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11044 nil 'org-refile-history (or cdef (car org-refile-history))))
11045 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11046 (org-refile-check-position pa)
11047 (if pa
11048 (progn
11049 (when (or (not org-refile-history)
11050 (not (eq old-hist org-refile-history))
11051 (not (equal (car pa) (car org-refile-history))))
11052 (setq org-refile-history
11053 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11054 org-refile-history
11055 (cdr org-refile-history))))
11056 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11057 (pop org-refile-history)))
11059 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11060 (progn
11061 (setq parent (match-string 1 answ)
11062 child (match-string 2 answ))
11063 (setq parent-target (or (assoc parent tbl)
11064 (assoc (concat parent "/") tbl)))
11065 (when (and parent-target
11066 (or (eq new-nodes t)
11067 (and (eq new-nodes 'confirm)
11068 (y-or-n-p (format "Create new node \"%s\"? "
11069 child)))))
11070 (org-refile-new-child parent-target child)))
11071 (error "Invalid target location")))))
11073 (declare-function org-string-nw-p "org-macs" (s))
11074 (defun org-refile-check-position (refile-pointer)
11075 "Check if the refile pointer matches the readline to which it points."
11076 (let* ((file (nth 1 refile-pointer))
11077 (re (nth 2 refile-pointer))
11078 (pos (nth 3 refile-pointer))
11079 buffer)
11080 (when (org-string-nw-p re)
11081 (setq buffer (if (markerp pos)
11082 (marker-buffer pos)
11083 (or (find-buffer-visiting file)
11084 (find-file-noselect file))))
11085 (with-current-buffer buffer
11086 (save-excursion
11087 (save-restriction
11088 (widen)
11089 (goto-char pos)
11090 (beginning-of-line 1)
11091 (unless (org-looking-at-p re)
11092 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11094 (defun org-refile-new-child (parent-target child)
11095 "Use refile target PARENT-TARGET to add new CHILD below it."
11096 (unless parent-target
11097 (error "Cannot find parent for new node"))
11098 (let ((file (nth 1 parent-target))
11099 (pos (nth 3 parent-target))
11100 level)
11101 (with-current-buffer (or (find-buffer-visiting file)
11102 (find-file-noselect file))
11103 (save-excursion
11104 (save-restriction
11105 (widen)
11106 (if pos
11107 (goto-char pos)
11108 (goto-char (point-max))
11109 (if (not (bolp)) (newline)))
11110 (when (looking-at org-outline-regexp)
11111 (setq level (funcall outline-level))
11112 (org-end-of-subtree t t))
11113 (org-back-over-empty-lines)
11114 (insert "\n" (make-string
11115 (if pos (org-get-valid-level level 1) 1) ?*)
11116 " " child "\n")
11117 (beginning-of-line 0)
11118 (list (concat (car parent-target) "/" child) file "" (point)))))))
11120 (defun org-olpath-completing-read (prompt collection &rest args)
11121 "Read an outline path like a file name."
11122 (let ((thetable collection)
11123 (org-completion-use-ido nil) ; does not work with ido.
11124 (org-completion-use-iswitchb nil)) ; or iswitchb
11125 (apply
11126 'org-icompleting-read prompt
11127 (lambda (string predicate &optional flag)
11128 (let (rtn r f (l (length string)))
11129 (cond
11130 ((eq flag nil)
11131 ;; try completion
11132 (try-completion string thetable))
11133 ((eq flag t)
11134 ;; all-completions
11135 (setq rtn (all-completions string thetable predicate))
11136 (mapcar
11137 (lambda (x)
11138 (setq r (substring x l))
11139 (if (string-match " ([^)]*)$" x)
11140 (setq f (match-string 0 x))
11141 (setq f ""))
11142 (if (string-match "/" r)
11143 (concat string (substring r 0 (match-end 0)) f)
11145 rtn))
11146 ((eq flag 'lambda)
11147 ;; exact match?
11148 (assoc string thetable)))))
11149 args)))
11151 ;;;; Dynamic blocks
11153 (defun org-find-dblock (name)
11154 "Find the first dynamic block with name NAME in the buffer.
11155 If not found, stay at current position and return nil."
11156 (let ((case-fold-search t) pos)
11157 (save-excursion
11158 (goto-char (point-min))
11159 (setq pos (and (re-search-forward
11160 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11161 (match-beginning 0))))
11162 (if pos (goto-char pos))
11163 pos))
11165 (defconst org-dblock-start-re
11166 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11167 "Matches the start line of a dynamic block, with parameters.")
11169 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11170 "Matches the end of a dynamic block.")
11172 (defun org-create-dblock (plist)
11173 "Create a dynamic block section, with parameters taken from PLIST.
11174 PLIST must contain a :name entry which is used as name of the block."
11175 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11176 (end-of-line 1)
11177 (newline))
11178 (let ((col (current-column))
11179 (name (plist-get plist :name)))
11180 (insert "#+BEGIN: " name)
11181 (while plist
11182 (if (eq (car plist) :name)
11183 (setq plist (cddr plist))
11184 (insert " " (prin1-to-string (pop plist)))))
11185 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11186 (beginning-of-line -2)))
11188 (defun org-prepare-dblock ()
11189 "Prepare dynamic block for refresh.
11190 This empties the block, puts the cursor at the insert position and returns
11191 the property list including an extra property :name with the block name."
11192 (unless (looking-at org-dblock-start-re)
11193 (error "Not at a dynamic block"))
11194 (let* ((begdel (1+ (match-end 0)))
11195 (name (org-no-properties (match-string 1)))
11196 (params (append (list :name name)
11197 (read (concat "(" (match-string 3) ")")))))
11198 (save-excursion
11199 (beginning-of-line 1)
11200 (skip-chars-forward " \t")
11201 (setq params (plist-put params :indentation-column (current-column))))
11202 (unless (re-search-forward org-dblock-end-re nil t)
11203 (error "Dynamic block not terminated"))
11204 (setq params
11205 (append params
11206 (list :content (buffer-substring
11207 begdel (match-beginning 0)))))
11208 (delete-region begdel (match-beginning 0))
11209 (goto-char begdel)
11210 (open-line 1)
11211 params))
11213 (defun org-map-dblocks (&optional command)
11214 "Apply COMMAND to all dynamic blocks in the current buffer.
11215 If COMMAND is not given, use `org-update-dblock'."
11216 (let ((cmd (or command 'org-update-dblock)))
11217 (save-excursion
11218 (goto-char (point-min))
11219 (while (re-search-forward org-dblock-start-re nil t)
11220 (goto-char (match-beginning 0))
11221 (save-excursion
11222 (condition-case nil
11223 (funcall cmd)
11224 (error (message "Error during update of dynamic block"))))
11225 (unless (re-search-forward org-dblock-end-re nil t)
11226 (error "Dynamic block not terminated"))))))
11228 (defun org-dblock-update (&optional arg)
11229 "User command for updating dynamic blocks.
11230 Update the dynamic block at point. With prefix ARG, update all dynamic
11231 blocks in the buffer."
11232 (interactive "P")
11233 (if arg
11234 (org-update-all-dblocks)
11235 (or (looking-at org-dblock-start-re)
11236 (org-beginning-of-dblock))
11237 (org-update-dblock)))
11239 (defun org-update-dblock ()
11240 "Update the dynamic block at point.
11241 This means to empty the block, parse for parameters and then call
11242 the correct writing function."
11243 (interactive)
11244 (save-window-excursion
11245 (let* ((pos (point))
11246 (line (org-current-line))
11247 (params (org-prepare-dblock))
11248 (name (plist-get params :name))
11249 (indent (plist-get params :indentation-column))
11250 (cmd (intern (concat "org-dblock-write:" name))))
11251 (message "Updating dynamic block `%s' at line %d..." name line)
11252 (funcall cmd params)
11253 (message "Updating dynamic block `%s' at line %d...done" name line)
11254 (goto-char pos)
11255 (when (and indent (> indent 0))
11256 (setq indent (make-string indent ?\ ))
11257 (save-excursion
11258 (org-beginning-of-dblock)
11259 (forward-line 1)
11260 (while (not (looking-at org-dblock-end-re))
11261 (insert indent)
11262 (beginning-of-line 2))
11263 (when (looking-at org-dblock-end-re)
11264 (and (looking-at "[ \t]+")
11265 (replace-match ""))
11266 (insert indent)))))))
11268 (defun org-beginning-of-dblock ()
11269 "Find the beginning of the dynamic block at point.
11270 Error if there is no such block at point."
11271 (let ((pos (point))
11272 beg)
11273 (end-of-line 1)
11274 (if (and (re-search-backward org-dblock-start-re nil t)
11275 (setq beg (match-beginning 0))
11276 (re-search-forward org-dblock-end-re nil t)
11277 (> (match-end 0) pos))
11278 (goto-char beg)
11279 (goto-char pos)
11280 (error "Not in a dynamic block"))))
11282 (defun org-update-all-dblocks ()
11283 "Update all dynamic blocks in the buffer.
11284 This function can be used in a hook."
11285 (interactive)
11286 (when (derived-mode-p 'org-mode)
11287 (org-map-dblocks 'org-update-dblock)))
11290 ;;;; Completion
11292 (defconst org-additional-option-like-keywords
11293 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11294 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11295 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11296 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11297 "BEGIN:" "END:"
11298 "ORGTBL" "TBLFM:" "TBLNAME:"
11299 "BEGIN_EXAMPLE" "END_EXAMPLE"
11300 "BEGIN_VERBATIM" "END_VERBATIM"
11301 "BEGIN_QUOTE" "END_QUOTE"
11302 "BEGIN_VERSE" "END_VERSE"
11303 "BEGIN_CENTER" "END_CENTER"
11304 "BEGIN_SRC" "END_SRC"
11305 "BEGIN_RESULT" "END_RESULT"
11306 "BEGIN_lstlisting" "END_lstlisting"
11307 "NAME:" "RESULTS:"
11308 "HEADER:" "HEADERS:"
11309 "COLUMNS:" "PROPERTY:"
11310 "CAPTION:" "LABEL:"
11311 "SETUPFILE:"
11312 "INCLUDE:"
11313 "BIND:"
11314 "MACRO:"))
11316 (defconst org-options-keywords
11317 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11318 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11319 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11320 "LINK_UP:" "LINK_HOME:" "LINK:" "TODO:"
11321 "XSLT:" "MATHJAX:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11322 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:" "STYLE:"
11323 "FILETAGS:" "ARCHIVE:" "INFOJS_OPT:"))
11325 (defconst org-additional-option-like-keywords-for-flyspell
11326 (delete-dups
11327 (split-string
11328 (mapconcat (lambda(k)
11329 (replace-regexp-in-string
11330 "_\\|:" " "
11331 (concat k " " (downcase k) " " (upcase k))))
11332 (append org-options-keywords org-additional-option-like-keywords)
11333 " ")
11334 " +" t)))
11336 (defcustom org-structure-template-alist
11338 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11339 "<src lang=\"?\">\n\n</src>")
11340 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11341 "<example>\n?\n</example>")
11342 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11343 "<quote>\n?\n</quote>")
11344 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11345 "<verse>\n?\n</verse>")
11346 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11347 "<center>\n?\n</center>")
11348 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11349 "<literal style=\"latex\">\n?\n</literal>")
11350 ("L" "#+LaTeX: "
11351 "<literal style=\"latex\">?</literal>")
11352 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11353 "<literal style=\"html\">\n?\n</literal>")
11354 ("H" "#+HTML: "
11355 "<literal style=\"html\">?</literal>")
11356 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11357 ("A" "#+ASCII: ")
11358 ("i" "#+INDEX: ?"
11359 "#+INDEX: ?")
11360 ("I" "#+INCLUDE: %file ?"
11361 "<include file=%file markup=\"?\">")
11363 "Structure completion elements.
11364 This is a list of abbreviation keys and values. The value gets inserted
11365 if you type `<' followed by the key and then press the completion key,
11366 usually `M-TAB'. %file will be replaced by a file name after prompting
11367 for the file using completion. The cursor will be placed at the position
11368 of the `?` in the template.
11369 There are two templates for each key, the first uses the original Org syntax,
11370 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11371 the default when the /org-mtags.el/ module has been loaded. See also the
11372 variable `org-mtags-prefer-muse-templates'."
11373 :group 'org-completion
11374 :type '(repeat
11375 (string :tag "Key")
11376 (string :tag "Template")
11377 (string :tag "Muse Template")))
11379 (defun org-try-structure-completion ()
11380 "Try to complete a structure template before point.
11381 This looks for strings like \"<e\" on an otherwise empty line and
11382 expands them."
11383 (let ((l (buffer-substring (point-at-bol) (point)))
11385 (when (and (looking-at "[ \t]*$")
11386 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11387 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11388 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11389 (match-beginning 1)) a)
11390 t)))
11392 (defun org-complete-expand-structure-template (start cell)
11393 "Expand a structure template."
11394 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11395 (rpl (nth (if musep 2 1) cell))
11396 (ind ""))
11397 (delete-region start (point))
11398 (when (string-match "\\`#\\+" rpl)
11399 (cond
11400 ((bolp))
11401 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11402 (setq ind (buffer-substring (point-at-bol) (point))))
11403 (t (newline))))
11404 (setq start (point))
11405 (if (string-match "%file" rpl)
11406 (setq rpl (replace-match
11407 (concat
11408 "\""
11409 (save-match-data
11410 (abbreviate-file-name (read-file-name "Include file: ")))
11411 "\"")
11412 t t rpl)))
11413 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11414 (concat "\n" ind)))
11415 (insert rpl)
11416 (if (re-search-backward "\\?" start t) (delete-char 1))))
11418 ;;;; TODO, DEADLINE, Comments
11420 (defun org-toggle-comment ()
11421 "Change the COMMENT state of an entry."
11422 (interactive)
11423 (save-excursion
11424 (org-back-to-heading)
11425 (let (case-fold-search)
11426 (cond
11427 ((looking-at (format org-heading-keyword-regexp-format
11428 org-comment-string))
11429 (goto-char (match-end 1))
11430 (looking-at (concat " +" org-comment-string))
11431 (replace-match "" t t)
11432 (when (eolp) (insert " ")))
11433 ((looking-at org-outline-regexp)
11434 (goto-char (match-end 0))
11435 (insert org-comment-string " "))))))
11437 (defvar org-last-todo-state-is-todo nil
11438 "This is non-nil when the last TODO state change led to a TODO state.
11439 If the last change removed the TODO tag or switched to DONE, then
11440 this is nil.")
11442 (defvar org-setting-tags nil) ; dynamically skipped
11444 (defvar org-todo-setup-filter-hook nil
11445 "Hook for functions that pre-filter todo specs.
11446 Each function takes a todo spec and returns either nil or the spec
11447 transformed into canonical form." )
11449 (defvar org-todo-get-default-hook nil
11450 "Hook for functions that get a default item for todo.
11451 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11452 nil or a string to be used for the todo mark." )
11454 (defvar org-agenda-headline-snapshot-before-repeat)
11456 (defun org-current-effective-time ()
11457 "Return current time adjusted for `org-extend-today-until' variable."
11458 (let* ((ct (org-current-time))
11459 (dct (decode-time ct))
11460 (ct1
11461 (cond
11462 (org-use-last-clock-out-time-as-effective-time
11463 (or (org-clock-get-last-clock-out-time) ct))
11464 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11465 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11466 (t ct))))
11467 ct1))
11469 (defun org-todo-yesterday (&optional arg)
11470 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11471 (interactive "P")
11472 (if (eq major-mode 'org-agenda-mode)
11473 (apply 'org-agenda-todo-yesterday arg)
11474 (let* ((hour (third (decode-time
11475 (org-current-time))))
11476 (org-extend-today-until (1+ hour)))
11477 (org-todo arg))))
11479 (defun org-todo (&optional arg)
11480 "Change the TODO state of an item.
11481 The state of an item is given by a keyword at the start of the heading,
11482 like
11483 *** TODO Write paper
11484 *** DONE Call mom
11486 The different keywords are specified in the variable `org-todo-keywords'.
11487 By default the available states are \"TODO\" and \"DONE\".
11488 So for this example: when the item starts with TODO, it is changed to DONE.
11489 When it starts with DONE, the DONE is removed. And when neither TODO nor
11490 DONE are present, add TODO at the beginning of the heading.
11492 With \\[universal-argument] prefix arg, use completion to determine the new \
11493 state.
11494 With numeric prefix arg, switch to that state.
11495 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11496 keywords (nextset).
11497 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11498 With a numeric prefix arg of 0, inhibit note taking for the change.
11500 For calling through lisp, arg is also interpreted in the following way:
11501 'none -> empty state
11502 \"\"(empty string) -> switch to empty state
11503 'done -> switch to DONE
11504 'nextset -> switch to the next set of keywords
11505 'previousset -> switch to the previous set of keywords
11506 \"WAITING\" -> switch to the specified keyword, but only if it
11507 really is a member of `org-todo-keywords'."
11508 (interactive "P")
11509 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11510 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11511 'region-start-level 'region))
11512 org-loop-over-headlines-in-active-region)
11513 (org-map-entries
11514 `(org-todo ,arg)
11515 org-loop-over-headlines-in-active-region
11516 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11517 (if (equal arg '(16)) (setq arg 'nextset))
11518 (let ((org-blocker-hook org-blocker-hook)
11519 (case-fold-search nil))
11520 (when (equal arg '(64))
11521 (setq arg nil org-blocker-hook nil))
11522 (when (and org-blocker-hook
11523 (or org-inhibit-blocking
11524 (org-entry-get nil "NOBLOCKING")))
11525 (setq org-blocker-hook nil))
11526 (save-excursion
11527 (catch 'exit
11528 (org-back-to-heading t)
11529 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11530 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11531 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11532 (let* ((match-data (match-data))
11533 (startpos (point-at-bol))
11534 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11535 (org-log-done org-log-done)
11536 (org-log-repeat org-log-repeat)
11537 (org-todo-log-states org-todo-log-states)
11538 (org-inhibit-logging
11539 (if (equal arg 0)
11540 (progn (setq arg nil) 'note) org-inhibit-logging))
11541 (this (match-string 1))
11542 (hl-pos (match-beginning 0))
11543 (head (org-get-todo-sequence-head this))
11544 (ass (assoc head org-todo-kwd-alist))
11545 (interpret (nth 1 ass))
11546 (done-word (nth 3 ass))
11547 (final-done-word (nth 4 ass))
11548 (org-last-state (or this ""))
11549 (completion-ignore-case t)
11550 (member (member this org-todo-keywords-1))
11551 (tail (cdr member))
11552 (org-state (cond
11553 ((and org-todo-key-trigger
11554 (or (and (equal arg '(4))
11555 (eq org-use-fast-todo-selection 'prefix))
11556 (and (not arg) org-use-fast-todo-selection
11557 (not (eq org-use-fast-todo-selection
11558 'prefix)))))
11559 ;; Use fast selection
11560 (org-fast-todo-selection))
11561 ((and (equal arg '(4))
11562 (or (not org-use-fast-todo-selection)
11563 (not org-todo-key-trigger)))
11564 ;; Read a state with completion
11565 (org-icompleting-read
11566 "State: " (mapcar (lambda(x) (list x))
11567 org-todo-keywords-1)
11568 nil t))
11569 ((eq arg 'right)
11570 (if this
11571 (if tail (car tail) nil)
11572 (car org-todo-keywords-1)))
11573 ((eq arg 'left)
11574 (if (equal member org-todo-keywords-1)
11576 (if this
11577 (nth (- (length org-todo-keywords-1)
11578 (length tail) 2)
11579 org-todo-keywords-1)
11580 (org-last org-todo-keywords-1))))
11581 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11582 (setq arg nil))) ; hack to fall back to cycling
11583 (arg
11584 ;; user or caller requests a specific state
11585 (cond
11586 ((equal arg "") nil)
11587 ((eq arg 'none) nil)
11588 ((eq arg 'done) (or done-word (car org-done-keywords)))
11589 ((eq arg 'nextset)
11590 (or (car (cdr (member head org-todo-heads)))
11591 (car org-todo-heads)))
11592 ((eq arg 'previousset)
11593 (let ((org-todo-heads (reverse org-todo-heads)))
11594 (or (car (cdr (member head org-todo-heads)))
11595 (car org-todo-heads))))
11596 ((car (member arg org-todo-keywords-1)))
11597 ((stringp arg)
11598 (error "State `%s' not valid in this file" arg))
11599 ((nth (1- (prefix-numeric-value arg))
11600 org-todo-keywords-1))))
11601 ((null member) (or head (car org-todo-keywords-1)))
11602 ((equal this final-done-word) nil) ;; -> make empty
11603 ((null tail) nil) ;; -> first entry
11604 ((memq interpret '(type priority))
11605 (if (eq this-command last-command)
11606 (car tail)
11607 (if (> (length tail) 0)
11608 (or done-word (car org-done-keywords))
11609 nil)))
11611 (car tail))))
11612 (org-state (or
11613 (run-hook-with-args-until-success
11614 'org-todo-get-default-hook org-state org-last-state)
11615 org-state))
11616 (next (if org-state (concat " " org-state " ") " "))
11617 (change-plist (list :type 'todo-state-change :from this :to org-state
11618 :position startpos))
11619 dolog now-done-p)
11620 (when org-blocker-hook
11621 (setq org-last-todo-state-is-todo
11622 (not (member this org-done-keywords)))
11623 (unless (save-excursion
11624 (save-match-data
11625 (org-with-wide-buffer
11626 (run-hook-with-args-until-failure
11627 'org-blocker-hook change-plist))))
11628 (if (org-called-interactively-p 'interactive)
11629 (error "TODO state change from %s to %s blocked" this org-state)
11630 ;; fail silently
11631 (message "TODO state change from %s to %s blocked" this org-state)
11632 (throw 'exit nil))))
11633 (store-match-data match-data)
11634 (replace-match next t t)
11635 (unless (pos-visible-in-window-p hl-pos)
11636 (message "TODO state changed to %s" (org-trim next)))
11637 (unless head
11638 (setq head (org-get-todo-sequence-head org-state)
11639 ass (assoc head org-todo-kwd-alist)
11640 interpret (nth 1 ass)
11641 done-word (nth 3 ass)
11642 final-done-word (nth 4 ass)))
11643 (when (memq arg '(nextset previousset))
11644 (message "Keyword-Set %d/%d: %s"
11645 (- (length org-todo-sets) -1
11646 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11647 (length org-todo-sets)
11648 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11649 (setq org-last-todo-state-is-todo
11650 (not (member org-state org-done-keywords)))
11651 (setq now-done-p (and (member org-state org-done-keywords)
11652 (not (member this org-done-keywords))))
11653 (and logging (org-local-logging logging))
11654 (when (and (or org-todo-log-states org-log-done)
11655 (not (eq org-inhibit-logging t))
11656 (not (memq arg '(nextset previousset))))
11657 ;; we need to look at recording a time and note
11658 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11659 (nth 2 (assoc this org-todo-log-states))))
11660 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11661 (setq dolog 'time))
11662 (when (and org-state
11663 (member org-state org-not-done-keywords)
11664 (not (member this org-not-done-keywords)))
11665 ;; This is now a todo state and was not one before
11666 ;; If there was a CLOSED time stamp, get rid of it.
11667 (org-add-planning-info nil nil 'closed))
11668 (when (and now-done-p org-log-done)
11669 ;; It is now done, and it was not done before
11670 (org-add-planning-info 'closed (org-current-effective-time))
11671 (if (and (not dolog) (eq 'note org-log-done))
11672 (org-add-log-setup 'done org-state this 'findpos 'note)))
11673 (when (and org-state dolog)
11674 ;; This is a non-nil state, and we need to log it
11675 (org-add-log-setup 'state org-state this 'findpos dolog)))
11676 ;; Fixup tag positioning
11677 (org-todo-trigger-tag-changes org-state)
11678 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11679 (when org-provide-todo-statistics
11680 (org-update-parent-todo-statistics))
11681 (run-hooks 'org-after-todo-state-change-hook)
11682 (if (and arg (not (member org-state org-done-keywords)))
11683 (setq head (org-get-todo-sequence-head org-state)))
11684 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11685 ;; Do we need to trigger a repeat?
11686 (when now-done-p
11687 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11688 ;; This is for the agenda, take a snapshot of the headline.
11689 (save-match-data
11690 (setq org-agenda-headline-snapshot-before-repeat
11691 (org-get-heading))))
11692 (org-auto-repeat-maybe org-state))
11693 ;; Fixup cursor location if close to the keyword
11694 (if (and (outline-on-heading-p)
11695 (not (bolp))
11696 (save-excursion (beginning-of-line 1)
11697 (looking-at org-todo-line-regexp))
11698 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11699 (progn
11700 (goto-char (or (match-end 2) (match-end 1)))
11701 (and (looking-at " ") (just-one-space))))
11702 (when org-trigger-hook
11703 (save-excursion
11704 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11706 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11707 "Block turning an entry into a TODO, using the hierarchy.
11708 This checks whether the current task should be blocked from state
11709 changes. Such blocking occurs when:
11711 1. The task has children which are not all in a completed state.
11713 2. A task has a parent with the property :ORDERED:, and there
11714 are siblings prior to the current task with incomplete
11715 status.
11717 3. The parent of the task is blocked because it has siblings that should
11718 be done first, or is child of a block grandparent TODO entry."
11720 (if (not org-enforce-todo-dependencies)
11721 t ; if locally turned off don't block
11722 (catch 'dont-block
11723 ;; If this is not a todo state change, or if this entry is already DONE,
11724 ;; do not block
11725 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11726 (member (plist-get change-plist :from)
11727 (cons 'done org-done-keywords))
11728 (member (plist-get change-plist :to)
11729 (cons 'todo org-not-done-keywords))
11730 (not (plist-get change-plist :to)))
11731 (throw 'dont-block t))
11732 ;; If this task has children, and any are undone, it's blocked
11733 (save-excursion
11734 (org-back-to-heading t)
11735 (let ((this-level (funcall outline-level)))
11736 (outline-next-heading)
11737 (let ((child-level (funcall outline-level)))
11738 (while (and (not (eobp))
11739 (> child-level this-level))
11740 ;; this todo has children, check whether they are all
11741 ;; completed
11742 (if (and (not (org-entry-is-done-p))
11743 (org-entry-is-todo-p))
11744 (throw 'dont-block nil))
11745 (outline-next-heading)
11746 (setq child-level (funcall outline-level))))))
11747 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11748 ;; any previous siblings are undone, it's blocked
11749 (save-excursion
11750 (org-back-to-heading t)
11751 (let* ((pos (point))
11752 (parent-pos (and (org-up-heading-safe) (point))))
11753 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11754 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11755 (forward-line 1)
11756 (re-search-forward org-not-done-heading-regexp pos t))
11757 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11758 ;; Search further up the hierarchy, to see if an ancestor is blocked
11759 (while t
11760 (goto-char parent-pos)
11761 (if (not (looking-at org-not-done-heading-regexp))
11762 (throw 'dont-block t)) ; do not block, parent is not a TODO
11763 (setq pos (point))
11764 (setq parent-pos (and (org-up-heading-safe) (point)))
11765 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11766 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11767 (forward-line 1)
11768 (re-search-forward org-not-done-heading-regexp pos t))
11769 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11771 (defcustom org-track-ordered-property-with-tag nil
11772 "Should the ORDERED property also be shown as a tag?
11773 The ORDERED property decides if an entry should require subtasks to be
11774 completed in sequence. Since a property is not very visible, setting
11775 this option means that toggling the ORDERED property with the command
11776 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11777 not relevant for the behavior, but it makes things more visible.
11779 Note that toggling the tag with tags commands will not change the property
11780 and therefore not influence behavior!
11782 This can be t, meaning the tag ORDERED should be used, It can also be a
11783 string to select a different tag for this task."
11784 :group 'org-todo
11785 :type '(choice
11786 (const :tag "No tracking" nil)
11787 (const :tag "Track with ORDERED tag" t)
11788 (string :tag "Use other tag")))
11790 (defun org-toggle-ordered-property ()
11791 "Toggle the ORDERED property of the current entry.
11792 For better visibility, you can track the value of this property with a tag.
11793 See variable `org-track-ordered-property-with-tag'."
11794 (interactive)
11795 (let* ((t1 org-track-ordered-property-with-tag)
11796 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11797 (save-excursion
11798 (org-back-to-heading)
11799 (if (org-entry-get nil "ORDERED")
11800 (progn
11801 (org-delete-property "ORDERED")
11802 (and tag (org-toggle-tag tag 'off))
11803 (message "Subtasks can be completed in arbitrary order"))
11804 (org-entry-put nil "ORDERED" "t")
11805 (and tag (org-toggle-tag tag 'on))
11806 (message "Subtasks must be completed in sequence")))))
11808 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11809 (defun org-block-todo-from-checkboxes (change-plist)
11810 "Block turning an entry into a TODO, using checkboxes.
11811 This checks whether the current task should be blocked from state
11812 changes because there are unchecked boxes in this entry."
11813 (if (not org-enforce-todo-checkbox-dependencies)
11814 t ; if locally turned off don't block
11815 (catch 'dont-block
11816 ;; If this is not a todo state change, or if this entry is already DONE,
11817 ;; do not block
11818 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11819 (member (plist-get change-plist :from)
11820 (cons 'done org-done-keywords))
11821 (member (plist-get change-plist :to)
11822 (cons 'todo org-not-done-keywords))
11823 (not (plist-get change-plist :to)))
11824 (throw 'dont-block t))
11825 ;; If this task has checkboxes that are not checked, it's blocked
11826 (save-excursion
11827 (org-back-to-heading t)
11828 (let ((beg (point)) end)
11829 (outline-next-heading)
11830 (setq end (point))
11831 (goto-char beg)
11832 (if (org-list-search-forward
11833 (concat (org-item-beginning-re)
11834 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11835 "\\[[- ]\\]")
11836 end t)
11837 (progn
11838 (if (boundp 'org-blocked-by-checkboxes)
11839 (setq org-blocked-by-checkboxes t))
11840 (throw 'dont-block nil)))))
11841 t))) ; do not block
11843 (defun org-entry-blocked-p ()
11844 "Is the current entry blocked?"
11845 (if (org-entry-get nil "NOBLOCKING")
11846 nil ;; Never block this entry
11847 (not
11848 (run-hook-with-args-until-failure
11849 'org-blocker-hook
11850 (list :type 'todo-state-change
11851 :position (point)
11852 :from 'todo
11853 :to 'done)))))
11855 (defun org-update-statistics-cookies (all)
11856 "Update the statistics cookie, either from TODO or from checkboxes.
11857 This should be called with the cursor in a line with a statistics cookie."
11858 (interactive "P")
11859 (if all
11860 (progn
11861 (org-update-checkbox-count 'all)
11862 (org-map-entries 'org-update-parent-todo-statistics))
11863 (if (not (org-at-heading-p))
11864 (org-update-checkbox-count)
11865 (let ((pos (move-marker (make-marker) (point)))
11866 end l1 l2)
11867 (ignore-errors (org-back-to-heading t))
11868 (if (not (org-at-heading-p))
11869 (org-update-checkbox-count)
11870 (setq l1 (org-outline-level))
11871 (setq end (save-excursion
11872 (outline-next-heading)
11873 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11874 (point)))
11875 (if (and (save-excursion
11876 (re-search-forward
11877 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11878 (not (save-excursion (re-search-forward
11879 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11880 (org-update-checkbox-count)
11881 (if (and l2 (> l2 l1))
11882 (progn
11883 (goto-char end)
11884 (org-update-parent-todo-statistics))
11885 (goto-char pos)
11886 (beginning-of-line 1)
11887 (while (re-search-forward
11888 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11889 (point-at-eol) t)
11890 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11891 (goto-char pos)
11892 (move-marker pos nil)))))
11894 (defvar org-entry-property-inherited-from) ;; defined below
11895 (defun org-update-parent-todo-statistics ()
11896 "Update any statistics cookie in the parent of the current headline.
11897 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11898 the entire subtree and this will travel up the hierarchy and update
11899 statistics everywhere."
11900 (let* ((prop (save-excursion (org-up-heading-safe)
11901 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11902 (recursive (or (not org-hierarchical-todo-statistics)
11903 (and prop (string-match "\\<recursive\\>" prop))))
11904 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11906 (first t)
11907 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11908 level ltoggle l1 new ndel
11909 (cnt-all 0) (cnt-done 0) is-percent kwd
11910 checkbox-beg ov ovs ove cookie-present)
11911 (catch 'exit
11912 (save-excursion
11913 (beginning-of-line 1)
11914 (setq ltoggle (funcall outline-level))
11915 ;; Three situations are to consider:
11917 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11918 ;; to the top-level ancestor on the headline;
11920 ;; 2. If parent has "recursive" property, repeat up to the
11921 ;; headline setting that property, taking inheritance into
11922 ;; account;
11924 ;; 3. Else, move up to direct parent and proceed only once.
11925 (while (and (setq level (org-up-heading-safe))
11926 (or recursive first)
11927 (>= (point) lim))
11928 (setq first nil cookie-present nil)
11929 (unless (and level
11930 (not (string-match
11931 "\\<checkbox\\>"
11932 (downcase (or (org-entry-get nil "COOKIE_DATA")
11933 "")))))
11934 (throw 'exit nil))
11935 (while (re-search-forward box-re (point-at-eol) t)
11936 (setq cnt-all 0 cnt-done 0 cookie-present t)
11937 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11938 (save-match-data
11939 (unless (outline-next-heading) (throw 'exit nil))
11940 (while (and (looking-at org-complex-heading-regexp)
11941 (> (setq l1 (length (match-string 1))) level))
11942 (setq kwd (and (or recursive (= l1 ltoggle))
11943 (match-string 2)))
11944 (if (or (eq org-provide-todo-statistics 'all-headlines)
11945 (and (listp org-provide-todo-statistics)
11946 (or (member kwd org-provide-todo-statistics)
11947 (member kwd org-done-keywords))))
11948 (setq cnt-all (1+ cnt-all))
11949 (if (eq org-provide-todo-statistics t)
11950 (and kwd (setq cnt-all (1+ cnt-all)))))
11951 (and (member kwd org-done-keywords)
11952 (setq cnt-done (1+ cnt-done)))
11953 (outline-next-heading)))
11954 (setq new
11955 (if is-percent
11956 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11957 (format "[%d/%d]" cnt-done cnt-all))
11958 ndel (- (match-end 0) checkbox-beg))
11959 ;; handle overlays when updating cookie from column view
11960 (when (setq ov (car (overlays-at checkbox-beg)))
11961 (setq ovs (overlay-start ov) ove (overlay-end ov))
11962 (delete-overlay ov))
11963 (goto-char checkbox-beg)
11964 (insert new)
11965 (delete-region (point) (+ (point) ndel))
11966 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11967 (when ov (move-overlay ov ovs ove)))
11968 (when cookie-present
11969 (run-hook-with-args 'org-after-todo-statistics-hook
11970 cnt-done (- cnt-all cnt-done))))))
11971 (run-hooks 'org-todo-statistics-hook)))
11973 (defvar org-after-todo-statistics-hook nil
11974 "Hook that is called after a TODO statistics cookie has been updated.
11975 Each function is called with two arguments: the number of not-done entries
11976 and the number of done entries.
11978 For example, the following function, when added to this hook, will switch
11979 an entry to DONE when all children are done, and back to TODO when new
11980 entries are set to a TODO status. Note that this hook is only called
11981 when there is a statistics cookie in the headline!
11983 (defun org-summary-todo (n-done n-not-done)
11984 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11985 (let (org-log-done org-log-states) ; turn off logging
11986 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11989 (defvar org-todo-statistics-hook nil
11990 "Hook that is run whenever Org thinks TODO statistics should be updated.
11991 This hook runs even if there is no statistics cookie present, in which case
11992 `org-after-todo-statistics-hook' would not run.")
11994 (defun org-todo-trigger-tag-changes (state)
11995 "Apply the changes defined in `org-todo-state-tags-triggers'."
11996 (let ((l org-todo-state-tags-triggers)
11997 changes)
11998 (when (or (not state) (equal state ""))
11999 (setq changes (append changes (cdr (assoc "" l)))))
12000 (when (and (stringp state) (> (length state) 0))
12001 (setq changes (append changes (cdr (assoc state l)))))
12002 (when (member state org-not-done-keywords)
12003 (setq changes (append changes (cdr (assoc 'todo l)))))
12004 (when (member state org-done-keywords)
12005 (setq changes (append changes (cdr (assoc 'done l)))))
12006 (dolist (c changes)
12007 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12009 (defun org-local-logging (value)
12010 "Get logging settings from a property VALUE."
12011 (let* (words w a)
12012 ;; directly set the variables, they are already local.
12013 (setq org-log-done nil
12014 org-log-repeat nil
12015 org-todo-log-states nil)
12016 (setq words (org-split-string value))
12017 (while (setq w (pop words))
12018 (cond
12019 ((setq a (assoc w org-startup-options))
12020 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12021 (set (nth 1 a) (nth 2 a))))
12022 ((setq a (org-extract-log-state-settings w))
12023 (and (member (car a) org-todo-keywords-1)
12024 (push a org-todo-log-states)))))))
12026 (defun org-get-todo-sequence-head (kwd)
12027 "Return the head of the TODO sequence to which KWD belongs.
12028 If KWD is not set, check if there is a text property remembering the
12029 right sequence."
12030 (let (p)
12031 (cond
12032 ((not kwd)
12033 (or (get-text-property (point-at-bol) 'org-todo-head)
12034 (progn
12035 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12036 nil (point-at-eol)))
12037 (get-text-property p 'org-todo-head))))
12038 ((not (member kwd org-todo-keywords-1))
12039 (car org-todo-keywords-1))
12040 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12042 (defun org-fast-todo-selection ()
12043 "Fast TODO keyword selection with single keys.
12044 Returns the new TODO keyword, or nil if no state change should occur."
12045 (let* ((fulltable org-todo-key-alist)
12046 (done-keywords org-done-keywords) ;; needed for the faces.
12047 (maxlen (apply 'max (mapcar
12048 (lambda (x)
12049 (if (stringp (car x)) (string-width (car x)) 0))
12050 fulltable)))
12051 (expert nil)
12052 (fwidth (+ maxlen 3 1 3))
12053 (ncol (/ (- (window-width) 4) fwidth))
12054 tg cnt e c tbl
12055 groups ingroup)
12056 (save-excursion
12057 (save-window-excursion
12058 (if expert
12059 (set-buffer (get-buffer-create " *Org todo*"))
12060 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12061 (erase-buffer)
12062 (org-set-local 'org-done-keywords done-keywords)
12063 (setq tbl fulltable cnt 0)
12064 (while (setq e (pop tbl))
12065 (cond
12066 ((equal e '(:startgroup))
12067 (push '() groups) (setq ingroup t)
12068 (when (not (= cnt 0))
12069 (setq cnt 0)
12070 (insert "\n"))
12071 (insert "{ "))
12072 ((equal e '(:endgroup))
12073 (setq ingroup nil cnt 0)
12074 (insert "}\n"))
12075 ((equal e '(:newline))
12076 (when (not (= cnt 0))
12077 (setq cnt 0)
12078 (insert "\n")
12079 (setq e (car tbl))
12080 (while (equal (car tbl) '(:newline))
12081 (insert "\n")
12082 (setq tbl (cdr tbl)))))
12084 (setq tg (car e) c (cdr e))
12085 (if ingroup (push tg (car groups)))
12086 (setq tg (org-add-props tg nil 'face
12087 (org-get-todo-face tg)))
12088 (if (and (= cnt 0) (not ingroup)) (insert " "))
12089 (insert "[" c "] " tg (make-string
12090 (- fwidth 4 (length tg)) ?\ ))
12091 (when (= (setq cnt (1+ cnt)) ncol)
12092 (insert "\n")
12093 (if ingroup (insert " "))
12094 (setq cnt 0)))))
12095 (insert "\n")
12096 (goto-char (point-min))
12097 (if (not expert) (org-fit-window-to-buffer))
12098 (message "[a-z..]:Set [SPC]:clear")
12099 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12100 (cond
12101 ((or (= c ?\C-g)
12102 (and (= c ?q) (not (rassoc c fulltable))))
12103 (setq quit-flag t))
12104 ((= c ?\ ) nil)
12105 ((setq e (rassoc c fulltable) tg (car e))
12107 (t (setq quit-flag t)))))))
12109 (defun org-entry-is-todo-p ()
12110 (member (org-get-todo-state) org-not-done-keywords))
12112 (defun org-entry-is-done-p ()
12113 (member (org-get-todo-state) org-done-keywords))
12115 (defun org-get-todo-state ()
12116 (save-excursion
12117 (org-back-to-heading t)
12118 (and (looking-at org-todo-line-regexp)
12119 (match-end 2)
12120 (match-string 2))))
12122 (defun org-at-date-range-p (&optional inactive-ok)
12123 "Is the cursor inside a date range?"
12124 (interactive)
12125 (save-excursion
12126 (catch 'exit
12127 (let ((pos (point)))
12128 (skip-chars-backward "^[<\r\n")
12129 (skip-chars-backward "<[")
12130 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12131 (>= (match-end 0) pos)
12132 (throw 'exit t))
12133 (skip-chars-backward "^<[\r\n")
12134 (skip-chars-backward "<[")
12135 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12136 (>= (match-end 0) pos)
12137 (throw 'exit t)))
12138 nil)))
12140 (defun org-get-repeat (&optional tagline)
12141 "Check if there is a deadline/schedule with repeater in this entry."
12142 (save-match-data
12143 (save-excursion
12144 (org-back-to-heading t)
12145 (and (re-search-forward (if tagline
12146 (concat tagline "\\s-*" org-repeat-re)
12147 org-repeat-re)
12148 (org-entry-end-position) t)
12149 (match-string-no-properties 1)))))
12151 (defvar org-last-changed-timestamp)
12152 (defvar org-last-inserted-timestamp)
12153 (defvar org-log-post-message)
12154 (defvar org-log-note-purpose)
12155 (defvar org-log-note-how)
12156 (defvar org-log-note-extra)
12157 (defun org-auto-repeat-maybe (done-word)
12158 "Check if the current headline contains a repeated deadline/schedule.
12159 If yes, set TODO state back to what it was and change the base date
12160 of repeating deadline/scheduled time stamps to new date.
12161 This function is run automatically after each state change to a DONE state."
12162 ;; last-state is dynamically scoped into this function
12163 (let* ((repeat (org-get-repeat))
12164 (aa (assoc org-last-state org-todo-kwd-alist))
12165 (interpret (nth 1 aa))
12166 (head (nth 2 aa))
12167 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12168 (msg "Entry repeats: ")
12169 (org-log-done nil)
12170 (org-todo-log-states nil)
12171 re type n what ts time to-state)
12172 (when repeat
12173 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12174 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12175 org-todo-repeat-to-state))
12176 (unless (and to-state (member to-state org-todo-keywords-1))
12177 (setq to-state (if (eq interpret 'type) org-last-state head)))
12178 (org-todo to-state)
12179 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12180 (org-entry-put nil "LAST_REPEAT" (format-time-string
12181 (org-time-stamp-format t t))))
12182 (when org-log-repeat
12183 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12184 (memq 'org-add-log-note post-command-hook))
12185 ;; OK, we are already setup for some record
12186 (if (eq org-log-repeat 'note)
12187 ;; make sure we take a note, not only a time stamp
12188 (setq org-log-note-how 'note))
12189 ;; Set up for taking a record
12190 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12191 org-last-state
12192 'findpos org-log-repeat)))
12193 (org-back-to-heading t)
12194 (org-add-planning-info nil nil 'closed)
12195 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12196 org-deadline-time-regexp "\\)\\|\\("
12197 org-ts-regexp "\\)"))
12198 (while (re-search-forward
12199 re (save-excursion (outline-next-heading) (point)) t)
12200 (setq type (if (match-end 1) org-scheduled-string
12201 (if (match-end 3) org-deadline-string "Plain:"))
12202 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12203 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12204 (setq n (string-to-number (match-string 2 ts))
12205 what (match-string 3 ts))
12206 (if (equal what "w") (setq n (* n 7) what "d"))
12207 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12208 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12209 ;; Preparation, see if we need to modify the start date for the change
12210 (when (match-end 1)
12211 (setq time (save-match-data (org-time-string-to-time ts)))
12212 (cond
12213 ((equal (match-string 1 ts) ".")
12214 ;; Shift starting date to today
12215 (org-timestamp-change
12216 (- (org-today) (time-to-days time))
12217 'day))
12218 ((equal (match-string 1 ts) "+")
12219 (let ((nshiftmax 10) (nshift 0))
12220 (while (or (= nshift 0)
12221 (<= (time-to-days time)
12222 (time-to-days (current-time))))
12223 (when (= (incf nshift) nshiftmax)
12224 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12225 (error "Abort")))
12226 (org-timestamp-change n (cdr (assoc what whata)))
12227 (org-at-timestamp-p t)
12228 (setq ts (match-string 1))
12229 (setq time (save-match-data (org-time-string-to-time ts)))))
12230 (org-timestamp-change (- n) (cdr (assoc what whata)))
12231 ;; rematch, so that we have everything in place for the real shift
12232 (org-at-timestamp-p t)
12233 (setq ts (match-string 1))
12234 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12235 (org-timestamp-change n (cdr (assoc what whata)))
12236 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12237 (setq org-log-post-message msg)
12238 (message "%s" msg))))
12240 (defun org-show-todo-tree (arg)
12241 "Make a compact tree which shows all headlines marked with TODO.
12242 The tree will show the lines where the regexp matches, and all higher
12243 headlines above the match.
12244 With a \\[universal-argument] prefix, prompt for a regexp to match.
12245 With a numeric prefix N, construct a sparse tree for the Nth element
12246 of `org-todo-keywords-1'."
12247 (interactive "P")
12248 (let ((case-fold-search nil)
12249 (kwd-re
12250 (cond ((null arg) org-not-done-regexp)
12251 ((equal arg '(4))
12252 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12253 (mapcar 'list org-todo-keywords-1))))
12254 (concat "\\("
12255 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12256 "\\)\\>")))
12257 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12258 (regexp-quote (nth (1- (prefix-numeric-value arg))
12259 org-todo-keywords-1)))
12260 (t (error "Invalid prefix argument: %s" arg)))))
12261 (message "%d TODO entries found"
12262 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12264 (defun org-deadline (&optional remove time)
12265 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12266 With argument REMOVE, remove any deadline from the item.
12267 With argument TIME, set the deadline at the corresponding date. TIME
12268 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12269 (interactive "P")
12270 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12271 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12272 'region-start-level 'region))
12273 org-loop-over-headlines-in-active-region)
12274 (org-map-entries
12275 `(org-deadline ',remove ,time)
12276 org-loop-over-headlines-in-active-region
12277 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12278 (let* ((old-date (org-entry-get nil "DEADLINE"))
12279 (repeater (and old-date
12280 (string-match
12281 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12282 old-date)
12283 (match-string 1 old-date))))
12284 (if remove
12285 (progn
12286 (when (and old-date org-log-redeadline)
12287 (org-add-log-setup 'deldeadline nil old-date 'findpos
12288 org-log-redeadline))
12289 (org-remove-timestamp-with-keyword org-deadline-string)
12290 (message "Item no longer has a deadline."))
12291 (org-add-planning-info 'deadline time 'closed)
12292 (when (and old-date org-log-redeadline
12293 (not (equal old-date
12294 (substring org-last-inserted-timestamp 1 -1))))
12295 (org-add-log-setup 'redeadline nil old-date 'findpos
12296 org-log-redeadline))
12297 (when repeater
12298 (save-excursion
12299 (org-back-to-heading t)
12300 (when (re-search-forward (concat org-deadline-string " "
12301 org-last-inserted-timestamp)
12302 (save-excursion
12303 (outline-next-heading) (point)) t)
12304 (goto-char (1- (match-end 0)))
12305 (insert " " repeater)
12306 (setq org-last-inserted-timestamp
12307 (concat (substring org-last-inserted-timestamp 0 -1)
12308 " " repeater
12309 (substring org-last-inserted-timestamp -1))))))
12310 (message "Deadline on %s" org-last-inserted-timestamp)))))
12312 (defun org-schedule (&optional remove time)
12313 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12314 With argument REMOVE, remove any scheduling date from the item.
12315 With argument TIME, scheduled at the corresponding date. TIME can
12316 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12317 (interactive "P")
12318 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12319 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12320 'region-start-level 'region))
12321 org-loop-over-headlines-in-active-region)
12322 (org-map-entries
12323 `(org-schedule ',remove ,time)
12324 org-loop-over-headlines-in-active-region
12325 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12326 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12327 (repeater (and old-date
12328 (string-match
12329 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12330 old-date)
12331 (match-string 1 old-date))))
12332 (if remove
12333 (progn
12334 (when (and old-date org-log-reschedule)
12335 (org-add-log-setup 'delschedule nil old-date 'findpos
12336 org-log-reschedule))
12337 (org-remove-timestamp-with-keyword org-scheduled-string)
12338 (message "Item is no longer scheduled."))
12339 (org-add-planning-info 'scheduled time 'closed)
12340 (when (and old-date org-log-reschedule
12341 (not (equal old-date
12342 (substring org-last-inserted-timestamp 1 -1))))
12343 (org-add-log-setup 'reschedule nil old-date 'findpos
12344 org-log-reschedule))
12345 (when repeater
12346 (save-excursion
12347 (org-back-to-heading t)
12348 (when (re-search-forward (concat org-scheduled-string " "
12349 org-last-inserted-timestamp)
12350 (save-excursion
12351 (outline-next-heading) (point)) t)
12352 (goto-char (1- (match-end 0)))
12353 (insert " " repeater)
12354 (setq org-last-inserted-timestamp
12355 (concat (substring org-last-inserted-timestamp 0 -1)
12356 " " repeater
12357 (substring org-last-inserted-timestamp -1))))))
12358 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12360 (defun org-get-scheduled-time (pom &optional inherit)
12361 "Get the scheduled time as a time tuple, of a format suitable
12362 for calling org-schedule with, or if there is no scheduling,
12363 returns nil."
12364 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12365 (when time
12366 (apply 'encode-time (org-parse-time-string time)))))
12368 (defun org-get-deadline-time (pom &optional inherit)
12369 "Get the deadline as a time tuple, of a format suitable for
12370 calling org-deadline with, or if there is no scheduling, returns
12371 nil."
12372 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12373 (when time
12374 (apply 'encode-time (org-parse-time-string time)))))
12376 (defun org-remove-timestamp-with-keyword (keyword)
12377 "Remove all time stamps with KEYWORD in the current entry."
12378 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12379 beg)
12380 (save-excursion
12381 (org-back-to-heading t)
12382 (setq beg (point))
12383 (outline-next-heading)
12384 (while (re-search-backward re beg t)
12385 (replace-match "")
12386 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12387 (equal (char-before) ?\ ))
12388 (backward-delete-char 1)
12389 (if (string-match "^[ \t]*$" (buffer-substring
12390 (point-at-bol) (point-at-eol)))
12391 (delete-region (point-at-bol)
12392 (min (point-max) (1+ (point-at-eol))))))))))
12394 (defun org-add-planning-info (what &optional time &rest remove)
12395 "Insert new timestamp with keyword in the line directly after the headline.
12396 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12397 If non is given, the user is prompted for a date.
12398 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12399 be removed."
12400 (interactive)
12401 (let (org-time-was-given org-end-time-was-given ts
12402 end default-time default-input)
12404 (catch 'exit
12405 (when (and (memq what '(scheduled deadline))
12406 (or (not time)
12407 (and (stringp time)
12408 (string-match "^[-+]+[0-9]" time))))
12409 ;; Try to get a default date/time from existing timestamp
12410 (save-excursion
12411 (org-back-to-heading t)
12412 (setq end (save-excursion (outline-next-heading) (point)))
12413 (when (re-search-forward (if (eq what 'scheduled)
12414 org-scheduled-time-regexp
12415 org-deadline-time-regexp)
12416 end t)
12417 (setq ts (match-string 1)
12418 default-time
12419 (apply 'encode-time (org-parse-time-string ts))
12420 default-input (and ts (org-get-compact-tod ts))))))
12421 (when what
12422 (setq time
12423 (if (stringp time)
12424 ;; This is a string (relative or absolute), set proper date
12425 (apply 'encode-time
12426 (org-read-date-analyze
12427 time default-time (decode-time default-time)))
12428 ;; If necessary, get the time from the user
12429 (or time (org-read-date nil 'to-time nil nil
12430 default-time default-input)))))
12432 (when (and org-insert-labeled-timestamps-at-point
12433 (member what '(scheduled deadline)))
12434 (insert
12435 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12436 (org-insert-time-stamp time org-time-was-given
12437 nil nil nil (list org-end-time-was-given))
12438 (setq what nil))
12439 (save-excursion
12440 (save-restriction
12441 (let (col list elt ts buffer-invisibility-spec)
12442 (org-back-to-heading t)
12443 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12444 (goto-char (match-end 1))
12445 (setq col (current-column))
12446 (goto-char (match-end 0))
12447 (if (eobp) (insert "\n") (forward-char 1))
12448 (when (and (not what)
12449 (not (looking-at
12450 (concat "[ \t]*"
12451 org-keyword-time-not-clock-regexp))))
12452 ;; Nothing to add, nothing to remove...... :-)
12453 (throw 'exit nil))
12454 (if (and (not (looking-at org-outline-regexp))
12455 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12456 "[^\r\n]*"))
12457 (not (equal (match-string 1) org-clock-string)))
12458 (narrow-to-region (match-beginning 0) (match-end 0))
12459 (insert-before-markers "\n")
12460 (backward-char 1)
12461 (narrow-to-region (point) (point))
12462 (and org-adapt-indentation (org-indent-to-column col)))
12463 ;; Check if we have to remove something.
12464 (setq list (cons what remove))
12465 (while list
12466 (setq elt (pop list))
12467 (when (or (and (eq elt 'scheduled)
12468 (re-search-forward org-scheduled-time-regexp nil t))
12469 (and (eq elt 'deadline)
12470 (re-search-forward org-deadline-time-regexp nil t))
12471 (and (eq elt 'closed)
12472 (re-search-forward org-closed-time-regexp nil t)))
12473 (replace-match "")
12474 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12475 (and (looking-at "[ \t]+") (replace-match ""))
12476 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12477 (when what
12478 (insert
12479 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12480 (cond ((eq what 'scheduled) org-scheduled-string)
12481 ((eq what 'deadline) org-deadline-string)
12482 ((eq what 'closed) org-closed-string))
12483 " ")
12484 (setq ts (org-insert-time-stamp
12485 time
12486 (or org-time-was-given
12487 (and (eq what 'closed) org-log-done-with-time))
12488 (eq what 'closed)
12489 nil nil (list org-end-time-was-given)))
12490 (insert
12491 (if (not (or (bolp) (eq (char-before) ?\ )
12492 (memq (char-after) '(32 10))
12493 (eobp))) " " ""))
12494 (end-of-line 1))
12495 (goto-char (point-min))
12496 (widen)
12497 (if (and (looking-at "[ \t]*\n")
12498 (equal (char-before) ?\n))
12499 (delete-region (1- (point)) (point-at-eol)))
12500 ts))))))
12502 (defvar org-log-note-marker (make-marker))
12503 (defvar org-log-note-purpose nil)
12504 (defvar org-log-note-state nil)
12505 (defvar org-log-note-previous-state nil)
12506 (defvar org-log-note-how nil)
12507 (defvar org-log-note-extra nil)
12508 (defvar org-log-note-window-configuration nil)
12509 (defvar org-log-note-return-to (make-marker))
12510 (defvar org-log-note-effective-time nil
12511 "Remembered current time so that dynamically scoped
12512 `org-extend-today-until' affects tha timestamps in state change
12513 log")
12515 (defvar org-log-post-message nil
12516 "Message to be displayed after a log note has been stored.
12517 The auto-repeater uses this.")
12519 (defun org-add-note ()
12520 "Add a note to the current entry.
12521 This is done in the same way as adding a state change note."
12522 (interactive)
12523 (org-add-log-setup 'note nil nil 'findpos nil))
12525 (defvar org-property-end-re)
12526 (defun org-add-log-setup (&optional purpose state prev-state
12527 findpos how extra)
12528 "Set up the post command hook to take a note.
12529 If this is about to TODO state change, the new state is expected in STATE.
12530 When FINDPOS is non-nil, find the correct position for the note in
12531 the current entry. If not, assume that it can be inserted at point.
12532 HOW is an indicator what kind of note should be created.
12533 EXTRA is additional text that will be inserted into the notes buffer."
12534 (let* ((org-log-into-drawer (org-log-into-drawer))
12535 (drawer (cond ((stringp org-log-into-drawer)
12536 org-log-into-drawer)
12537 (org-log-into-drawer "LOGBOOK"))))
12538 (save-restriction
12539 (save-excursion
12540 (when findpos
12541 (org-back-to-heading t)
12542 (narrow-to-region (point) (save-excursion
12543 (outline-next-heading) (point)))
12544 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12545 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12546 "[^\r\n]*\\)?"))
12547 (goto-char (match-end 0))
12548 (cond
12549 (drawer
12550 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12551 nil t)
12552 (progn
12553 (goto-char (match-end 0))
12554 (or org-log-states-order-reversed
12555 (and (re-search-forward org-property-end-re nil t)
12556 (goto-char (1- (match-beginning 0))))))
12557 (insert "\n:" drawer ":\n:END:")
12558 (beginning-of-line 0)
12559 (org-indent-line)
12560 (beginning-of-line 2)
12561 (org-indent-line)
12562 (end-of-line 0)))
12563 ((and org-log-state-notes-insert-after-drawers
12564 (save-excursion
12565 (forward-line) (looking-at org-drawer-regexp)))
12566 (forward-line)
12567 (while (looking-at org-drawer-regexp)
12568 (goto-char (match-end 0))
12569 (re-search-forward org-property-end-re (point-max) t)
12570 (forward-line))
12571 (forward-line -1)))
12572 (unless org-log-states-order-reversed
12573 (and (= (char-after) ?\n) (forward-char 1))
12574 (org-skip-over-state-notes)
12575 (skip-chars-backward " \t\n\r")))
12576 (move-marker org-log-note-marker (point))
12577 (setq org-log-note-purpose purpose
12578 org-log-note-state state
12579 org-log-note-previous-state prev-state
12580 org-log-note-how how
12581 org-log-note-extra extra
12582 org-log-note-effective-time (org-current-effective-time))
12583 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12585 (defun org-skip-over-state-notes ()
12586 "Skip past the list of State notes in an entry."
12587 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12588 (when (ignore-errors (goto-char (org-in-item-p)))
12589 (let* ((struct (org-list-struct))
12590 (prevs (org-list-prevs-alist struct)))
12591 (while (looking-at "[ \t]*- State")
12592 (goto-char (or (org-list-get-next-item (point) struct prevs)
12593 (org-list-get-item-end (point) struct)))))))
12595 (defun org-add-log-note (&optional purpose)
12596 "Pop up a window for taking a note, and add this note later at point."
12597 (remove-hook 'post-command-hook 'org-add-log-note)
12598 (setq org-log-note-window-configuration (current-window-configuration))
12599 (delete-other-windows)
12600 (move-marker org-log-note-return-to (point))
12601 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12602 (goto-char org-log-note-marker)
12603 (org-switch-to-buffer-other-window "*Org Note*")
12604 (erase-buffer)
12605 (if (memq org-log-note-how '(time state))
12606 (let (current-prefix-arg) (org-store-log-note))
12607 (let ((org-inhibit-startup t)) (org-mode))
12608 (insert (format "# Insert note for %s.
12609 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12610 (cond
12611 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12612 ((eq org-log-note-purpose 'done) "closed todo item")
12613 ((eq org-log-note-purpose 'state)
12614 (format "state change from \"%s\" to \"%s\""
12615 (or org-log-note-previous-state "")
12616 (or org-log-note-state "")))
12617 ((eq org-log-note-purpose 'reschedule)
12618 "rescheduling")
12619 ((eq org-log-note-purpose 'delschedule)
12620 "no longer scheduled")
12621 ((eq org-log-note-purpose 'redeadline)
12622 "changing deadline")
12623 ((eq org-log-note-purpose 'deldeadline)
12624 "removing deadline")
12625 ((eq org-log-note-purpose 'refile)
12626 "refiling")
12627 ((eq org-log-note-purpose 'note)
12628 "this entry")
12629 (t (error "This should not happen")))))
12630 (if org-log-note-extra (insert org-log-note-extra))
12631 (org-set-local 'org-finish-function 'org-store-log-note)
12632 (run-hooks 'org-log-buffer-setup-hook)))
12634 (defvar org-note-abort nil) ; dynamically scoped
12635 (defun org-store-log-note ()
12636 "Finish taking a log note, and insert it to where it belongs."
12637 (let ((txt (buffer-string))
12638 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12639 lines ind bul)
12640 (kill-buffer (current-buffer))
12641 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12642 (setq txt (replace-match "" t t txt)))
12643 (if (string-match "\\s-+\\'" txt)
12644 (setq txt (replace-match "" t t txt)))
12645 (setq lines (org-split-string txt "\n"))
12646 (when (and note (string-match "\\S-" note))
12647 (setq note
12648 (org-replace-escapes
12649 note
12650 (list (cons "%u" (user-login-name))
12651 (cons "%U" user-full-name)
12652 (cons "%t" (format-time-string
12653 (org-time-stamp-format 'long 'inactive)
12654 org-log-note-effective-time))
12655 (cons "%T" (format-time-string
12656 (org-time-stamp-format 'long nil)
12657 org-log-note-effective-time))
12658 (cons "%d" (format-time-string
12659 (org-time-stamp-format nil 'inactive)
12660 org-log-note-effective-time))
12661 (cons "%D" (format-time-string
12662 (org-time-stamp-format nil nil)
12663 org-log-note-effective-time))
12664 (cons "%s" (if org-log-note-state
12665 (concat "\"" org-log-note-state "\"")
12666 ""))
12667 (cons "%S" (if org-log-note-previous-state
12668 (concat "\"" org-log-note-previous-state "\"")
12669 "\"\"")))))
12670 (if lines (setq note (concat note " \\\\")))
12671 (push note lines))
12672 (when (or current-prefix-arg org-note-abort)
12673 (when org-log-into-drawer
12674 (org-remove-empty-drawer-at
12675 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12676 org-log-note-marker))
12677 (setq lines nil))
12678 (when lines
12679 (with-current-buffer (marker-buffer org-log-note-marker)
12680 (save-excursion
12681 (goto-char org-log-note-marker)
12682 (move-marker org-log-note-marker nil)
12683 (end-of-line 1)
12684 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12685 (setq ind (save-excursion
12686 (if (ignore-errors (goto-char (org-in-item-p)))
12687 (let ((struct (org-list-struct)))
12688 (org-list-get-ind
12689 (org-list-get-top-point struct) struct))
12690 (skip-chars-backward " \r\t\n")
12691 (cond
12692 ((and (org-at-heading-p)
12693 org-adapt-indentation)
12694 (1+ (org-current-level)))
12695 ((org-at-heading-p) 0)
12696 (t (org-get-indentation))))))
12697 (setq bul (org-list-bullet-string "-"))
12698 (org-indent-line-to ind)
12699 (insert bul (pop lines))
12700 (let ((ind-body (+ (length bul) ind)))
12701 (while lines
12702 (insert "\n")
12703 (org-indent-line-to ind-body)
12704 (insert (pop lines))))
12705 (message "Note stored")
12706 (org-back-to-heading t)
12707 (org-cycle-hide-drawers 'children)))))
12708 (set-window-configuration org-log-note-window-configuration)
12709 (with-current-buffer (marker-buffer org-log-note-return-to)
12710 (goto-char org-log-note-return-to))
12711 (move-marker org-log-note-return-to nil)
12712 (and org-log-post-message (message "%s" org-log-post-message)))
12714 (defun org-remove-empty-drawer-at (drawer pos)
12715 "Remove an empty drawer DRAWER at position POS.
12716 POS may also be a marker."
12717 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12718 (save-excursion
12719 (save-restriction
12720 (widen)
12721 (goto-char pos)
12722 (if (org-in-regexp
12723 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12724 (replace-match ""))))))
12726 (defvar org-ts-type nil)
12727 (defun org-sparse-tree (&optional arg type)
12728 "Create a sparse tree, prompt for the details.
12729 This command can create sparse trees. You first need to select the type
12730 of match used to create the tree:
12732 t Show all TODO entries.
12733 T Show entries with a specific TODO keyword.
12734 m Show entries selected by a tags/property match.
12735 p Enter a property name and its value (both with completion on existing
12736 names/values) and show entries with that property.
12737 r Show entries matching a regular expression (`/' can be used as well).
12738 b Show deadlines and scheduled items before a date.
12739 a Show deadlines and scheduled items after a date.
12740 d Show deadlines due within `org-deadline-warning-days'.
12741 D Show deadlines and scheduled items between a date range."
12742 (interactive "P")
12743 (let (ans kwd value ts-type)
12744 (setq type (or type org-sparse-tree-default-date-type))
12745 (setq org-ts-type type)
12746 (message "Sparse tree: [r]egexp [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty\n [d]eadlines [b]efore-date [a]fter-date [D]ates range\n [c]ycle through date types: %s"
12747 (cond ((eq type 'all) "all timestamps")
12748 ((eq type 'scheduled) "only scheduled")
12749 ((eq type 'deadline) "only deadline")
12750 ((eq type 'active) "only active timestamps")
12751 ((eq type 'inactive) "only inactive timestamps")
12752 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12753 (t "scheduled/deadline")))
12754 (setq ans (read-char-exclusive))
12755 (cond
12756 ((equal ans ?c)
12757 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12758 ((equal ans ?d)
12759 (call-interactively 'org-check-deadlines))
12760 ((equal ans ?b)
12761 (call-interactively 'org-check-before-date))
12762 ((equal ans ?a)
12763 (call-interactively 'org-check-after-date))
12764 ((equal ans ?D)
12765 (call-interactively 'org-check-dates-range))
12766 ((equal ans ?t)
12767 (org-show-todo-tree nil))
12768 ((equal ans ?T)
12769 (org-show-todo-tree '(4)))
12770 ((member ans '(?T ?m))
12771 (call-interactively 'org-match-sparse-tree))
12772 ((member ans '(?p ?P))
12773 (setq kwd (org-icompleting-read "Property: "
12774 (mapcar 'list (org-buffer-property-keys))))
12775 (setq value (org-icompleting-read "Value: "
12776 (mapcar 'list (org-property-values kwd))))
12777 (unless (string-match "\\`{.*}\\'" value)
12778 (setq value (concat "\"" value "\"")))
12779 (org-match-sparse-tree arg (concat kwd "=" value)))
12780 ((member ans '(?r ?R ?/))
12781 (call-interactively 'org-occur))
12782 (t (error "No such sparse tree command \"%c\"" ans)))))
12784 (defvar org-occur-highlights nil
12785 "List of overlays used for occur matches.")
12786 (make-variable-buffer-local 'org-occur-highlights)
12787 (defvar org-occur-parameters nil
12788 "Parameters of the active org-occur calls.
12789 This is a list, each call to org-occur pushes as cons cell,
12790 containing the regular expression and the callback, onto the list.
12791 The list can contain several entries if `org-occur' has been called
12792 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12793 will only contain one set of parameters. When the highlights are
12794 removed (for example with `C-c C-c', or with the next edit (depending
12795 on `org-remove-highlights-with-change'), this variable is emptied
12796 as well.")
12797 (make-variable-buffer-local 'org-occur-parameters)
12799 (defun org-occur (regexp &optional keep-previous callback)
12800 "Make a compact tree which shows all matches of REGEXP.
12801 The tree will show the lines where the regexp matches, and all higher
12802 headlines above the match. It will also show the heading after the match,
12803 to make sure editing the matching entry is easy.
12804 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12805 call to `org-occur' will be kept, to allow stacking of calls to this
12806 command.
12807 If CALLBACK is non-nil, it is a function which is called to confirm
12808 that the match should indeed be shown."
12809 (interactive "sRegexp: \nP")
12810 (when (equal regexp "")
12811 (error "Regexp cannot be empty"))
12812 (unless keep-previous
12813 (org-remove-occur-highlights nil nil t))
12814 (push (cons regexp callback) org-occur-parameters)
12815 (let ((cnt 0))
12816 (save-excursion
12817 (goto-char (point-min))
12818 (if (or (not keep-previous) ; do not want to keep
12819 (not org-occur-highlights)) ; no previous matches
12820 ;; hide everything
12821 (org-overview))
12822 (while (re-search-forward regexp nil t)
12823 (when (or (not callback)
12824 (save-match-data (funcall callback)))
12825 (setq cnt (1+ cnt))
12826 (when org-highlight-sparse-tree-matches
12827 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12828 (org-show-context 'occur-tree))))
12829 (when org-remove-highlights-with-change
12830 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12831 nil 'local))
12832 (unless org-sparse-tree-open-archived-trees
12833 (org-hide-archived-subtrees (point-min) (point-max)))
12834 (run-hooks 'org-occur-hook)
12835 (if (org-called-interactively-p 'interactive)
12836 (message "%d match(es) for regexp %s" cnt regexp))
12837 cnt))
12839 (defun org-occur-next-match (&optional n reset)
12840 "Function for `next-error-function' to find sparse tree matches.
12841 N is the number of matches to move, when negative move backwards.
12842 RESET is entirely ignored - this function always goes back to the
12843 starting point when no match is found."
12844 (let* ((limit (if (< n 0) (point-min) (point-max)))
12845 (search-func (if (< n 0)
12846 'previous-single-char-property-change
12847 'next-single-char-property-change))
12848 (n (abs n))
12849 (pos (point))
12851 (catch 'exit
12852 (while (setq p1 (funcall search-func (point) 'org-type))
12853 (when (equal p1 limit)
12854 (goto-char pos)
12855 (error "No more matches"))
12856 (when (equal (get-char-property p1 'org-type) 'org-occur)
12857 (setq n (1- n))
12858 (when (= n 0)
12859 (goto-char p1)
12860 (throw 'exit (point))))
12861 (goto-char p1))
12862 (goto-char p1)
12863 (error "No more matches"))))
12865 (defun org-show-context (&optional key)
12866 "Make sure point and context are visible.
12867 How much context is shown depends upon the variables
12868 `org-show-hierarchy-above', `org-show-following-heading',
12869 `org-show-entry-below' and `org-show-siblings'."
12870 (let ((heading-p (org-at-heading-p t))
12871 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12872 (following-p (org-get-alist-option org-show-following-heading key))
12873 (entry-p (org-get-alist-option org-show-entry-below key))
12874 (siblings-p (org-get-alist-option org-show-siblings key)))
12875 (catch 'exit
12876 ;; Show heading or entry text
12877 (if (and heading-p (not entry-p))
12878 (org-flag-heading nil) ; only show the heading
12879 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12880 (org-show-hidden-entry))) ; show entire entry
12881 (when following-p
12882 ;; Show next sibling, or heading below text
12883 (save-excursion
12884 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12885 (org-flag-heading nil))))
12886 (when siblings-p (org-show-siblings))
12887 (when hierarchy-p
12888 ;; show all higher headings, possibly with siblings
12889 (save-excursion
12890 (while (and (condition-case nil
12891 (progn (org-up-heading-all 1) t)
12892 (error nil))
12893 (not (bobp)))
12894 (org-flag-heading nil)
12895 (when siblings-p (org-show-siblings))))))))
12897 (defvar org-reveal-start-hook nil
12898 "Hook run before revealing a location.")
12900 (defun org-reveal (&optional siblings)
12901 "Show current entry, hierarchy above it, and the following headline.
12902 This can be used to show a consistent set of context around locations
12903 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12904 not t for the search context.
12906 With optional argument SIBLINGS, on each level of the hierarchy all
12907 siblings are shown. This repairs the tree structure to what it would
12908 look like when opened with hierarchical calls to `org-cycle'.
12909 With double optional argument \\[universal-argument] \\[universal-argument], \
12910 go to the parent and show the
12911 entire tree."
12912 (interactive "P")
12913 (run-hooks 'org-reveal-start-hook)
12914 (let ((org-show-hierarchy-above t)
12915 (org-show-following-heading t)
12916 (org-show-siblings (if siblings t org-show-siblings)))
12917 (org-show-context nil))
12918 (when (equal siblings '(16))
12919 (save-excursion
12920 (when (org-up-heading-safe)
12921 (org-show-subtree)
12922 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12924 (defun org-highlight-new-match (beg end)
12925 "Highlight from BEG to END and mark the highlight is an occur headline."
12926 (let ((ov (make-overlay beg end)))
12927 (overlay-put ov 'face 'secondary-selection)
12928 (overlay-put ov 'org-type 'org-occur)
12929 (push ov org-occur-highlights)))
12931 (defun org-remove-occur-highlights (&optional beg end noremove)
12932 "Remove the occur highlights from the buffer.
12933 BEG and END are ignored. If NOREMOVE is nil, remove this function
12934 from the `before-change-functions' in the current buffer."
12935 (interactive)
12936 (unless org-inhibit-highlight-removal
12937 (mapc 'delete-overlay org-occur-highlights)
12938 (setq org-occur-highlights nil)
12939 (setq org-occur-parameters nil)
12940 (unless noremove
12941 (remove-hook 'before-change-functions
12942 'org-remove-occur-highlights 'local))))
12944 ;;;; Priorities
12946 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12947 "Regular expression matching the priority indicator.")
12949 (defvar org-remove-priority-next-time nil)
12951 (defun org-priority-up ()
12952 "Increase the priority of the current item."
12953 (interactive)
12954 (org-priority 'up))
12956 (defun org-priority-down ()
12957 "Decrease the priority of the current item."
12958 (interactive)
12959 (org-priority 'down))
12961 (defun org-priority (&optional action show)
12962 "Change the priority of an item.
12963 ACTION can be `set', `up', `down', or a character."
12964 (interactive "P")
12965 (if (equal action '(4))
12966 (org-show-priority)
12967 (unless org-enable-priority-commands
12968 (error "Priority commands are disabled"))
12969 (setq action (or action 'set))
12970 (let (current new news have remove)
12971 (save-excursion
12972 (org-back-to-heading t)
12973 (if (looking-at org-priority-regexp)
12974 (setq current (string-to-char (match-string 2))
12975 have t))
12976 (cond
12977 ((eq action 'remove)
12978 (setq remove t new ?\ ))
12979 ((or (eq action 'set)
12980 (if (featurep 'xemacs) (characterp action) (integerp action)))
12981 (if (not (eq action 'set))
12982 (setq new action)
12983 (message "Priority %c-%c, SPC to remove: "
12984 org-highest-priority org-lowest-priority)
12985 (save-match-data
12986 (setq new (read-char-exclusive))))
12987 (if (and (= (upcase org-highest-priority) org-highest-priority)
12988 (= (upcase org-lowest-priority) org-lowest-priority))
12989 (setq new (upcase new)))
12990 (cond ((equal new ?\ ) (setq remove t))
12991 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12992 (error "Priority must be between `%c' and `%c'"
12993 org-highest-priority org-lowest-priority))))
12994 ((eq action 'up)
12995 (setq new (if have
12996 (1- current) ; normal cycling
12997 ;; last priority was empty
12998 (if (eq last-command this-command)
12999 org-lowest-priority ; wrap around empty to lowest
13000 ;; default
13001 (if org-priority-start-cycle-with-default
13002 org-default-priority
13003 (1- org-default-priority))))))
13004 ((eq action 'down)
13005 (setq new (if have
13006 (1+ current) ; normal cycling
13007 ;; last priority was empty
13008 (if (eq last-command this-command)
13009 org-highest-priority ; wrap around empty to highest
13010 ;; default
13011 (if org-priority-start-cycle-with-default
13012 org-default-priority
13013 (1+ org-default-priority))))))
13014 (t (error "Invalid action")))
13015 (if (or (< (upcase new) org-highest-priority)
13016 (> (upcase new) org-lowest-priority))
13017 (if (and (memq action '(up down))
13018 (not have) (not (eq last-command this-command)))
13019 ;; `new' is from default priority
13020 (error
13021 "The default can not be set, see `org-default-priority' why")
13022 ;; normal cycling: `new' is beyond highest/lowest priority
13023 ;; and is wrapped around to the empty priority
13024 (setq remove t)))
13025 (setq news (format "%c" new))
13026 (if have
13027 (if remove
13028 (replace-match "" t t nil 1)
13029 (replace-match news t t nil 2))
13030 (if remove
13031 (error "No priority cookie found in line")
13032 (let ((case-fold-search nil))
13033 (looking-at org-todo-line-regexp))
13034 (if (match-end 2)
13035 (progn
13036 (goto-char (match-end 2))
13037 (insert " [#" news "]"))
13038 (goto-char (match-beginning 3))
13039 (insert "[#" news "] "))))
13040 (org-preserve-lc (org-set-tags nil 'align)))
13041 (if remove
13042 (message "Priority removed")
13043 (message "Priority of current item set to %s" news)))))
13045 (defun org-show-priority ()
13046 "Show the priority of the current item.
13047 This priority is composed of the main priority given with the [#A] cookies,
13048 and by additional input from the age of a schedules or deadline entry."
13049 (interactive)
13050 (let ((pri (if (eq major-mode 'org-agenda-mode)
13051 (org-get-at-bol 'priority)
13052 (save-excursion
13053 (save-match-data
13054 (beginning-of-line)
13055 (and (looking-at org-heading-regexp)
13056 (org-get-priority (match-string 0))))))))
13057 (message "Priority is %d" (if pri pri -1000))))
13059 (defun org-get-priority (s)
13060 "Find priority cookie and return priority."
13061 (if (functionp org-get-priority-function)
13062 (funcall org-get-priority-function)
13063 (save-match-data
13064 (if (not (string-match org-priority-regexp s))
13065 (* 1000 (- org-lowest-priority org-default-priority))
13066 (* 1000 (- org-lowest-priority
13067 (string-to-char (match-string 2 s))))))))
13069 ;;;; Tags
13071 (defvar org-agenda-archives-mode)
13072 (defvar org-map-continue-from nil
13073 "Position from where mapping should continue.
13074 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13076 (defvar org-scanner-tags nil
13077 "The current tag list while the tags scanner is running.")
13078 (defvar org-trust-scanner-tags nil
13079 "Should `org-get-tags-at' use the tags for the scanner.
13080 This is for internal dynamical scoping only.
13081 When this is non-nil, the function `org-get-tags-at' will return the value
13082 of `org-scanner-tags' instead of building the list by itself. This
13083 can lead to large speed-ups when the tags scanner is used in a file with
13084 many entries, and when the list of tags is retrieved, for example to
13085 obtain a list of properties. Building the tags list for each entry in such
13086 a file becomes an N^2 operation - but with this variable set, it scales
13087 as N.")
13089 (defun org-scan-tags (action matcher todo-only &optional start-level)
13090 "Scan headline tags with inheritance and produce output ACTION.
13092 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13093 or `agenda' to produce an entry list for an agenda view. It can also be
13094 a Lisp form or a function that should be called at each matched headline, in
13095 this case the return value is a list of all return values from these calls.
13097 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13098 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13099 only lines with a not-done TODO keyword are included in the output.
13100 This should be the same variable that was scoped into
13101 and set by `org-make-tags-matcher' when it constructed MATCHER.
13103 START-LEVEL can be a string with asterisks, reducing the scope to
13104 headlines matching this string."
13105 (require 'org-agenda)
13106 (let* ((re (concat "^"
13107 (if start-level
13108 ;; Get the correct level to match
13109 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13110 org-outline-regexp)
13111 " *\\(\\<\\("
13112 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13113 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13114 (props (list 'face 'default
13115 'done-face 'org-agenda-done
13116 'undone-face 'default
13117 'mouse-face 'highlight
13118 'org-not-done-regexp org-not-done-regexp
13119 'org-todo-regexp org-todo-regexp
13120 'org-complex-heading-regexp org-complex-heading-regexp
13121 'help-echo
13122 (format "mouse-2 or RET jump to org file %s"
13123 (abbreviate-file-name
13124 (or (buffer-file-name (buffer-base-buffer))
13125 (buffer-name (buffer-base-buffer)))))))
13126 (case-fold-search nil)
13127 (org-map-continue-from nil)
13128 lspos tags tags-list
13129 (tags-alist (list (cons 0 org-file-tags)))
13130 (llast 0) rtn rtn1 level category i txt
13131 todo marker entry priority)
13132 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13133 (setq action (list 'lambda nil action)))
13134 (save-excursion
13135 (goto-char (point-min))
13136 (when (eq action 'sparse-tree)
13137 (org-overview)
13138 (org-remove-occur-highlights))
13139 (while (re-search-forward re nil t)
13140 (setq org-map-continue-from nil)
13141 (catch :skip
13142 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13143 tags (if (match-end 4) (org-match-string-no-properties 4)))
13144 (goto-char (setq lspos (match-beginning 0)))
13145 (setq level (org-reduced-level (org-outline-level))
13146 category (org-get-category))
13147 (setq i llast llast level)
13148 ;; remove tag lists from same and sublevels
13149 (while (>= i level)
13150 (when (setq entry (assoc i tags-alist))
13151 (setq tags-alist (delete entry tags-alist)))
13152 (setq i (1- i)))
13153 ;; add the next tags
13154 (when tags
13155 (setq tags (org-split-string tags ":")
13156 tags-alist
13157 (cons (cons level tags) tags-alist)))
13158 ;; compile tags for current headline
13159 (setq tags-list
13160 (if org-use-tag-inheritance
13161 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13162 tags)
13163 org-scanner-tags tags-list)
13164 (when org-use-tag-inheritance
13165 (setcdr (car tags-alist)
13166 (mapcar (lambda (x)
13167 (setq x (copy-sequence x))
13168 (org-add-prop-inherited x))
13169 (cdar tags-alist))))
13170 (when (and tags org-use-tag-inheritance
13171 (or (not (eq t org-use-tag-inheritance))
13172 org-tags-exclude-from-inheritance))
13173 ;; selective inheritance, remove uninherited ones
13174 (setcdr (car tags-alist)
13175 (org-remove-uninherited-tags (cdar tags-alist))))
13176 (when (and
13178 ;; eval matcher only when the todo condition is OK
13179 (and (or (not todo-only) (member todo org-not-done-keywords))
13180 (let ((case-fold-search t) (org-trust-scanner-tags t))
13181 (eval matcher)))
13183 ;; Call the skipper, but return t if it does not skip,
13184 ;; so that the `and' form continues evaluating
13185 (progn
13186 (unless (eq action 'sparse-tree) (org-agenda-skip))
13189 ;; Check if timestamps are deselecting this entry
13190 (or (not todo-only)
13191 (and (member todo org-not-done-keywords)
13192 (or (not org-agenda-tags-todo-honor-ignore-options)
13193 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
13195 ;; Extra check for the archive tag
13196 ;; FIXME: Does the skipper already do this????
13198 (not (member org-archive-tag tags-list))
13199 ;; we have an archive tag, should we use this anyway?
13200 (or (not org-agenda-skip-archived-trees)
13201 (and (eq action 'agenda) org-agenda-archives-mode))))
13203 ;; select this headline
13204 (cond
13205 ((eq action 'sparse-tree)
13206 (and org-highlight-sparse-tree-matches
13207 (org-get-heading) (match-end 0)
13208 (org-highlight-new-match
13209 (match-beginning 1) (match-end 1)))
13210 (org-show-context 'tags-tree))
13211 ((eq action 'agenda)
13212 (setq txt (org-agenda-format-item
13214 (concat
13215 (if (eq org-tags-match-list-sublevels 'indented)
13216 (make-string (1- level) ?.) "")
13217 (org-get-heading))
13218 level category
13219 tags-list)
13220 priority (org-get-priority txt))
13221 (goto-char lspos)
13222 (setq marker (org-agenda-new-marker))
13223 (org-add-props txt props
13224 'org-marker marker 'org-hd-marker marker 'org-category category
13225 'todo-state todo
13226 'priority priority 'type "tagsmatch")
13227 (push txt rtn))
13228 ((functionp action)
13229 (setq org-map-continue-from nil)
13230 (save-excursion
13231 (setq rtn1 (funcall action))
13232 (push rtn1 rtn)))
13233 (t (error "Invalid action")))
13235 ;; if we are to skip sublevels, jump to end of subtree
13236 (unless org-tags-match-list-sublevels
13237 (org-end-of-subtree t)
13238 (backward-char 1))))
13239 ;; Get the correct position from where to continue
13240 (if org-map-continue-from
13241 (goto-char org-map-continue-from)
13242 (and (= (point) lspos) (end-of-line 1)))))
13243 (when (and (eq action 'sparse-tree)
13244 (not org-sparse-tree-open-archived-trees))
13245 (org-hide-archived-subtrees (point-min) (point-max)))
13246 (nreverse rtn)))
13248 (defun org-remove-uninherited-tags (tags)
13249 "Remove all tags that are not inherited from the list TAGS."
13250 (cond
13251 ((eq org-use-tag-inheritance t)
13252 (if org-tags-exclude-from-inheritance
13253 (org-delete-all org-tags-exclude-from-inheritance tags)
13254 tags))
13255 ((not org-use-tag-inheritance) nil)
13256 ((stringp org-use-tag-inheritance)
13257 (delq nil (mapcar
13258 (lambda (x)
13259 (if (and (string-match org-use-tag-inheritance x)
13260 (not (member x org-tags-exclude-from-inheritance)))
13261 x nil))
13262 tags)))
13263 ((listp org-use-tag-inheritance)
13264 (delq nil (mapcar
13265 (lambda (x)
13266 (if (member x org-use-tag-inheritance) x nil))
13267 tags)))))
13269 (defun org-match-sparse-tree (&optional todo-only match)
13270 "Create a sparse tree according to tags string MATCH.
13271 MATCH can contain positive and negative selection of tags, like
13272 \"+WORK+URGENT-WITHBOSS\".
13273 If optional argument TODO-ONLY is non-nil, only select lines that are
13274 also TODO lines."
13275 (interactive "P")
13276 (org-agenda-prepare-buffers (list (current-buffer)))
13277 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13279 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13281 (defvar org-cached-props nil)
13282 (defun org-cached-entry-get (pom property)
13283 (if (or (eq t org-use-property-inheritance)
13284 (and (stringp org-use-property-inheritance)
13285 (string-match org-use-property-inheritance property))
13286 (and (listp org-use-property-inheritance)
13287 (member property org-use-property-inheritance)))
13288 ;; Caching is not possible, check it directly
13289 (org-entry-get pom property 'inherit)
13290 ;; Get all properties, so that we can do complicated checks easily
13291 (cdr (assoc property (or org-cached-props
13292 (setq org-cached-props
13293 (org-entry-properties pom)))))))
13295 (defun org-global-tags-completion-table (&optional files)
13296 "Return the list of all tags in all agenda buffer/files.
13297 Optional FILES argument is a list of files which can be used
13298 instead of the agenda files."
13299 (save-excursion
13300 (org-uniquify
13301 (delq nil
13302 (apply 'append
13303 (mapcar
13304 (lambda (file)
13305 (set-buffer (find-file-noselect file))
13306 (append (org-get-buffer-tags)
13307 (mapcar (lambda (x) (if (stringp (car-safe x))
13308 (list (car-safe x)) nil))
13309 org-tag-alist)))
13310 (if (and files (car files))
13311 files
13312 (org-agenda-files))))))))
13314 (defun org-make-tags-matcher (match)
13315 "Create the TAGS/TODO matcher form for the selection string MATCH.
13317 The variable `todo-only' is scoped dynamically into this function.
13318 It will be set to t if the matcher restricts matching to TODO entries,
13319 otherwise will not be touched.
13321 Returns a cons of the selection string MATCH and the constructed
13322 lisp form implementing the matcher. The matcher is to be evaluated
13323 at an Org entry, with point on the headline, and returns t if the
13324 entry matches the selection string MATCH. The returned lisp form
13325 references two variables with information about the entry, which
13326 must be bound around the form's evaluation: todo, the TODO keyword
13327 at the entry (or nil of none); and tags-list, the list of all tags
13328 at the entry including inherited ones. Additionally, the category
13329 of the entry (if any) must be specified as the text property
13330 'org-category on the headline.
13332 See also `org-scan-tags'.
13334 (declare (special todo-only))
13335 (unless (boundp 'todo-only)
13336 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13337 (unless match
13338 ;; Get a new match request, with completion
13339 (let ((org-last-tags-completion-table
13340 (org-global-tags-completion-table)))
13341 (setq match (org-completing-read-no-i
13342 "Match: " 'org-tags-completion-function nil nil nil
13343 'org-tags-history))))
13345 ;; Parse the string and create a lisp form
13346 (let ((match0 match)
13347 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13348 minus tag mm
13349 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13350 orterms term orlist re-p str-p level-p level-op time-p
13351 prop-p pn pv po gv rest)
13352 (if (string-match "/+" match)
13353 ;; match contains also a todo-matching request
13354 (progn
13355 (setq tagsmatch (substring match 0 (match-beginning 0))
13356 todomatch (substring match (match-end 0)))
13357 (if (string-match "^!" todomatch)
13358 (setq todo-only t todomatch (substring todomatch 1)))
13359 (if (string-match "^\\s-*$" todomatch)
13360 (setq todomatch nil)))
13361 ;; only matching tags
13362 (setq tagsmatch match todomatch nil))
13364 ;; Make the tags matcher
13365 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13366 (setq tagsmatcher t)
13367 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13368 (while (setq term (pop orterms))
13369 (while (and (equal (substring term -1) "\\") orterms)
13370 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13371 (while (string-match re term)
13372 (setq rest (substring term (match-end 0))
13373 minus (and (match-end 1)
13374 (equal (match-string 1 term) "-"))
13375 tag (save-match-data (replace-regexp-in-string
13376 "\\\\-" "-"
13377 (match-string 2 term)))
13378 re-p (equal (string-to-char tag) ?{)
13379 level-p (match-end 4)
13380 prop-p (match-end 5)
13381 mm (cond
13382 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13383 (level-p
13384 (setq level-op (org-op-to-function (match-string 3 term)))
13385 `(,level-op level ,(string-to-number
13386 (match-string 4 term))))
13387 (prop-p
13388 (setq pn (match-string 5 term)
13389 po (match-string 6 term)
13390 pv (match-string 7 term)
13391 re-p (equal (string-to-char pv) ?{)
13392 str-p (equal (string-to-char pv) ?\")
13393 time-p (save-match-data
13394 (string-match "^\"[[<].*[]>]\"$" pv))
13395 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13396 (if time-p (setq pv (org-matcher-time pv)))
13397 (setq po (org-op-to-function po (if time-p 'time str-p)))
13398 (cond
13399 ((equal pn "CATEGORY")
13400 (setq gv '(get-text-property (point) 'org-category)))
13401 ((equal pn "TODO")
13402 (setq gv 'todo))
13404 (setq gv `(org-cached-entry-get nil ,pn))))
13405 (if re-p
13406 (if (eq po 'org<>)
13407 `(not (string-match ,pv (or ,gv "")))
13408 `(string-match ,pv (or ,gv "")))
13409 (if str-p
13410 `(,po (or ,gv "") ,pv)
13411 `(,po (string-to-number (or ,gv ""))
13412 ,(string-to-number pv) ))))
13413 (t `(member ,tag tags-list)))
13414 mm (if minus (list 'not mm) mm)
13415 term rest)
13416 (push mm tagsmatcher))
13417 (push (if (> (length tagsmatcher) 1)
13418 (cons 'and tagsmatcher)
13419 (car tagsmatcher))
13420 orlist)
13421 (setq tagsmatcher nil))
13422 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13423 (setq tagsmatcher
13424 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13425 ;; Make the todo matcher
13426 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13427 (setq todomatcher t)
13428 (setq orterms (org-split-string todomatch "|") orlist nil)
13429 (while (setq term (pop orterms))
13430 (while (string-match re term)
13431 (setq minus (and (match-end 1)
13432 (equal (match-string 1 term) "-"))
13433 kwd (match-string 2 term)
13434 re-p (equal (string-to-char kwd) ?{)
13435 term (substring term (match-end 0))
13436 mm (if re-p
13437 `(string-match ,(substring kwd 1 -1) todo)
13438 (list 'equal 'todo kwd))
13439 mm (if minus (list 'not mm) mm))
13440 (push mm todomatcher))
13441 (push (if (> (length todomatcher) 1)
13442 (cons 'and todomatcher)
13443 (car todomatcher))
13444 orlist)
13445 (setq todomatcher nil))
13446 (setq todomatcher (if (> (length orlist) 1)
13447 (cons 'or orlist) (car orlist))))
13449 ;; Return the string and lisp forms of the matcher
13450 (setq matcher (if todomatcher
13451 (list 'and tagsmatcher todomatcher)
13452 tagsmatcher))
13453 (when todo-only
13454 (setq matcher (list 'and '(member todo org-not-done-keywords)
13455 matcher)))
13456 (cons match0 matcher)))
13458 (defun org-op-to-function (op &optional stringp)
13459 "Turn an operator into the appropriate function."
13460 (setq op
13461 (cond
13462 ((equal op "<" ) '(< string< org-time<))
13463 ((equal op ">" ) '(> org-string> org-time>))
13464 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13465 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13466 ((member op '("=" "==")) '(= string= org-time=))
13467 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13468 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13470 (defun org<> (a b) (not (= a b)))
13471 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13472 (defun org-string>= (a b) (not (string< a b)))
13473 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13474 (defun org-string<> (a b) (not (string= a b)))
13475 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13476 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13477 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13478 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13479 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13480 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13481 (defun org-2ft (s)
13482 "Convert S to a floating point time.
13483 If S is already a number, just return it. If it is a string, parse
13484 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13485 (cond
13486 ((numberp s) s)
13487 ((stringp s)
13488 (condition-case nil
13489 (float-time (apply 'encode-time (org-parse-time-string s)))
13490 (error 0.)))
13491 (t 0.)))
13493 (defun org-time-today ()
13494 "Time in seconds today at 0:00.
13495 Returns the float number of seconds since the beginning of the
13496 epoch to the beginning of today (00:00)."
13497 (float-time (apply 'encode-time
13498 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13500 (defun org-matcher-time (s)
13501 "Interpret a time comparison value."
13502 (save-match-data
13503 (cond
13504 ((string= s "<now>") (float-time))
13505 ((string= s "<today>") (org-time-today))
13506 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13507 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13508 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13509 (+ (org-time-today)
13510 (* (string-to-number (match-string 1 s))
13511 (cdr (assoc (match-string 2 s)
13512 '(("d" . 86400.0) ("w" . 604800.0)
13513 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13514 (t (org-2ft s)))))
13516 (defun org-match-any-p (re list)
13517 "Does re match any element of list?"
13518 (setq list (mapcar (lambda (x) (string-match re x)) list))
13519 (delq nil list))
13521 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13522 (defvar org-tags-overlay (make-overlay 1 1))
13523 (org-detach-overlay org-tags-overlay)
13525 (defun org-get-local-tags-at (&optional pos)
13526 "Get a list of tags defined in the current headline."
13527 (org-get-tags-at pos 'local))
13529 (defun org-get-local-tags ()
13530 "Get a list of tags defined in the current headline."
13531 (org-get-tags-at nil 'local))
13533 (defun org-get-tags-at (&optional pos local)
13534 "Get a list of all headline tags applicable at POS.
13535 POS defaults to point. If tags are inherited, the list contains
13536 the targets in the same sequence as the headlines appear, i.e.
13537 the tags of the current headline come last.
13538 When LOCAL is non-nil, only return tags from the current headline,
13539 ignore inherited ones."
13540 (interactive)
13541 (if (and org-trust-scanner-tags
13542 (or (not pos) (equal pos (point)))
13543 (not local))
13544 org-scanner-tags
13545 (let (tags ltags lastpos parent)
13546 (save-excursion
13547 (save-restriction
13548 (widen)
13549 (goto-char (or pos (point)))
13550 (save-match-data
13551 (catch 'done
13552 (condition-case nil
13553 (progn
13554 (org-back-to-heading t)
13555 (while (not (equal lastpos (point)))
13556 (setq lastpos (point))
13557 (when (looking-at
13558 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13559 (setq ltags (org-split-string
13560 (org-match-string-no-properties 1) ":"))
13561 (when parent
13562 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13563 (setq tags (append
13564 (if parent
13565 (org-remove-uninherited-tags ltags)
13566 ltags)
13567 tags)))
13568 (or org-use-tag-inheritance (throw 'done t))
13569 (if local (throw 'done t))
13570 (or (org-up-heading-safe) (error nil))
13571 (setq parent t)))
13572 (error nil)))))
13573 (if local
13574 tags
13575 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13577 (defun org-add-prop-inherited (s)
13578 (add-text-properties 0 (length s) '(inherited t) s)
13581 (defun org-toggle-tag (tag &optional onoff)
13582 "Toggle the tag TAG for the current line.
13583 If ONOFF is `on' or `off', don't toggle but set to this state."
13584 (let (res current)
13585 (save-excursion
13586 (org-back-to-heading t)
13587 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13588 (point-at-eol) t)
13589 (progn
13590 (setq current (match-string 1))
13591 (replace-match ""))
13592 (setq current ""))
13593 (setq current (nreverse (org-split-string current ":")))
13594 (cond
13595 ((eq onoff 'on)
13596 (setq res t)
13597 (or (member tag current) (push tag current)))
13598 ((eq onoff 'off)
13599 (or (not (member tag current)) (setq current (delete tag current))))
13600 (t (if (member tag current)
13601 (setq current (delete tag current))
13602 (setq res t)
13603 (push tag current))))
13604 (end-of-line 1)
13605 (if current
13606 (progn
13607 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13608 (org-set-tags nil t))
13609 (delete-horizontal-space))
13610 (run-hooks 'org-after-tags-change-hook))
13611 res))
13613 (defun org-align-tags-here (to-col)
13614 ;; Assumes that this is a headline
13615 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13616 (beginning-of-line 1)
13617 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13618 (< pos (match-beginning 2)))
13619 (progn
13620 (setq tags-l (- (match-end 2) (match-beginning 2)))
13621 (goto-char (match-beginning 1))
13622 (insert " ")
13623 (delete-region (point) (1+ (match-beginning 2)))
13624 (setq ncol (max (current-column)
13625 (1+ col)
13626 (if (> to-col 0)
13627 to-col
13628 (- (abs to-col) tags-l))))
13629 (setq p (point))
13630 (insert (make-string (- ncol (current-column)) ?\ ))
13631 (setq ncol (current-column))
13632 (when indent-tabs-mode (tabify p (point-at-eol)))
13633 (org-move-to-column (min ncol col) t))
13634 (goto-char pos))))
13636 (defun org-set-tags-command (&optional arg just-align)
13637 "Call the set-tags command for the current entry."
13638 (interactive "P")
13639 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13640 (org-set-tags arg just-align)
13641 (save-excursion
13642 (org-back-to-heading t)
13643 (org-set-tags arg just-align))))
13645 (defun org-set-tags-to (data)
13646 "Set the tags of the current entry to DATA, replacing the current tags.
13647 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13648 If DATA is nil or the empty string, any tags will be removed."
13649 (interactive "sTags: ")
13650 (setq data
13651 (cond
13652 ((eq data nil) "")
13653 ((equal data "") "")
13654 ((stringp data)
13655 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13656 ":"))
13657 ((listp data)
13658 (concat ":" (mapconcat 'identity data ":") ":"))))
13659 (when data
13660 (save-excursion
13661 (org-back-to-heading t)
13662 (when (looking-at org-complex-heading-regexp)
13663 (if (match-end 5)
13664 (progn
13665 (goto-char (match-beginning 5))
13666 (insert data)
13667 (delete-region (point) (point-at-eol))
13668 (org-set-tags nil 'align))
13669 (goto-char (point-at-eol))
13670 (insert " " data)
13671 (org-set-tags nil 'align)))
13672 (beginning-of-line 1)
13673 (if (looking-at ".*?\\([ \t]+\\)$")
13674 (delete-region (match-beginning 1) (match-end 1))))))
13676 (defun org-align-all-tags ()
13677 "Align the tags i all headings."
13678 (interactive)
13679 (save-excursion
13680 (or (ignore-errors (org-back-to-heading t))
13681 (outline-next-heading))
13682 (if (org-at-heading-p)
13683 (org-set-tags t)
13684 (message "No headings"))))
13686 (defvar org-indent-indentation-per-level)
13687 (defun org-set-tags (&optional arg just-align)
13688 "Set the tags for the current headline.
13689 With prefix ARG, realign all tags in headings in the current buffer."
13690 (interactive "P")
13691 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13692 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13693 'region-start-level 'region))
13694 org-loop-over-headlines-in-active-region)
13695 (org-map-entries
13696 ;; We don't use ARG and JUST-ALIGN here these args are not
13697 ;; useful when looping over headlines
13698 `(org-set-tags)
13699 org-loop-over-headlines-in-active-region
13700 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13701 (let* ((re org-outline-regexp-bol)
13702 (current (unless arg (org-get-tags-string)))
13703 (col (current-column))
13704 (org-setting-tags t)
13705 table current-tags inherited-tags ; computed below when needed
13706 tags p0 c0 c1 rpl di tc level)
13707 (if arg
13708 (save-excursion
13709 (goto-char (point-min))
13710 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13711 (while (re-search-forward re nil t)
13712 (org-set-tags nil t)
13713 (end-of-line 1)))
13714 (message "All tags realigned to column %d" org-tags-column))
13715 (if just-align
13716 (setq tags current)
13717 ;; Get a new set of tags from the user
13718 (save-excursion
13719 (setq table (append org-tag-persistent-alist
13720 (or org-tag-alist (org-get-buffer-tags))
13721 (and
13722 org-complete-tags-always-offer-all-agenda-tags
13723 (org-global-tags-completion-table
13724 (org-agenda-files))))
13725 org-last-tags-completion-table table
13726 current-tags (org-split-string current ":")
13727 inherited-tags (nreverse
13728 (nthcdr (length current-tags)
13729 (nreverse (org-get-tags-at))))
13730 tags
13731 (if (or (eq t org-use-fast-tag-selection)
13732 (and org-use-fast-tag-selection
13733 (delq nil (mapcar 'cdr table))))
13734 (org-fast-tag-selection
13735 current-tags inherited-tags table
13736 (if org-fast-tag-selection-include-todo
13737 org-todo-key-alist))
13738 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13739 (org-trim
13740 (org-icompleting-read "Tags: "
13741 'org-tags-completion-function
13742 nil nil current 'org-tags-history))))))
13743 (while (string-match "[-+&]+" tags)
13744 ;; No boolean logic, just a list
13745 (setq tags (replace-match ":" t t tags))))
13747 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13749 (if org-tags-sort-function
13750 (setq tags (mapconcat 'identity
13751 (sort (org-split-string
13752 tags (org-re "[^[:alnum:]_@#%]+"))
13753 org-tags-sort-function) ":")))
13755 (if (string-match "\\`[\t ]*\\'" tags)
13756 (setq tags "")
13757 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13758 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13760 ;; Insert new tags at the correct column
13761 (beginning-of-line 1)
13762 (setq level (or (and (looking-at org-outline-regexp)
13763 (- (match-end 0) (point) 1))
13765 (cond
13766 ((and (equal current "") (equal tags "")))
13767 ((re-search-forward
13768 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13769 (point-at-eol) t)
13770 (if (equal tags "")
13771 (setq rpl "")
13772 (goto-char (match-beginning 0))
13773 (setq c0 (current-column)
13774 ;; compute offset for the case of org-indent-mode active
13775 di (if org-indent-mode
13776 (* (1- org-indent-indentation-per-level) (1- level))
13778 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13779 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13780 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13781 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13782 (replace-match rpl t t)
13783 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13784 tags)
13785 (t (error "Tags alignment failed")))
13786 (org-move-to-column col)
13787 (unless just-align
13788 (run-hooks 'org-after-tags-change-hook))))))
13790 (defun org-change-tag-in-region (beg end tag off)
13791 "Add or remove TAG for each entry in the region.
13792 This works in the agenda, and also in an org-mode buffer."
13793 (interactive
13794 (list (region-beginning) (region-end)
13795 (let ((org-last-tags-completion-table
13796 (if (derived-mode-p 'org-mode)
13797 (org-get-buffer-tags)
13798 (org-global-tags-completion-table))))
13799 (org-icompleting-read
13800 "Tag: " 'org-tags-completion-function nil nil nil
13801 'org-tags-history))
13802 (progn
13803 (message "[s]et or [r]emove? ")
13804 (equal (read-char-exclusive) ?r))))
13805 (if (fboundp 'deactivate-mark) (deactivate-mark))
13806 (let ((agendap (equal major-mode 'org-agenda-mode))
13807 l1 l2 m buf pos newhead (cnt 0))
13808 (goto-char end)
13809 (setq l2 (1- (org-current-line)))
13810 (goto-char beg)
13811 (setq l1 (org-current-line))
13812 (loop for l from l1 to l2 do
13813 (org-goto-line l)
13814 (setq m (get-text-property (point) 'org-hd-marker))
13815 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13816 (and agendap m))
13817 (setq buf (if agendap (marker-buffer m) (current-buffer))
13818 pos (if agendap m (point)))
13819 (with-current-buffer buf
13820 (save-excursion
13821 (save-restriction
13822 (goto-char pos)
13823 (setq cnt (1+ cnt))
13824 (org-toggle-tag tag (if off 'off 'on))
13825 (setq newhead (org-get-heading)))))
13826 (and agendap (org-agenda-change-all-lines newhead m))))
13827 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13829 (defun org-tags-completion-function (string predicate &optional flag)
13830 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13831 (confirm (lambda (x) (stringp (car x)))))
13832 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13833 (setq s1 (match-string 1 string)
13834 s2 (match-string 2 string))
13835 (setq s1 "" s2 string))
13836 (cond
13837 ((eq flag nil)
13838 ;; try completion
13839 (setq rtn (try-completion s2 ctable confirm))
13840 (if (stringp rtn)
13841 (setq rtn
13842 (concat s1 s2 (substring rtn (length s2))
13843 (if (and org-add-colon-after-tag-completion
13844 (assoc rtn ctable))
13845 ":" ""))))
13846 rtn)
13847 ((eq flag t)
13848 ;; all-completions
13849 (all-completions s2 ctable confirm)
13851 ((eq flag 'lambda)
13852 ;; exact match?
13853 (assoc s2 ctable)))
13856 (defun org-fast-tag-insert (kwd tags face &optional end)
13857 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13858 (insert (format "%-12s" (concat kwd ":"))
13859 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13860 (or end "")))
13862 (defun org-fast-tag-show-exit (flag)
13863 (save-excursion
13864 (org-goto-line 3)
13865 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13866 (replace-match ""))
13867 (when flag
13868 (end-of-line 1)
13869 (org-move-to-column (- (window-width) 19) t)
13870 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13872 (defun org-set-current-tags-overlay (current prefix)
13873 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13874 (if (featurep 'xemacs)
13875 (org-overlay-display org-tags-overlay (concat prefix s)
13876 'secondary-selection)
13877 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13878 (org-overlay-display org-tags-overlay (concat prefix s)))))
13880 (defvar org-last-tag-selection-key nil)
13881 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13882 "Fast tag selection with single keys.
13883 CURRENT is the current list of tags in the headline, INHERITED is the
13884 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13885 possibly with grouping information. TODO-TABLE is a similar table with
13886 TODO keywords, should these have keys assigned to them.
13887 If the keys are nil, a-z are automatically assigned.
13888 Returns the new tags string, or nil to not change the current settings."
13889 (let* ((fulltable (append table todo-table))
13890 (maxlen (apply 'max (mapcar
13891 (lambda (x)
13892 (if (stringp (car x)) (string-width (car x)) 0))
13893 fulltable)))
13894 (buf (current-buffer))
13895 (expert (eq org-fast-tag-selection-single-key 'expert))
13896 (buffer-tags nil)
13897 (fwidth (+ maxlen 3 1 3))
13898 (ncol (/ (- (window-width) 4) fwidth))
13899 (i-face 'org-done)
13900 (c-face 'org-todo)
13901 tg cnt e c char c1 c2 ntable tbl rtn
13902 ov-start ov-end ov-prefix
13903 (exit-after-next org-fast-tag-selection-single-key)
13904 (done-keywords org-done-keywords)
13905 groups ingroup)
13906 (save-excursion
13907 (beginning-of-line 1)
13908 (if (looking-at
13909 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13910 (setq ov-start (match-beginning 1)
13911 ov-end (match-end 1)
13912 ov-prefix "")
13913 (setq ov-start (1- (point-at-eol))
13914 ov-end (1+ ov-start))
13915 (skip-chars-forward "^\n\r")
13916 (setq ov-prefix
13917 (concat
13918 (buffer-substring (1- (point)) (point))
13919 (if (> (current-column) org-tags-column)
13921 (make-string (- org-tags-column (current-column)) ?\ ))))))
13922 (move-overlay org-tags-overlay ov-start ov-end)
13923 (save-window-excursion
13924 (if expert
13925 (set-buffer (get-buffer-create " *Org tags*"))
13926 (delete-other-windows)
13927 (split-window-vertically)
13928 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13929 (erase-buffer)
13930 (org-set-local 'org-done-keywords done-keywords)
13931 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13932 (org-fast-tag-insert "Current" current c-face "\n\n")
13933 (org-fast-tag-show-exit exit-after-next)
13934 (org-set-current-tags-overlay current ov-prefix)
13935 (setq tbl fulltable char ?a cnt 0)
13936 (while (setq e (pop tbl))
13937 (cond
13938 ((equal (car e) :startgroup)
13939 (push '() groups) (setq ingroup t)
13940 (when (not (= cnt 0))
13941 (setq cnt 0)
13942 (insert "\n"))
13943 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13944 ((equal (car e) :endgroup)
13945 (setq ingroup nil cnt 0)
13946 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13947 ((equal e '(:newline))
13948 (when (not (= cnt 0))
13949 (setq cnt 0)
13950 (insert "\n")
13951 (setq e (car tbl))
13952 (while (equal (car tbl) '(:newline))
13953 (insert "\n")
13954 (setq tbl (cdr tbl)))))
13956 (setq tg (copy-sequence (car e)) c2 nil)
13957 (if (cdr e)
13958 (setq c (cdr e))
13959 ;; automatically assign a character.
13960 (setq c1 (string-to-char
13961 (downcase (substring
13962 tg (if (= (string-to-char tg) ?@) 1 0)))))
13963 (if (or (rassoc c1 ntable) (rassoc c1 table))
13964 (while (or (rassoc char ntable) (rassoc char table))
13965 (setq char (1+ char)))
13966 (setq c2 c1))
13967 (setq c (or c2 char)))
13968 (if ingroup (push tg (car groups)))
13969 (setq tg (org-add-props tg nil 'face
13970 (cond
13971 ((not (assoc tg table))
13972 (org-get-todo-face tg))
13973 ((member tg current) c-face)
13974 ((member tg inherited) i-face))))
13975 (if (and (= cnt 0) (not ingroup)) (insert " "))
13976 (insert "[" c "] " tg (make-string
13977 (- fwidth 4 (length tg)) ?\ ))
13978 (push (cons tg c) ntable)
13979 (when (= (setq cnt (1+ cnt)) ncol)
13980 (insert "\n")
13981 (if ingroup (insert " "))
13982 (setq cnt 0)))))
13983 (setq ntable (nreverse ntable))
13984 (insert "\n")
13985 (goto-char (point-min))
13986 (if (not expert) (org-fit-window-to-buffer))
13987 (setq rtn
13988 (catch 'exit
13989 (while t
13990 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13991 (if (not groups) "no " "")
13992 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13993 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13994 (setq org-last-tag-selection-key c)
13995 (cond
13996 ((= c ?\r) (throw 'exit t))
13997 ((= c ?!)
13998 (setq groups (not groups))
13999 (goto-char (point-min))
14000 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14001 ((= c ?\C-c)
14002 (if (not expert)
14003 (org-fast-tag-show-exit
14004 (setq exit-after-next (not exit-after-next)))
14005 (setq expert nil)
14006 (delete-other-windows)
14007 (set-window-buffer (split-window-vertically) " *Org tags*")
14008 (org-switch-to-buffer-other-window " *Org tags*")
14009 (org-fit-window-to-buffer)))
14010 ((or (= c ?\C-g)
14011 (and (= c ?q) (not (rassoc c ntable))))
14012 (org-detach-overlay org-tags-overlay)
14013 (setq quit-flag t))
14014 ((= c ?\ )
14015 (setq current nil)
14016 (if exit-after-next (setq exit-after-next 'now)))
14017 ((= c ?\t)
14018 (condition-case nil
14019 (setq tg (org-icompleting-read
14020 "Tag: "
14021 (or buffer-tags
14022 (with-current-buffer buf
14023 (org-get-buffer-tags)))))
14024 (quit (setq tg "")))
14025 (when (string-match "\\S-" tg)
14026 (add-to-list 'buffer-tags (list tg))
14027 (if (member tg current)
14028 (setq current (delete tg current))
14029 (push tg current)))
14030 (if exit-after-next (setq exit-after-next 'now)))
14031 ((setq e (rassoc c todo-table) tg (car e))
14032 (with-current-buffer buf
14033 (save-excursion (org-todo tg)))
14034 (if exit-after-next (setq exit-after-next 'now)))
14035 ((setq e (rassoc c ntable) tg (car e))
14036 (if (member tg current)
14037 (setq current (delete tg current))
14038 (loop for g in groups do
14039 (if (member tg g)
14040 (mapc (lambda (x)
14041 (setq current (delete x current)))
14042 g)))
14043 (push tg current))
14044 (if exit-after-next (setq exit-after-next 'now))))
14046 ;; Create a sorted list
14047 (setq current
14048 (sort current
14049 (lambda (a b)
14050 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14051 (if (eq exit-after-next 'now) (throw 'exit t))
14052 (goto-char (point-min))
14053 (beginning-of-line 2)
14054 (delete-region (point) (point-at-eol))
14055 (org-fast-tag-insert "Current" current c-face)
14056 (org-set-current-tags-overlay current ov-prefix)
14057 (while (re-search-forward
14058 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14059 (setq tg (match-string 1))
14060 (add-text-properties
14061 (match-beginning 1) (match-end 1)
14062 (list 'face
14063 (cond
14064 ((member tg current) c-face)
14065 ((member tg inherited) i-face)
14066 (t (get-text-property (match-beginning 1) 'face))))))
14067 (goto-char (point-min)))))
14068 (org-detach-overlay org-tags-overlay)
14069 (if rtn
14070 (mapconcat 'identity current ":")
14071 nil))))
14073 (defun org-get-tags-string ()
14074 "Get the TAGS string in the current headline."
14075 (unless (org-at-heading-p t)
14076 (error "Not on a heading"))
14077 (save-excursion
14078 (beginning-of-line 1)
14079 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14080 (org-match-string-no-properties 1)
14081 "")))
14083 (defun org-get-tags ()
14084 "Get the list of tags specified in the current headline."
14085 (org-split-string (org-get-tags-string) ":"))
14087 (defun org-get-buffer-tags ()
14088 "Get a table of all tags used in the buffer, for completion."
14089 (let (tags)
14090 (save-excursion
14091 (goto-char (point-min))
14092 (while (re-search-forward
14093 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14094 (when (equal (char-after (point-at-bol 0)) ?*)
14095 (mapc (lambda (x) (add-to-list 'tags x))
14096 (org-split-string (org-match-string-no-properties 1) ":")))))
14097 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14098 (mapcar 'list tags)))
14100 ;;;; The mapping API
14102 (defun org-map-entries (func &optional match scope &rest skip)
14103 "Call FUNC at each headline selected by MATCH in SCOPE.
14105 FUNC is a function or a lisp form. The function will be called without
14106 arguments, with the cursor positioned at the beginning of the headline.
14107 The return values of all calls to the function will be collected and
14108 returned as a list.
14110 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14111 does not need to preserve point. After evaluation, the cursor will be
14112 moved to the end of the line (presumably of the headline of the
14113 processed entry) and search continues from there. Under some
14114 circumstances, this may not produce the wanted results. For example,
14115 if you have removed (e.g. archived) the current (sub)tree it could
14116 mean that the next entry will be skipped entirely. In such cases, you
14117 can specify the position from where search should continue by making
14118 FUNC set the variable `org-map-continue-from' to the desired buffer
14119 position.
14121 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14122 Only headlines that are matched by this query will be considered during
14123 the iteration. When MATCH is nil or t, all headlines will be
14124 visited by the iteration.
14126 SCOPE determines the scope of this command. It can be any of:
14128 nil The current buffer, respecting the restriction if any
14129 tree The subtree started with the entry at point
14130 region The entries within the active region, if any
14131 region-start-level
14132 The entries within the active region, but only those at
14133 the same level than the first one.
14134 file The current buffer, without restriction
14135 file-with-archives
14136 The current buffer, and any archives associated with it
14137 agenda All agenda files
14138 agenda-with-archives
14139 All agenda files with any archive files associated with them
14140 \(file1 file2 ...)
14141 If this is a list, all files in the list will be scanned
14143 The remaining args are treated as settings for the skipping facilities of
14144 the scanner. The following items can be given here:
14146 archive skip trees with the archive tag.
14147 comment skip trees with the COMMENT keyword
14148 function or Emacs Lisp form:
14149 will be used as value for `org-agenda-skip-function', so whenever
14150 the function returns t, FUNC will not be called for that
14151 entry and search will continue from the point where the
14152 function leaves it.
14154 If your function needs to retrieve the tags including inherited tags
14155 at the *current* entry, you can use the value of the variable
14156 `org-scanner-tags' which will be much faster than getting the value
14157 with `org-get-tags-at'. If your function gets properties with
14158 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14159 to t around the call to `org-entry-properties' to get the same speedup.
14160 Note that if your function moves around to retrieve tags and properties at
14161 a *different* entry, you cannot use these techniques."
14162 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14163 (not (org-region-active-p)))
14164 (let* ((org-agenda-archives-mode nil) ; just to make sure
14165 (org-agenda-skip-archived-trees (memq 'archive skip))
14166 (org-agenda-skip-comment-trees (memq 'comment skip))
14167 (org-agenda-skip-function
14168 (car (org-delete-all '(comment archive) skip)))
14169 (org-tags-match-list-sublevels t)
14170 (start-level (eq scope 'region-start-level))
14171 matcher file res
14172 org-todo-keywords-for-agenda
14173 org-done-keywords-for-agenda
14174 org-todo-keyword-alist-for-agenda
14175 org-drawers-for-agenda
14176 org-tag-alist-for-agenda
14177 todo-only)
14179 (cond
14180 ((eq match t) (setq matcher t))
14181 ((eq match nil) (setq matcher t))
14182 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14184 (save-excursion
14185 (save-restriction
14186 (cond ((eq scope 'tree)
14187 (org-back-to-heading t)
14188 (org-narrow-to-subtree)
14189 (setq scope nil))
14190 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14191 (org-region-active-p))
14192 ;; If needed, set start-level to a string like "2"
14193 (when start-level
14194 (save-excursion
14195 (goto-char (region-beginning))
14196 (unless (org-at-heading-p) (outline-next-heading))
14197 (setq start-level (org-current-level))))
14198 (narrow-to-region (region-beginning)
14199 (save-excursion
14200 (goto-char (region-end))
14201 (unless (and (bolp) (org-at-heading-p))
14202 (outline-next-heading))
14203 (point)))
14204 (setq scope nil)))
14206 (if (not scope)
14207 (progn
14208 (org-agenda-prepare-buffers
14209 (list (buffer-file-name (current-buffer))))
14210 (setq res (org-scan-tags func matcher todo-only start-level)))
14211 ;; Get the right scope
14212 (cond
14213 ((and scope (listp scope) (symbolp (car scope)))
14214 (setq scope (eval scope)))
14215 ((eq scope 'agenda)
14216 (setq scope (org-agenda-files t)))
14217 ((eq scope 'agenda-with-archives)
14218 (setq scope (org-agenda-files t))
14219 (setq scope (org-add-archive-files scope)))
14220 ((eq scope 'file)
14221 (setq scope (list (buffer-file-name))))
14222 ((eq scope 'file-with-archives)
14223 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14224 (org-agenda-prepare-buffers scope)
14225 (while (setq file (pop scope))
14226 (with-current-buffer (org-find-base-buffer-visiting file)
14227 (save-excursion
14228 (save-restriction
14229 (widen)
14230 (goto-char (point-min))
14231 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14232 res)))
14234 ;;;; Properties
14236 ;;; Setting and retrieving properties
14238 (defconst org-special-properties
14239 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14240 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14241 "The special properties valid in Org-mode.
14243 These are properties that are not defined in the property drawer,
14244 but in some other way.")
14246 (defconst org-default-properties
14247 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14248 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14249 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14250 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14251 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14252 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14253 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14254 "Some properties that are used by Org-mode for various purposes.
14255 Being in this list makes sure that they are offered for completion.")
14257 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14258 "Regular expression matching the first line of a property drawer.")
14260 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14261 "Regular expression matching the last line of a property drawer.")
14263 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14264 "Regular expression matching the first line of a property drawer.")
14266 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14267 "Regular expression matching the first line of a property drawer.")
14269 (defconst org-property-drawer-re
14270 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14271 org-property-end-re "\\)\n?")
14272 "Matches an entire property drawer.")
14274 (defconst org-clock-drawer-re
14275 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14276 org-property-end-re "\\)\n?")
14277 "Matches an entire clock drawer.")
14279 (defsubst org-re-property (property)
14280 "Return a regexp matching a PROPERTY line.
14281 Match group 1 will be set to the value."
14282 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14284 (defsubst org-re-property-keyword (property)
14285 "Return a regexp matching a PROPERTY line, possibly with no
14286 value for the property."
14287 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14289 (defun org-property-action ()
14290 "Do an action on properties."
14291 (interactive)
14292 (let (c)
14293 (org-at-property-p)
14294 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14295 (setq c (read-char-exclusive))
14296 (cond
14297 ((equal c ?s)
14298 (call-interactively 'org-set-property))
14299 ((equal c ?d)
14300 (call-interactively 'org-delete-property))
14301 ((equal c ?D)
14302 (call-interactively 'org-delete-property-globally))
14303 ((equal c ?c)
14304 (call-interactively 'org-compute-property-at-point))
14305 (t (error "No such property action %c" c)))))
14307 (defun org-inc-effort ()
14308 "Increment the value of the effort property in the current entry."
14309 (interactive)
14310 (org-set-effort nil t))
14312 (defun org-set-effort (&optional value increment)
14313 "Set the effort property of the current entry.
14314 With numerical prefix arg, use the nth allowed value, 0 stands for the
14315 10th allowed value.
14317 When INCREMENT is non-nil, set the property to the next allowed value."
14318 (interactive "P")
14319 (if (equal value 0) (setq value 10))
14320 (let* ((completion-ignore-case t)
14321 (prop org-effort-property)
14322 (cur (org-entry-get nil prop))
14323 (allowed (org-property-get-allowed-values nil prop 'table))
14324 (existing (mapcar 'list (org-property-values prop)))
14326 (val (cond
14327 ((stringp value) value)
14328 ((and allowed (integerp value))
14329 (or (car (nth (1- value) allowed))
14330 (car (org-last allowed))))
14331 ((and allowed increment)
14332 (or (caadr (member (list cur) allowed))
14333 (error "Allowed effort values are not set")))
14334 (allowed
14335 (message "Select 1-9,0, [RET%s]: %s"
14336 (if cur (concat "=" cur) "")
14337 (mapconcat 'car allowed " "))
14338 (setq rpl (read-char-exclusive))
14339 (if (equal rpl ?\r)
14341 (setq rpl (- rpl ?0))
14342 (if (equal rpl 0) (setq rpl 10))
14343 (if (and (> rpl 0) (<= rpl (length allowed)))
14344 (car (nth (1- rpl) allowed))
14345 (org-completing-read "Effort: " allowed nil))))
14347 (let (org-completion-use-ido org-completion-use-iswitchb)
14348 (org-completing-read
14349 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14350 (concat "[" cur "]") "")
14351 ": ")
14352 existing nil nil "" nil cur))))))
14353 (unless (equal (org-entry-get nil prop) val)
14354 (org-entry-put nil prop val))
14355 (message "%s is now %s" prop val)))
14357 (defun org-at-property-p ()
14358 "Is cursor inside a property drawer?"
14359 (save-excursion
14360 (beginning-of-line 1)
14361 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14362 (save-match-data ;; Used by calling procedures
14363 (let ((p (point))
14364 (range (unless (org-before-first-heading-p)
14365 (org-get-property-block))))
14366 (and range (<= (car range) p) (< p (cdr range))))))))
14368 (defun org-get-property-block (&optional beg end force)
14369 "Return the (beg . end) range of the body of the property drawer.
14370 BEG and END are the beginning and end of the current subtree, or of
14371 the part before the first headline. If they are not given, they will
14372 be found. If the drawer does not exist and FORCE is non-nil, create
14373 the drawer."
14374 (catch 'exit
14375 (save-excursion
14376 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14377 (progn (org-back-to-heading t) (point))))
14378 (end (or end (and (not (outline-next-heading)) (point-max))
14379 (point))))
14380 (goto-char beg)
14381 (if (re-search-forward org-property-start-re end t)
14382 (setq beg (1+ (match-end 0)))
14383 (if force
14384 (save-excursion
14385 (org-insert-property-drawer)
14386 (setq end (progn (outline-next-heading) (point))))
14387 (throw 'exit nil))
14388 (goto-char beg)
14389 (if (re-search-forward org-property-start-re end t)
14390 (setq beg (1+ (match-end 0)))))
14391 (if (re-search-forward org-property-end-re end t)
14392 (setq end (match-beginning 0))
14393 (or force (throw 'exit nil))
14394 (goto-char beg)
14395 (setq end beg)
14396 (org-indent-line)
14397 (insert ":END:\n"))
14398 (cons beg end)))))
14400 (defun org-entry-properties (&optional pom which specific)
14401 "Get all properties of the entry at point-or-marker POM.
14402 This includes the TODO keyword, the tags, time strings for deadline,
14403 scheduled, and clocking, and any additional properties defined in the
14404 entry. The return value is an alist, keys may occur multiple times
14405 if the property key was used several times.
14406 POM may also be nil, in which case the current entry is used.
14407 If WHICH is nil or `all', get all properties. If WHICH is
14408 `special' or `standard', only get that subclass. If WHICH
14409 is a string only get exactly this property. SPECIFIC can be a string, the
14410 specific property we are interested in. Specifying it can speed
14411 things up because then unnecessary parsing is avoided."
14412 (setq which (or which 'all))
14413 (org-with-point-at pom
14414 (let ((clockstr (substring org-clock-string 0 -1))
14415 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14416 (case-fold-search nil)
14417 beg end range props sum-props key key1 value string clocksum clocksumt)
14418 (save-excursion
14419 (when (condition-case nil
14420 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14421 (error nil))
14422 (setq beg (point))
14423 (setq sum-props (get-text-property (point) 'org-summaries))
14424 (setq clocksum (get-text-property (point) :org-clock-minutes)
14425 clocksumt (get-text-property (point) :org-clock-minutes-today))
14426 (outline-next-heading)
14427 (setq end (point))
14428 (when (memq which '(all special))
14429 ;; Get the special properties, like TODO and tags
14430 (goto-char beg)
14431 (when (and (or (not specific) (string= specific "TODO"))
14432 (looking-at org-todo-line-regexp) (match-end 2))
14433 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14434 (when (and (or (not specific) (string= specific "PRIORITY"))
14435 (looking-at org-priority-regexp))
14436 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14437 (when (or (not specific) (string= specific "FILE"))
14438 (push (cons "FILE" buffer-file-name) props))
14439 (when (and (or (not specific) (string= specific "TAGS"))
14440 (setq value (org-get-tags-string))
14441 (string-match "\\S-" value))
14442 (push (cons "TAGS" value) props))
14443 (when (and (or (not specific) (string= specific "ALLTAGS"))
14444 (setq value (org-get-tags-at)))
14445 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14446 ":"))
14447 props))
14448 (when (or (not specific) (string= specific "BLOCKED"))
14449 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14450 (when (or (not specific)
14451 (member specific
14452 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14453 "TIMESTAMP" "TIMESTAMP_IA")))
14454 (catch 'match
14455 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14456 (setq key (if (match-end 1)
14457 (substring (org-match-string-no-properties 1)
14458 0 -1))
14459 string (if (equal key clockstr)
14460 (org-trim
14461 (buffer-substring-no-properties
14462 (match-beginning 3) (goto-char
14463 (point-at-eol))))
14464 (substring (org-match-string-no-properties 3)
14465 1 -1)))
14466 ;; Get the correct property name from the key. This is
14467 ;; necessary if the user has configured time keywords.
14468 (setq key1 (concat key ":"))
14469 (cond
14470 ((not key)
14471 (setq key
14472 (if (= (char-after (match-beginning 3)) ?\[)
14473 "TIMESTAMP_IA" "TIMESTAMP")))
14474 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14475 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14476 ((equal key1 org-closed-string) (setq key "CLOSED"))
14477 ((equal key1 org-clock-string) (setq key "CLOCK")))
14478 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14479 (progn
14480 (push (cons key string) props)
14481 ;; no need to search further if match is found
14482 (throw 'match t))
14483 (when (or (equal key "CLOCK") (not (assoc key props)))
14484 (push (cons key string) props)))))))
14486 (when (memq which '(all standard))
14487 ;; Get the standard properties, like :PROP: ...
14488 (setq range (org-get-property-block beg end))
14489 (when range
14490 (goto-char (car range))
14491 (while (re-search-forward
14492 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14493 (cdr range) t)
14494 (setq key (org-match-string-no-properties 1)
14495 value (org-trim (or (org-match-string-no-properties 2) "")))
14496 (unless (member key excluded)
14497 (push (cons key (or value "")) props)))))
14498 (if clocksum
14499 (push (cons "CLOCKSUM"
14500 (org-columns-number-to-string (/ (float clocksum) 60.)
14501 'add_times))
14502 props))
14503 (if clocksumt
14504 (push (cons "CLOCKSUM_T"
14505 (org-columns-number-to-string (/ (float clocksumt) 60.)
14506 'add_times))
14507 props))
14508 (unless (assoc "CATEGORY" props)
14509 (push (cons "CATEGORY" (org-get-category)) props))
14510 (append sum-props (nreverse props)))))))
14512 (defun org-entry-get (pom property &optional inherit literal-nil)
14513 "Get value of PROPERTY for entry or content at point-or-marker POM.
14514 If INHERIT is non-nil and the entry does not have the property,
14515 then also check higher levels of the hierarchy.
14516 If INHERIT is the symbol `selective', use inheritance only if the setting
14517 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14518 If the property is present but empty, the return value is the empty string.
14519 If the property is not present at all, nil is returned.
14521 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14522 do not interpret it as the list atom nil. This is used for inheritance
14523 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14524 (org-with-point-at pom
14525 (if (and inherit (if (eq inherit 'selective)
14526 (org-property-inherit-p property)
14528 (org-entry-get-with-inheritance property literal-nil)
14529 (if (member property org-special-properties)
14530 ;; We need a special property. Use `org-entry-properties' to
14531 ;; retrieve it, but specify the wanted property
14532 (cdr (assoc property (org-entry-properties nil 'special property)))
14533 (let* ((range (org-get-property-block))
14534 (props (list (or (assoc property org-file-properties)
14535 (assoc property org-global-properties)
14536 (assoc property org-global-properties-fixed))))
14537 (ap (lambda (key)
14538 (when (re-search-forward
14539 (org-re-property key) (cdr range) t)
14540 (setq props
14541 (org-update-property-plist
14543 (if (match-end 1)
14544 (org-match-string-no-properties 1) "")
14545 props)))))
14546 val)
14547 (when (and range (goto-char (car range)))
14548 (funcall ap property)
14549 (goto-char (car range))
14550 (while (funcall ap (concat property "+")))
14551 (setq val (cdr (assoc property props)))
14552 (when val (if literal-nil val (org-not-nil val)))))))))
14554 (defun org-property-or-variable-value (var &optional inherit)
14555 "Check if there is a property fixing the value of VAR.
14556 If yes, return this value. If not, return the current value of the variable."
14557 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14558 (if (and prop (stringp prop) (string-match "\\S-" prop))
14559 (read prop)
14560 (symbol-value var))))
14562 (defun org-entry-delete (pom property)
14563 "Delete the property PROPERTY from entry at point-or-marker POM."
14564 (org-with-point-at pom
14565 (if (member property org-special-properties)
14566 nil ; cannot delete these properties.
14567 (let ((range (org-get-property-block)))
14568 (if (and range
14569 (goto-char (car range))
14570 (re-search-forward
14571 (org-re-property property)
14572 (cdr range) t))
14573 (progn
14574 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14576 nil)))))
14578 ;; Multi-values properties are properties that contain multiple values
14579 ;; These values are assumed to be single words, separated by whitespace.
14580 (defun org-entry-add-to-multivalued-property (pom property value)
14581 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14582 (let* ((old (org-entry-get pom property))
14583 (values (and old (org-split-string old "[ \t]"))))
14584 (setq value (org-entry-protect-space value))
14585 (unless (member value values)
14586 (setq values (cons value values))
14587 (org-entry-put pom property
14588 (mapconcat 'identity values " ")))))
14590 (defun org-entry-remove-from-multivalued-property (pom property value)
14591 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14592 (let* ((old (org-entry-get pom property))
14593 (values (and old (org-split-string old "[ \t]"))))
14594 (setq value (org-entry-protect-space value))
14595 (when (member value values)
14596 (setq values (delete value values))
14597 (org-entry-put pom property
14598 (mapconcat 'identity values " ")))))
14600 (defun org-entry-member-in-multivalued-property (pom property value)
14601 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14602 (let* ((old (org-entry-get pom property))
14603 (values (and old (org-split-string old "[ \t]"))))
14604 (setq value (org-entry-protect-space value))
14605 (member value values)))
14607 (defun org-entry-get-multivalued-property (pom property)
14608 "Return a list of values in a multivalued property."
14609 (let* ((value (org-entry-get pom property))
14610 (values (and value (org-split-string value "[ \t]"))))
14611 (mapcar 'org-entry-restore-space values)))
14613 (defun org-entry-put-multivalued-property (pom property &rest values)
14614 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14615 VALUES should be a list of strings. Spaces will be protected."
14616 (org-entry-put pom property
14617 (mapconcat 'org-entry-protect-space values " "))
14618 (let* ((value (org-entry-get pom property))
14619 (values (and value (org-split-string value "[ \t]"))))
14620 (mapcar 'org-entry-restore-space values)))
14622 (defun org-entry-protect-space (s)
14623 "Protect spaces and newline in string S."
14624 (while (string-match " " s)
14625 (setq s (replace-match "%20" t t s)))
14626 (while (string-match "\n" s)
14627 (setq s (replace-match "%0A" t t s)))
14630 (defun org-entry-restore-space (s)
14631 "Restore spaces and newline in string S."
14632 (while (string-match "%20" s)
14633 (setq s (replace-match " " t t s)))
14634 (while (string-match "%0A" s)
14635 (setq s (replace-match "\n" t t s)))
14638 (defvar org-entry-property-inherited-from (make-marker)
14639 "Marker pointing to the entry from where a property was inherited.
14640 Each call to `org-entry-get-with-inheritance' will set this marker to the
14641 location of the entry where the inheritance search matched. If there was
14642 no match, the marker will point nowhere.
14643 Note that also `org-entry-get' calls this function, if the INHERIT flag
14644 is set.")
14646 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14647 "Get PROPERTY of entry or content at point, search higher levels if needed.
14648 The search will stop at the first ancestor which has the property defined.
14649 If the value found is \"nil\", return nil to show that the property
14650 should be considered as undefined (this is the meaning of nil here).
14651 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14652 (move-marker org-entry-property-inherited-from nil)
14653 (let (tmp)
14654 (save-excursion
14655 (save-restriction
14656 (widen)
14657 (catch 'ex
14658 (while t
14659 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14660 (or (ignore-errors (org-back-to-heading t))
14661 (goto-char (point-min)))
14662 (move-marker org-entry-property-inherited-from (point))
14663 (throw 'ex tmp))
14664 (or (ignore-errors (org-up-heading-safe))
14665 (throw 'ex nil))))))
14666 (setq tmp (or tmp
14667 (cdr (assoc property org-file-properties))
14668 (cdr (assoc property org-global-properties))
14669 (cdr (assoc property org-global-properties-fixed))))
14670 (if literal-nil tmp (org-not-nil tmp))))
14672 (defvar org-property-changed-functions nil
14673 "Hook called when the value of a property has changed.
14674 Each hook function should accept two arguments, the name of the property
14675 and the new value.")
14677 (defun org-entry-put (pom property value)
14678 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14679 (org-with-point-at pom
14680 (org-back-to-heading t)
14681 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14682 range)
14683 (cond
14684 ((equal property "TODO")
14685 (when (and (stringp value) (string-match "\\S-" value)
14686 (not (member value org-todo-keywords-1)))
14687 (error "\"%s\" is not a valid TODO state" value))
14688 (if (or (not value)
14689 (not (string-match "\\S-" value)))
14690 (setq value 'none))
14691 (org-todo value)
14692 (org-set-tags nil 'align))
14693 ((equal property "PRIORITY")
14694 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14695 (string-to-char value) ?\ ))
14696 (org-set-tags nil 'align))
14697 ((equal property "CLOCKSUM")
14698 (if (not (re-search-forward
14699 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
14700 (error "Cannot find a clock log")
14701 (goto-char (- (match-end 1) 2))
14702 (cond
14703 ((eq value 'earlier) (org-timestamp-down))
14704 ((eq value 'later) (org-timestamp-up)))
14705 (org-clock-sum-current-item)))
14706 ((equal property "SCHEDULED")
14707 (if (re-search-forward org-scheduled-time-regexp end t)
14708 (cond
14709 ((eq value 'earlier) (org-timestamp-change -1 'day))
14710 ((eq value 'later) (org-timestamp-change 1 'day))
14711 (t (call-interactively 'org-schedule)))
14712 (call-interactively 'org-schedule)))
14713 ((equal property "DEADLINE")
14714 (if (re-search-forward org-deadline-time-regexp end t)
14715 (cond
14716 ((eq value 'earlier) (org-timestamp-change -1 'day))
14717 ((eq value 'later) (org-timestamp-change 1 'day))
14718 (t (call-interactively 'org-deadline)))
14719 (call-interactively 'org-deadline)))
14720 ((member property org-special-properties)
14721 (error "The %s property can not yet be set with `org-entry-put'"
14722 property))
14723 (t ; a non-special property
14724 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14725 (setq range (org-get-property-block beg end 'force))
14726 (goto-char (car range))
14727 (if (re-search-forward
14728 (org-re-property-keyword property) (cdr range) t)
14729 (progn
14730 (delete-region (match-beginning 0) (match-end 0))
14731 (goto-char (match-beginning 0)))
14732 (goto-char (cdr range))
14733 (insert "\n")
14734 (backward-char 1)
14735 (org-indent-line))
14736 (insert ":" property ":")
14737 (and value (insert " " value))
14738 (org-indent-line)))))
14739 (run-hook-with-args 'org-property-changed-functions property value)))
14741 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14742 "Get all property keys in the current buffer.
14743 With INCLUDE-SPECIALS, also list the special properties that reflect things
14744 like tags and TODO state.
14745 With INCLUDE-DEFAULTS, also include properties that has special meaning
14746 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14747 and others.
14748 With INCLUDE-COLUMNS, also include property names given in COLUMN
14749 formats in the current buffer."
14750 (let (rtn range cfmt s p)
14751 (save-excursion
14752 (save-restriction
14753 (widen)
14754 (goto-char (point-min))
14755 (while (re-search-forward org-property-start-re nil t)
14756 (setq range (org-get-property-block))
14757 (goto-char (car range))
14758 (while (re-search-forward
14759 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14760 (cdr range) t)
14761 (add-to-list 'rtn (org-match-string-no-properties 1)))
14762 (outline-next-heading))))
14764 (when include-specials
14765 (setq rtn (append org-special-properties rtn)))
14767 (when include-defaults
14768 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14769 (add-to-list 'rtn org-effort-property))
14771 (when include-columns
14772 (save-excursion
14773 (save-restriction
14774 (widen)
14775 (goto-char (point-min))
14776 (while (re-search-forward
14777 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14778 nil t)
14779 (setq cfmt (match-string 2) s 0)
14780 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14781 cfmt s)
14782 (setq s (match-end 0)
14783 p (match-string 1 cfmt))
14784 (unless (or (equal p "ITEM")
14785 (member p org-special-properties))
14786 (add-to-list 'rtn (match-string 1 cfmt))))))))
14788 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14790 (defun org-property-values (key)
14791 "Return a list of all values of property KEY in the current buffer."
14792 (save-excursion
14793 (save-restriction
14794 (widen)
14795 (goto-char (point-min))
14796 (let ((re (org-re-property key))
14797 values)
14798 (while (re-search-forward re nil t)
14799 (add-to-list 'values (org-trim (match-string 1))))
14800 (delete "" values)))))
14802 (defun org-insert-property-drawer ()
14803 "Insert a property drawer into the current entry."
14804 (org-back-to-heading t)
14805 (looking-at org-outline-regexp)
14806 (let ((indent (if org-adapt-indentation
14807 (- (match-end 0) (match-beginning 0))
14809 (beg (point))
14810 (re (concat "^[ \t]*" org-keyword-time-regexp))
14811 end hiddenp)
14812 (outline-next-heading)
14813 (setq end (point))
14814 (goto-char beg)
14815 (while (re-search-forward re end t))
14816 (setq hiddenp (outline-invisible-p))
14817 (end-of-line 1)
14818 (and (equal (char-after) ?\n) (forward-char 1))
14819 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14820 (if (member (match-string 1) '("CLOCK:" ":END:"))
14821 ;; just skip this line
14822 (beginning-of-line 2)
14823 ;; Drawer start, find the end
14824 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14825 (beginning-of-line 1)))
14826 (org-skip-over-state-notes)
14827 (skip-chars-backward " \t\n\r")
14828 (if (eq (char-before) ?*) (forward-char 1))
14829 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14830 (beginning-of-line 0)
14831 (org-indent-to-column indent)
14832 (beginning-of-line 2)
14833 (org-indent-to-column indent)
14834 (beginning-of-line 0)
14835 (if hiddenp
14836 (save-excursion
14837 (org-back-to-heading t)
14838 (hide-entry))
14839 (org-flag-drawer t))))
14841 (defun org-insert-drawer (&optional arg drawer)
14842 "Insert a drawer at point.
14844 Optional argument DRAWER, when non-nil, is a string representing
14845 drawer's name. Otherwise, the user is prompted for a name.
14847 If a region is active, insert the drawer around that region
14848 instead.
14850 Point is left between drawer's boundaries."
14851 (interactive "P")
14852 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14853 "LOGBOOK"))
14854 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14855 ;; internally by Org. They are meant to be inserted
14856 ;; automatically.
14857 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14858 ;; Remove system drawers from list. Note: For some reason,
14859 ;; `org-completing-read' ignores the predicate while
14860 ;; `completing-read' handles it fine.
14861 (drawer (if arg "PROPERTIES"
14862 (or drawer
14863 (completing-read
14864 "Drawer: " org-drawers
14865 (lambda (d) (not (member d system-drawers))))))))
14866 (cond
14867 ;; With C-u, fall back on `org-insert-property-drawer'
14868 (arg (org-insert-property-drawer))
14869 ;; With an active region, insert a drawer at point.
14870 ((not (org-region-active-p))
14871 (progn
14872 (unless (bolp) (insert "\n"))
14873 (insert (format ":%s:\n\n:END:\n" drawer))
14874 (forward-line -2)))
14875 ;; Otherwise, insert the drawer at point
14877 (let ((rbeg (region-beginning))
14878 (rend (copy-marker (region-end))))
14879 (unwind-protect
14880 (progn
14881 (goto-char rbeg)
14882 (beginning-of-line)
14883 (when (save-excursion
14884 (re-search-forward org-outline-regexp-bol rend t))
14885 (error "Drawers cannot contain headlines"))
14886 ;; Position point at the beginning of the first
14887 ;; non-blank line in region. Insert drawer's opening
14888 ;; there, then indent it.
14889 (org-skip-whitespace)
14890 (beginning-of-line)
14891 (insert ":" drawer ":\n")
14892 (forward-line -1)
14893 (indent-for-tab-command)
14894 ;; Move point to the beginning of the first blank line
14895 ;; after the last non-blank line in region. Insert
14896 ;; drawer's closing, then indent it.
14897 (goto-char rend)
14898 (skip-chars-backward " \r\t\n")
14899 (insert "\n:END:")
14900 (deactivate-mark t)
14901 (indent-for-tab-command)
14902 (unless (eolp) (insert "\n")))
14903 ;; Clear marker, whatever the outcome of insertion is.
14904 (set-marker rend nil)))))))
14906 (defvar org-property-set-functions-alist nil
14907 "Property set function alist.
14908 Each entry should have the following format:
14910 (PROPERTY . READ-FUNCTION)
14912 The read function will be called with the same argument as
14913 `org-completing-read'.")
14915 (defun org-set-property-function (property)
14916 "Get the function that should be used to set PROPERTY.
14917 This is computed according to `org-property-set-functions-alist'."
14918 (or (cdr (assoc property org-property-set-functions-alist))
14919 'org-completing-read))
14921 (defun org-read-property-value (property)
14922 "Read PROPERTY value from user."
14923 (let* ((completion-ignore-case t)
14924 (allowed (org-property-get-allowed-values nil property 'table))
14925 (cur (org-entry-get nil property))
14926 (prompt (concat property " value"
14927 (if (and cur (string-match "\\S-" cur))
14928 (concat " [" cur "]") "") ": "))
14929 (set-function (org-set-property-function property))
14930 (val (if allowed
14931 (funcall set-function prompt allowed nil
14932 (not (get-text-property 0 'org-unrestricted
14933 (caar allowed))))
14934 (let (org-completion-use-ido org-completion-use-iswitchb)
14935 (funcall set-function prompt
14936 (mapcar 'list (org-property-values property))
14937 nil nil "" nil cur)))))
14938 (if (equal val "")
14940 val)))
14942 (defvar org-last-set-property nil)
14943 (defun org-read-property-name ()
14944 "Read a property name."
14945 (let* ((completion-ignore-case t)
14946 (keys (org-buffer-property-keys nil t t))
14947 (default-prop (or (save-excursion
14948 (save-match-data
14949 (beginning-of-line)
14950 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14951 (null (string= (match-string 1) "END"))
14952 (match-string 1))))
14953 org-last-set-property))
14954 (property (org-icompleting-read
14955 (concat "Property"
14956 (if default-prop (concat " [" default-prop "]") "")
14957 ": ")
14958 (mapcar 'list keys)
14959 nil nil nil nil
14960 default-prop
14962 (if (member property keys)
14963 property
14964 (or (cdr (assoc (downcase property)
14965 (mapcar (lambda (x) (cons (downcase x) x))
14966 keys)))
14967 property))))
14969 (defun org-set-property (property value)
14970 "In the current entry, set PROPERTY to VALUE.
14971 When called interactively, this will prompt for a property name, offering
14972 completion on existing and default properties. And then it will prompt
14973 for a value, offering completion either on allowed values (via an inherited
14974 xxx_ALL property) or on existing values in other instances of this property
14975 in the current file."
14976 (interactive (list nil nil))
14977 (let* ((property (or property (org-read-property-name)))
14978 (value (or value (org-read-property-value property)))
14979 (fn (cdr (assoc property org-properties-postprocess-alist))))
14980 (setq org-last-set-property property)
14981 ;; Possibly postprocess the inserted value:
14982 (when fn (setq value (funcall fn value)))
14983 (unless (equal (org-entry-get nil property) value)
14984 (org-entry-put nil property value))))
14986 (defun org-delete-property (property)
14987 "In the current entry, delete PROPERTY."
14988 (interactive
14989 (let* ((completion-ignore-case t)
14990 (prop (org-icompleting-read "Property: "
14991 (org-entry-properties nil 'standard))))
14992 (list prop)))
14993 (message "Property %s %s" property
14994 (if (org-entry-delete nil property)
14995 "deleted"
14996 "was not present in the entry")))
14998 (defun org-delete-property-globally (property)
14999 "Remove PROPERTY globally, from all entries."
15000 (interactive
15001 (let* ((completion-ignore-case t)
15002 (prop (org-icompleting-read
15003 "Globally remove property: "
15004 (mapcar 'list (org-buffer-property-keys)))))
15005 (list prop)))
15006 (save-excursion
15007 (save-restriction
15008 (widen)
15009 (goto-char (point-min))
15010 (let ((cnt 0))
15011 (while (re-search-forward
15012 (org-re-property property)
15013 nil t)
15014 (setq cnt (1+ cnt))
15015 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15016 (message "Property \"%s\" removed from %d entries" property cnt)))))
15018 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15020 (defun org-compute-property-at-point ()
15021 "Compute the property at point.
15022 This looks for an enclosing column format, extracts the operator and
15023 then applies it to the property in the column format's scope."
15024 (interactive)
15025 (unless (org-at-property-p)
15026 (error "Not at a property"))
15027 (let ((prop (org-match-string-no-properties 2)))
15028 (org-columns-get-format-and-top-level)
15029 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15030 (error "No operator defined for property %s" prop))
15031 (org-columns-compute prop)))
15033 (defvar org-property-allowed-value-functions nil
15034 "Hook for functions supplying allowed values for a specific property.
15035 The functions must take a single argument, the name of the property, and
15036 return a flat list of allowed values. If \":ETC\" is one of
15037 the values, this means that these values are intended as defaults for
15038 completion, but that other values should be allowed too.
15039 The functions must return nil if they are not responsible for this
15040 property.")
15042 (defun org-property-get-allowed-values (pom property &optional table)
15043 "Get allowed values for the property PROPERTY.
15044 When TABLE is non-nil, return an alist that can directly be used for
15045 completion."
15046 (let (vals)
15047 (cond
15048 ((equal property "TODO")
15049 (setq vals (org-with-point-at pom
15050 (append org-todo-keywords-1 '("")))))
15051 ((equal property "PRIORITY")
15052 (let ((n org-lowest-priority))
15053 (while (>= n org-highest-priority)
15054 (push (char-to-string n) vals)
15055 (setq n (1- n)))))
15056 ((member property org-special-properties))
15057 ((setq vals (run-hook-with-args-until-success
15058 'org-property-allowed-value-functions property)))
15060 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15061 (when (and vals (string-match "\\S-" vals))
15062 (setq vals (car (read-from-string (concat "(" vals ")"))))
15063 (setq vals (mapcar (lambda (x)
15064 (cond ((stringp x) x)
15065 ((numberp x) (number-to-string x))
15066 ((symbolp x) (symbol-name x))
15067 (t "???")))
15068 vals)))))
15069 (when (member ":ETC" vals)
15070 (setq vals (remove ":ETC" vals))
15071 (org-add-props (car vals) '(org-unrestricted t)))
15072 (if table (mapcar 'list vals) vals)))
15074 (defun org-property-previous-allowed-value (&optional previous)
15075 "Switch to the next allowed value for this property."
15076 (interactive)
15077 (org-property-next-allowed-value t))
15079 (defun org-property-next-allowed-value (&optional previous)
15080 "Switch to the next allowed value for this property."
15081 (interactive)
15082 (unless (org-at-property-p)
15083 (error "Not at a property"))
15084 (let* ((key (match-string 2))
15085 (value (match-string 3))
15086 (allowed (or (org-property-get-allowed-values (point) key)
15087 (and (member value '("[ ]" "[-]" "[X]"))
15088 '("[ ]" "[X]"))))
15089 nval)
15090 (unless allowed
15091 (error "Allowed values for this property have not been defined"))
15092 (if previous (setq allowed (reverse allowed)))
15093 (if (member value allowed)
15094 (setq nval (car (cdr (member value allowed)))))
15095 (setq nval (or nval (car allowed)))
15096 (if (equal nval value)
15097 (error "Only one allowed value for this property"))
15098 (org-at-property-p)
15099 (replace-match (concat " :" key ": " nval) t t)
15100 (org-indent-line)
15101 (beginning-of-line 1)
15102 (skip-chars-forward " \t")
15103 (run-hook-with-args 'org-property-changed-functions key nval)))
15105 (defun org-find-olp (path &optional this-buffer)
15106 "Return a marker pointing to the entry at outline path OLP.
15107 If anything goes wrong, throw an error.
15108 You can wrap this call to catch the error like this:
15110 (condition-case msg
15111 (org-mobile-locate-entry (match-string 4))
15112 (error (nth 1 msg)))
15114 The return value will then be either a string with the error message,
15115 or a marker if everything is OK.
15117 If THIS-BUFFER is set, the outline path does not contain a file,
15118 only headings."
15119 (let* ((file (if this-buffer buffer-file-name (pop path)))
15120 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15121 (level 1)
15122 (lmin 1)
15123 (lmax 1)
15124 limit re end found pos heading cnt flevel)
15125 (unless buffer (error "File not found :%s" file))
15126 (with-current-buffer buffer
15127 (save-excursion
15128 (save-restriction
15129 (widen)
15130 (setq limit (point-max))
15131 (goto-char (point-min))
15132 (while (setq heading (pop path))
15133 (setq re (format org-complex-heading-regexp-format
15134 (regexp-quote heading)))
15135 (setq cnt 0 pos (point))
15136 (while (re-search-forward re end t)
15137 (setq level (- (match-end 1) (match-beginning 1)))
15138 (if (and (>= level lmin) (<= level lmax))
15139 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15140 (when (= cnt 0) (error "Heading not found on level %d: %s"
15141 lmax heading))
15142 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15143 lmax heading))
15144 (goto-char found)
15145 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15146 (setq end (save-excursion (org-end-of-subtree t t))))
15147 (when (org-at-heading-p)
15148 (move-marker (make-marker) (point))))))))
15150 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15151 "Find node HEADING in BUFFER.
15152 Return a marker to the heading if it was found, or nil if not.
15153 If POS-ONLY is set, return just the position instead of a marker.
15155 The heading text must match exact, but it may have a TODO keyword,
15156 a priority cookie and tags in the standard locations."
15157 (with-current-buffer (or buffer (current-buffer))
15158 (save-excursion
15159 (save-restriction
15160 (widen)
15161 (goto-char (point-min))
15162 (let (case-fold-search)
15163 (if (re-search-forward
15164 (format org-complex-heading-regexp-format
15165 (regexp-quote heading)) nil t)
15166 (if pos-only
15167 (match-beginning 0)
15168 (move-marker (make-marker) (match-beginning 0)))))))))
15170 (defun org-find-exact-heading-in-directory (heading &optional dir)
15171 "Find Org node headline HEADING in all .org files in directory DIR.
15172 When the target headline is found, return a marker to this location."
15173 (let ((files (directory-files (or dir default-directory)
15174 nil "\\`[^.#].*\\.org\\'"))
15175 file visiting m buffer)
15176 (catch 'found
15177 (while (setq file (pop files))
15178 (message "trying %s" file)
15179 (setq visiting (org-find-base-buffer-visiting file))
15180 (setq buffer (or visiting (find-file-noselect file)))
15181 (setq m (org-find-exact-headline-in-buffer
15182 heading buffer))
15183 (when (and (not m) (not visiting)) (kill-buffer buffer))
15184 (and m (throw 'found m))))))
15186 (defun org-find-entry-with-id (ident)
15187 "Locate the entry that contains the ID property with exact value IDENT.
15188 IDENT can be a string, a symbol or a number, this function will search for
15189 the string representation of it.
15190 Return the position where this entry starts, or nil if there is no such entry."
15191 (interactive "sID: ")
15192 (let ((id (cond
15193 ((stringp ident) ident)
15194 ((symbol-name ident) (symbol-name ident))
15195 ((numberp ident) (number-to-string ident))
15196 (t (error "IDENT %s must be a string, symbol or number" ident))))
15197 (case-fold-search nil))
15198 (save-excursion
15199 (save-restriction
15200 (widen)
15201 (goto-char (point-min))
15202 (when (re-search-forward
15203 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15204 nil t)
15205 (org-back-to-heading t)
15206 (point))))))
15208 ;;;; Timestamps
15210 (defvar org-last-changed-timestamp nil)
15211 (defvar org-last-inserted-timestamp nil
15212 "The last time stamp inserted with `org-insert-time-stamp'.")
15213 (defvar org-time-was-given) ; dynamically scoped parameter
15214 (defvar org-end-time-was-given) ; dynamically scoped parameter
15215 (defvar org-ts-what) ; dynamically scoped parameter
15217 (defun org-time-stamp (arg &optional inactive)
15218 "Prompt for a date/time and insert a time stamp.
15219 If the user specifies a time like HH:MM or if this command is
15220 called with at least one prefix argument, the time stamp contains
15221 the date and the time. Otherwise, only the date is be included.
15223 All parts of a date not specified by the user is filled in from
15224 the current date/time. So if you just press return without
15225 typing anything, the time stamp will represent the current
15226 date/time.
15228 If there is already a timestamp at the cursor, it will be
15229 modified.
15231 With two universal prefix arguments, insert an active timestamp
15232 with the current time without prompting the user."
15233 (interactive "P")
15234 (let* ((ts nil)
15235 (default-time
15236 ;; Default time is either today, or, when entering a range,
15237 ;; the range start.
15238 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15239 (save-excursion
15240 (re-search-backward
15241 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15242 (- (point) 20) t)))
15243 (apply 'encode-time (org-parse-time-string (match-string 1)))
15244 (current-time)))
15245 (default-input (and ts (org-get-compact-tod ts)))
15246 (repeater (save-excursion
15247 (save-match-data
15248 (beginning-of-line)
15249 (when (re-search-forward
15250 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15251 (save-excursion (progn (end-of-line) (point))) t)
15252 (match-string 0)))))
15253 org-time-was-given org-end-time-was-given time)
15254 (cond
15255 ((and (org-at-timestamp-p t)
15256 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15257 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15258 (insert "--")
15259 (setq time (let ((this-command this-command))
15260 (org-read-date arg 'totime nil nil
15261 default-time default-input inactive)))
15262 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15263 ((org-at-timestamp-p t)
15264 (setq time (let ((this-command this-command))
15265 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15266 (when (org-at-timestamp-p t) ; just to get the match data
15267 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15268 (replace-match "")
15269 (setq org-last-changed-timestamp
15270 (org-insert-time-stamp
15271 time (or org-time-was-given arg)
15272 inactive nil nil (list org-end-time-was-given)))
15273 (when repeater (goto-char (1- (point))) (insert " " repeater)
15274 (setq org-last-changed-timestamp
15275 (concat (substring org-last-inserted-timestamp 0 -1)
15276 " " repeater ">"))))
15277 (message "Timestamp updated"))
15278 ((equal arg '(16))
15279 (org-insert-time-stamp (current-time) t))
15281 (setq time (let ((this-command this-command))
15282 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15283 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15284 nil nil (list org-end-time-was-given))))))
15286 ;; FIXME: can we use this for something else, like computing time differences?
15287 (defun org-get-compact-tod (s)
15288 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15289 (let* ((t1 (match-string 1 s))
15290 (h1 (string-to-number (match-string 2 s)))
15291 (m1 (string-to-number (match-string 3 s)))
15292 (t2 (and (match-end 4) (match-string 5 s)))
15293 (h2 (and t2 (string-to-number (match-string 6 s))))
15294 (m2 (and t2 (string-to-number (match-string 7 s))))
15295 dh dm)
15296 (if (not t2)
15298 (setq dh (- h2 h1) dm (- m2 m1))
15299 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15300 (concat t1 "+" (number-to-string dh)
15301 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15303 (defun org-time-stamp-inactive (&optional arg)
15304 "Insert an inactive time stamp.
15305 An inactive time stamp is enclosed in square brackets instead of angle
15306 brackets. It is inactive in the sense that it does not trigger agenda entries,
15307 does not link to the calendar and cannot be changed with the S-cursor keys.
15308 So these are more for recording a certain time/date."
15309 (interactive "P")
15310 (org-time-stamp arg 'inactive))
15312 (defvar org-date-ovl (make-overlay 1 1))
15313 (overlay-put org-date-ovl 'face 'org-date-selected)
15314 (org-detach-overlay org-date-ovl)
15316 (defvar org-ans1) ; dynamically scoped parameter
15317 (defvar org-ans2) ; dynamically scoped parameter
15319 (defvar org-plain-time-of-day-regexp) ; defined below
15321 (defvar org-overriding-default-time nil) ; dynamically scoped
15322 (defvar org-read-date-overlay nil)
15323 (defvar org-dcst nil) ; dynamically scoped
15324 (defvar org-read-date-history nil)
15325 (defvar org-read-date-final-answer nil)
15326 (defvar org-read-date-analyze-futurep nil)
15327 (defvar org-read-date-analyze-forced-year nil)
15328 (defvar org-read-date-inactive)
15330 (defun org-read-date (&optional org-with-time to-time from-string prompt
15331 default-time default-input inactive)
15332 "Read a date, possibly a time, and make things smooth for the user.
15333 The prompt will suggest to enter an ISO date, but you can also enter anything
15334 which will at least partially be understood by `parse-time-string'.
15335 Unrecognized parts of the date will default to the current day, month, year,
15336 hour and minute. If this command is called to replace a timestamp at point,
15337 or to enter the second timestamp of a range, the default time is taken
15338 from the existing stamp. Furthermore, the command prefers the future,
15339 so if you are giving a date where the year is not given, and the day-month
15340 combination is already past in the current year, it will assume you
15341 mean next year. For details, see the manual. A few examples:
15343 3-2-5 --> 2003-02-05
15344 feb 15 --> currentyear-02-15
15345 2/15 --> currentyear-02-15
15346 sep 12 9 --> 2009-09-12
15347 12:45 --> today 12:45
15348 22 sept 0:34 --> currentyear-09-22 0:34
15349 12 --> currentyear-currentmonth-12
15350 Fri --> nearest Friday (today or later)
15351 etc.
15353 Furthermore you can specify a relative date by giving, as the *first* thing
15354 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15355 change in days weeks, months, years.
15356 With a single plus or minus, the date is relative to today. With a double
15357 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15358 +4d --> four days from today
15359 +4 --> same as above
15360 +2w --> two weeks from today
15361 ++5 --> five days from default date
15363 The function understands only English month and weekday abbreviations.
15365 While prompting, a calendar is popped up - you can also select the
15366 date with the mouse (button 1). The calendar shows a period of three
15367 months. To scroll it to other months, use the keys `>' and `<'.
15368 If you don't like the calendar, turn it off with
15369 \(setq org-read-date-popup-calendar nil)
15371 With optional argument TO-TIME, the date will immediately be converted
15372 to an internal time.
15373 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15374 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15375 still enter a time, and this function will inform the calling routine
15376 about this change. The calling routine may then choose to change the
15377 format used to insert the time stamp into the buffer to include the time.
15378 With optional argument FROM-STRING, read from this string instead from
15379 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15380 the time/date that is used for everything that is not specified by the
15381 user."
15382 (require 'parse-time)
15383 (let* ((org-time-stamp-rounding-minutes
15384 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15385 (org-dcst org-display-custom-times)
15386 (ct (org-current-time))
15387 (org-def (or org-overriding-default-time default-time ct))
15388 (org-defdecode (decode-time org-def))
15389 (dummy (progn
15390 (when (< (nth 2 org-defdecode) org-extend-today-until)
15391 (setcar (nthcdr 2 org-defdecode) -1)
15392 (setcar (nthcdr 1 org-defdecode) 59)
15393 (setq org-def (apply 'encode-time org-defdecode)
15394 org-defdecode (decode-time org-def)))))
15395 (calendar-frame-setup nil)
15396 (calendar-setup nil)
15397 (calendar-move-hook nil)
15398 (calendar-view-diary-initially-flag nil)
15399 (calendar-view-holidays-initially-flag nil)
15400 (timestr (format-time-string
15401 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15402 (prompt (concat (if prompt (concat prompt " ") "")
15403 (format "Date+time [%s]: " timestr)))
15404 ans (org-ans0 "") org-ans1 org-ans2 final)
15406 (cond
15407 (from-string (setq ans from-string))
15408 (org-read-date-popup-calendar
15409 (save-excursion
15410 (save-window-excursion
15411 (calendar)
15412 (org-eval-in-calendar '(setq cursor-type nil) t)
15413 (unwind-protect
15414 (progn
15415 (calendar-forward-day (- (time-to-days org-def)
15416 (calendar-absolute-from-gregorian
15417 (calendar-current-date))))
15418 (org-eval-in-calendar nil t)
15419 (let* ((old-map (current-local-map))
15420 (map (copy-keymap calendar-mode-map))
15421 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15422 (org-defkey map (kbd "RET") 'org-calendar-select)
15423 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15424 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15425 (org-defkey minibuffer-local-map [(meta shift left)]
15426 (lambda () (interactive)
15427 (org-eval-in-calendar '(calendar-backward-month 1))))
15428 (org-defkey minibuffer-local-map [(meta shift right)]
15429 (lambda () (interactive)
15430 (org-eval-in-calendar '(calendar-forward-month 1))))
15431 (org-defkey minibuffer-local-map [(meta shift up)]
15432 (lambda () (interactive)
15433 (org-eval-in-calendar '(calendar-backward-year 1))))
15434 (org-defkey minibuffer-local-map [(meta shift down)]
15435 (lambda () (interactive)
15436 (org-eval-in-calendar '(calendar-forward-year 1))))
15437 (org-defkey minibuffer-local-map [?\e (shift left)]
15438 (lambda () (interactive)
15439 (org-eval-in-calendar '(calendar-backward-month 1))))
15440 (org-defkey minibuffer-local-map [?\e (shift right)]
15441 (lambda () (interactive)
15442 (org-eval-in-calendar '(calendar-forward-month 1))))
15443 (org-defkey minibuffer-local-map [?\e (shift up)]
15444 (lambda () (interactive)
15445 (org-eval-in-calendar '(calendar-backward-year 1))))
15446 (org-defkey minibuffer-local-map [?\e (shift down)]
15447 (lambda () (interactive)
15448 (org-eval-in-calendar '(calendar-forward-year 1))))
15449 (org-defkey minibuffer-local-map [(shift up)]
15450 (lambda () (interactive)
15451 (org-eval-in-calendar '(calendar-backward-week 1))))
15452 (org-defkey minibuffer-local-map [(shift down)]
15453 (lambda () (interactive)
15454 (org-eval-in-calendar '(calendar-forward-week 1))))
15455 (org-defkey minibuffer-local-map [(shift left)]
15456 (lambda () (interactive)
15457 (org-eval-in-calendar '(calendar-backward-day 1))))
15458 (org-defkey minibuffer-local-map [(shift right)]
15459 (lambda () (interactive)
15460 (org-eval-in-calendar '(calendar-forward-day 1))))
15461 (org-defkey minibuffer-local-map ">"
15462 (lambda () (interactive)
15463 (org-eval-in-calendar '(scroll-calendar-left 1))))
15464 (org-defkey minibuffer-local-map "<"
15465 (lambda () (interactive)
15466 (org-eval-in-calendar '(scroll-calendar-right 1))))
15467 (org-defkey minibuffer-local-map "\C-v"
15468 (lambda () (interactive)
15469 (org-eval-in-calendar
15470 '(calendar-scroll-left-three-months 1))))
15471 (org-defkey minibuffer-local-map "\M-v"
15472 (lambda () (interactive)
15473 (org-eval-in-calendar
15474 '(calendar-scroll-right-three-months 1))))
15475 (run-hooks 'org-read-date-minibuffer-setup-hook)
15476 (unwind-protect
15477 (progn
15478 (use-local-map map)
15479 (setq org-read-date-inactive inactive)
15480 (add-hook 'post-command-hook 'org-read-date-display)
15481 (setq org-ans0 (read-string prompt default-input
15482 'org-read-date-history nil))
15483 ;; org-ans0: from prompt
15484 ;; org-ans1: from mouse click
15485 ;; org-ans2: from calendar motion
15486 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15487 (remove-hook 'post-command-hook 'org-read-date-display)
15488 (use-local-map old-map)
15489 (when org-read-date-overlay
15490 (delete-overlay org-read-date-overlay)
15491 (setq org-read-date-overlay nil)))))
15492 (bury-buffer "*Calendar*")))))
15494 (t ; Naked prompt only
15495 (unwind-protect
15496 (setq ans (read-string prompt default-input
15497 'org-read-date-history timestr))
15498 (when org-read-date-overlay
15499 (delete-overlay org-read-date-overlay)
15500 (setq org-read-date-overlay nil)))))
15502 (setq final (org-read-date-analyze ans org-def org-defdecode))
15504 (when org-read-date-analyze-forced-year
15505 (message "Year was forced into %s"
15506 (if org-read-date-force-compatible-dates
15507 "compatible range (1970-2037)"
15508 "range representable on this machine"))
15509 (ding))
15511 ;; One round trip to get rid of 34th of August and stuff like that....
15512 (setq final (decode-time (apply 'encode-time final)))
15514 (setq org-read-date-final-answer ans)
15516 (if to-time
15517 (apply 'encode-time final)
15518 (if (and (boundp 'org-time-was-given) org-time-was-given)
15519 (format "%04d-%02d-%02d %02d:%02d"
15520 (nth 5 final) (nth 4 final) (nth 3 final)
15521 (nth 2 final) (nth 1 final))
15522 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15524 (defvar org-def)
15525 (defvar org-defdecode)
15526 (defvar org-with-time)
15527 (defun org-read-date-display ()
15528 "Display the current date prompt interpretation in the minibuffer."
15529 (when org-read-date-display-live
15530 (when org-read-date-overlay
15531 (delete-overlay org-read-date-overlay))
15532 (when (minibufferp (current-buffer))
15533 (save-excursion
15534 (end-of-line 1)
15535 (while (not (equal (buffer-substring
15536 (max (point-min) (- (point) 4)) (point))
15537 " "))
15538 (insert " ")))
15539 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15540 " " (or org-ans1 org-ans2)))
15541 (org-end-time-was-given nil)
15542 (f (org-read-date-analyze ans org-def org-defdecode))
15543 (fmts (if org-dcst
15544 org-time-stamp-custom-formats
15545 org-time-stamp-formats))
15546 (fmt (if (or org-with-time
15547 (and (boundp 'org-time-was-given) org-time-was-given))
15548 (cdr fmts)
15549 (car fmts)))
15550 (txt (format-time-string fmt (apply 'encode-time f)))
15551 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15552 (txt (concat "=> " txt)))
15553 (when (and org-end-time-was-given
15554 (string-match org-plain-time-of-day-regexp txt))
15555 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15556 org-end-time-was-given
15557 (substring txt (match-end 0)))))
15558 (when org-read-date-analyze-futurep
15559 (setq txt (concat txt " (=>F)")))
15560 (setq org-read-date-overlay
15561 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15562 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15564 (defun org-read-date-analyze (ans org-def org-defdecode)
15565 "Analyze the combined answer of the date prompt."
15566 ;; FIXME: cleanup and comment
15567 (let ((nowdecode (decode-time (current-time)))
15568 delta deltan deltaw deltadef year month day
15569 hour minute second wday pm h2 m2 tl wday1
15570 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15571 (setq org-read-date-analyze-futurep nil
15572 org-read-date-analyze-forced-year nil)
15573 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15574 (setq ans "+0"))
15576 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15577 (setq ans (replace-match "" t t ans)
15578 deltan (car delta)
15579 deltaw (nth 1 delta)
15580 deltadef (nth 2 delta)))
15582 ;; Check if there is an iso week date in there. If yes, store the
15583 ;; info and postpone interpreting it until the rest of the parsing
15584 ;; is done.
15585 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15586 (setq iso-year (if (match-end 1)
15587 (org-small-year-to-year
15588 (string-to-number (match-string 1 ans))))
15589 iso-weekday (if (match-end 3)
15590 (string-to-number (match-string 3 ans)))
15591 iso-week (string-to-number (match-string 2 ans)))
15592 (setq ans (replace-match "" t t ans)))
15594 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15595 (when (string-match
15596 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15597 (setq year (if (match-end 2)
15598 (string-to-number (match-string 2 ans))
15599 (progn (setq kill-year t)
15600 (string-to-number (format-time-string "%Y"))))
15601 month (string-to-number (match-string 3 ans))
15602 day (string-to-number (match-string 4 ans)))
15603 (if (< year 100) (setq year (+ 2000 year)))
15604 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15605 t nil ans)))
15607 ;; Help matching dotted european dates
15608 (when (string-match
15609 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
15610 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
15611 (setq kill-year t)
15612 (string-to-number (format-time-string "%Y")))
15613 day (string-to-number (match-string 1 ans))
15614 month (string-to-number (match-string 2 ans))
15615 ans (replace-match (format "%04d-%02d-%02d" year month day)
15616 t nil ans)))
15618 ;; Help matching american dates, like 5/30 or 5/30/7
15619 (when (string-match
15620 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15621 (setq year (if (match-end 4)
15622 (string-to-number (match-string 4 ans))
15623 (progn (setq kill-year t)
15624 (string-to-number (format-time-string "%Y"))))
15625 month (string-to-number (match-string 1 ans))
15626 day (string-to-number (match-string 2 ans)))
15627 (if (< year 100) (setq year (+ 2000 year)))
15628 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15629 t nil ans)))
15630 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15631 ;; If there is a time with am/pm, and *no* time without it, we convert
15632 ;; so that matching will be successful.
15633 (loop for i from 1 to 2 do ; twice, for end time as well
15634 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15635 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15636 (setq hour (string-to-number (match-string 1 ans))
15637 minute (if (match-end 3)
15638 (string-to-number (match-string 3 ans))
15640 pm (equal ?p
15641 (string-to-char (downcase (match-string 4 ans)))))
15642 (if (and (= hour 12) (not pm))
15643 (setq hour 0)
15644 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15645 (setq ans (replace-match (format "%02d:%02d" hour minute)
15646 t t ans))))
15648 ;; Check if a time range is given as a duration
15649 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15650 (setq hour (string-to-number (match-string 1 ans))
15651 h2 (+ hour (string-to-number (match-string 3 ans)))
15652 minute (string-to-number (match-string 2 ans))
15653 m2 (+ minute (if (match-end 5) (string-to-number
15654 (match-string 5 ans))0)))
15655 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15656 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15657 t t ans)))
15659 ;; Check if there is a time range
15660 (when (boundp 'org-end-time-was-given)
15661 (setq org-time-was-given nil)
15662 (when (and (string-match org-plain-time-of-day-regexp ans)
15663 (match-end 8))
15664 (setq org-end-time-was-given (match-string 8 ans))
15665 (setq ans (concat (substring ans 0 (match-beginning 7))
15666 (substring ans (match-end 7))))))
15668 (setq tl (parse-time-string ans)
15669 day (or (nth 3 tl) (nth 3 org-defdecode))
15670 month (or (nth 4 tl)
15671 (if (and org-read-date-prefer-future
15672 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15673 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15674 (nth 4 org-defdecode)))
15675 year (or (and (not kill-year) (nth 5 tl))
15676 (if (and org-read-date-prefer-future
15677 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15678 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15679 (nth 5 org-defdecode)))
15680 hour (or (nth 2 tl) (nth 2 org-defdecode))
15681 minute (or (nth 1 tl) (nth 1 org-defdecode))
15682 second (or (nth 0 tl) 0)
15683 wday (nth 6 tl))
15685 (when (and (eq org-read-date-prefer-future 'time)
15686 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15687 (equal day (nth 3 nowdecode))
15688 (equal month (nth 4 nowdecode))
15689 (equal year (nth 5 nowdecode))
15690 (nth 2 tl)
15691 (or (< (nth 2 tl) (nth 2 nowdecode))
15692 (and (= (nth 2 tl) (nth 2 nowdecode))
15693 (nth 1 tl)
15694 (< (nth 1 tl) (nth 1 nowdecode)))))
15695 (setq day (1+ day)
15696 futurep t))
15698 ;; Special date definitions below
15699 (cond
15700 (iso-week
15701 ;; There was an iso week
15702 (require 'cal-iso)
15703 (setq futurep nil)
15704 (setq year (or iso-year year)
15705 day (or iso-weekday wday 1)
15706 wday nil ; to make sure that the trigger below does not match
15707 iso-date (calendar-gregorian-from-absolute
15708 (calendar-absolute-from-iso
15709 (list iso-week day year))))
15710 ; FIXME: Should we also push ISO weeks into the future?
15711 ; (when (and org-read-date-prefer-future
15712 ; (not iso-year)
15713 ; (< (calendar-absolute-from-gregorian iso-date)
15714 ; (time-to-days (current-time))))
15715 ; (setq year (1+ year)
15716 ; iso-date (calendar-gregorian-from-absolute
15717 ; (calendar-absolute-from-iso
15718 ; (list iso-week day year)))))
15719 (setq month (car iso-date)
15720 year (nth 2 iso-date)
15721 day (nth 1 iso-date)))
15722 (deltan
15723 (setq futurep nil)
15724 (unless deltadef
15725 (let ((now (decode-time (current-time))))
15726 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15727 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15728 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15729 ((equal deltaw "m") (setq month (+ month deltan)))
15730 ((equal deltaw "y") (setq year (+ year deltan)))))
15731 ((and wday (not (nth 3 tl)))
15732 ;; Weekday was given, but no day, so pick that day in the week
15733 ;; on or after the derived date.
15734 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15735 (unless (equal wday wday1)
15736 (setq day (+ day (% (- wday wday1 -7) 7))))))
15737 (if (and (boundp 'org-time-was-given)
15738 (nth 2 tl))
15739 (setq org-time-was-given t))
15740 (if (< year 100) (setq year (+ 2000 year)))
15741 ;; Check of the date is representable
15742 (if org-read-date-force-compatible-dates
15743 (progn
15744 (if (< year 1970)
15745 (setq year 1970 org-read-date-analyze-forced-year t))
15746 (if (> year 2037)
15747 (setq year 2037 org-read-date-analyze-forced-year t)))
15748 (condition-case nil
15749 (ignore (encode-time second minute hour day month year))
15750 (error
15751 (setq year (nth 5 org-defdecode))
15752 (setq org-read-date-analyze-forced-year t))))
15753 (setq org-read-date-analyze-futurep futurep)
15754 (list second minute hour day month year)))
15756 (defvar parse-time-weekdays)
15757 (defun org-read-date-get-relative (s today default)
15758 "Check string S for special relative date string.
15759 TODAY and DEFAULT are internal times, for today and for a default.
15760 Return shift list (N what def-flag)
15761 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15762 N is the number of WHATs to shift.
15763 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15764 the DEFAULT date rather than TODAY."
15765 (require 'parse-time)
15766 (when (and
15767 (string-match
15768 (concat
15769 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15770 "\\([0-9]+\\)?"
15771 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15772 "\\([ \t]\\|$\\)") s)
15773 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15774 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15775 (string-to-char (substring (match-string 1 s) -1))
15776 ?+))
15777 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15778 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15779 (what (if (match-end 3) (match-string 3 s) "d"))
15780 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15781 (date (if rel default today))
15782 (wday (nth 6 (decode-time date)))
15783 delta)
15784 (if wday1
15785 (progn
15786 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15787 (if (= dir ?-) (setq delta (- delta 7)))
15788 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15789 (list delta "d" rel))
15790 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15792 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15793 "Turn a user-specified date into the internal representation.
15794 The internal representation needed by the calendar is (month day year).
15795 This is a wrapper to handle the brain-dead convention in calendar that
15796 user function argument order change dependent on argument order."
15797 (if (boundp 'calendar-date-style)
15798 (cond
15799 ((eq calendar-date-style 'american)
15800 (list arg1 arg2 arg3))
15801 ((eq calendar-date-style 'european)
15802 (list arg2 arg1 arg3))
15803 ((eq calendar-date-style 'iso)
15804 (list arg2 arg3 arg1)))
15805 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15806 (if (org-bound-and-true-p european-calendar-style)
15807 (list arg2 arg1 arg3)
15808 (list arg1 arg2 arg3)))))
15810 (defun org-eval-in-calendar (form &optional keepdate)
15811 "Eval FORM in the calendar window and return to current window.
15812 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15813 otherwise stick to the current value of `org-ans2'."
15814 (let ((sf (selected-frame))
15815 (sw (selected-window)))
15816 (select-window (get-buffer-window "*Calendar*" t))
15817 (eval form)
15818 (when (and (not keepdate) (calendar-cursor-to-date))
15819 (let* ((date (calendar-cursor-to-date))
15820 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15821 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15822 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15823 (select-window sw)
15824 (org-select-frame-set-input-focus sf)))
15826 (defun org-calendar-select ()
15827 "Return to `org-read-date' with the date currently selected.
15828 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15829 (interactive)
15830 (when (calendar-cursor-to-date)
15831 (let* ((date (calendar-cursor-to-date))
15832 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15833 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15834 (if (active-minibuffer-window) (exit-minibuffer))))
15836 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15837 "Insert a date stamp for the date given by the internal TIME.
15838 WITH-HM means use the stamp format that includes the time of the day.
15839 INACTIVE means use square brackets instead of angular ones, so that the
15840 stamp will not contribute to the agenda.
15841 PRE and POST are optional strings to be inserted before and after the
15842 stamp.
15843 The command returns the inserted time stamp."
15844 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15845 stamp)
15846 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15847 (insert-before-markers (or pre ""))
15848 (when (listp extra)
15849 (setq extra (car extra))
15850 (if (and (stringp extra)
15851 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15852 (setq extra (format "-%02d:%02d"
15853 (string-to-number (match-string 1 extra))
15854 (string-to-number (match-string 2 extra))))
15855 (setq extra nil)))
15856 (when extra
15857 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15858 (insert-before-markers (setq stamp (format-time-string fmt time)))
15859 (insert-before-markers (or post ""))
15860 (setq org-last-inserted-timestamp stamp)))
15862 (defun org-toggle-time-stamp-overlays ()
15863 "Toggle the use of custom time stamp formats."
15864 (interactive)
15865 (setq org-display-custom-times (not org-display-custom-times))
15866 (unless org-display-custom-times
15867 (let ((p (point-min)) (bmp (buffer-modified-p)))
15868 (while (setq p (next-single-property-change p 'display))
15869 (if (and (get-text-property p 'display)
15870 (eq (get-text-property p 'face) 'org-date))
15871 (remove-text-properties
15872 p (setq p (next-single-property-change p 'display))
15873 '(display t))))
15874 (set-buffer-modified-p bmp)))
15875 (if (featurep 'xemacs)
15876 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15877 (org-restart-font-lock)
15878 (setq org-table-may-need-update t)
15879 (if org-display-custom-times
15880 (message "Time stamps are overlaid with custom format")
15881 (message "Time stamp overlays removed")))
15883 (defun org-display-custom-time (beg end)
15884 "Overlay modified time stamp format over timestamp between BEG and END."
15885 (let* ((ts (buffer-substring beg end))
15886 t1 w1 with-hm tf time str w2 (off 0))
15887 (save-match-data
15888 (setq t1 (org-parse-time-string ts t))
15889 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15890 (setq off (- (match-end 0) (match-beginning 0)))))
15891 (setq end (- end off))
15892 (setq w1 (- end beg)
15893 with-hm (and (nth 1 t1) (nth 2 t1))
15894 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15895 time (org-fix-decoded-time t1)
15896 str (org-add-props
15897 (format-time-string
15898 (substring tf 1 -1) (apply 'encode-time time))
15899 nil 'mouse-face 'highlight)
15900 w2 (length str))
15901 (if (not (= w2 w1))
15902 (add-text-properties (1+ beg) (+ 2 beg)
15903 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15904 (if (featurep 'xemacs)
15905 (progn
15906 (put-text-property beg end 'invisible t)
15907 (put-text-property beg end 'end-glyph (make-glyph str)))
15908 (put-text-property beg end 'display str))))
15910 (defun org-translate-time (string)
15911 "Translate all timestamps in STRING to custom format.
15912 But do this only if the variable `org-display-custom-times' is set."
15913 (when org-display-custom-times
15914 (save-match-data
15915 (let* ((start 0)
15916 (re org-ts-regexp-both)
15917 t1 with-hm inactive tf time str beg end)
15918 (while (setq start (string-match re string start))
15919 (setq beg (match-beginning 0)
15920 end (match-end 0)
15921 t1 (save-match-data
15922 (org-parse-time-string (substring string beg end) t))
15923 with-hm (and (nth 1 t1) (nth 2 t1))
15924 inactive (equal (substring string beg (1+ beg)) "[")
15925 tf (funcall (if with-hm 'cdr 'car)
15926 org-time-stamp-custom-formats)
15927 time (org-fix-decoded-time t1)
15928 str (format-time-string
15929 (concat
15930 (if inactive "[" "<") (substring tf 1 -1)
15931 (if inactive "]" ">"))
15932 (apply 'encode-time time))
15933 string (replace-match str t t string)
15934 start (+ start (length str)))))))
15935 string)
15937 (defun org-fix-decoded-time (time)
15938 "Set 0 instead of nil for the first 6 elements of time.
15939 Don't touch the rest."
15940 (let ((n 0))
15941 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15943 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.3")
15945 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
15946 "Difference between TIMESTAMP-STRING and now in days.
15947 If SECONDS is non-nil, return the difference in seconds."
15948 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
15949 (- (funcall fdiff (org-time-string-to-time timestamp-string))
15950 (funcall fdiff (current-time)))))
15952 (defun org-deadline-close (timestamp-string &optional ndays)
15953 "Is the time in TIMESTAMP-STRING close to the current date?"
15954 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15955 (and (< (org-time-stamp-to-now timestamp-string) ndays)
15956 (not (org-entry-is-done-p))))
15958 (defun org-get-wdays (ts)
15959 "Get the deadline lead time appropriate for timestring TS."
15960 (cond
15961 ((<= org-deadline-warning-days 0)
15962 ;; 0 or negative, enforce this value no matter what
15963 (- org-deadline-warning-days))
15964 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
15965 ;; lead time is specified.
15966 (floor (* (string-to-number (match-string 1 ts))
15967 (cdr (assoc (match-string 2 ts)
15968 '(("d" . 1) ("w" . 7)
15969 ("m" . 30.4) ("y" . 365.25)))))))
15970 ;; go for the default.
15971 (t org-deadline-warning-days)))
15973 (defun org-calendar-select-mouse (ev)
15974 "Return to `org-read-date' with the date currently selected.
15975 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15976 (interactive "e")
15977 (mouse-set-point ev)
15978 (when (calendar-cursor-to-date)
15979 (let* ((date (calendar-cursor-to-date))
15980 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15981 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15982 (if (active-minibuffer-window) (exit-minibuffer))))
15984 (defun org-check-deadlines (ndays)
15985 "Check if there are any deadlines due or past due.
15986 A deadline is considered due if it happens within `org-deadline-warning-days'
15987 days from today's date. If the deadline appears in an entry marked DONE,
15988 it is not shown. The prefix arg NDAYS can be used to test that many
15989 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15990 (interactive "P")
15991 (let* ((org-warn-days
15992 (cond
15993 ((equal ndays '(4)) 100000)
15994 (ndays (prefix-numeric-value ndays))
15995 (t (abs org-deadline-warning-days))))
15996 (case-fold-search nil)
15997 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15998 (callback
15999 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16001 (message "%d deadlines past-due or due within %d days"
16002 (org-occur regexp nil callback)
16003 org-warn-days)))
16005 (defsubst org-re-timestamp (type)
16006 "Return a regexp for timestamp TYPE.
16007 Allowed values for TYPE are:
16009 all: all timestamps
16010 active: only active timestamps (<...>)
16011 inactive: only inactive timestamps ([...])
16012 scheduled: only scheduled timestamps
16013 deadline: only deadline timestamps
16015 When TYPE is nil, fall back on returning a regexp that matches
16016 both scheduled and deadline timestamps."
16017 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16018 ((eq type 'active) org-ts-regexp)
16019 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16020 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16021 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16022 ((eq type 'scheduled-or-deadline)
16023 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16025 (defun org-check-before-date (date)
16026 "Check if there are deadlines or scheduled entries before DATE."
16027 (interactive (list (org-read-date)))
16028 (let ((case-fold-search nil)
16029 (regexp (org-re-timestamp org-ts-type))
16030 (callback
16031 (lambda () (time-less-p
16032 (org-time-string-to-time (match-string 1))
16033 (org-time-string-to-time date)))))
16034 (message "%d entries before %s"
16035 (org-occur regexp nil callback) date)))
16037 (defun org-check-after-date (date)
16038 "Check if there are deadlines or scheduled entries after DATE."
16039 (interactive (list (org-read-date)))
16040 (let ((case-fold-search nil)
16041 (regexp (org-re-timestamp org-ts-type))
16042 (callback
16043 (lambda () (not
16044 (time-less-p
16045 (org-time-string-to-time (match-string 1))
16046 (org-time-string-to-time date))))))
16047 (message "%d entries after %s"
16048 (org-occur regexp nil callback) date)))
16050 (defun org-check-dates-range (start-date end-date)
16051 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16052 (interactive (list (org-read-date nil nil nil "Range starts")
16053 (org-read-date nil nil nil "Range end")))
16054 (let ((case-fold-search nil)
16055 (regexp (org-re-timestamp org-ts-type))
16056 (callback
16057 (lambda ()
16058 (let ((match (match-string 1)))
16059 (and
16060 (not (time-less-p
16061 (org-time-string-to-time match)
16062 (org-time-string-to-time start-date)))
16063 (time-less-p
16064 (org-time-string-to-time match)
16065 (org-time-string-to-time end-date)))))))
16066 (message "%d entries between %s and %s"
16067 (org-occur regexp nil callback) start-date end-date)))
16069 (defun org-evaluate-time-range (&optional to-buffer)
16070 "Evaluate a time range by computing the difference between start and end.
16071 Normally the result is just printed in the echo area, but with prefix arg
16072 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16073 If the time range is actually in a table, the result is inserted into the
16074 next column.
16075 For time difference computation, a year is assumed to be exactly 365
16076 days in order to avoid rounding problems."
16077 (interactive "P")
16079 (org-clock-update-time-maybe)
16080 (save-excursion
16081 (unless (org-at-date-range-p t)
16082 (goto-char (point-at-bol))
16083 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16084 (if (not (org-at-date-range-p t))
16085 (error "Not at a time-stamp range, and none found in current line")))
16086 (let* ((ts1 (match-string 1))
16087 (ts2 (match-string 2))
16088 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16089 (match-end (match-end 0))
16090 (time1 (org-time-string-to-time ts1))
16091 (time2 (org-time-string-to-time ts2))
16092 (t1 (org-float-time time1))
16093 (t2 (org-float-time time2))
16094 (diff (abs (- t2 t1)))
16095 (negative (< (- t2 t1) 0))
16096 ;; (ys (floor (* 365 24 60 60)))
16097 (ds (* 24 60 60))
16098 (hs (* 60 60))
16099 (fy "%dy %dd %02d:%02d")
16100 (fy1 "%dy %dd")
16101 (fd "%dd %02d:%02d")
16102 (fd1 "%dd")
16103 (fh "%02d:%02d")
16104 y d h m align)
16105 (if havetime
16106 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16108 d (floor (/ diff ds)) diff (mod diff ds)
16109 h (floor (/ diff hs)) diff (mod diff hs)
16110 m (floor (/ diff 60)))
16111 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16113 d (floor (+ (/ diff ds) 0.5))
16114 h 0 m 0))
16115 (if (not to-buffer)
16116 (message "%s" (org-make-tdiff-string y d h m))
16117 (if (org-at-table-p)
16118 (progn
16119 (goto-char match-end)
16120 (setq align t)
16121 (and (looking-at " *|") (goto-char (match-end 0))))
16122 (goto-char match-end))
16123 (if (looking-at
16124 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16125 (replace-match ""))
16126 (if negative (insert " -"))
16127 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16128 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16129 (insert " " (format fh h m))))
16130 (if align (org-table-align))
16131 (message "Time difference inserted")))))
16133 (defun org-make-tdiff-string (y d h m)
16134 (let ((fmt "")
16135 (l nil))
16136 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16137 l (push y l)))
16138 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16139 l (push d l)))
16140 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16141 l (push h l)))
16142 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16143 l (push m l)))
16144 (apply 'format fmt (nreverse l))))
16146 (defun org-time-string-to-time (s &optional buffer pos)
16147 "Convert a timestamp string into internal time."
16148 (condition-case errdata
16149 (apply 'encode-time (org-parse-time-string s))
16150 (error (error "Bad timestamp `%s'%s\nError was: %s"
16151 s (if (not (and buffer pos))
16153 (format " at %d in buffer `%s'" pos buffer))
16154 (cdr errdata)))))
16156 (defun org-time-string-to-seconds (s)
16157 "Convert a timestamp string to a number of seconds."
16158 (org-float-time (org-time-string-to-time s)))
16160 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16161 "Convert a time stamp to an absolute day number.
16162 If there is a specifier for a cyclic time stamp, get the closest date to
16163 DAYNR.
16164 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16165 The variable date is bound by the calendar when this is called."
16166 (cond
16167 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16168 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16169 daynr
16170 (+ daynr 1000)))
16171 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16172 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16173 (time-to-days (current-time))) (match-string 0 s)
16174 prefer show-all))
16175 (t (time-to-days
16176 (condition-case errdata
16177 (apply 'encode-time (org-parse-time-string s))
16178 (error (error "Bad timestamp `%s'%s\nError was: %s"
16179 s (if (not (and buffer pos))
16181 (format " at %d in buffer `%s'" pos buffer))
16182 (cdr errdata))))))))
16184 (defun org-days-to-iso-week (days)
16185 "Return the iso week number."
16186 (require 'cal-iso)
16187 (car (calendar-iso-from-absolute days)))
16189 (defun org-small-year-to-year (year)
16190 "Convert 2-digit years into 4-digit years.
16191 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16192 The year 2000 cannot be abbreviated. Any year larger than 99
16193 is returned unchanged."
16194 (if (< year 38)
16195 (setq year (+ 2000 year))
16196 (if (< year 100)
16197 (setq year (+ 1900 year))))
16198 year)
16200 (defun org-time-from-absolute (d)
16201 "Return the time corresponding to date D.
16202 D may be an absolute day number, or a calendar-type list (month day year)."
16203 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16204 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16206 (defun org-calendar-holiday ()
16207 "List of holidays, for Diary display in Org-mode."
16208 (require 'holidays)
16209 (let ((hl (funcall
16210 (if (fboundp 'calendar-check-holidays)
16211 'calendar-check-holidays 'check-calendar-holidays) date)))
16212 (if hl (mapconcat 'identity hl "; "))))
16214 (defun org-diary-sexp-entry (sexp entry date)
16215 "Process a SEXP diary ENTRY for DATE."
16216 (require 'diary-lib)
16217 (let ((result (if calendar-debug-sexp
16218 (let ((stack-trace-on-error t))
16219 (eval (car (read-from-string sexp))))
16220 (condition-case nil
16221 (eval (car (read-from-string sexp)))
16222 (error
16223 (beep)
16224 (message "Bad sexp at line %d in %s: %s"
16225 (org-current-line)
16226 (buffer-file-name) sexp)
16227 (sleep-for 2))))))
16228 (cond ((stringp result) (split-string result "; "))
16229 ((and (consp result)
16230 (not (consp (cdr result)))
16231 (stringp (cdr result))) (cdr result))
16232 ((and (consp result)
16233 (stringp (car result))) result)
16234 (result entry))))
16236 (defun org-diary-to-ical-string (frombuf)
16237 "Get iCalendar entries from diary entries in buffer FROMBUF.
16238 This uses the icalendar.el library."
16239 (let* ((tmpdir (if (featurep 'xemacs)
16240 (temp-directory)
16241 temporary-file-directory))
16242 (tmpfile (make-temp-name
16243 (expand-file-name "orgics" tmpdir)))
16244 buf rtn b e)
16245 (with-current-buffer frombuf
16246 (icalendar-export-region (point-min) (point-max) tmpfile)
16247 (setq buf (find-buffer-visiting tmpfile))
16248 (set-buffer buf)
16249 (goto-char (point-min))
16250 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16251 (setq b (match-beginning 0)))
16252 (goto-char (point-max))
16253 (if (re-search-backward "^END:VEVENT" nil t)
16254 (setq e (match-end 0)))
16255 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16256 (kill-buffer buf)
16257 (delete-file tmpfile)
16258 rtn))
16260 (defun org-closest-date (start current change prefer show-all)
16261 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16262 When PREFER is `past', return a date that is either CURRENT or past.
16263 When PREFER is `future', return a date that is either CURRENT or future.
16264 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16265 ;; Make the proper lists from the dates
16266 (catch 'exit
16267 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
16268 dn dw sday cday n1 n2 n0
16269 d m y y1 y2 date1 date2 nmonths nm ny m2)
16271 (setq start (org-date-to-gregorian start)
16272 current (org-date-to-gregorian
16273 (if show-all
16274 current
16275 (time-to-days (current-time))))
16276 sday (calendar-absolute-from-gregorian start)
16277 cday (calendar-absolute-from-gregorian current))
16279 (if (<= cday sday) (throw 'exit sday))
16281 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16282 (setq dn (string-to-number (match-string 1 change))
16283 dw (cdr (assoc (match-string 2 change) a1)))
16284 (error "Invalid change specifier: %s" change))
16285 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16286 (cond
16287 ((eq dw 'day)
16288 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16289 n2 (+ n1 dn)))
16290 ((eq dw 'year)
16291 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16292 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16293 (setq date1 (list m d y1)
16294 n1 (calendar-absolute-from-gregorian date1)
16295 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16296 n2 (calendar-absolute-from-gregorian date2)))
16297 ((eq dw 'month)
16298 ;; approx number of month between the two dates
16299 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16300 ;; How often does dn fit in there?
16301 (setq d (nth 1 start) m (car start) y (nth 2 start)
16302 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16303 m (+ m nm)
16304 ny (floor (/ m 12))
16305 y (+ y ny)
16306 m (- m (* ny 12)))
16307 (while (> m 12) (setq m (- m 12) y (1+ y)))
16308 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16309 (setq m2 (+ m dn) y2 y)
16310 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16311 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16312 (while (<= n2 cday)
16313 (setq n1 n2 m m2 y y2)
16314 (setq m2 (+ m dn) y2 y)
16315 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16316 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16317 ;; Make sure n1 is the earlier date
16318 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16319 (if show-all
16320 (cond
16321 ((eq prefer 'past) (if (= cday n2) n2 n1))
16322 ((eq prefer 'future) (if (= cday n1) n1 n2))
16323 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16324 (cond
16325 ((eq prefer 'past) (if (= cday n2) n2 n1))
16326 ((eq prefer 'future) (if (= cday n1) n1 n2))
16327 (t (if (= cday n1) n1 n2)))))))
16329 (defun org-date-to-gregorian (date)
16330 "Turn any specification of DATE into a Gregorian date for the calendar."
16331 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16332 ((and (listp date) (= (length date) 3)) date)
16333 ((stringp date)
16334 (setq date (org-parse-time-string date))
16335 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16336 ((listp date)
16337 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16339 (defun org-parse-time-string (s &optional nodefault)
16340 "Parse the standard Org-mode time string.
16341 This should be a lot faster than the normal `parse-time-string'.
16342 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16343 hour and minute fields will be nil if not given."
16344 (if (string-match org-ts-regexp0 s)
16345 (list 0
16346 (if (or (match-beginning 8) (not nodefault))
16347 (string-to-number (or (match-string 8 s) "0")))
16348 (if (or (match-beginning 7) (not nodefault))
16349 (string-to-number (or (match-string 7 s) "0")))
16350 (string-to-number (match-string 4 s))
16351 (string-to-number (match-string 3 s))
16352 (string-to-number (match-string 2 s))
16353 nil nil nil)
16354 (error "Not a standard Org-mode time string: %s" s)))
16356 (defun org-timestamp-up (&optional arg)
16357 "Increase the date item at the cursor by one.
16358 If the cursor is on the year, change the year. If it is on the month,
16359 the day or the time, change that.
16360 With prefix ARG, change by that many units."
16361 (interactive "p")
16362 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16364 (defun org-timestamp-down (&optional arg)
16365 "Decrease the date item at the cursor by one.
16366 If the cursor is on the year, change the year. If it is on the month,
16367 the day or the time, change that.
16368 With prefix ARG, change by that many units."
16369 (interactive "p")
16370 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16372 (defun org-timestamp-up-day (&optional arg)
16373 "Increase the date in the time stamp by one day.
16374 With prefix ARG, change that many days."
16375 (interactive "p")
16376 (if (and (not (org-at-timestamp-p t))
16377 (org-at-heading-p))
16378 (org-todo 'up)
16379 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16381 (defun org-timestamp-down-day (&optional arg)
16382 "Decrease the date in the time stamp by one day.
16383 With prefix ARG, change that many days."
16384 (interactive "p")
16385 (if (and (not (org-at-timestamp-p t))
16386 (org-at-heading-p))
16387 (org-todo 'down)
16388 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16390 (defun org-at-timestamp-p (&optional inactive-ok)
16391 "Determine if the cursor is in or at a timestamp."
16392 (interactive)
16393 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16394 (pos (point))
16395 (ans (or (looking-at tsr)
16396 (save-excursion
16397 (skip-chars-backward "^[<\n\r\t")
16398 (if (> (point) (point-min)) (backward-char 1))
16399 (and (looking-at tsr)
16400 (> (- (match-end 0) pos) -1))))))
16401 (and ans
16402 (boundp 'org-ts-what)
16403 (setq org-ts-what
16404 (cond
16405 ((= pos (match-beginning 0)) 'bracket)
16406 ;; Point is considered to be "on the bracket" whether
16407 ;; it's really on it or right after it.
16408 ((= pos (1- (match-end 0))) 'bracket)
16409 ((= pos (match-end 0)) 'after)
16410 ((org-pos-in-match-range pos 2) 'year)
16411 ((org-pos-in-match-range pos 3) 'month)
16412 ((org-pos-in-match-range pos 7) 'hour)
16413 ((org-pos-in-match-range pos 8) 'minute)
16414 ((or (org-pos-in-match-range pos 4)
16415 (org-pos-in-match-range pos 5)) 'day)
16416 ((and (> pos (or (match-end 8) (match-end 5)))
16417 (< pos (match-end 0)))
16418 (- pos (or (match-end 8) (match-end 5))))
16419 (t 'day))))
16420 ans))
16422 (defun org-toggle-timestamp-type ()
16423 "Toggle the type (<active> or [inactive]) of a time stamp."
16424 (interactive)
16425 (when (org-at-timestamp-p t)
16426 (let ((beg (match-beginning 0)) (end (match-end 0))
16427 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16428 (save-excursion
16429 (goto-char beg)
16430 (while (re-search-forward "[][<>]" end t)
16431 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16432 t t)))
16433 (message "Timestamp is now %sactive"
16434 (if (equal (char-after beg) ?<) "" "in")))))
16436 (defvar org-clock-history) ; defined in org-clock.el
16437 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16438 (defun org-timestamp-change (n &optional what updown)
16439 "Change the date in the time stamp at point.
16440 The date will be changed by N times WHAT. WHAT can be `day', `month',
16441 `year', `minute', `second'. If WHAT is not given, the cursor position
16442 in the timestamp determines what will be changed."
16443 (let ((origin (point)) origin-cat
16444 with-hm inactive
16445 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16446 org-ts-what
16447 extra rem
16448 ts time time0 fixnext clrgx)
16449 (if (not (org-at-timestamp-p t))
16450 (error "Not at a timestamp"))
16451 (if (and (not what) (eq org-ts-what 'bracket))
16452 (org-toggle-timestamp-type)
16453 ;; Point isn't on brackets. Remember the part of the time-stamp
16454 ;; the point was in. Indeed, size of time-stamps may change,
16455 ;; but point must be kept in the same category nonetheless.
16456 (setq origin-cat org-ts-what)
16457 (if (and (not what) (not (eq org-ts-what 'day))
16458 org-display-custom-times
16459 (get-text-property (point) 'display)
16460 (not (get-text-property (1- (point)) 'display)))
16461 (setq org-ts-what 'day))
16462 (setq org-ts-what (or what org-ts-what)
16463 inactive (= (char-after (match-beginning 0)) ?\[)
16464 ts (match-string 0))
16465 (replace-match "")
16466 (if (string-match
16467 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16469 (setq extra (match-string 1 ts)))
16470 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16471 (setq with-hm t))
16472 (setq time0 (org-parse-time-string ts))
16473 (when (and updown
16474 (eq org-ts-what 'minute)
16475 (not current-prefix-arg))
16476 ;; This looks like s-up and s-down. Change by one rounding step.
16477 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16478 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16479 (setcar (cdr time0) (+ (nth 1 time0)
16480 (if (> n 0) (- rem) (- dm rem))))))
16481 (setq time
16482 (encode-time (or (car time0) 0)
16483 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16484 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16485 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16486 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16487 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16488 (nthcdr 6 time0)))
16489 (when (and (member org-ts-what '(hour minute))
16490 extra
16491 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16492 (setq extra (org-modify-ts-extra
16493 extra
16494 (if (eq org-ts-what 'hour) 2 5)
16495 n dm)))
16496 (when (integerp org-ts-what)
16497 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16498 (if (eq what 'calendar)
16499 (let ((cal-date (org-get-date-from-calendar)))
16500 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16501 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16502 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16503 (setcar time0 (or (car time0) 0))
16504 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16505 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16506 (setq time (apply 'encode-time time0))))
16507 ;; Insert the new time-stamp, and ensure point stays in the same
16508 ;; category as before (i.e. not after the last position in that
16509 ;; category).
16510 (let ((pos (point)))
16511 ;; Stay before inserted string. `save-excursion' is of no use.
16512 (setq org-last-changed-timestamp
16513 (org-insert-time-stamp time with-hm inactive nil nil extra))
16514 (goto-char pos))
16515 (save-match-data
16516 (looking-at org-ts-regexp3)
16517 (goto-char (cond
16518 ;; `day' category ends before `hour' if any, or at
16519 ;; the end of the day name.
16520 ((eq origin-cat 'day)
16521 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16522 ((eq origin-cat 'hour) (min (match-end 7) origin))
16523 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16524 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16525 ;; `year' and `month' have both fixed size: point
16526 ;; couldn't have moved into another part.
16527 (t origin))))
16528 ;; Update clock if on a CLOCK line.
16529 (org-clock-update-time-maybe)
16530 ;; Maybe adjust the closest clock in `org-clock-history'
16531 (when org-clock-adjust-closest
16532 (if (not (and (org-at-clock-log-p)
16533 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16534 org-clock-history))))))
16535 (message "No clock to adjust")
16536 (cond ((save-excursion ; fix previous clock?
16537 (re-search-backward org-ts-regexp0 nil t)
16538 (org-looking-back (concat org-clock-string " \\[")))
16539 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16540 ((save-excursion ; fix next clock?
16541 (re-search-backward org-ts-regexp0 nil t)
16542 (looking-at (concat org-ts-regexp0 "\\] =>")))
16543 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16544 (save-window-excursion
16545 ;; Find closest clock to point, adjust the previous/next one in history
16546 (let* ((p (save-excursion (org-back-to-heading t)))
16547 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16548 (clfixnth
16549 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16550 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16551 (if (not clfixpos)
16552 (message "No clock to adjust")
16553 (save-excursion
16554 (org-goto-marker-or-bmk clfixpos)
16555 (org-show-subtree)
16556 (when (re-search-forward clrgx nil t)
16557 (goto-char (match-beginning 1))
16558 (let (org-clock-adjust-closest)
16559 (org-timestamp-change n org-ts-what updown))
16560 (message "Clock adjusted in %s for heading: %s"
16561 (file-name-nondirectory (buffer-file-name))
16562 (org-get-heading t t)))))))))
16563 ;; Try to recenter the calendar window, if any.
16564 (if (and org-calendar-follow-timestamp-change
16565 (get-buffer-window "*Calendar*" t)
16566 (memq org-ts-what '(day month year)))
16567 (org-recenter-calendar (time-to-days time))))))
16569 (defun org-modify-ts-extra (s pos n dm)
16570 "Change the different parts of the lead-time and repeat fields in timestamp."
16571 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16572 ng h m new rem)
16573 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16574 (cond
16575 ((or (org-pos-in-match-range pos 2)
16576 (org-pos-in-match-range pos 3))
16577 (setq m (string-to-number (match-string 3 s))
16578 h (string-to-number (match-string 2 s)))
16579 (if (org-pos-in-match-range pos 2)
16580 (setq h (+ h n))
16581 (setq n (* dm (org-no-warnings (signum n))))
16582 (when (not (= 0 (setq rem (% m dm))))
16583 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16584 (setq m (+ m n)))
16585 (if (< m 0) (setq m (+ m 60) h (1- h)))
16586 (if (> m 59) (setq m (- m 60) h (1+ h)))
16587 (setq h (min 24 (max 0 h)))
16588 (setq ng 1 new (format "-%02d:%02d" h m)))
16589 ((org-pos-in-match-range pos 6)
16590 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16591 ((org-pos-in-match-range pos 5)
16592 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16594 ((org-pos-in-match-range pos 9)
16595 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16596 ((org-pos-in-match-range pos 8)
16597 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16599 (when ng
16600 (setq s (concat
16601 (substring s 0 (match-beginning ng))
16603 (substring s (match-end ng))))))
16606 (defun org-recenter-calendar (date)
16607 "If the calendar is visible, recenter it to DATE."
16608 (let ((cwin (get-buffer-window "*Calendar*" t)))
16609 (when cwin
16610 (let ((calendar-move-hook nil))
16611 (with-selected-window cwin
16612 (calendar-goto-date (if (listp date) date
16613 (calendar-gregorian-from-absolute date))))))))
16615 (defun org-goto-calendar (&optional arg)
16616 "Go to the Emacs calendar at the current date.
16617 If there is a time stamp in the current line, go to that date.
16618 A prefix ARG can be used to force the current date."
16619 (interactive "P")
16620 (let ((tsr org-ts-regexp) diff
16621 (calendar-move-hook nil)
16622 (calendar-view-holidays-initially-flag nil)
16623 (calendar-view-diary-initially-flag nil))
16624 (if (or (org-at-timestamp-p)
16625 (save-excursion
16626 (beginning-of-line 1)
16627 (looking-at (concat ".*" tsr))))
16628 (let ((d1 (time-to-days (current-time)))
16629 (d2 (time-to-days
16630 (org-time-string-to-time (match-string 1)))))
16631 (setq diff (- d2 d1))))
16632 (calendar)
16633 (calendar-goto-today)
16634 (if (and diff (not arg)) (calendar-forward-day diff))))
16636 (defun org-get-date-from-calendar ()
16637 "Return a list (month day year) of date at point in calendar."
16638 (with-current-buffer "*Calendar*"
16639 (save-match-data
16640 (calendar-cursor-to-date))))
16642 (defun org-date-from-calendar ()
16643 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16644 If there is already a time stamp at the cursor position, update it."
16645 (interactive)
16646 (if (org-at-timestamp-p t)
16647 (org-timestamp-change 0 'calendar)
16648 (let ((cal-date (org-get-date-from-calendar)))
16649 (org-insert-time-stamp
16650 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16652 (defun org-minutes-to-hh:mm-string (m)
16653 "Compute H:MM from a number of minutes."
16654 (let ((h (/ m 60)))
16655 (setq m (- m (* 60 h)))
16656 (format org-time-clocksum-format h m)))
16658 (defun org-hh:mm-string-to-minutes (s)
16659 "Convert a string H:MM to a number of minutes.
16660 If the string is just a number, interpret it as minutes.
16661 In fact, the first hh:mm or number in the string will be taken,
16662 there can be extra stuff in the string.
16663 If no number is found, the return value is 0."
16664 (cond
16665 ((integerp s) s)
16666 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16667 (+ (* (string-to-number (match-string 1 s)) 60)
16668 (string-to-number (match-string 2 s))))
16669 ((string-match "\\([0-9]+\\)" s)
16670 (string-to-number (match-string 1 s)))
16671 (t 0)))
16673 (defcustom org-effort-durations
16674 `(("h" . 60)
16675 ("d" . ,(* 60 8))
16676 ("w" . ,(* 60 8 5))
16677 ("m" . ,(* 60 8 5 4))
16678 ("y" . ,(* 60 8 5 40)))
16679 "Conversion factor to minutes for an effort modifier.
16681 Each entry has the form (MODIFIER . MINUTES).
16683 In an effort string, a number followed by MODIFIER is multiplied
16684 by the specified number of MINUTES to obtain an effort in
16685 minutes.
16687 For example, if the value of this variable is ((\"hours\" . 60)), then an
16688 effort string \"2hours\" is equivalent to 120 minutes."
16689 :group 'org-agenda
16690 :version "24.1"
16691 :type '(alist :key-type (string :tag "Modifier")
16692 :value-type (number :tag "Minutes")))
16694 (defcustom org-image-actual-width t
16695 "Should we use the actual width of images when inlining them?
16697 When set to `t', always use the image width.
16699 When set to a number, use imagemagick (when available) to set
16700 the image's width to this value.
16702 When set to a number in a list, try to get the width from the
16703 #+ATTR.* keyword if it matches a width specification like
16704 width=\"[0-9]+\", and fall back on that number if none is found.
16706 When set to nil, try to get the width from an #+ATTR.* keyword
16707 and fall back on the original width if none is found.
16709 This requires Emacs >= 24.1, build with imagemagick support."
16710 :group 'org-appearance
16711 :version "24.3"
16712 :type '(choice
16713 (const :tag "Use the image width" t)
16714 (integer :tag "Use a number of pixels")
16715 (list :tag "Use #+ATTR* or a number of pixels" (integer))
16716 (const :tag "Use #+ATTR* or don't resize" nil)))
16718 (defun org-duration-string-to-minutes (s &optional output-to-string)
16719 "Convert a duration string S to minutes.
16721 A bare number is interpreted as minutes, modifiers can be set by
16722 customizing `org-effort-durations' (which see).
16724 Entries containing a colon are interpreted as H:MM by
16725 `org-hh:mm-string-to-minutes'."
16726 (let ((result 0)
16727 (re (concat "\\([0-9.]+\\) *\\("
16728 (regexp-opt (mapcar 'car org-effort-durations))
16729 "\\)")))
16730 (while (string-match re s)
16731 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16732 (string-to-number (match-string 1 s))))
16733 (setq s (replace-match "" nil t s)))
16734 (setq result (floor result))
16735 (incf result (org-hh:mm-string-to-minutes s))
16736 (if output-to-string (number-to-string result) result)))
16738 ;;;; Files
16740 (defun org-save-all-org-buffers ()
16741 "Save all Org-mode buffers without user confirmation."
16742 (interactive)
16743 (message "Saving all Org-mode buffers...")
16744 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16745 (when (featurep 'org-id) (org-id-locations-save))
16746 (message "Saving all Org-mode buffers... done"))
16748 (defun org-revert-all-org-buffers ()
16749 "Revert all Org-mode buffers.
16750 Prompt for confirmation when there are unsaved changes.
16751 Be sure you know what you are doing before letting this function
16752 overwrite your changes.
16754 This function is useful in a setup where one tracks org files
16755 with a version control system, to revert on one machine after pulling
16756 changes from another. I believe the procedure must be like this:
16758 1. M-x org-save-all-org-buffers
16759 2. Pull changes from the other machine, resolve conflicts
16760 3. M-x org-revert-all-org-buffers"
16761 (interactive)
16762 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16763 (error "Abort"))
16764 (save-excursion
16765 (save-window-excursion
16766 (mapc
16767 (lambda (b)
16768 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16769 (with-current-buffer b buffer-file-name))
16770 (org-pop-to-buffer-same-window b)
16771 (revert-buffer t 'no-confirm)))
16772 (buffer-list))
16773 (when (and (featurep 'org-id) org-id-track-globally)
16774 (org-id-locations-load)))))
16776 ;;;; Agenda files
16778 ;;;###autoload
16779 (defun org-switchb (&optional arg)
16780 "Switch between Org buffers.
16781 With one prefix argument, restrict available buffers to files.
16782 With two prefix arguments, restrict available buffers to agenda files.
16784 Defaults to `iswitchb' for buffer name completion.
16785 Set `org-completion-use-ido' to make it use ido instead."
16786 (interactive "P")
16787 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16788 ((equal arg '(16)) (org-buffer-list 'agenda))
16789 (t (org-buffer-list))))
16790 (org-completion-use-iswitchb org-completion-use-iswitchb)
16791 (org-completion-use-ido org-completion-use-ido))
16792 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16793 (setq org-completion-use-iswitchb t))
16794 (org-pop-to-buffer-same-window
16795 (org-icompleting-read "Org buffer: "
16796 (mapcar 'list (mapcar 'buffer-name blist))
16797 nil t))))
16799 ;;; Define some older names previously used for this functionality
16800 ;;;###autoload
16801 (defalias 'org-ido-switchb 'org-switchb)
16802 ;;;###autoload
16803 (defalias 'org-iswitchb 'org-switchb)
16805 (defun org-buffer-list (&optional predicate exclude-tmp)
16806 "Return a list of Org buffers.
16807 PREDICATE can be `export', `files' or `agenda'.
16809 export restrict the list to Export buffers.
16810 files restrict the list to buffers visiting Org files.
16811 agenda restrict the list to buffers visiting agenda files.
16813 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16814 (let* ((bfn nil)
16815 (agenda-files (and (eq predicate 'agenda)
16816 (mapcar 'file-truename (org-agenda-files t))))
16817 (filter
16818 (cond
16819 ((eq predicate 'files)
16820 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16821 ((eq predicate 'export)
16822 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16823 ((eq predicate 'agenda)
16824 (lambda (b)
16825 (with-current-buffer b
16826 (and (derived-mode-p 'org-mode)
16827 (setq bfn (buffer-file-name b))
16828 (member (file-truename bfn) agenda-files)))))
16829 (t (lambda (b) (with-current-buffer b
16830 (or (derived-mode-p 'org-mode)
16831 (string-match "\*Org .*Export"
16832 (buffer-name b)))))))))
16833 (delq nil
16834 (mapcar
16835 (lambda(b)
16836 (if (and (funcall filter b)
16837 (or (not exclude-tmp)
16838 (not (string-match "tmp" (buffer-name b)))))
16840 nil))
16841 (buffer-list)))))
16843 (defun org-agenda-files (&optional unrestricted archives)
16844 "Get the list of agenda files.
16845 Optional UNRESTRICTED means return the full list even if a restriction
16846 is currently in place.
16847 When ARCHIVES is t, include all archive files that are really being
16848 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16849 `org-agenda-archives-mode' is t."
16850 (let ((files
16851 (cond
16852 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16853 ((stringp org-agenda-files) (org-read-agenda-file-list))
16854 ((listp org-agenda-files) org-agenda-files)
16855 (t (error "Invalid value of `org-agenda-files'")))))
16856 (setq files (apply 'append
16857 (mapcar (lambda (f)
16858 (if (file-directory-p f)
16859 (directory-files
16860 f t org-agenda-file-regexp)
16861 (list f)))
16862 files)))
16863 (when org-agenda-skip-unavailable-files
16864 (setq files (delq nil
16865 (mapcar (function
16866 (lambda (file)
16867 (and (file-readable-p file) file)))
16868 files))))
16869 (when (or (eq archives t)
16870 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16871 (setq files (org-add-archive-files files)))
16872 files))
16874 (defun org-agenda-file-p (&optional file)
16875 "Return non-nil, if FILE is an agenda file.
16876 If FILE is omitted, use the file associated with the current
16877 buffer."
16878 (member (or file (buffer-file-name))
16879 (org-agenda-files t)))
16881 (defun org-edit-agenda-file-list ()
16882 "Edit the list of agenda files.
16883 Depending on setup, this either uses customize to edit the variable
16884 `org-agenda-files', or it visits the file that is holding the list. In the
16885 latter case, the buffer is set up in a way that saving it automatically kills
16886 the buffer and restores the previous window configuration."
16887 (interactive)
16888 (if (stringp org-agenda-files)
16889 (let ((cw (current-window-configuration)))
16890 (find-file org-agenda-files)
16891 (org-set-local 'org-window-configuration cw)
16892 (org-add-hook 'after-save-hook
16893 (lambda ()
16894 (set-window-configuration
16895 (prog1 org-window-configuration
16896 (kill-buffer (current-buffer))))
16897 (org-install-agenda-files-menu)
16898 (message "New agenda file list installed"))
16899 nil 'local)
16900 (message "%s" (substitute-command-keys
16901 "Edit list and finish with \\[save-buffer]")))
16902 (customize-variable 'org-agenda-files)))
16904 (defun org-store-new-agenda-file-list (list)
16905 "Set new value for the agenda file list and save it correctly."
16906 (if (stringp org-agenda-files)
16907 (let ((fe (org-read-agenda-file-list t)) b u)
16908 (while (setq b (find-buffer-visiting org-agenda-files))
16909 (kill-buffer b))
16910 (with-temp-file org-agenda-files
16911 (insert
16912 (mapconcat
16913 (lambda (f) ;; Keep un-expanded entries.
16914 (if (setq u (assoc f fe))
16915 (cdr u)
16917 list "\n")
16918 "\n")))
16919 (let ((org-mode-hook nil) (org-inhibit-startup t)
16920 (org-insert-mode-line-in-empty-file nil))
16921 (setq org-agenda-files list)
16922 (customize-save-variable 'org-agenda-files org-agenda-files))))
16924 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16925 "Read the list of agenda files from a file.
16926 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16927 filenames, used by `org-store-new-agenda-file-list' to write back
16928 un-expanded file names."
16929 (when (file-directory-p org-agenda-files)
16930 (error "`org-agenda-files' cannot be a single directory"))
16931 (when (stringp org-agenda-files)
16932 (with-temp-buffer
16933 (insert-file-contents org-agenda-files)
16934 (mapcar
16935 (lambda (f)
16936 (let ((e (expand-file-name (substitute-in-file-name f)
16937 org-directory)))
16938 (if pair-with-expansion
16939 (cons e f)
16940 e)))
16941 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16943 ;;;###autoload
16944 (defun org-cycle-agenda-files ()
16945 "Cycle through the files in `org-agenda-files'.
16946 If the current buffer visits an agenda file, find the next one in the list.
16947 If the current buffer does not, find the first agenda file."
16948 (interactive)
16949 (let* ((fs (org-agenda-files t))
16950 (files (append fs (list (car fs))))
16951 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16952 file)
16953 (unless files (error "No agenda files"))
16954 (catch 'exit
16955 (while (setq file (pop files))
16956 (if (equal (file-truename file) tcf)
16957 (when (car files)
16958 (find-file (car files))
16959 (throw 'exit t))))
16960 (find-file (car fs)))
16961 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16963 (defun org-agenda-file-to-front (&optional to-end)
16964 "Move/add the current file to the top of the agenda file list.
16965 If the file is not present in the list, it is added to the front. If it is
16966 present, it is moved there. With optional argument TO-END, add/move to the
16967 end of the list."
16968 (interactive "P")
16969 (let ((org-agenda-skip-unavailable-files nil)
16970 (file-alist (mapcar (lambda (x)
16971 (cons (file-truename x) x))
16972 (org-agenda-files t)))
16973 (ctf (file-truename buffer-file-name))
16974 x had)
16975 (setq x (assoc ctf file-alist) had x)
16977 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16978 (if to-end
16979 (setq file-alist (append (delq x file-alist) (list x)))
16980 (setq file-alist (cons x (delq x file-alist))))
16981 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16982 (org-install-agenda-files-menu)
16983 (message "File %s to %s of agenda file list"
16984 (if had "moved" "added") (if to-end "end" "front"))))
16986 (defun org-remove-file (&optional file)
16987 "Remove current file from the list of files in variable `org-agenda-files'.
16988 These are the files which are being checked for agenda entries.
16989 Optional argument FILE means use this file instead of the current."
16990 (interactive)
16991 (let* ((org-agenda-skip-unavailable-files nil)
16992 (file (or file buffer-file-name))
16993 (true-file (file-truename file))
16994 (afile (abbreviate-file-name file))
16995 (files (delq nil (mapcar
16996 (lambda (x)
16997 (if (equal true-file
16998 (file-truename x))
16999 nil x))
17000 (org-agenda-files t)))))
17001 (if (not (= (length files) (length (org-agenda-files t))))
17002 (progn
17003 (org-store-new-agenda-file-list files)
17004 (org-install-agenda-files-menu)
17005 (message "Removed file: %s" afile))
17006 (message "File was not in list: %s (not removed)" afile))))
17008 (defun org-file-menu-entry (file)
17009 (vector file (list 'find-file file) t))
17011 (defun org-check-agenda-file (file)
17012 "Make sure FILE exists. If not, ask user what to do."
17013 (when (not (file-exists-p file))
17014 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
17015 (abbreviate-file-name file))
17016 (let ((r (downcase (read-char-exclusive))))
17017 (cond
17018 ((equal r ?r)
17019 (org-remove-file file)
17020 (throw 'nextfile t))
17021 (t (error "Abort"))))))
17023 (defun org-get-agenda-file-buffer (file)
17024 "Get a buffer visiting FILE. If the buffer needs to be created, add
17025 it to the list of buffers which might be released later."
17026 (let ((buf (org-find-base-buffer-visiting file)))
17027 (if buf
17028 buf ; just return it
17029 ;; Make a new buffer and remember it
17030 (setq buf (find-file-noselect file))
17031 (if buf (push buf org-agenda-new-buffers))
17032 buf)))
17034 (defun org-release-buffers (blist)
17035 "Release all buffers in list, asking the user for confirmation when needed.
17036 When a buffer is unmodified, it is just killed. When modified, it is saved
17037 \(if the user agrees) and then killed."
17038 (let (buf file)
17039 (while (setq buf (pop blist))
17040 (setq file (buffer-file-name buf))
17041 (when (and (buffer-modified-p buf)
17042 file
17043 (y-or-n-p (format "Save file %s? " file)))
17044 (with-current-buffer buf (save-buffer)))
17045 (kill-buffer buf))))
17047 (defun org-agenda-prepare-buffers (files)
17048 "Create buffers for all agenda files, protect archived trees and comments."
17049 (interactive)
17050 (let ((pa '(:org-archived t))
17051 (pc '(:org-comment t))
17052 (pall '(:org-archived t :org-comment t))
17053 (inhibit-read-only t)
17054 (rea (concat ":" org-archive-tag ":"))
17055 bmp file re)
17056 (save-excursion
17057 (save-restriction
17058 (while (setq file (pop files))
17059 (catch 'nextfile
17060 (if (bufferp file)
17061 (set-buffer file)
17062 (org-check-agenda-file file)
17063 (set-buffer (org-get-agenda-file-buffer file)))
17064 (widen)
17065 (setq bmp (buffer-modified-p))
17066 (org-refresh-category-properties)
17067 (setq org-todo-keywords-for-agenda
17068 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17069 (setq org-done-keywords-for-agenda
17070 (append org-done-keywords-for-agenda org-done-keywords))
17071 (setq org-todo-keyword-alist-for-agenda
17072 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17073 (setq org-drawers-for-agenda
17074 (append org-drawers-for-agenda org-drawers))
17075 (setq org-tag-alist-for-agenda
17076 (append org-tag-alist-for-agenda org-tag-alist))
17078 (save-excursion
17079 (remove-text-properties (point-min) (point-max) pall)
17080 (when org-agenda-skip-archived-trees
17081 (goto-char (point-min))
17082 (while (re-search-forward rea nil t)
17083 (if (org-at-heading-p t)
17084 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17085 (goto-char (point-min))
17086 (setq re (format org-heading-keyword-regexp-format
17087 org-comment-string))
17088 (while (re-search-forward re nil t)
17089 (add-text-properties
17090 (match-beginning 0) (org-end-of-subtree t) pc)))
17091 (set-buffer-modified-p bmp)))))
17092 (setq org-todo-keywords-for-agenda
17093 (org-uniquify org-todo-keywords-for-agenda))
17094 (setq org-todo-keyword-alist-for-agenda
17095 (org-uniquify org-todo-keyword-alist-for-agenda)
17096 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17098 ;;;; Embedded LaTeX
17100 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17101 "Keymap for the minor `org-cdlatex-mode'.")
17103 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17104 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17105 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17106 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17107 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17109 (defvar org-cdlatex-texmathp-advice-is-done nil
17110 "Flag remembering if we have applied the advice to texmathp already.")
17112 (define-minor-mode org-cdlatex-mode
17113 "Toggle the minor `org-cdlatex-mode'.
17114 This mode supports entering LaTeX environment and math in LaTeX fragments
17115 in Org-mode.
17116 \\{org-cdlatex-mode-map}"
17117 nil " OCDL" nil
17118 (when org-cdlatex-mode
17119 (require 'cdlatex)
17120 (run-hooks 'cdlatex-mode-hook)
17121 (cdlatex-compute-tables))
17122 (unless org-cdlatex-texmathp-advice-is-done
17123 (setq org-cdlatex-texmathp-advice-is-done t)
17124 (defadvice texmathp (around org-math-always-on activate)
17125 "Always return t in org-mode buffers.
17126 This is because we want to insert math symbols without dollars even outside
17127 the LaTeX math segments. If Orgmode thinks that point is actually inside
17128 an embedded LaTeX fragment, let texmathp do its job.
17129 \\[org-cdlatex-mode-map]"
17130 (interactive)
17131 (let (p)
17132 (cond
17133 ((not (derived-mode-p 'org-mode)) ad-do-it)
17134 ((eq this-command 'cdlatex-math-symbol)
17135 (setq ad-return-value t
17136 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17138 (let ((p (org-inside-LaTeX-fragment-p)))
17139 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17140 (setq ad-return-value t
17141 texmathp-why '("Org-mode embedded math" . 0))
17142 (if p ad-do-it)))))))))
17144 (defun turn-on-org-cdlatex ()
17145 "Unconditionally turn on `org-cdlatex-mode'."
17146 (org-cdlatex-mode 1))
17148 (defun org-inside-LaTeX-fragment-p ()
17149 "Test if point is inside a LaTeX fragment.
17150 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17151 sequence appearing also before point.
17152 Even though the matchers for math are configurable, this function assumes
17153 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17154 delimiters are skipped when they have been removed by customization.
17155 The return value is nil, or a cons cell with the delimiter and the
17156 position of this delimiter.
17158 This function does a reasonably good job, but can locally be fooled by
17159 for example currency specifications. For example it will assume being in
17160 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17161 fragments that are properly closed, but during editing, we have to live
17162 with the uncertainty caused by missing closing delimiters. This function
17163 looks only before point, not after."
17164 (catch 'exit
17165 (let ((pos (point))
17166 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17167 (lim (progn
17168 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17169 (point)))
17170 dd-on str (start 0) m re)
17171 (goto-char pos)
17172 (when dodollar
17173 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17174 re (nth 1 (assoc "$" org-latex-regexps)))
17175 (while (string-match re str start)
17176 (cond
17177 ((= (match-end 0) (length str))
17178 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17179 ((= (match-end 0) (- (length str) 5))
17180 (throw 'exit nil))
17181 (t (setq start (match-end 0))))))
17182 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17183 (goto-char pos)
17184 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17185 (and (match-beginning 2) (throw 'exit nil))
17186 ;; count $$
17187 (while (re-search-backward "\\$\\$" lim t)
17188 (setq dd-on (not dd-on)))
17189 (goto-char pos)
17190 (if dd-on (cons "$$" m))))))
17192 (defun org-inside-latex-macro-p ()
17193 "Is point inside a LaTeX macro or its arguments?"
17194 (save-match-data
17195 (org-in-regexp
17196 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17198 (defun org-try-cdlatex-tab ()
17199 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17200 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17201 - inside a LaTeX fragment, or
17202 - after the first word in a line, where an abbreviation expansion could
17203 insert a LaTeX environment."
17204 (when org-cdlatex-mode
17205 (cond
17206 ;; Before any word on the line: No expansion possible.
17207 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17208 ;; Just after first word on the line: Expand it. Make sure it
17209 ;; cannot happen on headlines, though.
17210 ((save-excursion
17211 (skip-chars-backward "a-zA-Z0-9*")
17212 (skip-chars-backward " \t")
17213 (and (bolp) (not (org-at-heading-p))))
17214 (cdlatex-tab) t)
17215 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17217 (defun org-cdlatex-underscore-caret (&optional arg)
17218 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17219 Revert to the normal definition outside of these fragments."
17220 (interactive "P")
17221 (if (org-inside-LaTeX-fragment-p)
17222 (call-interactively 'cdlatex-sub-superscript)
17223 (let (org-cdlatex-mode)
17224 (call-interactively (key-binding (vector last-input-event))))))
17226 (defun org-cdlatex-math-modify (&optional arg)
17227 "Execute `cdlatex-math-modify' in LaTeX fragments.
17228 Revert to the normal definition outside of these fragments."
17229 (interactive "P")
17230 (if (org-inside-LaTeX-fragment-p)
17231 (call-interactively 'cdlatex-math-modify)
17232 (let (org-cdlatex-mode)
17233 (call-interactively (key-binding (vector last-input-event))))))
17235 (defvar org-latex-fragment-image-overlays nil
17236 "List of overlays carrying the images of latex fragments.")
17237 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17239 (defun org-remove-latex-fragment-image-overlays ()
17240 "Remove all overlays with LaTeX fragment images in current buffer."
17241 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17242 (setq org-latex-fragment-image-overlays nil))
17244 (defun org-preview-latex-fragment (&optional subtree)
17245 "Preview the LaTeX fragment at point, or all locally or globally.
17246 If the cursor is in a LaTeX fragment, create the image and overlay
17247 it over the source code. If there is no fragment at point, display
17248 all fragments in the current text, from one headline to the next. With
17249 prefix SUBTREE, display all fragments in the current subtree. With a
17250 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17251 the cursor is before the first headline,
17252 display all fragments in the buffer.
17253 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17254 (interactive "P")
17255 (unless buffer-file-name
17256 (error "Can't preview LaTeX fragment in a non-file buffer"))
17257 (org-remove-latex-fragment-image-overlays)
17258 (save-excursion
17259 (save-restriction
17260 (let (beg end at msg)
17261 (cond
17262 ((or (equal subtree '(16))
17263 (not (save-excursion
17264 (re-search-backward org-outline-regexp-bol nil t))))
17265 (setq beg (point-min) end (point-max)
17266 msg "Creating images for buffer...%s"))
17267 ((equal subtree '(4))
17268 (org-back-to-heading)
17269 (setq beg (point) end (org-end-of-subtree t)
17270 msg "Creating images for subtree...%s"))
17272 (if (setq at (org-inside-LaTeX-fragment-p))
17273 (goto-char (max (point-min) (- (cdr at) 2)))
17274 (org-back-to-heading))
17275 (setq beg (point) end (progn (outline-next-heading) (point))
17276 msg (if at "Creating image...%s"
17277 "Creating images for entry...%s"))))
17278 (message msg "")
17279 (narrow-to-region beg end)
17280 (goto-char beg)
17281 (org-format-latex
17282 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17283 (file-name-nondirectory
17284 buffer-file-name)))
17285 default-directory 'overlays msg at 'forbuffer
17286 org-latex-create-formula-image-program)
17287 (message msg "done. Use `C-c C-c' to remove images.")))))
17289 (defvar org-latex-regexps
17290 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17291 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17292 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17293 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17294 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17295 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17296 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17297 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17298 "Regular expressions for matching embedded LaTeX.")
17300 (defvar org-export-have-math nil) ;; dynamic scoping
17301 (defun org-format-latex (prefix &optional dir overlays msg at
17302 forbuffer processing-type)
17303 "Replace LaTeX fragments with links to an image, and produce images.
17304 Some of the options can be changed using the variable
17305 `org-format-latex-options'."
17306 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17307 (let* ((prefixnodir (file-name-nondirectory prefix))
17308 (absprefix (expand-file-name prefix dir))
17309 (todir (file-name-directory absprefix))
17310 (opt org-format-latex-options)
17311 (optnew org-format-latex-options)
17312 (matchers (plist-get opt :matchers))
17313 (re-list org-latex-regexps)
17314 (org-format-latex-header-extra
17315 (plist-get (org-infile-export-plist) :latex-header-extra))
17316 (cnt 0) txt hash link beg end re e checkdir
17317 string
17318 m n block-type block linkfile movefile ov)
17319 ;; Check the different regular expressions
17320 (while (setq e (pop re-list))
17321 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17322 block (if block-type "\n\n" ""))
17323 (when (member m matchers)
17324 (goto-char (point-min))
17325 (while (re-search-forward re nil t)
17326 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17327 (not (get-text-property (match-beginning n)
17328 'org-protected))
17329 (or (not overlays)
17330 (not (eq (get-char-property (match-beginning n)
17331 'org-overlay-type)
17332 'org-latex-overlay))))
17333 (setq org-export-have-math t)
17334 (cond
17335 ((eq processing-type 'verbatim)
17336 ;; Leave the text verbatim, just protect it
17337 (add-text-properties (match-beginning n) (match-end n)
17338 '(org-protected t)))
17339 ((eq processing-type 'mathjax)
17340 ;; Prepare for MathJax processing
17341 (setq string (match-string n))
17342 (if (member m '("$" "$1"))
17343 (save-excursion
17344 (delete-region (match-beginning n) (match-end n))
17345 (goto-char (match-beginning n))
17346 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17347 "\\)")
17348 '(org-protected t))))
17349 (add-text-properties (match-beginning n) (match-end n)
17350 '(org-protected t))))
17351 ((or (eq processing-type 'dvipng)
17352 (eq processing-type 'imagemagick))
17353 ;; Process to an image
17354 (setq txt (match-string n)
17355 beg (match-beginning n) end (match-end n)
17356 cnt (1+ cnt))
17357 (let ((face (face-at-point))
17358 (fg (plist-get opt :foreground))
17359 (bg (plist-get opt :background))
17360 print-length print-level) ; make sure full list is printed
17361 (when forbuffer
17362 ; Get the colors from the face at point
17363 (goto-char beg)
17364 (when (eq fg 'auto)
17365 (setq fg (face-attribute face :foreground nil 'default)))
17366 (when (eq bg 'auto)
17367 (setq bg (face-attribute face :background nil 'default)))
17368 (setq optnew (copy-sequence opt))
17369 (plist-put optnew :foreground fg)
17370 (plist-put optnew :background bg))
17371 (setq hash (sha1 (prin1-to-string
17372 (list org-format-latex-header
17373 org-format-latex-header-extra
17374 org-export-latex-default-packages-alist
17375 org-export-latex-packages-alist
17376 org-format-latex-options
17377 forbuffer txt fg bg)))
17378 linkfile (format "%s_%s.png" prefix hash)
17379 movefile (format "%s_%s.png" absprefix hash)))
17380 (setq link (concat block "[[file:" linkfile "]]" block))
17381 (if msg (message msg cnt))
17382 (goto-char beg)
17383 (unless checkdir ; make sure the directory exists
17384 (setq checkdir t)
17385 (or (file-directory-p todir) (make-directory todir t)))
17386 (org-create-formula-image
17387 txt movefile optnew forbuffer processing-type)
17388 (if overlays
17389 (progn
17390 (mapc (lambda (o)
17391 (if (eq (overlay-get o 'org-overlay-type)
17392 'org-latex-overlay)
17393 (delete-overlay o)))
17394 (overlays-in beg end))
17395 (setq ov (make-overlay beg end))
17396 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17397 (if (featurep 'xemacs)
17398 (progn
17399 (overlay-put ov 'invisible t)
17400 (overlay-put
17401 ov 'end-glyph
17402 (make-glyph (vector 'png :file movefile))))
17403 (overlay-put
17404 ov 'display
17405 (list 'image :type 'png :file movefile :ascent 'center)))
17406 (push ov org-latex-fragment-image-overlays)
17407 (goto-char end))
17408 (delete-region beg end)
17409 (insert (org-add-props link
17410 (list 'org-latex-src
17411 (replace-regexp-in-string
17412 "\"" "" txt)
17413 'org-latex-src-embed-type
17414 (if block-type 'paragraph 'character))))))
17415 ((eq processing-type 'mathml)
17416 ;; Process to MathML
17417 (unless (save-match-data (org-format-latex-mathml-available-p))
17418 (error "LaTeX to MathML converter not configured"))
17419 (setq txt (match-string n)
17420 beg (match-beginning n) end (match-end n)
17421 cnt (1+ cnt))
17422 (if msg (message msg cnt))
17423 (goto-char beg)
17424 (delete-region beg end)
17425 (insert (org-format-latex-as-mathml
17426 txt block-type prefix dir)))
17428 (error "Unknown conversion type %s for latex fragments"
17429 processing-type)))))))))
17431 (defun org-create-math-formula (latex-frag &optional mathml-file)
17432 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17433 Use `org-latex-to-mathml-convert-command'. If the conversion is
17434 sucessful, return the portion between \"<math...> </math>\"
17435 elements otherwise return nil. When MATHML-FILE is specified,
17436 write the results in to that file. When invoked as an
17437 interactive command, prompt for LATEX-FRAG, with initial value
17438 set to the current active region and echo the results for user
17439 inspection."
17440 (interactive (list (let ((frag (when (org-region-active-p)
17441 (buffer-substring-no-properties
17442 (region-beginning) (region-end)))))
17443 (read-string "LaTeX Fragment: " frag nil frag))))
17444 (unless latex-frag (error "Invalid latex-frag"))
17445 (let* ((tmp-in-file (file-relative-name
17446 (make-temp-name (expand-file-name "ltxmathml-in"))))
17447 (ignore (write-region latex-frag nil tmp-in-file))
17448 (tmp-out-file (file-relative-name
17449 (make-temp-name (expand-file-name "ltxmathml-out"))))
17450 (cmd (format-spec
17451 org-latex-to-mathml-convert-command
17452 `((?j . ,(shell-quote-argument
17453 (expand-file-name org-latex-to-mathml-jar-file)))
17454 (?I . ,(shell-quote-argument tmp-in-file))
17455 (?o . ,(shell-quote-argument tmp-out-file)))))
17456 mathml shell-command-output)
17457 (when (org-called-interactively-p 'any)
17458 (unless (org-format-latex-mathml-available-p)
17459 (error "LaTeX to MathML converter not configured")))
17460 (message "Running %s" cmd)
17461 (setq shell-command-output (shell-command-to-string cmd))
17462 (setq mathml
17463 (when (file-readable-p tmp-out-file)
17464 (with-current-buffer (find-file-noselect tmp-out-file t)
17465 (goto-char (point-min))
17466 (when (re-search-forward
17467 (concat
17468 (regexp-quote
17469 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17470 "\\(.\\|\n\\)*"
17471 (regexp-quote "</math>")) nil t)
17472 (prog1 (match-string 0) (kill-buffer))))))
17473 (cond
17474 (mathml
17475 (setq mathml
17476 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17477 (when mathml-file
17478 (write-region mathml nil mathml-file))
17479 (when (org-called-interactively-p 'any)
17480 (message mathml)))
17481 ((message "LaTeX to MathML conversion failed")
17482 (message shell-command-output)))
17483 (delete-file tmp-in-file)
17484 (when (file-exists-p tmp-out-file)
17485 (delete-file tmp-out-file))
17486 mathml))
17488 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17489 prefix &optional dir)
17490 "Use `org-create-math-formula' but check local cache first."
17491 (let* ((absprefix (expand-file-name prefix dir))
17492 (print-length nil) (print-level nil)
17493 (formula-id (concat
17494 "formula-"
17495 (sha1
17496 (prin1-to-string
17497 (list latex-frag
17498 org-latex-to-mathml-convert-command)))))
17499 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17500 (formula-cache-dir (file-name-directory formula-cache)))
17502 (unless (file-directory-p formula-cache-dir)
17503 (make-directory formula-cache-dir t))
17505 (unless (file-exists-p formula-cache)
17506 (org-create-math-formula latex-frag formula-cache))
17508 (if (file-exists-p formula-cache)
17509 ;; Successful conversion. Return the link to MathML file.
17510 (org-add-props
17511 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17512 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17513 'org-latex-src-embed-type (if latex-frag-type
17514 'paragraph 'character)))
17515 ;; Failed conversion. Return the LaTeX fragment verbatim
17516 (add-text-properties
17517 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17518 latex-frag)))
17520 (defun org-create-formula-image (string tofile options buffer &optional type)
17521 "Create an image from LaTeX source using dvipng or convert.
17522 This function calls either `org-create-formula-image-with-dvipng'
17523 or `org-create-formula-image-with-imagemagick' depending on the
17524 value of `org-latex-create-formula-image-program' or on the value
17525 of the optional TYPE variable.
17527 Note: ultimately these two function should be combined as they
17528 share a good deal of logic."
17529 (org-check-external-command
17530 "latex" "needed to convert LaTeX fragments to images")
17531 (funcall
17532 (case (or type org-latex-create-formula-image-program)
17533 ('dvipng
17534 (org-check-external-command
17535 "dvipng" "needed to convert LaTeX fragments to images")
17536 #'org-create-formula-image-with-dvipng)
17537 ('imagemagick
17538 (org-check-external-command
17539 "convert" "you need to install imagemagick")
17540 #'org-create-formula-image-with-imagemagick)
17541 (t (error
17542 "invalid value of `org-latex-create-formula-image-program'")))
17543 string tofile options buffer))
17545 ;; This function borrows from Ganesh Swami's latex2png.el
17546 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17547 "This calls dvipng."
17548 (require 'org-latex)
17549 (let* ((tmpdir (if (featurep 'xemacs)
17550 (temp-directory)
17551 temporary-file-directory))
17552 (texfilebase (make-temp-name
17553 (expand-file-name "orgtex" tmpdir)))
17554 (texfile (concat texfilebase ".tex"))
17555 (dvifile (concat texfilebase ".dvi"))
17556 (pngfile (concat texfilebase ".png"))
17557 (fnh (if (featurep 'xemacs)
17558 (font-height (face-font 'default))
17559 (face-attribute 'default :height nil)))
17560 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17561 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17562 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17563 "Black"))
17564 (bg (or (plist-get options (if buffer :background :html-background))
17565 "Transparent")))
17566 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
17567 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
17568 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
17569 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
17570 (with-temp-file texfile
17571 (insert (org-splice-latex-header
17572 org-format-latex-header
17573 org-export-latex-default-packages-alist
17574 org-export-latex-packages-alist t
17575 org-format-latex-header-extra))
17576 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17577 (require 'org-latex)
17578 (org-export-latex-fix-inputenc))
17579 (let ((dir default-directory))
17580 (condition-case nil
17581 (progn
17582 (cd tmpdir)
17583 (call-process "latex" nil nil nil texfile))
17584 (error nil))
17585 (cd dir))
17586 (if (not (file-exists-p dvifile))
17587 (progn (message "Failed to create dvi file from %s" texfile) nil)
17588 (condition-case nil
17589 (if (featurep 'xemacs)
17590 (call-process "dvipng" nil nil nil
17591 "-fg" fg "-bg" bg
17592 "-T" "tight"
17593 "-o" pngfile
17594 dvifile)
17595 (call-process "dvipng" nil nil nil
17596 "-fg" fg "-bg" bg
17597 "-D" dpi
17598 ;;"-x" scale "-y" scale
17599 "-T" "tight"
17600 "-o" pngfile
17601 dvifile))
17602 (error nil))
17603 (if (not (file-exists-p pngfile))
17604 (if org-format-latex-signal-error
17605 (error "Failed to create png file from %s" texfile)
17606 (message "Failed to create png file from %s" texfile)
17607 nil)
17608 ;; Use the requested file name and clean up
17609 (copy-file pngfile tofile 'replace)
17610 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17611 (if (file-exists-p (concat texfilebase e))
17612 (delete-file (concat texfilebase e))))
17613 pngfile))))
17615 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17616 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17617 "This calls convert, which is included into imagemagick."
17618 (require 'org-latex)
17619 (let* ((tmpdir (if (featurep 'xemacs)
17620 (temp-directory)
17621 temporary-file-directory))
17622 (texfilebase (make-temp-name
17623 (expand-file-name "orgtex" tmpdir)))
17624 (texfile (concat texfilebase ".tex"))
17625 (pdffile (concat texfilebase ".pdf"))
17626 (pngfile (concat texfilebase ".png"))
17627 (fnh (if (featurep 'xemacs)
17628 (font-height (face-font 'default))
17629 (face-attribute 'default :height nil)))
17630 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17631 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17632 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17633 "black"))
17634 (bg (or (plist-get options (if buffer :background :html-background))
17635 "white")))
17636 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17637 (setq fg (org-latex-color-format fg)))
17638 (if (eq bg 'default) (setq bg (org-latex-color :background))
17639 (setq bg (org-latex-color-format
17640 (if (string= bg "Transparent") "white" bg))))
17641 (with-temp-file texfile
17642 (insert (org-splice-latex-header
17643 org-format-latex-header
17644 org-export-latex-default-packages-alist
17645 org-export-latex-packages-alist t
17646 org-format-latex-header-extra))
17647 (insert "\n\\begin{document}\n"
17648 "\\definecolor{fg}{rgb}{" fg "}\n"
17649 "\\definecolor{bg}{rgb}{" bg "}\n"
17650 "\n\\pagecolor{bg}\n"
17651 "\n{\\color{fg}\n"
17652 string
17653 "\n}\n"
17654 "\n\\end{document}\n" )
17655 (require 'org-latex)
17656 (org-export-latex-fix-inputenc))
17657 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17658 (condition-case nil
17659 (progn
17660 (cd tmpdir)
17661 (setq cmds org-latex-to-pdf-process)
17662 (while cmds
17663 (setq latex-frags-cmds (pop cmds))
17664 (if (listp latex-frags-cmds)
17665 (setq cmds nil)
17666 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17667 (while latex-frags-cmds
17668 (setq cmd (pop latex-frags-cmds))
17669 (while (string-match "%b" cmd)
17670 (setq cmd (replace-match
17671 (save-match-data
17672 (shell-quote-argument texfile))
17673 t t cmd)))
17674 (while (string-match "%f" cmd)
17675 (setq cmd (replace-match
17676 (save-match-data
17677 (shell-quote-argument (file-name-nondirectory texfile)))
17678 t t cmd)))
17679 (while (string-match "%o" cmd)
17680 (setq cmd (replace-match
17681 (save-match-data
17682 (shell-quote-argument (file-name-directory texfile)))
17683 t t cmd)))
17684 (setq cmd (split-string cmd))
17685 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17686 (error nil))
17687 (cd dir))
17688 (if (not (file-exists-p pdffile))
17689 (progn (message "Failed to create pdf file from %s" texfile) nil)
17690 (condition-case nil
17691 (if (featurep 'xemacs)
17692 (call-process "convert" nil nil nil
17693 "-density" "96"
17694 "-trim"
17695 "-antialias"
17696 pdffile
17697 "-quality" "100"
17698 ;; "-sharpen" "0x1.0"
17699 pngfile)
17700 (call-process "convert" nil nil nil
17701 "-density" dpi
17702 "-trim"
17703 "-antialias"
17704 pdffile
17705 "-quality" "100"
17706 ; "-sharpen" "0x1.0"
17707 pngfile))
17708 (error nil))
17709 (if (not (file-exists-p pngfile))
17710 (if org-format-latex-signal-error
17711 (error "Failed to create png file from %s" texfile)
17712 (message "Failed to create png file from %s" texfile)
17713 nil)
17714 ;; Use the requested file name and clean up
17715 (copy-file pngfile tofile 'replace)
17716 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17717 (if (file-exists-p (concat texfilebase e))
17718 (delete-file (concat texfilebase e))))
17719 pngfile))))
17721 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17722 "Fill a LaTeX header template TPL.
17723 In the template, the following place holders will be recognized:
17725 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17726 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17727 [PACKAGES] \\usepackage statements for PKG
17728 [NO-PACKAGES] do not include PKG
17729 [EXTRA] the string EXTRA
17730 [NO-EXTRA] do not include EXTRA
17732 For backward compatibility, if both the positive and the negative place
17733 holder is missing, the positive one (without the \"NO-\") will be
17734 assumed to be present at the end of the template.
17735 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17736 EXTRA is a string.
17737 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17738 (let (rpl (end ""))
17739 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17740 (setq rpl (if (or (match-end 1) (not def-pkg))
17741 "" (org-latex-packages-to-string def-pkg snippets-p t))
17742 tpl (replace-match rpl t t tpl))
17743 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17745 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17746 (setq rpl (if (or (match-end 1) (not pkg))
17747 "" (org-latex-packages-to-string pkg snippets-p t))
17748 tpl (replace-match rpl t t tpl))
17749 (if pkg (setq end
17750 (concat end "\n"
17751 (org-latex-packages-to-string pkg snippets-p)))))
17753 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17754 (setq rpl (if (or (match-end 1) (not extra))
17755 "" (concat extra "\n"))
17756 tpl (replace-match rpl t t tpl))
17757 (if (and extra (string-match "\\S-" extra))
17758 (setq end (concat end "\n" extra))))
17760 (if (string-match "\\S-" end)
17761 (concat tpl "\n" end)
17762 tpl)))
17764 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17765 "Turn an alist of packages into a string with the \\usepackage macros."
17766 (setq pkg (mapconcat (lambda(p)
17767 (cond
17768 ((stringp p) p)
17769 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17770 (format "%% Package %s omitted" (cadr p)))
17771 ((equal "" (car p))
17772 (format "\\usepackage{%s}" (cadr p)))
17774 (format "\\usepackage[%s]{%s}"
17775 (car p) (cadr p)))))
17777 "\n"))
17778 (if newline (concat pkg "\n") pkg))
17780 (defun org-dvipng-color (attr)
17781 "Return a RGB color specification for dvipng."
17782 (apply 'format "rgb %s %s %s"
17783 (mapcar 'org-normalize-color
17784 (if (featurep 'xemacs)
17785 (color-rgb-components
17786 (face-property 'default
17787 (cond ((eq attr :foreground) 'foreground)
17788 ((eq attr :background) 'background))))
17789 (color-values (face-attribute 'default attr nil))))))
17791 (defun org-dvipng-color-format (color-name)
17792 "Convert COLOR-NAME to a RGB color value for dvipng."
17793 (apply 'format "rgb %s %s %s"
17794 (mapcar 'org-normalize-color
17795 (color-values color-name))))
17797 (defun org-latex-color (attr)
17798 "Return a RGB color for the LaTeX color package."
17799 (apply 'format "%s,%s,%s"
17800 (mapcar 'org-normalize-color
17801 (if (featurep 'xemacs)
17802 (color-rgb-components
17803 (face-property 'default
17804 (cond ((eq attr :foreground) 'foreground)
17805 ((eq attr :background) 'background))))
17806 (color-values (face-attribute 'default attr nil))))))
17808 (defun org-latex-color-format (color-name)
17809 "Convert COLOR-NAME to a RGB color value."
17810 (apply 'format "%s,%s,%s"
17811 (mapcar 'org-normalize-color
17812 (color-values color-name))))
17814 (defun org-normalize-color (value)
17815 "Return string to be used as color value for an RGB component."
17816 (format "%g" (/ value 65535.0)))
17818 ;; Image display
17821 (defvar org-inline-image-overlays nil)
17822 (make-variable-buffer-local 'org-inline-image-overlays)
17824 (defun org-toggle-inline-images (&optional include-linked)
17825 "Toggle the display of inline images.
17826 INCLUDE-LINKED is passed to `org-display-inline-images'."
17827 (interactive "P")
17828 (if org-inline-image-overlays
17829 (progn
17830 (org-remove-inline-images)
17831 (message "Inline image display turned off"))
17832 (org-display-inline-images include-linked)
17833 (if (and (org-called-interactively-p)
17834 org-inline-image-overlays)
17835 (message "%d images displayed inline"
17836 (length org-inline-image-overlays))
17837 (message "No images to display inline"))))
17839 (defun org-redisplay-inline-images ()
17840 "Refresh the display of inline images."
17841 (interactive)
17842 (if (not org-inline-image-overlays)
17843 (org-toggle-inline-images)
17844 (org-toggle-inline-images)
17845 (org-toggle-inline-images)))
17847 (defun org-display-inline-images (&optional include-linked refresh beg end)
17848 "Display inline images.
17849 Normally only links without a description part are inlined, because this
17850 is how it will work for export. When INCLUDE-LINKED is set, also links
17851 with a description part will be inlined. This can be nice for a quick
17852 look at those images, but it does not reflect what exported files will look
17853 like.
17854 When REFRESH is set, refresh existing images between BEG and END.
17855 This will create new image displays only if necessary.
17856 BEG and END default to the buffer boundaries."
17857 (interactive "P")
17858 (unless refresh
17859 (org-remove-inline-images)
17860 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17861 (save-excursion
17862 (save-restriction
17863 (widen)
17864 (setq beg (or beg (point-min)) end (or end (point-max)))
17865 (goto-char beg)
17866 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17867 (substring (org-image-file-name-regexp) 0 -2)
17868 "\\)\\]" (if include-linked "" "\\]")))
17869 old file ov img type attrwidth width)
17870 (while (re-search-forward re end t)
17871 (setq old (get-char-property-and-overlay (match-beginning 1)
17872 'org-image-overlay)
17873 file (expand-file-name
17874 (concat (or (match-string 3) "") (match-string 4))))
17875 (when (image-type-available-p 'imagemagick)
17876 (setq attrwidth (if (or (listp org-image-actual-width)
17877 (null org-image-actual-width))
17878 (save-excursion
17879 (save-match-data
17880 (when (re-search-backward
17881 "#\\+ATTR.*width=\"\\([^\"]+\\)\""
17882 (save-excursion
17883 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
17884 (string-to-number (match-string 1))))))
17885 width (cond ((eq org-image-actual-width t) nil)
17886 ((null org-image-actual-width) attrwidth)
17887 ((numberp org-image-actual-width)
17888 org-image-actual-width)
17889 ((listp org-image-actual-width)
17890 (or attrwidth (car org-image-actual-width))))
17891 type (if width 'imagemagick)))
17892 (when (file-exists-p file)
17893 (if (and (car-safe old) refresh)
17894 (image-refresh (overlay-get (cdr old) 'display))
17895 (setq img (save-match-data (create-image file type nil :width width)))
17896 (when img
17897 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17898 (overlay-put ov 'display img)
17899 (overlay-put ov 'face 'default)
17900 (overlay-put ov 'org-image-overlay t)
17901 (overlay-put ov 'modification-hooks
17902 (list 'org-display-inline-remove-overlay))
17903 (push ov org-inline-image-overlays)))))))))
17905 (define-obsolete-function-alias
17906 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
17908 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
17909 "Remove inline-display overlay if a corresponding region is modified."
17910 (let ((inhibit-modification-hooks t))
17911 (when (and ov after)
17912 (delete ov org-inline-image-overlays)
17913 (delete-overlay ov))))
17915 (defun org-remove-inline-images ()
17916 "Remove inline display of images."
17917 (interactive)
17918 (mapc 'delete-overlay org-inline-image-overlays)
17919 (setq org-inline-image-overlays nil))
17921 ;;;; Key bindings
17923 ;; Outline functions from `outline-mode-prefix-map'
17924 ;; that can be remapped in Org:
17925 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17926 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17927 (define-key org-mode-map [remap outline-forward-same-level]
17928 'org-forward-heading-same-level)
17929 (define-key org-mode-map [remap outline-backward-same-level]
17930 'org-backward-heading-same-level)
17931 (define-key org-mode-map [remap show-branches]
17932 'org-kill-note-or-show-branches)
17933 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17934 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17935 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17937 ;; Outline functions from `outline-mode-prefix-map' that can not
17938 ;; be remapped in Org:
17940 ;; - the column "key binding" shows whether the Outline function is still
17941 ;; available in Org mode on the same key that it has been bound to in
17942 ;; Outline mode:
17943 ;; - "overridden": key used for a different functionality in Org mode
17944 ;; - else: key still bound to the same Outline function in Org mode
17946 ;; | Outline function | key binding | Org replacement |
17947 ;; |------------------------------------+-------------+-----------------------|
17948 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17949 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17950 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17951 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
17952 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17953 ;; | `show-entry' | overridden | no replacement |
17954 ;; | `show-children' | `C-c C-i' | visibility cycling |
17955 ;; | `show-branches' | `C-c C-k' | still same function |
17956 ;; | `show-subtree' | overridden | visibility cycling |
17957 ;; | `show-all' | overridden | no replacement |
17958 ;; | `hide-subtree' | overridden | visibility cycling |
17959 ;; | `hide-body' | overridden | no replacement |
17960 ;; | `hide-entry' | overridden | visibility cycling |
17961 ;; | `hide-leaves' | overridden | no replacement |
17962 ;; | `hide-sublevels' | overridden | no replacement |
17963 ;; | `hide-other' | overridden | no replacement |
17965 ;; Make `C-c C-x' a prefix key
17966 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17968 ;; TAB key with modifiers
17969 (org-defkey org-mode-map "\C-i" 'org-cycle)
17970 (org-defkey org-mode-map [(tab)] 'org-cycle)
17971 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17972 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17973 ;; The following line is necessary under Suse GNU/Linux
17974 (unless (featurep 'xemacs)
17975 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17976 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17977 (define-key org-mode-map [backtab] 'org-shifttab)
17979 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17980 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17981 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17983 ;; Cursor keys with modifiers
17984 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17985 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17986 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17987 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17989 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17990 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17991 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17992 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17994 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17995 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17996 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17997 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17999 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18000 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18001 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18002 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18004 ;; Babel keys
18005 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18006 (mapc (lambda (pair)
18007 (define-key org-babel-map (car pair) (cdr pair)))
18008 org-babel-key-bindings)
18010 ;;; Extra keys for tty access.
18011 ;; We only set them when really needed because otherwise the
18012 ;; menus don't show the simple keys
18014 (when (or org-use-extra-keys
18015 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18016 (not window-system))
18017 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18018 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18019 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18020 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18021 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18022 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18023 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18024 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18025 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18026 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18027 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18028 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18029 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18030 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18031 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18032 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18033 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18034 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18035 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18036 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18037 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18038 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18039 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18040 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18041 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18042 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18043 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18044 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18046 ;; All the other keys
18048 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18049 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18050 (if (boundp 'narrow-map)
18051 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18052 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18053 (if (boundp 'narrow-map)
18054 (org-defkey narrow-map "b" 'org-narrow-to-block)
18055 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18056 (if (boundp 'narrow-map)
18057 (org-defkey narrow-map "e" 'org-narrow-to-element)
18058 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18059 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18060 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18061 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18062 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18063 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18064 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18065 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18066 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18067 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18068 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18069 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18070 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18071 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18072 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18073 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18074 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18075 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18076 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18077 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18078 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18079 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18080 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18081 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18082 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18083 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18084 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18085 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18086 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18087 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18088 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18089 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18090 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18091 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18092 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18093 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18094 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18095 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18096 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18097 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18098 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18099 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18100 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18101 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18102 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18103 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18104 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18105 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18106 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18107 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18108 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18109 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18110 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18111 (org-defkey org-mode-map "\C-c^" 'org-sort)
18112 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18113 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18114 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18115 (org-defkey org-mode-map "\C-m" 'org-return)
18116 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18117 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18118 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18119 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18120 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18121 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18122 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18123 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18124 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18125 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18126 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18127 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18128 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18129 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
18130 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18131 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18132 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18133 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18134 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18135 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18136 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18137 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18138 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18140 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18141 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18142 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18144 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18145 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18146 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18147 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18148 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18149 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18150 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18151 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18152 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18153 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18154 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18155 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18156 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18157 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18158 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18159 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18160 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18161 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18162 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18163 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18164 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18165 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18167 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18168 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18169 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18170 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18171 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18173 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18175 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18177 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18178 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18180 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18183 (when (featurep 'xemacs)
18184 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18187 (defconst org-speed-commands-default
18189 ("Outline Navigation")
18190 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18191 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18192 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18193 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18194 ("u" . (org-speed-move-safe 'outline-up-heading))
18195 ("j" . org-goto)
18196 ("g" . (org-refile t))
18197 ("Outline Visibility")
18198 ("c" . org-cycle)
18199 ("C" . org-shifttab)
18200 (" " . org-display-outline-path)
18201 (":" . org-columns)
18202 ("Outline Structure Editing")
18203 ("U" . org-shiftmetaup)
18204 ("D" . org-shiftmetadown)
18205 ("r" . org-metaright)
18206 ("l" . org-metaleft)
18207 ("R" . org-shiftmetaright)
18208 ("L" . org-shiftmetaleft)
18209 ("i" . (progn (forward-char 1) (call-interactively
18210 'org-insert-heading-respect-content)))
18211 ("^" . org-sort)
18212 ("w" . org-refile)
18213 ("a" . org-archive-subtree-default-with-confirmation)
18214 ("." . org-mark-subtree)
18215 ("#" . org-toggle-comment)
18216 ("Clock Commands")
18217 ("I" . org-clock-in)
18218 ("O" . org-clock-out)
18219 ("Meta Data Editing")
18220 ("t" . org-todo)
18221 ("," . (org-priority))
18222 ("0" . (org-priority ?\ ))
18223 ("1" . (org-priority ?A))
18224 ("2" . (org-priority ?B))
18225 ("3" . (org-priority ?C))
18226 (";" . org-set-tags-command)
18227 ("e" . org-set-effort)
18228 ("E" . org-inc-effort)
18229 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18230 (org-entry-put (point) "APPT_WARNTIME" m)))
18231 ("Agenda Views etc")
18232 ("v" . org-agenda)
18233 ("/" . org-sparse-tree)
18234 ("Misc")
18235 ("o" . org-open-at-point)
18236 ("?" . org-speed-command-help)
18237 ("<" . (org-agenda-set-restriction-lock 'subtree))
18238 (">" . (org-agenda-remove-restriction-lock))
18240 "The default speed commands.")
18242 (defun org-print-speed-command (e)
18243 (if (> (length (car e)) 1)
18244 (progn
18245 (princ "\n")
18246 (princ (car e))
18247 (princ "\n")
18248 (princ (make-string (length (car e)) ?-))
18249 (princ "\n"))
18250 (princ (car e))
18251 (princ " ")
18252 (if (symbolp (cdr e))
18253 (princ (symbol-name (cdr e)))
18254 (prin1 (cdr e)))
18255 (princ "\n")))
18257 (defun org-speed-command-help ()
18258 "Show the available speed commands."
18259 (interactive)
18260 (if (not org-use-speed-commands)
18261 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18262 (with-output-to-temp-buffer "*Help*"
18263 (princ "User-defined Speed commands\n===========================\n")
18264 (mapc 'org-print-speed-command org-speed-commands-user)
18265 (princ "\n")
18266 (princ "Built-in Speed commands\n=======================\n")
18267 (mapc 'org-print-speed-command org-speed-commands-default))
18268 (with-current-buffer "*Help*"
18269 (setq truncate-lines t))))
18271 (defun org-speed-move-safe (cmd)
18272 "Execute CMD, but make sure that the cursor always ends up in a headline.
18273 If not, return to the original position and throw an error."
18274 (interactive)
18275 (let ((pos (point)))
18276 (call-interactively cmd)
18277 (unless (and (bolp) (org-at-heading-p))
18278 (goto-char pos)
18279 (error "Boundary reached while executing %s" cmd))))
18281 (defvar org-self-insert-command-undo-counter 0)
18283 (defvar org-table-auto-blank-field) ; defined in org-table.el
18284 (defvar org-speed-command nil)
18286 (define-obsolete-function-alias
18287 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18289 (defun org-speed-command-activate (keys)
18290 "Hook for activating single-letter speed commands.
18291 `org-speed-commands-default' specifies a minimal command set.
18292 Use `org-speed-commands-user' for further customization."
18293 (when (or (and (bolp) (looking-at org-outline-regexp))
18294 (and (functionp org-use-speed-commands)
18295 (funcall org-use-speed-commands)))
18296 (cdr (assoc keys (append org-speed-commands-user
18297 org-speed-commands-default)))))
18299 (define-obsolete-function-alias
18300 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18302 (defun org-babel-speed-command-activate (keys)
18303 "Hook for activating single-letter code block commands."
18304 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18305 (cdr (assoc keys org-babel-key-bindings))))
18307 (defcustom org-speed-command-hook
18308 '(org-speed-command-default-hook org-babel-speed-command-hook)
18309 "Hook for activating speed commands at strategic locations.
18310 Hook functions are called in sequence until a valid handler is
18311 found.
18313 Each hook takes a single argument, a user-pressed command key
18314 which is also a `self-insert-command' from the global map.
18316 Within the hook, examine the cursor position and the command key
18317 and return nil or a valid handler as appropriate. Handler could
18318 be one of an interactive command, a function, or a form.
18320 Set `org-use-speed-commands' to non-nil value to enable this
18321 hook. The default setting is `org-speed-command-activate'."
18322 :group 'org-structure
18323 :version "24.1"
18324 :type 'hook)
18326 (defun org-self-insert-command (N)
18327 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18328 If the cursor is in a table looking at whitespace, the whitespace is
18329 overwritten, and the table is not marked as requiring realignment."
18330 (interactive "p")
18331 (org-check-before-invisible-edit 'insert)
18332 (cond
18333 ((and org-use-speed-commands
18334 (setq org-speed-command
18335 (run-hook-with-args-until-success
18336 'org-speed-command-hook (this-command-keys))))
18337 (cond
18338 ((commandp org-speed-command)
18339 (setq this-command org-speed-command)
18340 (call-interactively org-speed-command))
18341 ((functionp org-speed-command)
18342 (funcall org-speed-command))
18343 ((and org-speed-command (listp org-speed-command))
18344 (eval org-speed-command))
18345 (t (let (org-use-speed-commands)
18346 (call-interactively 'org-self-insert-command)))))
18347 ((and
18348 (org-table-p)
18349 (progn
18350 ;; check if we blank the field, and if that triggers align
18351 (and (featurep 'org-table) org-table-auto-blank-field
18352 (member last-command
18353 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18354 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18355 ;; got extra space, this field does not determine column width
18356 (let (org-table-may-need-update) (org-table-blank-field))
18357 ;; no extra space, this field may determine column width
18358 (org-table-blank-field)))
18360 (eq N 1)
18361 (looking-at "[^|\n]* |"))
18362 (let (org-table-may-need-update)
18363 (goto-char (1- (match-end 0)))
18364 (backward-delete-char 1)
18365 (goto-char (match-beginning 0))
18366 (self-insert-command N)))
18368 (setq org-table-may-need-update t)
18369 (self-insert-command N)
18370 (org-fix-tags-on-the-fly)
18371 (if org-self-insert-cluster-for-undo
18372 (if (not (eq last-command 'org-self-insert-command))
18373 (setq org-self-insert-command-undo-counter 1)
18374 (if (>= org-self-insert-command-undo-counter 20)
18375 (setq org-self-insert-command-undo-counter 1)
18376 (and (> org-self-insert-command-undo-counter 0)
18377 buffer-undo-list (listp buffer-undo-list)
18378 (not (cadr buffer-undo-list)) ; remove nil entry
18379 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18380 (setq org-self-insert-command-undo-counter
18381 (1+ org-self-insert-command-undo-counter))))))))
18383 (defun org-check-before-invisible-edit (kind)
18384 "Check is editing if kind KIND would be dangerous with invisible text around.
18385 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18386 ;; First, try to get out of here as quickly as possible, to reduce overhead
18387 (if (and org-catch-invisible-edits
18388 (or (not (boundp 'visible-mode)) (not visible-mode))
18389 (or (get-char-property (point) 'invisible)
18390 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18391 ;; OK, we need to take a closer look
18392 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18393 (invisible-before-point (if (bobp) nil (get-char-property
18394 (1- (point)) 'invisible)))
18395 (border-and-ok-direction
18397 ;; Check if we are acting predictably before invisible text
18398 (and invisible-at-point (not invisible-before-point)
18399 (memq kind '(insert delete-backward)))
18400 ;; Check if we are acting predictably after invisible text
18401 ;; This works not well, and I have turned it off. It seems
18402 ;; better to always show and stop after invisible text.
18403 ;; (and (not invisible-at-point) invisible-before-point
18404 ;; (memq kind '(insert delete)))
18406 (when (or (memq invisible-at-point '(outline org-hide-block t))
18407 (memq invisible-before-point '(outline org-hide-block t)))
18408 (if (eq org-catch-invisible-edits 'error)
18409 (error "Editing in invisible areas is prohibited - make visible first"))
18410 (if (and org-custom-properties-overlays
18411 (y-or-n-p "Display invisible properties in this buffer? "))
18412 (org-toggle-custom-properties-visibility)
18413 ;; Make the area visible
18414 (save-excursion
18415 (if invisible-before-point
18416 (goto-char (previous-single-char-property-change
18417 (point) 'invisible)))
18418 (org-cycle))
18419 (cond
18420 ((eq org-catch-invisible-edits 'show)
18421 ;; That's it, we do the edit after showing
18422 (message
18423 "Unfolding invisible region around point before editing")
18424 (sit-for 1))
18425 ((and (eq org-catch-invisible-edits 'smart)
18426 border-and-ok-direction)
18427 (message "Unfolding invisible region around point before editing"))
18429 ;; Don't do the edit, make the user repeat it in full visibility
18430 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18432 (defun org-fix-tags-on-the-fly ()
18433 (when (and (equal (char-after (point-at-bol)) ?*)
18434 (org-at-heading-p))
18435 (org-align-tags-here org-tags-column)))
18437 (defun org-delete-backward-char (N)
18438 "Like `delete-backward-char', insert whitespace at field end in tables.
18439 When deleting backwards, in tables this function will insert whitespace in
18440 front of the next \"|\" separator, to keep the table aligned. The table will
18441 still be marked for re-alignment if the field did fill the entire column,
18442 because, in this case the deletion might narrow the column."
18443 (interactive "p")
18444 (org-check-before-invisible-edit 'delete-backward)
18445 (if (and (org-table-p)
18446 (eq N 1)
18447 (string-match "|" (buffer-substring (point-at-bol) (point)))
18448 (looking-at ".*?|"))
18449 (let ((pos (point))
18450 (noalign (looking-at "[^|\n\r]* |"))
18451 (c org-table-may-need-update))
18452 (backward-delete-char N)
18453 (if (not overwrite-mode)
18454 (progn
18455 (skip-chars-forward "^|")
18456 (insert " ")
18457 (goto-char (1- pos))))
18458 ;; noalign: if there were two spaces at the end, this field
18459 ;; does not determine the width of the column.
18460 (if noalign (setq org-table-may-need-update c)))
18461 (backward-delete-char N)
18462 (org-fix-tags-on-the-fly)))
18464 (defun org-delete-char (N)
18465 "Like `delete-char', but insert whitespace at field end in tables.
18466 When deleting characters, in tables this function will insert whitespace in
18467 front of the next \"|\" separator, to keep the table aligned. The table will
18468 still be marked for re-alignment if the field did fill the entire column,
18469 because, in this case the deletion might narrow the column."
18470 (interactive "p")
18471 (org-check-before-invisible-edit 'delete)
18472 (if (and (org-table-p)
18473 (not (bolp))
18474 (not (= (char-after) ?|))
18475 (eq N 1))
18476 (if (looking-at ".*?|")
18477 (let ((pos (point))
18478 (noalign (looking-at "[^|\n\r]* |"))
18479 (c org-table-may-need-update))
18480 (replace-match (concat
18481 (substring (match-string 0) 1 -1)
18482 " |"))
18483 (goto-char pos)
18484 ;; noalign: if there were two spaces at the end, this field
18485 ;; does not determine the width of the column.
18486 (if noalign (setq org-table-may-need-update c)))
18487 (delete-char N))
18488 (delete-char N)
18489 (org-fix-tags-on-the-fly)))
18491 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18492 (put 'org-self-insert-command 'delete-selection t)
18493 (put 'orgtbl-self-insert-command 'delete-selection t)
18494 (put 'org-delete-char 'delete-selection 'supersede)
18495 (put 'org-delete-backward-char 'delete-selection 'supersede)
18496 (put 'org-yank 'delete-selection 'yank)
18498 ;; Make `flyspell-mode' delay after some commands
18499 (put 'org-self-insert-command 'flyspell-delayed t)
18500 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18501 (put 'org-delete-char 'flyspell-delayed t)
18502 (put 'org-delete-backward-char 'flyspell-delayed t)
18504 ;; Make pabbrev-mode expand after org-mode commands
18505 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18506 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18508 ;; How to do this: Measure non-white length of current string
18509 ;; If equal to column width, we should realign.
18511 (defun org-remap (map &rest commands)
18512 "In MAP, remap the functions given in COMMANDS.
18513 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18514 (let (new old)
18515 (while commands
18516 (setq old (pop commands) new (pop commands))
18517 (if (fboundp 'command-remapping)
18518 (org-defkey map (vector 'remap old) new)
18519 (substitute-key-definition old new map global-map)))))
18521 (when (eq org-enable-table-editor 'optimized)
18522 ;; If the user wants maximum table support, we need to hijack
18523 ;; some standard editing functions
18524 (org-remap org-mode-map
18525 'self-insert-command 'org-self-insert-command
18526 'delete-char 'org-delete-char
18527 'delete-backward-char 'org-delete-backward-char)
18528 (org-defkey org-mode-map "|" 'org-force-self-insert))
18530 (defvar org-ctrl-c-ctrl-c-hook nil
18531 "Hook for functions attaching themselves to `C-c C-c'.
18533 This can be used to add additional functionality to the C-c C-c
18534 key which executes context-dependent commands. This hook is run
18535 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18536 run after the last test.
18538 Each function will be called with no arguments. The function
18539 must check if the context is appropriate for it to act. If yes,
18540 it should do its thing and then return a non-nil value. If the
18541 context is wrong, just do nothing and return nil.")
18543 (defvar org-ctrl-c-ctrl-c-final-hook nil
18544 "Hook for functions attaching themselves to `C-c C-c'.
18546 This can be used to add additional functionality to the C-c C-c
18547 key which executes context-dependent commands. This hook is run
18548 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18549 before the first test.
18551 Each function will be called with no arguments. The function
18552 must check if the context is appropriate for it to act. If yes,
18553 it should do its thing and then return a non-nil value. If the
18554 context is wrong, just do nothing and return nil.")
18556 (defvar org-tab-first-hook nil
18557 "Hook for functions to attach themselves to TAB.
18558 See `org-ctrl-c-ctrl-c-hook' for more information.
18559 This hook runs as the first action when TAB is pressed, even before
18560 `org-cycle' messes around with the `outline-regexp' to cater for
18561 inline tasks and plain list item folding.
18562 If any function in this hook returns t, any other actions that
18563 would have been caused by TAB (such as table field motion or visibility
18564 cycling) will not occur.")
18566 (defvar org-tab-after-check-for-table-hook nil
18567 "Hook for functions to attach themselves to TAB.
18568 See `org-ctrl-c-ctrl-c-hook' for more information.
18569 This hook runs after it has been established that the cursor is not in a
18570 table, but before checking if the cursor is in a headline or if global cycling
18571 should be done.
18572 If any function in this hook returns t, not other actions like visibility
18573 cycling will be done.")
18575 (defvar org-tab-after-check-for-cycling-hook nil
18576 "Hook for functions to attach themselves to TAB.
18577 See `org-ctrl-c-ctrl-c-hook' for more information.
18578 This hook runs after it has been established that not table field motion and
18579 not visibility should be done because of current context. This is probably
18580 the place where a package like yasnippets can hook in.")
18582 (defvar org-tab-before-tab-emulation-hook nil
18583 "Hook for functions to attach themselves to TAB.
18584 See `org-ctrl-c-ctrl-c-hook' for more information.
18585 This hook runs after every other options for TAB have been exhausted, but
18586 before indentation and \t insertion takes place.")
18588 (defvar org-metaleft-hook nil
18589 "Hook for functions attaching themselves to `M-left'.
18590 See `org-ctrl-c-ctrl-c-hook' for more information.")
18591 (defvar org-metaright-hook nil
18592 "Hook for functions attaching themselves to `M-right'.
18593 See `org-ctrl-c-ctrl-c-hook' for more information.")
18594 (defvar org-metaup-hook nil
18595 "Hook for functions attaching themselves to `M-up'.
18596 See `org-ctrl-c-ctrl-c-hook' for more information.")
18597 (defvar org-metadown-hook nil
18598 "Hook for functions attaching themselves to `M-down'.
18599 See `org-ctrl-c-ctrl-c-hook' for more information.")
18600 (defvar org-shiftmetaleft-hook nil
18601 "Hook for functions attaching themselves to `M-S-left'.
18602 See `org-ctrl-c-ctrl-c-hook' for more information.")
18603 (defvar org-shiftmetaright-hook nil
18604 "Hook for functions attaching themselves to `M-S-right'.
18605 See `org-ctrl-c-ctrl-c-hook' for more information.")
18606 (defvar org-shiftmetaup-hook nil
18607 "Hook for functions attaching themselves to `M-S-up'.
18608 See `org-ctrl-c-ctrl-c-hook' for more information.")
18609 (defvar org-shiftmetadown-hook nil
18610 "Hook for functions attaching themselves to `M-S-down'.
18611 See `org-ctrl-c-ctrl-c-hook' for more information.")
18612 (defvar org-metareturn-hook nil
18613 "Hook for functions attaching themselves to `M-RET'.
18614 See `org-ctrl-c-ctrl-c-hook' for more information.")
18615 (defvar org-shiftup-hook nil
18616 "Hook for functions attaching themselves to `S-up'.
18617 See `org-ctrl-c-ctrl-c-hook' for more information.")
18618 (defvar org-shiftup-final-hook nil
18619 "Hook for functions attaching themselves to `S-up'.
18620 This one runs after all other options except shift-select have been excluded.
18621 See `org-ctrl-c-ctrl-c-hook' for more information.")
18622 (defvar org-shiftdown-hook nil
18623 "Hook for functions attaching themselves to `S-down'.
18624 See `org-ctrl-c-ctrl-c-hook' for more information.")
18625 (defvar org-shiftdown-final-hook nil
18626 "Hook for functions attaching themselves to `S-down'.
18627 This one runs after all other options except shift-select have been excluded.
18628 See `org-ctrl-c-ctrl-c-hook' for more information.")
18629 (defvar org-shiftleft-hook nil
18630 "Hook for functions attaching themselves to `S-left'.
18631 See `org-ctrl-c-ctrl-c-hook' for more information.")
18632 (defvar org-shiftleft-final-hook nil
18633 "Hook for functions attaching themselves to `S-left'.
18634 This one runs after all other options except shift-select have been excluded.
18635 See `org-ctrl-c-ctrl-c-hook' for more information.")
18636 (defvar org-shiftright-hook nil
18637 "Hook for functions attaching themselves to `S-right'.
18638 See `org-ctrl-c-ctrl-c-hook' for more information.")
18639 (defvar org-shiftright-final-hook nil
18640 "Hook for functions attaching themselves to `S-right'.
18641 This one runs after all other options except shift-select have been excluded.
18642 See `org-ctrl-c-ctrl-c-hook' for more information.")
18644 (defun org-modifier-cursor-error ()
18645 "Throw an error, a modified cursor command was applied in wrong context."
18646 (error "This command is active in special context like tables, headlines or items"))
18648 (defun org-shiftselect-error ()
18649 "Throw an error because Shift-Cursor command was applied in wrong context."
18650 (if (and (boundp 'shift-select-mode) shift-select-mode)
18651 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18652 (error "This command works only in special context like headlines or timestamps")))
18654 (defun org-call-for-shift-select (cmd)
18655 (let ((this-command-keys-shift-translated t))
18656 (call-interactively cmd)))
18658 (defun org-shifttab (&optional arg)
18659 "Global visibility cycling or move to previous table field.
18660 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18661 on context.
18662 See the individual commands for more information."
18663 (interactive "P")
18664 (cond
18665 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18666 ((integerp arg)
18667 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18668 (message "Content view to level: %d" arg)
18669 (org-content (prefix-numeric-value arg2))
18670 (setq org-cycle-global-status 'overview)))
18671 (t (call-interactively 'org-global-cycle))))
18673 (defun org-shiftmetaleft ()
18674 "Promote subtree or delete table column.
18675 Calls `org-promote-subtree', `org-outdent-item-tree', or
18676 `org-table-delete-column', depending on context. See the
18677 individual commands for more information."
18678 (interactive)
18679 (cond
18680 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18681 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18682 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18683 ((if (not (org-region-active-p)) (org-at-item-p)
18684 (save-excursion (goto-char (region-beginning))
18685 (org-at-item-p)))
18686 (call-interactively 'org-outdent-item-tree))
18687 (t (org-modifier-cursor-error))))
18689 (defun org-shiftmetaright ()
18690 "Demote subtree or insert table column.
18691 Calls `org-demote-subtree', `org-indent-item-tree', or
18692 `org-table-insert-column', depending on context. See the
18693 individual commands for more information."
18694 (interactive)
18695 (cond
18696 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18697 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18698 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18699 ((if (not (org-region-active-p)) (org-at-item-p)
18700 (save-excursion (goto-char (region-beginning))
18701 (org-at-item-p)))
18702 (call-interactively 'org-indent-item-tree))
18703 (t (org-modifier-cursor-error))))
18705 (defun org-shiftmetaup (&optional arg)
18706 "Move subtree up or kill table row.
18707 Calls `org-move-subtree-up' or `org-table-kill-row' or
18708 `org-move-item-up' or `org-timestamp-up', depending on context.
18709 See the individual commands for more information."
18710 (interactive "P")
18711 (cond
18712 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18713 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18714 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18715 ((org-at-item-p) (call-interactively 'org-move-item-up))
18716 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18717 (call-interactively 'org-timestamp-up)))
18718 (t (org-modifier-cursor-error))))
18720 (defun org-shiftmetadown (&optional arg)
18721 "Move subtree down or insert table row.
18722 Calls `org-move-subtree-down' or `org-table-insert-row' or
18723 `org-move-item-down' or `org-timestamp-up', depending on context.
18724 See the individual commands for more information."
18725 (interactive "P")
18726 (cond
18727 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18728 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18729 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18730 ((org-at-item-p) (call-interactively 'org-move-item-down))
18731 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18732 (call-interactively 'org-timestamp-down)))
18733 (t (org-modifier-cursor-error))))
18735 (defsubst org-hidden-tree-error ()
18736 (error
18737 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18739 (defun org-metaleft (&optional arg)
18740 "Promote heading or move table column to left.
18741 Calls `org-do-promote' or `org-table-move-column', depending on context.
18742 With no specific context, calls the Emacs default `backward-word'.
18743 See the individual commands for more information."
18744 (interactive "P")
18745 (cond
18746 ((run-hook-with-args-until-success 'org-metaleft-hook))
18747 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18748 ((org-with-limited-levels
18749 (or (org-at-heading-p)
18750 (and (org-region-active-p)
18751 (save-excursion
18752 (goto-char (region-beginning))
18753 (org-at-heading-p)))))
18754 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18755 (call-interactively 'org-do-promote))
18756 ;; At an inline task.
18757 ((org-at-heading-p)
18758 (call-interactively 'org-inlinetask-promote))
18759 ((or (org-at-item-p)
18760 (and (org-region-active-p)
18761 (save-excursion
18762 (goto-char (region-beginning))
18763 (org-at-item-p))))
18764 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18765 (call-interactively 'org-outdent-item))
18766 (t (call-interactively 'backward-word))))
18768 (defun org-metaright (&optional arg)
18769 "Demote a subtree, a list item or move table column to right.
18770 In front of a drawer or a block keyword, indent it correctly.
18771 With no specific context, calls the Emacs default `forward-word'.
18772 See the individual commands for more information."
18773 (interactive "P")
18774 (cond
18775 ((run-hook-with-args-until-success 'org-metaright-hook))
18776 ((org-at-table-p) (call-interactively 'org-table-move-column))
18777 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18778 ((org-at-block-p) (call-interactively 'org-indent-block))
18779 ((org-with-limited-levels
18780 (or (org-at-heading-p)
18781 (and (org-region-active-p)
18782 (save-excursion
18783 (goto-char (region-beginning))
18784 (org-at-heading-p)))))
18785 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18786 (call-interactively 'org-do-demote))
18787 ;; At an inline task.
18788 ((org-at-heading-p)
18789 (call-interactively 'org-inlinetask-demote))
18790 ((or (org-at-item-p)
18791 (and (org-region-active-p)
18792 (save-excursion
18793 (goto-char (region-beginning))
18794 (org-at-item-p))))
18795 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18796 (call-interactively 'org-indent-item))
18797 (t (call-interactively 'forward-word))))
18799 (defun org-check-for-hidden (what)
18800 "Check if there are hidden headlines/items in the current visual line.
18801 WHAT can be either `headlines' or `items'. If the current line is
18802 an outline or item heading and it has a folded subtree below it,
18803 this function returns t, nil otherwise."
18804 (let ((re (cond
18805 ((eq what 'headlines) org-outline-regexp-bol)
18806 ((eq what 'items) (org-item-beginning-re))
18807 (t (error "This should not happen"))))
18808 beg end)
18809 (save-excursion
18810 (catch 'exit
18811 (unless (org-region-active-p)
18812 (setq beg (point-at-bol))
18813 (beginning-of-line 2)
18814 (while (and (not (eobp)) ;; this is like `next-line'
18815 (get-char-property (1- (point)) 'invisible))
18816 (beginning-of-line 2))
18817 (setq end (point))
18818 (goto-char beg)
18819 (goto-char (point-at-eol))
18820 (setq end (max end (point)))
18821 (while (re-search-forward re end t)
18822 (if (get-char-property (match-beginning 0) 'invisible)
18823 (throw 'exit t))))
18824 nil))))
18826 (defun org-metaup (&optional arg)
18827 "Move subtree up or move table row up.
18828 Calls `org-move-subtree-up' or `org-table-move-row' or
18829 `org-move-item-up', depending on context. See the individual commands
18830 for more information."
18831 (interactive "P")
18832 (cond
18833 ((run-hook-with-args-until-success 'org-metaup-hook))
18834 ((org-region-active-p)
18835 (let* ((a (min (region-beginning) (region-end)))
18836 (b (1- (max (region-beginning) (region-end))))
18837 (c (save-excursion (goto-char a)
18838 (move-beginning-of-line 0)))
18839 (d (save-excursion (goto-char a)
18840 (move-end-of-line 0) (point))))
18841 (transpose-regions a b c d)
18842 (goto-char c)))
18843 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18844 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18845 ((org-at-item-p) (call-interactively 'org-move-item-up))
18846 (t (org-drag-element-backward))))
18848 (defun org-metadown (&optional arg)
18849 "Move subtree down or move table row down.
18850 Calls `org-move-subtree-down' or `org-table-move-row' or
18851 `org-move-item-down', depending on context. See the individual
18852 commands for more information."
18853 (interactive "P")
18854 (cond
18855 ((run-hook-with-args-until-success 'org-metadown-hook))
18856 ((org-region-active-p)
18857 (let* ((a (min (region-beginning) (region-end)))
18858 (b (max (region-beginning) (region-end)))
18859 (c (save-excursion (goto-char b)
18860 (move-beginning-of-line 1)))
18861 (d (save-excursion (goto-char b)
18862 (move-end-of-line 1) (1+ (point)))))
18863 (transpose-regions a b c d)
18864 (goto-char d)))
18865 ((org-at-table-p) (call-interactively 'org-table-move-row))
18866 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18867 ((org-at-item-p) (call-interactively 'org-move-item-down))
18868 (t (org-drag-element-forward))))
18870 (defun org-shiftup (&optional arg)
18871 "Increase item in timestamp or increase priority of current headline.
18872 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18873 depending on context. See the individual commands for more information."
18874 (interactive "P")
18875 (cond
18876 ((run-hook-with-args-until-success 'org-shiftup-hook))
18877 ((and org-support-shift-select (org-region-active-p))
18878 (org-call-for-shift-select 'previous-line))
18879 ((org-at-timestamp-p t)
18880 (call-interactively (if org-edit-timestamp-down-means-later
18881 'org-timestamp-down 'org-timestamp-up)))
18882 ((and (not (eq org-support-shift-select 'always))
18883 org-enable-priority-commands
18884 (org-at-heading-p))
18885 (call-interactively 'org-priority-up))
18886 ((and (not org-support-shift-select) (org-at-item-p))
18887 (call-interactively 'org-previous-item))
18888 ((org-clocktable-try-shift 'up arg))
18889 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18890 (org-support-shift-select
18891 (org-call-for-shift-select 'previous-line))
18892 (t (org-shiftselect-error))))
18894 (defun org-shiftdown (&optional arg)
18895 "Decrease item in timestamp or decrease priority of current headline.
18896 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18897 depending on context. See the individual commands for more information."
18898 (interactive "P")
18899 (cond
18900 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18901 ((and org-support-shift-select (org-region-active-p))
18902 (org-call-for-shift-select 'next-line))
18903 ((org-at-timestamp-p t)
18904 (call-interactively (if org-edit-timestamp-down-means-later
18905 'org-timestamp-up 'org-timestamp-down)))
18906 ((and (not (eq org-support-shift-select 'always))
18907 org-enable-priority-commands
18908 (org-at-heading-p))
18909 (call-interactively 'org-priority-down))
18910 ((and (not org-support-shift-select) (org-at-item-p))
18911 (call-interactively 'org-next-item))
18912 ((org-clocktable-try-shift 'down arg))
18913 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18914 (org-support-shift-select
18915 (org-call-for-shift-select 'next-line))
18916 (t (org-shiftselect-error))))
18918 (defun org-shiftright (&optional arg)
18919 "Cycle the thing at point or in the current line, depending on context.
18920 Depending on context, this does one of the following:
18922 - switch a timestamp at point one day into the future
18923 - on a headline, switch to the next TODO keyword.
18924 - on an item, switch entire list to the next bullet type
18925 - on a property line, switch to the next allowed value
18926 - on a clocktable definition line, move time block into the future"
18927 (interactive "P")
18928 (cond
18929 ((run-hook-with-args-until-success 'org-shiftright-hook))
18930 ((and org-support-shift-select (org-region-active-p))
18931 (org-call-for-shift-select 'forward-char))
18932 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18933 ((and (not (eq org-support-shift-select 'always))
18934 (org-at-heading-p))
18935 (let ((org-inhibit-logging
18936 (not org-treat-S-cursor-todo-selection-as-state-change))
18937 (org-inhibit-blocking
18938 (not org-treat-S-cursor-todo-selection-as-state-change)))
18939 (org-call-with-arg 'org-todo 'right)))
18940 ((or (and org-support-shift-select
18941 (not (eq org-support-shift-select 'always))
18942 (org-at-item-bullet-p))
18943 (and (not org-support-shift-select) (org-at-item-p)))
18944 (org-call-with-arg 'org-cycle-list-bullet nil))
18945 ((and (not (eq org-support-shift-select 'always))
18946 (org-at-property-p))
18947 (call-interactively 'org-property-next-allowed-value))
18948 ((org-clocktable-try-shift 'right arg))
18949 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18950 (org-support-shift-select
18951 (org-call-for-shift-select 'forward-char))
18952 (t (org-shiftselect-error))))
18954 (defun org-shiftleft (&optional arg)
18955 "Cycle the thing at point or in the current line, depending on context.
18956 Depending on context, this does one of the following:
18958 - switch a timestamp at point one day into the past
18959 - on a headline, switch to the previous TODO keyword.
18960 - on an item, switch entire list to the previous bullet type
18961 - on a property line, switch to the previous allowed value
18962 - on a clocktable definition line, move time block into the past"
18963 (interactive "P")
18964 (cond
18965 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18966 ((and org-support-shift-select (org-region-active-p))
18967 (org-call-for-shift-select 'backward-char))
18968 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18969 ((and (not (eq org-support-shift-select 'always))
18970 (org-at-heading-p))
18971 (let ((org-inhibit-logging
18972 (not org-treat-S-cursor-todo-selection-as-state-change))
18973 (org-inhibit-blocking
18974 (not org-treat-S-cursor-todo-selection-as-state-change)))
18975 (org-call-with-arg 'org-todo 'left)))
18976 ((or (and org-support-shift-select
18977 (not (eq org-support-shift-select 'always))
18978 (org-at-item-bullet-p))
18979 (and (not org-support-shift-select) (org-at-item-p)))
18980 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18981 ((and (not (eq org-support-shift-select 'always))
18982 (org-at-property-p))
18983 (call-interactively 'org-property-previous-allowed-value))
18984 ((org-clocktable-try-shift 'left arg))
18985 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18986 (org-support-shift-select
18987 (org-call-for-shift-select 'backward-char))
18988 (t (org-shiftselect-error))))
18990 (defun org-shiftcontrolright ()
18991 "Switch to next TODO set."
18992 (interactive)
18993 (cond
18994 ((and org-support-shift-select (org-region-active-p))
18995 (org-call-for-shift-select 'forward-word))
18996 ((and (not (eq org-support-shift-select 'always))
18997 (org-at-heading-p))
18998 (org-call-with-arg 'org-todo 'nextset))
18999 (org-support-shift-select
19000 (org-call-for-shift-select 'forward-word))
19001 (t (org-shiftselect-error))))
19003 (defun org-shiftcontrolleft ()
19004 "Switch to previous TODO set."
19005 (interactive)
19006 (cond
19007 ((and org-support-shift-select (org-region-active-p))
19008 (org-call-for-shift-select 'backward-word))
19009 ((and (not (eq org-support-shift-select 'always))
19010 (org-at-heading-p))
19011 (org-call-with-arg 'org-todo 'previousset))
19012 (org-support-shift-select
19013 (org-call-for-shift-select 'backward-word))
19014 (t (org-shiftselect-error))))
19016 (defun org-shiftcontrolup ()
19017 "Change timestamps synchronously up in CLOCK log lines."
19018 (interactive)
19019 (cond ((and (not org-support-shift-select)
19020 (org-at-clock-log-p)
19021 (org-at-timestamp-p t))
19022 (org-clock-timestamps-up))
19023 (t (org-shiftselect-error))))
19025 (defun org-shiftcontroldown ()
19026 "Change timestamps synchronously down in CLOCK log lines."
19027 (interactive)
19028 (cond ((and (not org-support-shift-select)
19029 (org-at-clock-log-p)
19030 (org-at-timestamp-p t))
19031 (org-clock-timestamps-down))
19032 (t (org-shiftselect-error))))
19034 (defun org-ctrl-c-ret ()
19035 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19036 (interactive)
19037 (cond
19038 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19039 (t (call-interactively 'org-insert-heading))))
19041 (defun org-find-visible ()
19042 (let ((s (point)))
19043 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19044 (get-char-property s 'invisible)))
19046 (defun org-find-invisible ()
19047 (let ((s (point)))
19048 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19049 (not (get-char-property s 'invisible))))
19052 (defun org-copy-visible (beg end)
19053 "Copy the visible parts of the region."
19054 (interactive "r")
19055 (let (snippets s)
19056 (save-excursion
19057 (save-restriction
19058 (narrow-to-region beg end)
19059 (setq s (goto-char (point-min)))
19060 (while (not (= (point) (point-max)))
19061 (goto-char (org-find-invisible))
19062 (push (buffer-substring s (point)) snippets)
19063 (setq s (goto-char (org-find-visible))))))
19064 (kill-new (apply 'concat (nreverse snippets)))))
19066 (defun org-copy-special ()
19067 "Copy region in table or copy current subtree.
19068 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19069 See the individual commands for more information."
19070 (interactive)
19071 (call-interactively
19072 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19074 (defun org-cut-special ()
19075 "Cut region in table or cut current subtree.
19076 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19077 See the individual commands for more information."
19078 (interactive)
19079 (call-interactively
19080 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19082 (defun org-paste-special (arg)
19083 "Paste rectangular region into table, or past subtree relative to level.
19084 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19085 See the individual commands for more information."
19086 (interactive "P")
19087 (if (org-at-table-p)
19088 (org-table-paste-rectangle)
19089 (org-paste-subtree arg)))
19091 (defun org-edit-special (&optional arg)
19092 "Call a special editor for the stuff at point.
19093 When at a table, call the formula editor with `org-table-edit-formulas'.
19094 When at the first line of an src example, call `org-edit-src-code'.
19095 When in an #+include line, visit the include file. Otherwise call
19096 `ffap' to visit the file at point."
19097 (interactive)
19098 ;; possibly prep session before editing source
19099 (when arg
19100 (let* ((info (org-babel-get-src-block-info))
19101 (lang (nth 0 info))
19102 (params (nth 2 info))
19103 (session (cdr (assoc :session params))))
19104 (when (and info session) ;; we are in a source-code block with a session
19105 (funcall
19106 (intern (concat "org-babel-prep-session:" lang)) session params))))
19107 (cond ;; proceed with `org-edit-special'
19108 ((save-excursion
19109 (beginning-of-line 1)
19110 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
19111 (find-file (org-trim (match-string 1))))
19112 ((org-edit-src-code))
19113 ((org-edit-fixed-width-region))
19114 ((org-at-table.el-p)
19115 (org-edit-src-code))
19116 ((or (org-at-table-p)
19117 (save-excursion
19118 (beginning-of-line 1)
19119 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
19120 (call-interactively 'org-table-edit-formulas))
19121 (t (call-interactively 'ffap))))
19123 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19124 (defun org-ctrl-c-ctrl-c (&optional arg)
19125 "Set tags in headline, or update according to changed information at point.
19127 This command does many different things, depending on context:
19129 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19130 this is what we do.
19132 - If the cursor is on a statistics cookie, update it.
19134 - If the cursor is in a headline, prompt for tags and insert them
19135 into the current line, aligned to `org-tags-column'. When called
19136 with prefix arg, realign all tags in the current buffer.
19138 - If the cursor is in one of the special #+KEYWORD lines, this
19139 triggers scanning the buffer for these lines and updating the
19140 information.
19142 - If the cursor is inside a table, realign the table. This command
19143 works even if the automatic table editor has been turned off.
19145 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19146 the entire table.
19148 - If the cursor is at a footnote reference or definition, jump to
19149 the corresponding definition or references, respectively.
19151 - If the cursor is a the beginning of a dynamic block, update it.
19153 - If the current buffer is a capture buffer, close note and file it.
19155 - If the cursor is on a <<<target>>>, update radio targets and
19156 corresponding links in this buffer.
19158 - If the cursor is on a numbered item in a plain list, renumber the
19159 ordered list.
19161 - If the cursor is on a checkbox, toggle it.
19163 - If the cursor is on a code block, evaluate it. The variable
19164 `org-confirm-babel-evaluate' can be used to control prompting
19165 before code block evaluation, by default every code block
19166 evaluation requires confirmation. Code block evaluation can be
19167 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19168 (interactive "P")
19169 (let ((org-enable-table-editor t))
19170 (cond
19171 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19172 org-occur-highlights
19173 org-latex-fragment-image-overlays)
19174 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19175 (org-remove-occur-highlights)
19176 (org-remove-latex-fragment-image-overlays)
19177 (message "Temporary highlights/overlays removed from current buffer"))
19178 ((and (local-variable-p 'org-finish-function (current-buffer))
19179 (fboundp org-finish-function))
19180 (funcall org-finish-function))
19181 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19182 ((org-in-regexp org-ts-regexp-both)
19183 (org-timestamp-change 0 'day))
19184 ((or (looking-at org-property-start-re)
19185 (org-at-property-p))
19186 (call-interactively 'org-property-action))
19187 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
19188 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
19189 (or (org-at-heading-p) (org-at-item-p)))
19190 (call-interactively 'org-update-statistics-cookies))
19191 ((org-at-heading-p) (call-interactively 'org-set-tags))
19192 ((org-at-table.el-p)
19193 (message "Use C-c ' to edit table.el tables"))
19194 ((org-at-table-p)
19195 (org-table-maybe-eval-formula)
19196 (if arg
19197 (call-interactively 'org-table-recalculate)
19198 (org-table-maybe-recalculate-line))
19199 (call-interactively 'org-table-align)
19200 (orgtbl-send-table 'maybe))
19201 ((or (org-footnote-at-reference-p)
19202 (org-footnote-at-definition-p))
19203 (call-interactively 'org-footnote-action))
19204 ((org-at-item-checkbox-p)
19205 ;; Cursor at a checkbox: repair list and update checkboxes. Send
19206 ;; list only if at top item.
19207 (let* ((cbox (match-string 1))
19208 (struct (org-list-struct))
19209 (old-struct (copy-tree struct))
19210 (parents (org-list-parents-alist struct))
19211 (orderedp (org-entry-get nil "ORDERED"))
19212 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19213 block-item)
19214 ;; Use a light version of `org-toggle-checkbox' to avoid
19215 ;; computing list structure twice.
19216 (let ((new-box (cond
19217 ((equal arg '(16)) "[-]")
19218 ((equal arg '(4)) nil)
19219 ((equal "[X]" cbox) "[ ]")
19220 (t "[X]"))))
19221 (if (and firstp arg)
19222 ;; If at first item of sub-list, remove check-box from
19223 ;; every item at the same level.
19224 (mapc
19225 (lambda (pos) (org-list-set-checkbox pos struct new-box))
19226 (org-list-get-all-items
19227 (point-at-bol) struct (org-list-prevs-alist struct)))
19228 (org-list-set-checkbox (point-at-bol) struct new-box)))
19229 ;; Replicate `org-list-write-struct', while grabbing a return
19230 ;; value from `org-list-struct-fix-box'.
19231 (org-list-struct-fix-ind struct parents 2)
19232 (org-list-struct-fix-item-end struct)
19233 (let ((prevs (org-list-prevs-alist struct)))
19234 (org-list-struct-fix-bul struct prevs)
19235 (org-list-struct-fix-ind struct parents)
19236 (setq block-item
19237 (org-list-struct-fix-box struct parents prevs orderedp)))
19238 (org-list-struct-apply-struct struct old-struct)
19239 (org-update-checkbox-count-maybe)
19240 (when block-item
19241 (message
19242 "Checkboxes were removed due to unchecked box at line %d"
19243 (org-current-line block-item)))
19244 (when firstp (org-list-send-list 'maybe))))
19245 ((org-at-item-p)
19246 ;; Cursor at an item: repair list. Do checkbox related actions
19247 ;; only if function was called with an argument. Send list only
19248 ;; if at top item.
19249 (let* ((struct (org-list-struct))
19250 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19251 old-struct)
19252 (when arg
19253 (setq old-struct (copy-tree struct))
19254 (if firstp
19255 ;; If at first item of sub-list, add check-box to every
19256 ;; item at the same level.
19257 (mapc
19258 (lambda (pos)
19259 (unless (org-list-get-checkbox pos struct)
19260 (org-list-set-checkbox pos struct "[ ]")))
19261 (org-list-get-all-items
19262 (point-at-bol) struct (org-list-prevs-alist struct)))
19263 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
19264 (org-list-write-struct
19265 struct (org-list-parents-alist struct) old-struct)
19266 (when arg (org-update-checkbox-count-maybe))
19267 (when firstp (org-list-send-list 'maybe))))
19268 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
19269 ;; Dynamic block
19270 (beginning-of-line 1)
19271 (save-excursion (org-update-dblock)))
19272 ((save-excursion
19273 (let ((case-fold-search t))
19274 (beginning-of-line 1)
19275 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
19276 (cond
19277 ((or (equal (match-string 1) "TBLFM")
19278 (equal (match-string 1) "tblfm"))
19279 ;; Recalculate the table before this line
19280 (save-excursion
19281 (beginning-of-line 1)
19282 (skip-chars-backward " \r\n\t")
19283 (if (org-at-table-p)
19284 (org-call-with-arg 'org-table-recalculate (or arg t)))))
19286 (let ((org-inhibit-startup-visibility-stuff t)
19287 (org-startup-align-all-tables nil))
19288 (when (boundp 'org-table-coordinate-overlays)
19289 (mapc 'delete-overlay org-table-coordinate-overlays)
19290 (setq org-table-coordinate-overlays nil))
19291 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19292 (message "Local setup has been refreshed"))))
19293 ((org-clock-update-time-maybe))
19295 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19296 (error "C-c C-c can do nothing useful at this location"))))))
19298 (defun org-mode-restart ()
19299 "Restart Org-mode, to scan again for special lines.
19300 Also updates the keyword regular expressions."
19301 (interactive)
19302 (org-mode)
19303 (message "Org-mode restarted"))
19305 (defun org-kill-note-or-show-branches ()
19306 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19307 (interactive)
19308 (if (not org-finish-function)
19309 (progn
19310 (hide-subtree)
19311 (call-interactively 'show-branches))
19312 (let ((org-note-abort t))
19313 (funcall org-finish-function))))
19315 (defun org-return (&optional indent)
19316 "Goto next table row or insert a newline.
19317 Calls `org-table-next-row' or `newline', depending on context.
19318 See the individual commands for more information."
19319 (interactive)
19320 (let (org-ts-what)
19321 (cond
19322 ((or (bobp) (org-in-src-block-p))
19323 (if indent (newline-and-indent) (newline)))
19324 ((org-at-table-p)
19325 (org-table-justify-field-maybe)
19326 (call-interactively 'org-table-next-row))
19327 ;; when `newline-and-indent' is called within a list, make sure
19328 ;; text moved stays inside the item.
19329 ((and (org-in-item-p) indent)
19330 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19331 (progn
19332 (save-match-data (newline))
19333 (org-indent-line-to (length (match-string 0))))
19334 (let ((ind (org-get-indentation)))
19335 (newline)
19336 (if (org-looking-back org-list-end-re)
19337 (org-indent-line)
19338 (org-indent-line-to ind)))))
19339 ((and org-return-follows-link
19340 (org-at-timestamp-p t)
19341 (not (eq org-ts-what 'after)))
19342 (org-follow-timestamp-link))
19343 ((and org-return-follows-link
19344 (let ((tprop (get-text-property (point) 'face)))
19345 (or (eq tprop 'org-link)
19346 (and (listp tprop) (memq 'org-link tprop)))))
19347 (call-interactively 'org-open-at-point))
19348 ((and (org-at-heading-p)
19349 (looking-at
19350 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19351 (org-show-entry)
19352 (end-of-line 1)
19353 (newline))
19354 (t (if indent (newline-and-indent) (newline))))))
19356 (defun org-return-indent ()
19357 "Goto next table row or insert a newline and indent.
19358 Calls `org-table-next-row' or `newline-and-indent', depending on
19359 context. See the individual commands for more information."
19360 (interactive)
19361 (org-return t))
19363 (defun org-ctrl-c-star ()
19364 "Compute table, or change heading status of lines.
19365 Calls `org-table-recalculate' or `org-toggle-heading',
19366 depending on context."
19367 (interactive)
19368 (cond
19369 ((org-at-table-p)
19370 (call-interactively 'org-table-recalculate))
19372 ;; Convert all lines in region to list items
19373 (call-interactively 'org-toggle-heading))))
19375 (defun org-ctrl-c-minus ()
19376 "Insert separator line in table or modify bullet status of line.
19377 Also turns a plain line or a region of lines into list items.
19378 Calls `org-table-insert-hline', `org-toggle-item', or
19379 `org-cycle-list-bullet', depending on context."
19380 (interactive)
19381 (cond
19382 ((org-at-table-p)
19383 (call-interactively 'org-table-insert-hline))
19384 ((org-region-active-p)
19385 (call-interactively 'org-toggle-item))
19386 ((org-in-item-p)
19387 (call-interactively 'org-cycle-list-bullet))
19389 (call-interactively 'org-toggle-item))))
19391 (defun org-toggle-item (arg)
19392 "Convert headings or normal lines to items, items to normal lines.
19393 If there is no active region, only the current line is considered.
19395 If the first non blank line in the region is an headline, convert
19396 all headlines to items, shifting text accordingly.
19398 If it is an item, convert all items to normal lines.
19400 If it is normal text, change region into an item. With a prefix
19401 argument ARG, change each line in region into an item."
19402 (interactive "P")
19403 (let ((shift-text
19404 (function
19405 ;; Shift text in current section to IND, from point to END.
19406 ;; The function leaves point to END line.
19407 (lambda (ind end)
19408 (let ((min-i 1000) (end (copy-marker end)))
19409 ;; First determine the minimum indentation (MIN-I) of
19410 ;; the text.
19411 (save-excursion
19412 (catch 'exit
19413 (while (< (point) end)
19414 (let ((i (org-get-indentation)))
19415 (cond
19416 ;; Skip blank lines and inline tasks.
19417 ((looking-at "^[ \t]*$"))
19418 ((looking-at org-outline-regexp-bol))
19419 ;; We can't find less than 0 indentation.
19420 ((zerop i) (throw 'exit (setq min-i 0)))
19421 ((< i min-i) (setq min-i i))))
19422 (forward-line))))
19423 ;; Then indent each line so that a line indented to
19424 ;; MIN-I becomes indented to IND. Ignore blank lines
19425 ;; and inline tasks in the process.
19426 (let ((delta (- ind min-i)))
19427 (while (< (point) end)
19428 (unless (or (looking-at "^[ \t]*$")
19429 (looking-at org-outline-regexp-bol))
19430 (org-indent-line-to (+ (org-get-indentation) delta)))
19431 (forward-line)))))))
19432 (skip-blanks
19433 (function
19434 ;; Return beginning of first non-blank line, starting from
19435 ;; line at POS.
19436 (lambda (pos)
19437 (save-excursion
19438 (goto-char pos)
19439 (skip-chars-forward " \r\t\n")
19440 (point-at-bol)))))
19441 beg end)
19442 ;; Determine boundaries of changes.
19443 (if (org-region-active-p)
19444 (setq beg (funcall skip-blanks (region-beginning))
19445 end (copy-marker (region-end)))
19446 (setq beg (funcall skip-blanks (point-at-bol))
19447 end (copy-marker (point-at-eol))))
19448 ;; Depending on the starting line, choose an action on the text
19449 ;; between BEG and END.
19450 (org-with-limited-levels
19451 (save-excursion
19452 (goto-char beg)
19453 (cond
19454 ;; Case 1. Start at an item: de-itemize. Note that it only
19455 ;; happens when a region is active: `org-ctrl-c-minus'
19456 ;; would call `org-cycle-list-bullet' otherwise.
19457 ((org-at-item-p)
19458 (while (< (point) end)
19459 (when (org-at-item-p)
19460 (skip-chars-forward " \t")
19461 (delete-region (point) (match-end 0)))
19462 (forward-line)))
19463 ;; Case 2. Start at an heading: convert to items.
19464 ((org-at-heading-p)
19465 (let* ((bul (org-list-bullet-string "-"))
19466 (bul-len (length bul))
19467 ;; Indentation of the first heading. It should be
19468 ;; relative to the indentation of its parent, if any.
19469 (start-ind (save-excursion
19470 (cond
19471 ((not org-adapt-indentation) 0)
19472 ((not (outline-previous-heading)) 0)
19473 (t (length (match-string 0))))))
19474 ;; Level of first heading. Further headings will be
19475 ;; compared to it to determine hierarchy in the list.
19476 (ref-level (org-reduced-level (org-outline-level))))
19477 (while (< (point) end)
19478 (let* ((level (org-reduced-level (org-outline-level)))
19479 (delta (max 0 (- level ref-level))))
19480 ;; If current headline is less indented than the first
19481 ;; one, set it as reference, in order to preserve
19482 ;; subtrees.
19483 (when (< level ref-level) (setq ref-level level))
19484 (replace-match bul t t)
19485 (org-indent-line-to (+ start-ind (* delta bul-len)))
19486 ;; Ensure all text down to END (or SECTION-END) belongs
19487 ;; to the newly created item.
19488 (let ((section-end (save-excursion
19489 (or (outline-next-heading) (point)))))
19490 (forward-line)
19491 (funcall shift-text
19492 (+ start-ind (* (1+ delta) bul-len))
19493 (min end section-end)))))))
19494 ;; Case 3. Normal line with ARG: turn each non-item line into
19495 ;; an item.
19496 (arg
19497 (while (< (point) end)
19498 (unless (or (org-at-heading-p) (org-at-item-p))
19499 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19500 (replace-match
19501 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19502 (forward-line)))
19503 ;; Case 4. Normal line without ARG: make the first line of
19504 ;; region an item, and shift indentation of others
19505 ;; lines to set them as item's body.
19506 (t (let* ((bul (org-list-bullet-string "-"))
19507 (bul-len (length bul))
19508 (ref-ind (org-get-indentation)))
19509 (skip-chars-forward " \t")
19510 (insert bul)
19511 (forward-line)
19512 (while (< (point) end)
19513 ;; Ensure that lines less indented than first one
19514 ;; still get included in item body.
19515 (funcall shift-text
19516 (+ ref-ind bul-len)
19517 (min end (save-excursion (or (outline-next-heading)
19518 (point)))))
19519 (forward-line)))))))))
19521 (defun org-toggle-heading (&optional nstars)
19522 "Convert headings to normal text, or items or text to headings.
19523 If there is no active region, only the current line is considered.
19525 With a \\[universal-argument] prefix, convert the whole list at
19526 point into heading.
19528 In a region:
19530 - If the first non blank line is an headline, remove the stars
19531 from all headlines in the region.
19533 - If it is a normal line turn each and every normal line (i.e. not an
19534 heading or an item) in the region into a heading.
19536 - If it is a plain list item, turn all plain list items into headings.
19538 When converting a line into a heading, the number of stars is chosen
19539 such that the lines become children of the current entry. However,
19540 when a prefix argument is given, its value determines the number of
19541 stars to add."
19542 (interactive "P")
19543 (let ((skip-blanks
19544 (function
19545 ;; Return beginning of first non-blank line, starting from
19546 ;; line at POS.
19547 (lambda (pos)
19548 (save-excursion
19549 (goto-char pos)
19550 (while (org-at-comment-p) (forward-line))
19551 (skip-chars-forward " \r\t\n")
19552 (point-at-bol)))))
19553 beg end toggled)
19554 ;; Determine boundaries of changes. If a universal prefix has
19555 ;; been given, put the list in a region. If region ends at a bol,
19556 ;; do not consider the last line to be in the region.
19558 (when (and current-prefix-arg (org-at-item-p))
19559 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19560 (org-mark-element))
19562 (if (org-region-active-p)
19563 (setq beg (funcall skip-blanks (region-beginning))
19564 end (copy-marker (save-excursion
19565 (goto-char (region-end))
19566 (if (bolp) (point) (point-at-eol)))))
19567 (setq beg (funcall skip-blanks (point-at-bol))
19568 end (copy-marker (point-at-eol))))
19569 ;; Ensure inline tasks don't count as headings.
19570 (org-with-limited-levels
19571 (save-excursion
19572 (goto-char beg)
19573 (cond
19574 ;; Case 1. Started at an heading: de-star headings.
19575 ((org-at-heading-p)
19576 (while (< (point) end)
19577 (when (org-at-heading-p t)
19578 (looking-at org-outline-regexp) (replace-match "")
19579 (setq toggled t))
19580 (forward-line)))
19581 ;; Case 2. Started at an item: change items into headlines.
19582 ;; One star will be added by `org-list-to-subtree'.
19583 ((org-at-item-p)
19584 (let* ((stars (make-string
19585 (if nstars
19586 ;; subtract the star that will be added again by
19587 ;; `org-list-to-subtree'
19588 (1- (prefix-numeric-value current-prefix-arg))
19589 (or (org-current-level) 0))
19590 ?*))
19591 (add-stars
19592 (cond (nstars "") ; stars from prefix only
19593 ((equal stars "") "") ; before first heading
19594 (org-odd-levels-only "*") ; inside heading, odd
19595 (t "")))) ; inside heading, oddeven
19596 (while (< (point) end)
19597 (when (org-at-item-p)
19598 ;; Pay attention to cases when region ends before list.
19599 (let* ((struct (org-list-struct))
19600 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19601 (save-restriction
19602 (narrow-to-region (point) list-end)
19603 (insert
19604 (org-list-to-subtree
19605 (org-list-parse-list t)
19606 '(:istart (concat stars add-stars (funcall get-stars depth))
19607 :icount (concat stars add-stars (funcall get-stars depth)))))))
19608 (setq toggled t))
19609 (forward-line))))
19610 ;; Case 3. Started at normal text: make every line an heading,
19611 ;; skipping headlines and items.
19612 (t (let* ((stars (make-string
19613 (if nstars
19614 (prefix-numeric-value current-prefix-arg)
19615 (or (org-current-level) 0))
19616 ?*))
19617 (add-stars
19618 (cond (nstars "") ; stars from prefix only
19619 ((equal stars "") "*") ; before first heading
19620 (org-odd-levels-only "**") ; inside heading, odd
19621 (t "*"))) ; inside heading, oddeven
19622 (rpl (concat stars add-stars " ")))
19623 (while (< (point) end)
19624 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19625 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19626 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19627 (forward-line)))))))
19628 (unless toggled (message "Cannot toggle heading from here"))))
19630 (defun org-meta-return (&optional arg)
19631 "Insert a new heading or wrap a region in a table.
19632 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19633 See the individual commands for more information."
19634 (interactive "P")
19635 (cond
19636 ((run-hook-with-args-until-success 'org-metareturn-hook))
19637 ((or (org-at-drawer-p) (org-at-property-p))
19638 (newline-and-indent))
19639 ((org-at-table-p)
19640 (call-interactively 'org-table-wrap-region))
19641 (t (call-interactively 'org-insert-heading))))
19643 ;;; Menu entries
19645 (defsubst org-in-subtree-not-table-p ()
19646 "Are we in a subtree and not in a table?"
19647 (and (not (org-before-first-heading-p))
19648 (not (org-at-table-p))))
19650 ;; Define the Org-mode menus
19651 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19652 '("Tbl"
19653 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19654 ["Next Field" org-cycle (org-at-table-p)]
19655 ["Previous Field" org-shifttab (org-at-table-p)]
19656 ["Next Row" org-return (org-at-table-p)]
19657 "--"
19658 ["Blank Field" org-table-blank-field (org-at-table-p)]
19659 ["Edit Field" org-table-edit-field (org-at-table-p)]
19660 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19661 "--"
19662 ("Column"
19663 ["Move Column Left" org-metaleft (org-at-table-p)]
19664 ["Move Column Right" org-metaright (org-at-table-p)]
19665 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19666 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19667 ("Row"
19668 ["Move Row Up" org-metaup (org-at-table-p)]
19669 ["Move Row Down" org-metadown (org-at-table-p)]
19670 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19671 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19672 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19673 "--"
19674 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19675 ("Rectangle"
19676 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19677 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19678 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19679 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19680 "--"
19681 ("Calculate"
19682 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19683 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19684 ["Edit Formulas" org-edit-special (org-at-table-p)]
19685 "--"
19686 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19687 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19688 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19689 "--"
19690 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19691 "--"
19692 ["Sum Column/Rectangle" org-table-sum
19693 (or (org-at-table-p) (org-region-active-p))]
19694 ["Which Column?" org-table-current-column (org-at-table-p)])
19695 ["Debug Formulas"
19696 org-table-toggle-formula-debugger
19697 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19698 ["Show Col/Row Numbers"
19699 org-table-toggle-coordinate-overlays
19700 :style toggle
19701 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19702 "--"
19703 ["Create" org-table-create (and (not (org-at-table-p))
19704 org-enable-table-editor)]
19705 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19706 ["Import from File" org-table-import (not (org-at-table-p))]
19707 ["Export to File" org-table-export (org-at-table-p)]
19708 "--"
19709 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19711 (easy-menu-define org-org-menu org-mode-map "Org menu"
19712 '("Org"
19713 ("Show/Hide"
19714 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19715 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19716 ["Sparse Tree..." org-sparse-tree t]
19717 ["Reveal Context" org-reveal t]
19718 ["Show All" show-all t]
19719 "--"
19720 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19721 "--"
19722 ["New Heading" org-insert-heading t]
19723 ("Navigate Headings"
19724 ["Up" outline-up-heading t]
19725 ["Next" outline-next-visible-heading t]
19726 ["Previous" outline-previous-visible-heading t]
19727 ["Next Same Level" outline-forward-same-level t]
19728 ["Previous Same Level" outline-backward-same-level t]
19729 "--"
19730 ["Jump" org-goto t])
19731 ("Edit Structure"
19732 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
19733 "--"
19734 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
19735 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
19736 "--"
19737 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
19738 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
19739 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19740 "--"
19741 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19742 "--"
19743 ["Copy visible text" org-copy-visible t]
19744 "--"
19745 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
19746 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
19747 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
19748 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
19749 "--"
19750 ["Sort Region/Children" org-sort t]
19751 "--"
19752 ["Convert to odd levels" org-convert-to-odd-levels t]
19753 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19754 ("Editing"
19755 ["Emphasis..." org-emphasize t]
19756 ["Edit Source Example" org-edit-special t]
19757 "--"
19758 ["Footnote new/jump" org-footnote-action t]
19759 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19760 ("Archive"
19761 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
19762 "--"
19763 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
19764 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
19765 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
19767 "--"
19768 ("Hyperlinks"
19769 ["Store Link (Global)" org-store-link t]
19770 ["Find existing link to here" org-occur-link-in-agenda-files t]
19771 ["Insert Link" org-insert-link t]
19772 ["Follow Link" org-open-at-point t]
19773 "--"
19774 ["Next link" org-next-link t]
19775 ["Previous link" org-previous-link t]
19776 "--"
19777 ["Descriptive Links"
19778 org-toggle-link-display
19779 :style radio
19780 :selected org-descriptive-links
19782 ["Literal Links"
19783 org-toggle-link-display
19784 :style radio
19785 :selected (not org-descriptive-links)])
19786 "--"
19787 ("TODO Lists"
19788 ["TODO/DONE/-" org-todo t]
19789 ("Select keyword"
19790 ["Next keyword" org-shiftright (org-at-heading-p)]
19791 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19792 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19793 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19794 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19795 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19796 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19797 "--"
19798 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19799 :selected org-enforce-todo-dependencies :style toggle :active t]
19800 "Settings for tree at point"
19801 ["Do Children sequentially" org-toggle-ordered-property :style radio
19802 :selected (org-entry-get nil "ORDERED")
19803 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19804 ["Do Children parallel" org-toggle-ordered-property :style radio
19805 :selected (not (org-entry-get nil "ORDERED"))
19806 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19807 "--"
19808 ["Set Priority" org-priority t]
19809 ["Priority Up" org-shiftup t]
19810 ["Priority Down" org-shiftdown t]
19811 "--"
19812 ["Get news from all feeds" org-feed-update-all t]
19813 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19814 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19815 ("TAGS and Properties"
19816 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
19817 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19818 "--"
19819 ["Set property" org-set-property (not (org-before-first-heading-p))]
19820 ["Column view of properties" org-columns t]
19821 ["Insert Column View DBlock" org-insert-columns-dblock t])
19822 ("Dates and Scheduling"
19823 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
19824 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
19825 ("Change Date"
19826 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
19827 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
19828 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
19829 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
19830 ["Compute Time Range" org-evaluate-time-range t]
19831 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
19832 ["Deadline" org-deadline (not (org-before-first-heading-p))]
19833 "--"
19834 ["Custom time format" org-toggle-time-stamp-overlays
19835 :style radio :selected org-display-custom-times]
19836 "--"
19837 ["Goto Calendar" org-goto-calendar t]
19838 ["Date from Calendar" org-date-from-calendar t]
19839 "--"
19840 ["Start/Restart Timer" org-timer-start t]
19841 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19842 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19843 ["Insert Timer String" org-timer t]
19844 ["Insert Timer Item" org-timer-item t])
19845 ("Logging work"
19846 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19847 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19848 ["Clock out" org-clock-out t]
19849 ["Clock cancel" org-clock-cancel t]
19850 "--"
19851 ["Mark as default task" org-clock-mark-default-task t]
19852 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19853 ["Goto running clock" org-clock-goto t]
19854 "--"
19855 ["Display times" org-clock-display t]
19856 ["Create clock table" org-clock-report t]
19857 "--"
19858 ["Record DONE time"
19859 (progn (setq org-log-done (not org-log-done))
19860 (message "Switching to %s will %s record a timestamp"
19861 (car org-done-keywords)
19862 (if org-log-done "automatically" "not")))
19863 :style toggle :selected org-log-done])
19864 "--"
19865 ["Agenda Command..." org-agenda t]
19866 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19867 ("File List for Agenda")
19868 ("Special views current file"
19869 ["TODO Tree" org-show-todo-tree t]
19870 ["Check Deadlines" org-check-deadlines t]
19871 ["Timeline" org-timeline t]
19872 ["Tags/Property tree" org-match-sparse-tree t])
19873 "--"
19874 ["Export/Publish..." org-export t]
19875 ("LaTeX"
19876 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19877 :selected org-cdlatex-mode]
19878 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19879 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19880 ["Modify math symbol" org-cdlatex-math-modify
19881 (org-inside-LaTeX-fragment-p)]
19882 ["Insert citation" org-reftex-citation t]
19883 "--"
19884 ["Template for BEAMER" (progn (require 'org-beamer)
19885 (org-insert-beamer-options-template)) t])
19886 "--"
19887 ("MobileOrg"
19888 ["Push Files and Views" org-mobile-push t]
19889 ["Get Captured and Flagged" org-mobile-pull t]
19890 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19891 "--"
19892 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19893 "--"
19894 ("Documentation"
19895 ["Show Version" org-version t]
19896 ["Info Documentation" org-info t])
19897 ("Customize"
19898 ["Browse Org Group" org-customize t]
19899 "--"
19900 ["Expand This Menu" org-create-customize-menu
19901 (fboundp 'customize-menu-create)])
19902 ["Send bug report" org-submit-bug-report t]
19903 "--"
19904 ("Refresh/Reload"
19905 ["Refresh setup current buffer" org-mode-restart t]
19906 ["Reload Org (after update)" org-reload t]
19907 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19910 (defun org-info (&optional node)
19911 "Read documentation for Org-mode in the info system.
19912 With optional NODE, go directly to that node."
19913 (interactive)
19914 (info (format "(org)%s" (or node ""))))
19916 ;;;###autoload
19917 (defun org-submit-bug-report ()
19918 "Submit a bug report on Org-mode via mail.
19920 Don't hesitate to report any problems or inaccurate documentation.
19922 If you don't have setup sending mail from (X)Emacs, please copy the
19923 output buffer into your mail program, as it gives us important
19924 information about your Org-mode version and configuration."
19925 (interactive)
19926 (require 'reporter)
19927 (org-load-modules-maybe)
19928 (org-require-autoloaded-modules)
19929 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19930 (reporter-submit-bug-report
19931 "emacs-orgmode@gnu.org"
19932 (org-version nil 'full)
19933 (let (list)
19934 (save-window-excursion
19935 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19936 (delete-other-windows)
19937 (erase-buffer)
19938 (insert "You are about to submit a bug report to the Org-mode mailing list.
19940 We would like to add your full Org-mode and Outline configuration to the
19941 bug report. This greatly simplifies the work of the maintainer and
19942 other experts on the mailing list.
19944 HOWEVER, some variables you have customized may contain private
19945 information. The names of customers, colleagues, or friends, might
19946 appear in the form of file names, tags, todo states, or search strings.
19947 If you answer yes to the prompt, you might want to check and remove
19948 such private information before sending the email.")
19949 (add-text-properties (point-min) (point-max) '(face org-warning))
19950 (when (yes-or-no-p "Include your Org-mode configuration ")
19951 (mapatoms
19952 (lambda (v)
19953 (and (boundp v)
19954 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19955 (or (and (symbol-value v)
19956 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19957 (and
19958 (get v 'custom-type) (get v 'standard-value)
19959 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19960 (push v list)))))
19961 (kill-buffer (get-buffer "*Warn about privacy*"))
19962 list))
19963 nil nil
19964 "Remember to cover the basics, that is, what you expected to happen and
19965 what in fact did happen. You don't know how to make a good report? See
19967 http://orgmode.org/manual/Feedback.html#Feedback
19969 Your bug report will be posted to the Org-mode mailing list.
19970 ------------------------------------------------------------------------")
19971 (save-excursion
19972 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19973 (replace-match "\\1Bug: \\3 [\\2]")))))
19976 (defun org-install-agenda-files-menu ()
19977 (let ((bl (buffer-list)))
19978 (save-excursion
19979 (while bl
19980 (set-buffer (pop bl))
19981 (if (derived-mode-p 'org-mode) (setq bl nil)))
19982 (when (derived-mode-p 'org-mode)
19983 (easy-menu-change
19984 '("Org") "File List for Agenda"
19985 (append
19986 (list
19987 ["Edit File List" (org-edit-agenda-file-list) t]
19988 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19989 ["Remove Current File from List" org-remove-file t]
19990 ["Cycle through agenda files" org-cycle-agenda-files t]
19991 ["Occur in all agenda files" org-occur-in-agenda-files t]
19992 "--")
19993 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19995 ;;;; Documentation
19997 (defun org-require-autoloaded-modules ()
19998 (interactive)
19999 (mapc 'require
20000 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
20001 org-docbook org-exp org-html org-icalendar
20002 org-id org-latex
20003 org-publish org-remember org-table
20004 org-timer org-xoxo)))
20006 ;;;###autoload
20007 (defun org-reload (&optional uncompiled)
20008 "Reload all org lisp files.
20009 With prefix arg UNCOMPILED, load the uncompiled versions."
20010 (interactive "P")
20011 (require 'loadhist)
20012 (let* ((org-dir (org-find-library-dir "org"))
20013 (babel-dir (or (org-find-library-dir "ob") org-dir))
20014 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20015 (feature-re "^\\(org\\|ob\\)\\(-.*\\)?")
20016 (remove-re (mapconcat 'identity
20017 (mapcar (lambda (f) (concat "^" f "$"))
20018 (list (if (featurep 'xemacs)
20019 "org-colview"
20020 "org-colview-xemacs")
20021 "org" "org-loaddefs" "org-version"))
20022 "\\|"))
20023 (feats (delete-dups
20024 (mapcar 'file-name-sans-extension
20025 (mapcar 'file-name-nondirectory
20026 (delq nil
20027 (mapcar 'feature-file
20028 features))))))
20029 (lfeat (append
20030 (sort
20031 (setq feats
20032 (delq nil (mapcar
20033 (lambda (f)
20034 (if (and (string-match feature-re f)
20035 (not (string-match remove-re f)))
20036 f nil))
20037 feats)))
20038 'string-lessp)
20039 (list "org-version" "org")))
20040 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20041 (load-misses ()))
20042 (setq load-misses
20043 (delq 't
20044 (mapcar (lambda (f)
20046 (load (concat org-dir f) 'noerror nil nil 'mustsuffix)
20047 (unless (string= org-dir babel-dir)
20048 (load (concat babel-dir f) 'noerror nil nil 'mustsuffix))
20049 (unless (string= org-dir contrib-dir)
20050 (load (concat contrib-dir f) 'noerror nil nil 'mustsuffix))
20051 (and (load (concat (org-find-library-dir f) f) 'noerror nil nil 'mustsuffix)
20052 ;; fallback to load-path, report as a possible error
20053 (message "Had to fall back onto load-path, something is not quite right...")
20054 f)))
20055 lfeat)))
20056 (if (not load-misses)
20057 (message "Successfully reloaded Org\n%s" (org-version nil 'full))
20058 (message "Some error occured while reloading Org features\n%s\nPlease check *Messages*!\n%s"
20059 load-misses (org-version nil 'full)))))
20061 ;;;###autoload
20062 (defun org-customize ()
20063 "Call the customize function with org as argument."
20064 (interactive)
20065 (org-load-modules-maybe)
20066 (org-require-autoloaded-modules)
20067 (customize-browse 'org))
20069 (defun org-create-customize-menu ()
20070 "Create a full customization menu for Org-mode, insert it into the menu."
20071 (interactive)
20072 (org-load-modules-maybe)
20073 (org-require-autoloaded-modules)
20074 (if (fboundp 'customize-menu-create)
20075 (progn
20076 (easy-menu-change
20077 '("Org") "Customize"
20078 `(["Browse Org group" org-customize t]
20079 "--"
20080 ,(customize-menu-create 'org)
20081 ["Set" Custom-set t]
20082 ["Save" Custom-save t]
20083 ["Reset to Current" Custom-reset-current t]
20084 ["Reset to Saved" Custom-reset-saved t]
20085 ["Reset to Standard Settings" Custom-reset-standard t]))
20086 (message "\"Org\"-menu now contains full customization menu"))
20087 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20089 ;;;; Miscellaneous stuff
20091 ;;; Generally useful functions
20093 (defun org-get-at-bol (property)
20094 "Get text property PROPERTY at beginning of line."
20095 (get-text-property (point-at-bol) property))
20097 (defun org-find-text-property-in-string (prop s)
20098 "Return the first non-nil value of property PROP in string S."
20099 (or (get-text-property 0 prop s)
20100 (get-text-property (or (next-single-property-change 0 prop s) 0)
20101 prop s)))
20103 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20104 "Display the given MESSAGE as a warning."
20105 (if (fboundp 'display-warning)
20106 (display-warning 'org message
20107 (if (featurep 'xemacs) 'warning :warning))
20108 (let ((buf (get-buffer-create "*Org warnings*")))
20109 (with-current-buffer buf
20110 (goto-char (point-max))
20111 (insert "Warning (Org): " message)
20112 (unless (bolp)
20113 (newline)))
20114 (display-buffer buf)
20115 (sit-for 0))))
20117 (defun org-eval (form)
20118 "Eval FORM and return result."
20119 (condition-case error
20120 (eval form)
20121 (error (format "%%![Error: %s]" error))))
20123 (defun org-in-clocktable-p ()
20124 "Check if the cursor is in a clocktable."
20125 (let ((pos (point)) start)
20126 (save-excursion
20127 (end-of-line 1)
20128 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20129 (setq start (match-beginning 0))
20130 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20131 (>= (match-end 0) pos)
20132 start))))
20134 (defun org-in-commented-line ()
20135 "Is point in a line starting with `#'?"
20136 (equal (char-after (point-at-bol)) ?#))
20138 (defun org-in-indented-comment-line ()
20139 "Is point in a line starting with `#' after some white space?"
20140 (save-excursion
20141 (save-match-data
20142 (goto-char (point-at-bol))
20143 (looking-at "[ \t]*#"))))
20145 (defun org-in-verbatim-emphasis ()
20146 (save-match-data
20147 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20149 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20150 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20151 (if (and marker (marker-buffer marker)
20152 (buffer-live-p (marker-buffer marker)))
20153 (progn
20154 (org-pop-to-buffer-same-window (marker-buffer marker))
20155 (if (or (> marker (point-max)) (< marker (point-min)))
20156 (widen))
20157 (goto-char marker)
20158 (org-show-context 'org-goto))
20159 (if bookmark
20160 (bookmark-jump bookmark)
20161 (error "Cannot find location"))))
20163 (defun org-quote-csv-field (s)
20164 "Quote field for inclusion in CSV material."
20165 (if (string-match "[\",]" s)
20166 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20169 (defun org-force-self-insert (N)
20170 "Needed to enforce self-insert under remapping."
20171 (interactive "p")
20172 (self-insert-command N))
20174 (defun org-string-width (s)
20175 "Compute width of string, ignoring invisible characters.
20176 This ignores character with invisibility property `org-link', and also
20177 characters with property `org-cwidth', because these will become invisible
20178 upon the next fontification round."
20179 (let (b l)
20180 (when (or (eq t buffer-invisibility-spec)
20181 (assq 'org-link buffer-invisibility-spec))
20182 (while (setq b (text-property-any 0 (length s)
20183 'invisible 'org-link s))
20184 (setq s (concat (substring s 0 b)
20185 (substring s (or (next-single-property-change
20186 b 'invisible s) (length s)))))))
20187 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20188 (setq s (concat (substring s 0 b)
20189 (substring s (or (next-single-property-change
20190 b 'org-cwidth s) (length s))))))
20191 (setq l (string-width s) b -1)
20192 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20193 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20196 (defun org-shorten-string (s maxlength)
20197 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20198 If the string is shorter or has length MAXLENGTH, just return the
20199 original string. If it is longer, the functions finds a space in the
20200 string, breaks this string off at that locations and adds three dots
20201 as ellipsis. Including the ellipsis, the string will not be longer
20202 than MAXLENGTH. If finding a good breaking point in the string does
20203 not work, the string is just chopped off in the middle of a word
20204 if necessary."
20205 (if (<= (length s) maxlength)
20207 (let* ((n (max (- maxlength 4) 1))
20208 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20209 (if (string-match re s)
20210 (concat (match-string 1 s) "...")
20211 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20213 (defun org-get-indentation (&optional line)
20214 "Get the indentation of the current line, interpreting tabs.
20215 When LINE is given, assume it represents a line and compute its indentation."
20216 (if line
20217 (if (string-match "^ *" (org-remove-tabs line))
20218 (match-end 0))
20219 (save-excursion
20220 (beginning-of-line 1)
20221 (skip-chars-forward " \t")
20222 (current-column))))
20224 (defun org-get-string-indentation (s)
20225 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20226 (let ((n -1) (i 0) (w tab-width) c)
20227 (catch 'exit
20228 (while (< (setq n (1+ n)) (length s))
20229 (setq c (aref s n))
20230 (cond ((= c ?\ ) (setq i (1+ i)))
20231 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20232 (t (throw 'exit t)))))
20235 (defun org-remove-tabs (s &optional width)
20236 "Replace tabulators in S with spaces.
20237 Assumes that s is a single line, starting in column 0."
20238 (setq width (or width tab-width))
20239 (while (string-match "\t" s)
20240 (setq s (replace-match
20241 (make-string
20242 (- (* width (/ (+ (match-beginning 0) width) width))
20243 (match-beginning 0)) ?\ )
20244 t t s)))
20247 (defun org-fix-indentation (line ind)
20248 "Fix indentation in LINE.
20249 IND is a cons cell with target and minimum indentation.
20250 If the current indentation in LINE is smaller than the minimum,
20251 leave it alone. If it is larger than ind, set it to the target."
20252 (let* ((l (org-remove-tabs line))
20253 (i (org-get-indentation l))
20254 (i1 (car ind)) (i2 (cdr ind)))
20255 (if (>= i i2) (setq l (substring line i2)))
20256 (if (> i1 0)
20257 (concat (make-string i1 ?\ ) l)
20258 l)))
20260 (defun org-remove-indentation (code &optional n)
20261 "Remove the maximum common indentation from the lines in CODE.
20262 N may optionally be the number of spaces to remove."
20263 (with-temp-buffer
20264 (insert code)
20265 (org-do-remove-indentation n)
20266 (buffer-string)))
20268 (defun org-do-remove-indentation (&optional n)
20269 "Remove the maximum common indentation from the buffer."
20270 (untabify (point-min) (point-max))
20271 (let ((min 10000) re)
20272 (if n
20273 (setq min n)
20274 (goto-char (point-min))
20275 (while (re-search-forward "^ *[^ \n]" nil t)
20276 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20277 (unless (or (= min 0) (= min 10000))
20278 (setq re (format "^ \\{%d\\}" min))
20279 (goto-char (point-min))
20280 (while (re-search-forward re nil t)
20281 (replace-match "")
20282 (end-of-line 1))
20283 min)))
20285 (defun org-fill-template (template alist)
20286 "Find each %key of ALIST in TEMPLATE and replace it."
20287 (let ((case-fold-search nil)
20288 entry key value)
20289 (setq alist (sort (copy-sequence alist)
20290 (lambda (a b) (< (length (car a)) (length (car b))))))
20291 (while (setq entry (pop alist))
20292 (setq template
20293 (replace-regexp-in-string
20294 (concat "%" (regexp-quote (car entry)))
20295 (or (cdr entry) "") template t t)))
20296 template))
20298 (defun org-base-buffer (buffer)
20299 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20300 (if (not buffer)
20301 buffer
20302 (or (buffer-base-buffer buffer)
20303 buffer)))
20305 (defun org-trim (s)
20306 "Remove whitespace at beginning and end of string."
20307 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20308 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20311 (defun org-wrap (string &optional width lines)
20312 "Wrap string to either a number of lines, or a width in characters.
20313 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20314 that costs. If there is a word longer than WIDTH, the text is actually
20315 wrapped to the length of that word.
20316 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20317 many lines, whatever width that takes.
20318 The return value is a list of lines, without newlines at the end."
20319 (let* ((words (org-split-string string "[ \t\n]+"))
20320 (maxword (apply 'max (mapcar 'org-string-width words)))
20321 w ll)
20322 (cond (width
20323 (org-do-wrap words (max maxword width)))
20324 (lines
20325 (setq w maxword)
20326 (setq ll (org-do-wrap words maxword))
20327 (if (<= (length ll) lines)
20329 (setq ll words)
20330 (while (> (length ll) lines)
20331 (setq w (1+ w))
20332 (setq ll (org-do-wrap words w)))
20333 ll))
20334 (t (error "Cannot wrap this")))))
20336 (defun org-do-wrap (words width)
20337 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20338 (let (lines line)
20339 (while words
20340 (setq line (pop words))
20341 (while (and words (< (+ (length line) (length (car words))) width))
20342 (setq line (concat line " " (pop words))))
20343 (setq lines (push line lines)))
20344 (nreverse lines)))
20346 (defun org-split-string (string &optional separators)
20347 "Splits STRING into substrings at SEPARATORS.
20348 No empty strings are returned if there are matches at the beginning
20349 and end of string."
20350 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20351 (start 0)
20352 notfirst
20353 (list nil))
20354 (while (and (string-match rexp string
20355 (if (and notfirst
20356 (= start (match-beginning 0))
20357 (< start (length string)))
20358 (1+ start) start))
20359 (< (match-beginning 0) (length string)))
20360 (setq notfirst t)
20361 (or (eq (match-beginning 0) 0)
20362 (and (eq (match-beginning 0) (match-end 0))
20363 (eq (match-beginning 0) start))
20364 (setq list
20365 (cons (substring string start (match-beginning 0))
20366 list)))
20367 (setq start (match-end 0)))
20368 (or (eq start (length string))
20369 (setq list
20370 (cons (substring string start)
20371 list)))
20372 (nreverse list)))
20374 (defun org-quote-vert (s)
20375 "Replace \"|\" with \"\\vert\"."
20376 (while (string-match "|" s)
20377 (setq s (replace-match "\\vert" t t s)))
20380 (defun org-uuidgen-p (s)
20381 "Is S an ID created by UUIDGEN?"
20382 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20384 (defun org-in-src-block-p nil
20385 "Whether point is in a code source block."
20386 (let (ov)
20387 (when (setq ov (overlays-at (point)))
20388 (memq 'org-block-background
20389 (overlay-properties
20390 (car ov))))))
20392 (defun org-context ()
20393 "Return a list of contexts of the current cursor position.
20394 If several contexts apply, all are returned.
20395 Each context entry is a list with a symbol naming the context, and
20396 two positions indicating start and end of the context. Possible
20397 contexts are:
20399 :headline anywhere in a headline
20400 :headline-stars on the leading stars in a headline
20401 :todo-keyword on a TODO keyword (including DONE) in a headline
20402 :tags on the TAGS in a headline
20403 :priority on the priority cookie in a headline
20404 :item on the first line of a plain list item
20405 :item-bullet on the bullet/number of a plain list item
20406 :checkbox on the checkbox in a plain list item
20407 :table in an org-mode table
20408 :table-special on a special filed in a table
20409 :table-table in a table.el table
20410 :clocktable in a clocktable
20411 :src-block in a source block
20412 :link on a hyperlink
20413 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20414 :target on a <<target>>
20415 :radio-target on a <<<radio-target>>>
20416 :latex-fragment on a LaTeX fragment
20417 :latex-preview on a LaTeX fragment with overlaid preview image
20419 This function expects the position to be visible because it uses font-lock
20420 faces as a help to recognize the following contexts: :table-special, :link,
20421 and :keyword."
20422 (let* ((f (get-text-property (point) 'face))
20423 (faces (if (listp f) f (list f)))
20424 (case-fold-search t)
20425 (p (point)) clist o)
20426 ;; First the large context
20427 (cond
20428 ((org-at-heading-p t)
20429 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20430 (when (progn
20431 (beginning-of-line 1)
20432 (looking-at org-todo-line-tags-regexp))
20433 (push (org-point-in-group p 1 :headline-stars) clist)
20434 (push (org-point-in-group p 2 :todo-keyword) clist)
20435 (push (org-point-in-group p 4 :tags) clist))
20436 (goto-char p)
20437 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20438 (if (looking-at "\\[#[A-Z0-9]\\]")
20439 (push (org-point-in-group p 0 :priority) clist)))
20441 ((org-at-item-p)
20442 (push (org-point-in-group p 2 :item-bullet) clist)
20443 (push (list :item (point-at-bol)
20444 (save-excursion (org-end-of-item) (point)))
20445 clist)
20446 (and (org-at-item-checkbox-p)
20447 (push (org-point-in-group p 0 :checkbox) clist)))
20449 ((org-at-table-p)
20450 (push (list :table (org-table-begin) (org-table-end)) clist)
20451 (if (memq 'org-formula faces)
20452 (push (list :table-special
20453 (previous-single-property-change p 'face)
20454 (next-single-property-change p 'face)) clist)))
20455 ((org-at-table-p 'any)
20456 (push (list :table-table) clist)))
20457 (goto-char p)
20459 (let ((case-fold-search t))
20460 ;; New the "medium" contexts: clocktables, source blocks
20461 (cond ((org-in-clocktable-p)
20462 (push (list :clocktable
20463 (and (or (looking-at "#\\+BEGIN: clocktable")
20464 (search-backward "#+BEGIN: clocktable" nil t))
20465 (match-beginning 0))
20466 (and (re-search-forward "#\\+END:?" nil t)
20467 (match-end 0))) clist))
20468 ((org-in-src-block-p)
20469 (push (list :src-block
20470 (and (or (looking-at "#\\+BEGIN_SRC")
20471 (search-backward "#+BEGIN_SRC" nil t))
20472 (match-beginning 0))
20473 (and (search-forward "#+END_SRC" nil t)
20474 (match-beginning 0))) clist))))
20475 (goto-char p)
20477 ;; Now the small context
20478 (cond
20479 ((org-at-timestamp-p)
20480 (push (org-point-in-group p 0 :timestamp) clist))
20481 ((memq 'org-link faces)
20482 (push (list :link
20483 (previous-single-property-change p 'face)
20484 (next-single-property-change p 'face)) clist))
20485 ((memq 'org-special-keyword faces)
20486 (push (list :keyword
20487 (previous-single-property-change p 'face)
20488 (next-single-property-change p 'face)) clist))
20489 ((org-at-target-p)
20490 (push (org-point-in-group p 0 :target) clist)
20491 (goto-char (1- (match-beginning 0)))
20492 (if (looking-at org-radio-target-regexp)
20493 (push (org-point-in-group p 0 :radio-target) clist))
20494 (goto-char p))
20495 ((setq o (car (delq nil
20496 (mapcar
20497 (lambda (x)
20498 (if (memq x org-latex-fragment-image-overlays) x))
20499 (overlays-at (point))))))
20500 (push (list :latex-fragment
20501 (overlay-start o) (overlay-end o)) clist)
20502 (push (list :latex-preview
20503 (overlay-start o) (overlay-end o)) clist))
20504 ((org-inside-LaTeX-fragment-p)
20505 ;; FIXME: positions wrong.
20506 (push (list :latex-fragment (point) (point)) clist)))
20508 (setq clist (nreverse (delq nil clist)))
20509 clist))
20511 ;; FIXME: Compare with at-regexp-p Do we need both?
20512 (defun org-in-regexp (re &optional nlines visually)
20513 "Check if point is inside a match of regexp.
20514 Normally only the current line is checked, but you can include NLINES extra
20515 lines both before and after point into the search.
20516 If VISUALLY is set, require that the cursor is not after the match but
20517 really on, so that the block visually is on the match."
20518 (catch 'exit
20519 (let ((pos (point))
20520 (eol (point-at-eol (+ 1 (or nlines 0))))
20521 (inc (if visually 1 0)))
20522 (save-excursion
20523 (beginning-of-line (- 1 (or nlines 0)))
20524 (while (re-search-forward re eol t)
20525 (if (and (<= (match-beginning 0) pos)
20526 (>= (+ inc (match-end 0)) pos))
20527 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20529 (defun org-at-regexp-p (regexp)
20530 "Is point inside a match of REGEXP in the current line?"
20531 (catch 'exit
20532 (save-excursion
20533 (let ((pos (point)) (end (point-at-eol)))
20534 (beginning-of-line 1)
20535 (while (re-search-forward regexp end t)
20536 (if (and (<= (match-beginning 0) pos)
20537 (>= (match-end 0) pos))
20538 (throw 'exit t)))
20539 nil))))
20541 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20542 "Non-nil when point is between matches of START-RE and END-RE.
20544 Also return a non-nil value when point is on one of the matches.
20546 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20547 buffer positions. Default values are the positions of headlines
20548 surrounding the point.
20550 The functions returns a cons cell whose car (resp. cdr) is the
20551 position before START-RE (resp. after END-RE)."
20552 (save-match-data
20553 (let ((pos (point))
20554 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20555 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20556 beg end)
20557 (save-excursion
20558 ;; Point is on a block when on START-RE or if START-RE can be
20559 ;; found before it...
20560 (and (or (org-at-regexp-p start-re)
20561 (re-search-backward start-re limit-up t))
20562 (setq beg (match-beginning 0))
20563 ;; ... and END-RE after it...
20564 (goto-char (match-end 0))
20565 (re-search-forward end-re limit-down t)
20566 (> (setq end (match-end 0)) pos)
20567 ;; ... without another START-RE in-between.
20568 (goto-char (match-beginning 0))
20569 (not (re-search-backward start-re (1+ beg) t))
20570 ;; Return value.
20571 (cons beg end))))))
20573 (defun org-in-block-p (names)
20574 "Non-nil when point belongs to a block whose name belongs to NAMES.
20576 NAMES is a list of strings containing names of blocks.
20578 Return first block name matched, or nil. Beware that in case of
20579 nested blocks, the returned name may not belong to the closest
20580 block from point."
20581 (save-match-data
20582 (catch 'exit
20583 (let ((case-fold-search t)
20584 (lim-up (save-excursion (outline-previous-heading)))
20585 (lim-down (save-excursion (outline-next-heading))))
20586 (mapc (lambda (name)
20587 (let ((n (regexp-quote name)))
20588 (when (org-between-regexps-p
20589 (concat "^[ \t]*#\\+begin_" n)
20590 (concat "^[ \t]*#\\+end_" n)
20591 lim-up lim-down)
20592 (throw 'exit n))))
20593 names))
20594 nil)))
20596 (defun org-occur-in-agenda-files (regexp &optional nlines)
20597 "Call `multi-occur' with buffers for all agenda files."
20598 (interactive "sOrg-files matching: \np")
20599 (let* ((files (org-agenda-files))
20600 (tnames (mapcar 'file-truename files))
20601 (extra org-agenda-text-search-extra-files)
20603 (when (eq (car extra) 'agenda-archives)
20604 (setq extra (cdr extra))
20605 (setq files (org-add-archive-files files)))
20606 (while (setq f (pop extra))
20607 (unless (member (file-truename f) tnames)
20608 (add-to-list 'files f 'append)
20609 (add-to-list 'tnames (file-truename f) 'append)))
20610 (multi-occur
20611 (mapcar (lambda (x)
20612 (with-current-buffer
20613 (or (get-file-buffer x) (find-file-noselect x))
20614 (widen)
20615 (current-buffer)))
20616 files)
20617 regexp)))
20619 (if (boundp 'occur-mode-find-occurrence-hook)
20620 ;; Emacs 23
20621 (add-hook 'occur-mode-find-occurrence-hook
20622 (lambda ()
20623 (when (derived-mode-p 'org-mode)
20624 (org-reveal))))
20625 ;; Emacs 22
20626 (defadvice occur-mode-goto-occurrence
20627 (after org-occur-reveal activate)
20628 (and (derived-mode-p 'org-mode) (org-reveal)))
20629 (defadvice occur-mode-goto-occurrence-other-window
20630 (after org-occur-reveal activate)
20631 (and (derived-mode-p 'org-mode) (org-reveal)))
20632 (defadvice occur-mode-display-occurrence
20633 (after org-occur-reveal activate)
20634 (when (derived-mode-p 'org-mode)
20635 (let ((pos (occur-mode-find-occurrence)))
20636 (with-current-buffer (marker-buffer pos)
20637 (save-excursion
20638 (goto-char pos)
20639 (org-reveal)))))))
20641 (defun org-occur-link-in-agenda-files ()
20642 "Create a link and search for it in the agendas.
20643 The link is not stored in `org-stored-links', it is just created
20644 for the search purpose."
20645 (interactive)
20646 (let ((link (condition-case nil
20647 (org-store-link nil)
20648 (error "Unable to create a link to here"))))
20649 (org-occur-in-agenda-files (regexp-quote link))))
20651 (defun org-uniquify (list)
20652 "Remove duplicate elements from LIST."
20653 (let (res)
20654 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20655 res))
20657 (defun org-delete-all (elts list)
20658 "Remove all elements in ELTS from LIST."
20659 (while elts
20660 (setq list (delete (pop elts) list)))
20661 list)
20663 (defun org-count (cl-item cl-seq)
20664 "Count the number of occurrences of ITEM in SEQ.
20665 Taken from `count' in cl-seq.el with all keyword arguments removed."
20666 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20667 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20668 (while (< cl-start cl-end)
20669 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20670 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20671 (setq cl-start (1+ cl-start)))
20672 cl-count))
20674 (defun org-remove-if (predicate seq)
20675 "Remove everything from SEQ that fulfills PREDICATE."
20676 (let (res e)
20677 (while seq
20678 (setq e (pop seq))
20679 (if (not (funcall predicate e)) (push e res)))
20680 (nreverse res)))
20682 (defun org-remove-if-not (predicate seq)
20683 "Remove everything from SEQ that does not fulfill PREDICATE."
20684 (let (res e)
20685 (while seq
20686 (setq e (pop seq))
20687 (if (funcall predicate e) (push e res)))
20688 (nreverse res)))
20690 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20691 "Reduce two-argument FUNCTION across SEQ.
20692 Taken from `reduce' in cl-seq.el with all keyword arguments but
20693 \":initial-value\" removed."
20694 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20695 (cadr (memq :initial-value cl-keys)))
20696 (cl-seq (pop cl-seq))
20697 (t (funcall cl-func)))))
20698 (while cl-seq
20699 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20700 cl-accum))
20702 (defun org-back-over-empty-lines ()
20703 "Move backwards over whitespace, to the beginning of the first empty line.
20704 Returns the number of empty lines passed."
20705 (let ((pos (point)))
20706 (if (cdr (assoc 'heading org-blank-before-new-entry))
20707 (skip-chars-backward " \t\n\r")
20708 (unless (eobp)
20709 (forward-line -1)))
20710 (beginning-of-line 2)
20711 (goto-char (min (point) pos))
20712 (count-lines (point) pos)))
20714 (defun org-skip-whitespace ()
20715 (skip-chars-forward " \t\n\r"))
20717 (defun org-point-in-group (point group &optional context)
20718 "Check if POINT is in match-group GROUP.
20719 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20720 match. If the match group does not exist or point is not inside it,
20721 return nil."
20722 (and (match-beginning group)
20723 (>= point (match-beginning group))
20724 (<= point (match-end group))
20725 (if context
20726 (list context (match-beginning group) (match-end group))
20727 t)))
20729 (defun org-switch-to-buffer-other-window (&rest args)
20730 "Switch to buffer in a second window on the current frame.
20731 In particular, do not allow pop-up frames.
20732 Returns the newly created buffer."
20733 (let (pop-up-frames special-display-buffer-names special-display-regexps
20734 special-display-function)
20735 (apply 'switch-to-buffer-other-window args)))
20737 (defun org-combine-plists (&rest plists)
20738 "Create a single property list from all plists in PLISTS.
20739 The process starts by copying the first list, and then setting properties
20740 from the other lists. Settings in the last list are the most significant
20741 ones and overrule settings in the other lists."
20742 (let ((rtn (copy-sequence (pop plists)))
20743 p v ls)
20744 (while plists
20745 (setq ls (pop plists))
20746 (while ls
20747 (setq p (pop ls) v (pop ls))
20748 (setq rtn (plist-put rtn p v))))
20749 rtn))
20751 (defun org-replace-escapes (string table)
20752 "Replace %-escapes in STRING with values in TABLE.
20753 TABLE is an association list with keys like \"%a\" and string values.
20754 The sequences in STRING may contain normal field width and padding information,
20755 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20756 so values can contain further %-escapes if they are define later in TABLE."
20757 (let ((tbl (copy-alist table))
20758 (case-fold-search nil)
20759 (pchg 0)
20760 e re rpl)
20761 (while (setq e (pop tbl))
20762 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20763 (when (and (cdr e) (string-match re (cdr e)))
20764 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20765 (safe "SREF"))
20766 (add-text-properties 0 3 (list 'sref sref) safe)
20767 (setcdr e (replace-match safe t t (cdr e)))))
20768 (while (string-match re string)
20769 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20770 (cdr e)))
20771 (setq string (replace-match rpl t t string))))
20772 (while (setq pchg (next-property-change pchg string))
20773 (let ((sref (get-text-property pchg 'sref string)))
20774 (when (and sref (string-match "SREF" string pchg))
20775 (setq string (replace-match sref t t string)))))
20776 string))
20778 (defun org-sublist (list start end)
20779 "Return a section of LIST, from START to END.
20780 Counting starts at 1."
20781 (let (rtn (c start))
20782 (setq list (nthcdr (1- start) list))
20783 (while (and list (<= c end))
20784 (push (pop list) rtn)
20785 (setq c (1+ c)))
20786 (nreverse rtn)))
20788 (defun org-find-base-buffer-visiting (file)
20789 "Like `find-buffer-visiting' but always return the base buffer and
20790 not an indirect buffer."
20791 (let ((buf (or (get-file-buffer file)
20792 (find-buffer-visiting file))))
20793 (if buf
20794 (or (buffer-base-buffer buf) buf)
20795 nil)))
20797 (defun org-image-file-name-regexp (&optional extensions)
20798 "Return regexp matching the file names of images.
20799 If EXTENSIONS is given, only match these."
20800 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20801 (image-file-name-regexp)
20802 (let ((image-file-name-extensions
20803 (or extensions
20804 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20805 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20806 (concat "\\."
20807 (regexp-opt (nconc (mapcar 'upcase
20808 image-file-name-extensions)
20809 image-file-name-extensions)
20811 "\\'"))))
20813 (defun org-file-image-p (file &optional extensions)
20814 "Return non-nil if FILE is an image."
20815 (save-match-data
20816 (string-match (org-image-file-name-regexp extensions) file)))
20818 (defun org-get-cursor-date ()
20819 "Return the date at cursor in as a time.
20820 This works in the calendar and in the agenda, anywhere else it just
20821 returns the current time."
20822 (let (date day defd)
20823 (cond
20824 ((eq major-mode 'calendar-mode)
20825 (setq date (calendar-cursor-to-date)
20826 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20827 ((eq major-mode 'org-agenda-mode)
20828 (setq day (get-text-property (point) 'day))
20829 (if day
20830 (setq date (calendar-gregorian-from-absolute day)
20831 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20832 (nth 2 date))))))
20833 (or defd (current-time))))
20835 (defun org-mark-subtree (&optional up)
20836 "Mark the current subtree.
20837 This puts point at the start of the current subtree, and mark at
20838 the end. If a numeric prefix UP is given, move up into the
20839 hierarchy of headlines by UP levels before marking the subtree."
20840 (interactive "P")
20841 (org-with-limited-levels
20842 (cond ((org-at-heading-p) (beginning-of-line))
20843 ((org-before-first-heading-p) (error "Not in a subtree"))
20844 (t (outline-previous-visible-heading 1))))
20845 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
20846 (if (org-called-interactively-p 'any)
20847 (call-interactively 'org-mark-element)
20848 (org-mark-element)))
20851 ;;; Macros
20853 ;; Macros are expanded with `org-macro-replace-all', which relies
20854 ;; internally on `org-macro-expand'.
20856 ;; Default templates for expansion are stored in the buffer-local
20857 ;; variable `org-macro-templates'. This variable is updated by
20858 ;; `org-macro-initialize-templates'.
20860 ;; Along with macros defined through #+MACRO: keyword, default
20861 ;; templates include the following hard-coded macros:
20862 ;; {{{time(format-string)}}}, {{{property(node-property)}}},
20863 ;; {{{input-file}}} and {{{modification-time(format-string)}}}.
20865 ;; During export, {{{author}}}, {{{date}}}, {{{email}}} and
20866 ;; {{{title}}} will also be provided.
20869 (defvar org-macro-templates nil
20870 "Alist containing all macro templates in current buffer.
20871 Associations are in the shape of (NAME . TEMPLATE) where NAME
20872 stands for macro's name and template for its replacement value,
20873 both as strings. This is an internal variable. Do not set it
20874 directly, use instead:
20876 #+MACRO: name template")
20877 (make-variable-buffer-local 'org-macro-templates)
20879 (defun org-macro-expand (macro templates)
20880 "Return expanded MACRO, as a string.
20881 MACRO is an object, obtained, for example, with
20882 `org-element-context'. TEMPLATES is an alist of templates used
20883 for expansion. See `org-macro-templates' for a buffer-local
20884 default value. Return nil if no template was found."
20885 (let ((template
20886 ;; Macro names are case-insensitive.
20887 (cdr (assoc-string (org-element-property :key macro) templates t))))
20888 (when template
20889 (let ((value (replace-regexp-in-string
20890 "\\$[0-9]+"
20891 (lambda (arg)
20892 (or (nth (1- (string-to-number (substring arg 1)))
20893 (org-element-property :args macro))
20894 ;; No argument provided: remove
20895 ;; place-holder.
20896 ""))
20897 template)))
20898 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
20899 (when (string-match "\\`(eval\\>" value)
20900 (setq value (eval (read value))))
20901 ;; Return string.
20902 (format "%s" (or value ""))))))
20904 (defun org-macro-replace-all (templates)
20905 "Replace all macros in current buffer by their expansion.
20906 TEMPLATES is an alist of templates used for expansion. See
20907 `org-macro-templates' for a buffer-local default value."
20908 (save-excursion
20909 (goto-char (point-min))
20910 (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t)
20911 (let ((object (org-element-context)))
20912 (when (eq (org-element-type object) 'macro)
20913 (let ((value (org-macro-expand object templates)))
20914 (when value
20915 (delete-region
20916 (org-element-property :begin object)
20917 ;; Preserve white spaces after the macro.
20918 (progn (goto-char (org-element-property :end object))
20919 (skip-chars-backward " \t")
20920 (point)))
20921 ;; Leave point before replacement in case of recursive
20922 ;; expansions.
20923 (save-excursion (insert value)))))))))
20925 (defun org-macro-initialize-templates ()
20926 "Collect macro templates defined in current buffer.
20927 Templates are stored in buffer-local variable
20928 `org-macro-templates'. In addition to buffer-defined macros, the
20929 function installs the following ones: \"property\", \"date\",
20930 \"time\". and, if appropriate, \"input-file\" and
20931 \"modification-time\"."
20932 (let ((case-fold-search t)
20933 (set-template
20934 (lambda (cell)
20935 ;; Add CELL to `org-macro-templates' if there's no
20936 ;; association matching its name already. Otherwise,
20937 ;; replace old association with the new one in that
20938 ;; variable.
20939 (let ((old-template (assoc (car cell) org-macro-templates)))
20940 (if old-template (setcdr old-template (cdr cell))
20941 (push cell org-macro-templates))))))
20942 ;; Install buffer-local macros.
20943 (org-with-wide-buffer
20944 (goto-char (point-min))
20945 (while (re-search-forward "^[ \t]*#\\+MACRO:" nil t)
20946 (let ((element (org-element-at-point)))
20947 (when (eq (org-element-type element) 'keyword)
20948 (let ((value (org-element-property :value element)))
20949 (when (string-match "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$" value)
20950 (funcall set-template
20951 (cons (match-string 1 value)
20952 (or (match-string 2 value) "")))))))))
20953 ;; Install hard-coded macros.
20954 (mapc (lambda (cell) (funcall set-template cell))
20955 (list
20956 (cons "property" "(eval (org-entry-get nil \"$1\" 'selective))")
20957 (cons "time" "(eval (format-time-string \"$1\"))")))
20958 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
20959 (when (and visited-file (file-exists-p visited-file))
20960 (mapc (lambda (cell) (funcall set-template cell))
20961 (list
20962 (cons "input-file" (file-name-nondirectory visited-file))
20963 (cons "modification-time"
20964 (format "(eval (format-time-string \"$1\" '%s))"
20965 (prin1-to-string
20966 (nth 5 (file-attributes visited-file)))))))))))
20969 ;;; Indentation
20971 (defun org-indent-line ()
20972 "Indent line depending on context."
20973 (interactive)
20974 (let* ((pos (point))
20975 (itemp (org-at-item-p))
20976 (case-fold-search t)
20977 (org-drawer-regexp (or org-drawer-regexp "\000"))
20978 (inline-task-p (and (featurep 'org-inlinetask)
20979 (org-inlinetask-in-task-p)))
20980 (inline-re (and inline-task-p
20981 (org-inlinetask-outline-regexp)))
20982 column)
20983 (if (and orgstruct-is-++ (eq pos (point)))
20984 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
20985 (indent-according-to-mode))
20986 (beginning-of-line 1)
20987 (cond
20988 ;; Headings
20989 ((looking-at org-outline-regexp) (setq column 0))
20990 ;; Included files
20991 ((looking-at "#\\+include:") (setq column 0))
20992 ;; Footnote definition
20993 ((looking-at org-footnote-definition-re) (setq column 0))
20994 ;; Literal examples
20995 ((looking-at "[ \t]*:\\( \\|$\\)")
20996 (setq column (org-get-indentation))) ; do nothing
20997 ;; Lists
20998 ((ignore-errors (goto-char (org-in-item-p)))
20999 (setq column (if itemp
21000 (org-get-indentation)
21001 (org-list-item-body-column (point))))
21002 (goto-char pos))
21003 ;; Drawers
21004 ((and (looking-at "[ \t]*:END:")
21005 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21006 (save-excursion
21007 (goto-char (1- (match-beginning 1)))
21008 (setq column (current-column))))
21009 ;; Special blocks
21010 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21011 (save-excursion
21012 (re-search-backward
21013 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21014 (setq column (org-get-indentation (match-string 0))))
21015 ((and (not (looking-at "[ \t]*#\\+begin_"))
21016 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21017 (save-excursion
21018 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21019 (setq column
21020 (cond ((equal (downcase (match-string 1)) "src")
21021 ;; src blocks: let `org-edit-src-exit' handle them
21022 (org-get-indentation))
21023 ((equal (downcase (match-string 1)) "example")
21024 (max (org-get-indentation)
21025 (org-get-indentation (match-string 0))))
21027 (org-get-indentation (match-string 0))))))
21028 ;; This line has nothing special, look at the previous relevant
21029 ;; line to compute indentation
21031 (beginning-of-line 0)
21032 (while (and (not (bobp))
21033 (not (looking-at org-drawer-regexp))
21034 ;; When point started in an inline task, do not move
21035 ;; above task starting line.
21036 (not (and inline-task-p (looking-at inline-re)))
21037 ;; Skip drawers, blocks, empty lines, verbatim,
21038 ;; comments, tables, footnotes definitions, lists,
21039 ;; inline tasks.
21040 (or (and (looking-at "[ \t]*:END:")
21041 (re-search-backward org-drawer-regexp nil t))
21042 (and (looking-at "[ \t]*#\\+end_")
21043 (re-search-backward "[ \t]*#\\+begin_"nil t))
21044 (looking-at "[ \t]*[\n:#|]")
21045 (looking-at org-footnote-definition-re)
21046 (and (ignore-errors (goto-char (org-in-item-p)))
21047 (goto-char
21048 (org-list-get-top-point (org-list-struct))))
21049 (and (not inline-task-p)
21050 (featurep 'org-inlinetask)
21051 (org-inlinetask-in-task-p)
21052 (or (org-inlinetask-goto-beginning) t))))
21053 (beginning-of-line 0))
21054 (cond
21055 ;; There was an heading above.
21056 ((looking-at "\\*+[ \t]+")
21057 (if (not org-adapt-indentation)
21058 (setq column 0)
21059 (goto-char (match-end 0))
21060 (setq column (current-column))))
21061 ;; A drawer had started and is unfinished
21062 ((looking-at org-drawer-regexp)
21063 (goto-char (1- (match-beginning 1)))
21064 (setq column (current-column)))
21065 ;; Else, nothing noticeable found: get indentation and go on.
21066 (t (setq column (org-get-indentation))))))
21067 ;; Now apply indentation and move cursor accordingly
21068 (goto-char pos)
21069 (if (<= (current-column) (current-indentation))
21070 (org-indent-line-to column)
21071 (save-excursion (org-indent-line-to column)))
21072 ;; Special polishing for properties, see `org-property-format'
21073 (setq column (current-column))
21074 (beginning-of-line 1)
21075 (if (looking-at
21076 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21077 (replace-match (concat (match-string 1)
21078 (format org-property-format
21079 (match-string 2) (match-string 3)))
21080 t t))
21081 (org-move-to-column column))))
21083 (defun org-indent-drawer ()
21084 "Indent the drawer at point."
21085 (interactive)
21086 (let ((p (point))
21087 (e (and (save-excursion (re-search-forward ":END:" nil t))
21088 (match-end 0)))
21089 (folded
21090 (save-excursion
21091 (end-of-line)
21092 (when (overlays-at (point))
21093 (member 'invisible (overlay-properties
21094 (car (overlays-at (point)))))))))
21095 (when folded (org-cycle))
21096 (indent-for-tab-command)
21097 (while (and (move-beginning-of-line 2) (< (point) e))
21098 (indent-for-tab-command))
21099 (goto-char p)
21100 (when folded (org-cycle)))
21101 (message "Drawer at point indented"))
21103 (defun org-indent-block ()
21104 "Indent the block at point."
21105 (interactive)
21106 (let ((p (point))
21107 (case-fold-search t)
21108 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21109 (match-end 0)))
21110 (folded
21111 (save-excursion
21112 (end-of-line)
21113 (when (overlays-at (point))
21114 (member 'invisible (overlay-properties
21115 (car (overlays-at (point)))))))))
21116 (when folded (org-cycle))
21117 (indent-for-tab-command)
21118 (while (and (move-beginning-of-line 2) (< (point) e))
21119 (indent-for-tab-command))
21120 (goto-char p)
21121 (when folded (org-cycle)))
21122 (message "Block at point indented"))
21124 (defun org-indent-region (start end)
21125 "Indent region."
21126 (interactive "r")
21127 (save-excursion
21128 (let ((line-end (org-current-line end)))
21129 (goto-char start)
21130 (while (< (org-current-line) line-end)
21131 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21132 (t (call-interactively 'org-indent-line)))
21133 (move-beginning-of-line 2)))))
21136 ;;; Filling
21138 ;; We use our own fill-paragraph and auto-fill functions.
21140 ;; `org-fill-paragraph' relies on adaptive filling and context
21141 ;; checking. Appropriate `fill-prefix' is computed with
21142 ;; `org-adaptive-fill-function'.
21144 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21145 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21146 ;; `org-adaptive-fill-function' value. Internally,
21147 ;; `org-comment-line-break-function' breaks the line.
21149 ;; `org-setup-filling' installs filling and auto-filling related
21150 ;; variables during `org-mode' initialization.
21152 (defun org-setup-filling ()
21153 (interactive)
21154 ;; Prevent auto-fill from inserting unwanted new items.
21155 (when (boundp 'fill-nobreak-predicate)
21156 (org-set-local
21157 'fill-nobreak-predicate
21158 (org-uniquify
21159 (append fill-nobreak-predicate
21160 '(org-fill-paragraph-separate-nobreak-p
21161 org-fill-line-break-nobreak-p)))))
21162 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21163 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21164 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21165 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21167 (defvar org-element-paragraph-separate) ; org-element.el
21168 (defun org-fill-paragraph-separate-nobreak-p ()
21169 "Non-nil when a line break at point would insert a new item."
21170 (looking-at (substring org-element-paragraph-separate 1)))
21172 (defun org-fill-line-break-nobreak-p ()
21173 "Non-nil when a line break at point would create an Org line break."
21174 (save-excursion
21175 (skip-chars-backward "[ \t]")
21176 (skip-chars-backward "\\\\")
21177 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21179 (declare-function message-in-body-p "message" ())
21180 (defvar org-element--affiliated-re) ; From org-element.el
21181 (defun org-adaptive-fill-function ()
21182 "Compute a fill prefix for the current line.
21183 Return fill prefix, as a string, or nil if current line isn't
21184 meant to be filled."
21185 (org-with-wide-buffer
21186 (unless (and (derived-mode-p 'message-mode) (not (message-in-body-p)))
21187 ;; FIXME: This is really the job of orgstruct++-mode
21188 (let* ((p (line-beginning-position))
21189 (element (save-excursion (beginning-of-line)
21190 (org-element-at-point)))
21191 (type (org-element-type element))
21192 (post-affiliated
21193 (save-excursion
21194 (goto-char (org-element-property :begin element))
21195 (while (looking-at org-element--affiliated-re) (forward-line))
21196 (point))))
21197 (unless (< p post-affiliated)
21198 (case type
21199 (comment (looking-at "[ \t]*# ?") (match-string 0))
21200 (footnote-definition "")
21201 ((item plain-list)
21202 (make-string (org-list-item-body-column post-affiliated) ? ))
21203 (paragraph
21204 ;; Fill prefix is usually the same as the current line,
21205 ;; except if the paragraph is at the beginning of an item.
21206 (let ((parent (org-element-property :parent element)))
21207 (cond ((eq (org-element-type parent) 'item)
21208 (make-string (org-list-item-body-column
21209 (org-element-property :begin parent))
21210 ? ))
21211 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21212 (match-string 0))
21213 (t ""))))
21214 (comment-block
21215 ;; Only fill contents if P is within block boundaries.
21216 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21217 (forward-line)
21218 (point)))
21219 (cend (save-excursion
21220 (goto-char (org-element-property :end element))
21221 (skip-chars-backward " \r\t\n")
21222 (line-beginning-position))))
21223 (when (and (>= p cbeg) (< p cend))
21224 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21225 (match-string 0)
21226 ""))))))))))
21228 (declare-function message-goto-body "message" ())
21229 (defvar message-cite-prefix-regexp) ; From message.el
21230 (defvar org-element-all-objects) ; From org-element.el
21231 (defun org-fill-paragraph (&optional justify)
21232 "Fill element at point, when applicable.
21234 This function only applies to comment blocks, comments, example
21235 blocks and paragraphs. Also, as a special case, re-align table
21236 when point is at one.
21238 If JUSTIFY is non-nil (interactively, with prefix argument),
21239 justify as well. If `sentence-end-double-space' is non-nil, then
21240 period followed by one space does not end a sentence, so don't
21241 break a line there. The variable `fill-column' controls the
21242 width for filling.
21244 For convenience, when point is at a plain list, an item or
21245 a footnote definition, try to fill the first paragraph within."
21246 ;; Falls back on message-fill-paragraph when necessary
21247 (interactive)
21248 (if (and (derived-mode-p 'message-mode)
21249 (or (not (message-in-body-p))
21250 (save-excursion (move-beginning-of-line 1)
21251 (looking-at message-cite-prefix-regexp))))
21252 (let ((fill-paragraph-function
21253 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21254 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21255 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21256 (paragraph-separate
21257 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21258 (fill-paragraph nil))
21259 (save-excursion
21260 ;; Move to end of line in order to get the first paragraph
21261 ;; within a plain list or a footnote definition.
21262 (end-of-line)
21263 (let ((element (org-element-at-point)))
21264 ;; First check if point is in a blank line at the beginning of
21265 ;; the buffer. In that case, ignore filling.
21266 (if (< (point) (org-element-property :begin element)) t
21267 (case (org-element-type element)
21268 ;; Align Org tables, leave table.el tables as-is.
21269 (table-row (org-table-align) t)
21270 (table
21271 (when (eq (org-element-property :type element) 'org)
21272 (org-table-align))
21274 (paragraph
21275 ;; Paragraphs may contain `line-break' type objects.
21276 (let ((beg (max (point-min)
21277 (org-element-property :contents-begin element)))
21278 (end (min (point-max)
21279 (org-element-property :contents-end element))))
21280 ;; Do nothing if point is at an affiliated keyword.
21281 (if (< (point) beg) t
21282 (when (derived-mode-p 'message-mode)
21283 ;; In `message-mode', do not fill following
21284 ;; citation in current paragraph nor text before
21285 ;; message body.
21286 (let ((body-start (save-excursion (message-goto-body))))
21287 (when body-start (setq beg (max body-start beg))))
21288 (when (save-excursion
21289 (re-search-forward
21290 (concat "^" message-cite-prefix-regexp) end t))
21291 (setq end (match-beginning 0))))
21292 ;; Fill paragraph, taking line breaks into
21293 ;; consideration. For that, slice the paragraph
21294 ;; using line breaks as separators, and fill the
21295 ;; parts in reverse order to avoid messing with
21296 ;; markers.
21297 (save-excursion
21298 (goto-char end)
21299 (mapc
21300 (lambda (pos)
21301 (fill-region-as-paragraph pos (point) justify)
21302 (goto-char pos))
21303 ;; Find the list of ending positions for line
21304 ;; breaks in the current paragraph. Add paragraph
21305 ;; beginning to include first slice.
21306 (nreverse
21307 (cons
21309 (org-element-map
21310 (org-element--parse-objects
21311 beg end nil org-element-all-objects)
21312 'line-break
21313 (lambda (lb) (org-element-property :end lb)))))))
21314 t)))
21315 ;; Contents of `comment-block' type elements should be
21316 ;; filled as plain text, but only if point is within block
21317 ;; markers.
21318 (comment-block
21319 (let* ((case-fold-search t)
21320 (beg (save-excursion
21321 (goto-char (org-element-property :begin element))
21322 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21323 (forward-line)
21324 (point)))
21325 (end (save-excursion
21326 (goto-char (org-element-property :end element))
21327 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21328 (line-beginning-position))))
21329 (when (and (>= (point) beg) (< (point) end))
21330 (fill-region-as-paragraph
21331 (save-excursion
21332 (end-of-line)
21333 (re-search-backward "^[ \t]*$" beg 'move)
21334 (line-beginning-position))
21335 (save-excursion
21336 (beginning-of-line)
21337 (re-search-forward "^[ \t]*$" end 'move)
21338 (line-beginning-position))
21339 justify)))
21341 ;; Fill comments.
21342 (comment (fill-comment-paragraph justify))
21343 ;; Ignore every other element.
21344 (otherwise t)))))))
21346 (defun org-auto-fill-function ()
21347 "Auto-fill function."
21348 ;; Check if auto-filling is meaningful.
21349 (let ((fc (current-fill-column)))
21350 (when (and fc (> (current-column) fc))
21351 (let ((fill-prefix (org-adaptive-fill-function)))
21352 (when fill-prefix (do-auto-fill))))))
21354 (defun org-comment-line-break-function (&optional soft)
21355 "Break line at point and indent, continuing comment if within one.
21356 The inserted newline is marked hard if variable
21357 `use-hard-newlines' is true, unless optional argument SOFT is
21358 non-nil."
21359 (if soft (insert-and-inherit ?\n) (newline 1))
21360 (save-excursion (forward-char -1) (delete-horizontal-space))
21361 (delete-horizontal-space)
21362 (indent-to-left-margin)
21363 (insert-before-markers-and-inherit fill-prefix))
21366 ;;; Comments
21368 ;; Org comments syntax is quite complex. It requires the entire line
21369 ;; to be just a comment. Also, even with the right syntax at the
21370 ;; beginning of line, some some elements (i.e. verse-block or
21371 ;; example-block) don't accept comments. Usual Emacs comment commands
21372 ;; cannot cope with those requirements. Therefore, Org replaces them.
21374 ;; Org still relies on `comment-dwim', but cannot trust
21375 ;; `comment-only-p'. So, `comment-region-function' and
21376 ;; `uncomment-region-function' both point
21377 ;; to`org-comment-or-uncomment-region'. Eventually,
21378 ;; `org-insert-comment' takes care of insertion of comments at the
21379 ;; beginning of line.
21381 ;; `org-setup-comments-handling' install comments related variables
21382 ;; during `org-mode' initialization.
21384 (defun org-setup-comments-handling ()
21385 (interactive)
21386 (org-set-local 'comment-use-syntax nil)
21387 (org-set-local 'comment-start "# ")
21388 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21389 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21390 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21391 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21393 (defun org-insert-comment ()
21394 "Insert an empty comment above current line.
21395 If the line is empty, insert comment at its beginning."
21396 (beginning-of-line)
21397 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21398 (org-indent-line)
21399 (insert "# "))
21401 (defvar comment-empty-lines) ; From newcomment.el.
21402 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21403 "Comment or uncomment each non-blank line in the region.
21404 Uncomment each non-blank line between BEG and END if it only
21405 contains commented lines. Otherwise, comment them."
21406 (save-restriction
21407 ;; Restrict region
21408 (narrow-to-region (save-excursion (goto-char beg)
21409 (skip-chars-forward " \r\t\n" end)
21410 (line-beginning-position))
21411 (save-excursion (goto-char end)
21412 (skip-chars-backward " \r\t\n" beg)
21413 (line-end-position)))
21414 (let ((uncommentp
21415 ;; UNCOMMENTP is non-nil when every non blank line between
21416 ;; BEG and END is a comment.
21417 (save-excursion
21418 (goto-char (point-min))
21419 (while (and (not (eobp))
21420 (let ((element (org-element-at-point)))
21421 (and (eq (org-element-type element) 'comment)
21422 (goto-char (min (point-max)
21423 (org-element-property
21424 :end element)))))))
21425 (eobp))))
21426 (if uncommentp
21427 ;; Only blank lines and comments in region: uncomment it.
21428 (save-excursion
21429 (goto-char (point-min))
21430 (while (not (eobp))
21431 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21432 (replace-match "" nil nil nil 1))
21433 (forward-line)))
21434 ;; Comment each line in region.
21435 (let ((min-indent (point-max)))
21436 ;; First find the minimum indentation across all lines.
21437 (save-excursion
21438 (goto-char (point-min))
21439 (while (and (not (eobp)) (not (zerop min-indent)))
21440 (unless (looking-at "[ \t]*$")
21441 (setq min-indent (min min-indent (current-indentation))))
21442 (forward-line)))
21443 ;; Then loop over all lines.
21444 (save-excursion
21445 (goto-char (point-min))
21446 (while (not (eobp))
21447 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21448 (org-move-to-column min-indent t)
21449 (insert comment-start))
21450 (forward-line))))))))
21453 ;;; Other stuff.
21455 (defun org-toggle-fixed-width-section (arg)
21456 "Toggle the fixed-width export.
21457 If there is no active region, the QUOTE keyword at the current headline is
21458 inserted or removed. When present, it causes the text between this headline
21459 and the next to be exported as fixed-width text, and unmodified.
21460 If there is an active region, this command adds or removes a colon as the
21461 first character of this line. If the first character of a line is a colon,
21462 this line is also exported in fixed-width font."
21463 (interactive "P")
21464 (let* ((cc 0)
21465 (regionp (org-region-active-p))
21466 (beg (if regionp (region-beginning) (point)))
21467 (end (if regionp (region-end)))
21468 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21469 (case-fold-search nil)
21470 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21471 off)
21472 (if regionp
21473 (save-excursion
21474 (goto-char beg)
21475 (setq cc (current-column))
21476 (beginning-of-line 1)
21477 (setq off (looking-at re))
21478 (while (> nlines 0)
21479 (setq nlines (1- nlines))
21480 (beginning-of-line 1)
21481 (cond
21482 (arg
21483 (org-move-to-column cc t)
21484 (insert ": \n")
21485 (forward-line -1))
21486 ((and off (looking-at re))
21487 (replace-match "" t t nil 1))
21488 ((not off) (org-move-to-column cc t) (insert ": ")))
21489 (forward-line 1)))
21490 (save-excursion
21491 (org-back-to-heading)
21492 (cond
21493 ((looking-at (format org-heading-keyword-regexp-format
21494 org-quote-string))
21495 (goto-char (match-end 1))
21496 (looking-at (concat " +" org-quote-string))
21497 (replace-match "" t t)
21498 (when (eolp) (insert " ")))
21499 ((looking-at org-outline-regexp)
21500 (goto-char (match-end 0))
21501 (insert org-quote-string " ")))))))
21503 (defun org-reftex-citation ()
21504 "Use reftex-citation to insert a citation into the buffer.
21505 This looks for a line like
21507 #+BIBLIOGRAPHY: foo plain option:-d
21509 and derives from it that foo.bib is the bibliography file relevant
21510 for this document. It then installs the necessary environment for RefTeX
21511 to work in this buffer and calls `reftex-citation' to insert a citation
21512 into the buffer.
21514 Export of such citations to both LaTeX and HTML is handled by the contributed
21515 package org-exp-bibtex by Taru Karttunen."
21516 (interactive)
21517 (let ((reftex-docstruct-symbol 'rds)
21518 (reftex-cite-format "\\cite{%l}")
21519 rds bib)
21520 (save-excursion
21521 (save-restriction
21522 (widen)
21523 (let ((case-fold-search t)
21524 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
21525 (if (not (save-excursion
21526 (or (re-search-forward re nil t)
21527 (re-search-backward re nil t))))
21528 (error "No bibliography defined in file")
21529 (setq bib (concat (match-string 1) ".bib")
21530 rds (list (list 'bib bib)))))))
21531 (call-interactively 'reftex-citation)))
21533 ;;;; Functions extending outline functionality
21535 (defun org-beginning-of-line (&optional arg)
21536 "Go to the beginning of the current line. If that is invisible, continue
21537 to a visible line beginning. This makes the function of C-a more intuitive.
21538 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21539 first attempt, and only move to after the tags when the cursor is already
21540 beyond the end of the headline."
21541 (interactive "P")
21542 (let ((pos (point))
21543 (special (if (consp org-special-ctrl-a/e)
21544 (car org-special-ctrl-a/e)
21545 org-special-ctrl-a/e))
21546 refpos)
21547 (if (org-bound-and-true-p line-move-visual)
21548 (beginning-of-visual-line 1)
21549 (beginning-of-line 1))
21550 (if (and arg (fboundp 'move-beginning-of-line))
21551 (call-interactively 'move-beginning-of-line)
21552 (if (bobp)
21554 (backward-char 1)
21555 (if (org-truely-invisible-p)
21556 (while (and (not (bobp)) (org-truely-invisible-p))
21557 (backward-char 1)
21558 (beginning-of-line 1))
21559 (forward-char 1))))
21560 (when special
21561 (cond
21562 ((and (looking-at org-complex-heading-regexp)
21563 (= (char-after (match-end 1)) ?\ ))
21564 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
21565 (point-at-eol)))
21566 (goto-char
21567 (if (eq special t)
21568 (cond ((> pos refpos) refpos)
21569 ((= pos (point)) refpos)
21570 (t (point)))
21571 (cond ((> pos (point)) (point))
21572 ((not (eq last-command this-command)) (point))
21573 (t refpos)))))
21574 ((org-at-item-p)
21575 ;; Being at an item and not looking at an the item means point
21576 ;; was previously moved to beginning of a visual line, which
21577 ;; doesn't contain the item. Therefore, do nothing special,
21578 ;; just stay here.
21579 (when (looking-at org-list-full-item-re)
21580 ;; Set special position at first white space character after
21581 ;; bullet, and check-box, if any.
21582 (let ((after-bullet
21583 (let ((box (match-end 3)))
21584 (if (not box) (match-end 1)
21585 (let ((after (char-after box)))
21586 (if (and after (= after ? )) (1+ box) box))))))
21587 ;; Special case: Move point to special position when
21588 ;; currently after it or at beginning of line.
21589 (if (eq special t)
21590 (when (or (> pos after-bullet) (= (point) pos))
21591 (goto-char after-bullet))
21592 ;; Reversed case: Move point to special position when
21593 ;; point was already at beginning of line and command is
21594 ;; repeated.
21595 (when (and (= (point) pos) (eq last-command this-command))
21596 (goto-char after-bullet))))))))
21597 (org-no-warnings
21598 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21600 (defun org-end-of-line (&optional arg)
21601 "Go to the end of the line.
21602 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21603 first attempt, and only move to after the tags when the cursor is already
21604 beyond the end of the headline."
21605 (interactive "P")
21606 (let ((special (if (consp org-special-ctrl-a/e)
21607 (cdr org-special-ctrl-a/e)
21608 org-special-ctrl-a/e)))
21609 (cond
21610 ((or (not special) arg
21611 (not (or (org-at-heading-p) (org-at-item-p) (org-at-drawer-p))))
21612 (call-interactively
21613 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21614 ((fboundp 'move-end-of-line) 'move-end-of-line)
21615 (t 'end-of-line))))
21616 ((org-at-heading-p)
21617 (let ((pos (point)))
21618 (beginning-of-line 1)
21619 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21620 (if (eq special t)
21621 (if (or (< pos (match-beginning 1))
21622 (= pos (match-end 0)))
21623 (goto-char (match-beginning 1))
21624 (goto-char (match-end 0)))
21625 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
21626 (goto-char (match-end 0))
21627 (goto-char (match-beginning 1))))
21628 (call-interactively (if (fboundp 'move-end-of-line)
21629 'move-end-of-line
21630 'end-of-line)))))
21631 ((org-at-drawer-p)
21632 (move-end-of-line 1)
21633 (when (overlays-at (1- (point))) (backward-char 1)))
21634 ;; At an item: Move before any hidden text.
21635 (t (call-interactively
21636 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21637 ((fboundp 'move-end-of-line) 'move-end-of-line)
21638 (t 'end-of-line)))))
21639 (org-no-warnings
21640 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21642 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21643 (define-key org-mode-map "\C-e" 'org-end-of-line)
21645 (defun org-backward-sentence (&optional arg)
21646 "Go to beginning of sentence, or beginning of table field.
21647 This will call `backward-sentence' or `org-table-beginning-of-field',
21648 depending on context."
21649 (interactive "P")
21650 (cond
21651 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21652 (t (call-interactively 'backward-sentence))))
21654 (defun org-forward-sentence (&optional arg)
21655 "Go to end of sentence, or end of table field.
21656 This will call `forward-sentence' or `org-table-end-of-field',
21657 depending on context."
21658 (interactive "P")
21659 (cond
21660 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21661 (t (call-interactively 'forward-sentence))))
21663 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21664 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21666 (defun org-kill-line (&optional arg)
21667 "Kill line, to tags or end of line."
21668 (interactive "P")
21669 (cond
21670 ((or (not org-special-ctrl-k)
21671 (bolp)
21672 (not (org-at-heading-p)))
21673 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21674 org-ctrl-k-protect-subtree)
21675 (if (or (eq org-ctrl-k-protect-subtree 'error)
21676 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21677 (error "C-k aborted - would kill hidden subtree")))
21678 (call-interactively
21679 (if (and (boundp 'visual-line-mode) visual-line-mode) 'kill-visual-line 'kill-line)))
21680 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21681 (kill-region (point) (match-beginning 1))
21682 (org-set-tags nil t))
21683 (t (kill-region (point) (point-at-eol)))))
21685 (define-key org-mode-map "\C-k" 'org-kill-line)
21687 (defun org-yank (&optional arg)
21688 "Yank. If the kill is a subtree, treat it specially.
21689 This command will look at the current kill and check if is a single
21690 subtree, or a series of subtrees[1]. If it passes the test, and if the
21691 cursor is at the beginning of a line or after the stars of a currently
21692 empty headline, then the yank is handled specially. How exactly depends
21693 on the value of the following variables, both set by default.
21695 org-yank-folded-subtrees
21696 When set, the subtree(s) will be folded after insertion, but only
21697 if doing so would now swallow text after the yanked text.
21699 org-yank-adjusted-subtrees
21700 When set, the subtree will be promoted or demoted in order to
21701 fit into the local outline tree structure, which means that the level
21702 will be adjusted so that it becomes the smaller one of the two
21703 *visible* surrounding headings.
21705 Any prefix to this command will cause `yank' to be called directly with
21706 no special treatment. In particular, a simple \\[universal-argument] prefix \
21707 will just
21708 plainly yank the text as it is.
21710 \[1] The test checks if the first non-white line is a heading
21711 and if there are no other headings with fewer stars."
21712 (interactive "P")
21713 (org-yank-generic 'yank arg))
21715 (defun org-yank-generic (command arg)
21716 "Perform some yank-like command.
21718 This function implements the behavior described in the `org-yank'
21719 documentation. However, it has been generalized to work for any
21720 interactive command with similar behavior."
21722 ;; pretend to be command COMMAND
21723 (setq this-command command)
21725 (if arg
21726 (call-interactively command)
21728 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21729 (and (org-kill-is-subtree-p)
21730 (or (bolp)
21731 (and (looking-at "[ \t]*$")
21732 (string-match
21733 "\\`\\*+\\'"
21734 (buffer-substring (point-at-bol) (point)))))))
21735 swallowp)
21736 (cond
21737 ((and subtreep org-yank-folded-subtrees)
21738 (let ((beg (point))
21739 end)
21740 (if (and subtreep org-yank-adjusted-subtrees)
21741 (org-paste-subtree nil nil 'for-yank)
21742 (call-interactively command))
21744 (setq end (point))
21745 (goto-char beg)
21746 (when (and (bolp) subtreep
21747 (not (setq swallowp
21748 (org-yank-folding-would-swallow-text beg end))))
21749 (org-with-limited-levels
21750 (or (looking-at org-outline-regexp)
21751 (re-search-forward org-outline-regexp-bol end t))
21752 (while (and (< (point) end) (looking-at org-outline-regexp))
21753 (hide-subtree)
21754 (org-cycle-show-empty-lines 'folded)
21755 (condition-case nil
21756 (outline-forward-same-level 1)
21757 (error (goto-char end))))))
21758 (when swallowp
21759 (message
21760 "Inserted text not folded because that would swallow text"))
21762 (goto-char end)
21763 (skip-chars-forward " \t\n\r")
21764 (beginning-of-line 1)
21765 (push-mark beg 'nomsg)))
21766 ((and subtreep org-yank-adjusted-subtrees)
21767 (let ((beg (point-at-bol)))
21768 (org-paste-subtree nil nil 'for-yank)
21769 (push-mark beg 'nomsg)))
21771 (call-interactively command))))))
21773 (defun org-yank-folding-would-swallow-text (beg end)
21774 "Would hide-subtree at BEG swallow any text after END?"
21775 (let (level)
21776 (org-with-limited-levels
21777 (save-excursion
21778 (goto-char beg)
21779 (when (or (looking-at org-outline-regexp)
21780 (re-search-forward org-outline-regexp-bol end t))
21781 (setq level (org-outline-level)))
21782 (goto-char end)
21783 (skip-chars-forward " \t\r\n\v\f")
21784 (if (or (eobp)
21785 (and (bolp) (looking-at org-outline-regexp)
21786 (<= (org-outline-level) level)))
21787 nil ; Nothing would be swallowed
21788 t))))) ; something would swallow
21790 (define-key org-mode-map "\C-y" 'org-yank)
21792 (defun org-truely-invisible-p ()
21793 "Check if point is at a character currently not visible.
21794 This version does not only check the character property, but also
21795 `visible-mode'."
21796 ;; Early versions of noutline don't have `outline-invisible-p'.
21797 (if (org-bound-and-true-p visible-mode)
21799 (outline-invisible-p)))
21801 (defun org-invisible-p2 ()
21802 "Check if point is at a character currently not visible."
21803 (save-excursion
21804 (if (and (eolp) (not (bobp))) (backward-char 1))
21805 ;; Early versions of noutline don't have `outline-invisible-p'.
21806 (outline-invisible-p)))
21808 (defun org-back-to-heading (&optional invisible-ok)
21809 "Call `outline-back-to-heading', but provide a better error message."
21810 (condition-case nil
21811 (outline-back-to-heading invisible-ok)
21812 (error (error "Before first headline at position %d in buffer %s"
21813 (point) (current-buffer)))))
21815 (defun org-before-first-heading-p ()
21816 "Before first heading?"
21817 (save-excursion
21818 (end-of-line)
21819 (null (re-search-backward org-outline-regexp-bol nil t))))
21821 (defun org-at-heading-p (&optional ignored)
21822 (outline-on-heading-p t))
21823 ;; Compatibility alias with Org versions < 7.8.03
21824 (defalias 'org-on-heading-p 'org-at-heading-p)
21826 (defun org-at-comment-p nil
21827 "Is cursor in a line starting with a # character?"
21828 (save-excursion
21829 (beginning-of-line)
21830 (looking-at "^#")))
21832 (defun org-at-drawer-p nil
21833 "Is cursor at a drawer keyword?"
21834 (save-excursion
21835 (move-beginning-of-line 1)
21836 (looking-at org-drawer-regexp)))
21838 (defun org-at-block-p nil
21839 "Is cursor at a block keyword?"
21840 (save-excursion
21841 (move-beginning-of-line 1)
21842 (looking-at org-block-regexp)))
21844 (defun org-point-at-end-of-empty-headline ()
21845 "If point is at the end of an empty headline, return t, else nil.
21846 If the heading only contains a TODO keyword, it is still still considered
21847 empty."
21848 (and (looking-at "[ \t]*$")
21849 (when org-todo-line-regexp
21850 (save-excursion
21851 (beginning-of-line 1)
21852 (let ((case-fold-search nil))
21853 (looking-at org-todo-line-regexp)
21854 (string= (match-string 3) ""))))))
21856 (defun org-at-heading-or-item-p ()
21857 (or (org-at-heading-p) (org-at-item-p)))
21859 (defun org-at-target-p ()
21860 (or (org-in-regexp org-radio-target-regexp)
21861 (org-in-regexp org-target-regexp)))
21862 ;; Compatibility alias with Org versions < 7.8.03
21863 (defalias 'org-on-target-p 'org-at-target-p)
21865 (defun org-up-heading-all (arg)
21866 "Move to the heading line of which the present line is a subheading.
21867 This function considers both visible and invisible heading lines.
21868 With argument, move up ARG levels."
21869 (if (fboundp 'outline-up-heading-all)
21870 (outline-up-heading-all arg) ; emacs 21 version of outline.el
21871 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21873 (defun org-up-heading-safe ()
21874 "Move to the heading line of which the present line is a subheading.
21875 This version will not throw an error. It will return the level of the
21876 headline found, or nil if no higher level is found.
21878 Also, this function will be a lot faster than `outline-up-heading',
21879 because it relies on stars being the outline starters. This can really
21880 make a significant difference in outlines with very many siblings."
21881 (let (start-level re)
21882 (org-back-to-heading t)
21883 (setq start-level (funcall outline-level))
21884 (if (equal start-level 1)
21886 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21887 (if (re-search-backward re nil t)
21888 (funcall outline-level)))))
21890 (defun org-first-sibling-p ()
21891 "Is this heading the first child of its parents?"
21892 (interactive)
21893 (let ((re org-outline-regexp-bol)
21894 level l)
21895 (unless (org-at-heading-p t)
21896 (error "Not at a heading"))
21897 (setq level (funcall outline-level))
21898 (save-excursion
21899 (if (not (re-search-backward re nil t))
21901 (setq l (funcall outline-level))
21902 (< l level)))))
21904 (defun org-goto-sibling (&optional previous)
21905 "Goto the next sibling, even if it is invisible.
21906 When PREVIOUS is set, go to the previous sibling instead. Returns t
21907 when a sibling was found. When none is found, return nil and don't
21908 move point."
21909 (let ((fun (if previous 're-search-backward 're-search-forward))
21910 (pos (point))
21911 (re org-outline-regexp-bol)
21912 level l)
21913 (when (condition-case nil (org-back-to-heading t) (error nil))
21914 (setq level (funcall outline-level))
21915 (catch 'exit
21916 (or previous (forward-char 1))
21917 (while (funcall fun re nil t)
21918 (setq l (funcall outline-level))
21919 (when (< l level) (goto-char pos) (throw 'exit nil))
21920 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21921 (goto-char pos)
21922 nil))))
21924 (defun org-show-siblings ()
21925 "Show all siblings of the current headline."
21926 (save-excursion
21927 (while (org-goto-sibling) (org-flag-heading nil)))
21928 (save-excursion
21929 (while (org-goto-sibling 'previous)
21930 (org-flag-heading nil))))
21932 (defun org-goto-first-child ()
21933 "Goto the first child, even if it is invisible.
21934 Return t when a child was found. Otherwise don't move point and
21935 return nil."
21936 (let (level (pos (point)) (re org-outline-regexp-bol))
21937 (when (condition-case nil (org-back-to-heading t) (error nil))
21938 (setq level (outline-level))
21939 (forward-char 1)
21940 (if (and (re-search-forward re nil t) (> (outline-level) level))
21941 (progn (goto-char (match-beginning 0)) t)
21942 (goto-char pos) nil))))
21944 (defun org-show-hidden-entry ()
21945 "Show an entry where even the heading is hidden."
21946 (save-excursion
21947 (org-show-entry)))
21949 (defun org-flag-heading (flag &optional entry)
21950 "Flag the current heading. FLAG non-nil means make invisible.
21951 When ENTRY is non-nil, show the entire entry."
21952 (save-excursion
21953 (org-back-to-heading t)
21954 ;; Check if we should show the entire entry
21955 (if entry
21956 (progn
21957 (org-show-entry)
21958 (save-excursion
21959 (and (outline-next-heading)
21960 (org-flag-heading nil))))
21961 (outline-flag-region (max (point-min) (1- (point)))
21962 (save-excursion (outline-end-of-heading) (point))
21963 flag))))
21965 (defun org-get-next-sibling ()
21966 "Move to next heading of the same level, and return point.
21967 If there is no such heading, return nil.
21968 This is like outline-next-sibling, but invisible headings are ok."
21969 (let ((level (funcall outline-level)))
21970 (outline-next-heading)
21971 (while (and (not (eobp)) (> (funcall outline-level) level))
21972 (outline-next-heading))
21973 (if (or (eobp) (< (funcall outline-level) level))
21975 (point))))
21977 (defun org-get-last-sibling ()
21978 "Move to previous heading of the same level, and return point.
21979 If there is no such heading, return nil."
21980 (let ((opoint (point))
21981 (level (funcall outline-level)))
21982 (outline-previous-heading)
21983 (when (and (/= (point) opoint) (outline-on-heading-p t))
21984 (while (and (> (funcall outline-level) level)
21985 (not (bobp)))
21986 (outline-previous-heading))
21987 (if (< (funcall outline-level) level)
21989 (point)))))
21991 (defun org-end-of-subtree (&optional invisible-ok to-heading)
21992 "Goto to the end of a subtree."
21993 ;; This contains an exact copy of the original function, but it uses
21994 ;; `org-back-to-heading', to make it work also in invisible
21995 ;; trees. And is uses an invisible-ok argument.
21996 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21997 ;; Furthermore, when used inside Org, finding the end of a large subtree
21998 ;; with many children and grandchildren etc, this can be much faster
21999 ;; than the outline version.
22000 (org-back-to-heading invisible-ok)
22001 (let ((first t)
22002 (level (funcall outline-level)))
22003 (if (and (derived-mode-p 'org-mode) (< level 1000))
22004 ;; A true heading (not a plain list item), in Org-mode
22005 ;; This means we can easily find the end by looking
22006 ;; only for the right number of stars. Using a regexp to do
22007 ;; this is so much faster than using a Lisp loop.
22008 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22009 (forward-char 1)
22010 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22011 ;; something else, do it the slow way
22012 (while (and (not (eobp))
22013 (or first (> (funcall outline-level) level)))
22014 (setq first nil)
22015 (outline-next-heading)))
22016 (unless to-heading
22017 (if (memq (preceding-char) '(?\n ?\^M))
22018 (progn
22019 ;; Go to end of line before heading
22020 (forward-char -1)
22021 (if (memq (preceding-char) '(?\n ?\^M))
22022 ;; leave blank line before heading
22023 (forward-char -1))))))
22024 (point))
22026 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22027 "Use Org version in org-mode, for dramatic speed-up."
22028 (if (derived-mode-p 'org-mode)
22029 (progn
22030 (org-end-of-subtree nil t)
22031 (unless (eobp) (backward-char 1)))
22032 ad-do-it))
22034 (defun org-end-of-meta-data-and-drawers ()
22035 "Jump to the first text after meta data and drawers in the current entry.
22036 This will move over empty lines, lines with planning time stamps,
22037 clocking lines, and drawers."
22038 (org-back-to-heading t)
22039 (let ((end (save-excursion (outline-next-heading) (point)))
22040 (re (concat "\\(" org-drawer-regexp "\\)"
22041 "\\|" "[ \t]*" org-keyword-time-regexp)))
22042 (forward-line 1)
22043 (while (re-search-forward re end t)
22044 (if (not (match-end 1))
22045 ;; empty or planning line
22046 (forward-line 1)
22047 ;; a drawer, find the end
22048 (re-search-forward "^[ \t]*:END:" end 'move)
22049 (forward-line 1)))
22050 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22051 (point)))
22053 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22054 "Move forward to the arg'th subheading at same level as this one.
22055 Stop at the first and last subheadings of a superior heading.
22056 Normally this only looks at visible headings, but when INVISIBLE-OK is
22057 non-nil it will also look at invisible ones."
22058 (interactive "p")
22059 (org-back-to-heading invisible-ok)
22060 (org-at-heading-p)
22061 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22062 (re (format "^\\*\\{1,%d\\} " level))
22064 (forward-char 1)
22065 (while (> arg 0)
22066 (while (and (re-search-forward re nil 'move)
22067 (setq l (- (match-end 0) (match-beginning 0) 1))
22068 (= l level)
22069 (not invisible-ok)
22070 (progn (backward-char 1) (outline-invisible-p)))
22071 (if (< l level) (setq arg 1)))
22072 (setq arg (1- arg)))
22073 (beginning-of-line 1)))
22075 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22076 "Move backward to the arg'th subheading at same level as this one.
22077 Stop at the first and last subheadings of a superior heading."
22078 (interactive "p")
22079 (org-back-to-heading)
22080 (org-at-heading-p)
22081 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22082 (re (format "^\\*\\{1,%d\\} " level))
22084 (while (> arg 0)
22085 (while (and (re-search-backward re nil 'move)
22086 (setq l (- (match-end 0) (match-beginning 0) 1))
22087 (= l level)
22088 (not invisible-ok)
22089 (outline-invisible-p))
22090 (if (< l level) (setq arg 1)))
22091 (setq arg (1- arg)))))
22093 (defun org-forward-element ()
22094 "Move forward by one element.
22095 Move to the next element at the same level, when possible."
22096 (interactive)
22097 (cond ((eobp) (error "Cannot move further down"))
22098 ((org-with-limited-levels (org-at-heading-p))
22099 (let ((origin (point)))
22100 (org-forward-heading-same-level 1)
22101 (unless (org-with-limited-levels (org-at-heading-p))
22102 (goto-char origin)
22103 (error "Cannot move further down"))))
22105 (let* ((elem (org-element-at-point))
22106 (end (org-element-property :end elem))
22107 (parent (org-element-property :parent elem)))
22108 (if (and parent (= (org-element-property :contents-end parent) end))
22109 (goto-char (org-element-property :end parent))
22110 (goto-char end))))))
22112 (defun org-backward-element ()
22113 "Move backward by one element.
22114 Move to the previous element at the same level, when possible."
22115 (interactive)
22116 (cond ((bobp) (error "Cannot move further up"))
22117 ((org-with-limited-levels (org-at-heading-p))
22118 ;; At an headline, move to the previous one, if any, or stay
22119 ;; here.
22120 (let ((origin (point)))
22121 (org-backward-heading-same-level 1)
22122 (unless (org-with-limited-levels (org-at-heading-p))
22123 (goto-char origin)
22124 (error "Cannot move further up"))))
22126 (let* ((trail (org-element-at-point 'keep-trail))
22127 (elem (car trail))
22128 (prev-elem (nth 1 trail))
22129 (beg (org-element-property :begin elem)))
22130 (cond
22131 ;; Move to beginning of current element if point isn't
22132 ;; there already.
22133 ((/= (point) beg) (goto-char beg))
22134 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22135 ((org-before-first-heading-p) (goto-char (point-min)))
22136 (t (org-back-to-heading)))))))
22138 (defun org-up-element ()
22139 "Move to upper element."
22140 (interactive)
22141 (if (org-with-limited-levels (org-at-heading-p))
22142 (unless (org-up-heading-safe) (error "No surrounding element"))
22143 (let* ((elem (org-element-at-point))
22144 (parent (org-element-property :parent elem)))
22145 (if parent (goto-char (org-element-property :begin parent))
22146 (if (org-with-limited-levels (org-before-first-heading-p))
22147 (error "No surrounding element")
22148 (org-with-limited-levels (org-back-to-heading)))))))
22150 (defvar org-element-greater-elements)
22151 (defun org-down-element ()
22152 "Move to inner element."
22153 (interactive)
22154 (let ((element (org-element-at-point)))
22155 (cond
22156 ((memq (org-element-type element) '(plain-list table))
22157 (goto-char (org-element-property :contents-begin element))
22158 (forward-char))
22159 ((memq (org-element-type element) org-element-greater-elements)
22160 ;; If contents are hidden, first disclose them.
22161 (when (org-element-property :hiddenp element) (org-cycle))
22162 (goto-char (or (org-element-property :contents-begin element)
22163 (error "No content for this element"))))
22164 (t (error "No inner element")))))
22166 (defun org-drag-element-backward ()
22167 "Move backward element at point."
22168 (interactive)
22169 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22170 (let* ((trail (org-element-at-point 'keep-trail))
22171 (elem (car trail))
22172 (prev-elem (nth 1 trail)))
22173 ;; Error out if no previous element or previous element is
22174 ;; a parent of the current one.
22175 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22176 (error "Cannot drag element backward")
22177 (let ((pos (point)))
22178 (org-element-swap-A-B prev-elem elem)
22179 (goto-char (+ (org-element-property :begin prev-elem)
22180 (- pos (org-element-property :begin elem)))))))))
22182 (defun org-drag-element-forward ()
22183 "Move forward element at point."
22184 (interactive)
22185 (let* ((pos (point))
22186 (elem (org-element-at-point)))
22187 (when (= (point-max) (org-element-property :end elem))
22188 (error "Cannot drag element forward"))
22189 (goto-char (org-element-property :end elem))
22190 (let ((next-elem (org-element-at-point)))
22191 (when (or (org-element-nested-p elem next-elem)
22192 (and (eq (org-element-type next-elem) 'headline)
22193 (not (eq (org-element-type elem) 'headline))))
22194 (goto-char pos)
22195 (error "Cannot drag element forward"))
22196 ;; Compute new position of point: it's shifted by NEXT-ELEM
22197 ;; body's length (without final blanks) and by the length of
22198 ;; blanks between ELEM and NEXT-ELEM.
22199 (let ((size-next (- (save-excursion
22200 (goto-char (org-element-property :end next-elem))
22201 (skip-chars-backward " \r\t\n")
22202 (forward-line)
22203 ;; Small correction if buffer doesn't end
22204 ;; with a newline character.
22205 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22206 (org-element-property :begin next-elem)))
22207 (size-blank (- (org-element-property :end elem)
22208 (save-excursion
22209 (goto-char (org-element-property :end elem))
22210 (skip-chars-backward " \r\t\n")
22211 (forward-line)
22212 (point)))))
22213 (org-element-swap-A-B elem next-elem)
22214 (goto-char (+ pos size-next size-blank))))))
22216 (defun org-mark-element ()
22217 "Put point at beginning of this element, mark at end.
22219 Interactively, if this command is repeated or (in Transient Mark
22220 mode) if the mark is active, it marks the next element after the
22221 ones already marked."
22222 (interactive)
22223 (let (deactivate-mark)
22224 (if (and (org-called-interactively-p 'any)
22225 (or (and (eq last-command this-command) (mark t))
22226 (and transient-mark-mode mark-active)))
22227 (set-mark
22228 (save-excursion
22229 (goto-char (mark))
22230 (goto-char (org-element-property :end (org-element-at-point)))))
22231 (let ((element (org-element-at-point)))
22232 (end-of-line)
22233 (push-mark (org-element-property :end element) t t)
22234 (goto-char (org-element-property :begin element))))))
22236 (defun org-narrow-to-element ()
22237 "Narrow buffer to current element."
22238 (interactive)
22239 (let ((elem (org-element-at-point)))
22240 (cond
22241 ((eq (car elem) 'headline)
22242 (narrow-to-region
22243 (org-element-property :begin elem)
22244 (org-element-property :end elem)))
22245 ((memq (car elem) org-element-greater-elements)
22246 (narrow-to-region
22247 (org-element-property :contents-begin elem)
22248 (org-element-property :contents-end elem)))
22250 (narrow-to-region
22251 (org-element-property :begin elem)
22252 (org-element-property :end elem))))))
22254 (defun org-transpose-element ()
22255 "Transpose current and previous elements, keeping blank lines between.
22256 Point is moved after both elements."
22257 (interactive)
22258 (org-skip-whitespace)
22259 (let ((end (org-element-property :end (org-element-at-point))))
22260 (org-drag-element-backward)
22261 (goto-char end)))
22263 (defun org-unindent-buffer ()
22264 "Un-indent the visible part of the buffer.
22265 Relative indentation (between items, inside blocks, etc.) isn't
22266 modified."
22267 (interactive)
22268 (unless (eq major-mode 'org-mode)
22269 (error "Cannot un-indent a buffer not in Org mode"))
22270 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22271 unindent-tree ; For byte-compiler.
22272 (unindent-tree
22273 (function
22274 (lambda (contents)
22275 (mapc
22276 (lambda (element)
22277 (if (memq (org-element-type element) '(headline section))
22278 (funcall unindent-tree (org-element-contents element))
22279 (save-excursion
22280 (save-restriction
22281 (narrow-to-region
22282 (org-element-property :begin element)
22283 (org-element-property :end element))
22284 (org-do-remove-indentation)))))
22285 (reverse contents))))))
22286 (funcall unindent-tree (org-element-contents parse-tree))))
22288 (defun org-show-subtree ()
22289 "Show everything after this heading at deeper levels."
22290 (interactive)
22291 (outline-flag-region
22292 (point)
22293 (save-excursion
22294 (org-end-of-subtree t t))
22295 nil))
22297 (defun org-show-entry ()
22298 "Show the body directly following this heading.
22299 Show the heading too, if it is currently invisible."
22300 (interactive)
22301 (save-excursion
22302 (condition-case nil
22303 (progn
22304 (org-back-to-heading t)
22305 (outline-flag-region
22306 (max (point-min) (1- (point)))
22307 (save-excursion
22308 (if (re-search-forward
22309 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22310 (match-beginning 1)
22311 (point-max)))
22312 nil)
22313 (org-cycle-hide-drawers 'children))
22314 (error nil))))
22316 (defun org-make-options-regexp (kwds &optional extra)
22317 "Make a regular expression for keyword lines."
22318 (concat
22319 "^#\\+\\("
22320 (mapconcat 'regexp-quote kwds "\\|")
22321 (if extra (concat "\\|" extra))
22322 "\\):[ \t]*\\(.*\\)"))
22324 ;; Make isearch reveal the necessary context
22325 (defun org-isearch-end ()
22326 "Reveal context after isearch exits."
22327 (when isearch-success ; only if search was successful
22328 (if (featurep 'xemacs)
22329 ;; Under XEmacs, the hook is run in the correct place,
22330 ;; we directly show the context.
22331 (org-show-context 'isearch)
22332 ;; In Emacs the hook runs *before* restoring the overlays.
22333 ;; So we have to use a one-time post-command-hook to do this.
22334 ;; (Emacs 22 has a special variable, see function `org-mode')
22335 (unless (and (boundp 'isearch-mode-end-hook-quit)
22336 isearch-mode-end-hook-quit)
22337 ;; Only when the isearch was not quitted.
22338 (org-add-hook 'post-command-hook 'org-isearch-post-command
22339 'append 'local)))))
22341 (defun org-isearch-post-command ()
22342 "Remove self from hook, and show context."
22343 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22344 (org-show-context 'isearch))
22347 ;;;; Integration with and fixes for other packages
22349 ;;; Imenu support
22351 (defvar org-imenu-markers nil
22352 "All markers currently used by Imenu.")
22353 (make-variable-buffer-local 'org-imenu-markers)
22355 (defun org-imenu-new-marker (&optional pos)
22356 "Return a new marker for use by Imenu, and remember the marker."
22357 (let ((m (make-marker)))
22358 (move-marker m (or pos (point)))
22359 (push m org-imenu-markers)
22362 (defun org-imenu-get-tree ()
22363 "Produce the index for Imenu."
22364 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22365 (setq org-imenu-markers nil)
22366 (let* ((n org-imenu-depth)
22367 (re (concat "^" (org-get-limited-outline-regexp)))
22368 (subs (make-vector (1+ n) nil))
22369 (last-level 0)
22370 m level head)
22371 (save-excursion
22372 (save-restriction
22373 (widen)
22374 (goto-char (point-max))
22375 (while (re-search-backward re nil t)
22376 (setq level (org-reduced-level (funcall outline-level)))
22377 (when (and (<= level n)
22378 (looking-at org-complex-heading-regexp))
22379 (setq head (org-link-display-format
22380 (org-match-string-no-properties 4))
22381 m (org-imenu-new-marker))
22382 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22383 (if (>= level last-level)
22384 (push (cons head m) (aref subs level))
22385 (push (cons head (aref subs (1+ level))) (aref subs level))
22386 (loop for i from (1+ level) to n do (aset subs i nil)))
22387 (setq last-level level)))))
22388 (aref subs 1)))
22390 (eval-after-load "imenu"
22391 '(progn
22392 (add-hook 'imenu-after-jump-hook
22393 (lambda ()
22394 (if (derived-mode-p 'org-mode)
22395 (org-show-context 'org-goto))))))
22397 (defun org-link-display-format (link)
22398 "Replace a link with either the description, or the link target
22399 if no description is present"
22400 (save-match-data
22401 (if (string-match org-bracket-link-analytic-regexp link)
22402 (replace-match (if (match-end 5)
22403 (match-string 5 link)
22404 (concat (match-string 1 link)
22405 (match-string 3 link)))
22406 nil t link)
22407 link)))
22409 (defun org-toggle-link-display ()
22410 "Toggle the literal or descriptive display of links."
22411 (interactive)
22412 (if org-descriptive-links
22413 (progn (org-remove-from-invisibility-spec '(org-link))
22414 (org-restart-font-lock)
22415 (setq org-descriptive-links nil))
22416 (progn (add-to-invisibility-spec '(org-link))
22417 (org-restart-font-lock)
22418 (setq org-descriptive-links t))))
22420 ;; Speedbar support
22422 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22423 "Overlay marking the agenda restriction line in speedbar.")
22424 (overlay-put org-speedbar-restriction-lock-overlay
22425 'face 'org-agenda-restriction-lock)
22426 (overlay-put org-speedbar-restriction-lock-overlay
22427 'help-echo "Agendas are currently limited to this item.")
22428 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22430 (defun org-speedbar-set-agenda-restriction ()
22431 "Restrict future agenda commands to the location at point in speedbar.
22432 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22433 (interactive)
22434 (require 'org-agenda)
22435 (let (p m tp np dir txt)
22436 (cond
22437 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22438 'org-imenu t))
22439 (setq m (get-text-property p 'org-imenu-marker))
22440 (with-current-buffer (marker-buffer m)
22441 (goto-char m)
22442 (org-agenda-set-restriction-lock 'subtree)))
22443 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22444 'speedbar-function 'speedbar-find-file))
22445 (setq tp (previous-single-property-change
22446 (1+ p) 'speedbar-function)
22447 np (next-single-property-change
22448 tp 'speedbar-function)
22449 dir (speedbar-line-directory)
22450 txt (buffer-substring-no-properties (or tp (point-min))
22451 (or np (point-max))))
22452 (with-current-buffer (find-file-noselect
22453 (let ((default-directory dir))
22454 (expand-file-name txt)))
22455 (unless (derived-mode-p 'org-mode)
22456 (error "Cannot restrict to non-Org-mode file"))
22457 (org-agenda-set-restriction-lock 'file)))
22458 (t (error "Don't know how to restrict Org-mode's agenda")))
22459 (move-overlay org-speedbar-restriction-lock-overlay
22460 (point-at-bol) (point-at-eol))
22461 (setq current-prefix-arg nil)
22462 (org-agenda-maybe-redo)))
22464 (eval-after-load "speedbar"
22465 '(progn
22466 (speedbar-add-supported-extension ".org")
22467 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
22468 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
22469 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
22470 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
22471 (add-hook 'speedbar-visiting-tag-hook
22472 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
22474 ;;; Fixes and Hacks for problems with other packages
22476 ;; Make flyspell not check words in links, to not mess up our keymap
22477 (defun org-mode-flyspell-verify ()
22478 "Don't let flyspell put overlays at active buttons, or on
22479 {todo,all-time,additional-option-like}-keywords."
22480 (let ((pos (max (1- (point)) (point-min)))
22481 (word (thing-at-point 'word)))
22482 (and (not (get-text-property pos 'keymap))
22483 (not (get-text-property pos 'org-no-flyspell))
22484 (not (member word org-todo-keywords-1))
22485 (not (member word org-all-time-keywords))
22486 (not (member word org-options-keywords))
22487 (not (member word (mapcar 'car org-startup-options)))
22488 (not (member word org-additional-option-like-keywords-for-flyspell)))))
22490 (defun org-remove-flyspell-overlays-in (beg end)
22491 "Remove flyspell overlays in region."
22492 (and (org-bound-and-true-p flyspell-mode)
22493 (fboundp 'flyspell-delete-region-overlays)
22494 (flyspell-delete-region-overlays beg end))
22495 (add-text-properties beg end '(org-no-flyspell t)))
22497 ;; Make `bookmark-jump' shows the jump location if it was hidden.
22498 (eval-after-load "bookmark"
22499 '(if (boundp 'bookmark-after-jump-hook)
22500 ;; We can use the hook
22501 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
22502 ;; Hook not available, use advice
22503 (defadvice bookmark-jump (after org-make-visible activate)
22504 "Make the position visible."
22505 (org-bookmark-jump-unhide))))
22507 ;; Make sure saveplace shows the location if it was hidden
22508 (eval-after-load "saveplace"
22509 '(defadvice save-place-find-file-hook (after org-make-visible activate)
22510 "Make the position visible."
22511 (org-bookmark-jump-unhide)))
22513 ;; Make sure ecb shows the location if it was hidden
22514 (eval-after-load "ecb"
22515 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
22516 "Make hierarchy visible when jumping into location from ECB tree buffer."
22517 (if (derived-mode-p 'org-mode)
22518 (org-show-context))))
22520 (defun org-bookmark-jump-unhide ()
22521 "Unhide the current position, to show the bookmark location."
22522 (and (derived-mode-p 'org-mode)
22523 (or (outline-invisible-p)
22524 (save-excursion (goto-char (max (point-min) (1- (point))))
22525 (outline-invisible-p)))
22526 (org-show-context 'bookmark-jump)))
22528 ;; Make session.el ignore our circular variable
22529 (eval-after-load "session"
22530 '(add-to-list 'session-globals-exclude 'org-mark-ring))
22532 ;;;; Experimental code
22534 (defun org-closed-in-range ()
22535 "Sparse tree of items closed in a certain time range.
22536 Still experimental, may disappear in the future."
22537 (interactive)
22538 ;; Get the time interval from the user.
22539 (let* ((time1 (org-float-time
22540 (org-read-date nil 'to-time nil "Starting date: ")))
22541 (time2 (org-float-time
22542 (org-read-date nil 'to-time nil "End date:")))
22543 ;; callback function
22544 (callback (lambda ()
22545 (let ((time
22546 (org-float-time
22547 (apply 'encode-time
22548 (org-parse-time-string
22549 (match-string 1))))))
22550 ;; check if time in interval
22551 (and (>= time time1) (<= time time2))))))
22552 ;; make tree, check each match with the callback
22553 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
22555 ;;;; Finish up
22557 (provide 'org)
22559 (run-hooks 'org-load-hook)
22561 ;;; org.el ends here