Release 7.01e
[org-mode/org-tableheadings.git] / lisp / org.el
blob93135ce6b902051d50c60b414036ca048b4dc3c6
1 ;;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010
4 ;; Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; Homepage: http://orgmode.org
9 ;; Version: 7.01e
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 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
79 (when (fboundp 'defvaralias)
80 (unless (boundp 'calendar-view-holidays-initially-flag)
81 (defvaralias 'calendar-view-holidays-initially-flag
82 'view-calendar-holidays-initially))
83 (unless (boundp 'calendar-view-diary-initially-flag)
84 (defvaralias 'calendar-view-diary-initially-flag
85 'view-diary-entries-initially))
86 (unless (boundp 'diary-fancy-buffer)
87 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
89 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
90 ;; the file noutline.el being loaded.
91 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
92 ;; We require noutline, which might be provided in outline.el
93 (require 'outline) (require 'noutline)
94 ;; Other stuff we need.
95 (require 'time-date)
96 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
97 (require 'easymenu)
98 (require 'overlay)
100 (require 'org-macs)
101 (require 'org-entities)
102 (require 'org-compat)
103 (require 'org-faces)
104 (require 'org-list)
105 (require 'org-src)
106 (require 'org-footnote)
108 ;; babel
109 (require 'ob)
110 (require 'ob-table)
111 (require 'ob-lob)
112 (require 'ob-ref)
113 (require 'ob-tangle)
114 (require 'ob-comint)
115 (require 'ob-keys)
117 ;; load languages based on value of `org-babel-load-languages'
118 (defvar org-babel-load-languages)
119 ;;;###autoload
120 (defun org-babel-do-load-languages (sym value)
121 "Load the languages defined in `org-babel-load-languages'."
122 (set-default sym value)
123 (mapc (lambda (pair)
124 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
125 (if active
126 (progn
127 (require (intern (concat "ob-" lang))))
128 (progn
129 (funcall 'fmakunbound
130 (intern (concat "org-babel-execute:" lang)))
131 (funcall 'fmakunbound
132 (intern (concat "org-babel-expand-body:" lang)))))))
133 org-babel-load-languages))
135 (defcustom org-babel-load-languages '((emacs-lisp . t))
136 "Languages which can be evaluated in Org-mode buffers.
137 This list can be used to load support for any of the languages
138 below, note that each language will depend on a different set of
139 system executables and/or Emacs modes. When a language is
140 \"loaded\", then code blocks in that language can be evaluated
141 with `org-babel-execute-src-block' bound by default to C-c
142 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
143 be set to remove code block evaluation from the C-c C-c
144 keybinding. By default only Emacs Lisp (which has no
145 requirements) is loaded."
146 :group 'org-babel
147 :set 'org-babel-do-load-languages
148 :type '(alist :tag "Babel Languages"
149 :key-type
150 (choice
151 (const :tag "C" C)
152 (const :tag "R" R)
153 (const :tag "Asymptote" asymptote)
154 (const :tag "Clojure" clojure)
155 (const :tag "CSS" css)
156 (const :tag "Ditaa" ditaa)
157 (const :tag "Dot" dot)
158 (const :tag "Emacs Lisp" emacs-lisp)
159 (const :tag "Gnuplot" gnuplot)
160 (const :tag "Haskell" haskell)
161 (const :tag "Latex" latex)
162 (const :tag "Matlab" matlab)
163 (const :tag "Mscgen" mscgen)
164 (const :tag "Ocaml" ocaml)
165 (const :tag "Octave" octave)
166 (const :tag "Perl" perl)
167 (const :tag "Python" python)
168 (const :tag "Ruby" ruby)
169 (const :tag "Sass" sass)
170 (const :tag "Screen" screen)
171 (const :tag "Shell Script" sh)
172 (const :tag "Sql" sql)
173 (const :tag "Sqlite" sqlite))
174 :value-type (boolean :tag "Activate" :value t)))
176 ;;;; Customization variables
177 (defcustom org-clone-delete-id nil
178 "Remove ID property of clones of a subtree.
179 When non-nil, clones of a subtree don't inherit the ID property.
180 Otherwise they inherit the ID property with a new unique
181 identifier."
182 :type 'boolean
183 :group 'org-id)
185 ;;; Version
187 (defconst org-version "7.01e"
188 "The version number of the file org.el.")
190 (defun org-version (&optional here)
191 "Show the org-mode version in the echo area.
192 With prefix arg HERE, insert it at point."
193 (interactive "P")
194 (let* ((origin default-directory)
195 (version org-version)
196 (git-version)
197 (dir (concat (file-name-directory (locate-library "org")) "../" )))
198 (when (and (file-exists-p (expand-file-name ".git" dir))
199 (executable-find "git"))
200 (unwind-protect
201 (progn
202 (cd dir)
203 (when (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
204 (with-current-buffer "*Shell Command Output*"
205 (goto-char (point-min))
206 (setq git-version (buffer-substring (point) (point-at-eol))))
207 (subst-char-in-string ?- ?. git-version t)
208 (when (string-match "\\S-"
209 (shell-command-to-string
210 "git diff-index --name-only HEAD --"))
211 (setq git-version (concat git-version ".dirty")))
212 (setq version (concat version " (" git-version ")"))))
213 (cd origin)))
214 (setq version (format "Org-mode version %s" version))
215 (if here (insert version))
216 (message version)))
218 ;;; Compatibility constants
220 ;;; The custom variables
222 (defgroup org nil
223 "Outline-based notes management and organizer."
224 :tag "Org"
225 :group 'outlines
226 :group 'calendar)
228 (defcustom org-mode-hook nil
229 "Mode hook for Org-mode, run after the mode was turned on."
230 :group 'org
231 :type 'hook)
233 (defcustom org-load-hook nil
234 "Hook that is run after org.el has been loaded."
235 :group 'org
236 :type 'hook)
238 (defvar org-modules) ; defined below
239 (defvar org-modules-loaded nil
240 "Have the modules been loaded already?")
242 (defun org-load-modules-maybe (&optional force)
243 "Load all extensions listed in `org-modules'."
244 (when (or force (not org-modules-loaded))
245 (mapc (lambda (ext)
246 (condition-case nil (require ext)
247 (error (message "Problems while trying to load feature `%s'" ext))))
248 org-modules)
249 (setq org-modules-loaded t)))
251 (defun org-set-modules (var value)
252 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
253 (set var value)
254 (when (featurep 'org)
255 (org-load-modules-maybe 'force)))
257 (when (org-bound-and-true-p org-modules)
258 (let ((a (member 'org-infojs org-modules)))
259 (and a (setcar a 'org-jsinfo))))
261 (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)
262 "Modules that should always be loaded together with org.el.
263 If a description starts with <C>, the file is not part of Emacs
264 and loading it will require that you have downloaded and properly installed
265 the org-mode distribution.
267 You can also use this system to load external packages (i.e. neither Org
268 core modules, nor modules from the CONTRIB directory). Just add symbols
269 to the end of the list. If the package is called org-xyz.el, then you need
270 to add the symbol `xyz', and the package must have a call to
272 (provide 'org-xyz)"
273 :group 'org
274 :set 'org-set-modules
275 :type
276 '(set :greedy t
277 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
278 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
279 (const :tag " crypt: Encryption of subtrees" org-crypt)
280 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
281 (const :tag " docview: Links to doc-view buffers" org-docview)
282 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
283 (const :tag " id: Global IDs for identifying entries" org-id)
284 (const :tag " info: Links to Info nodes" org-info)
285 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
286 (const :tag " habit: Track your consistency with habits" org-habit)
287 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
288 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
289 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
290 (const :tag " mew Links to Mew folders/messages" org-mew)
291 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
292 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
293 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
294 (const :tag " vm: Links to VM folders/messages" org-vm)
295 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
296 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
297 (const :tag " mouse: Additional mouse support" org-mouse)
299 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
300 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
301 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
302 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
303 (const :tag "C collector: Collect properties into tables" org-collector)
304 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
305 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
306 (const :tag "C eval: Include command output as text" org-eval)
307 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
308 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
309 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
310 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
311 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
313 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
315 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
316 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
317 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
318 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
319 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
320 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
321 (const :tag "C mtags: Support for muse-like tags" org-mtags)
322 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
323 (const :tag "C registry: A registry for Org-mode links" org-registry)
324 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
325 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
326 (const :tag "C secretary: Team management with org-mode" org-secretary)
327 (const :tag "C special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
328 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
329 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
330 (const :tag "C track: Keep up with Org-mode development" org-track)
331 (const :tag "C TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
332 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
334 (defcustom org-support-shift-select nil
335 "Non-nil means make shift-cursor commands select text when possible.
337 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
338 selecting a region, or enlarge regions started in this way.
339 In Org-mode, in special contexts, these same keys are used for other
340 purposes, important enough to compete with shift selection. Org tries
341 to balance these needs by supporting `shift-select-mode' outside these
342 special contexts, under control of this variable.
344 The default of this variable is nil, to avoid confusing behavior. Shifted
345 cursor keys will then execute Org commands in the following contexts:
346 - on a headline, changing TODO state (left/right) and priority (up/down)
347 - on a time stamp, changing the time
348 - in a plain list item, changing the bullet type
349 - in a property definition line, switching between allowed values
350 - in the BEGIN line of a clock table (changing the time block).
351 Outside these contexts, the commands will throw an error.
353 When this variable is t and the cursor is not in a special context,
354 Org-mode will support shift-selection for making and enlarging regions.
355 To make this more effective, the bullet cycling will no longer happen
356 anywhere in an item line, but only if the cursor is exactly on the bullet.
358 If you set this variable to the symbol `always', then the keys
359 will not be special in headlines, property lines, and item lines, to make
360 shift selection work there as well. If this is what you want, you can
361 use the following alternative commands: `C-c C-t' and `C-c ,' to
362 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
363 TODO sets, `C-c -' to cycle item bullet types, and properties can be
364 edited by hand or in column view.
366 However, when the cursor is on a timestamp, shift-cursor commands
367 will still edit the time stamp - this is just too good to give up.
369 XEmacs user should have this variable set to nil, because shift-select-mode
370 is Emacs 23 only."
371 :group 'org
372 :type '(choice
373 (const :tag "Never" nil)
374 (const :tag "When outside special context" t)
375 (const :tag "Everywhere except timestamps" always)))
377 (defgroup org-startup nil
378 "Options concerning startup of Org-mode."
379 :tag "Org Startup"
380 :group 'org)
382 (defcustom org-startup-folded t
383 "Non-nil means entering Org-mode will switch to OVERVIEW.
384 This can also be configured on a per-file basis by adding one of
385 the following lines anywhere in the buffer:
387 #+STARTUP: fold (or `overview', this is equivalent)
388 #+STARTUP: nofold (or `showall', this is equivalent)
389 #+STARTUP: content
390 #+STARTUP: showeverything"
391 :group 'org-startup
392 :type '(choice
393 (const :tag "nofold: show all" nil)
394 (const :tag "fold: overview" t)
395 (const :tag "content: all headlines" content)
396 (const :tag "show everything, even drawers" showeverything)))
398 (defcustom org-startup-truncated t
399 "Non-nil means entering Org-mode will set `truncate-lines'.
400 This is useful since some lines containing links can be very long and
401 uninteresting. Also tables look terrible when wrapped."
402 :group 'org-startup
403 :type 'boolean)
405 (defcustom org-startup-indented nil
406 "Non-nil means turn on `org-indent-mode' on startup.
407 This can also be configured on a per-file basis by adding one of
408 the following lines anywhere in the buffer:
410 #+STARTUP: indent
411 #+STARTUP: noindent"
412 :group 'org-structure
413 :type '(choice
414 (const :tag "Not" nil)
415 (const :tag "Globally (slow on startup in large files)" t)))
417 (defcustom org-use-sub-superscripts t
418 "Non-nil means interpret \"_\" and \"^\" for export.
419 When this option is turned on, you can use TeX-like syntax for sub- and
420 superscripts. Several characters after \"_\" or \"^\" will be
421 considered as a single item - so grouping with {} is normally not
422 needed. For example, the following things will be parsed as single
423 sub- or superscripts.
425 10^24 or 10^tau several digits will be considered 1 item.
426 10^-12 or 10^-tau a leading sign with digits or a word
427 x^2-y^3 will be read as x^2 - y^3, because items are
428 terminated by almost any nonword/nondigit char.
429 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
431 Still, ambiguity is possible - so when in doubt use {} to enclose the
432 sub/superscript. If you set this variable to the symbol `{}',
433 the braces are *required* in order to trigger interpretations as
434 sub/superscript. This can be helpful in documents that need \"_\"
435 frequently in plain text.
437 Not all export backends support this, but HTML does.
439 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
440 :group 'org-startup
441 :group 'org-export-translation
442 :type '(choice
443 (const :tag "Always interpret" t)
444 (const :tag "Only with braces" {})
445 (const :tag "Never interpret" nil)))
447 (if (fboundp 'defvaralias)
448 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
451 (defcustom org-startup-with-beamer-mode nil
452 "Non-nil means turn on `org-beamer-mode' on startup.
453 This can also be configured on a per-file basis by adding one of
454 the following lines anywhere in the buffer:
456 #+STARTUP: beamer"
457 :group 'org-startup
458 :type 'boolean)
460 (defcustom org-startup-align-all-tables nil
461 "Non-nil means align all tables when visiting a file.
462 This is useful when the column width in tables is forced with <N> cookies
463 in table fields. Such tables will look correct only after the first re-align.
464 This can also be configured on a per-file basis by adding one of
465 the following lines anywhere in the buffer:
466 #+STARTUP: align
467 #+STARTUP: noalign"
468 :group 'org-startup
469 :type 'boolean)
471 (defcustom org-insert-mode-line-in-empty-file nil
472 "Non-nil means insert the first line setting Org-mode in empty files.
473 When the function `org-mode' is called interactively in an empty file, this
474 normally means that the file name does not automatically trigger Org-mode.
475 To ensure that the file will always be in Org-mode in the future, a
476 line enforcing Org-mode will be inserted into the buffer, if this option
477 has been set."
478 :group 'org-startup
479 :type 'boolean)
481 (defcustom org-replace-disputed-keys nil
482 "Non-nil means use alternative key bindings for some keys.
483 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
484 These keys are also used by other packages like shift-selection-mode'
485 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
486 If you want to use Org-mode together with one of these other modes,
487 or more generally if you would like to move some Org-mode commands to
488 other keys, set this variable and configure the keys with the variable
489 `org-disputed-keys'.
491 This option is only relevant at load-time of Org-mode, and must be set
492 *before* org.el is loaded. Changing it requires a restart of Emacs to
493 become effective."
494 :group 'org-startup
495 :type 'boolean)
497 (defcustom org-use-extra-keys nil
498 "Non-nil means use extra key sequence definitions for certain commands.
499 This happens automatically if you run XEmacs or if `window-system'
500 is nil. This variable lets you do the same manually. You must
501 set it before loading org.
503 Example: on Carbon Emacs 22 running graphically, with an external
504 keyboard on a Powerbook, the default way of setting M-left might
505 not work for either Alt or ESC. Setting this variable will make
506 it work for ESC."
507 :group 'org-startup
508 :type 'boolean)
510 (if (fboundp 'defvaralias)
511 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
513 (defcustom org-disputed-keys
514 '(([(shift up)] . [(meta p)])
515 ([(shift down)] . [(meta n)])
516 ([(shift left)] . [(meta -)])
517 ([(shift right)] . [(meta +)])
518 ([(control shift right)] . [(meta shift +)])
519 ([(control shift left)] . [(meta shift -)]))
520 "Keys for which Org-mode and other modes compete.
521 This is an alist, cars are the default keys, second element specifies
522 the alternative to use when `org-replace-disputed-keys' is t.
524 Keys can be specified in any syntax supported by `define-key'.
525 The value of this option takes effect only at Org-mode's startup,
526 therefore you'll have to restart Emacs to apply it after changing."
527 :group 'org-startup
528 :type 'alist)
530 (defun org-key (key)
531 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
532 Or return the original if not disputed.
533 Also apply the translations defined in `org-xemacs-key-equivalents'."
534 (when org-replace-disputed-keys
535 (let* ((nkey (key-description key))
536 (x (org-find-if (lambda (x)
537 (equal (key-description (car x)) nkey))
538 org-disputed-keys)))
539 (setq key (if x (cdr x) key))))
540 (when (featurep 'xemacs)
541 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
542 key)
544 (defun org-find-if (predicate seq)
545 (catch 'exit
546 (while seq
547 (if (funcall predicate (car seq))
548 (throw 'exit (car seq))
549 (pop seq)))))
551 (defun org-defkey (keymap key def)
552 "Define a key, possibly translated, as returned by `org-key'."
553 (define-key keymap (org-key key) def))
555 (defcustom org-ellipsis nil
556 "The ellipsis to use in the Org-mode outline.
557 When nil, just use the standard three dots. When a string, use that instead,
558 When a face, use the standard 3 dots, but with the specified face.
559 The change affects only Org-mode (which will then use its own display table).
560 Changing this requires executing `M-x org-mode' in a buffer to become
561 effective."
562 :group 'org-startup
563 :type '(choice (const :tag "Default" nil)
564 (face :tag "Face" :value org-warning)
565 (string :tag "String" :value "...#")))
567 (defvar org-display-table nil
568 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
570 (defgroup org-keywords nil
571 "Keywords in Org-mode."
572 :tag "Org Keywords"
573 :group 'org)
575 (defcustom org-deadline-string "DEADLINE:"
576 "String to mark deadline entries.
577 A deadline is this string, followed by a time stamp. Should be a word,
578 terminated by a colon. You can insert a schedule keyword and
579 a timestamp with \\[org-deadline].
580 Changes become only effective after restarting Emacs."
581 :group 'org-keywords
582 :type 'string)
584 (defcustom org-scheduled-string "SCHEDULED:"
585 "String to mark scheduled TODO entries.
586 A schedule is this string, followed by a time stamp. Should be a word,
587 terminated by a colon. You can insert a schedule keyword and
588 a timestamp with \\[org-schedule].
589 Changes become only effective after restarting Emacs."
590 :group 'org-keywords
591 :type 'string)
593 (defcustom org-closed-string "CLOSED:"
594 "String used as the prefix for timestamps logging closing a TODO entry."
595 :group 'org-keywords
596 :type 'string)
598 (defcustom org-clock-string "CLOCK:"
599 "String used as prefix for timestamps clocking work hours on an item."
600 :group 'org-keywords
601 :type 'string)
603 (defcustom org-comment-string "COMMENT"
604 "Entries starting with this keyword will never be exported.
605 An entry can be toggled between COMMENT and normal with
606 \\[org-toggle-comment].
607 Changes become only effective after restarting Emacs."
608 :group 'org-keywords
609 :type 'string)
611 (defcustom org-quote-string "QUOTE"
612 "Entries starting with this keyword will be exported in fixed-width font.
613 Quoting applies only to the text in the entry following the headline, and does
614 not extend beyond the next headline, even if that is lower level.
615 An entry can be toggled between QUOTE and normal with
616 \\[org-toggle-fixed-width-section]."
617 :group 'org-keywords
618 :type 'string)
620 (defconst org-repeat-re
621 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
622 "Regular expression for specifying repeated events.
623 After a match, group 1 contains the repeat expression.")
625 (defgroup org-structure nil
626 "Options concerning the general structure of Org-mode files."
627 :tag "Org Structure"
628 :group 'org)
630 (defgroup org-reveal-location nil
631 "Options about how to make context of a location visible."
632 :tag "Org Reveal Location"
633 :group 'org-structure)
635 (defconst org-context-choice
636 '(choice
637 (const :tag "Always" t)
638 (const :tag "Never" nil)
639 (repeat :greedy t :tag "Individual contexts"
640 (cons
641 (choice :tag "Context"
642 (const agenda)
643 (const org-goto)
644 (const occur-tree)
645 (const tags-tree)
646 (const link-search)
647 (const mark-goto)
648 (const bookmark-jump)
649 (const isearch)
650 (const default))
651 (boolean))))
652 "Contexts for the reveal options.")
654 (defcustom org-show-hierarchy-above '((default . t))
655 "Non-nil means show full hierarchy when revealing a location.
656 Org-mode often shows locations in an org-mode file which might have
657 been invisible before. When this is set, the hierarchy of headings
658 above the exposed location is shown.
659 Turning this off for example for sparse trees makes them very compact.
660 Instead of t, this can also be an alist specifying this option for different
661 contexts. Valid contexts are
662 agenda when exposing an entry from the agenda
663 org-goto when using the command `org-goto' on key C-c C-j
664 occur-tree when using the command `org-occur' on key C-c /
665 tags-tree when constructing a sparse tree based on tags matches
666 link-search when exposing search matches associated with a link
667 mark-goto when exposing the jump goal of a mark
668 bookmark-jump when exposing a bookmark location
669 isearch when exiting from an incremental search
670 default default for all contexts not set explicitly"
671 :group 'org-reveal-location
672 :type org-context-choice)
674 (defcustom org-show-following-heading '((default . nil))
675 "Non-nil means show following heading when revealing a location.
676 Org-mode often shows locations in an org-mode file which might have
677 been invisible before. When this is set, the heading following the
678 match is shown.
679 Turning this off for example for sparse trees makes them very compact,
680 but makes it harder to edit the location of the match. In such a case,
681 use the command \\[org-reveal] to show more context.
682 Instead of t, this can also be an alist specifying this option for different
683 contexts. See `org-show-hierarchy-above' for valid contexts."
684 :group 'org-reveal-location
685 :type org-context-choice)
687 (defcustom org-show-siblings '((default . nil) (isearch t))
688 "Non-nil means show all sibling heading when revealing a location.
689 Org-mode often shows locations in an org-mode file which might have
690 been invisible before. When this is set, the sibling of the current entry
691 heading are all made visible. If `org-show-hierarchy-above' is t,
692 the same happens on each level of the hierarchy above the current entry.
694 By default this is on for the isearch context, off for all other contexts.
695 Turning this off for example for sparse trees makes them very compact,
696 but makes it harder to edit the location of the match. In such a case,
697 use the command \\[org-reveal] to show more context.
698 Instead of t, this can also be an alist specifying this option for different
699 contexts. See `org-show-hierarchy-above' for valid contexts."
700 :group 'org-reveal-location
701 :type org-context-choice)
703 (defcustom org-show-entry-below '((default . nil))
704 "Non-nil means show the entry below a headline when revealing a location.
705 Org-mode often shows locations in an org-mode file which might have
706 been invisible before. When this is set, the text below the headline that is
707 exposed is also shown.
709 By default this is off for all contexts.
710 Instead of t, this can also be an alist specifying this option for different
711 contexts. See `org-show-hierarchy-above' for valid contexts."
712 :group 'org-reveal-location
713 :type org-context-choice)
715 (defcustom org-indirect-buffer-display 'other-window
716 "How should indirect tree buffers be displayed?
717 This applies to indirect buffers created with the commands
718 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
719 Valid values are:
720 current-window Display in the current window
721 other-window Just display in another window.
722 dedicated-frame Create one new frame, and re-use it each time.
723 new-frame Make a new frame each time. Note that in this case
724 previously-made indirect buffers are kept, and you need to
725 kill these buffers yourself."
726 :group 'org-structure
727 :group 'org-agenda-windows
728 :type '(choice
729 (const :tag "In current window" current-window)
730 (const :tag "In current frame, other window" other-window)
731 (const :tag "Each time a new frame" new-frame)
732 (const :tag "One dedicated frame" dedicated-frame)))
734 (defcustom org-use-speed-commands nil
735 "Non-nil means activate single letter commands at beginning of a headline.
736 This may also be a function to test for appropriate locations where speed
737 commands should be active."
738 :group 'org-structure
739 :type '(choice
740 (const :tag "Never" nil)
741 (const :tag "At beginning of headline stars" t)
742 (function)))
744 (defcustom org-speed-commands-user nil
745 "Alist of additional speed commands.
746 This list will be checked before `org-speed-commands-default'
747 when the variable `org-use-speed-commands' is non-nil
748 and when the cursor is at the beginning of a headline.
749 The car if each entry is a string with a single letter, which must
750 be assigned to `self-insert-command' in the global map.
751 The cdr is either a command to be called interactively, a function
752 to be called, or a form to be evaluated.
753 An entry that is just a list with a single string will be interpreted
754 as a descriptive headline that will be added when listing the speed
755 commands in the Help buffer using the `?' speed command."
756 :group 'org-structure
757 :type '(repeat :value ("k" . ignore)
758 (choice :value ("k" . ignore)
759 (list :tag "Descriptive Headline" (string :tag "Headline"))
760 (cons :tag "Letter and Command"
761 (string :tag "Command letter")
762 (choice
763 (function)
764 (sexp))))))
766 (defgroup org-cycle nil
767 "Options concerning visibility cycling in Org-mode."
768 :tag "Org Cycle"
769 :group 'org-structure)
771 (defcustom org-cycle-skip-children-state-if-no-children t
772 "Non-nil means skip CHILDREN state in entries that don't have any."
773 :group 'org-cycle
774 :type 'boolean)
776 (defcustom org-cycle-max-level nil
777 "Maximum level which should still be subject to visibility cycling.
778 Levels higher than this will, for cycling, be treated as text, not a headline.
779 When `org-odd-levels-only' is set, a value of N in this variable actually
780 means 2N-1 stars as the limiting headline.
781 When nil, cycle all levels.
782 Note that the limiting level of cycling is also influenced by
783 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
784 `org-inlinetask-min-level' is, cycling will be limited to levels one less
785 than its value."
786 :group 'org-cycle
787 :type '(choice
788 (const :tag "No limit" nil)
789 (integer :tag "Maximum level")))
791 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
792 "Names of drawers. Drawers are not opened by cycling on the headline above.
793 Drawers only open with a TAB on the drawer line itself. A drawer looks like
794 this:
795 :DRAWERNAME:
796 .....
797 :END:
798 The drawer \"PROPERTIES\" is special for capturing properties through
799 the property API.
801 Drawers can be defined on the per-file basis with a line like:
803 #+DRAWERS: HIDDEN STATE PROPERTIES"
804 :group 'org-structure
805 :group 'org-cycle
806 :type '(repeat (string :tag "Drawer Name")))
808 (defcustom org-hide-block-startup nil
809 "Non-nil means entering Org-mode will fold all blocks.
810 This can also be set in on a per-file basis with
812 #+STARTUP: hideblocks
813 #+STARTUP: showblocks"
814 :group 'org-startup
815 :group 'org-cycle
816 :type 'boolean)
818 (defcustom org-cycle-global-at-bob nil
819 "Cycle globally if cursor is at beginning of buffer and not at a headline.
820 This makes it possible to do global cycling without having to use S-TAB or
821 \\[universal-argument] TAB. For this special case to work, the first line \
822 of the buffer
823 must not be a headline - it may be empty or some other text. When used in
824 this way, `org-cycle-hook' is disables temporarily, to make sure the
825 cursor stays at the beginning of the buffer.
826 When this option is nil, don't do anything special at the beginning
827 of the buffer."
828 :group 'org-cycle
829 :type 'boolean)
831 (defcustom org-cycle-level-after-item/entry-creation t
832 "Non-nil means cycle entry level or item indentation in new empty entries.
834 When the cursor is at the end of an empty headline, i.e with only stars
835 and maybe a TODO keyword, TAB will then switch the entry to become a child,
836 and then all possible ancestor states, before returning to the original state.
837 This makes data entry extremely fast: M-RET to create a new headline,
838 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
840 When the cursor is at the end of an empty plain list item, one TAB will
841 make it a subitem, two or more tabs will back up to make this an item
842 higher up in the item hierarchy."
843 :group 'org-cycle
844 :type 'boolean)
846 (defcustom org-cycle-emulate-tab t
847 "Where should `org-cycle' emulate TAB.
848 nil Never
849 white Only in completely white lines
850 whitestart Only at the beginning of lines, before the first non-white char
851 t Everywhere except in headlines
852 exc-hl-bol Everywhere except at the start of a headline
853 If TAB is used in a place where it does not emulate TAB, the current subtree
854 visibility is cycled."
855 :group 'org-cycle
856 :type '(choice (const :tag "Never" nil)
857 (const :tag "Only in completely white lines" white)
858 (const :tag "Before first char in a line" whitestart)
859 (const :tag "Everywhere except in headlines" t)
860 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
863 (defcustom org-cycle-separator-lines 2
864 "Number of empty lines needed to keep an empty line between collapsed trees.
865 If you leave an empty line between the end of a subtree and the following
866 headline, this empty line is hidden when the subtree is folded.
867 Org-mode will leave (exactly) one empty line visible if the number of
868 empty lines is equal or larger to the number given in this variable.
869 So the default 2 means at least 2 empty lines after the end of a subtree
870 are needed to produce free space between a collapsed subtree and the
871 following headline.
873 If the number is negative, and the number of empty lines is at least -N,
874 all empty lines are shown.
876 Special case: when 0, never leave empty lines in collapsed view."
877 :group 'org-cycle
878 :type 'integer)
879 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
881 (defcustom org-pre-cycle-hook nil
882 "Hook that is run before visibility cycling is happening.
883 The function(s) in this hook must accept a single argument which indicates
884 the new state that will be set right after running this hook. The
885 argument is a symbol. Before a global state change, it can have the values
886 `overview', `content', or `all'. Before a local state change, it can have
887 the values `folded', `children', or `subtree'."
888 :group 'org-cycle
889 :type 'hook)
891 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
892 org-cycle-hide-drawers
893 org-cycle-show-empty-lines
894 org-optimize-window-after-visibility-change)
895 "Hook that is run after `org-cycle' has changed the buffer visibility.
896 The function(s) in this hook must accept a single argument which indicates
897 the new state that was set by the most recent `org-cycle' command. The
898 argument is a symbol. After a global state change, it can have the values
899 `overview', `content', or `all'. After a local state change, it can have
900 the values `folded', `children', or `subtree'."
901 :group 'org-cycle
902 :type 'hook)
904 (defgroup org-edit-structure nil
905 "Options concerning structure editing in Org-mode."
906 :tag "Org Edit Structure"
907 :group 'org-structure)
909 (defcustom org-odd-levels-only nil
910 "Non-nil means skip even levels and only use odd levels for the outline.
911 This has the effect that two stars are being added/taken away in
912 promotion/demotion commands. It also influences how levels are
913 handled by the exporters.
914 Changing it requires restart of `font-lock-mode' to become effective
915 for fontification also in regions already fontified.
916 You may also set this on a per-file basis by adding one of the following
917 lines to the buffer:
919 #+STARTUP: odd
920 #+STARTUP: oddeven"
921 :group 'org-edit-structure
922 :group 'org-appearance
923 :type 'boolean)
925 (defcustom org-adapt-indentation t
926 "Non-nil means adapt indentation to outline node level.
928 When this variable is set, Org assumes that you write outlines by
929 indenting text in each node to align with the headline (after the stars).
930 The following issues are influenced by this variable:
932 - When this is set and the *entire* text in an entry is indented, the
933 indentation is increased by one space in a demotion command, and
934 decreased by one in a promotion command. If any line in the entry
935 body starts with text at column 0, indentation is not changed at all.
937 - Property drawers and planning information is inserted indented when
938 this variable s set. When nil, they will not be indented.
940 - TAB indents a line relative to context. The lines below a headline
941 will be indented when this variable is set.
943 Note that this is all about true indentation, by adding and removing
944 space characters. See also `org-indent.el' which does level-dependent
945 indentation in a virtual way, i.e. at display time in Emacs."
946 :group 'org-edit-structure
947 :type 'boolean)
949 (defcustom org-special-ctrl-a/e nil
950 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
952 When t, `C-a' will bring back the cursor to the beginning of the
953 headline text, i.e. after the stars and after a possible TODO keyword.
954 In an item, this will be the position after the bullet.
955 When the cursor is already at that position, another `C-a' will bring
956 it to the beginning of the line.
958 `C-e' will jump to the end of the headline, ignoring the presence of tags
959 in the headline. A second `C-e' will then jump to the true end of the
960 line, after any tags. This also means that, when this variable is
961 non-nil, `C-e' also will never jump beyond the end of the heading of a
962 folded section, i.e. not after the ellipses.
964 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
965 going to the true line boundary first. Only a directly following, identical
966 keypress will bring the cursor to the special positions.
968 This may also be a cons cell where the behavior for `C-a' and `C-e' is
969 set separately."
970 :group 'org-edit-structure
971 :type '(choice
972 (const :tag "off" nil)
973 (const :tag "on: after stars/bullet and before tags first" t)
974 (const :tag "reversed: true line boundary first" reversed)
975 (cons :tag "Set C-a and C-e separately"
976 (choice :tag "Special C-a"
977 (const :tag "off" nil)
978 (const :tag "on: after stars/bullet first" t)
979 (const :tag "reversed: before stars/bullet first" reversed))
980 (choice :tag "Special C-e"
981 (const :tag "off" nil)
982 (const :tag "on: before tags first" t)
983 (const :tag "reversed: after tags first" reversed)))))
984 (if (fboundp 'defvaralias)
985 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
987 (defcustom org-special-ctrl-k nil
988 "Non-nil means `C-k' will behave specially in headlines.
989 When nil, `C-k' will call the default `kill-line' command.
990 When t, the following will happen while the cursor is in the headline:
992 - When the cursor is at the beginning of a headline, kill the entire
993 line and possible the folded subtree below the line.
994 - When in the middle of the headline text, kill the headline up to the tags.
995 - When after the headline text, kill the tags."
996 :group 'org-edit-structure
997 :type 'boolean)
999 (defcustom org-ctrl-k-protect-subtree nil
1000 "Non-nil means, do not delete a hidden subtree with C-k.
1001 When set to the symbol `error', simply throw an error when C-k is
1002 used to kill (part-of) a headline that has hidden text behind it.
1003 Any other non-nil value will result in a query to the user, if it is
1004 OK to kill that hidden subtree. When nil, kill without remorse."
1005 :group 'org-edit-structure
1006 :type '(choice
1007 (const :tag "Do not protect hidden subtrees" nil)
1008 (const :tag "Protect hidden subtrees with a security query" t)
1009 (const :tag "Never kill a hidden subtree with C-k" error)))
1011 (defcustom org-yank-folded-subtrees t
1012 "Non-nil means when yanking subtrees, fold them.
1013 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1014 it starts with a heading and all other headings in it are either children
1015 or siblings, then fold all the subtrees. However, do this only if no
1016 text after the yank would be swallowed into a folded tree by this action."
1017 :group 'org-edit-structure
1018 :type 'boolean)
1020 (defcustom org-yank-adjusted-subtrees nil
1021 "Non-nil means when yanking subtrees, adjust the level.
1022 With this setting, `org-paste-subtree' is used to insert the subtree, see
1023 this function for details."
1024 :group 'org-edit-structure
1025 :type 'boolean)
1027 (defcustom org-M-RET-may-split-line '((default . t))
1028 "Non-nil means M-RET will split the line at the cursor position.
1029 When nil, it will go to the end of the line before making a
1030 new line.
1031 You may also set this option in a different way for different
1032 contexts. Valid contexts are:
1034 headline when creating a new headline
1035 item when creating a new item
1036 table in a table field
1037 default the value to be used for all contexts not explicitly
1038 customized"
1039 :group 'org-structure
1040 :group 'org-table
1041 :type '(choice
1042 (const :tag "Always" t)
1043 (const :tag "Never" nil)
1044 (repeat :greedy t :tag "Individual contexts"
1045 (cons
1046 (choice :tag "Context"
1047 (const headline)
1048 (const item)
1049 (const table)
1050 (const default))
1051 (boolean)))))
1054 (defcustom org-insert-heading-respect-content nil
1055 "Non-nil means insert new headings after the current subtree.
1056 When nil, the new heading is created directly after the current line.
1057 The commands \\[org-insert-heading-respect-content] and
1058 \\[org-insert-todo-heading-respect-content] turn this variable on
1059 for the duration of the command."
1060 :group 'org-structure
1061 :type 'boolean)
1063 (defcustom org-blank-before-new-entry '((heading . auto)
1064 (plain-list-item . auto))
1065 "Should `org-insert-heading' leave a blank line before new heading/item?
1066 The value is an alist, with `heading' and `plain-list-item' as car,
1067 and a boolean flag as cdr. For plain lists, if the variable
1068 `org-empty-line-terminates-plain-lists' is set, the setting here
1069 is ignored and no empty line is inserted, to keep the list in tact."
1070 :group 'org-edit-structure
1071 :type '(list
1072 (cons (const heading)
1073 (choice (const :tag "Never" nil)
1074 (const :tag "Always" t)
1075 (const :tag "Auto" auto)))
1076 (cons (const plain-list-item)
1077 (choice (const :tag "Never" nil)
1078 (const :tag "Always" t)
1079 (const :tag "Auto" auto)))))
1081 (defcustom org-insert-heading-hook nil
1082 "Hook being run after inserting a new heading."
1083 :group 'org-edit-structure
1084 :type 'hook)
1086 (defcustom org-enable-fixed-width-editor t
1087 "Non-nil means lines starting with \":\" are treated as fixed-width.
1088 This currently only means they are never auto-wrapped.
1089 When nil, such lines will be treated like ordinary lines.
1090 See also the QUOTE keyword."
1091 :group 'org-edit-structure
1092 :type 'boolean)
1094 (defcustom org-goto-auto-isearch t
1095 "Non-nil means typing characters in `org-goto' starts incremental search."
1096 :group 'org-edit-structure
1097 :type 'boolean)
1099 (defgroup org-sparse-trees nil
1100 "Options concerning sparse trees in Org-mode."
1101 :tag "Org Sparse Trees"
1102 :group 'org-structure)
1104 (defcustom org-highlight-sparse-tree-matches t
1105 "Non-nil means highlight all matches that define a sparse tree.
1106 The highlights will automatically disappear the next time the buffer is
1107 changed by an edit command."
1108 :group 'org-sparse-trees
1109 :type 'boolean)
1111 (defcustom org-remove-highlights-with-change t
1112 "Non-nil means any change to the buffer will remove temporary highlights.
1113 Such highlights are created by `org-occur' and `org-clock-display'.
1114 When nil, `C-c C-c needs to be used to get rid of the highlights.
1115 The highlights created by `org-preview-latex-fragment' always need
1116 `C-c C-c' to be removed."
1117 :group 'org-sparse-trees
1118 :group 'org-time
1119 :type 'boolean)
1122 (defcustom org-occur-hook '(org-first-headline-recenter)
1123 "Hook that is run after `org-occur' has constructed a sparse tree.
1124 This can be used to recenter the window to show as much of the structure
1125 as possible."
1126 :group 'org-sparse-trees
1127 :type 'hook)
1129 (defgroup org-imenu-and-speedbar nil
1130 "Options concerning imenu and speedbar in Org-mode."
1131 :tag "Org Imenu and Speedbar"
1132 :group 'org-structure)
1134 (defcustom org-imenu-depth 2
1135 "The maximum level for Imenu access to Org-mode headlines.
1136 This also applied for speedbar access."
1137 :group 'org-imenu-and-speedbar
1138 :type 'integer)
1140 (defgroup org-table nil
1141 "Options concerning tables in Org-mode."
1142 :tag "Org Table"
1143 :group 'org)
1145 (defcustom org-enable-table-editor 'optimized
1146 "Non-nil means lines starting with \"|\" are handled by the table editor.
1147 When nil, such lines will be treated like ordinary lines.
1149 When equal to the symbol `optimized', the table editor will be optimized to
1150 do the following:
1151 - Automatic overwrite mode in front of whitespace in table fields.
1152 This makes the structure of the table stay in tact as long as the edited
1153 field does not exceed the column width.
1154 - Minimize the number of realigns. Normally, the table is aligned each time
1155 TAB or RET are pressed to move to another field. With optimization this
1156 happens only if changes to a field might have changed the column width.
1157 Optimization requires replacing the functions `self-insert-command',
1158 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1159 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1160 very good at guessing when a re-align will be necessary, but you can always
1161 force one with \\[org-ctrl-c-ctrl-c].
1163 If you would like to use the optimized version in Org-mode, but the
1164 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1166 This variable can be used to turn on and off the table editor during a session,
1167 but in order to toggle optimization, a restart is required.
1169 See also the variable `org-table-auto-blank-field'."
1170 :group 'org-table
1171 :type '(choice
1172 (const :tag "off" nil)
1173 (const :tag "on" t)
1174 (const :tag "on, optimized" optimized)))
1176 (defcustom org-self-insert-cluster-for-undo t
1177 "Non-nil means cluster self-insert commands for undo when possible.
1178 If this is set, then, like in the Emacs command loop, 20 consecutive
1179 characters will be undone together.
1180 This is configurable, because there is some impact on typing performance."
1181 :group 'org-table
1182 :type 'boolean)
1184 (defcustom org-table-tab-recognizes-table.el t
1185 "Non-nil means TAB will automatically notice a table.el table.
1186 When it sees such a table, it moves point into it and - if necessary -
1187 calls `table-recognize-table'."
1188 :group 'org-table-editing
1189 :type 'boolean)
1191 (defgroup org-link nil
1192 "Options concerning links in Org-mode."
1193 :tag "Org Link"
1194 :group 'org)
1196 (defvar org-link-abbrev-alist-local nil
1197 "Buffer-local version of `org-link-abbrev-alist', which see.
1198 The value of this is taken from the #+LINK lines.")
1199 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1201 (defcustom org-link-abbrev-alist nil
1202 "Alist of link abbreviations.
1203 The car of each element is a string, to be replaced at the start of a link.
1204 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1205 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1207 [[linkkey:tag][description]]
1209 The 'linkkey' must be a word word, starting with a letter, followed
1210 by letters, numbers, '-' or '_'.
1212 If REPLACE is a string, the tag will simply be appended to create the link.
1213 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1214 the placeholder \"%h\" will cause a url-encoded version of the tag to
1215 be inserted at that point (see the function `url-hexify-string').
1217 REPLACE may also be a function that will be called with the tag as the
1218 only argument to create the link, which should be returned as a string.
1220 See the manual for examples."
1221 :group 'org-link
1222 :type '(repeat
1223 (cons
1224 (string :tag "Protocol")
1225 (choice
1226 (string :tag "Format")
1227 (function)))))
1229 (defcustom org-descriptive-links t
1230 "Non-nil means hide link part and only show description of bracket links.
1231 Bracket links are like [[link][description]]. This variable sets the initial
1232 state in new org-mode buffers. The setting can then be toggled on a
1233 per-buffer basis from the Org->Hyperlinks menu."
1234 :group 'org-link
1235 :type 'boolean)
1237 (defcustom org-link-file-path-type 'adaptive
1238 "How the path name in file links should be stored.
1239 Valid values are:
1241 relative Relative to the current directory, i.e. the directory of the file
1242 into which the link is being inserted.
1243 absolute Absolute path, if possible with ~ for home directory.
1244 noabbrev Absolute path, no abbreviation of home directory.
1245 adaptive Use relative path for files in the current directory and sub-
1246 directories of it. For other files, use an absolute path."
1247 :group 'org-link
1248 :type '(choice
1249 (const relative)
1250 (const absolute)
1251 (const noabbrev)
1252 (const adaptive)))
1254 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1255 "Types of links that should be activated in Org-mode files.
1256 This is a list of symbols, each leading to the activation of a certain link
1257 type. In principle, it does not hurt to turn on most link types - there may
1258 be a small gain when turning off unused link types. The types are:
1260 bracket The recommended [[link][description]] or [[link]] links with hiding.
1261 angular Links in angular brackets that may contain whitespace like
1262 <bbdb:Carsten Dominik>.
1263 plain Plain links in normal text, no whitespace, like http://google.com.
1264 radio Text that is matched by a radio target, see manual for details.
1265 tag Tag settings in a headline (link to tag search).
1266 date Time stamps (link to calendar).
1267 footnote Footnote labels.
1269 Changing this variable requires a restart of Emacs to become effective."
1270 :group 'org-link
1271 :type '(set :greedy t
1272 (const :tag "Double bracket links (new style)" bracket)
1273 (const :tag "Angular bracket links (old style)" angular)
1274 (const :tag "Plain text links" plain)
1275 (const :tag "Radio target matches" radio)
1276 (const :tag "Tags" tag)
1277 (const :tag "Timestamps" date)
1278 (const :tag "Footnotes" footnote)))
1280 (defcustom org-make-link-description-function nil
1281 "Function to use to generate link descriptions from links.
1282 If nil the link location will be used. This function must take
1283 two parameters; the first is the link and the second the
1284 description `org-insert-link' has generated, and should return the
1285 description to use."
1286 :group 'org-link
1287 :type 'function)
1289 (defgroup org-link-store nil
1290 "Options concerning storing links in Org-mode."
1291 :tag "Org Store Link"
1292 :group 'org-link)
1294 (defcustom org-email-link-description-format "Email %c: %.30s"
1295 "Format of the description part of a link to an email or usenet message.
1296 The following %-escapes will be replaced by corresponding information:
1298 %F full \"From\" field
1299 %f name, taken from \"From\" field, address if no name
1300 %T full \"To\" field
1301 %t first name in \"To\" field, address if no name
1302 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1303 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1304 %s subject
1305 %m message-id.
1307 You may use normal field width specification between the % and the letter.
1308 This is for example useful to limit the length of the subject.
1310 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1311 :group 'org-link-store
1312 :type 'string)
1314 (defcustom org-from-is-user-regexp
1315 (let (r1 r2)
1316 (when (and user-mail-address (not (string= user-mail-address "")))
1317 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1318 (when (and user-full-name (not (string= user-full-name "")))
1319 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1320 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1321 "Regexp matched against the \"From:\" header of an email or usenet message.
1322 It should match if the message is from the user him/herself."
1323 :group 'org-link-store
1324 :type 'regexp)
1326 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1327 "Non-nil means storing a link to an Org file will use entry IDs.
1329 Note that before this variable is even considered, org-id must be loaded,
1330 so please customize `org-modules' and turn it on.
1332 The variable can have the following values:
1334 t Create an ID if needed to make a link to the current entry.
1336 create-if-interactive
1337 If `org-store-link' is called directly (interactively, as a user
1338 command), do create an ID to support the link. But when doing the
1339 job for remember, only use the ID if it already exists. The
1340 purpose of this setting is to avoid proliferation of unwanted
1341 IDs, just because you happen to be in an Org file when you
1342 call `org-remember' that automatically and preemptively
1343 creates a link. If you do want to get an ID link in a remember
1344 template to an entry not having an ID, create it first by
1345 explicitly creating a link to it, using `C-c C-l' first.
1347 create-if-interactive-and-no-custom-id
1348 Like create-if-interactive, but do not create an ID if there is
1349 a CUSTOM_ID property defined in the entry. This is the default.
1351 use-existing
1352 Use existing ID, do not create one.
1354 nil Never use an ID to make a link, instead link using a text search for
1355 the headline text."
1356 :group 'org-link-store
1357 :type '(choice
1358 (const :tag "Create ID to make link" t)
1359 (const :tag "Create if storing link interactively"
1360 create-if-interactive)
1361 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1362 create-if-interactive-and-no-custom-id)
1363 (const :tag "Only use existing" use-existing)
1364 (const :tag "Do not use ID to create link" nil)))
1366 (defcustom org-context-in-file-links t
1367 "Non-nil means file links from `org-store-link' contain context.
1368 A search string will be added to the file name with :: as separator and
1369 used to find the context when the link is activated by the command
1370 `org-open-at-point'.
1371 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1372 negates this setting for the duration of the command."
1373 :group 'org-link-store
1374 :type 'boolean)
1376 (defcustom org-keep-stored-link-after-insertion nil
1377 "Non-nil means keep link in list for entire session.
1379 The command `org-store-link' adds a link pointing to the current
1380 location to an internal list. These links accumulate during a session.
1381 The command `org-insert-link' can be used to insert links into any
1382 Org-mode file (offering completion for all stored links). When this
1383 option is nil, every link which has been inserted once using \\[org-insert-link]
1384 will be removed from the list, to make completing the unused links
1385 more efficient."
1386 :group 'org-link-store
1387 :type 'boolean)
1389 (defgroup org-link-follow nil
1390 "Options concerning following links in Org-mode."
1391 :tag "Org Follow Link"
1392 :group 'org-link)
1394 (defcustom org-link-translation-function nil
1395 "Function to translate links with different syntax to Org syntax.
1396 This can be used to translate links created for example by the Planner
1397 or emacs-wiki packages to Org syntax.
1398 The function must accept two parameters, a TYPE containing the link
1399 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1400 which is everything after the link protocol. It should return a cons
1401 with possibly modified values of type and path.
1402 Org contains a function for this, so if you set this variable to
1403 `org-translate-link-from-planner', you should be able follow many
1404 links created by planner."
1405 :group 'org-link-follow
1406 :type 'function)
1408 (defcustom org-follow-link-hook nil
1409 "Hook that is run after a link has been followed."
1410 :group 'org-link-follow
1411 :type 'hook)
1413 (defcustom org-tab-follows-link nil
1414 "Non-nil means on links TAB will follow the link.
1415 Needs to be set before org.el is loaded.
1416 This really should not be used, it does not make sense, and the
1417 implementation is bad."
1418 :group 'org-link-follow
1419 :type 'boolean)
1421 (defcustom org-return-follows-link nil
1422 "Non-nil means on links RET will follow the link."
1423 :group 'org-link-follow
1424 :type 'boolean)
1426 (defcustom org-mouse-1-follows-link
1427 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1428 "Non-nil means mouse-1 on a link will follow the link.
1429 A longer mouse click will still set point. Does not work on XEmacs.
1430 Needs to be set before org.el is loaded."
1431 :group 'org-link-follow
1432 :type 'boolean)
1434 (defcustom org-mark-ring-length 4
1435 "Number of different positions to be recorded in the ring.
1436 Changing this requires a restart of Emacs to work correctly."
1437 :group 'org-link-follow
1438 :type 'integer)
1440 (defcustom org-link-frame-setup
1441 '((vm . vm-visit-folder-other-frame)
1442 (gnus . org-gnus-no-new-news)
1443 (file . find-file-other-window)
1444 (wl . wl-other-frame))
1445 "Setup the frame configuration for following links.
1446 When following a link with Emacs, it may often be useful to display
1447 this link in another window or frame. This variable can be used to
1448 set this up for the different types of links.
1449 For VM, use any of
1450 `vm-visit-folder'
1451 `vm-visit-folder-other-frame'
1452 For Gnus, use any of
1453 `gnus'
1454 `gnus-other-frame'
1455 `org-gnus-no-new-news'
1456 For FILE, use any of
1457 `find-file'
1458 `find-file-other-window'
1459 `find-file-other-frame'
1460 For Wanderlust use any of
1461 `wl'
1462 `wl-other-frame'
1463 For the calendar, use the variable `calendar-setup'.
1464 For BBDB, it is currently only possible to display the matches in
1465 another window."
1466 :group 'org-link-follow
1467 :type '(list
1468 (cons (const vm)
1469 (choice
1470 (const vm-visit-folder)
1471 (const vm-visit-folder-other-window)
1472 (const vm-visit-folder-other-frame)))
1473 (cons (const gnus)
1474 (choice
1475 (const gnus)
1476 (const gnus-other-frame)
1477 (const org-gnus-no-new-news)))
1478 (cons (const file)
1479 (choice
1480 (const find-file)
1481 (const find-file-other-window)
1482 (const find-file-other-frame)))
1483 (cons (const wl)
1484 (choice
1485 (const wl)
1486 (const wl-other-frame)))))
1488 (defcustom org-display-internal-link-with-indirect-buffer nil
1489 "Non-nil means use indirect buffer to display infile links.
1490 Activating internal links (from one location in a file to another location
1491 in the same file) normally just jumps to the location. When the link is
1492 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1493 is displayed in
1494 another window. When this option is set, the other window actually displays
1495 an indirect buffer clone of the current buffer, to avoid any visibility
1496 changes to the current buffer."
1497 :group 'org-link-follow
1498 :type 'boolean)
1500 (defcustom org-open-non-existing-files nil
1501 "Non-nil means `org-open-file' will open non-existing files.
1502 When nil, an error will be generated.
1503 This variable applies only to external applications because they
1504 might choke on non-existing files. If the link is to a file that
1505 will be opened in Emacs, the variable is ignored."
1506 :group 'org-link-follow
1507 :type 'boolean)
1509 (defcustom org-open-directory-means-index-dot-org nil
1510 "Non-nil means a link to a directory really means to index.org.
1511 When nil, following a directory link will run dired or open a finder/explorer
1512 window on that directory."
1513 :group 'org-link-follow
1514 :type 'boolean)
1516 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1517 "Function and arguments to call for following mailto links.
1518 This is a list with the first element being a Lisp function, and the
1519 remaining elements being arguments to the function. In string arguments,
1520 %a will be replaced by the address, and %s will be replaced by the subject
1521 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1522 :group 'org-link-follow
1523 :type '(choice
1524 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1525 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1526 (const :tag "message-mail" (message-mail "%a" "%s"))
1527 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1529 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1530 "Non-nil means ask for confirmation before executing shell links.
1531 Shell links can be dangerous: just think about a link
1533 [[shell:rm -rf ~/*][Google Search]]
1535 This link would show up in your Org-mode document as \"Google Search\",
1536 but really it would remove your entire home directory.
1537 Therefore we advise against setting this variable to nil.
1538 Just change it to `y-or-n-p' if you want to confirm with a
1539 single keystroke rather than having to type \"yes\"."
1540 :group 'org-link-follow
1541 :type '(choice
1542 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1543 (const :tag "with y-or-n (faster)" y-or-n-p)
1544 (const :tag "no confirmation (dangerous)" nil)))
1545 (put 'org-confirm-shell-link-function
1546 'safe-local-variable
1547 '(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1549 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1550 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1551 Elisp links can be dangerous: just think about a link
1553 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1555 This link would show up in your Org-mode document as \"Google Search\",
1556 but really it would remove your entire home directory.
1557 Therefore we advise against setting this variable to nil.
1558 Just change it to `y-or-n-p' if you want to confirm with a
1559 single keystroke rather than having to type \"yes\"."
1560 :group 'org-link-follow
1561 :type '(choice
1562 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1563 (const :tag "with y-or-n (faster)" y-or-n-p)
1564 (const :tag "no confirmation (dangerous)" nil)))
1565 (put 'org-confirm-shell-link-function
1566 'safe-local-variable
1567 '(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1569 (defconst org-file-apps-defaults-gnu
1570 '((remote . emacs)
1571 (system . mailcap)
1572 (t . mailcap))
1573 "Default file applications on a UNIX or GNU/Linux system.
1574 See `org-file-apps'.")
1576 (defconst org-file-apps-defaults-macosx
1577 '((remote . emacs)
1578 (t . "open %s")
1579 (system . "open %s")
1580 ("ps.gz" . "gv %s")
1581 ("eps.gz" . "gv %s")
1582 ("dvi" . "xdvi %s")
1583 ("fig" . "xfig %s"))
1584 "Default file applications on a MacOS X system.
1585 The system \"open\" is known as a default, but we use X11 applications
1586 for some files for which the OS does not have a good default.
1587 See `org-file-apps'.")
1589 (defconst org-file-apps-defaults-windowsnt
1590 (list
1591 '(remote . emacs)
1592 (cons t
1593 (list (if (featurep 'xemacs)
1594 'mswindows-shell-execute
1595 'w32-shell-execute)
1596 "open" 'file))
1597 (cons 'system
1598 (list (if (featurep 'xemacs)
1599 'mswindows-shell-execute
1600 'w32-shell-execute)
1601 "open" 'file)))
1602 "Default file applications on a Windows NT system.
1603 The system \"open\" is used for most files.
1604 See `org-file-apps'.")
1606 (defcustom org-file-apps
1608 (auto-mode . emacs)
1609 ("\\.mm\\'" . default)
1610 ("\\.x?html?\\'" . default)
1611 ("\\.pdf\\'" . default)
1613 "External applications for opening `file:path' items in a document.
1614 Org-mode uses system defaults for different file types, but
1615 you can use this variable to set the application for a given file
1616 extension. The entries in this list are cons cells where the car identifies
1617 files and the cdr the corresponding command. Possible values for the
1618 file identifier are
1619 \"string\" A string as a file identifier can be interpreted in different
1620 ways, depending on its contents:
1622 - Alphanumeric characters only:
1623 Match links with this file extension.
1624 Example: (\"pdf\" . \"evince %s\")
1625 to open PDFs with evince.
1627 - Regular expression: Match links where the
1628 filename matches the regexp. If you want to
1629 use groups here, use shy groups.
1631 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1632 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1633 to open *.html and *.xhtml with firefox.
1635 - Regular expression which contains (non-shy) groups:
1636 Match links where the whole link, including \"::\", and
1637 anything after that, matches the regexp.
1638 In a custom command string, %1, %2, etc. are replaced with
1639 the parts of the link that were matched by the groups.
1640 For backwards compatibility, if a command string is given
1641 that does not use any of the group matches, this case is
1642 handled identically to the second one (i.e. match against
1643 file name only).
1644 In a custom lisp form, you can access the group matches with
1645 (match-string n link).
1647 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1648 to open [[file:document.pdf::5]] with evince at page 5.
1650 `directory' Matches a directory
1651 `remote' Matches a remote file, accessible through tramp or efs.
1652 Remote files most likely should be visited through Emacs
1653 because external applications cannot handle such paths.
1654 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1655 so all files Emacs knows how to handle. Using this with
1656 command `emacs' will open most files in Emacs. Beware that this
1657 will also open html files inside Emacs, unless you add
1658 (\"html\" . default) to the list as well.
1659 t Default for files not matched by any of the other options.
1660 `system' The system command to open files, like `open' on Windows
1661 and Mac OS X, and mailcap under GNU/Linux. This is the command
1662 that will be selected if you call `C-c C-o' with a double
1663 \\[universal-argument] \\[universal-argument] prefix.
1665 Possible values for the command are:
1666 `emacs' The file will be visited by the current Emacs process.
1667 `default' Use the default application for this file type, which is the
1668 association for t in the list, most likely in the system-specific
1669 part.
1670 This can be used to overrule an unwanted setting in the
1671 system-specific variable.
1672 `system' Use the system command for opening files, like \"open\".
1673 This command is specified by the entry whose car is `system'.
1674 Most likely, the system-specific version of this variable
1675 does define this command, but you can overrule/replace it
1676 here.
1677 string A command to be executed by a shell; %s will be replaced
1678 by the path to the file.
1679 sexp A Lisp form which will be evaluated. The file path will
1680 be available in the Lisp variable `file'.
1681 For more examples, see the system specific constants
1682 `org-file-apps-defaults-macosx'
1683 `org-file-apps-defaults-windowsnt'
1684 `org-file-apps-defaults-gnu'."
1685 :group 'org-link-follow
1686 :type '(repeat
1687 (cons (choice :value ""
1688 (string :tag "Extension")
1689 (const :tag "System command to open files" system)
1690 (const :tag "Default for unrecognized files" t)
1691 (const :tag "Remote file" remote)
1692 (const :tag "Links to a directory" directory)
1693 (const :tag "Any files that have Emacs modes"
1694 auto-mode))
1695 (choice :value ""
1696 (const :tag "Visit with Emacs" emacs)
1697 (const :tag "Use default" default)
1698 (const :tag "Use the system command" system)
1699 (string :tag "Command")
1700 (sexp :tag "Lisp form")))))
1704 (defgroup org-refile nil
1705 "Options concerning refiling entries in Org-mode."
1706 :tag "Org Refile"
1707 :group 'org)
1709 (defcustom org-directory "~/org"
1710 "Directory with org files.
1711 This is just a default location to look for Org files. There is no need
1712 at all to put your files into this directory. It is only used in the
1713 following situations:
1715 1. When a remember template specifies a target file that is not an
1716 absolute path. The path will then be interpreted relative to
1717 `org-directory'
1718 2. When a remember note is filed away in an interactive way (when exiting the
1719 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1720 with `org-directory' as the default path."
1721 :group 'org-refile
1722 :group 'org-remember
1723 :type 'directory)
1725 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1726 "Default target for storing notes.
1727 Used as a fall back file for org-remember.el and org-capture.el, for
1728 templates that do not specify a target file."
1729 :group 'org-refile
1730 :group 'org-remember
1731 :type '(choice
1732 (const :tag "Default from remember-data-file" nil)
1733 file))
1735 (defcustom org-goto-interface 'outline
1736 "The default interface to be used for `org-goto'.
1737 Allowed values are:
1738 outline The interface shows an outline of the relevant file
1739 and the correct heading is found by moving through
1740 the outline or by searching with incremental search.
1741 outline-path-completion Headlines in the current buffer are offered via
1742 completion. This is the interface also used by
1743 the refile command."
1744 :group 'org-refile
1745 :type '(choice
1746 (const :tag "Outline" outline)
1747 (const :tag "Outline-path-completion" outline-path-completion)))
1749 (defcustom org-goto-max-level 5
1750 "Maximum target level when running `org-goto' with refile interface."
1751 :group 'org-refile
1752 :type 'integer)
1754 (defcustom org-reverse-note-order nil
1755 "Non-nil means store new notes at the beginning of a file or entry.
1756 When nil, new notes will be filed to the end of a file or entry.
1757 This can also be a list with cons cells of regular expressions that
1758 are matched against file names, and values."
1759 :group 'org-remember
1760 :group 'org-refile
1761 :type '(choice
1762 (const :tag "Reverse always" t)
1763 (const :tag "Reverse never" nil)
1764 (repeat :tag "By file name regexp"
1765 (cons regexp boolean))))
1767 (defcustom org-log-refile nil
1768 "Information to record when a task is refiled.
1770 Possible values are:
1772 nil Don't add anything
1773 time Add a time stamp to the task
1774 note Prompt for a note and add it with template `org-log-note-headings'
1776 This option can also be set with on a per-file-basis with
1778 #+STARTUP: nologrefile
1779 #+STARTUP: logrefile
1780 #+STARTUP: lognoterefile
1782 You can have local logging settings for a subtree by setting the LOGGING
1783 property to one or more of these keywords.
1785 When bulk-refiling from the agenda, the value `note' is forbidden and
1786 will temporarily be changed to `time'."
1787 :group 'org-refile
1788 :group 'org-progress
1789 :type '(choice
1790 (const :tag "No logging" nil)
1791 (const :tag "Record timestamp" time)
1792 (const :tag "Record timestamp with note." note)))
1794 (defcustom org-refile-targets nil
1795 "Targets for refiling entries with \\[org-refile].
1796 This is list of cons cells. Each cell contains:
1797 - a specification of the files to be considered, either a list of files,
1798 or a symbol whose function or variable value will be used to retrieve
1799 a file name or a list of file names. If you use `org-agenda-files' for
1800 that, all agenda files will be scanned for targets. Nil means consider
1801 headings in the current buffer.
1802 - A specification of how to find candidate refile targets. This may be
1803 any of:
1804 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1805 This tag has to be present in all target headlines, inheritance will
1806 not be considered.
1807 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1808 todo keyword.
1809 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1810 headlines that are refiling targets.
1811 - a cons cell (:level . N). Any headline of level N is considered a target.
1812 Note that, when `org-odd-levels-only' is set, level corresponds to
1813 order in hierarchy, not to the number of stars.
1814 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1815 Note that, when `org-odd-levels-only' is set, level corresponds to
1816 order in hierarchy, not to the number of stars.
1818 You can set the variable `org-refile-target-verify-function' to a function
1819 to verify each headline found by the simple criteria above.
1821 When this variable is nil, all top-level headlines in the current buffer
1822 are used, equivalent to the value `((nil . (:level . 1))'."
1823 :group 'org-refile
1824 :type '(repeat
1825 (cons
1826 (choice :value org-agenda-files
1827 (const :tag "All agenda files" org-agenda-files)
1828 (const :tag "Current buffer" nil)
1829 (function) (variable) (file))
1830 (choice :tag "Identify target headline by"
1831 (cons :tag "Specific tag" (const :value :tag) (string))
1832 (cons :tag "TODO keyword" (const :value :todo) (string))
1833 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1834 (cons :tag "Level number" (const :value :level) (integer))
1835 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1837 (defcustom org-refile-target-verify-function nil
1838 "Function to verify if the headline at point should be a refile target.
1839 The function will be called without arguments, with point at the
1840 beginning of the headline. It should return t and leave point
1841 where it is if the headline is a valid target for refiling.
1843 If the target should not be selected, the function must return nil.
1844 In addition to this, it may move point to a place from where the search
1845 should be continued. For example, the function may decide that the entire
1846 subtree of the current entry should be excluded and move point to the end
1847 of the subtree."
1848 :group 'org-refile
1849 :type 'function)
1851 (defcustom org-refile-use-cache nil
1852 "Non-nil means cache refile targets to speed up the process.
1853 The cache for a particular file will be updated automatically when
1854 the buffer has been killed, or when any of the marker used for flagging
1855 refile targets no longer points at a live buffer.
1856 If you have added new entries to a buffer that might themselves be targets,
1857 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
1858 find that easier, `C-u C-u C-u C-c C-w'."
1859 :group 'org-refile
1860 :type 'boolean)
1862 (defcustom org-refile-use-outline-path nil
1863 "Non-nil means provide refile targets as paths.
1864 So a level 3 headline will be available as level1/level2/level3.
1866 When the value is `file', also include the file name (without directory)
1867 into the path. In this case, you can also stop the completion after
1868 the file name, to get entries inserted as top level in the file.
1870 When `full-file-path', include the full file path."
1871 :group 'org-refile
1872 :type '(choice
1873 (const :tag "Not" nil)
1874 (const :tag "Yes" t)
1875 (const :tag "Start with file name" file)
1876 (const :tag "Start with full file path" full-file-path)))
1878 (defcustom org-outline-path-complete-in-steps t
1879 "Non-nil means complete the outline path in hierarchical steps.
1880 When Org-mode uses the refile interface to select an outline path
1881 \(see variable `org-refile-use-outline-path'), the completion of
1882 the path can be done is a single go, or if can be done in steps down
1883 the headline hierarchy. Going in steps is probably the best if you
1884 do not use a special completion package like `ido' or `icicles'.
1885 However, when using these packages, going in one step can be very
1886 fast, while still showing the whole path to the entry."
1887 :group 'org-refile
1888 :type 'boolean)
1890 (defcustom org-refile-allow-creating-parent-nodes nil
1891 "Non-nil means allow to create new nodes as refile targets.
1892 New nodes are then created by adding \"/new node name\" to the completion
1893 of an existing node. When the value of this variable is `confirm',
1894 new node creation must be confirmed by the user (recommended)
1895 When nil, the completion must match an existing entry.
1897 Note that, if the new heading is not seen by the criteria
1898 listed in `org-refile-targets', multiple instances of the same
1899 heading would be created by trying again to file under the new
1900 heading."
1901 :group 'org-refile
1902 :type '(choice
1903 (const :tag "Never" nil)
1904 (const :tag "Always" t)
1905 (const :tag "Prompt for confirmation" confirm)))
1907 (defgroup org-todo nil
1908 "Options concerning TODO items in Org-mode."
1909 :tag "Org TODO"
1910 :group 'org)
1912 (defgroup org-progress nil
1913 "Options concerning Progress logging in Org-mode."
1914 :tag "Org Progress"
1915 :group 'org-time)
1917 (defvar org-todo-interpretation-widgets
1919 (:tag "Sequence (cycling hits every state)" sequence)
1920 (:tag "Type (cycling directly to DONE)" type))
1921 "The available interpretation symbols for customizing `org-todo-keywords'.
1922 Interested libraries should add to this list.")
1924 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1925 "List of TODO entry keyword sequences and their interpretation.
1926 \\<org-mode-map>This is a list of sequences.
1928 Each sequence starts with a symbol, either `sequence' or `type',
1929 indicating if the keywords should be interpreted as a sequence of
1930 action steps, or as different types of TODO items. The first
1931 keywords are states requiring action - these states will select a headline
1932 for inclusion into the global TODO list Org-mode produces. If one of
1933 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1934 signify that no further action is necessary. If \"|\" is not found,
1935 the last keyword is treated as the only DONE state of the sequence.
1937 The command \\[org-todo] cycles an entry through these states, and one
1938 additional state where no keyword is present. For details about this
1939 cycling, see the manual.
1941 TODO keywords and interpretation can also be set on a per-file basis with
1942 the special #+SEQ_TODO and #+TYP_TODO lines.
1944 Each keyword can optionally specify a character for fast state selection
1945 \(in combination with the variable `org-use-fast-todo-selection')
1946 and specifiers for state change logging, using the same syntax
1947 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1948 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1949 indicates to record a time stamp each time this state is selected.
1951 Each keyword may also specify if a timestamp or a note should be
1952 recorded when entering or leaving the state, by adding additional
1953 characters in the parenthesis after the keyword. This looks like this:
1954 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1955 record only the time of the state change. With X and Y being either
1956 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1957 Y when leaving the state if and only if the *target* state does not
1958 define X. You may omit any of the fast-selection key or X or /Y,
1959 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1961 For backward compatibility, this variable may also be just a list
1962 of keywords - in this case the interpretation (sequence or type) will be
1963 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1964 :group 'org-todo
1965 :group 'org-keywords
1966 :type '(choice
1967 (repeat :tag "Old syntax, just keywords"
1968 (string :tag "Keyword"))
1969 (repeat :tag "New syntax"
1970 (cons
1971 (choice
1972 :tag "Interpretation"
1973 ;;Quick and dirty way to see
1974 ;;`org-todo-interpretations'. This takes the
1975 ;;place of item arguments
1976 :convert-widget
1977 (lambda (widget)
1978 (widget-put widget
1979 :args (mapcar
1980 #'(lambda (x)
1981 (widget-convert
1982 (cons 'const x)))
1983 org-todo-interpretation-widgets))
1984 widget))
1985 (repeat
1986 (string :tag "Keyword"))))))
1988 (defvar org-todo-keywords-1 nil
1989 "All TODO and DONE keywords active in a buffer.")
1990 (make-variable-buffer-local 'org-todo-keywords-1)
1991 (defvar org-todo-keywords-for-agenda nil)
1992 (defvar org-done-keywords-for-agenda nil)
1993 (defvar org-drawers-for-agenda nil)
1994 (defvar org-todo-keyword-alist-for-agenda nil)
1995 (defvar org-tag-alist-for-agenda nil)
1996 (defvar org-agenda-contributing-files nil)
1997 (defvar org-not-done-keywords nil)
1998 (make-variable-buffer-local 'org-not-done-keywords)
1999 (defvar org-done-keywords nil)
2000 (make-variable-buffer-local 'org-done-keywords)
2001 (defvar org-todo-heads nil)
2002 (make-variable-buffer-local 'org-todo-heads)
2003 (defvar org-todo-sets nil)
2004 (make-variable-buffer-local 'org-todo-sets)
2005 (defvar org-todo-log-states nil)
2006 (make-variable-buffer-local 'org-todo-log-states)
2007 (defvar org-todo-kwd-alist nil)
2008 (make-variable-buffer-local 'org-todo-kwd-alist)
2009 (defvar org-todo-key-alist nil)
2010 (make-variable-buffer-local 'org-todo-key-alist)
2011 (defvar org-todo-key-trigger nil)
2012 (make-variable-buffer-local 'org-todo-key-trigger)
2014 (defcustom org-todo-interpretation 'sequence
2015 "Controls how TODO keywords are interpreted.
2016 This variable is in principle obsolete and is only used for
2017 backward compatibility, if the interpretation of todo keywords is
2018 not given already in `org-todo-keywords'. See that variable for
2019 more information."
2020 :group 'org-todo
2021 :group 'org-keywords
2022 :type '(choice (const sequence)
2023 (const type)))
2025 (defcustom org-use-fast-todo-selection t
2026 "Non-nil means use the fast todo selection scheme with C-c C-t.
2027 This variable describes if and under what circumstances the cycling
2028 mechanism for TODO keywords will be replaced by a single-key, direct
2029 selection scheme.
2031 When nil, fast selection is never used.
2033 When the symbol `prefix', it will be used when `org-todo' is called with
2034 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
2035 in an agenda buffer.
2037 When t, fast selection is used by default. In this case, the prefix
2038 argument forces cycling instead.
2040 In all cases, the special interface is only used if access keys have actually
2041 been assigned by the user, i.e. if keywords in the configuration are followed
2042 by a letter in parenthesis, like TODO(t)."
2043 :group 'org-todo
2044 :type '(choice
2045 (const :tag "Never" nil)
2046 (const :tag "By default" t)
2047 (const :tag "Only with C-u C-c C-t" prefix)))
2049 (defcustom org-provide-todo-statistics t
2050 "Non-nil means update todo statistics after insert and toggle.
2051 ALL-HEADLINES means update todo statistics by including headlines
2052 with no TODO keyword as well, counting them as not done.
2053 A list of TODO keywords means the same, but skip keywords that are
2054 not in this list.
2056 When this is set, todo statistics is updated in the parent of the
2057 current entry each time a todo state is changed."
2058 :group 'org-todo
2059 :type '(choice
2060 (const :tag "Yes, only for TODO entries" t)
2061 (const :tag "Yes, including all entries" 'all-headlines)
2062 (repeat :tag "Yes, for TODOs in this list"
2063 (string :tag "TODO keyword"))
2064 (other :tag "No TODO statistics" nil)))
2066 (defcustom org-hierarchical-todo-statistics t
2067 "Non-nil means TODO statistics covers just direct children.
2068 When nil, all entries in the subtree are considered.
2069 This has only an effect if `org-provide-todo-statistics' is set.
2070 To set this to nil for only a single subtree, use a COOKIE_DATA
2071 property and include the word \"recursive\" into the value."
2072 :group 'org-todo
2073 :type 'boolean)
2075 (defcustom org-after-todo-state-change-hook nil
2076 "Hook which is run after the state of a TODO item was changed.
2077 The new state (a string with a TODO keyword, or nil) is available in the
2078 Lisp variable `state'."
2079 :group 'org-todo
2080 :type 'hook)
2082 (defvar org-blocker-hook nil
2083 "Hook for functions that are allowed to block a state change.
2085 Each function gets as its single argument a property list, see
2086 `org-trigger-hook' for more information about this list.
2088 If any of the functions in this hook returns nil, the state change
2089 is blocked.")
2091 (defvar org-trigger-hook nil
2092 "Hook for functions that are triggered by a state change.
2094 Each function gets as its single argument a property list with at least
2095 the following elements:
2097 (:type type-of-change :position pos-at-entry-start
2098 :from old-state :to new-state)
2100 Depending on the type, more properties may be present.
2102 This mechanism is currently implemented for:
2104 TODO state changes
2105 ------------------
2106 :type todo-state-change
2107 :from previous state (keyword as a string), or nil, or a symbol
2108 'todo' or 'done', to indicate the general type of state.
2109 :to new state, like in :from")
2111 (defcustom org-enforce-todo-dependencies nil
2112 "Non-nil means undone TODO entries will block switching the parent to DONE.
2113 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2114 be blocked if any prior sibling is not yet done.
2115 Finally, if the parent is blocked because of ordered siblings of its own,
2116 the child will also be blocked.
2117 This variable needs to be set before org.el is loaded, and you need to
2118 restart Emacs after a change to make the change effective. The only way
2119 to change is while Emacs is running is through the customize interface."
2120 :set (lambda (var val)
2121 (set var val)
2122 (if val
2123 (add-hook 'org-blocker-hook
2124 'org-block-todo-from-children-or-siblings-or-parent)
2125 (remove-hook 'org-blocker-hook
2126 'org-block-todo-from-children-or-siblings-or-parent)))
2127 :group 'org-todo
2128 :type 'boolean)
2130 (defcustom org-enforce-todo-checkbox-dependencies nil
2131 "Non-nil means unchecked boxes will block switching the parent to DONE.
2132 When this is nil, checkboxes have no influence on switching TODO states.
2133 When non-nil, you first need to check off all check boxes before the TODO
2134 entry can be switched to DONE.
2135 This variable needs to be set before org.el is loaded, and you need to
2136 restart Emacs after a change to make the change effective. The only way
2137 to change is while Emacs is running is through the customize interface."
2138 :set (lambda (var val)
2139 (set var val)
2140 (if val
2141 (add-hook 'org-blocker-hook
2142 'org-block-todo-from-checkboxes)
2143 (remove-hook 'org-blocker-hook
2144 'org-block-todo-from-checkboxes)))
2145 :group 'org-todo
2146 :type 'boolean)
2148 (defcustom org-treat-insert-todo-heading-as-state-change nil
2149 "Non-nil means inserting a TODO heading is treated as state change.
2150 So when the command \\[org-insert-todo-heading] is used, state change
2151 logging will apply if appropriate. When nil, the new TODO item will
2152 be inserted directly, and no logging will take place."
2153 :group 'org-todo
2154 :type 'boolean)
2156 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2157 "Non-nil means switching TODO states with S-cursor counts as state change.
2158 This is the default behavior. However, setting this to nil allows a
2159 convenient way to select a TODO state and bypass any logging associated
2160 with that."
2161 :group 'org-todo
2162 :type 'boolean)
2164 (defcustom org-todo-state-tags-triggers nil
2165 "Tag changes that should be triggered by TODO state changes.
2166 This is a list. Each entry is
2168 (state-change (tag . flag) .......)
2170 State-change can be a string with a state, and empty string to indicate the
2171 state that has no TODO keyword, or it can be one of the symbols `todo'
2172 or `done', meaning any not-done or done state, respectively."
2173 :group 'org-todo
2174 :group 'org-tags
2175 :type '(repeat
2176 (cons (choice :tag "When changing to"
2177 (const :tag "Not-done state" todo)
2178 (const :tag "Done state" done)
2179 (string :tag "State"))
2180 (repeat
2181 (cons :tag "Tag action"
2182 (string :tag "Tag")
2183 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2185 (defcustom org-log-done nil
2186 "Information to record when a task moves to the DONE state.
2188 Possible values are:
2190 nil Don't add anything, just change the keyword
2191 time Add a time stamp to the task
2192 note Prompt for a note and add it with template `org-log-note-headings'
2194 This option can also be set with on a per-file-basis with
2196 #+STARTUP: nologdone
2197 #+STARTUP: logdone
2198 #+STARTUP: lognotedone
2200 You can have local logging settings for a subtree by setting the LOGGING
2201 property to one or more of these keywords."
2202 :group 'org-todo
2203 :group 'org-progress
2204 :type '(choice
2205 (const :tag "No logging" nil)
2206 (const :tag "Record CLOSED timestamp" time)
2207 (const :tag "Record CLOSED timestamp with note." note)))
2209 ;; Normalize old uses of org-log-done.
2210 (cond
2211 ((eq org-log-done t) (setq org-log-done 'time))
2212 ((and (listp org-log-done) (memq 'done org-log-done))
2213 (setq org-log-done 'note)))
2215 (defcustom org-log-reschedule nil
2216 "Information to record when the scheduling date of a tasks is modified.
2218 Possible values are:
2220 nil Don't add anything, just change the date
2221 time Add a time stamp to the task
2222 note Prompt for a note and add it with template `org-log-note-headings'
2224 This option can also be set with on a per-file-basis with
2226 #+STARTUP: nologreschedule
2227 #+STARTUP: logreschedule
2228 #+STARTUP: lognotereschedule"
2229 :group 'org-todo
2230 :group 'org-progress
2231 :type '(choice
2232 (const :tag "No logging" nil)
2233 (const :tag "Record timestamp" time)
2234 (const :tag "Record timestamp with note." note)))
2236 (defcustom org-log-redeadline nil
2237 "Information to record when the deadline date of a tasks is modified.
2239 Possible values are:
2241 nil Don't add anything, just change the date
2242 time Add a time stamp to the task
2243 note Prompt for a note and add it with template `org-log-note-headings'
2245 This option can also be set with on a per-file-basis with
2247 #+STARTUP: nologredeadline
2248 #+STARTUP: logredeadline
2249 #+STARTUP: lognoteredeadline
2251 You can have local logging settings for a subtree by setting the LOGGING
2252 property to one or more of these keywords."
2253 :group 'org-todo
2254 :group 'org-progress
2255 :type '(choice
2256 (const :tag "No logging" nil)
2257 (const :tag "Record timestamp" time)
2258 (const :tag "Record timestamp with note." note)))
2260 (defcustom org-log-note-clock-out nil
2261 "Non-nil means record a note when clocking out of an item.
2262 This can also be configured on a per-file basis by adding one of
2263 the following lines anywhere in the buffer:
2265 #+STARTUP: lognoteclock-out
2266 #+STARTUP: nolognoteclock-out"
2267 :group 'org-todo
2268 :group 'org-progress
2269 :type 'boolean)
2271 (defcustom org-log-done-with-time t
2272 "Non-nil means the CLOSED time stamp will contain date and time.
2273 When nil, only the date will be recorded."
2274 :group 'org-progress
2275 :type 'boolean)
2277 (defcustom org-log-note-headings
2278 '((done . "CLOSING NOTE %t")
2279 (state . "State %-12s from %-12S %t")
2280 (note . "Note taken on %t")
2281 (reschedule . "Rescheduled from %S on %t")
2282 (delschedule . "Not scheduled, was %S on %t")
2283 (redeadline . "New deadline from %S on %t")
2284 (deldeadline . "Removed deadline, was %S on %t")
2285 (refile . "Refiled on %t")
2286 (clock-out . ""))
2287 "Headings for notes added to entries.
2288 The value is an alist, with the car being a symbol indicating the note
2289 context, and the cdr is the heading to be used. The heading may also be the
2290 empty string.
2291 %t in the heading will be replaced by a time stamp.
2292 %T will be an active time stamp instead the default inactive one
2293 %s will be replaced by the new TODO state, in double quotes.
2294 %S will be replaced by the old TODO state, in double quotes.
2295 %u will be replaced by the user name.
2296 %U will be replaced by the full user name.
2298 In fact, it is not a good idea to change the `state' entry, because
2299 agenda log mode depends on the format of these entries."
2300 :group 'org-todo
2301 :group 'org-progress
2302 :type '(list :greedy t
2303 (cons (const :tag "Heading when closing an item" done) string)
2304 (cons (const :tag
2305 "Heading when changing todo state (todo sequence only)"
2306 state) string)
2307 (cons (const :tag "Heading when just taking a note" note) string)
2308 (cons (const :tag "Heading when clocking out" clock-out) string)
2309 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2310 (cons (const :tag "Heading when rescheduling" reschedule) string)
2311 (cons (const :tag "Heading when changing deadline" redeadline) string)
2312 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2313 (cons (const :tag "Heading when refiling" refile) string)))
2315 (unless (assq 'note org-log-note-headings)
2316 (push '(note . "%t") org-log-note-headings))
2318 (defcustom org-log-into-drawer nil
2319 "Non-nil means insert state change notes and time stamps into a drawer.
2320 When nil, state changes notes will be inserted after the headline and
2321 any scheduling and clock lines, but not inside a drawer.
2323 The value of this variable should be the name of the drawer to use.
2324 LOGBOOK is proposed at the default drawer for this purpose, you can
2325 also set this to a string to define the drawer of your choice.
2327 A value of t is also allowed, representing \"LOGBOOK\".
2329 If this variable is set, `org-log-state-notes-insert-after-drawers'
2330 will be ignored.
2332 You can set the property LOG_INTO_DRAWER to overrule this setting for
2333 a subtree."
2334 :group 'org-todo
2335 :group 'org-progress
2336 :type '(choice
2337 (const :tag "Not into a drawer" nil)
2338 (const :tag "LOGBOOK" t)
2339 (string :tag "Other")))
2341 (if (fboundp 'defvaralias)
2342 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2344 (defun org-log-into-drawer ()
2345 "Return the value of `org-log-into-drawer', but let properties overrule.
2346 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2347 used instead of the default value."
2348 (let ((p (ignore-errors (org-entry-get nil "LOG_INTO_DRAWER" 'inherit))))
2349 (cond
2350 ((or (not p) (equal p "nil")) org-log-into-drawer)
2351 ((equal p "t") "LOGBOOK")
2352 (t p))))
2354 (defcustom org-log-state-notes-insert-after-drawers nil
2355 "Non-nil means insert state change notes after any drawers in entry.
2356 Only the drawers that *immediately* follow the headline and the
2357 deadline/scheduled line are skipped.
2358 When nil, insert notes right after the heading and perhaps the line
2359 with deadline/scheduling if present.
2361 This variable will have no effect if `org-log-into-drawer' is
2362 set."
2363 :group 'org-todo
2364 :group 'org-progress
2365 :type 'boolean)
2367 (defcustom org-log-states-order-reversed t
2368 "Non-nil means the latest state note will be directly after heading.
2369 When nil, the state change notes will be ordered according to time."
2370 :group 'org-todo
2371 :group 'org-progress
2372 :type 'boolean)
2374 (defcustom org-todo-repeat-to-state nil
2375 "The TODO state to which a repeater should return the repeating task.
2376 By default this is the first task in a TODO sequence, or the previous state
2377 in a TODO_TYP set. But you can specify another task here.
2378 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2379 :group 'org-todo
2380 :type '(choice (const :tag "Head of sequence" nil)
2381 (string :tag "Specific state")))
2383 (defcustom org-log-repeat 'time
2384 "Non-nil means record moving through the DONE state when triggering repeat.
2385 An auto-repeating task is immediately switched back to TODO when
2386 marked DONE. If you are not logging state changes (by adding \"@\"
2387 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2388 record a closing note, there will be no record of the task moving
2389 through DONE. This variable forces taking a note anyway.
2391 nil Don't force a record
2392 time Record a time stamp
2393 note Record a note
2395 This option can also be set with on a per-file-basis with
2397 #+STARTUP: logrepeat
2398 #+STARTUP: lognoterepeat
2399 #+STARTUP: nologrepeat
2401 You can have local logging settings for a subtree by setting the LOGGING
2402 property to one or more of these keywords."
2403 :group 'org-todo
2404 :group 'org-progress
2405 :type '(choice
2406 (const :tag "Don't force a record" nil)
2407 (const :tag "Force recording the DONE state" time)
2408 (const :tag "Force recording a note with the DONE state" note)))
2411 (defgroup org-priorities nil
2412 "Priorities in Org-mode."
2413 :tag "Org Priorities"
2414 :group 'org-todo)
2416 (defcustom org-enable-priority-commands t
2417 "Non-nil means priority commands are active.
2418 When nil, these commands will be disabled, so that you never accidentally
2419 set a priority."
2420 :group 'org-priorities
2421 :type 'boolean)
2423 (defcustom org-highest-priority ?A
2424 "The highest priority of TODO items. A character like ?A, ?B etc.
2425 Must have a smaller ASCII number than `org-lowest-priority'."
2426 :group 'org-priorities
2427 :type 'character)
2429 (defcustom org-lowest-priority ?C
2430 "The lowest priority of TODO items. A character like ?A, ?B etc.
2431 Must have a larger ASCII number than `org-highest-priority'."
2432 :group 'org-priorities
2433 :type 'character)
2435 (defcustom org-default-priority ?B
2436 "The default priority of TODO items.
2437 This is the priority an item get if no explicit priority is given."
2438 :group 'org-priorities
2439 :type 'character)
2441 (defcustom org-priority-start-cycle-with-default t
2442 "Non-nil means start with default priority when starting to cycle.
2443 When this is nil, the first step in the cycle will be (depending on the
2444 command used) one higher or lower that the default priority."
2445 :group 'org-priorities
2446 :type 'boolean)
2448 (defgroup org-time nil
2449 "Options concerning time stamps and deadlines in Org-mode."
2450 :tag "Org Time"
2451 :group 'org)
2453 (defcustom org-insert-labeled-timestamps-at-point nil
2454 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2455 When nil, these labeled time stamps are forces into the second line of an
2456 entry, just after the headline. When scheduling from the global TODO list,
2457 the time stamp will always be forced into the second line."
2458 :group 'org-time
2459 :type 'boolean)
2461 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2462 "Formats for `format-time-string' which are used for time stamps.
2463 It is not recommended to change this constant.")
2465 (defcustom org-time-stamp-rounding-minutes '(0 5)
2466 "Number of minutes to round time stamps to.
2467 These are two values, the first applies when first creating a time stamp.
2468 The second applies when changing it with the commands `S-up' and `S-down'.
2469 When changing the time stamp, this means that it will change in steps
2470 of N minutes, as given by the second value.
2472 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2473 numbers should be factors of 60, so for example 5, 10, 15.
2475 When this is larger than 1, you can still force an exact time stamp by using
2476 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2477 and by using a prefix arg to `S-up/down' to specify the exact number
2478 of minutes to shift."
2479 :group 'org-time
2480 :get '(lambda (var) ; Make sure both elements are there
2481 (if (integerp (default-value var))
2482 (list (default-value var) 5)
2483 (default-value var)))
2484 :type '(list
2485 (integer :tag "when inserting times")
2486 (integer :tag "when modifying times")))
2488 ;; Normalize old customizations of this variable.
2489 (when (integerp org-time-stamp-rounding-minutes)
2490 (setq org-time-stamp-rounding-minutes
2491 (list org-time-stamp-rounding-minutes
2492 org-time-stamp-rounding-minutes)))
2494 (defcustom org-display-custom-times nil
2495 "Non-nil means overlay custom formats over all time stamps.
2496 The formats are defined through the variable `org-time-stamp-custom-formats'.
2497 To turn this on on a per-file basis, insert anywhere in the file:
2498 #+STARTUP: customtime"
2499 :group 'org-time
2500 :set 'set-default
2501 :type 'sexp)
2502 (make-variable-buffer-local 'org-display-custom-times)
2504 (defcustom org-time-stamp-custom-formats
2505 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2506 "Custom formats for time stamps. See `format-time-string' for the syntax.
2507 These are overlayed over the default ISO format if the variable
2508 `org-display-custom-times' is set. Time like %H:%M should be at the
2509 end of the second format. The custom formats are also honored by export
2510 commands, if custom time display is turned on at the time of export."
2511 :group 'org-time
2512 :type 'sexp)
2514 (defun org-time-stamp-format (&optional long inactive)
2515 "Get the right format for a time string."
2516 (let ((f (if long (cdr org-time-stamp-formats)
2517 (car org-time-stamp-formats))))
2518 (if inactive
2519 (concat "[" (substring f 1 -1) "]")
2520 f)))
2522 (defcustom org-time-clocksum-format "%d:%02d"
2523 "The format string used when creating CLOCKSUM lines.
2524 This is also used when org-mode generates a time duration."
2525 :group 'org-time
2526 :type 'string)
2528 (defcustom org-time-clocksum-use-fractional nil
2529 "If non-nil, \\[org-clock-display] uses fractional times.
2530 org-mode generates a time duration."
2531 :group 'org-time
2532 :type 'boolean)
2534 (defcustom org-time-clocksum-fractional-format "%.2f"
2535 "The format string used when creating CLOCKSUM lines, or when
2536 org-mode generates a time duration."
2537 :group 'org-time
2538 :type 'string)
2540 (defcustom org-deadline-warning-days 14
2541 "No. of days before expiration during which a deadline becomes active.
2542 This variable governs the display in sparse trees and in the agenda.
2543 When 0 or negative, it means use this number (the absolute value of it)
2544 even if a deadline has a different individual lead time specified.
2546 Custom commands can set this variable in the options section."
2547 :group 'org-time
2548 :group 'org-agenda-daily/weekly
2549 :type 'integer)
2551 (defcustom org-read-date-prefer-future t
2552 "Non-nil means assume future for incomplete date input from user.
2553 This affects the following situations:
2554 1. The user gives a month but not a year.
2555 For example, if it is April and you enter \"feb 2\", this will be read
2556 as Feb 2, *next* year. \"May 5\", however, will be this year.
2557 2. The user gives a day, but no month.
2558 For example, if today is the 15th, and you enter \"3\", Org-mode will
2559 read this as the third of *next* month. However, if you enter \"17\",
2560 it will be considered as *this* month.
2562 If you set this variable to the symbol `time', then also the following
2563 will work:
2565 3. If the user gives a time, but no day. If the time is before now,
2566 to will be interpreted as tomorrow.
2568 Currently none of this works for ISO week specifications.
2570 When this option is nil, the current day, month and year will always be
2571 used as defaults."
2572 :group 'org-time
2573 :type '(choice
2574 (const :tag "Never" nil)
2575 (const :tag "Check month and day" t)
2576 (const :tag "Check month, day, and time" time)))
2578 (defcustom org-read-date-display-live t
2579 "Non-nil means display current interpretation of date prompt live.
2580 This display will be in an overlay, in the minibuffer."
2581 :group 'org-time
2582 :type 'boolean)
2584 (defcustom org-read-date-popup-calendar t
2585 "Non-nil means pop up a calendar when prompting for a date.
2586 In the calendar, the date can be selected with mouse-1. However, the
2587 minibuffer will also be active, and you can simply enter the date as well.
2588 When nil, only the minibuffer will be available."
2589 :group 'org-time
2590 :type 'boolean)
2591 (if (fboundp 'defvaralias)
2592 (defvaralias 'org-popup-calendar-for-date-prompt
2593 'org-read-date-popup-calendar))
2595 (defcustom org-read-date-minibuffer-setup-hook nil
2596 "Hook to be used to set up keys for the date/time interface.
2597 Add key definitions to `minibuffer-local-map', which will be a temporary
2598 copy."
2599 :group 'org-time
2600 :type 'hook)
2602 (defcustom org-extend-today-until 0
2603 "The hour when your day really ends. Must be an integer.
2604 This has influence for the following applications:
2605 - When switching the agenda to \"today\". It it is still earlier than
2606 the time given here, the day recognized as TODAY is actually yesterday.
2607 - When a date is read from the user and it is still before the time given
2608 here, the current date and time will be assumed to be yesterday, 23:59.
2609 Also, timestamps inserted in remember templates follow this rule.
2611 IMPORTANT: This is a feature whose implementation is and likely will
2612 remain incomplete. Really, it is only here because past midnight seems to
2613 be the favorite working time of John Wiegley :-)"
2614 :group 'org-time
2615 :type 'integer)
2617 (defcustom org-edit-timestamp-down-means-later nil
2618 "Non-nil means S-down will increase the time in a time stamp.
2619 When nil, S-up will increase."
2620 :group 'org-time
2621 :type 'boolean)
2623 (defcustom org-calendar-follow-timestamp-change t
2624 "Non-nil means make the calendar window follow timestamp changes.
2625 When a timestamp is modified and the calendar window is visible, it will be
2626 moved to the new date."
2627 :group 'org-time
2628 :type 'boolean)
2630 (defgroup org-tags nil
2631 "Options concerning tags in Org-mode."
2632 :tag "Org Tags"
2633 :group 'org)
2635 (defcustom org-tag-alist nil
2636 "List of tags allowed in Org-mode files.
2637 When this list is nil, Org-mode will base TAG input on what is already in the
2638 buffer.
2639 The value of this variable is an alist, the car of each entry must be a
2640 keyword as a string, the cdr may be a character that is used to select
2641 that tag through the fast-tag-selection interface.
2642 See the manual for details."
2643 :group 'org-tags
2644 :type '(repeat
2645 (choice
2646 (cons (string :tag "Tag name")
2647 (character :tag "Access char"))
2648 (list :tag "Start radio group"
2649 (const :startgroup)
2650 (option (string :tag "Group description")))
2651 (list :tag "End radio group"
2652 (const :endgroup)
2653 (option (string :tag "Group description")))
2654 (const :tag "New line" (:newline)))))
2656 (defcustom org-tag-persistent-alist nil
2657 "List of tags that will always appear in all Org-mode files.
2658 This is in addition to any in buffer settings or customizations
2659 of `org-tag-alist'.
2660 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2661 The value of this variable is an alist, the car of each entry must be a
2662 keyword as a string, the cdr may be a character that is used to select
2663 that tag through the fast-tag-selection interface.
2664 See the manual for details.
2665 To disable these tags on a per-file basis, insert anywhere in the file:
2666 #+STARTUP: noptag"
2667 :group 'org-tags
2668 :type '(repeat
2669 (choice
2670 (cons (string :tag "Tag name")
2671 (character :tag "Access char"))
2672 (const :tag "Start radio group" (:startgroup))
2673 (const :tag "End radio group" (:endgroup))
2674 (const :tag "New line" (:newline)))))
2676 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2677 "If non-nil, always offer completion for all tags of all agenda files.
2678 Instead of customizing this variable directly, you might want to
2679 set it locally for remember buffers, because there no list of
2680 tags in that file can be created dynamically (there are none).
2682 (add-hook 'org-remember-mode-hook
2683 (lambda ()
2684 (set (make-local-variable
2685 'org-complete-tags-always-offer-all-agenda-tags)
2686 t)))"
2687 :group 'org-tags
2688 :type 'boolean)
2690 (defvar org-file-tags nil
2691 "List of tags that can be inherited by all entries in the file.
2692 The tags will be inherited if the variable `org-use-tag-inheritance'
2693 says they should be.
2694 This variable is populated from #+FILETAGS lines.")
2696 (defcustom org-use-fast-tag-selection 'auto
2697 "Non-nil means use fast tag selection scheme.
2698 This is a special interface to select and deselect tags with single keys.
2699 When nil, fast selection is never used.
2700 When the symbol `auto', fast selection is used if and only if selection
2701 characters for tags have been configured, either through the variable
2702 `org-tag-alist' or through a #+TAGS line in the buffer.
2703 When t, fast selection is always used and selection keys are assigned
2704 automatically if necessary."
2705 :group 'org-tags
2706 :type '(choice
2707 (const :tag "Always" t)
2708 (const :tag "Never" nil)
2709 (const :tag "When selection characters are configured" 'auto)))
2711 (defcustom org-fast-tag-selection-single-key nil
2712 "Non-nil means fast tag selection exits after first change.
2713 When nil, you have to press RET to exit it.
2714 During fast tag selection, you can toggle this flag with `C-c'.
2715 This variable can also have the value `expert'. In this case, the window
2716 displaying the tags menu is not even shown, until you press C-c again."
2717 :group 'org-tags
2718 :type '(choice
2719 (const :tag "No" nil)
2720 (const :tag "Yes" t)
2721 (const :tag "Expert" expert)))
2723 (defvar org-fast-tag-selection-include-todo nil
2724 "Non-nil means fast tags selection interface will also offer TODO states.
2725 This is an undocumented feature, you should not rely on it.")
2727 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2728 "The column to which tags should be indented in a headline.
2729 If this number is positive, it specifies the column. If it is negative,
2730 it means that the tags should be flushright to that column. For example,
2731 -80 works well for a normal 80 character screen."
2732 :group 'org-tags
2733 :type 'integer)
2735 (defcustom org-auto-align-tags t
2736 "Non-nil means realign tags after pro/demotion of TODO state change.
2737 These operations change the length of a headline and therefore shift
2738 the tags around. With this options turned on, after each such operation
2739 the tags are again aligned to `org-tags-column'."
2740 :group 'org-tags
2741 :type 'boolean)
2743 (defcustom org-use-tag-inheritance t
2744 "Non-nil means tags in levels apply also for sublevels.
2745 When nil, only the tags directly given in a specific line apply there.
2746 This may also be a list of tags that should be inherited, or a regexp that
2747 matches tags that should be inherited. Additional control is possible
2748 with the variable `org-tags-exclude-from-inheritance' which gives an
2749 explicit list of tags to be excluded from inheritance., even if the value of
2750 `org-use-tag-inheritance' would select it for inheritance.
2752 If this option is t, a match early-on in a tree can lead to a large
2753 number of matches in the subtree when constructing the agenda or creating
2754 a sparse tree. If you only want to see the first match in a tree during
2755 a search, check out the variable `org-tags-match-list-sublevels'."
2756 :group 'org-tags
2757 :type '(choice
2758 (const :tag "Not" nil)
2759 (const :tag "Always" t)
2760 (repeat :tag "Specific tags" (string :tag "Tag"))
2761 (regexp :tag "Tags matched by regexp")))
2763 (defcustom org-tags-exclude-from-inheritance nil
2764 "List of tags that should never be inherited.
2765 This is a way to exclude a few tags from inheritance. For way to do
2766 the opposite, to actively allow inheritance for selected tags,
2767 see the variable `org-use-tag-inheritance'."
2768 :group 'org-tags
2769 :type '(repeat (string :tag "Tag")))
2771 (defun org-tag-inherit-p (tag)
2772 "Check if TAG is one that should be inherited."
2773 (cond
2774 ((member tag org-tags-exclude-from-inheritance) nil)
2775 ((eq org-use-tag-inheritance t) t)
2776 ((not org-use-tag-inheritance) nil)
2777 ((stringp org-use-tag-inheritance)
2778 (string-match org-use-tag-inheritance tag))
2779 ((listp org-use-tag-inheritance)
2780 (member tag org-use-tag-inheritance))
2781 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2783 (defcustom org-tags-match-list-sublevels t
2784 "Non-nil means list also sublevels of headlines matching a search.
2785 This variable applies to tags/property searches, and also to stuck
2786 projects because this search is based on a tags match as well.
2788 When set to the symbol `indented', sublevels are indented with
2789 leading dots.
2791 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2792 the sublevels of a headline matching a tag search often also match
2793 the same search. Listing all of them can create very long lists.
2794 Setting this variable to nil causes subtrees of a match to be skipped.
2796 This variable is semi-obsolete and probably should always be true. It
2797 is better to limit inheritance to certain tags using the variables
2798 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2799 :group 'org-tags
2800 :type '(choice
2801 (const :tag "No, don't list them" nil)
2802 (const :tag "Yes, do list them" t)
2803 (const :tag "List them, indented with leading dots" indented)))
2805 (defcustom org-tags-sort-function nil
2806 "When set, tags are sorted using this function as a comparator."
2807 :group 'org-tags
2808 :type '(choice
2809 (const :tag "No sorting" nil)
2810 (const :tag "Alphabetical" string<)
2811 (const :tag "Reverse alphabetical" string>)
2812 (function :tag "Custom function" nil)))
2814 (defvar org-tags-history nil
2815 "History of minibuffer reads for tags.")
2816 (defvar org-last-tags-completion-table nil
2817 "The last used completion table for tags.")
2818 (defvar org-after-tags-change-hook nil
2819 "Hook that is run after the tags in a line have changed.")
2821 (defgroup org-properties nil
2822 "Options concerning properties in Org-mode."
2823 :tag "Org Properties"
2824 :group 'org)
2826 (defcustom org-property-format "%-10s %s"
2827 "How property key/value pairs should be formatted by `indent-line'.
2828 When `indent-line' hits a property definition, it will format the line
2829 according to this format, mainly to make sure that the values are
2830 lined-up with respect to each other."
2831 :group 'org-properties
2832 :type 'string)
2834 (defcustom org-use-property-inheritance nil
2835 "Non-nil means properties apply also for sublevels.
2837 This setting is chiefly used during property searches. Turning it on can
2838 cause significant overhead when doing a search, which is why it is not
2839 on by default.
2841 When nil, only the properties directly given in the current entry count.
2842 When t, every property is inherited. The value may also be a list of
2843 properties that should have inheritance, or a regular expression matching
2844 properties that should be inherited.
2846 However, note that some special properties use inheritance under special
2847 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2848 and the properties ending in \"_ALL\" when they are used as descriptor
2849 for valid values of a property.
2851 Note for programmers:
2852 When querying an entry with `org-entry-get', you can control if inheritance
2853 should be used. By default, `org-entry-get' looks only at the local
2854 properties. You can request inheritance by setting the inherit argument
2855 to t (to force inheritance) or to `selective' (to respect the setting
2856 in this variable)."
2857 :group 'org-properties
2858 :type '(choice
2859 (const :tag "Not" nil)
2860 (const :tag "Always" t)
2861 (repeat :tag "Specific properties" (string :tag "Property"))
2862 (regexp :tag "Properties matched by regexp")))
2864 (defun org-property-inherit-p (property)
2865 "Check if PROPERTY is one that should be inherited."
2866 (cond
2867 ((eq org-use-property-inheritance t) t)
2868 ((not org-use-property-inheritance) nil)
2869 ((stringp org-use-property-inheritance)
2870 (string-match org-use-property-inheritance property))
2871 ((listp org-use-property-inheritance)
2872 (member property org-use-property-inheritance))
2873 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2875 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2876 "The default column format, if no other format has been defined.
2877 This variable can be set on the per-file basis by inserting a line
2879 #+COLUMNS: %25ITEM ....."
2880 :group 'org-properties
2881 :type 'string)
2883 (defcustom org-columns-ellipses ".."
2884 "The ellipses to be used when a field in column view is truncated.
2885 When this is the empty string, as many characters as possible are shown,
2886 but then there will be no visual indication that the field has been truncated.
2887 When this is a string of length N, the last N characters of a truncated
2888 field are replaced by this string. If the column is narrower than the
2889 ellipses string, only part of the ellipses string will be shown."
2890 :group 'org-properties
2891 :type 'string)
2893 (defcustom org-columns-modify-value-for-display-function nil
2894 "Function that modifies values for display in column view.
2895 For example, it can be used to cut out a certain part from a time stamp.
2896 The function must take 2 arguments:
2898 column-title The title of the column (*not* the property name)
2899 value The value that should be modified.
2901 The function should return the value that should be displayed,
2902 or nil if the normal value should be used."
2903 :group 'org-properties
2904 :type 'function)
2906 (defcustom org-effort-property "Effort"
2907 "The property that is being used to keep track of effort estimates.
2908 Effort estimates given in this property need to have the format H:MM."
2909 :group 'org-properties
2910 :group 'org-progress
2911 :type '(string :tag "Property"))
2913 (defconst org-global-properties-fixed
2914 '(("VISIBILITY_ALL" . "folded children content all")
2915 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
2916 "List of property/value pairs that can be inherited by any entry.
2918 These are fixed values, for the preset properties. The user variable
2919 that can be used to add to this list is `org-global-properties'.
2921 The entries in this list are cons cells where the car is a property
2922 name and cdr is a string with the value. If the value represents
2923 multiple items like an \"_ALL\" property, separate the items by
2924 spaces.")
2926 (defcustom org-global-properties nil
2927 "List of property/value pairs that can be inherited by any entry.
2929 This list will be combined with the constant `org-global-properties-fixed'.
2931 The entries in this list are cons cells where the car is a property
2932 name and cdr is a string with the value.
2934 You can set buffer-local values for the same purpose in the variable
2935 `org-file-properties' this by adding lines like
2937 #+PROPERTY: NAME VALUE"
2938 :group 'org-properties
2939 :type '(repeat
2940 (cons (string :tag "Property")
2941 (string :tag "Value"))))
2943 (defvar org-file-properties nil
2944 "List of property/value pairs that can be inherited by any entry.
2945 Valid for the current buffer.
2946 This variable is populated from #+PROPERTY lines.")
2947 (make-variable-buffer-local 'org-file-properties)
2949 (defgroup org-agenda nil
2950 "Options concerning agenda views in Org-mode."
2951 :tag "Org Agenda"
2952 :group 'org)
2954 (defvar org-category nil
2955 "Variable used by org files to set a category for agenda display.
2956 Such files should use a file variable to set it, for example
2958 # -*- mode: org; org-category: \"ELisp\"
2960 or contain a special line
2962 #+CATEGORY: ELisp
2964 If the file does not specify a category, then file's base name
2965 is used instead.")
2966 (make-variable-buffer-local 'org-category)
2967 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2969 (defcustom org-agenda-files nil
2970 "The files to be used for agenda display.
2971 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2972 \\[org-remove-file]. You can also use customize to edit the list.
2974 If an entry is a directory, all files in that directory that are matched by
2975 `org-agenda-file-regexp' will be part of the file list.
2977 If the value of the variable is not a list but a single file name, then
2978 the list of agenda files is actually stored and maintained in that file, one
2979 agenda file per line. In this file paths can be given relative to
2980 `org-directory'. Tilde expansion and environment variable substitution
2981 are also made."
2982 :group 'org-agenda
2983 :type '(choice
2984 (repeat :tag "List of files and directories" file)
2985 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2987 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2988 "Regular expression to match files for `org-agenda-files'.
2989 If any element in the list in that variable contains a directory instead
2990 of a normal file, all files in that directory that are matched by this
2991 regular expression will be included."
2992 :group 'org-agenda
2993 :type 'regexp)
2995 (defcustom org-agenda-text-search-extra-files nil
2996 "List of extra files to be searched by text search commands.
2997 These files will be search in addition to the agenda files by the
2998 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2999 Note that these files will only be searched for text search commands,
3000 not for the other agenda views like todo lists, tag searches or the weekly
3001 agenda. This variable is intended to list notes and possibly archive files
3002 that should also be searched by these two commands.
3003 In fact, if the first element in the list is the symbol `agenda-archives',
3004 than all archive files of all agenda files will be added to the search
3005 scope."
3006 :group 'org-agenda
3007 :type '(set :greedy t
3008 (const :tag "Agenda Archives" agenda-archives)
3009 (repeat :inline t (file))))
3011 (if (fboundp 'defvaralias)
3012 (defvaralias 'org-agenda-multi-occur-extra-files
3013 'org-agenda-text-search-extra-files))
3015 (defcustom org-agenda-skip-unavailable-files nil
3016 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3017 A nil value means to remove them, after a query, from the list."
3018 :group 'org-agenda
3019 :type 'boolean)
3021 (defcustom org-calendar-to-agenda-key [?c]
3022 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3023 The command `org-calendar-goto-agenda' will be bound to this key. The
3024 default is the character `c' because then `c' can be used to switch back and
3025 forth between agenda and calendar."
3026 :group 'org-agenda
3027 :type 'sexp)
3029 (defcustom org-calendar-agenda-action-key [?k]
3030 "The key to be installed in `calendar-mode-map' for agenda-action.
3031 The command `org-agenda-action' will be bound to this key. The
3032 default is the character `k' because we use the same key in the agenda."
3033 :group 'org-agenda
3034 :type 'sexp)
3036 (defcustom org-calendar-insert-diary-entry-key [?i]
3037 "The key to be installed in `calendar-mode-map' for adding diary entries.
3038 This option is irrelevant until `org-agenda-diary-file' has been configured
3039 to point to an Org-mode file. When that is the case, the command
3040 `org-agenda-diary-entry' will be bound to the key given here, by default
3041 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3042 if you want to continue doing this, you need to change this to a different
3043 key."
3044 :group 'org-agenda
3045 :type 'sexp)
3047 (defcustom org-agenda-diary-file 'diary-file
3048 "File to which to add new entries with the `i' key in agenda and calendar.
3049 When this is the symbol `diary-file', the functionality in the Emacs
3050 calendar will be used to add entries to the `diary-file'. But when this
3051 points to a file, `org-agenda-diary-entry' will be used instead."
3052 :group 'org-agenda
3053 :type '(choice
3054 (const :tag "The standard Emacs diary file" diary-file)
3055 (file :tag "Special Org file diary entries")))
3057 (eval-after-load "calendar"
3058 '(progn
3059 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3060 'org-calendar-goto-agenda)
3061 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3062 'org-agenda-action)
3063 (add-hook 'calendar-mode-hook
3064 (lambda ()
3065 (unless (eq org-agenda-diary-file 'diary-file)
3066 (define-key calendar-mode-map
3067 org-calendar-insert-diary-entry-key
3068 'org-agenda-diary-entry))))))
3070 (defgroup org-latex nil
3071 "Options for embedding LaTeX code into Org-mode."
3072 :tag "Org LaTeX"
3073 :group 'org)
3075 (defcustom org-format-latex-options
3076 '(:foreground default :background default :scale 1.0
3077 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
3078 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3079 "Options for creating images from LaTeX fragments.
3080 This is a property list with the following properties:
3081 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3082 `default' means use the foreground of the default face.
3083 :background the background color, or \"Transparent\".
3084 `default' means use the background of the default face.
3085 :scale a scaling factor for the size of the images.
3086 :html-foreground, :html-background, :html-scale
3087 the same numbers for HTML export.
3088 :matchers a list indicating which matchers should be used to
3089 find LaTeX fragments. Valid members of this list are:
3090 \"begin\" find environments
3091 \"$1\" find single characters surrounded by $.$
3092 \"$\" find math expressions surrounded by $...$
3093 \"$$\" find math expressions surrounded by $$....$$
3094 \"\\(\" find math expressions surrounded by \\(...\\)
3095 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3096 :group 'org-latex
3097 :type 'plist)
3099 (defcustom org-format-latex-signal-error t
3100 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3101 When nil, just push out a message."
3102 :group 'org-latex
3103 :type 'boolean)
3105 (defcustom org-format-latex-header "\\documentclass{article}
3106 \\usepackage[usenames]{color}
3107 \\usepackage{amsmath}
3108 \\usepackage[mathscr]{eucal}
3109 \\pagestyle{empty} % do not remove
3110 \[PACKAGES]
3111 \[DEFAULT-PACKAGES]
3112 % The settings below are copied from fullpage.sty
3113 \\setlength{\\textwidth}{\\paperwidth}
3114 \\addtolength{\\textwidth}{-3cm}
3115 \\setlength{\\oddsidemargin}{1.5cm}
3116 \\addtolength{\\oddsidemargin}{-2.54cm}
3117 \\setlength{\\evensidemargin}{\\oddsidemargin}
3118 \\setlength{\\textheight}{\\paperheight}
3119 \\addtolength{\\textheight}{-\\headheight}
3120 \\addtolength{\\textheight}{-\\headsep}
3121 \\addtolength{\\textheight}{-\\footskip}
3122 \\addtolength{\\textheight}{-3cm}
3123 \\setlength{\\topmargin}{1.5cm}
3124 \\addtolength{\\topmargin}{-2.54cm}"
3125 "The document header used for processing LaTeX fragments.
3126 It is imperative that this header make sure that no page number
3127 appears on the page. The package defined in the variables
3128 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3129 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3130 will be appended."
3131 :group 'org-latex
3132 :type 'string)
3134 (defvar org-format-latex-header-extra nil)
3136 (defun org-set-packages-alist (var val)
3137 "Set the packages alist and make sure it has 3 elements per entry."
3138 (set var (mapcar (lambda (x)
3139 (if (and (consp x) (= (length x) 2))
3140 (list (car x) (nth 1 x) t)
3142 val)))
3144 (defun org-get-packages-alist (var)
3146 "Get the packages alist and make sure it has 3 elements per entry."
3147 (mapcar (lambda (x)
3148 (if (and (consp x) (= (length x) 2))
3149 (list (car x) (nth 1 x) t)
3151 (default-value var)))
3153 ;; The following variables are defined here because is it also used
3154 ;; when formatting latex fragments. Originally it was part of the
3155 ;; LaTeX exporter, which is why the name includes "export".
3156 (defcustom org-export-latex-default-packages-alist
3157 '(("AUTO" "inputenc" t)
3158 ("T1" "fontenc" t)
3159 ("" "fixltx2e" nil)
3160 ("" "graphicx" t)
3161 ("" "longtable" nil)
3162 ("" "float" nil)
3163 ("" "wrapfig" nil)
3164 ("" "soul" t)
3165 ("" "t1enc" t)
3166 ("" "textcomp" t)
3167 ("" "marvosym" t)
3168 ("" "wasysym" t)
3169 ("" "latexsym" t)
3170 ("" "amssymb" t)
3171 ("" "hyperref" nil)
3172 "\\tolerance=1000"
3174 "Alist of default packages to be inserted in the header.
3175 Change this only if one of the packages here causes an incompatibility
3176 with another package you are using.
3177 The packages in this list are needed by one part or another of Org-mode
3178 to function properly.
3180 - inputenc, fontenc, t1enc: for basic font and character selection
3181 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3182 for interpreting the entities in `org-entities'. You can skip some of these
3183 packages if you don't use any of the symbols in it.
3184 - graphicx: for including images
3185 - float, wrapfig: for figure placement
3186 - longtable: for long tables
3187 - hyperref: for cross references
3189 Therefore you should not modify this variable unless you know what you
3190 are doing. The one reason to change it anyway is that you might be loading
3191 some other package that conflicts with one of the default packages.
3192 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3193 If SNIPPET-FLAG is t, the package also needs to be included when
3194 compiling LaTeX snippets into images for inclusion into HTML."
3195 :group 'org-export-latex
3196 :set 'org-set-packages-alist
3197 :get 'org-get-packages-alist
3198 :type '(repeat
3199 (choice
3200 (list :tag "options/package pair"
3201 (string :tag "options")
3202 (string :tag "package")
3203 (boolean :tag "Snippet"))
3204 (string :tag "A line of LaTeX"))))
3206 (defcustom org-export-latex-packages-alist nil
3207 "Alist of packages to be inserted in every LaTeX header.
3208 These will be inserted after `org-export-latex-default-packages-alist'.
3209 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3210 SNIPPET-FLAG, when t, indicates that this package is also needed when
3211 turning LaTeX snippets into images for inclusion into HTML.
3212 Make sure that you only list packages here which:
3213 - you want in every file
3214 - do not conflict with the default packages in
3215 `org-export-latex-default-packages-alist'
3216 - do not conflict with the setup in `org-format-latex-header'."
3217 :group 'org-export-latex
3218 :set 'org-set-packages-alist
3219 :get 'org-get-packages-alist
3220 :type '(repeat
3221 (choice
3222 (list :tag "options/package pair"
3223 (string :tag "options")
3224 (string :tag "package")
3225 (boolean :tag "Snippet"))
3226 (string :tag "A line of LaTeX"))))
3229 (defgroup org-appearance nil
3230 "Settings for Org-mode appearance."
3231 :tag "Org Appearance"
3232 :group 'org)
3234 (defcustom org-level-color-stars-only nil
3235 "Non-nil means fontify only the stars in each headline.
3236 When nil, the entire headline is fontified.
3237 Changing it requires restart of `font-lock-mode' to become effective
3238 also in regions already fontified."
3239 :group 'org-appearance
3240 :type 'boolean)
3242 (defcustom org-hide-leading-stars nil
3243 "Non-nil means hide the first N-1 stars in a headline.
3244 This works by using the face `org-hide' for these stars. This
3245 face is white for a light background, and black for a dark
3246 background. You may have to customize the face `org-hide' to
3247 make this work.
3248 Changing it requires restart of `font-lock-mode' to become effective
3249 also in regions already fontified.
3250 You may also set this on a per-file basis by adding one of the following
3251 lines to the buffer:
3253 #+STARTUP: hidestars
3254 #+STARTUP: showstars"
3255 :group 'org-appearance
3256 :type 'boolean)
3258 (defcustom org-hidden-keywords nil
3259 "List of keywords that should be hidden when typed in the org buffer.
3260 For example, add #+TITLE to this list in order to make the
3261 document title appear in the buffer without the initial #+TITLE:
3262 keyword."
3263 :group 'org-appearance
3264 :type '(set (const :tag "#+AUTHOR" author)
3265 (const :tag "#+DATE" date)
3266 (const :tag "#+EMAIL" email)
3267 (const :tag "#+TITLE" title)))
3269 (defcustom org-fontify-done-headline nil
3270 "Non-nil means change the face of a headline if it is marked DONE.
3271 Normally, only the TODO/DONE keyword indicates the state of a headline.
3272 When this is non-nil, the headline after the keyword is set to the
3273 `org-headline-done' as an additional indication."
3274 :group 'org-appearance
3275 :type 'boolean)
3277 (defcustom org-fontify-emphasized-text t
3278 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3279 Changing this variable requires a restart of Emacs to take effect."
3280 :group 'org-appearance
3281 :type 'boolean)
3283 (defcustom org-fontify-whole-heading-line nil
3284 "Non-nil means fontify the whole line for headings.
3285 This is useful when setting a background color for the
3286 org-level-* faces."
3287 :group 'org-appearance
3288 :type 'boolean)
3290 (defcustom org-highlight-latex-fragments-and-specials nil
3291 "Non-nil means fontify what is treated specially by the exporters."
3292 :group 'org-appearance
3293 :type 'boolean)
3295 (defcustom org-hide-emphasis-markers nil
3296 "Non-nil mean font-lock should hide the emphasis marker characters."
3297 :group 'org-appearance
3298 :type 'boolean)
3300 (defcustom org-pretty-entities nil
3301 "Non-nil means show entities as UTF8 characters.
3302 When nil, the \\name form remains in the buffer."
3303 :group 'org-appearance
3304 :type 'boolean)
3306 (defcustom org-pretty-entities-include-sub-superscripts t
3307 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3308 :group 'org-appearance
3309 :type 'boolean)
3311 (defvar org-emph-re nil
3312 "Regular expression for matching emphasis.
3313 After a match, the match groups contain these elements:
3314 1 The character before the proper match, or empty at beginning of line
3315 2 The proper match, including the leading and trailing markers
3316 3 The leading marker like * or /, indicating the type of highlighting
3317 4 The text between the emphasis markers, not including the markers
3318 5 The character after the match, empty at the end of a line")
3319 (defvar org-verbatim-re nil
3320 "Regular expression for matching verbatim text.")
3321 (defvar org-emphasis-regexp-components) ; defined just below
3322 (defvar org-emphasis-alist) ; defined just below
3323 (defun org-set-emph-re (var val)
3324 "Set variable and compute the emphasis regular expression."
3325 (set var val)
3326 (when (and (boundp 'org-emphasis-alist)
3327 (boundp 'org-emphasis-regexp-components)
3328 org-emphasis-alist org-emphasis-regexp-components)
3329 (let* ((e org-emphasis-regexp-components)
3330 (pre (car e))
3331 (post (nth 1 e))
3332 (border (nth 2 e))
3333 (body (nth 3 e))
3334 (nl (nth 4 e))
3335 (body1 (concat body "*?"))
3336 (markers (mapconcat 'car org-emphasis-alist ""))
3337 (vmarkers (mapconcat
3338 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3339 org-emphasis-alist "")))
3340 ;; make sure special characters appear at the right position in the class
3341 (if (string-match "\\^" markers)
3342 (setq markers (concat (replace-match "" t t markers) "^")))
3343 (if (string-match "-" markers)
3344 (setq markers (concat (replace-match "" t t markers) "-")))
3345 (if (string-match "\\^" vmarkers)
3346 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3347 (if (string-match "-" vmarkers)
3348 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3349 (if (> nl 0)
3350 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3351 (int-to-string nl) "\\}")))
3352 ;; Make the regexp
3353 (setq org-emph-re
3354 (concat "\\([" pre "]\\|^\\)"
3355 "\\("
3356 "\\([" markers "]\\)"
3357 "\\("
3358 "[^" border "]\\|"
3359 "[^" border "]"
3360 body1
3361 "[^" border "]"
3362 "\\)"
3363 "\\3\\)"
3364 "\\([" post "]\\|$\\)"))
3365 (setq org-verbatim-re
3366 (concat "\\([" pre "]\\|^\\)"
3367 "\\("
3368 "\\([" vmarkers "]\\)"
3369 "\\("
3370 "[^" border "]\\|"
3371 "[^" border "]"
3372 body1
3373 "[^" border "]"
3374 "\\)"
3375 "\\3\\)"
3376 "\\([" post "]\\|$\\)")))))
3378 (defcustom org-emphasis-regexp-components
3379 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3380 "Components used to build the regular expression for emphasis.
3381 This is a list with 6 entries. Terminology: In an emphasis string
3382 like \" *strong word* \", we call the initial space PREMATCH, the final
3383 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3384 and \"trong wor\" is the body. The different components in this variable
3385 specify what is allowed/forbidden in each part:
3387 pre Chars allowed as prematch. Beginning of line will be allowed too.
3388 post Chars allowed as postmatch. End of line will be allowed too.
3389 border The chars *forbidden* as border characters.
3390 body-regexp A regexp like \".\" to match a body character. Don't use
3391 non-shy groups here, and don't allow newline here.
3392 newline The maximum number of newlines allowed in an emphasis exp.
3394 Use customize to modify this, or restart Emacs after changing it."
3395 :group 'org-appearance
3396 :set 'org-set-emph-re
3397 :type '(list
3398 (sexp :tag "Allowed chars in pre ")
3399 (sexp :tag "Allowed chars in post ")
3400 (sexp :tag "Forbidden chars in border ")
3401 (sexp :tag "Regexp for body ")
3402 (integer :tag "number of newlines allowed")
3403 (option (boolean :tag "Please ignore this button"))))
3405 (defcustom org-emphasis-alist
3406 `(("*" bold "<b>" "</b>")
3407 ("/" italic "<i>" "</i>")
3408 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3409 ("=" org-code "<code>" "</code>" verbatim)
3410 ("~" org-verbatim "<code>" "</code>" verbatim)
3411 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3412 "<del>" "</del>")
3414 "Special syntax for emphasized text.
3415 Text starting and ending with a special character will be emphasized, for
3416 example *bold*, _underlined_ and /italic/. This variable sets the marker
3417 characters, the face to be used by font-lock for highlighting in Org-mode
3418 Emacs buffers, and the HTML tags to be used for this.
3419 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3420 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3421 Use customize to modify this, or restart Emacs after changing it."
3422 :group 'org-appearance
3423 :set 'org-set-emph-re
3424 :type '(repeat
3425 (list
3426 (string :tag "Marker character")
3427 (choice
3428 (face :tag "Font-lock-face")
3429 (plist :tag "Face property list"))
3430 (string :tag "HTML start tag")
3431 (string :tag "HTML end tag")
3432 (option (const verbatim)))))
3434 (defvar org-protecting-blocks
3435 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3436 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3437 This is needed for font-lock setup.")
3439 ;;; Miscellaneous options
3441 (defgroup org-completion nil
3442 "Completion in Org-mode."
3443 :tag "Org Completion"
3444 :group 'org)
3446 (defcustom org-completion-use-ido nil
3447 "Non-nil means use ido completion wherever possible.
3448 Note that `ido-mode' must be active for this variable to be relevant.
3449 If you decide to turn this variable on, you might well want to turn off
3450 `org-outline-path-complete-in-steps'.
3451 See also `org-completion-use-iswitchb'."
3452 :group 'org-completion
3453 :type 'boolean)
3455 (defcustom org-completion-use-iswitchb nil
3456 "Non-nil means use iswitchb completion wherever possible.
3457 Note that `iswitchb-mode' must be active for this variable to be relevant.
3458 If you decide to turn this variable on, you might well want to turn off
3459 `org-outline-path-complete-in-steps'.
3460 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3461 :group 'org-completion
3462 :type 'boolean)
3464 (defcustom org-completion-fallback-command 'hippie-expand
3465 "The expansion command called by \\[org-complete] in normal context.
3466 Normal means no org-mode-specific context."
3467 :group 'org-completion
3468 :type 'function)
3470 ;;; Functions and variables from their packages
3471 ;; Declared here to avoid compiler warnings
3473 ;; XEmacs only
3474 (defvar outline-mode-menu-heading)
3475 (defvar outline-mode-menu-show)
3476 (defvar outline-mode-menu-hide)
3477 (defvar zmacs-regions) ; XEmacs regions
3479 ;; Emacs only
3480 (defvar mark-active)
3482 ;; Various packages
3483 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3484 (declare-function calendar-forward-day "cal-move" (arg))
3485 (declare-function calendar-goto-date "cal-move" (date))
3486 (declare-function calendar-goto-today "cal-move" ())
3487 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3488 (defvar calc-embedded-close-formula)
3489 (defvar calc-embedded-open-formula)
3490 (declare-function cdlatex-tab "ext:cdlatex" ())
3491 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3492 (defvar font-lock-unfontify-region-function)
3493 (declare-function iswitchb-read-buffer "iswitchb"
3494 (prompt &optional default require-match start matches-set))
3495 (defvar iswitchb-temp-buflist)
3496 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3497 (defvar org-agenda-tags-todo-honor-ignore-options)
3498 (declare-function org-agenda-skip "org-agenda" ())
3499 (declare-function
3500 org-format-agenda-item "org-agenda"
3501 (extra txt &optional category tags dotime noprefix remove-re habitp))
3502 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3503 (declare-function org-agenda-change-all-lines "org-agenda"
3504 (newhead hdmarker &optional fixface just-this))
3505 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3506 (declare-function org-agenda-maybe-redo "org-agenda" ())
3507 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3508 (beg end))
3509 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3510 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3511 "org-agenda" (&optional end))
3512 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3513 (declare-function org-indent-mode "org-indent" (&optional arg))
3514 (declare-function parse-time-string "parse-time" (string))
3515 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3516 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3517 (defvar remember-data-file)
3518 (defvar texmathp-why)
3519 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3520 (declare-function table--at-cell-p "table" (position &optional object at-column))
3522 (defvar w3m-current-url)
3523 (defvar w3m-current-title)
3525 (defvar org-latex-regexps)
3527 ;;; Autoload and prepare some org modules
3529 ;; Some table stuff that needs to be defined here, because it is used
3530 ;; by the functions setting up org-mode or checking for table context.
3532 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3533 "Detect an org-type or table-type table.")
3534 (defconst org-table-line-regexp "^[ \t]*|"
3535 "Detect an org-type table line.")
3536 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3537 "Detect an org-type table line.")
3538 (defconst org-table-hline-regexp "^[ \t]*|-"
3539 "Detect an org-type table hline.")
3540 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3541 "Detect a table-type table hline.")
3542 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3543 "Detect the first line outside a table when searching from within it.
3544 This works for both table types.")
3546 ;; Autoload the functions in org-table.el that are needed by functions here.
3548 (eval-and-compile
3549 (org-autoload "org-table"
3550 '(org-table-align org-table-begin org-table-blank-field
3551 org-table-convert org-table-convert-region org-table-copy-down
3552 org-table-copy-region org-table-create
3553 org-table-create-or-convert-from-region
3554 org-table-create-with-table.el org-table-current-dline
3555 org-table-cut-region org-table-delete-column org-table-edit-field
3556 org-table-edit-formulas org-table-end org-table-eval-formula
3557 org-table-export org-table-field-info
3558 org-table-get-stored-formulas org-table-goto-column
3559 org-table-hline-and-move org-table-import org-table-insert-column
3560 org-table-insert-hline org-table-insert-row org-table-iterate
3561 org-table-justify-field-maybe org-table-kill-row
3562 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3563 org-table-move-column org-table-move-column-left
3564 org-table-move-column-right org-table-move-row
3565 org-table-move-row-down org-table-move-row-up
3566 org-table-next-field org-table-next-row org-table-paste-rectangle
3567 org-table-previous-field org-table-recalculate
3568 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3569 org-table-toggle-coordinate-overlays
3570 org-table-toggle-formula-debugger org-table-wrap-region
3571 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3572 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3573 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3575 (defun org-at-table-p (&optional table-type)
3576 "Return t if the cursor is inside an org-type table.
3577 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3578 (if org-enable-table-editor
3579 (save-excursion
3580 (beginning-of-line 1)
3581 (looking-at (if table-type org-table-any-line-regexp
3582 org-table-line-regexp)))
3583 nil))
3584 (defsubst org-table-p () (org-at-table-p))
3586 (defun org-at-table.el-p ()
3587 "Return t if and only if we are at a table.el table."
3588 (and (org-at-table-p 'any)
3589 (save-excursion
3590 (goto-char (org-table-begin 'any))
3591 (looking-at org-table1-hline-regexp))))
3592 (defun org-table-recognize-table.el ()
3593 "If there is a table.el table nearby, recognize it and move into it."
3594 (if org-table-tab-recognizes-table.el
3595 (if (org-at-table.el-p)
3596 (progn
3597 (beginning-of-line 1)
3598 (if (looking-at org-table-dataline-regexp)
3600 (if (looking-at org-table1-hline-regexp)
3601 (progn
3602 (beginning-of-line 2)
3603 (if (looking-at org-table-any-border-regexp)
3604 (beginning-of-line -1)))))
3605 (if (re-search-forward "|" (org-table-end t) t)
3606 (progn
3607 (require 'table)
3608 (if (table--at-cell-p (point))
3610 (message "recognizing table.el table...")
3611 (table-recognize-table)
3612 (message "recognizing table.el table...done")))
3613 (error "This should not happen"))
3615 nil)
3616 nil))
3618 (defun org-at-table-hline-p ()
3619 "Return t if the cursor is inside a hline in a table."
3620 (if org-enable-table-editor
3621 (save-excursion
3622 (beginning-of-line 1)
3623 (looking-at org-table-hline-regexp))
3624 nil))
3626 (defvar org-table-clean-did-remove-column nil)
3628 (defun org-table-map-tables (function &optional quietly)
3629 "Apply FUNCTION to the start of all tables in the buffer."
3630 (save-excursion
3631 (save-restriction
3632 (widen)
3633 (goto-char (point-min))
3634 (while (re-search-forward org-table-any-line-regexp nil t)
3635 (unless quietly
3636 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3637 (beginning-of-line 1)
3638 (when (looking-at org-table-line-regexp)
3639 (save-excursion (funcall function))
3640 (or (looking-at org-table-line-regexp)
3641 (forward-char 1)))
3642 (re-search-forward org-table-any-border-regexp nil 1))))
3643 (unless quietly (message "Mapping tables: done")))
3645 ;; Declare and autoload functions from org-exp.el & Co
3647 (declare-function org-default-export-plist "org-exp")
3648 (declare-function org-infile-export-plist "org-exp")
3649 (declare-function org-get-current-options "org-exp")
3650 (eval-and-compile
3651 (org-autoload "org-exp"
3652 '(org-export org-export-visible
3653 org-insert-export-options-template
3654 org-table-clean-before-export))
3655 (org-autoload "org-ascii"
3656 '(org-export-as-ascii org-export-ascii-preprocess
3657 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3658 org-export-region-as-ascii))
3659 (org-autoload "org-latex"
3660 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3661 org-replace-region-by-latex org-export-region-as-latex
3662 org-export-as-latex org-export-as-pdf
3663 org-export-as-pdf-and-open))
3664 (org-autoload "org-html"
3665 '(org-export-as-html-and-open
3666 org-export-as-html-batch org-export-as-html-to-buffer
3667 org-replace-region-by-html org-export-region-as-html
3668 org-export-as-html))
3669 (org-autoload "org-docbook"
3670 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3671 org-replace-region-by-docbook org-export-region-as-docbook
3672 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3673 org-export-as-docbook))
3674 (org-autoload "org-icalendar"
3675 '(org-export-icalendar-this-file
3676 org-export-icalendar-all-agenda-files
3677 org-export-icalendar-combine-agenda-files))
3678 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3679 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3681 ;; Declare and autoload functions from org-agenda.el
3683 (eval-and-compile
3684 (org-autoload "org-agenda"
3685 '(org-agenda org-agenda-list org-search-view
3686 org-todo-list org-tags-view org-agenda-list-stuck-projects
3687 org-diary org-agenda-to-appt
3688 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3690 ;; Autoload org-remember
3692 (eval-and-compile
3693 (org-autoload "org-remember"
3694 '(org-remember-insinuate org-remember-annotation
3695 org-remember-apply-template org-remember org-remember-handler)))
3697 (eval-and-compile
3698 (org-autoload "org-capture"
3699 '(org-capture org-capture-insert-template-here
3700 org-capture-import-remember-templates)))
3702 ;; Autoload org-clock.el
3705 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3706 (beg end))
3707 (declare-function org-clock-update-mode-line "org-clock" ())
3708 (declare-function org-resolve-clocks "org-clock"
3709 (&optional also-non-dangling-p prompt last-valid))
3710 (defvar org-clock-start-time)
3711 (defvar org-clock-marker (make-marker)
3712 "Marker recording the last clock-in.")
3713 (defvar org-clock-hd-marker (make-marker)
3714 "Marker recording the last clock-in, but the headline position.")
3715 (defvar org-clock-heading ""
3716 "The heading of the current clock entry.")
3717 (defun org-clock-is-active ()
3718 "Return non-nil if clock is currently running.
3719 The return value is actually the clock marker."
3720 (marker-buffer org-clock-marker))
3722 (eval-and-compile
3723 (org-autoload
3724 "org-clock"
3725 '(org-clock-in org-clock-out org-clock-cancel
3726 org-clock-goto org-clock-sum org-clock-display
3727 org-clock-remove-overlays org-clock-report
3728 org-clocktable-shift org-dblock-write:clocktable
3729 org-get-clocktable org-resolve-clocks)))
3731 (defun org-clock-update-time-maybe ()
3732 "If this is a CLOCK line, update it and return t.
3733 Otherwise, return nil."
3734 (interactive)
3735 (save-excursion
3736 (beginning-of-line 1)
3737 (skip-chars-forward " \t")
3738 (when (looking-at org-clock-string)
3739 (let ((re (concat "[ \t]*" org-clock-string
3740 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3741 "\\([ \t]*=>.*\\)?\\)?"))
3742 ts te h m s neg)
3743 (cond
3744 ((not (looking-at re))
3745 nil)
3746 ((not (match-end 2))
3747 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3748 (> org-clock-marker (point))
3749 (<= org-clock-marker (point-at-eol)))
3750 ;; The clock is running here
3751 (setq org-clock-start-time
3752 (apply 'encode-time
3753 (org-parse-time-string (match-string 1))))
3754 (org-clock-update-mode-line)))
3756 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3757 (end-of-line 1)
3758 (setq ts (match-string 1)
3759 te (match-string 3))
3760 (setq s (- (org-float-time
3761 (apply 'encode-time (org-parse-time-string te)))
3762 (org-float-time
3763 (apply 'encode-time (org-parse-time-string ts))))
3764 neg (< s 0)
3765 s (abs s)
3766 h (floor (/ s 3600))
3767 s (- s (* 3600 h))
3768 m (floor (/ s 60))
3769 s (- s (* 60 s)))
3770 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3771 t))))))
3773 (defun org-check-running-clock ()
3774 "Check if the current buffer contains the running clock.
3775 If yes, offer to stop it and to save the buffer with the changes."
3776 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3777 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3778 (buffer-name))))
3779 (org-clock-out)
3780 (when (y-or-n-p "Save changed buffer?")
3781 (save-buffer))))
3783 (defun org-clocktable-try-shift (dir n)
3784 "Check if this line starts a clock table, if yes, shift the time block."
3785 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3786 (org-clocktable-shift dir n)))
3788 ;; Autoload org-timer.el
3790 (eval-and-compile
3791 (org-autoload
3792 "org-timer"
3793 '(org-timer-start org-timer org-timer-item
3794 org-timer-change-times-in-region
3795 org-timer-set-timer
3796 org-timer-reset-timers
3797 org-timer-show-remaining-time)))
3799 ;; Autoload org-feed.el
3801 (eval-and-compile
3802 (org-autoload
3803 "org-feed"
3804 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3807 ;; Autoload org-indent.el
3809 ;; Define the variable already here, to make sure we have it.
3810 (defvar org-indent-mode nil
3811 "Non-nil if Org-Indent mode is enabled.
3812 Use the command `org-indent-mode' to change this variable.")
3814 (eval-and-compile
3815 (org-autoload
3816 "org-indent"
3817 '(org-indent-mode)))
3819 ;; Autoload org-mobile.el
3821 (eval-and-compile
3822 (org-autoload
3823 "org-mobile"
3824 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
3826 ;; Autoload archiving code
3827 ;; The stuff that is needed for cycling and tags has to be defined here.
3829 (defgroup org-archive nil
3830 "Options concerning archiving in Org-mode."
3831 :tag "Org Archive"
3832 :group 'org-structure)
3834 (defcustom org-archive-location "%s_archive::"
3835 "The location where subtrees should be archived.
3837 The value of this variable is a string, consisting of two parts,
3838 separated by a double-colon. The first part is a filename and
3839 the second part is a headline.
3841 When the filename is omitted, archiving happens in the same file.
3842 %s in the filename will be replaced by the current file
3843 name (without the directory part). Archiving to a different file
3844 is useful to keep archived entries from contributing to the
3845 Org-mode Agenda.
3847 The archived entries will be filed as subtrees of the specified
3848 headline. When the headline is omitted, the subtrees are simply
3849 filed away at the end of the file, as top-level entries. Also in
3850 the heading you can use %s to represent the file name, this can be
3851 useful when using the same archive for a number of different files.
3853 Here are a few examples:
3854 \"%s_archive::\"
3855 If the current file is Projects.org, archive in file
3856 Projects.org_archive, as top-level trees. This is the default.
3858 \"::* Archived Tasks\"
3859 Archive in the current file, under the top-level headline
3860 \"* Archived Tasks\".
3862 \"~/org/archive.org::\"
3863 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3865 \"~/org/archive.org::From %s\"
3866 Archive in file ~/org/archive.org (absolute path), under headlines
3867 \"From FILENAME\" where file name is the current file name.
3869 \"basement::** Finished Tasks\"
3870 Archive in file ./basement (relative path), as level 3 trees
3871 below the level 2 heading \"** Finished Tasks\".
3873 You may set this option on a per-file basis by adding to the buffer a
3874 line like
3876 #+ARCHIVE: basement::** Finished Tasks
3878 You may also define it locally for a subtree by setting an ARCHIVE property
3879 in the entry. If such a property is found in an entry, or anywhere up
3880 the hierarchy, it will be used."
3881 :group 'org-archive
3882 :type 'string)
3884 (defcustom org-archive-tag "ARCHIVE"
3885 "The tag that marks a subtree as archived.
3886 An archived subtree does not open during visibility cycling, and does
3887 not contribute to the agenda listings.
3888 After changing this, font-lock must be restarted in the relevant buffers to
3889 get the proper fontification."
3890 :group 'org-archive
3891 :group 'org-keywords
3892 :type 'string)
3894 (defcustom org-agenda-skip-archived-trees t
3895 "Non-nil means the agenda will skip any items located in archived trees.
3896 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3897 variable is no longer recommended, you should leave it at the value t.
3898 Instead, use the key `v' to cycle the archives-mode in the agenda."
3899 :group 'org-archive
3900 :group 'org-agenda-skip
3901 :type 'boolean)
3903 (defcustom org-columns-skip-archived-trees t
3904 "Non-nil means ignore archived trees when creating column view."
3905 :group 'org-archive
3906 :group 'org-properties
3907 :type 'boolean)
3909 (defcustom org-cycle-open-archived-trees nil
3910 "Non-nil means `org-cycle' will open archived trees.
3911 An archived tree is a tree marked with the tag ARCHIVE.
3912 When nil, archived trees will stay folded. You can still open them with
3913 normal outline commands like `show-all', but not with the cycling commands."
3914 :group 'org-archive
3915 :group 'org-cycle
3916 :type 'boolean)
3918 (defcustom org-sparse-tree-open-archived-trees nil
3919 "Non-nil means sparse tree construction shows matches in archived trees.
3920 When nil, matches in these trees are highlighted, but the trees are kept in
3921 collapsed state."
3922 :group 'org-archive
3923 :group 'org-sparse-trees
3924 :type 'boolean)
3926 (defun org-cycle-hide-archived-subtrees (state)
3927 "Re-hide all archived subtrees after a visibility state change."
3928 (when (and (not org-cycle-open-archived-trees)
3929 (not (memq state '(overview folded))))
3930 (save-excursion
3931 (let* ((globalp (memq state '(contents all)))
3932 (beg (if globalp (point-min) (point)))
3933 (end (if globalp (point-max) (org-end-of-subtree t))))
3934 (org-hide-archived-subtrees beg end)
3935 (goto-char beg)
3936 (if (looking-at (concat ".*:" org-archive-tag ":"))
3937 (message "%s" (substitute-command-keys
3938 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3940 (defun org-force-cycle-archived ()
3941 "Cycle subtree even if it is archived."
3942 (interactive)
3943 (setq this-command 'org-cycle)
3944 (let ((org-cycle-open-archived-trees t))
3945 (call-interactively 'org-cycle)))
3947 (defun org-hide-archived-subtrees (beg end)
3948 "Re-hide all archived subtrees after a visibility state change."
3949 (save-excursion
3950 (let* ((re (concat ":" org-archive-tag ":")))
3951 (goto-char beg)
3952 (while (re-search-forward re end t)
3953 (when (org-on-heading-p)
3954 (org-flag-subtree t)
3955 (org-end-of-subtree t))))))
3957 (defun org-flag-subtree (flag)
3958 (save-excursion
3959 (org-back-to-heading t)
3960 (outline-end-of-heading)
3961 (outline-flag-region (point)
3962 (progn (org-end-of-subtree t) (point))
3963 flag)))
3965 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3967 (eval-and-compile
3968 (org-autoload "org-archive"
3969 '(org-add-archive-files org-archive-subtree
3970 org-archive-to-archive-sibling org-toggle-archive-tag
3971 org-archive-subtree-default
3972 org-archive-subtree-default-with-confirmation)))
3974 ;; Autoload Column View Code
3976 (declare-function org-columns-number-to-string "org-colview")
3977 (declare-function org-columns-get-format-and-top-level "org-colview")
3978 (declare-function org-columns-compute "org-colview")
3980 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3981 '(org-columns-number-to-string org-columns-get-format-and-top-level
3982 org-columns-compute org-agenda-columns org-columns-remove-overlays
3983 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3985 ;; Autoload ID code
3987 (declare-function org-id-store-link "org-id")
3988 (declare-function org-id-locations-load "org-id")
3989 (declare-function org-id-locations-save "org-id")
3990 (defvar org-id-track-globally)
3991 (org-autoload "org-id"
3992 '(org-id-get-create org-id-new org-id-copy org-id-get
3993 org-id-get-with-outline-path-completion
3994 org-id-get-with-outline-drilling
3995 org-id-goto org-id-find org-id-store-link))
3997 ;; Autoload Plotting Code
3999 (org-autoload "org-plot"
4000 '(org-plot/gnuplot))
4002 ;;; Variables for pre-computed regular expressions, all buffer local
4004 (defvar org-drawer-regexp nil
4005 "Matches first line of a hidden block.")
4006 (make-variable-buffer-local 'org-drawer-regexp)
4007 (defvar org-todo-regexp nil
4008 "Matches any of the TODO state keywords.")
4009 (make-variable-buffer-local 'org-todo-regexp)
4010 (defvar org-not-done-regexp nil
4011 "Matches any of the TODO state keywords except the last one.")
4012 (make-variable-buffer-local 'org-not-done-regexp)
4013 (defvar org-not-done-heading-regexp nil
4014 "Matches a TODO headline that is not done.")
4015 (make-variable-buffer-local 'org-not-done-regexp)
4016 (defvar org-todo-line-regexp nil
4017 "Matches a headline and puts TODO state into group 2 if present.")
4018 (make-variable-buffer-local 'org-todo-line-regexp)
4019 (defvar org-complex-heading-regexp nil
4020 "Matches a headline and puts everything into groups:
4021 group 1: the stars
4022 group 2: The todo keyword, maybe
4023 group 3: Priority cookie
4024 group 4: True headline
4025 group 5: Tags")
4026 (make-variable-buffer-local 'org-complex-heading-regexp)
4027 (defvar org-complex-heading-regexp-format nil)
4028 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4029 (defvar org-todo-line-tags-regexp nil
4030 "Matches a headline and puts TODO state into group 2 if present.
4031 Also put tags into group 4 if tags are present.")
4032 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4033 (defvar org-nl-done-regexp nil
4034 "Matches newline followed by a headline with the DONE keyword.")
4035 (make-variable-buffer-local 'org-nl-done-regexp)
4036 (defvar org-looking-at-done-regexp nil
4037 "Matches the DONE keyword a point.")
4038 (make-variable-buffer-local 'org-looking-at-done-regexp)
4039 (defvar org-ds-keyword-length 12
4040 "Maximum length of the Deadline and SCHEDULED keywords.")
4041 (make-variable-buffer-local 'org-ds-keyword-length)
4042 (defvar org-deadline-regexp nil
4043 "Matches the DEADLINE keyword.")
4044 (make-variable-buffer-local 'org-deadline-regexp)
4045 (defvar org-deadline-time-regexp nil
4046 "Matches the DEADLINE keyword together with a time stamp.")
4047 (make-variable-buffer-local 'org-deadline-time-regexp)
4048 (defvar org-deadline-line-regexp nil
4049 "Matches the DEADLINE keyword and the rest of the line.")
4050 (make-variable-buffer-local 'org-deadline-line-regexp)
4051 (defvar org-scheduled-regexp nil
4052 "Matches the SCHEDULED keyword.")
4053 (make-variable-buffer-local 'org-scheduled-regexp)
4054 (defvar org-scheduled-time-regexp nil
4055 "Matches the SCHEDULED keyword together with a time stamp.")
4056 (make-variable-buffer-local 'org-scheduled-time-regexp)
4057 (defvar org-closed-time-regexp nil
4058 "Matches the CLOSED keyword together with a time stamp.")
4059 (make-variable-buffer-local 'org-closed-time-regexp)
4061 (defvar org-keyword-time-regexp nil
4062 "Matches any of the 4 keywords, together with the time stamp.")
4063 (make-variable-buffer-local 'org-keyword-time-regexp)
4064 (defvar org-keyword-time-not-clock-regexp nil
4065 "Matches any of the 3 keywords, together with the time stamp.")
4066 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4067 (defvar org-maybe-keyword-time-regexp nil
4068 "Matches a timestamp, possibly preceded by a keyword.")
4069 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4070 (defvar org-planning-or-clock-line-re nil
4071 "Matches a line with planning or clock info.")
4072 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4073 (defvar org-all-time-keywords nil
4074 "List of time keywords.")
4075 (make-variable-buffer-local 'org-all-time-keywords)
4077 (defconst org-plain-time-of-day-regexp
4078 (concat
4079 "\\(\\<[012]?[0-9]"
4080 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4081 "\\(--?"
4082 "\\(\\<[012]?[0-9]"
4083 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4084 "\\)?")
4085 "Regular expression to match a plain time or time range.
4086 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4087 groups carry important information:
4088 0 the full match
4089 1 the first time, range or not
4090 8 the second time, if it is a range.")
4092 (defconst org-plain-time-extension-regexp
4093 (concat
4094 "\\(\\<[012]?[0-9]"
4095 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4096 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4097 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4098 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4099 groups carry important information:
4100 0 the full match
4101 7 hours of duration
4102 9 minutes of duration")
4104 (defconst org-stamp-time-of-day-regexp
4105 (concat
4106 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4107 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4108 "\\(--?"
4109 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4110 "Regular expression to match a timestamp time or time range.
4111 After a match, the following groups carry important information:
4112 0 the full match
4113 1 date plus weekday, for back referencing to make sure both times are on the same day
4114 2 the first time, range or not
4115 4 the second time, if it is a range.")
4117 (defconst org-startup-options
4118 '(("fold" org-startup-folded t)
4119 ("overview" org-startup-folded t)
4120 ("nofold" org-startup-folded nil)
4121 ("showall" org-startup-folded nil)
4122 ("showeverything" org-startup-folded showeverything)
4123 ("content" org-startup-folded content)
4124 ("indent" org-startup-indented t)
4125 ("noindent" org-startup-indented nil)
4126 ("hidestars" org-hide-leading-stars t)
4127 ("showstars" org-hide-leading-stars nil)
4128 ("odd" org-odd-levels-only t)
4129 ("oddeven" org-odd-levels-only nil)
4130 ("align" org-startup-align-all-tables t)
4131 ("noalign" org-startup-align-all-tables nil)
4132 ("customtime" org-display-custom-times t)
4133 ("logdone" org-log-done time)
4134 ("lognotedone" org-log-done note)
4135 ("nologdone" org-log-done nil)
4136 ("lognoteclock-out" org-log-note-clock-out t)
4137 ("nolognoteclock-out" org-log-note-clock-out nil)
4138 ("logrepeat" org-log-repeat state)
4139 ("lognoterepeat" org-log-repeat note)
4140 ("nologrepeat" org-log-repeat nil)
4141 ("logreschedule" org-log-reschedule time)
4142 ("lognotereschedule" org-log-reschedule note)
4143 ("nologreschedule" org-log-reschedule nil)
4144 ("logredeadline" org-log-redeadline time)
4145 ("lognoteredeadline" org-log-redeadline note)
4146 ("nologredeadline" org-log-redeadline nil)
4147 ("logrefile" org-log-refile time)
4148 ("lognoterefile" org-log-refile note)
4149 ("nologrefile" org-log-refile nil)
4150 ("fninline" org-footnote-define-inline t)
4151 ("nofninline" org-footnote-define-inline nil)
4152 ("fnlocal" org-footnote-section nil)
4153 ("fnauto" org-footnote-auto-label t)
4154 ("fnprompt" org-footnote-auto-label nil)
4155 ("fnconfirm" org-footnote-auto-label confirm)
4156 ("fnplain" org-footnote-auto-label plain)
4157 ("fnadjust" org-footnote-auto-adjust t)
4158 ("nofnadjust" org-footnote-auto-adjust nil)
4159 ("constcgs" constants-unit-system cgs)
4160 ("constSI" constants-unit-system SI)
4161 ("noptag" org-tag-persistent-alist nil)
4162 ("hideblocks" org-hide-block-startup t)
4163 ("nohideblocks" org-hide-block-startup nil)
4164 ("beamer" org-startup-with-beamer-mode t)
4165 ("entitiespretty" org-pretty-entities t)
4166 ("entitiesplain" org-pretty-entities nil))
4167 "Variable associated with STARTUP options for org-mode.
4168 Each element is a list of three items: The startup options as written
4169 in the #+STARTUP line, the corresponding variable, and the value to
4170 set this variable to if the option is found. An optional forth element PUSH
4171 means to push this value onto the list in the variable.")
4173 (defun org-set-regexps-and-options ()
4174 "Precompute regular expressions for current buffer."
4175 (when (org-mode-p)
4176 (org-set-local 'org-todo-kwd-alist nil)
4177 (org-set-local 'org-todo-key-alist nil)
4178 (org-set-local 'org-todo-key-trigger nil)
4179 (org-set-local 'org-todo-keywords-1 nil)
4180 (org-set-local 'org-done-keywords nil)
4181 (org-set-local 'org-todo-heads nil)
4182 (org-set-local 'org-todo-sets nil)
4183 (org-set-local 'org-todo-log-states nil)
4184 (org-set-local 'org-file-properties nil)
4185 (org-set-local 'org-file-tags nil)
4186 (let ((re (org-make-options-regexp
4187 '("CATEGORY" "TODO" "COLUMNS"
4188 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4189 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4190 "OPTIONS")
4191 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4192 (splitre "[ \t]+")
4193 (scripts org-use-sub-superscripts)
4194 kwds kws0 kwsa key log value cat arch tags const links hw dws
4195 tail sep kws1 prio props ftags drawers beamer-p
4196 ext-setup-or-nil setup-contents (start 0))
4197 (save-excursion
4198 (save-restriction
4199 (widen)
4200 (goto-char (point-min))
4201 (while (or (and ext-setup-or-nil
4202 (string-match re ext-setup-or-nil start)
4203 (setq start (match-end 0)))
4204 (and (setq ext-setup-or-nil nil start 0)
4205 (re-search-forward re nil t)))
4206 (setq key (upcase (match-string 1 ext-setup-or-nil))
4207 value (org-match-string-no-properties 2 ext-setup-or-nil))
4208 (if (stringp value) (setq value (org-trim value)))
4209 (cond
4210 ((equal key "CATEGORY")
4211 (setq cat value))
4212 ((member key '("SEQ_TODO" "TODO"))
4213 (push (cons 'sequence (org-split-string value splitre)) kwds))
4214 ((equal key "TYP_TODO")
4215 (push (cons 'type (org-split-string value splitre)) kwds))
4216 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4217 ;; general TODO-like setup
4218 (push (cons (intern (downcase (match-string 1 key)))
4219 (org-split-string value splitre)) kwds))
4220 ((equal key "TAGS")
4221 (setq tags (append tags (if tags '("\\n") nil)
4222 (org-split-string value splitre))))
4223 ((equal key "COLUMNS")
4224 (org-set-local 'org-columns-default-format value))
4225 ((equal key "LINK")
4226 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4227 (push (cons (match-string 1 value)
4228 (org-trim (match-string 2 value)))
4229 links)))
4230 ((equal key "PRIORITIES")
4231 (setq prio (org-split-string value " +")))
4232 ((equal key "PROPERTY")
4233 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4234 (push (cons (match-string 1 value) (match-string 2 value))
4235 props)))
4236 ((equal key "FILETAGS")
4237 (when (string-match "\\S-" value)
4238 (setq ftags
4239 (append
4240 ftags
4241 (apply 'append
4242 (mapcar (lambda (x) (org-split-string x ":"))
4243 (org-split-string value)))))))
4244 ((equal key "DRAWERS")
4245 (setq drawers (org-split-string value splitre)))
4246 ((equal key "CONSTANTS")
4247 (setq const (append const (org-split-string value splitre))))
4248 ((equal key "STARTUP")
4249 (let ((opts (org-split-string value splitre))
4250 l var val)
4251 (while (setq l (pop opts))
4252 (when (setq l (assoc l org-startup-options))
4253 (setq var (nth 1 l) val (nth 2 l))
4254 (if (not (nth 3 l))
4255 (set (make-local-variable var) val)
4256 (if (not (listp (symbol-value var)))
4257 (set (make-local-variable var) nil))
4258 (set (make-local-variable var) (symbol-value var))
4259 (add-to-list var val))))))
4260 ((equal key "ARCHIVE")
4261 (setq arch value)
4262 (remove-text-properties 0 (length arch)
4263 '(face t fontified t) arch))
4264 ((equal key "LATEX_CLASS")
4265 (setq beamer-p (equal value "beamer")))
4266 ((equal key "OPTIONS")
4267 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4268 (setq scripts (read (match-string 2 value)))))
4269 ((equal key "SETUPFILE")
4270 (setq setup-contents (org-file-contents
4271 (expand-file-name
4272 (org-remove-double-quotes value))
4273 'noerror))
4274 (if (not ext-setup-or-nil)
4275 (setq ext-setup-or-nil setup-contents start 0)
4276 (setq ext-setup-or-nil
4277 (concat (substring ext-setup-or-nil 0 start)
4278 "\n" setup-contents "\n"
4279 (substring ext-setup-or-nil start)))))
4280 ))))
4281 (org-set-local 'org-use-sub-superscripts scripts)
4282 (when cat
4283 (org-set-local 'org-category (intern cat))
4284 (push (cons "CATEGORY" cat) props))
4285 (when prio
4286 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4287 (setq prio (mapcar 'string-to-char prio))
4288 (org-set-local 'org-highest-priority (nth 0 prio))
4289 (org-set-local 'org-lowest-priority (nth 1 prio))
4290 (org-set-local 'org-default-priority (nth 2 prio)))
4291 (and props (org-set-local 'org-file-properties (nreverse props)))
4292 (and ftags (org-set-local 'org-file-tags
4293 (mapcar 'org-add-prop-inherited ftags)))
4294 (and drawers (org-set-local 'org-drawers drawers))
4295 (and arch (org-set-local 'org-archive-location arch))
4296 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4297 ;; Process the TODO keywords
4298 (unless kwds
4299 ;; Use the global values as if they had been given locally.
4300 (setq kwds (default-value 'org-todo-keywords))
4301 (if (stringp (car kwds))
4302 (setq kwds (list (cons org-todo-interpretation
4303 (default-value 'org-todo-keywords)))))
4304 (setq kwds (reverse kwds)))
4305 (setq kwds (nreverse kwds))
4306 (let (inter kws kw)
4307 (while (setq kws (pop kwds))
4308 (let ((kws (or
4309 (run-hook-with-args-until-success
4310 'org-todo-setup-filter-hook kws)
4311 kws)))
4312 (setq inter (pop kws) sep (member "|" kws)
4313 kws0 (delete "|" (copy-sequence kws))
4314 kwsa nil
4315 kws1 (mapcar
4316 (lambda (x)
4317 ;; 1 2
4318 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4319 (progn
4320 (setq kw (match-string 1 x)
4321 key (and (match-end 2) (match-string 2 x))
4322 log (org-extract-log-state-settings x))
4323 (push (cons kw (and key (string-to-char key))) kwsa)
4324 (and log (push log org-todo-log-states))
4326 (error "Invalid TODO keyword %s" x)))
4327 kws0)
4328 kwsa (if kwsa (append '((:startgroup))
4329 (nreverse kwsa)
4330 '((:endgroup))))
4331 hw (car kws1)
4332 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4333 tail (list inter hw (car dws) (org-last dws))))
4334 (add-to-list 'org-todo-heads hw 'append)
4335 (push kws1 org-todo-sets)
4336 (setq org-done-keywords (append org-done-keywords dws nil))
4337 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4338 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4339 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4340 (setq org-todo-sets (nreverse org-todo-sets)
4341 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4342 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4343 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4344 ;; Process the constants
4345 (when const
4346 (let (e cst)
4347 (while (setq e (pop const))
4348 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4349 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4350 (setq org-table-formula-constants-local cst)))
4352 ;; Process the tags.
4353 (when tags
4354 (let (e tgs)
4355 (while (setq e (pop tags))
4356 (cond
4357 ((equal e "{") (push '(:startgroup) tgs))
4358 ((equal e "}") (push '(:endgroup) tgs))
4359 ((equal e "\\n") (push '(:newline) tgs))
4360 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4361 (push (cons (match-string 1 e)
4362 (string-to-char (match-string 2 e)))
4363 tgs))
4364 (t (push (list e) tgs))))
4365 (org-set-local 'org-tag-alist nil)
4366 (while (setq e (pop tgs))
4367 (or (and (stringp (car e))
4368 (assoc (car e) org-tag-alist))
4369 (push e org-tag-alist)))))
4371 ;; Compute the regular expressions and other local variables
4372 (if (not org-done-keywords)
4373 (setq org-done-keywords (and org-todo-keywords-1
4374 (list (org-last org-todo-keywords-1)))))
4375 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4376 (length org-scheduled-string)
4377 (length org-clock-string)
4378 (length org-closed-string)))
4379 org-drawer-regexp
4380 (concat "^[ \t]*:\\("
4381 (mapconcat 'regexp-quote org-drawers "\\|")
4382 "\\):[ \t]*$")
4383 org-not-done-keywords
4384 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4385 org-todo-regexp
4386 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4387 "\\|") "\\)\\>")
4388 org-not-done-regexp
4389 (concat "\\<\\("
4390 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4391 "\\)\\>")
4392 org-not-done-heading-regexp
4393 (concat "^\\(\\*+\\)[ \t]+\\("
4394 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4395 "\\)\\>")
4396 org-todo-line-regexp
4397 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4398 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4399 "\\)\\>\\)?[ \t]*\\(.*\\)")
4400 org-complex-heading-regexp
4401 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4402 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4403 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4404 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4405 org-complex-heading-regexp-format
4406 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4407 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4408 "\\)\\>\\)?"
4409 "\\(?:[ \t]*\\(\\[#.\\]\\)\\)?"
4410 "\\(?:[ \t]*\\(?:\\[[0-9%%/]+\\]\\)\\)?" ;; stats cookie
4411 "[ \t]*\\(%s\\)"
4412 "\\(?:[ \t]*\\(?:\\[[0-9%%/]+\\]\\)\\)?" ;; stats cookie
4413 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4414 org-nl-done-regexp
4415 (concat "\n\\*+[ \t]+"
4416 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4417 "\\)" "\\>")
4418 org-todo-line-tags-regexp
4419 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4420 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4421 (org-re
4422 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4423 org-looking-at-done-regexp
4424 (concat "^" "\\(?:"
4425 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4426 "\\>")
4427 org-deadline-regexp (concat "\\<" org-deadline-string)
4428 org-deadline-time-regexp
4429 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4430 org-deadline-line-regexp
4431 (concat "\\<\\(" org-deadline-string "\\).*")
4432 org-scheduled-regexp
4433 (concat "\\<" org-scheduled-string)
4434 org-scheduled-time-regexp
4435 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4436 org-closed-time-regexp
4437 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4438 org-keyword-time-regexp
4439 (concat "\\<\\(" org-scheduled-string
4440 "\\|" org-deadline-string
4441 "\\|" org-closed-string
4442 "\\|" org-clock-string "\\)"
4443 " *[[<]\\([^]>]+\\)[]>]")
4444 org-keyword-time-not-clock-regexp
4445 (concat "\\<\\(" org-scheduled-string
4446 "\\|" org-deadline-string
4447 "\\|" org-closed-string
4448 "\\)"
4449 " *[[<]\\([^]>]+\\)[]>]")
4450 org-maybe-keyword-time-regexp
4451 (concat "\\(\\<\\(" org-scheduled-string
4452 "\\|" org-deadline-string
4453 "\\|" org-closed-string
4454 "\\|" org-clock-string "\\)\\)?"
4455 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4456 org-planning-or-clock-line-re
4457 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4458 "\\|" org-deadline-string
4459 "\\|" org-closed-string "\\|" org-clock-string
4460 "\\)\\>\\)")
4461 org-all-time-keywords
4462 (mapcar (lambda (w) (substring w 0 -1))
4463 (list org-scheduled-string org-deadline-string
4464 org-clock-string org-closed-string))
4466 (org-compute-latex-and-specials-regexp)
4467 (org-set-font-lock-defaults))))
4469 (defun org-file-contents (file &optional noerror)
4470 "Return the contents of FILE, as a string."
4471 (if (or (not file)
4472 (not (file-readable-p file)))
4473 (if noerror
4474 (progn
4475 (message "Cannot read file \"%s\"" file)
4476 (ding) (sit-for 2)
4478 (error "Cannot read file \"%s\"" file))
4479 (with-temp-buffer
4480 (insert-file-contents file)
4481 (buffer-string))))
4483 (defun org-extract-log-state-settings (x)
4484 "Extract the log state setting from a TODO keyword string.
4485 This will extract info from a string like \"WAIT(w@/!)\"."
4486 (let (kw key log1 log2)
4487 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4488 (setq kw (match-string 1 x)
4489 key (and (match-end 2) (match-string 2 x))
4490 log1 (and (match-end 3) (match-string 3 x))
4491 log2 (and (match-end 4) (match-string 4 x)))
4492 (and (or log1 log2)
4493 (list kw
4494 (and log1 (if (equal log1 "!") 'time 'note))
4495 (and log2 (if (equal log2 "!") 'time 'note)))))))
4497 (defun org-remove-keyword-keys (list)
4498 "Remove a pair of parenthesis at the end of each string in LIST."
4499 (mapcar (lambda (x)
4500 (if (string-match "(.*)$" x)
4501 (substring x 0 (match-beginning 0))
4503 list))
4505 (defun org-assign-fast-keys (alist)
4506 "Assign fast keys to a keyword-key alist.
4507 Respect keys that are already there."
4508 (let (new e (alt ?0))
4509 (while (setq e (pop alist))
4510 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4511 (cdr e)) ;; Key already assigned.
4512 (push e new)
4513 (let ((clist (string-to-list (downcase (car e))))
4514 (used (append new alist)))
4515 (when (= (car clist) ?@)
4516 (pop clist))
4517 (while (and clist (rassoc (car clist) used))
4518 (pop clist))
4519 (unless clist
4520 (while (rassoc alt used)
4521 (incf alt)))
4522 (push (cons (car e) (or (car clist) alt)) new))))
4523 (nreverse new)))
4525 ;;; Some variables used in various places
4527 (defvar org-window-configuration nil
4528 "Used in various places to store a window configuration.")
4529 (defvar org-selected-window nil
4530 "Used in various places to store a window configuration.")
4531 (defvar org-finish-function nil
4532 "Function to be called when `C-c C-c' is used.
4533 This is for getting out of special buffers like remember.")
4536 ;; FIXME: Occasionally check by commenting these, to make sure
4537 ;; no other functions uses these, forgetting to let-bind them.
4538 (defvar entry)
4539 (defvar last-state)
4540 (defvar date)
4542 ;; Defined somewhere in this file, but used before definition.
4543 (defvar org-entities) ;; defined in org-entities.el
4544 (defvar org-struct-menu)
4545 (defvar org-org-menu)
4546 (defvar org-tbl-menu)
4548 ;;;; Define the Org-mode
4550 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4551 (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"))
4554 ;; We use a before-change function to check if a table might need
4555 ;; an update.
4556 (defvar org-table-may-need-update t
4557 "Indicates that a table might need an update.
4558 This variable is set by `org-before-change-function'.
4559 `org-table-align' sets it back to nil.")
4560 (defun org-before-change-function (beg end)
4561 "Every change indicates that a table might need an update."
4562 (setq org-table-may-need-update t))
4563 (defvar org-mode-map)
4564 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4565 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4566 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4567 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4568 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4569 (defvar org-table-buffer-is-an nil)
4570 (defconst org-outline-regexp "\\*+ ")
4572 ;;;###autoload
4573 (define-derived-mode org-mode outline-mode "Org"
4574 "Outline-based notes management and organizer, alias
4575 \"Carsten's outline-mode for keeping track of everything.\"
4577 Org-mode develops organizational tasks around a NOTES file which
4578 contains information about projects as plain text. Org-mode is
4579 implemented on top of outline-mode, which is ideal to keep the content
4580 of large files well structured. It supports ToDo items, deadlines and
4581 time stamps, which magically appear in the diary listing of the Emacs
4582 calendar. Tables are easily created with a built-in table editor.
4583 Plain text URL-like links connect to websites, emails (VM), Usenet
4584 messages (Gnus), BBDB entries, and any files related to the project.
4585 For printing and sharing of notes, an Org-mode file (or a part of it)
4586 can be exported as a structured ASCII or HTML file.
4588 The following commands are available:
4590 \\{org-mode-map}"
4592 ;; Get rid of Outline menus, they are not needed
4593 ;; Need to do this here because define-derived-mode sets up
4594 ;; the keymap so late. Still, it is a waste to call this each time
4595 ;; we switch another buffer into org-mode.
4596 (if (featurep 'xemacs)
4597 (when (boundp 'outline-mode-menu-heading)
4598 ;; Assume this is Greg's port, it uses easymenu
4599 (easy-menu-remove outline-mode-menu-heading)
4600 (easy-menu-remove outline-mode-menu-show)
4601 (easy-menu-remove outline-mode-menu-hide))
4602 (define-key org-mode-map [menu-bar headings] 'undefined)
4603 (define-key org-mode-map [menu-bar hide] 'undefined)
4604 (define-key org-mode-map [menu-bar show] 'undefined))
4606 (org-load-modules-maybe)
4607 (easy-menu-add org-org-menu)
4608 (easy-menu-add org-tbl-menu)
4609 (org-install-agenda-files-menu)
4610 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4611 (add-to-invisibility-spec '(org-cwidth))
4612 (add-to-invisibility-spec '(org-hide-block . t))
4613 (when (featurep 'xemacs)
4614 (org-set-local 'line-move-ignore-invisible t))
4615 (org-set-local 'outline-regexp org-outline-regexp)
4616 (org-set-local 'outline-level 'org-outline-level)
4617 (when (and org-ellipsis
4618 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4619 (fboundp 'make-glyph-code))
4620 (unless org-display-table
4621 (setq org-display-table (make-display-table)))
4622 (set-display-table-slot
4623 org-display-table 4
4624 (vconcat (mapcar
4625 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4626 org-ellipsis)))
4627 (if (stringp org-ellipsis) org-ellipsis "..."))))
4628 (setq buffer-display-table org-display-table))
4629 (org-set-regexps-and-options)
4630 (when (and org-tag-faces (not org-tags-special-faces-re))
4631 ;; tag faces set outside customize.... force initialization.
4632 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4633 ;; Calc embedded
4634 (org-set-local 'calc-embedded-open-mode "# ")
4635 (modify-syntax-entry ?@ "w")
4636 (if org-startup-truncated (setq truncate-lines t))
4637 (org-set-local 'font-lock-unfontify-region-function
4638 'org-unfontify-region)
4639 ;; Activate before-change-function
4640 (org-set-local 'org-table-may-need-update t)
4641 (org-add-hook 'before-change-functions 'org-before-change-function nil
4642 'local)
4643 ;; Check for running clock before killing a buffer
4644 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4645 ;; Paragraphs and auto-filling
4646 (org-set-autofill-regexps)
4647 (setq indent-line-function 'org-indent-line-function)
4648 (org-update-radio-target-regexp)
4649 ;; Beginning/end of defun
4650 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
4651 (org-set-local 'end-of-defun-function 'org-end-of-defun)
4652 ;; Make sure dependence stuff works reliably, even for users who set it
4653 ;; too late :-(
4654 (if org-enforce-todo-dependencies
4655 (add-hook 'org-blocker-hook
4656 'org-block-todo-from-children-or-siblings-or-parent)
4657 (remove-hook 'org-blocker-hook
4658 'org-block-todo-from-children-or-siblings-or-parent))
4659 (if org-enforce-todo-checkbox-dependencies
4660 (add-hook 'org-blocker-hook
4661 'org-block-todo-from-checkboxes)
4662 (remove-hook 'org-blocker-hook
4663 'org-block-todo-from-checkboxes))
4665 ;; Comment characters
4666 (org-set-local 'comment-start "#")
4667 (org-set-local 'comment-padding " ")
4669 ;; Align options lines
4670 (org-set-local
4671 'align-mode-rules-list
4672 '((org-in-buffer-settings
4673 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4674 (modes . '(org-mode)))))
4676 ;; Imenu
4677 (org-set-local 'imenu-create-index-function
4678 'org-imenu-get-tree)
4680 ;; Make isearch reveal context
4681 (if (or (featurep 'xemacs)
4682 (not (boundp 'outline-isearch-open-invisible-function)))
4683 ;; Emacs 21 and XEmacs make use of the hook
4684 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4685 ;; Emacs 22 deals with this through a special variable
4686 (org-set-local 'outline-isearch-open-invisible-function
4687 (lambda (&rest ignore) (org-show-context 'isearch))))
4689 ;; Turn on org-beamer-mode?
4690 (and org-startup-with-beamer-mode (org-beamer-mode 1))
4692 ;; If empty file that did not turn on org-mode automatically, make it to.
4693 (if (and org-insert-mode-line-in-empty-file
4694 (interactive-p)
4695 (= (point-min) (point-max)))
4696 (insert "# -*- mode: org -*-\n\n"))
4697 (unless org-inhibit-startup
4698 (when org-startup-align-all-tables
4699 (let ((bmp (buffer-modified-p)))
4700 (org-table-map-tables 'org-table-align 'quietly)
4701 (set-buffer-modified-p bmp)))
4702 (when org-startup-indented
4703 (require 'org-indent)
4704 (org-indent-mode 1))
4705 (unless org-inhibit-startup-visibility-stuff
4706 (org-set-startup-visibility))))
4708 (when (fboundp 'abbrev-table-put)
4709 (abbrev-table-put org-mode-abbrev-table
4710 :parents (list text-mode-abbrev-table)))
4712 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4714 (defun org-current-time ()
4715 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4716 (if (> (car org-time-stamp-rounding-minutes) 1)
4717 (let ((r (car org-time-stamp-rounding-minutes))
4718 (time (decode-time)))
4719 (apply 'encode-time
4720 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4721 (nthcdr 2 time))))
4722 (current-time)))
4724 ;;;; Font-Lock stuff, including the activators
4726 (defvar org-mouse-map (make-sparse-keymap))
4727 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
4728 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
4729 (when org-mouse-1-follows-link
4730 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4731 (when org-tab-follows-link
4732 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4733 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4735 (require 'font-lock)
4737 (defconst org-non-link-chars "]\t\n\r<>")
4738 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4739 "shell" "elisp" "doi"))
4740 (defvar org-link-types-re nil
4741 "Matches a link that has a url-like prefix like \"http:\"")
4742 (defvar org-link-re-with-space nil
4743 "Matches a link with spaces, optional angular brackets around it.")
4744 (defvar org-link-re-with-space2 nil
4745 "Matches a link with spaces, optional angular brackets around it.")
4746 (defvar org-link-re-with-space3 nil
4747 "Matches a link with spaces, only for internal part in bracket links.")
4748 (defvar org-angle-link-re nil
4749 "Matches link with angular brackets, spaces are allowed.")
4750 (defvar org-plain-link-re nil
4751 "Matches plain link, without spaces.")
4752 (defvar org-bracket-link-regexp nil
4753 "Matches a link in double brackets.")
4754 (defvar org-bracket-link-analytic-regexp nil
4755 "Regular expression used to analyze links.
4756 Here is what the match groups contain after a match:
4757 1: http:
4758 2: http
4759 3: path
4760 4: [desc]
4761 5: desc")
4762 (defvar org-bracket-link-analytic-regexp++ nil
4763 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
4764 (defvar org-any-link-re nil
4765 "Regular expression matching any link.")
4767 (defcustom org-match-sexp-depth 3
4768 "Number of stacked braces for sub/superscript matching.
4769 This has to be set before loading org.el to be effective."
4770 :group 'org-export-translation ; ??????????????????????????/
4771 :type 'integer)
4773 (defun org-create-multibrace-regexp (left right n)
4774 "Create a regular expression which will match a balanced sexp.
4775 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
4776 as single character strings.
4777 The regexp returned will match the entire expression including the
4778 delimiters. It will also define a single group which contains the
4779 match except for the outermost delimiters. The maximum depth of
4780 stacked delimiters is N. Escaping delimiters is not possible."
4781 (let* ((nothing (concat "[^" left right "]*?"))
4782 (or "\\|")
4783 (re nothing)
4784 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
4785 (while (> n 1)
4786 (setq n (1- n)
4787 re (concat re or next)
4788 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
4789 (concat left "\\(" re "\\)" right)))
4791 (defvar org-match-substring-regexp
4792 (concat
4793 "\\([^\\]\\)\\([_^]\\)\\("
4794 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
4795 "\\|"
4796 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
4797 "\\|"
4798 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
4799 "The regular expression matching a sub- or superscript.")
4801 (defvar org-match-substring-with-braces-regexp
4802 (concat
4803 "\\([^\\]\\)\\([_^]\\)\\("
4804 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
4805 "\\)")
4806 "The regular expression matching a sub- or superscript, forcing braces.")
4808 (defun org-make-link-regexps ()
4809 "Update the link regular expressions.
4810 This should be called after the variable `org-link-types' has changed."
4811 (setq org-link-types-re
4812 (concat
4813 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
4814 org-link-re-with-space
4815 (concat
4816 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4817 "\\([^" org-non-link-chars " ]"
4818 "[^" org-non-link-chars "]*"
4819 "[^" org-non-link-chars " ]\\)>?")
4820 org-link-re-with-space2
4821 (concat
4822 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4823 "\\([^" org-non-link-chars " ]"
4824 "[^\t\n\r]*"
4825 "[^" org-non-link-chars " ]\\)>?")
4826 org-link-re-with-space3
4827 (concat
4828 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4829 "\\([^" org-non-link-chars " ]"
4830 "[^\t\n\r]*\\)")
4831 org-angle-link-re
4832 (concat
4833 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4834 "\\([^" org-non-link-chars " ]"
4835 "[^" org-non-link-chars "]*"
4836 "\\)>")
4837 org-plain-link-re
4838 (concat
4839 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4840 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
4841 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4842 org-bracket-link-regexp
4843 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4844 org-bracket-link-analytic-regexp
4845 (concat
4846 "\\[\\["
4847 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
4848 "\\([^]]+\\)"
4849 "\\]"
4850 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4851 "\\]")
4852 org-bracket-link-analytic-regexp++
4853 (concat
4854 "\\[\\["
4855 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4856 "\\([^]]+\\)"
4857 "\\]"
4858 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4859 "\\]")
4860 org-any-link-re
4861 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4862 org-angle-link-re "\\)\\|\\("
4863 org-plain-link-re "\\)")))
4865 (org-make-link-regexps)
4867 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4868 "Regular expression for fast time stamp matching.")
4869 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4870 "Regular expression for fast time stamp matching.")
4871 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4872 "Regular expression matching time strings for analysis.
4873 This one does not require the space after the date, so it can be used
4874 on a string that terminates immediately after the date.")
4875 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4876 "Regular expression matching time strings for analysis.")
4877 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4878 "Regular expression matching time stamps, with groups.")
4879 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4880 "Regular expression matching time stamps (also [..]), with groups.")
4881 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4882 "Regular expression matching a time stamp range.")
4883 (defconst org-tr-regexp-both
4884 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4885 "Regular expression matching a time stamp range.")
4886 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4887 org-ts-regexp "\\)?")
4888 "Regular expression matching a time stamp or time stamp range.")
4889 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4890 org-ts-regexp-both "\\)?")
4891 "Regular expression matching a time stamp or time stamp range.
4892 The time stamps may be either active or inactive.")
4894 (defvar org-emph-face nil)
4896 (defun org-do-emphasis-faces (limit)
4897 "Run through the buffer and add overlays to links."
4898 (let (rtn a)
4899 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4900 (if (not (= (char-after (match-beginning 3))
4901 (char-after (match-beginning 4))))
4902 (progn
4903 (setq rtn t)
4904 (setq a (assoc (match-string 3) org-emphasis-alist))
4905 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4906 'face
4907 (nth 1 a))
4908 (and (nth 4 a)
4909 (org-remove-flyspell-overlays-in
4910 (match-beginning 0) (match-end 0)))
4911 (add-text-properties (match-beginning 2) (match-end 2)
4912 '(font-lock-multiline t org-emphasis t))
4913 (when org-hide-emphasis-markers
4914 (add-text-properties (match-end 4) (match-beginning 5)
4915 '(invisible org-link))
4916 (add-text-properties (match-beginning 3) (match-end 3)
4917 '(invisible org-link)))))
4918 (backward-char 1))
4919 rtn))
4921 (defun org-emphasize (&optional char)
4922 "Insert or change an emphasis, i.e. a font like bold or italic.
4923 If there is an active region, change that region to a new emphasis.
4924 If there is no region, just insert the marker characters and position
4925 the cursor between them.
4926 CHAR should be either the marker character, or the first character of the
4927 HTML tag associated with that emphasis. If CHAR is a space, the means
4928 to remove the emphasis of the selected region.
4929 If char is not given (for example in an interactive call) it
4930 will be prompted for."
4931 (interactive)
4932 (let ((eal org-emphasis-alist) e det
4933 (erc org-emphasis-regexp-components)
4934 (prompt "")
4935 (string "") beg end move tag c s)
4936 (if (org-region-active-p)
4937 (setq beg (region-beginning) end (region-end)
4938 string (buffer-substring beg end))
4939 (setq move t))
4941 (while (setq e (pop eal))
4942 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4943 c (aref tag 0))
4944 (push (cons c (string-to-char (car e))) det)
4945 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4946 (substring tag 1)))))
4947 (setq det (nreverse det))
4948 (unless char
4949 (message "%s" (concat "Emphasis marker or tag:" prompt))
4950 (setq char (read-char-exclusive)))
4951 (setq char (or (cdr (assoc char det)) char))
4952 (if (equal char ?\ )
4953 (setq s "" move nil)
4954 (unless (assoc (char-to-string char) org-emphasis-alist)
4955 (error "No such emphasis marker: \"%c\"" char))
4956 (setq s (char-to-string char)))
4957 (while (and (> (length string) 1)
4958 (equal (substring string 0 1) (substring string -1))
4959 (assoc (substring string 0 1) org-emphasis-alist))
4960 (setq string (substring string 1 -1)))
4961 (setq string (concat s string s))
4962 (if beg (delete-region beg end))
4963 (unless (or (bolp)
4964 (string-match (concat "[" (nth 0 erc) "\n]")
4965 (char-to-string (char-before (point)))))
4966 (insert " "))
4967 (unless (or (eobp)
4968 (string-match (concat "[" (nth 1 erc) "\n]")
4969 (char-to-string (char-after (point)))))
4970 (insert " ") (backward-char 1))
4971 (insert string)
4972 (and move (backward-char 1))))
4974 (defconst org-nonsticky-props
4975 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4977 (defsubst org-rear-nonsticky-at (pos)
4978 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4980 (defun org-activate-plain-links (limit)
4981 "Run through the buffer and add overlays to links."
4982 (catch 'exit
4983 (let (f)
4984 (if (re-search-forward org-plain-link-re limit t)
4985 (progn
4986 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4987 (setq f (get-text-property (match-beginning 0) 'face))
4988 (if (or (eq f 'org-tag)
4989 (and (listp f) (memq 'org-tag f)))
4991 (add-text-properties (match-beginning 0) (match-end 0)
4992 (list 'mouse-face 'highlight
4993 'face 'org-link
4994 'keymap org-mouse-map))
4995 (org-rear-nonsticky-at (match-end 0)))
4996 t)))))
4998 (defun org-activate-code (limit)
4999 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
5000 (progn
5001 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5002 (remove-text-properties (match-beginning 0) (match-end 0)
5003 '(display t invisible t intangible t))
5004 t)))
5006 (defun org-fontify-meta-lines-and-blocks (limit)
5007 "Fontify #+ lines and blocks, in the correct ways."
5008 (let ((case-fold-search t))
5009 (if (re-search-forward
5010 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
5011 limit t)
5012 (let ((beg (match-beginning 0))
5013 (beg1 (line-beginning-position 2))
5014 (dc1 (downcase (match-string 2)))
5015 (dc3 (downcase (match-string 3)))
5016 end end1 quoting block-type)
5017 (cond
5018 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
5019 ;; a single line of backend-specific content
5020 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5021 (remove-text-properties (match-beginning 0) (match-end 0)
5022 '(display t invisible t intangible t))
5023 (add-text-properties (match-beginning 1) (match-end 3)
5024 '(font-lock-fontified t face org-meta-line))
5025 (add-text-properties (match-beginning 6) (match-end 6)
5026 '(font-lock-fontified t face org-block))
5028 ((and (match-end 4) (equal dc3 "begin"))
5029 ;; Truly a block
5030 (setq block-type (downcase (match-string 5))
5031 quoting (member block-type org-protecting-blocks))
5032 (when (re-search-forward
5033 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5034 nil t) ;; on purpose, we look further than LIMIT
5035 (setq end (match-end 0) end1 (1- (match-beginning 0)))
5036 (when quoting
5037 (remove-text-properties beg end
5038 '(display t invisible t intangible t)))
5039 (add-text-properties
5040 beg end
5041 '(font-lock-fontified t font-lock-multiline t))
5042 (add-text-properties beg beg1 '(face org-meta-line))
5043 (add-text-properties end1 end '(face org-meta-line))
5044 (cond
5045 (quoting
5046 (add-text-properties beg1 end1 '(face org-block)))
5047 ((not org-fontify-quote-and-verse-blocks))
5048 ((string= block-type "quote")
5049 (add-text-properties beg1 end1 '(face org-quote)))
5050 ((string= block-type "verse")
5051 (add-text-properties beg1 end1 '(face org-verse))))
5053 ((member dc1 '("title:" "author:" "email:" "date:"))
5054 (add-text-properties
5055 beg (match-end 3)
5056 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5057 '(font-lock-fontified t invisible t)
5058 '(font-lock-fontified t face org-document-info-keyword)))
5059 (add-text-properties
5060 (match-beginning 6) (match-end 6)
5061 (if (string-equal dc1 "title:")
5062 '(font-lock-fontified t face org-document-title)
5063 '(font-lock-fontified t face org-document-info))))
5064 ((not (member (char-after beg) '(?\ ?\t)))
5065 ;; just any other in-buffer setting, but not indented
5066 (add-text-properties
5067 beg (match-end 0)
5068 '(font-lock-fontified t face org-meta-line))
5070 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
5071 "orgtbl:" "tblfm:" "tblname:" "result:"
5072 "results:" "source:" "srcname:" "call:"))
5073 (and (match-end 4) (equal dc3 "attr")))
5074 (add-text-properties
5075 beg (match-end 0)
5076 '(font-lock-fontified t face org-meta-line))
5078 ((member dc3 '(" " ""))
5079 (add-text-properties
5080 beg (match-end 0)
5081 '(font-lock-fontified t face font-lock-comment-face)))
5082 (t nil))))))
5084 (defun org-activate-angle-links (limit)
5085 "Run through the buffer and add overlays to links."
5086 (if (re-search-forward org-angle-link-re limit t)
5087 (progn
5088 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5089 (add-text-properties (match-beginning 0) (match-end 0)
5090 (list 'mouse-face 'highlight
5091 'keymap org-mouse-map))
5092 (org-rear-nonsticky-at (match-end 0))
5093 t)))
5095 (defun org-activate-footnote-links (limit)
5096 "Run through the buffer and add overlays to links."
5097 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
5098 limit t)
5099 (progn
5100 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5101 (add-text-properties (match-beginning 2) (match-end 2)
5102 (list 'mouse-face 'highlight
5103 'keymap org-mouse-map
5104 'help-echo
5105 (if (= (point-at-bol) (match-beginning 2))
5106 "Footnote definition"
5107 "Footnote reference")
5109 (org-rear-nonsticky-at (match-end 2))
5110 t)))
5112 (defun org-activate-bracket-links (limit)
5113 "Run through the buffer and add overlays to bracketed links."
5114 (if (re-search-forward org-bracket-link-regexp limit t)
5115 (let* ((help (concat "LINK: "
5116 (org-match-string-no-properties 1)))
5117 ;; FIXME: above we should remove the escapes.
5118 ;; but that requires another match, protecting match data,
5119 ;; a lot of overhead for font-lock.
5120 (ip (org-maybe-intangible
5121 (list 'invisible 'org-link
5122 'keymap org-mouse-map 'mouse-face 'highlight
5123 'font-lock-multiline t 'help-echo help)))
5124 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5125 'font-lock-multiline t 'help-echo help)))
5126 ;; We need to remove the invisible property here. Table narrowing
5127 ;; may have made some of this invisible.
5128 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5129 (remove-text-properties (match-beginning 0) (match-end 0)
5130 '(invisible nil))
5131 (if (match-end 3)
5132 (progn
5133 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5134 (org-rear-nonsticky-at (match-beginning 3))
5135 (add-text-properties (match-beginning 3) (match-end 3) vp)
5136 (org-rear-nonsticky-at (match-end 3))
5137 (add-text-properties (match-end 3) (match-end 0) ip)
5138 (org-rear-nonsticky-at (match-end 0)))
5139 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5140 (org-rear-nonsticky-at (match-beginning 1))
5141 (add-text-properties (match-beginning 1) (match-end 1) vp)
5142 (org-rear-nonsticky-at (match-end 1))
5143 (add-text-properties (match-end 1) (match-end 0) ip)
5144 (org-rear-nonsticky-at (match-end 0)))
5145 t)))
5147 (defun org-activate-dates (limit)
5148 "Run through the buffer and add overlays to dates."
5149 (if (re-search-forward org-tsr-regexp-both limit t)
5150 (progn
5151 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5152 (add-text-properties (match-beginning 0) (match-end 0)
5153 (list 'mouse-face 'highlight
5154 'keymap org-mouse-map))
5155 (org-rear-nonsticky-at (match-end 0))
5156 (when org-display-custom-times
5157 (if (match-end 3)
5158 (org-display-custom-time (match-beginning 3) (match-end 3)))
5159 (org-display-custom-time (match-beginning 1) (match-end 1)))
5160 t)))
5162 (defvar org-target-link-regexp nil
5163 "Regular expression matching radio targets in plain text.")
5164 (make-variable-buffer-local 'org-target-link-regexp)
5165 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5166 "Regular expression matching a link target.")
5167 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5168 "Regular expression matching a radio target.")
5169 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5170 "Regular expression matching any target.")
5172 (defun org-activate-target-links (limit)
5173 "Run through the buffer and add overlays to target matches."
5174 (when org-target-link-regexp
5175 (let ((case-fold-search t))
5176 (if (re-search-forward org-target-link-regexp limit t)
5177 (progn
5178 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5179 (add-text-properties (match-beginning 0) (match-end 0)
5180 (list 'mouse-face 'highlight
5181 'keymap org-mouse-map
5182 'help-echo "Radio target link"
5183 'org-linked-text t))
5184 (org-rear-nonsticky-at (match-end 0))
5185 t)))))
5187 (defun org-update-radio-target-regexp ()
5188 "Find all radio targets in this file and update the regular expression."
5189 (interactive)
5190 (when (memq 'radio org-activate-links)
5191 (setq org-target-link-regexp
5192 (org-make-target-link-regexp (org-all-targets 'radio)))
5193 (org-restart-font-lock)))
5195 (defun org-hide-wide-columns (limit)
5196 (let (s e)
5197 (setq s (text-property-any (point) (or limit (point-max))
5198 'org-cwidth t))
5199 (when s
5200 (setq e (next-single-property-change s 'org-cwidth))
5201 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5202 (goto-char e)
5203 t)))
5205 (defvar org-latex-and-specials-regexp nil
5206 "Regular expression for highlighting export special stuff.")
5207 (defvar org-match-substring-regexp)
5208 (defvar org-match-substring-with-braces-regexp)
5210 ;; This should be with the exporter code, but we also use if for font-locking
5211 (defconst org-export-html-special-string-regexps
5212 '(("\\\\-" . "&shy;")
5213 ("---\\([^-]\\)" . "&mdash;\\1")
5214 ("--\\([^-]\\)" . "&ndash;\\1")
5215 ("\\.\\.\\." . "&hellip;"))
5216 "Regular expressions for special string conversion.")
5219 (defun org-compute-latex-and-specials-regexp ()
5220 "Compute regular expression for stuff treated specially by exporters."
5221 (if (not org-highlight-latex-fragments-and-specials)
5222 (org-set-local 'org-latex-and-specials-regexp nil)
5223 (require 'org-exp)
5224 (let*
5225 ((matchers (plist-get org-format-latex-options :matchers))
5226 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5227 org-latex-regexps)))
5228 (org-export-allow-BIND nil)
5229 (options (org-combine-plists (org-default-export-plist)
5230 (org-infile-export-plist)))
5231 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5232 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5233 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5234 (org-export-html-expand (plist-get options :expand-quoted-html))
5235 (org-export-with-special-strings (plist-get options :special-strings))
5236 (re-sub
5237 (cond
5238 ((equal org-export-with-sub-superscripts '{})
5239 (list org-match-substring-with-braces-regexp))
5240 (org-export-with-sub-superscripts
5241 (list org-match-substring-regexp))
5242 (t nil)))
5243 (re-latex
5244 (if org-export-with-LaTeX-fragments
5245 (mapcar (lambda (x) (nth 1 x)) latexs)))
5246 (re-macros
5247 (if org-export-with-TeX-macros
5248 (list (concat "\\\\"
5249 (regexp-opt
5250 (append
5252 (delq nil
5253 (mapcar 'car-safe
5254 (append org-entities-user
5255 org-entities)))
5256 (if (boundp 'org-latex-entities)
5257 (mapcar (lambda (x)
5258 (or (car-safe x) x))
5259 org-latex-entities)
5260 nil))
5261 'words))) ; FIXME
5263 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5264 (re-special (if org-export-with-special-strings
5265 (mapcar (lambda (x) (car x))
5266 org-export-html-special-string-regexps)))
5267 (re-rest
5268 (delq nil
5269 (list
5270 (if org-export-html-expand "@<[^>\n]+>")
5271 ))))
5272 (org-set-local
5273 'org-latex-and-specials-regexp
5274 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5275 re-rest) "\\|")))))
5277 (defun org-do-latex-and-special-faces (limit)
5278 "Run through the buffer and add overlays to links."
5279 (when org-latex-and-specials-regexp
5280 (let (rtn d)
5281 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5282 limit t))
5283 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5284 'face))
5285 '(org-code org-verbatim underline)))
5286 (progn
5287 (setq rtn t
5288 d (cond ((member (char-after (1+ (match-beginning 0)))
5289 '(?_ ?^)) 1)
5290 (t 0)))
5291 (font-lock-prepend-text-property
5292 (+ d (match-beginning 0)) (match-end 0)
5293 'face 'org-latex-and-export-specials)
5294 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5295 '(font-lock-multiline t)))))
5296 rtn)))
5298 (defun org-restart-font-lock ()
5299 "Restart `font-lock-mode', to force refontification."
5300 (when (and (boundp 'font-lock-mode) font-lock-mode)
5301 (font-lock-mode -1)
5302 (font-lock-mode 1)))
5304 (defun org-all-targets (&optional radio)
5305 "Return a list of all targets in this file.
5306 With optional argument RADIO, only find radio targets."
5307 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5308 rtn)
5309 (save-excursion
5310 (goto-char (point-min))
5311 (while (re-search-forward re nil t)
5312 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5313 rtn)))
5315 (defun org-make-target-link-regexp (targets)
5316 "Make regular expression matching all strings in TARGETS.
5317 The regular expression finds the targets also if there is a line break
5318 between words."
5319 (and targets
5320 (concat
5321 "\\<\\("
5322 (mapconcat
5323 (lambda (x)
5324 (while (string-match " +" x)
5325 (setq x (replace-match "\\s-+" t t x)))
5327 targets
5328 "\\|")
5329 "\\)\\>")))
5331 (defun org-activate-tags (limit)
5332 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
5333 (progn
5334 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5335 (add-text-properties (match-beginning 1) (match-end 1)
5336 (list 'mouse-face 'highlight
5337 'keymap org-mouse-map))
5338 (org-rear-nonsticky-at (match-end 1))
5339 t)))
5341 (defun org-outline-level ()
5342 "Compute the outline level of the heading at point.
5343 This function assumes that the cursor is at the beginning of a line matched
5344 by `outline-regexp'. Otherwise it returns garbage.
5345 If this is called at a normal headline, the level is the number of stars.
5346 Use `org-reduced-level' to remove the effect of `org-odd-levels'.
5347 For plain list items, if they are matched by `outline-regexp', this returns
5348 1000 plus the line indentation."
5349 (save-excursion
5350 (looking-at outline-regexp)
5351 (if (match-beginning 1)
5352 (+ (org-get-string-indentation (match-string 1)) 1000)
5353 (1- (- (match-end 0) (match-beginning 0))))))
5355 (defvar org-font-lock-keywords nil)
5357 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5358 "Regular expression matching a property line.")
5360 (defvar org-font-lock-hook nil
5361 "Functions to be called for special font lock stuff.")
5363 (defun org-font-lock-hook (limit)
5364 (run-hook-with-args 'org-font-lock-hook limit))
5366 (defun org-set-font-lock-defaults ()
5367 (let* ((em org-fontify-emphasized-text)
5368 (lk org-activate-links)
5369 (org-font-lock-extra-keywords
5370 (list
5371 ;; Call the hook
5372 '(org-font-lock-hook)
5373 ;; Headlines
5374 `(,(if org-fontify-whole-heading-line
5375 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5376 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5377 (1 (org-get-level-face 1))
5378 (2 (org-get-level-face 2))
5379 (3 (org-get-level-face 3)))
5380 ;; Table lines
5381 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5382 (1 'org-table t))
5383 ;; Table internals
5384 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5385 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5386 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5387 '("| *\\(<[lr]?[0-9]*>\\)" (1 'org-formula t))
5388 ;; Drawers
5389 (list org-drawer-regexp '(0 'org-special-keyword t))
5390 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5391 ;; Properties
5392 (list org-property-re
5393 '(1 'org-special-keyword t)
5394 '(3 'org-property-value t))
5395 ;; Links
5396 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5397 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5398 (if (memq 'plain lk) '(org-activate-plain-links))
5399 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5400 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5401 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5402 (if (memq 'footnote lk) '(org-activate-footnote-links
5403 (2 'org-footnote t)))
5404 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5405 '(org-hide-wide-columns (0 nil append))
5406 ;; TODO lines
5407 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
5408 '(1 (org-get-todo-face 1) t))
5409 ;; DONE
5410 (if org-fontify-done-headline
5411 (list (concat "^[*]+ +\\<\\("
5412 (mapconcat 'regexp-quote org-done-keywords "\\|")
5413 "\\)\\(.*\\)")
5414 '(2 'org-headline-done t))
5415 nil)
5416 ;; Priorities
5417 '(org-font-lock-add-priority-faces)
5418 ;; Tags
5419 '(org-font-lock-add-tag-faces)
5420 ;; Special keywords
5421 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5422 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5423 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5424 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5425 ;; Emphasis
5426 (if em
5427 (if (featurep 'xemacs)
5428 '(org-do-emphasis-faces (0 nil append))
5429 '(org-do-emphasis-faces)))
5430 ;; Checkboxes
5431 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5432 2 'org-checkbox prepend)
5433 (if org-provide-checkbox-statistics
5434 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5435 (0 (org-get-checkbox-statistics-face) t)))
5436 ;; Description list items
5437 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
5438 2 'bold prepend)
5439 ;; ARCHIVEd headings
5440 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5441 '(1 'org-archived prepend))
5442 ;; Specials
5443 '(org-do-latex-and-special-faces)
5444 '(org-fontify-entities)
5445 '(org-raise-scripts)
5446 ;; Code
5447 '(org-activate-code (1 'org-code t))
5448 ;; COMMENT
5449 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5450 "\\|" org-quote-string "\\)\\>")
5451 '(1 'org-special-keyword t))
5452 '("^#.*" (0 'font-lock-comment-face t))
5453 ;; Blocks and meta lines
5454 '(org-fontify-meta-lines-and-blocks)
5456 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5457 ;; Now set the full font-lock-keywords
5458 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5459 (org-set-local 'font-lock-defaults
5460 '(org-font-lock-keywords t nil nil backward-paragraph))
5461 (kill-local-variable 'font-lock-keywords) nil))
5463 (defun org-toggle-pretty-entities ()
5464 "Toggle the composition display of entities as UTF8 characters."
5465 (interactive)
5466 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5467 (org-restart-font-lock)
5468 (if org-pretty-entities
5469 (message "Entities are displayed as UTF8 characers")
5470 (save-restriction
5471 (widen)
5472 (decompose-region (point-min) (point-max))
5473 (message "Entities are displayed plain"))))
5475 (defun org-fontify-entities (limit)
5476 "Find an entity to fontify."
5477 (let (ee)
5478 (when org-pretty-entities
5479 (catch 'match
5480 (while (re-search-forward
5481 "\\\\\\([a-zA-Z][a-zA-Z0-9]*\\)\\($\\|[^[:alnum:]\n]\\)"
5482 limit t)
5483 (if (and (not (org-in-indented-comment-line))
5484 (setq ee (org-entity-get (match-string 1)))
5485 (= (length (nth 6 ee)) 1))
5486 (progn
5487 (add-text-properties
5488 (match-beginning 0) (match-end 1)
5489 (list 'font-lock-fontified t))
5490 (compose-region (match-beginning 0) (match-end 1)
5491 (nth 6 ee) nil)
5492 (backward-char 1)
5493 (throw 'match t))))
5494 nil))))
5496 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5497 "Fontify string S like in Org-mode."
5498 (with-temp-buffer
5499 (insert s)
5500 (let ((org-odd-levels-only odd-levels))
5501 (org-mode)
5502 (font-lock-fontify-buffer)
5503 (buffer-string))))
5505 (defvar org-m nil)
5506 (defvar org-l nil)
5507 (defvar org-f nil)
5508 (defun org-get-level-face (n)
5509 "Get the right face for match N in font-lock matching of headlines."
5510 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5511 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5512 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5513 (cond
5514 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5515 ((eq n 2) org-f)
5516 (t (if org-level-color-stars-only nil org-f))))
5518 (defun org-get-todo-face (kwd)
5519 "Get the right face for a TODO keyword KWD.
5520 If KWD is a number, get the corresponding match group."
5521 (if (numberp kwd) (setq kwd (match-string kwd)))
5522 (or (org-face-from-face-or-color
5523 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5524 (and (member kwd org-done-keywords) 'org-done)
5525 'org-todo))
5527 (defun org-face-from-face-or-color (context inherit face-or-color)
5528 "Create a face list that inherits INHERIT, but sets the foreground color.
5529 When FACE-OR-COLOR is not a string, just return it."
5530 (if (stringp face-or-color)
5531 (list :inherit inherit
5532 (cdr (assoc context org-faces-easy-properties))
5533 face-or-color)
5534 face-or-color))
5536 (defun org-font-lock-add-tag-faces (limit)
5537 "Add the special tag faces."
5538 (when (and org-tag-faces org-tags-special-faces-re)
5539 (while (re-search-forward org-tags-special-faces-re limit t)
5540 (add-text-properties (match-beginning 1) (match-end 1)
5541 (list 'face (org-get-tag-face 1)
5542 'font-lock-fontified t))
5543 (backward-char 1))))
5545 (defun org-font-lock-add-priority-faces (limit)
5546 "Add the special priority faces."
5547 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5548 (add-text-properties
5549 (match-beginning 0) (match-end 0)
5550 (list 'face (or (org-face-from-face-or-color
5551 'priority 'org-special-keyword
5552 (cdr (assoc (char-after (match-beginning 1))
5553 org-priority-faces)))
5554 'org-special-keyword)
5555 'font-lock-fontified t))))
5557 (defun org-get-tag-face (kwd)
5558 "Get the right face for a TODO keyword KWD.
5559 If KWD is a number, get the corresponding match group."
5560 (if (numberp kwd) (setq kwd (match-string kwd)))
5561 (or (org-face-from-face-or-color
5562 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5563 'org-tag))
5565 (defun org-unfontify-region (beg end &optional maybe_loudly)
5566 "Remove fontification and activation overlays from links."
5567 (font-lock-default-unfontify-region beg end)
5568 (let* ((buffer-undo-list t)
5569 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5570 (inhibit-modification-hooks t)
5571 deactivate-mark buffer-file-name buffer-file-truename)
5572 (decompose-region beg end)
5573 (remove-text-properties
5574 beg end
5575 (if org-indent-mode
5576 ;; also remove line-prefix and wrap-prefix properties
5577 '(mouse-face t keymap t org-linked-text t
5578 invisible t intangible t
5579 line-prefix t wrap-prefix t
5580 org-no-flyspell t org-emphasis t)
5581 '(mouse-face t keymap t org-linked-text t
5582 invisible t intangible t
5583 org-no-flyspell t org-emphasis t)))
5584 (org-remove-font-lock-display-properties beg end)))
5586 (defconst org-script-display '(((raise -0.3) (height 0.7))
5587 ((raise 0.3) (height 0.7))
5588 ((raise -0.5))
5589 ((raise 0.5)))
5590 "Display properties for showing superscripts and subscripts.")
5592 (defun org-remove-font-lock-display-properties (beg end)
5593 "Remove specific display properties that have been added by font lock.
5594 The will remove the raise properties that are used to show superscripts
5595 and subscripts."
5596 (let (next prop)
5597 (while (< beg end)
5598 (setq next (next-single-property-change beg 'display nil end)
5599 prop (get-text-property beg 'display))
5600 (if (member prop org-script-display)
5601 (put-text-property beg next 'display nil))
5602 (setq beg next))))
5604 (defun org-raise-scripts (limit)
5605 "Add raise properties to sub/superscripts."
5606 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
5607 (if (re-search-forward
5608 (if (eq org-use-sub-superscripts t)
5609 org-match-substring-regexp
5610 org-match-substring-with-braces-regexp)
5611 limit t)
5612 (let* ((pos (point)) table-p comment-p
5613 (mpos (match-beginning 3))
5614 (emph-p (get-text-property mpos 'org-emphasis))
5615 (link-p (get-text-property mpos 'mouse-face))
5616 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
5617 (goto-char (point-at-bol))
5618 (setq table-p (org-looking-at-p org-table-dataline-regexp)
5619 comment-p (org-looking-at-p "[ \t]*#"))
5620 (goto-char pos)
5621 ;; FIXME: Should we go back one character here, for a_b^c
5622 ;; (goto-char (1- pos)) ;????????????????????
5623 (if (or comment-p emph-p link-p keyw-p)
5625 (put-text-property (match-beginning 3) (match-end 0)
5626 'display
5627 (if (equal (char-after (match-beginning 2)) ?^)
5628 (nth (if table-p 3 1) org-script-display)
5629 (nth (if table-p 2 0) org-script-display)))
5630 (add-text-properties (match-beginning 2) (match-end 2)
5631 (list 'invisible t
5632 'org-dwidth t 'org-dwidth-n 1))
5633 (if (and (eq (char-after (match-beginning 3)) ?{)
5634 (eq (char-before (match-end 3)) ?}))
5635 (progn
5636 (add-text-properties
5637 (match-beginning 3) (1+ (match-beginning 3))
5638 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
5639 (add-text-properties
5640 (1- (match-end 3)) (match-end 3)
5641 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
5642 t)))))
5644 ;;;; Visibility cycling, including org-goto and indirect buffer
5646 ;;; Cycling
5648 (defvar org-cycle-global-status nil)
5649 (make-variable-buffer-local 'org-cycle-global-status)
5650 (defvar org-cycle-subtree-status nil)
5651 (make-variable-buffer-local 'org-cycle-subtree-status)
5653 ;;;###autoload
5655 (defvar org-inlinetask-min-level)
5657 (defun org-cycle (&optional arg)
5658 "TAB-action and visibility cycling for Org-mode.
5660 This is the command invoked in Org-mode by the TAB key. Its main purpose
5661 is outline visibility cycling, but it also invokes other actions
5662 in special contexts.
5664 - When this function is called with a prefix argument, rotate the entire
5665 buffer through 3 states (global cycling)
5666 1. OVERVIEW: Show only top-level headlines.
5667 2. CONTENTS: Show all headlines of all levels, but no body text.
5668 3. SHOW ALL: Show everything.
5669 When called with two `C-u C-u' prefixes, switch to the startup visibility,
5670 determined by the variable `org-startup-folded', and by any VISIBILITY
5671 properties in the buffer.
5672 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
5673 including any drawers.
5675 - When inside a table, re-align the table and move to the next field.
5677 - When point is at the beginning of a headline, rotate the subtree started
5678 by this line through 3 different states (local cycling)
5679 1. FOLDED: Only the main headline is shown.
5680 2. CHILDREN: The main headline and the direct children are shown.
5681 From this state, you can move to one of the children
5682 and zoom in further.
5683 3. SUBTREE: Show the entire subtree, including body text.
5684 If there is no subtree, switch directly from CHILDREN to FOLDED.
5686 - When point is at the beginning of an empty headline and the variable
5687 `org-cycle-level-after-item/entry-creation' is set, cycle the level
5688 of the headline by demoting and promoting it to likely levels. This
5689 speeds up creation document structure by pressing TAB once or several
5690 times right after creating a new headline.
5692 - When there is a numeric prefix, go up to a heading with level ARG, do
5693 a `show-subtree' and return to the previous cursor position. If ARG
5694 is negative, go up that many levels.
5696 - When point is not at the beginning of a headline, execute the global
5697 binding for TAB, which is re-indenting the line. See the option
5698 `org-cycle-emulate-tab' for details.
5700 - Special case: if point is at the beginning of the buffer and there is
5701 no headline in line 1, this function will act as if called with prefix arg.
5702 But only if also the variable `org-cycle-global-at-bob' is t."
5703 (interactive "P")
5704 (org-load-modules-maybe)
5705 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
5706 (and org-cycle-level-after-item/entry-creation
5707 (or (org-cycle-level)
5708 (org-cycle-item-indentation))))
5709 (let* ((limit-level
5710 (or org-cycle-max-level
5711 (and (boundp 'org-inlinetask-min-level)
5712 org-inlinetask-min-level
5713 (1- org-inlinetask-min-level))))
5714 (nstars (and limit-level
5715 (if org-odd-levels-only
5716 (and limit-level (1- (* limit-level 2)))
5717 limit-level)))
5718 (outline-regexp
5719 (cond
5720 ((not (org-mode-p)) outline-regexp)
5721 ((or (eq org-cycle-include-plain-lists 'integrate)
5722 (and org-cycle-include-plain-lists (org-at-item-p)))
5723 (concat "\\(?:\\*"
5724 (if nstars (format "\\{1,%d\\}" nstars) "+")
5725 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
5726 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
5727 (bob-special (and org-cycle-global-at-bob (bobp)
5728 (not (looking-at outline-regexp))))
5729 (org-cycle-hook
5730 (if bob-special
5731 (delq 'org-optimize-window-after-visibility-change
5732 (copy-sequence org-cycle-hook))
5733 org-cycle-hook))
5734 (pos (point)))
5736 (if (or bob-special (equal arg '(4)))
5737 ;; special case: use global cycling
5738 (setq arg t))
5740 (cond
5742 ((equal arg '(16))
5743 (org-set-startup-visibility)
5744 (message "Startup visibility, plus VISIBILITY properties"))
5746 ((equal arg '(64))
5747 (show-all)
5748 (message "Entire buffer visible, including drawers"))
5750 ((org-at-table-p 'any)
5751 ;; Enter the table or move to the next field in the table
5752 (if (org-at-table.el-p)
5753 (message "Use C-c ' to edit table.el tables")
5754 (if arg (org-table-edit-field t)
5755 (org-table-justify-field-maybe)
5756 (call-interactively 'org-table-next-field))))
5758 ((run-hook-with-args-until-success
5759 'org-tab-after-check-for-table-hook))
5761 ((eq arg t) ;; Global cycling
5762 (org-cycle-internal-global))
5764 ((and org-drawers org-drawer-regexp
5765 (save-excursion
5766 (beginning-of-line 1)
5767 (looking-at org-drawer-regexp)))
5768 ;; Toggle block visibility
5769 (org-flag-drawer
5770 (not (get-char-property (match-end 0) 'invisible))))
5772 ((integerp arg)
5773 ;; Show-subtree, ARG levels up from here.
5774 (save-excursion
5775 (org-back-to-heading)
5776 (outline-up-heading (if (< arg 0) (- arg)
5777 (- (funcall outline-level) arg)))
5778 (org-show-subtree)))
5780 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5781 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5783 (org-cycle-internal-local))
5785 ;; TAB emulation and template completion
5786 (buffer-read-only (org-back-to-heading))
5788 ((run-hook-with-args-until-success
5789 'org-tab-after-check-for-cycling-hook))
5791 ((org-try-structure-completion))
5793 ((org-try-cdlatex-tab))
5795 ((run-hook-with-args-until-success
5796 'org-tab-before-tab-emulation-hook))
5798 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5799 (or (not (bolp))
5800 (not (looking-at outline-regexp))))
5801 (call-interactively (global-key-binding "\t")))
5803 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5804 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5805 (or (and (eq org-cycle-emulate-tab 'white)
5806 (= (match-end 0) (point-at-eol)))
5807 (and (eq org-cycle-emulate-tab 'whitestart)
5808 (>= (match-end 0) pos))))
5810 (eq org-cycle-emulate-tab t))
5811 (call-interactively (global-key-binding "\t")))
5813 (t (save-excursion
5814 (org-back-to-heading)
5815 (org-cycle)))))))
5817 (defun org-cycle-internal-global ()
5818 "Do the global cycling action."
5819 (cond
5820 ((and (eq last-command this-command)
5821 (eq org-cycle-global-status 'overview))
5822 ;; We just created the overview - now do table of contents
5823 ;; This can be slow in very large buffers, so indicate action
5824 (run-hook-with-args 'org-pre-cycle-hook 'contents)
5825 (message "CONTENTS...")
5826 (org-content)
5827 (message "CONTENTS...done")
5828 (setq org-cycle-global-status 'contents)
5829 (run-hook-with-args 'org-cycle-hook 'contents))
5831 ((and (eq last-command this-command)
5832 (eq org-cycle-global-status 'contents))
5833 ;; We just showed the table of contents - now show everything
5834 (run-hook-with-args 'org-pre-cycle-hook 'all)
5835 (show-all)
5836 (message "SHOW ALL")
5837 (setq org-cycle-global-status 'all)
5838 (run-hook-with-args 'org-cycle-hook 'all))
5841 ;; Default action: go to overview
5842 (run-hook-with-args 'org-pre-cycle-hook 'overview)
5843 (org-overview)
5844 (message "OVERVIEW")
5845 (setq org-cycle-global-status 'overview)
5846 (run-hook-with-args 'org-cycle-hook 'overview))))
5848 (defun org-cycle-internal-local ()
5849 "Do the local cycling action."
5850 (org-back-to-heading)
5851 (let ((goal-column 0) eoh eol eos level has-children children-skipped)
5852 ;; First, some boundaries
5853 (save-excursion
5854 (org-back-to-heading)
5855 (setq level (funcall outline-level))
5856 (save-excursion
5857 (beginning-of-line 2)
5858 (if (or (featurep 'xemacs) (<= emacs-major-version 21))
5859 ; XEmacs does not have `next-single-char-property-change'
5860 ; I'm not sure about Emacs 21.
5861 (while (and (not (eobp)) ;; this is like `next-line'
5862 (get-char-property (1- (point)) 'invisible))
5863 (beginning-of-line 2))
5864 (while (and (not (eobp)) ;; this is like `next-line'
5865 (get-char-property (1- (point)) 'invisible))
5866 (goto-char (next-single-char-property-change (point) 'invisible))
5867 (and (eolp) (beginning-of-line 2))))
5868 (setq eol (point)))
5869 (outline-end-of-heading) (setq eoh (point))
5870 (save-excursion
5871 (outline-next-heading)
5872 (setq has-children (and (org-at-heading-p t)
5873 (> (funcall outline-level) level))))
5874 (org-end-of-subtree t)
5875 (unless (eobp)
5876 (skip-chars-forward " \t\n")
5877 (beginning-of-line 1) ; in case this is an item
5879 (setq eos (if (eobp) (point) (1- (point)))))
5880 ;; Find out what to do next and set `this-command'
5881 (cond
5882 ((= eos eoh)
5883 ;; Nothing is hidden behind this heading
5884 (run-hook-with-args 'org-pre-cycle-hook 'empty)
5885 (message "EMPTY ENTRY")
5886 (setq org-cycle-subtree-status nil)
5887 (save-excursion
5888 (goto-char eos)
5889 (outline-next-heading)
5890 (if (org-invisible-p) (org-flag-heading nil))))
5891 ((and (or (>= eol eos)
5892 (not (string-match "\\S-" (buffer-substring eol eos))))
5893 (or has-children
5894 (not (setq children-skipped
5895 org-cycle-skip-children-state-if-no-children))))
5896 ;; Entire subtree is hidden in one line: children view
5897 (run-hook-with-args 'org-pre-cycle-hook 'children)
5898 (org-show-entry)
5899 (show-children)
5900 (message "CHILDREN")
5901 (save-excursion
5902 (goto-char eos)
5903 (outline-next-heading)
5904 (if (org-invisible-p) (org-flag-heading nil)))
5905 (setq org-cycle-subtree-status 'children)
5906 (run-hook-with-args 'org-cycle-hook 'children))
5907 ((or children-skipped
5908 (and (eq last-command this-command)
5909 (eq org-cycle-subtree-status 'children)))
5910 ;; We just showed the children, or no children are there,
5911 ;; now show everything.
5912 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
5913 (org-show-subtree)
5914 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
5915 (setq org-cycle-subtree-status 'subtree)
5916 (run-hook-with-args 'org-cycle-hook 'subtree))
5918 ;; Default action: hide the subtree.
5919 (run-hook-with-args 'org-pre-cycle-hook 'folded)
5920 (hide-subtree)
5921 (message "FOLDED")
5922 (setq org-cycle-subtree-status 'folded)
5923 (run-hook-with-args 'org-cycle-hook 'folded)))))
5925 ;;;###autoload
5926 (defun org-global-cycle (&optional arg)
5927 "Cycle the global visibility. For details see `org-cycle'.
5928 With \\[universal-argument] prefix arg, switch to startup visibility.
5929 With a numeric prefix, show all headlines up to that level."
5930 (interactive "P")
5931 (let ((org-cycle-include-plain-lists
5932 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5933 (cond
5934 ((integerp arg)
5935 (show-all)
5936 (hide-sublevels arg)
5937 (setq org-cycle-global-status 'contents))
5938 ((equal arg '(4))
5939 (org-set-startup-visibility)
5940 (message "Startup visibility, plus VISIBILITY properties."))
5942 (org-cycle '(4))))))
5944 (defun org-set-startup-visibility ()
5945 "Set the visibility required by startup options and properties."
5946 (cond
5947 ((eq org-startup-folded t)
5948 (org-cycle '(4)))
5949 ((eq org-startup-folded 'content)
5950 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5951 (org-cycle '(4)) (org-cycle '(4)))))
5952 (unless (eq org-startup-folded 'showeverything)
5953 (if org-hide-block-startup (org-hide-block-all))
5954 (org-set-visibility-according-to-property 'no-cleanup)
5955 (org-cycle-hide-archived-subtrees 'all)
5956 (org-cycle-hide-drawers 'all)
5957 (org-cycle-show-empty-lines t)))
5959 (defun org-set-visibility-according-to-property (&optional no-cleanup)
5960 "Switch subtree visibilities according to :VISIBILITY: property."
5961 (interactive)
5962 (let (org-show-entry-below state)
5963 (save-excursion
5964 (goto-char (point-min))
5965 (while (re-search-forward
5966 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
5967 nil t)
5968 (setq state (match-string 1))
5969 (save-excursion
5970 (org-back-to-heading t)
5971 (hide-subtree)
5972 (org-reveal)
5973 (cond
5974 ((equal state '("fold" "folded"))
5975 (hide-subtree))
5976 ((equal state "children")
5977 (org-show-hidden-entry)
5978 (show-children))
5979 ((equal state "content")
5980 (save-excursion
5981 (save-restriction
5982 (org-narrow-to-subtree)
5983 (org-content))))
5984 ((member state '("all" "showall"))
5985 (show-subtree)))))
5986 (unless no-cleanup
5987 (org-cycle-hide-archived-subtrees 'all)
5988 (org-cycle-hide-drawers 'all)
5989 (org-cycle-show-empty-lines 'all)))))
5991 (defun org-overview ()
5992 "Switch to overview mode, showing only top-level headlines.
5993 Really, this shows all headlines with level equal or greater than the level
5994 of the first headline in the buffer. This is important, because if the
5995 first headline is not level one, then (hide-sublevels 1) gives confusing
5996 results."
5997 (interactive)
5998 (let ((level (save-excursion
5999 (goto-char (point-min))
6000 (if (re-search-forward (concat "^" outline-regexp) nil t)
6001 (progn
6002 (goto-char (match-beginning 0))
6003 (funcall outline-level))))))
6004 (and level (hide-sublevels level))))
6006 (defun org-content (&optional arg)
6007 "Show all headlines in the buffer, like a table of contents.
6008 With numerical argument N, show content up to level N."
6009 (interactive "P")
6010 (save-excursion
6011 ;; Visit all headings and show their offspring
6012 (and (integerp arg) (org-overview))
6013 (goto-char (point-max))
6014 (catch 'exit
6015 (while (and (progn (condition-case nil
6016 (outline-previous-visible-heading 1)
6017 (error (goto-char (point-min))))
6019 (looking-at outline-regexp))
6020 (if (integerp arg)
6021 (show-children (1- arg))
6022 (show-branches))
6023 (if (bobp) (throw 'exit nil))))))
6026 (defun org-optimize-window-after-visibility-change (state)
6027 "Adjust the window after a change in outline visibility.
6028 This function is the default value of the hook `org-cycle-hook'."
6029 (when (get-buffer-window (current-buffer))
6030 (cond
6031 ((eq state 'content) nil)
6032 ((eq state 'all) nil)
6033 ((eq state 'folded) nil)
6034 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6035 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6037 (defun org-remove-empty-overlays-at (pos)
6038 "Remove outline overlays that do not contain non-white stuff."
6039 (mapc
6040 (lambda (o)
6041 (and (eq 'outline (overlay-get o 'invisible))
6042 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6043 (overlay-end o))))
6044 (delete-overlay o)))
6045 (overlays-at pos)))
6047 (defun org-clean-visibility-after-subtree-move ()
6048 "Fix visibility issues after moving a subtree."
6049 ;; First, find a reasonable region to look at:
6050 ;; Start two siblings above, end three below
6051 (let* ((beg (save-excursion
6052 (and (org-get-last-sibling)
6053 (org-get-last-sibling))
6054 (point)))
6055 (end (save-excursion
6056 (and (org-get-next-sibling)
6057 (org-get-next-sibling)
6058 (org-get-next-sibling))
6059 (if (org-at-heading-p)
6060 (point-at-eol)
6061 (point))))
6062 (level (looking-at "\\*+"))
6063 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6064 (save-excursion
6065 (save-restriction
6066 (narrow-to-region beg end)
6067 (when re
6068 ;; Properly fold already folded siblings
6069 (goto-char (point-min))
6070 (while (re-search-forward re nil t)
6071 (if (and (not (org-invisible-p))
6072 (save-excursion
6073 (goto-char (point-at-eol)) (org-invisible-p)))
6074 (hide-entry))))
6075 (org-cycle-show-empty-lines 'overview)
6076 (org-cycle-hide-drawers 'overview)))))
6078 (defun org-cycle-show-empty-lines (state)
6079 "Show empty lines above all visible headlines.
6080 The region to be covered depends on STATE when called through
6081 `org-cycle-hook'. Lisp program can use t for STATE to get the
6082 entire buffer covered. Note that an empty line is only shown if there
6083 are at least `org-cycle-separator-lines' empty lines before the headline."
6084 (when (not (= org-cycle-separator-lines 0))
6085 (save-excursion
6086 (let* ((n (abs org-cycle-separator-lines))
6087 (re (cond
6088 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6089 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6090 (t (let ((ns (number-to-string (- n 2))))
6091 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6092 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6093 beg end b e)
6094 (cond
6095 ((memq state '(overview contents t))
6096 (setq beg (point-min) end (point-max)))
6097 ((memq state '(children folded))
6098 (setq beg (point) end (progn (org-end-of-subtree t t)
6099 (beginning-of-line 2)
6100 (point)))))
6101 (when beg
6102 (goto-char beg)
6103 (while (re-search-forward re end t)
6104 (unless (get-char-property (match-end 1) 'invisible)
6105 (setq e (match-end 1))
6106 (if (< org-cycle-separator-lines 0)
6107 (setq b (save-excursion
6108 (goto-char (match-beginning 0))
6109 (org-back-over-empty-lines)
6110 (if (save-excursion
6111 (goto-char (max (point-min) (1- (point))))
6112 (org-on-heading-p))
6113 (1- (point))
6114 (point))))
6115 (setq b (match-beginning 1)))
6116 (outline-flag-region b e nil)))))))
6117 ;; Never hide empty lines at the end of the file.
6118 (save-excursion
6119 (goto-char (point-max))
6120 (outline-previous-heading)
6121 (outline-end-of-heading)
6122 (if (and (looking-at "[ \t\n]+")
6123 (= (match-end 0) (point-max)))
6124 (outline-flag-region (point) (match-end 0) nil))))
6126 (defun org-show-empty-lines-in-parent ()
6127 "Move to the parent and re-show empty lines before visible headlines."
6128 (save-excursion
6129 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6130 (org-cycle-show-empty-lines context))))
6132 (defun org-files-list ()
6133 "Return `org-agenda-files' list, plus all open org-mode files.
6134 This is useful for operations that need to scan all of a user's
6135 open and agenda-wise Org files."
6136 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6137 (dolist (buf (buffer-list))
6138 (with-current-buffer buf
6139 (if (and (eq major-mode 'org-mode) (buffer-file-name))
6140 (let ((file (expand-file-name (buffer-file-name))))
6141 (unless (member file files)
6142 (push file files))))))
6143 files))
6145 (defsubst org-entry-beginning-position ()
6146 "Return the beginning position of the current entry."
6147 (save-excursion (outline-back-to-heading t) (point)))
6149 (defsubst org-entry-end-position ()
6150 "Return the end position of the current entry."
6151 (save-excursion (outline-next-heading) (point)))
6153 (defun org-cycle-hide-drawers (state)
6154 "Re-hide all drawers after a visibility state change."
6155 (when (and (org-mode-p)
6156 (not (memq state '(overview folded contents))))
6157 (save-excursion
6158 (let* ((globalp (memq state '(contents all)))
6159 (beg (if globalp (point-min) (point)))
6160 (end (if globalp (point-max)
6161 (if (eq state 'children)
6162 (save-excursion (outline-next-heading) (point))
6163 (org-end-of-subtree t)))))
6164 (goto-char beg)
6165 (while (re-search-forward org-drawer-regexp end t)
6166 (org-flag-drawer t))))))
6168 (defun org-flag-drawer (flag)
6169 (save-excursion
6170 (beginning-of-line 1)
6171 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6172 (let ((b (match-end 0))
6173 (outline-regexp org-outline-regexp))
6174 (if (re-search-forward
6175 "^[ \t]*:END:"
6176 (save-excursion (outline-next-heading) (point)) t)
6177 (outline-flag-region b (point-at-eol) flag)
6178 (error ":END: line missing at position %s" b))))))
6180 (defun org-subtree-end-visible-p ()
6181 "Is the end of the current subtree visible?"
6182 (pos-visible-in-window-p
6183 (save-excursion (org-end-of-subtree t) (point))))
6185 (defun org-first-headline-recenter (&optional N)
6186 "Move cursor to the first headline and recenter the headline.
6187 Optional argument N means put the headline into the Nth line of the window."
6188 (goto-char (point-min))
6189 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
6190 (beginning-of-line)
6191 (recenter (prefix-numeric-value N))))
6193 ;;; Saving and restoring visibility
6195 (defun org-outline-overlay-data (&optional use-markers)
6196 "Return a list of the locations of all outline overlays.
6197 The are overlays with the `invisible' property value `outline'.
6198 The return values is a list of cons cells, with start and stop
6199 positions for each overlay.
6200 If USE-MARKERS is set, return the positions as markers."
6201 (let (beg end)
6202 (save-excursion
6203 (save-restriction
6204 (widen)
6205 (delq nil
6206 (mapcar (lambda (o)
6207 (when (eq (overlay-get o 'invisible) 'outline)
6208 (setq beg (overlay-start o)
6209 end (overlay-end o))
6210 (and beg end (> end beg)
6211 (if use-markers
6212 (cons (move-marker (make-marker) beg)
6213 (move-marker (make-marker) end))
6214 (cons beg end)))))
6215 (overlays-in (point-min) (point-max))))))))
6217 (defun org-set-outline-overlay-data (data)
6218 "Create visibility overlays for all positions in DATA.
6219 DATA should have been made by `org-outline-overlay-data'."
6220 (let (o)
6221 (save-excursion
6222 (save-restriction
6223 (widen)
6224 (show-all)
6225 (mapc (lambda (c)
6226 (setq o (make-overlay (car c) (cdr c)))
6227 (overlay-put o 'invisible 'outline))
6228 data)))))
6230 (defmacro org-save-outline-visibility (use-markers &rest body)
6231 "Save and restore outline visibility around BODY.
6232 If USE-MARKERS is non-nil, use markers for the positions.
6233 This means that the buffer may change while running BODY,
6234 but it also means that the buffer should stay alive
6235 during the operation, because otherwise all these markers will
6236 point nowhere."
6237 (declare (indent 1))
6238 `(let ((data (org-outline-overlay-data ,use-markers)))
6239 (unwind-protect
6240 (progn
6241 ,@body
6242 (org-set-outline-overlay-data data))
6243 (when ,use-markers
6244 (mapc (lambda (c)
6245 (and (markerp (car c)) (move-marker (car c) nil))
6246 (and (markerp (cdr c)) (move-marker (cdr c) nil)))
6247 data)))))
6250 ;;; Folding of blocks
6252 (defconst org-block-regexp
6254 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
6255 "Regular expression for hiding blocks.")
6257 (defvar org-hide-block-overlays nil
6258 "Overlays hiding blocks.")
6259 (make-variable-buffer-local 'org-hide-block-overlays)
6261 (defun org-block-map (function &optional start end)
6262 "Call FUNCTION at the head of all source blocks in the current buffer.
6263 Optional arguments START and END can be used to limit the range."
6264 (let ((start (or start (point-min)))
6265 (end (or end (point-max))))
6266 (save-excursion
6267 (goto-char start)
6268 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6269 (save-excursion
6270 (save-match-data
6271 (goto-char (match-beginning 0))
6272 (funcall function)))))))
6274 (defun org-hide-block-toggle-all ()
6275 "Toggle the visibility of all blocks in the current buffer."
6276 (org-block-map #'org-hide-block-toggle))
6278 (defun org-hide-block-all ()
6279 "Fold all blocks in the current buffer."
6280 (interactive)
6281 (org-show-block-all)
6282 (org-block-map #'org-hide-block-toggle-maybe))
6284 (defun org-show-block-all ()
6285 "Unfold all blocks in the current buffer."
6286 (interactive)
6287 (mapc 'delete-overlay org-hide-block-overlays)
6288 (setq org-hide-block-overlays nil))
6290 (defun org-hide-block-toggle-maybe ()
6291 "Toggle visibility of block at point."
6292 (interactive)
6293 (let ((case-fold-search t))
6294 (if (save-excursion
6295 (beginning-of-line 1)
6296 (looking-at org-block-regexp))
6297 (progn (org-hide-block-toggle)
6298 t) ;; to signal that we took action
6299 nil))) ;; to signal that we did not
6301 (defun org-hide-block-toggle (&optional force)
6302 "Toggle the visibility of the current block."
6303 (interactive)
6304 (save-excursion
6305 (beginning-of-line)
6306 (if (re-search-forward org-block-regexp nil t)
6307 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6308 (end (match-end 0)) ;; end of entire body
6310 (if (memq t (mapcar (lambda (overlay)
6311 (eq (overlay-get overlay 'invisible)
6312 'org-hide-block))
6313 (overlays-at start)))
6314 (if (or (not force) (eq force 'off))
6315 (mapc (lambda (ov)
6316 (when (member ov org-hide-block-overlays)
6317 (setq org-hide-block-overlays
6318 (delq ov org-hide-block-overlays)))
6319 (when (eq (overlay-get ov 'invisible)
6320 'org-hide-block)
6321 (delete-overlay ov)))
6322 (overlays-at start)))
6323 (setq ov (make-overlay start end))
6324 (overlay-put ov 'invisible 'org-hide-block)
6325 ;; make the block accessible to isearch
6326 (overlay-put
6327 ov 'isearch-open-invisible
6328 (lambda (ov)
6329 (when (member ov org-hide-block-overlays)
6330 (setq org-hide-block-overlays
6331 (delq ov org-hide-block-overlays)))
6332 (when (eq (overlay-get ov 'invisible)
6333 'org-hide-block)
6334 (delete-overlay ov))))
6335 (push ov org-hide-block-overlays)))
6336 (error "Not looking at a source block"))))
6338 ;; org-tab-after-check-for-cycling-hook
6339 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6340 ;; Remove overlays when changing major mode
6341 (add-hook 'org-mode-hook
6342 (lambda () (org-add-hook 'change-major-mode-hook
6343 'org-show-block-all 'append 'local)))
6345 ;;; Org-goto
6347 (defvar org-goto-window-configuration nil)
6348 (defvar org-goto-marker nil)
6349 (defvar org-goto-map
6350 (let ((map (make-sparse-keymap)))
6351 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6352 (while (setq cmd (pop cmds))
6353 (substitute-key-definition cmd cmd map global-map)))
6354 (suppress-keymap map)
6355 (org-defkey map "\C-m" 'org-goto-ret)
6356 (org-defkey map [(return)] 'org-goto-ret)
6357 (org-defkey map [(left)] 'org-goto-left)
6358 (org-defkey map [(right)] 'org-goto-right)
6359 (org-defkey map [(control ?g)] 'org-goto-quit)
6360 (org-defkey map "\C-i" 'org-cycle)
6361 (org-defkey map [(tab)] 'org-cycle)
6362 (org-defkey map [(down)] 'outline-next-visible-heading)
6363 (org-defkey map [(up)] 'outline-previous-visible-heading)
6364 (if org-goto-auto-isearch
6365 (if (fboundp 'define-key-after)
6366 (define-key-after map [t] 'org-goto-local-auto-isearch)
6367 nil)
6368 (org-defkey map "q" 'org-goto-quit)
6369 (org-defkey map "n" 'outline-next-visible-heading)
6370 (org-defkey map "p" 'outline-previous-visible-heading)
6371 (org-defkey map "f" 'outline-forward-same-level)
6372 (org-defkey map "b" 'outline-backward-same-level)
6373 (org-defkey map "u" 'outline-up-heading))
6374 (org-defkey map "/" 'org-occur)
6375 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6376 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6377 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6378 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6379 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6380 map))
6382 (defconst org-goto-help
6383 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6384 RET=jump to location [Q]uit and return to previous location
6385 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6387 (defvar org-goto-start-pos) ; dynamically scoped parameter
6389 ;; FIXME: Docstring does not mention both interfaces
6390 (defun org-goto (&optional alternative-interface)
6391 "Look up a different location in the current file, keeping current visibility.
6393 When you want look-up or go to a different location in a document, the
6394 fastest way is often to fold the entire buffer and then dive into the tree.
6395 This method has the disadvantage, that the previous location will be folded,
6396 which may not be what you want.
6398 This command works around this by showing a copy of the current buffer
6399 in an indirect buffer, in overview mode. You can dive into the tree in
6400 that copy, use org-occur and incremental search to find a location.
6401 When pressing RET or `Q', the command returns to the original buffer in
6402 which the visibility is still unchanged. After RET is will also jump to
6403 the location selected in the indirect buffer and expose the
6404 the headline hierarchy above."
6405 (interactive "P")
6406 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6407 (org-refile-use-outline-path t)
6408 (org-refile-target-verify-function nil)
6409 (interface
6410 (if (not alternative-interface)
6411 org-goto-interface
6412 (if (eq org-goto-interface 'outline)
6413 'outline-path-completion
6414 'outline)))
6415 (org-goto-start-pos (point))
6416 (selected-point
6417 (if (eq interface 'outline)
6418 (car (org-get-location (current-buffer) org-goto-help))
6419 (nth 3 (org-refile-get-location "Goto: ")))))
6420 (if selected-point
6421 (progn
6422 (org-mark-ring-push org-goto-start-pos)
6423 (goto-char selected-point)
6424 (if (or (org-invisible-p) (org-invisible-p2))
6425 (org-show-context 'org-goto)))
6426 (message "Quit"))))
6428 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6429 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6430 (defvar org-goto-local-auto-isearch-map) ; defined below
6432 (defun org-get-location (buf help)
6433 "Let the user select a location in the Org-mode buffer BUF.
6434 This function uses a recursive edit. It returns the selected position
6435 or nil."
6436 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6437 (isearch-hide-immediately nil)
6438 (isearch-search-fun-function
6439 (lambda () 'org-goto-local-search-headings))
6440 (org-goto-selected-point org-goto-exit-command)
6441 (pop-up-frames nil)
6442 (special-display-buffer-names nil)
6443 (special-display-regexps nil)
6444 (special-display-function nil))
6445 (save-excursion
6446 (save-window-excursion
6447 (delete-other-windows)
6448 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6449 (switch-to-buffer
6450 (condition-case nil
6451 (make-indirect-buffer (current-buffer) "*org-goto*")
6452 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6453 (with-output-to-temp-buffer "*Help*"
6454 (princ help))
6455 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6456 (setq buffer-read-only nil)
6457 (let ((org-startup-truncated t)
6458 (org-startup-folded nil)
6459 (org-startup-align-all-tables nil))
6460 (org-mode)
6461 (org-overview))
6462 (setq buffer-read-only t)
6463 (if (and (boundp 'org-goto-start-pos)
6464 (integer-or-marker-p org-goto-start-pos))
6465 (let ((org-show-hierarchy-above t)
6466 (org-show-siblings t)
6467 (org-show-following-heading t))
6468 (goto-char org-goto-start-pos)
6469 (and (org-invisible-p) (org-show-context)))
6470 (goto-char (point-min)))
6471 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6472 (message "Select location and press RET")
6473 (use-local-map org-goto-map)
6474 (recursive-edit)
6476 (kill-buffer "*org-goto*")
6477 (cons org-goto-selected-point org-goto-exit-command)))
6479 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6480 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6481 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6482 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6484 (defun org-goto-local-search-headings (string bound noerror)
6485 "Search and make sure that any matches are in headlines."
6486 (catch 'return
6487 (while (if isearch-forward
6488 (search-forward string bound noerror)
6489 (search-backward string bound noerror))
6490 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6491 (and (member :headline context)
6492 (not (member :tags context))))
6493 (throw 'return (point))))))
6495 (defun org-goto-local-auto-isearch ()
6496 "Start isearch."
6497 (interactive)
6498 (goto-char (point-min))
6499 (let ((keys (this-command-keys)))
6500 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6501 (isearch-mode t)
6502 (isearch-process-search-char (string-to-char keys)))))
6504 (defun org-goto-ret (&optional arg)
6505 "Finish `org-goto' by going to the new location."
6506 (interactive "P")
6507 (setq org-goto-selected-point (point)
6508 org-goto-exit-command 'return)
6509 (throw 'exit nil))
6511 (defun org-goto-left ()
6512 "Finish `org-goto' by going to the new location."
6513 (interactive)
6514 (if (org-on-heading-p)
6515 (progn
6516 (beginning-of-line 1)
6517 (setq org-goto-selected-point (point)
6518 org-goto-exit-command 'left)
6519 (throw 'exit nil))
6520 (error "Not on a heading")))
6522 (defun org-goto-right ()
6523 "Finish `org-goto' by going to the new location."
6524 (interactive)
6525 (if (org-on-heading-p)
6526 (progn
6527 (setq org-goto-selected-point (point)
6528 org-goto-exit-command 'right)
6529 (throw 'exit nil))
6530 (error "Not on a heading")))
6532 (defun org-goto-quit ()
6533 "Finish `org-goto' without cursor motion."
6534 (interactive)
6535 (setq org-goto-selected-point nil)
6536 (setq org-goto-exit-command 'quit)
6537 (throw 'exit nil))
6539 ;;; Indirect buffer display of subtrees
6541 (defvar org-indirect-dedicated-frame nil
6542 "This is the frame being used for indirect tree display.")
6543 (defvar org-last-indirect-buffer nil)
6545 (defun org-tree-to-indirect-buffer (&optional arg)
6546 "Create indirect buffer and narrow it to current subtree.
6547 With numerical prefix ARG, go up to this level and then take that tree.
6548 If ARG is negative, go up that many levels.
6549 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6550 indirect buffer previously made with this command, to avoid proliferation of
6551 indirect buffers. However, when you call the command with a \
6552 \\[universal-argument] prefix, or
6553 when `org-indirect-buffer-display' is `new-frame', the last buffer
6554 is kept so that you can work with several indirect buffers at the same time.
6555 If `org-indirect-buffer-display' is `dedicated-frame', the \
6556 \\[universal-argument] prefix also
6557 requests that a new frame be made for the new buffer, so that the dedicated
6558 frame is not changed."
6559 (interactive "P")
6560 (let ((cbuf (current-buffer))
6561 (cwin (selected-window))
6562 (pos (point))
6563 beg end level heading ibuf)
6564 (save-excursion
6565 (org-back-to-heading t)
6566 (when (numberp arg)
6567 (setq level (org-outline-level))
6568 (if (< arg 0) (setq arg (+ level arg)))
6569 (while (> (setq level (org-outline-level)) arg)
6570 (outline-up-heading 1 t)))
6571 (setq beg (point)
6572 heading (org-get-heading))
6573 (org-end-of-subtree t t)
6574 (if (org-on-heading-p) (backward-char 1))
6575 (setq end (point)))
6576 (if (and (buffer-live-p org-last-indirect-buffer)
6577 (not (eq org-indirect-buffer-display 'new-frame))
6578 (not arg))
6579 (kill-buffer org-last-indirect-buffer))
6580 (setq ibuf (org-get-indirect-buffer cbuf)
6581 org-last-indirect-buffer ibuf)
6582 (cond
6583 ((or (eq org-indirect-buffer-display 'new-frame)
6584 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6585 (select-frame (make-frame))
6586 (delete-other-windows)
6587 (switch-to-buffer ibuf)
6588 (org-set-frame-title heading))
6589 ((eq org-indirect-buffer-display 'dedicated-frame)
6590 (raise-frame
6591 (select-frame (or (and org-indirect-dedicated-frame
6592 (frame-live-p org-indirect-dedicated-frame)
6593 org-indirect-dedicated-frame)
6594 (setq org-indirect-dedicated-frame (make-frame)))))
6595 (delete-other-windows)
6596 (switch-to-buffer ibuf)
6597 (org-set-frame-title (concat "Indirect: " heading)))
6598 ((eq org-indirect-buffer-display 'current-window)
6599 (switch-to-buffer ibuf))
6600 ((eq org-indirect-buffer-display 'other-window)
6601 (pop-to-buffer ibuf))
6602 (t (error "Invalid value")))
6603 (if (featurep 'xemacs)
6604 (save-excursion (org-mode) (turn-on-font-lock)))
6605 (narrow-to-region beg end)
6606 (show-all)
6607 (goto-char pos)
6608 (and (window-live-p cwin) (select-window cwin))))
6610 (defun org-get-indirect-buffer (&optional buffer)
6611 (setq buffer (or buffer (current-buffer)))
6612 (let ((n 1) (base (buffer-name buffer)) bname)
6613 (while (buffer-live-p
6614 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6615 (setq n (1+ n)))
6616 (condition-case nil
6617 (make-indirect-buffer buffer bname 'clone)
6618 (error (make-indirect-buffer buffer bname)))))
6620 (defun org-set-frame-title (title)
6621 "Set the title of the current frame to the string TITLE."
6622 ;; FIXME: how to name a single frame in XEmacs???
6623 (unless (featurep 'xemacs)
6624 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6626 ;;;; Structure editing
6628 ;;; Inserting headlines
6630 (defun org-previous-line-empty-p ()
6631 (save-excursion
6632 (and (not (bobp))
6633 (or (beginning-of-line 0) t)
6634 (save-match-data
6635 (looking-at "[ \t]*$")))))
6637 (defun org-insert-heading (&optional force-heading invisible-ok)
6638 "Insert a new heading or item with same depth at point.
6639 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6640 If point is at the beginning of a headline, insert a sibling before the
6641 current headline. If point is not at the beginning, do not split the line,
6642 but create the new headline after the current line.
6643 When INVISIBLE-OK is set, stop at invisible headlines when going back.
6644 This is important for non-interactive uses of the command."
6645 (interactive "P")
6646 (if (or (= (buffer-size) 0)
6647 (and (not (save-excursion (and (ignore-errors (org-back-to-heading invisible-ok))
6648 (org-on-heading-p))))
6649 (not (org-in-item-p))))
6650 (insert "\n* ")
6651 (when (or force-heading (not (org-insert-item)))
6652 (let* ((empty-line-p nil)
6653 (head (save-excursion
6654 (condition-case nil
6655 (progn
6656 (org-back-to-heading invisible-ok)
6657 (setq empty-line-p (org-previous-line-empty-p))
6658 (match-string 0))
6659 (error "*"))))
6660 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
6661 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
6662 pos hide-previous previous-pos)
6663 (cond
6664 ((and (org-on-heading-p) (bolp)
6665 (or (bobp)
6666 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6667 ;; insert before the current line
6668 (open-line (if blank 2 1)))
6669 ((and (bolp)
6670 (not org-insert-heading-respect-content)
6671 (or (bobp)
6672 (save-excursion
6673 (backward-char 1) (not (org-invisible-p)))))
6674 ;; insert right here
6675 nil)
6677 ;; somewhere in the line
6678 (save-excursion
6679 (setq previous-pos (point-at-bol))
6680 (end-of-line)
6681 (setq hide-previous (org-invisible-p)))
6682 (and org-insert-heading-respect-content (org-show-subtree))
6683 (let ((split
6684 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
6685 (save-excursion
6686 (let ((p (point)))
6687 (goto-char (point-at-bol))
6688 (and (looking-at org-complex-heading-regexp)
6689 (> p (match-beginning 4)))))))
6690 tags pos)
6691 (cond
6692 (org-insert-heading-respect-content
6693 (org-end-of-subtree nil t)
6694 (or (bolp) (newline))
6695 (or (org-previous-line-empty-p)
6696 (and blank (newline)))
6697 (open-line 1))
6698 ((org-on-heading-p)
6699 (when hide-previous
6700 (show-children)
6701 (org-show-entry))
6702 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6703 (setq tags (and (match-end 2) (match-string 2)))
6704 (and (match-end 1)
6705 (delete-region (match-beginning 1) (match-end 1)))
6706 (setq pos (point-at-bol))
6707 (or split (end-of-line 1))
6708 (delete-horizontal-space)
6709 (if (string-match "\\`\\*+\\'"
6710 (buffer-substring (point-at-bol) (point)))
6711 (insert " "))
6712 (newline (if blank 2 1))
6713 (when tags
6714 (save-excursion
6715 (goto-char pos)
6716 (end-of-line 1)
6717 (insert " " tags)
6718 (org-set-tags nil 'align))))
6720 (or split (end-of-line 1))
6721 (newline (if blank 2 1)))))))
6722 (insert head) (just-one-space)
6723 (setq pos (point))
6724 (end-of-line 1)
6725 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6726 (when (and org-insert-heading-respect-content hide-previous)
6727 (save-excursion
6728 (goto-char previous-pos)
6729 (hide-subtree)))
6730 (run-hooks 'org-insert-heading-hook)))))
6732 (defun org-get-heading (&optional no-tags)
6733 "Return the heading of the current entry, without the stars."
6734 (save-excursion
6735 (org-back-to-heading t)
6736 (if (looking-at
6737 (if no-tags
6738 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
6739 "\\*+[ \t]+\\([^\r\n]*\\)"))
6740 (match-string 1) "")))
6742 (defun org-heading-components ()
6743 "Return the components of the current heading.
6744 This is a list with the following elements:
6745 - the level as an integer
6746 - the reduced level, different if `org-odd-levels-only' is set.
6747 - the TODO keyword, or nil
6748 - the priority character, like ?A, or nil if no priority is given
6749 - the headline text itself, or the tags string if no headline text
6750 - the tags string, or nil."
6751 (save-excursion
6752 (org-back-to-heading t)
6753 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
6754 (list (length (match-string 1))
6755 (org-reduced-level (length (match-string 1)))
6756 (org-match-string-no-properties 2)
6757 (and (match-end 3) (aref (match-string 3) 2))
6758 (org-match-string-no-properties 4)
6759 (org-match-string-no-properties 5)))))
6761 (defun org-get-entry ()
6762 "Get the entry text, after heading, entire subtree."
6763 (save-excursion
6764 (org-back-to-heading t)
6765 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
6767 (defun org-insert-heading-after-current ()
6768 "Insert a new heading with same level as current, after current subtree."
6769 (interactive)
6770 (org-back-to-heading)
6771 (org-insert-heading)
6772 (org-move-subtree-down)
6773 (end-of-line 1))
6775 (defun org-insert-heading-respect-content ()
6776 (interactive)
6777 (let ((org-insert-heading-respect-content t))
6778 (org-insert-heading t)))
6780 (defun org-insert-todo-heading-respect-content (&optional force-state)
6781 (interactive "P")
6782 (let ((org-insert-heading-respect-content t))
6783 (org-insert-todo-heading force-state t)))
6785 (defun org-insert-todo-heading (arg &optional force-heading)
6786 "Insert a new heading with the same level and TODO state as current heading.
6787 If the heading has no TODO state, or if the state is DONE, use the first
6788 state (TODO by default). Also with prefix arg, force first state."
6789 (interactive "P")
6790 (when (or force-heading (not (org-insert-item 'checkbox)))
6791 (org-insert-heading force-heading)
6792 (save-excursion
6793 (org-back-to-heading)
6794 (outline-previous-heading)
6795 (looking-at org-todo-line-regexp))
6796 (let*
6797 ((new-mark-x
6798 (if (or arg
6799 (not (match-beginning 2))
6800 (member (match-string 2) org-done-keywords))
6801 (car org-todo-keywords-1)
6802 (match-string 2)))
6803 (new-mark
6805 (run-hook-with-args-until-success
6806 'org-todo-get-default-hook new-mark-x nil)
6807 new-mark-x)))
6808 (beginning-of-line 1)
6809 (and (looking-at "\\*+ ") (goto-char (match-end 0))
6810 (if org-treat-insert-todo-heading-as-state-change
6811 (org-todo new-mark)
6812 (insert new-mark " "))))
6813 (when org-provide-todo-statistics
6814 (org-update-parent-todo-statistics))))
6816 (defun org-insert-subheading (arg)
6817 "Insert a new subheading and demote it.
6818 Works for outline headings and for plain lists alike."
6819 (interactive "P")
6820 (org-insert-heading arg)
6821 (cond
6822 ((org-on-heading-p) (org-do-demote))
6823 ((org-at-item-p) (org-indent-item 1))))
6825 (defun org-insert-todo-subheading (arg)
6826 "Insert a new subheading with TODO keyword or checkbox and demote it.
6827 Works for outline headings and for plain lists alike."
6828 (interactive "P")
6829 (org-insert-todo-heading arg)
6830 (cond
6831 ((org-on-heading-p) (org-do-demote))
6832 ((org-at-item-p) (org-indent-item 1))))
6834 ;;; Promotion and Demotion
6836 (defvar org-after-demote-entry-hook nil
6837 "Hook run after an entry has been demoted.
6838 The cursor will be at the beginning of the entry.
6839 When a subtree is being demoted, the hook will be called for each node.")
6841 (defvar org-after-promote-entry-hook nil
6842 "Hook run after an entry has been promoted.
6843 The cursor will be at the beginning of the entry.
6844 When a subtree is being promoted, the hook will be called for each node.")
6846 (defun org-promote-subtree ()
6847 "Promote the entire subtree.
6848 See also `org-promote'."
6849 (interactive)
6850 (save-excursion
6851 (org-map-tree 'org-promote))
6852 (org-fix-position-after-promote))
6854 (defun org-demote-subtree ()
6855 "Demote the entire subtree. See `org-demote'.
6856 See also `org-promote'."
6857 (interactive)
6858 (save-excursion
6859 (org-map-tree 'org-demote))
6860 (org-fix-position-after-promote))
6863 (defun org-do-promote ()
6864 "Promote the current heading higher up the tree.
6865 If the region is active in `transient-mark-mode', promote all headings
6866 in the region."
6867 (interactive)
6868 (save-excursion
6869 (if (org-region-active-p)
6870 (org-map-region 'org-promote (region-beginning) (region-end))
6871 (org-promote)))
6872 (org-fix-position-after-promote))
6874 (defun org-do-demote ()
6875 "Demote the current heading lower down the tree.
6876 If the region is active in `transient-mark-mode', demote all headings
6877 in the region."
6878 (interactive)
6879 (save-excursion
6880 (if (org-region-active-p)
6881 (org-map-region 'org-demote (region-beginning) (region-end))
6882 (org-demote)))
6883 (org-fix-position-after-promote))
6885 (defun org-fix-position-after-promote ()
6886 "Make sure that after pro/demotion cursor position is right."
6887 (let ((pos (point)))
6888 (when (save-excursion
6889 (beginning-of-line 1)
6890 (looking-at org-todo-line-regexp)
6891 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6892 (cond ((eobp) (insert " "))
6893 ((eolp) (insert " "))
6894 ((equal (char-after) ?\ ) (forward-char 1))))))
6896 (defun org-current-level ()
6897 "Return the level of the current entry, or nil if before the first headline.
6898 The level is the number of stars at the beginning of the headline."
6899 (save-excursion
6900 (condition-case nil
6901 (progn
6902 (org-back-to-heading t)
6903 (funcall outline-level))
6904 (error nil))))
6906 (defun org-get-previous-line-level ()
6907 "Return the outline depth of the last headline before the current line.
6908 Returns 0 for the first headline in the buffer, and nil if before the
6909 first headline."
6910 (let ((current-level (org-current-level))
6911 (prev-level (when (> (line-number-at-pos) 1)
6912 (save-excursion
6913 (beginning-of-line 0)
6914 (org-current-level)))))
6915 (cond ((null current-level) nil) ; Before first headline
6916 ((null prev-level) 0) ; At first headline
6917 (prev-level))))
6919 (defun org-reduced-level (l)
6920 "Compute the effective level of a heading.
6921 This takes into account the setting of `org-odd-levels-only'."
6922 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6924 (defun org-level-increment ()
6925 "Return the number of stars that will be added or removed at a
6926 time to headlines when structure editing, based on the value of
6927 `org-odd-levels-only'."
6928 (if org-odd-levels-only 2 1))
6930 (defun org-get-valid-level (level &optional change)
6931 "Rectify a level change under the influence of `org-odd-levels-only'
6932 LEVEL is a current level, CHANGE is by how much the level should be
6933 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6934 even level numbers will become the next higher odd number."
6935 (if org-odd-levels-only
6936 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6937 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6938 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6939 (max 1 (+ level (or change 0)))))
6941 (if (boundp 'define-obsolete-function-alias)
6942 (if (or (featurep 'xemacs) (< emacs-major-version 23))
6943 (define-obsolete-function-alias 'org-get-legal-level
6944 'org-get-valid-level)
6945 (define-obsolete-function-alias 'org-get-legal-level
6946 'org-get-valid-level "23.1")))
6948 (defun org-promote ()
6949 "Promote the current heading higher up the tree.
6950 If the region is active in `transient-mark-mode', promote all headings
6951 in the region."
6952 (org-back-to-heading t)
6953 (let* ((level (save-match-data (funcall outline-level)))
6954 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6955 (diff (abs (- level (length up-head) -1))))
6956 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6957 (replace-match up-head nil t)
6958 ;; Fixup tag positioning
6959 (and org-auto-align-tags (org-set-tags nil t))
6960 (if org-adapt-indentation (org-fixup-indentation (- diff)))
6961 (run-hooks 'org-after-promote-entry-hook)))
6963 (defun org-demote ()
6964 "Demote the current heading lower down the tree.
6965 If the region is active in `transient-mark-mode', demote all headings
6966 in the region."
6967 (org-back-to-heading t)
6968 (let* ((level (save-match-data (funcall outline-level)))
6969 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6970 (diff (abs (- level (length down-head) -1))))
6971 (replace-match down-head nil t)
6972 ;; Fixup tag positioning
6973 (and org-auto-align-tags (org-set-tags nil t))
6974 (if org-adapt-indentation (org-fixup-indentation diff))
6975 (run-hooks 'org-after-demote-entry-hook)))
6977 (defun org-cycle-level ()
6978 "Cycle the level of an empty headline through possible states.
6979 This goes first to child, then to parent, level, then up the hierarchy.
6980 After top level, it switches back to sibling level."
6981 (interactive)
6982 (let ((org-adapt-indentation nil))
6983 (when (org-point-at-end-of-empty-headline)
6984 (setq this-command 'org-cycle-level) ; Only needed for caching
6985 (let ((cur-level (org-current-level))
6986 (prev-level (org-get-previous-line-level)))
6987 (cond
6988 ;; If first headline in file, promote to top-level.
6989 ((= prev-level 0)
6990 (loop repeat (/ (- cur-level 1) (org-level-increment))
6991 do (org-do-promote)))
6992 ;; If same level as prev, demote one.
6993 ((= prev-level cur-level)
6994 (org-do-demote))
6995 ;; If parent is top-level, promote to top level if not already.
6996 ((= prev-level 1)
6997 (loop repeat (/ (- cur-level 1) (org-level-increment))
6998 do (org-do-promote)))
6999 ;; If top-level, return to prev-level.
7000 ((= cur-level 1)
7001 (loop repeat (/ (- prev-level 1) (org-level-increment))
7002 do (org-do-demote)))
7003 ;; If less than prev-level, promote one.
7004 ((< cur-level prev-level)
7005 (org-do-promote))
7006 ;; If deeper than prev-level, promote until higher than
7007 ;; prev-level.
7008 ((> cur-level prev-level)
7009 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7010 do (org-do-promote))))
7011 t))))
7013 (defun org-map-tree (fun)
7014 "Call FUN for every heading underneath the current one."
7015 (org-back-to-heading)
7016 (let ((level (funcall outline-level)))
7017 (save-excursion
7018 (funcall fun)
7019 (while (and (progn
7020 (outline-next-heading)
7021 (> (funcall outline-level) level))
7022 (not (eobp)))
7023 (funcall fun)))))
7025 (defun org-map-region (fun beg end)
7026 "Call FUN for every heading between BEG and END."
7027 (let ((org-ignore-region t))
7028 (save-excursion
7029 (setq end (copy-marker end))
7030 (goto-char beg)
7031 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
7032 (< (point) end))
7033 (funcall fun))
7034 (while (and (progn
7035 (outline-next-heading)
7036 (< (point) end))
7037 (not (eobp)))
7038 (funcall fun)))))
7040 (defun org-fixup-indentation (diff)
7041 "Change the indentation in the current entry by DIFF.
7042 However, if any line in the current entry has no indentation, or if it
7043 would end up with no indentation after the change, nothing at all is done."
7044 (save-excursion
7045 (let ((end (save-excursion (outline-next-heading)
7046 (point-marker)))
7047 (prohibit (if (> diff 0)
7048 "^\\S-"
7049 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7050 col)
7051 (unless (save-excursion (end-of-line 1)
7052 (re-search-forward prohibit end t))
7053 (while (and (< (point) end)
7054 (re-search-forward "^[ \t]+" end t))
7055 (goto-char (match-end 0))
7056 (setq col (current-column))
7057 (if (< diff 0) (replace-match ""))
7058 (org-indent-to-column (+ diff col))))
7059 (move-marker end nil))))
7061 (defun org-convert-to-odd-levels ()
7062 "Convert an org-mode file with all levels allowed to one with odd levels.
7063 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7064 level 5 etc."
7065 (interactive)
7066 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7067 (let ((outline-regexp org-outline-regexp)
7068 (outline-level 'org-outline-level)
7069 (org-odd-levels-only nil) n)
7070 (save-excursion
7071 (goto-char (point-min))
7072 (while (re-search-forward "^\\*\\*+ " nil t)
7073 (setq n (- (length (match-string 0)) 2))
7074 (while (>= (setq n (1- n)) 0)
7075 (org-demote))
7076 (end-of-line 1))))))
7078 (defun org-convert-to-oddeven-levels ()
7079 "Convert an org-mode file with only odd levels to one with odd/even levels.
7080 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7081 file contains a section with an even level, conversion would
7082 destroy the structure of the file. An error is signaled in this
7083 case."
7084 (interactive)
7085 (goto-char (point-min))
7086 ;; First check if there are no even levels
7087 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7088 (org-show-context t)
7089 (error "Not all levels are odd in this file. Conversion not possible"))
7090 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7091 (let ((outline-regexp org-outline-regexp)
7092 (outline-level 'org-outline-level)
7093 (org-odd-levels-only nil) n)
7094 (save-excursion
7095 (goto-char (point-min))
7096 (while (re-search-forward "^\\*\\*+ " nil t)
7097 (setq n (/ (1- (length (match-string 0))) 2))
7098 (while (>= (setq n (1- n)) 0)
7099 (org-promote))
7100 (end-of-line 1))))))
7102 (defun org-tr-level (n)
7103 "Make N odd if required."
7104 (if org-odd-levels-only (1+ (/ n 2)) n))
7106 ;;; Vertical tree motion, cutting and pasting of subtrees
7108 (defun org-move-subtree-up (&optional arg)
7109 "Move the current subtree up past ARG headlines of the same level."
7110 (interactive "p")
7111 (org-move-subtree-down (- (prefix-numeric-value arg))))
7113 (defun org-move-subtree-down (&optional arg)
7114 "Move the current subtree down past ARG headlines of the same level."
7115 (interactive "p")
7116 (setq arg (prefix-numeric-value arg))
7117 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7118 'org-get-last-sibling))
7119 (ins-point (make-marker))
7120 (cnt (abs arg))
7121 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7122 ;; Select the tree
7123 (org-back-to-heading)
7124 (setq beg0 (point))
7125 (save-excursion
7126 (setq ne-beg (org-back-over-empty-lines))
7127 (setq beg (point)))
7128 (save-match-data
7129 (save-excursion (outline-end-of-heading)
7130 (setq folded (org-invisible-p)))
7131 (outline-end-of-subtree))
7132 (outline-next-heading)
7133 (setq ne-end (org-back-over-empty-lines))
7134 (setq end (point))
7135 (goto-char beg0)
7136 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7137 ;; include less whitespace
7138 (save-excursion
7139 (goto-char beg)
7140 (forward-line (- ne-beg ne-end))
7141 (setq beg (point))))
7142 ;; Find insertion point, with error handling
7143 (while (> cnt 0)
7144 (or (and (funcall movfunc) (looking-at outline-regexp))
7145 (progn (goto-char beg0)
7146 (error "Cannot move past superior level or buffer limit")))
7147 (setq cnt (1- cnt)))
7148 (if (> arg 0)
7149 ;; Moving forward - still need to move over subtree
7150 (progn (org-end-of-subtree t t)
7151 (save-excursion
7152 (org-back-over-empty-lines)
7153 (or (bolp) (newline)))))
7154 (setq ne-ins (org-back-over-empty-lines))
7155 (move-marker ins-point (point))
7156 (setq txt (buffer-substring beg end))
7157 (org-save-markers-in-region beg end)
7158 (delete-region beg end)
7159 (org-remove-empty-overlays-at beg)
7160 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7161 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7162 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7163 (let ((bbb (point)))
7164 (insert-before-markers txt)
7165 (org-reinstall-markers-in-region bbb)
7166 (move-marker ins-point bbb))
7167 (or (bolp) (insert "\n"))
7168 (setq ins-end (point))
7169 (goto-char ins-point)
7170 (org-skip-whitespace)
7171 (when (and (< arg 0)
7172 (org-first-sibling-p)
7173 (> ne-ins ne-beg))
7174 ;; Move whitespace back to beginning
7175 (save-excursion
7176 (goto-char ins-end)
7177 (let ((kill-whole-line t))
7178 (kill-line (- ne-ins ne-beg)) (point)))
7179 (insert (make-string (- ne-ins ne-beg) ?\n)))
7180 (move-marker ins-point nil)
7181 (if folded
7182 (hide-subtree)
7183 (org-show-entry)
7184 (show-children)
7185 (org-cycle-hide-drawers 'children))
7186 (org-clean-visibility-after-subtree-move)))
7188 (defvar org-subtree-clip ""
7189 "Clipboard for cut and paste of subtrees.
7190 This is actually only a copy of the kill, because we use the normal kill
7191 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7193 (defvar org-subtree-clip-folded nil
7194 "Was the last copied subtree folded?
7195 This is used to fold the tree back after pasting.")
7197 (defun org-cut-subtree (&optional n)
7198 "Cut the current subtree into the clipboard.
7199 With prefix arg N, cut this many sequential subtrees.
7200 This is a short-hand for marking the subtree and then cutting it."
7201 (interactive "p")
7202 (org-copy-subtree n 'cut))
7204 (defun org-copy-subtree (&optional n cut force-store-markers)
7205 "Cut the current subtree into the clipboard.
7206 With prefix arg N, cut this many sequential subtrees.
7207 This is a short-hand for marking the subtree and then copying it.
7208 If CUT is non-nil, actually cut the subtree.
7209 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7210 of some markers in the region, even if CUT is non-nil. This is
7211 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7212 (interactive "p")
7213 (let (beg end folded (beg0 (point)))
7214 (if (interactive-p)
7215 (org-back-to-heading nil) ; take what looks like a subtree
7216 (org-back-to-heading t)) ; take what is really there
7217 (org-back-over-empty-lines)
7218 (setq beg (point))
7219 (skip-chars-forward " \t\r\n")
7220 (save-match-data
7221 (save-excursion (outline-end-of-heading)
7222 (setq folded (org-invisible-p)))
7223 (condition-case nil
7224 (org-forward-same-level (1- n) t)
7225 (error nil))
7226 (org-end-of-subtree t t))
7227 (org-back-over-empty-lines)
7228 (setq end (point))
7229 (goto-char beg0)
7230 (when (> end beg)
7231 (setq org-subtree-clip-folded folded)
7232 (when (or cut force-store-markers)
7233 (org-save-markers-in-region beg end))
7234 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7235 (setq org-subtree-clip (current-kill 0))
7236 (message "%s: Subtree(s) with %d characters"
7237 (if cut "Cut" "Copied")
7238 (length org-subtree-clip)))))
7240 (defun org-paste-subtree (&optional level tree for-yank)
7241 "Paste the clipboard as a subtree, with modification of headline level.
7242 The entire subtree is promoted or demoted in order to match a new headline
7243 level.
7245 If the cursor is at the beginning of a headline, the same level as
7246 that headline is used to paste the tree
7248 If not, the new level is derived from the *visible* headings
7249 before and after the insertion point, and taken to be the inferior headline
7250 level of the two. So if the previous visible heading is level 3 and the
7251 next is level 4 (or vice versa), level 4 will be used for insertion.
7252 This makes sure that the subtree remains an independent subtree and does
7253 not swallow low level entries.
7255 You can also force a different level, either by using a numeric prefix
7256 argument, or by inserting the heading marker by hand. For example, if the
7257 cursor is after \"*****\", then the tree will be shifted to level 5.
7259 If optional TREE is given, use this text instead of the kill ring.
7261 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7262 move back over whitespace before inserting, and move point to the end of
7263 the inserted text when done."
7264 (interactive "P")
7265 (setq tree (or tree (and kill-ring (current-kill 0))))
7266 (unless (org-kill-is-subtree-p tree)
7267 (error "%s"
7268 (substitute-command-keys
7269 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7270 (let* ((visp (not (org-invisible-p)))
7271 (txt tree)
7272 (^re (concat "^\\(" outline-regexp "\\)"))
7273 (re (concat "\\(" outline-regexp "\\)"))
7274 (^re_ (concat "\\(\\*+\\)[ \t]*"))
7276 (old-level (if (string-match ^re txt)
7277 (- (match-end 0) (match-beginning 0) 1)
7278 -1))
7279 (force-level (cond (level (prefix-numeric-value level))
7280 ((and (looking-at "[ \t]*$")
7281 (string-match
7282 ^re_ (buffer-substring
7283 (point-at-bol) (point))))
7284 (- (match-end 1) (match-beginning 1)))
7285 ((and (bolp)
7286 (looking-at org-outline-regexp))
7287 (- (match-end 0) (point) 1))
7288 (t nil)))
7289 (previous-level (save-excursion
7290 (condition-case nil
7291 (progn
7292 (outline-previous-visible-heading 1)
7293 (if (looking-at re)
7294 (- (match-end 0) (match-beginning 0) 1)
7296 (error 1))))
7297 (next-level (save-excursion
7298 (condition-case nil
7299 (progn
7300 (or (looking-at outline-regexp)
7301 (outline-next-visible-heading 1))
7302 (if (looking-at re)
7303 (- (match-end 0) (match-beginning 0) 1)
7305 (error 1))))
7306 (new-level (or force-level (max previous-level next-level)))
7307 (shift (if (or (= old-level -1)
7308 (= new-level -1)
7309 (= old-level new-level))
7311 (- new-level old-level)))
7312 (delta (if (> shift 0) -1 1))
7313 (func (if (> shift 0) 'org-demote 'org-promote))
7314 (org-odd-levels-only nil)
7315 beg end newend)
7316 ;; Remove the forced level indicator
7317 (if force-level
7318 (delete-region (point-at-bol) (point)))
7319 ;; Paste
7320 (beginning-of-line 1)
7321 (unless for-yank (org-back-over-empty-lines))
7322 (setq beg (point))
7323 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7324 (insert-before-markers txt)
7325 (unless (string-match "\n\\'" txt) (insert "\n"))
7326 (setq newend (point))
7327 (org-reinstall-markers-in-region beg)
7328 (setq end (point))
7329 (goto-char beg)
7330 (skip-chars-forward " \t\n\r")
7331 (setq beg (point))
7332 (if (and (org-invisible-p) visp)
7333 (save-excursion (outline-show-heading)))
7334 ;; Shift if necessary
7335 (unless (= shift 0)
7336 (save-restriction
7337 (narrow-to-region beg end)
7338 (while (not (= shift 0))
7339 (org-map-region func (point-min) (point-max))
7340 (setq shift (+ delta shift)))
7341 (goto-char (point-min))
7342 (setq newend (point-max))))
7343 (when (or (interactive-p) for-yank)
7344 (message "Clipboard pasted as level %d subtree" new-level))
7345 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7346 kill-ring
7347 (eq org-subtree-clip (current-kill 0))
7348 org-subtree-clip-folded)
7349 ;; The tree was folded before it was killed/copied
7350 (hide-subtree))
7351 (and for-yank (goto-char newend))))
7353 (defun org-kill-is-subtree-p (&optional txt)
7354 "Check if the current kill is an outline subtree, or a set of trees.
7355 Returns nil if kill does not start with a headline, or if the first
7356 headline level is not the largest headline level in the tree.
7357 So this will actually accept several entries of equal levels as well,
7358 which is OK for `org-paste-subtree'.
7359 If optional TXT is given, check this string instead of the current kill."
7360 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7361 (start-level (and kill
7362 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
7363 org-outline-regexp "\\)")
7364 kill)
7365 (- (match-end 2) (match-beginning 2) 1)))
7366 (re (concat "^" org-outline-regexp))
7367 (start (1+ (or (match-beginning 2) -1))))
7368 (if (not start-level)
7369 (progn
7370 nil) ;; does not even start with a heading
7371 (catch 'exit
7372 (while (setq start (string-match re kill (1+ start)))
7373 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7374 (throw 'exit nil)))
7375 t))))
7377 (defvar org-markers-to-move nil
7378 "Markers that should be moved with a cut-and-paste operation.
7379 Those markers are stored together with their positions relative to
7380 the start of the region.")
7382 (defun org-save-markers-in-region (beg end)
7383 "Check markers in region.
7384 If these markers are between BEG and END, record their position relative
7385 to BEG, so that after moving the block of text, we can put the markers back
7386 into place.
7387 This function gets called just before an entry or tree gets cut from the
7388 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7389 called immediately, to move the markers with the entries."
7390 (setq org-markers-to-move nil)
7391 (when (featurep 'org-clock)
7392 (org-clock-save-markers-for-cut-and-paste beg end))
7393 (when (featurep 'org-agenda)
7394 (org-agenda-save-markers-for-cut-and-paste beg end)))
7396 (defun org-check-and-save-marker (marker beg end)
7397 "Check if MARKER is between BEG and END.
7398 If yes, remember the marker and the distance to BEG."
7399 (when (and (marker-buffer marker)
7400 (equal (marker-buffer marker) (current-buffer)))
7401 (if (and (>= marker beg) (< marker end))
7402 (push (cons marker (- marker beg)) org-markers-to-move))))
7404 (defun org-reinstall-markers-in-region (beg)
7405 "Move all remembered markers to their position relative to BEG."
7406 (mapc (lambda (x)
7407 (move-marker (car x) (+ beg (cdr x))))
7408 org-markers-to-move)
7409 (setq org-markers-to-move nil))
7411 (defun org-narrow-to-subtree ()
7412 "Narrow buffer to the current subtree."
7413 (interactive)
7414 (save-excursion
7415 (save-match-data
7416 (narrow-to-region
7417 (progn (org-back-to-heading t) (point))
7418 (progn (org-end-of-subtree t t)
7419 (if (org-on-heading-p) (backward-char 1))
7420 (point))))))
7422 (eval-when-compile
7423 (defvar org-property-drawer-re))
7425 (defun org-clone-subtree-with-time-shift (n &optional shift)
7426 "Clone the task (subtree) at point N times.
7427 The clones will be inserted as siblings.
7429 In interactive use, the user will be prompted for the number of
7430 clones to be produced, and for a time SHIFT, which may be a
7431 repeater as used in time stamps, for example `+3d'.
7433 When a valid repeater is given and the entry contains any time
7434 stamps, the clones will become a sequence in time, with time
7435 stamps in the subtree shifted for each clone produced. If SHIFT
7436 is nil or the empty string, time stamps will be left alone. The
7437 ID property of the original subtree is removed.
7439 If the original subtree did contain time stamps with a repeater,
7440 the following will happen:
7441 - the repeater will be removed in each clone
7442 - an additional clone will be produced, with the current, unshifted
7443 date(s) in the entry.
7444 - the original entry will be placed *after* all the clones, with
7445 repeater intact.
7446 - the start days in the repeater in the original entry will be shifted
7447 to past the last clone.
7448 I this way you can spell out a number of instances of a repeating task,
7449 and still retain the repeater to cover future instances of the task."
7450 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7451 (let (beg end template task idprop
7452 shift-n shift-what doshift nmin nmax (n-no-remove -1))
7453 (if (not (and (integerp n) (> n 0)))
7454 (error "Invalid number of replications %s" n))
7455 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7456 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
7457 shift)))
7458 (error "Invalid shift specification %s" shift))
7459 (when doshift
7460 (setq shift-n (string-to-number (match-string 1 shift))
7461 shift-what (cdr (assoc (match-string 2 shift)
7462 '(("d" . day) ("w" . week)
7463 ("m" . month) ("y" . year))))))
7464 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7465 (setq nmin 1 nmax n)
7466 (org-back-to-heading t)
7467 (setq beg (point))
7468 (setq idprop (org-entry-get nil "ID"))
7469 (org-end-of-subtree t t)
7470 (or (bolp) (insert "\n"))
7471 (setq end (point))
7472 (setq template (buffer-substring beg end))
7473 (when (and doshift
7474 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
7475 (delete-region beg end)
7476 (setq end beg)
7477 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7478 (goto-char end)
7479 (loop for n from nmin to nmax do
7480 ;; prepare clone
7481 (with-temp-buffer
7482 (insert template)
7483 (org-mode)
7484 (goto-char (point-min))
7485 (and idprop (if org-clone-delete-id
7486 (org-entry-delete nil "ID")
7487 (org-id-get-create t)))
7488 (while (re-search-forward org-property-drawer-re nil t)
7489 (org-remove-empty-drawer-at "PROPERTIES" (point)))
7490 (goto-char (point-min))
7491 (when doshift
7492 (while (re-search-forward org-ts-regexp-both nil t)
7493 (org-timestamp-change (* n shift-n) shift-what))
7494 (unless (= n n-no-remove)
7495 (goto-char (point-min))
7496 (while (re-search-forward org-ts-regexp nil t)
7497 (save-excursion
7498 (goto-char (match-beginning 0))
7499 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
7500 (delete-region (match-beginning 1) (match-end 1)))))))
7501 (setq task (buffer-string)))
7502 (insert task))
7503 (goto-char beg)))
7505 ;;; Outline Sorting
7507 (defun org-sort (with-case)
7508 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
7509 Optional argument WITH-CASE means sort case-sensitively.
7510 With a double prefix argument, also remove duplicate entries."
7511 (interactive "P")
7512 (if (org-at-table-p)
7513 (org-call-with-arg 'org-table-sort-lines with-case)
7514 (org-call-with-arg 'org-sort-entries-or-items with-case)))
7516 (defun org-sort-remove-invisible (s)
7517 (remove-text-properties 0 (length s) org-rm-props s)
7518 (while (string-match org-bracket-link-regexp s)
7519 (setq s (replace-match (if (match-end 2)
7520 (match-string 3 s)
7521 (match-string 1 s)) t t s)))
7524 (defvar org-priority-regexp) ; defined later in the file
7526 (defvar org-after-sorting-entries-or-items-hook nil
7527 "Hook that is run after a bunch of entries or items have been sorted.
7528 When children are sorted, the cursor is in the parent line when this
7529 hook gets called. When a region or a plain list is sorted, the cursor
7530 will be in the first entry of the sorted region/list.")
7532 (defun org-sort-entries-or-items
7533 (&optional with-case sorting-type getkey-func compare-func property)
7534 "Sort entries on a certain level of an outline tree, or plain list items.
7535 If there is an active region, the entries in the region are sorted.
7536 Else, if the cursor is before the first entry, sort the top-level items.
7537 Else, the children of the entry at point are sorted.
7538 If the cursor is at the first item in a plain list, the list items will be
7539 sorted.
7541 Sorting can be alphabetically, numerically, by date/time as given by
7542 a time stamp, by a property or by priority.
7544 The command prompts for the sorting type unless it has been given to the
7545 function through the SORTING-TYPE argument, which needs to be a character,
7546 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
7547 precise meaning of each character:
7549 n Numerically, by converting the beginning of the entry/item to a number.
7550 a Alphabetically, ignoring the TODO keyword and the priority, if any.
7551 t By date/time, either the first active time stamp in the entry, or, if
7552 none exist, by the first inactive one.
7553 In items, only the first line will be checked.
7554 s By the scheduled date/time.
7555 d By deadline date/time.
7556 c By creation time, which is assumed to be the first inactive time stamp
7557 at the beginning of a line.
7558 p By priority according to the cookie.
7559 r By the value of a property.
7561 Capital letters will reverse the sort order.
7563 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
7564 called with point at the beginning of the record. It must return either
7565 a string or a number that should serve as the sorting key for that record.
7567 Comparing entries ignores case by default. However, with an optional argument
7568 WITH-CASE, the sorting considers case as well."
7569 (interactive "P")
7570 (let ((case-func (if with-case 'identity 'downcase))
7571 start beg end stars re re2
7572 txt what tmp plain-list-p)
7573 ;; Find beginning and end of region to sort
7574 (cond
7575 ((org-region-active-p)
7576 ;; we will sort the region
7577 (setq end (region-end)
7578 what "region")
7579 (goto-char (region-beginning))
7580 (if (not (org-on-heading-p)) (outline-next-heading))
7581 (setq start (point)))
7582 ((org-at-item-p)
7583 ;; we will sort this plain list
7584 (org-beginning-of-item-list) (setq start (point))
7585 (org-end-of-item-list)
7586 (or (bolp) (insert "\n"))
7587 (setq end (point))
7588 (goto-char start)
7589 (setq plain-list-p t
7590 what "plain list"))
7591 ((or (org-on-heading-p)
7592 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
7593 ;; we will sort the children of the current headline
7594 (org-back-to-heading)
7595 (setq start (point)
7596 end (progn (org-end-of-subtree t t)
7597 (or (bolp) (insert "\n"))
7598 (org-back-over-empty-lines)
7599 (point))
7600 what "children")
7601 (goto-char start)
7602 (show-subtree)
7603 (outline-next-heading))
7605 ;; we will sort the top-level entries in this file
7606 (goto-char (point-min))
7607 (or (org-on-heading-p) (outline-next-heading))
7608 (setq start (point))
7609 (goto-char (point-max))
7610 (beginning-of-line 1)
7611 (when (looking-at ".*?\\S-")
7612 ;; File ends in a non-white line
7613 (end-of-line 1)
7614 (insert "\n"))
7615 (setq end (point-max))
7616 (setq what "top-level")
7617 (goto-char start)
7618 (show-all)))
7620 (setq beg (point))
7621 (if (>= beg end) (error "Nothing to sort"))
7623 (unless plain-list-p
7624 (looking-at "\\(\\*+\\)")
7625 (setq stars (match-string 1)
7626 re (concat "^" (regexp-quote stars) " +")
7627 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
7628 txt (buffer-substring beg end))
7629 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
7630 (if (and (not (equal stars "*")) (string-match re2 txt))
7631 (error "Region to sort contains a level above the first entry")))
7633 (unless sorting-type
7634 (message
7635 (if plain-list-p
7636 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
7637 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
7638 [t]ime [s]cheduled [d]eadline [c]reated
7639 A/N/T/S/D/C/P/O/F means reversed:")
7640 what)
7641 (setq sorting-type (read-char-exclusive))
7643 (and (= (downcase sorting-type) ?f)
7644 (setq getkey-func
7645 (org-icompleting-read "Sort using function: "
7646 obarray 'fboundp t nil nil))
7647 (setq getkey-func (intern getkey-func)))
7649 (and (= (downcase sorting-type) ?r)
7650 (setq property
7651 (org-icompleting-read "Property: "
7652 (mapcar 'list (org-buffer-property-keys t))
7653 nil t))))
7655 (message "Sorting entries...")
7657 (save-restriction
7658 (narrow-to-region start end)
7660 (let ((dcst (downcase sorting-type))
7661 (case-fold-search nil)
7662 (now (current-time)))
7663 (sort-subr
7664 (/= dcst sorting-type)
7665 ;; This function moves to the beginning character of the "record" to
7666 ;; be sorted.
7667 (if plain-list-p
7668 (lambda nil
7669 (if (org-at-item-p) t (goto-char (point-max))))
7670 (lambda nil
7671 (if (re-search-forward re nil t)
7672 (goto-char (match-beginning 0))
7673 (goto-char (point-max)))))
7674 ;; This function moves to the last character of the "record" being
7675 ;; sorted.
7676 (if plain-list-p
7677 'org-end-of-item
7678 (lambda nil
7679 (save-match-data
7680 (condition-case nil
7681 (outline-forward-same-level 1)
7682 (error
7683 (goto-char (point-max)))))))
7685 ;; This function returns the value that gets sorted against.
7686 (if plain-list-p
7687 (lambda nil
7688 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
7689 (cond
7690 ((= dcst ?n)
7691 (string-to-number (buffer-substring (match-end 0)
7692 (point-at-eol))))
7693 ((= dcst ?a)
7694 (buffer-substring (match-end 0) (point-at-eol)))
7695 ((= dcst ?t)
7696 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
7697 (re-search-forward org-ts-regexp-both
7698 (point-at-eol) t))
7699 (org-time-string-to-seconds (match-string 0))
7700 (org-float-time now)))
7701 ((= dcst ?f)
7702 (if getkey-func
7703 (progn
7704 (setq tmp (funcall getkey-func))
7705 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7706 tmp)
7707 (error "Invalid key function `%s'" getkey-func)))
7708 (t (error "Invalid sorting type `%c'" sorting-type)))))
7709 (lambda nil
7710 (cond
7711 ((= dcst ?n)
7712 (if (looking-at org-complex-heading-regexp)
7713 (string-to-number (match-string 4))
7714 nil))
7715 ((= dcst ?a)
7716 (if (looking-at org-complex-heading-regexp)
7717 (funcall case-func (match-string 4))
7718 nil))
7719 ((= dcst ?t)
7720 (let ((end (save-excursion (outline-next-heading) (point))))
7721 (if (or (re-search-forward org-ts-regexp end t)
7722 (re-search-forward org-ts-regexp-both end t))
7723 (org-time-string-to-seconds (match-string 0))
7724 (org-float-time now))))
7725 ((= dcst ?c)
7726 (let ((end (save-excursion (outline-next-heading) (point))))
7727 (if (re-search-forward
7728 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
7729 end t)
7730 (org-time-string-to-seconds (match-string 0))
7731 (org-float-time now))))
7732 ((= dcst ?s)
7733 (let ((end (save-excursion (outline-next-heading) (point))))
7734 (if (re-search-forward org-scheduled-time-regexp end t)
7735 (org-time-string-to-seconds (match-string 1))
7736 (org-float-time now))))
7737 ((= dcst ?d)
7738 (let ((end (save-excursion (outline-next-heading) (point))))
7739 (if (re-search-forward org-deadline-time-regexp end t)
7740 (org-time-string-to-seconds (match-string 1))
7741 (org-float-time now))))
7742 ((= dcst ?p)
7743 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7744 (string-to-char (match-string 2))
7745 org-default-priority))
7746 ((= dcst ?r)
7747 (or (org-entry-get nil property) ""))
7748 ((= dcst ?o)
7749 (if (looking-at org-complex-heading-regexp)
7750 (- 9999 (length (member (match-string 2)
7751 org-todo-keywords-1)))))
7752 ((= dcst ?f)
7753 (if getkey-func
7754 (progn
7755 (setq tmp (funcall getkey-func))
7756 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7757 tmp)
7758 (error "Invalid key function `%s'" getkey-func)))
7759 (t (error "Invalid sorting type `%c'" sorting-type)))))
7761 (cond
7762 ((= dcst ?a) 'string<)
7763 ((= dcst ?f) compare-func)
7764 ((member dcst '(?p ?t ?s ?d ?c)) '<)
7765 (t nil)))))
7766 (run-hooks 'org-after-sorting-entries-or-items-hook)
7767 (message "Sorting entries...done")))
7769 (defun org-do-sort (table what &optional with-case sorting-type)
7770 "Sort TABLE of WHAT according to SORTING-TYPE.
7771 The user will be prompted for the SORTING-TYPE if the call to this
7772 function does not specify it. WHAT is only for the prompt, to indicate
7773 what is being sorted. The sorting key will be extracted from
7774 the car of the elements of the table.
7775 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7776 (unless sorting-type
7777 (message
7778 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7779 what)
7780 (setq sorting-type (read-char-exclusive)))
7781 (let ((dcst (downcase sorting-type))
7782 extractfun comparefun)
7783 ;; Define the appropriate functions
7784 (cond
7785 ((= dcst ?n)
7786 (setq extractfun 'string-to-number
7787 comparefun (if (= dcst sorting-type) '< '>)))
7788 ((= dcst ?a)
7789 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7790 (lambda(x) (downcase (org-sort-remove-invisible x))))
7791 comparefun (if (= dcst sorting-type)
7792 'string<
7793 (lambda (a b) (and (not (string< a b))
7794 (not (string= a b)))))))
7795 ((= dcst ?t)
7796 (setq extractfun
7797 (lambda (x)
7798 (if (or (string-match org-ts-regexp x)
7799 (string-match org-ts-regexp-both x))
7800 (org-float-time
7801 (org-time-string-to-time (match-string 0 x)))
7803 comparefun (if (= dcst sorting-type) '< '>)))
7804 (t (error "Invalid sorting type `%c'" sorting-type)))
7806 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7807 table)
7808 (lambda (a b) (funcall comparefun (car a) (car b))))))
7811 ;;; The orgstruct minor mode
7813 ;; Define a minor mode which can be used in other modes in order to
7814 ;; integrate the org-mode structure editing commands.
7816 ;; This is really a hack, because the org-mode structure commands use
7817 ;; keys which normally belong to the major mode. Here is how it
7818 ;; works: The minor mode defines all the keys necessary to operate the
7819 ;; structure commands, but wraps the commands into a function which
7820 ;; tests if the cursor is currently at a headline or a plain list
7821 ;; item. If that is the case, the structure command is used,
7822 ;; temporarily setting many Org-mode variables like regular
7823 ;; expressions for filling etc. However, when any of those keys is
7824 ;; used at a different location, function uses `key-binding' to look
7825 ;; up if the key has an associated command in another currently active
7826 ;; keymap (minor modes, major mode, global), and executes that
7827 ;; command. There might be problems if any of the keys is otherwise
7828 ;; used as a prefix key.
7830 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7831 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7832 ;; addresses this by checking explicitly for both bindings.
7834 (defvar orgstruct-mode-map (make-sparse-keymap)
7835 "Keymap for the minor `orgstruct-mode'.")
7837 (defvar org-local-vars nil
7838 "List of local variables, for use by `orgstruct-mode'.")
7840 ;;;###autoload
7841 (define-minor-mode orgstruct-mode
7842 "Toggle the minor mode `orgstruct-mode'.
7843 This mode is for using Org-mode structure commands in other
7844 modes. The following keys behave as if Org-mode were active, if
7845 the cursor is on a headline, or on a plain list item (both as
7846 defined by Org-mode).
7848 M-up Move entry/item up
7849 M-down Move entry/item down
7850 M-left Promote
7851 M-right Demote
7852 M-S-up Move entry/item up
7853 M-S-down Move entry/item down
7854 M-S-left Promote subtree
7855 M-S-right Demote subtree
7856 M-q Fill paragraph and items like in Org-mode
7857 C-c ^ Sort entries
7858 C-c - Cycle list bullet
7859 TAB Cycle item visibility
7860 M-RET Insert new heading/item
7861 S-M-RET Insert new TODO heading / Checkbox item
7862 C-c C-c Set tags / toggle checkbox"
7863 nil " OrgStruct" nil
7864 (org-load-modules-maybe)
7865 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7867 ;;;###autoload
7868 (defun turn-on-orgstruct ()
7869 "Unconditionally turn on `orgstruct-mode'."
7870 (orgstruct-mode 1))
7872 (defun orgstruct++-mode (&optional arg)
7873 "Toggle `orgstruct-mode', the enhanced version of it.
7874 In addition to setting orgstruct-mode, this also exports all indentation
7875 and autofilling variables from org-mode into the buffer. It will also
7876 recognize item context in multiline items.
7877 Note that turning off orgstruct-mode will *not* remove the
7878 indentation/paragraph settings. This can only be done by refreshing the
7879 major mode, for example with \\[normal-mode]."
7880 (interactive "P")
7881 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
7882 (if (< arg 1)
7883 (orgstruct-mode -1)
7884 (orgstruct-mode 1)
7885 (let (var val)
7886 (mapc
7887 (lambda (x)
7888 (when (string-match
7889 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7890 (symbol-name (car x)))
7891 (setq var (car x) val (nth 1 x))
7892 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7893 org-local-vars)
7894 (org-set-local 'orgstruct-is-++ t))))
7896 (defvar orgstruct-is-++ nil
7897 "Is `orgstruct-mode' in ++ version in the current-buffer?")
7898 (make-variable-buffer-local 'orgstruct-is-++)
7900 ;;;###autoload
7901 (defun turn-on-orgstruct++ ()
7902 "Unconditionally turn on `orgstruct++-mode'."
7903 (orgstruct++-mode 1))
7905 (defun orgstruct-error ()
7906 "Error when there is no default binding for a structure key."
7907 (interactive)
7908 (error "This key has no function outside structure elements"))
7910 (defun orgstruct-setup ()
7911 "Setup orgstruct keymaps."
7912 (let ((nfunc 0)
7913 (bindings
7914 (list
7915 '([(meta up)] org-metaup)
7916 '([(meta down)] org-metadown)
7917 '([(meta left)] org-metaleft)
7918 '([(meta right)] org-metaright)
7919 '([(meta shift up)] org-shiftmetaup)
7920 '([(meta shift down)] org-shiftmetadown)
7921 '([(meta shift left)] org-shiftmetaleft)
7922 '([(meta shift right)] org-shiftmetaright)
7923 '([?\e (up)] org-metaup)
7924 '([?\e (down)] org-metadown)
7925 '([?\e (left)] org-metaleft)
7926 '([?\e (right)] org-metaright)
7927 '([?\e (shift up)] org-shiftmetaup)
7928 '([?\e (shift down)] org-shiftmetadown)
7929 '([?\e (shift left)] org-shiftmetaleft)
7930 '([?\e (shift right)] org-shiftmetaright)
7931 '([(shift up)] org-shiftup)
7932 '([(shift down)] org-shiftdown)
7933 '([(shift left)] org-shiftleft)
7934 '([(shift right)] org-shiftright)
7935 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7936 '("\M-q" fill-paragraph)
7937 '("\C-c^" org-sort)
7938 '("\C-c-" org-cycle-list-bullet)))
7939 elt key fun cmd)
7940 (while (setq elt (pop bindings))
7941 (setq nfunc (1+ nfunc))
7942 (setq key (org-key (car elt))
7943 fun (nth 1 elt)
7944 cmd (orgstruct-make-binding fun nfunc key))
7945 (org-defkey orgstruct-mode-map key cmd))
7947 ;; Special treatment needed for TAB and RET
7948 (org-defkey orgstruct-mode-map [(tab)]
7949 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7950 (org-defkey orgstruct-mode-map "\C-i"
7951 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7953 (org-defkey orgstruct-mode-map "\M-\C-m"
7954 (orgstruct-make-binding 'org-insert-heading 105
7955 "\M-\C-m" [(meta return)]))
7956 (org-defkey orgstruct-mode-map [(meta return)]
7957 (orgstruct-make-binding 'org-insert-heading 106
7958 [(meta return)] "\M-\C-m"))
7960 (org-defkey orgstruct-mode-map [(shift meta return)]
7961 (orgstruct-make-binding 'org-insert-todo-heading 107
7962 [(meta return)] "\M-\C-m"))
7964 (org-defkey orgstruct-mode-map "\e\C-m"
7965 (orgstruct-make-binding 'org-insert-heading 108
7966 "\e\C-m" [?\e (return)]))
7967 (org-defkey orgstruct-mode-map [?\e (return)]
7968 (orgstruct-make-binding 'org-insert-heading 109
7969 [?\e (return)] "\e\C-m"))
7970 (org-defkey orgstruct-mode-map [?\e (shift return)]
7971 (orgstruct-make-binding 'org-insert-todo-heading 110
7972 [?\e (return)] "\e\C-m"))
7974 (unless org-local-vars
7975 (setq org-local-vars (org-get-local-variables)))
7979 (defun orgstruct-make-binding (fun n &rest keys)
7980 "Create a function for binding in the structure minor mode.
7981 FUN is the command to call inside a table. N is used to create a unique
7982 command name. KEYS are keys that should be checked in for a command
7983 to execute outside of tables."
7984 (eval
7985 (list 'defun
7986 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7987 '(arg)
7988 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7989 "Outside of structure, run the binding of `"
7990 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7991 "'.")
7992 '(interactive "p")
7993 (list 'if
7994 `(org-context-p 'headline 'item
7995 (and orgstruct-is-++
7996 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
7997 'item-body))
7998 (list 'org-run-like-in-org-mode (list 'quote fun))
7999 (list 'let '(orgstruct-mode)
8000 (list 'call-interactively
8001 (append '(or)
8002 (mapcar (lambda (k)
8003 (list 'key-binding k))
8004 keys)
8005 '('orgstruct-error))))))))
8007 (defun org-context-p (&rest contexts)
8008 "Check if local context is any of CONTEXTS.
8009 Possible values in the list of contexts are `table', `headline', and `item'."
8010 (let ((pos (point)))
8011 (goto-char (point-at-bol))
8012 (prog1 (or (and (memq 'table contexts)
8013 (looking-at "[ \t]*|"))
8014 (and (memq 'headline contexts)
8015 ;;????????? (looking-at "\\*+"))
8016 (looking-at outline-regexp))
8017 (and (memq 'item contexts)
8018 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8019 (and (memq 'item-body contexts)
8020 (org-in-item-p)))
8021 (goto-char pos))))
8023 (defun org-get-local-variables ()
8024 "Return a list of all local variables in an org-mode buffer."
8025 (let (varlist)
8026 (with-current-buffer (get-buffer-create "*Org tmp*")
8027 (erase-buffer)
8028 (org-mode)
8029 (setq varlist (buffer-local-variables)))
8030 (kill-buffer "*Org tmp*")
8031 (delq nil
8032 (mapcar
8033 (lambda (x)
8034 (setq x
8035 (if (symbolp x)
8036 (list x)
8037 (list (car x) (list 'quote (cdr x)))))
8038 (if (string-match
8039 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8040 (symbol-name (car x)))
8041 x nil))
8042 varlist))))
8044 ;;;###autoload
8045 (defun org-run-like-in-org-mode (cmd)
8046 "Run a command, pretending that the current buffer is in Org-mode.
8047 This will temporarily bind local variables that are typically bound in
8048 Org-mode to the values they have in Org-mode, and then interactively
8049 call CMD."
8050 (org-load-modules-maybe)
8051 (unless org-local-vars
8052 (setq org-local-vars (org-get-local-variables)))
8053 (eval (list 'let org-local-vars
8054 (list 'call-interactively (list 'quote cmd)))))
8056 ;;;; Archiving
8058 (defun org-get-category (&optional pos)
8059 "Get the category applying to position POS."
8060 (get-text-property (or pos (point)) 'org-category))
8062 (defun org-refresh-category-properties ()
8063 "Refresh category text properties in the buffer."
8064 (let ((def-cat (cond
8065 ((null org-category)
8066 (if buffer-file-name
8067 (file-name-sans-extension
8068 (file-name-nondirectory buffer-file-name))
8069 "???"))
8070 ((symbolp org-category) (symbol-name org-category))
8071 (t org-category)))
8072 beg end cat pos optionp)
8073 (org-unmodified
8074 (save-excursion
8075 (save-restriction
8076 (widen)
8077 (goto-char (point-min))
8078 (put-text-property (point) (point-max) 'org-category def-cat)
8079 (while (re-search-forward
8080 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8081 (setq pos (match-end 0)
8082 optionp (equal (char-after (match-beginning 0)) ?#)
8083 cat (org-trim (match-string 2)))
8084 (if optionp
8085 (setq beg (point-at-bol) end (point-max))
8086 (org-back-to-heading t)
8087 (setq beg (point) end (org-end-of-subtree t t)))
8088 (put-text-property beg end 'org-category cat)
8089 (goto-char pos)))))))
8092 ;;;; Link Stuff
8094 ;;; Link abbreviations
8096 (defun org-link-expand-abbrev (link)
8097 "Apply replacements as defined in `org-link-abbrev-alist."
8098 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
8099 (let* ((key (match-string 1 link))
8100 (as (or (assoc key org-link-abbrev-alist-local)
8101 (assoc key org-link-abbrev-alist)))
8102 (tag (and (match-end 2) (match-string 3 link)))
8103 rpl)
8104 (if (not as)
8105 link
8106 (setq rpl (cdr as))
8107 (cond
8108 ((symbolp rpl) (funcall rpl tag))
8109 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8110 ((string-match "%h" rpl)
8111 (replace-match (url-hexify-string (or tag "")) t t rpl))
8112 (t (concat rpl tag)))))
8113 link))
8115 ;;; Storing and inserting links
8117 (defvar org-insert-link-history nil
8118 "Minibuffer history for links inserted with `org-insert-link'.")
8120 (defvar org-stored-links nil
8121 "Contains the links stored with `org-store-link'.")
8123 (defvar org-store-link-plist nil
8124 "Plist with info about the most recently link created with `org-store-link'.")
8126 (defvar org-link-protocols nil
8127 "Link protocols added to Org-mode using `org-add-link-type'.")
8129 (defvar org-store-link-functions nil
8130 "List of functions that are called to create and store a link.
8131 Each function will be called in turn until one returns a non-nil
8132 value. Each function should check if it is responsible for creating
8133 this link (for example by looking at the major mode).
8134 If not, it must exit and return nil.
8135 If yes, it should return a non-nil value after a calling
8136 `org-store-link-props' with a list of properties and values.
8137 Special properties are:
8139 :type The link prefix, like \"http\". This must be given.
8140 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8141 This is obligatory as well.
8142 :description Optional default description for the second pair
8143 of brackets in an Org-mode link. The user can still change
8144 this when inserting this link into an Org-mode buffer.
8146 In addition to these, any additional properties can be specified
8147 and then used in remember templates.")
8149 (defun org-add-link-type (type &optional follow export)
8150 "Add TYPE to the list of `org-link-types'.
8151 Re-compute all regular expressions depending on `org-link-types'
8153 FOLLOW and EXPORT are two functions.
8155 FOLLOW should take the link path as the single argument and do whatever
8156 is necessary to follow the link, for example find a file or display
8157 a mail message.
8159 EXPORT should format the link path for export to one of the export formats.
8160 It should be a function accepting three arguments:
8162 path the path of the link, the text after the prefix (like \"http:\")
8163 desc the description of the link, if any, nil if there was no description
8164 format the export format, a symbol like `html' or `latex'.
8166 The function may use the FORMAT information to return different values
8167 depending on the format. The return value will be put literally into
8168 the exported file.
8169 Org-mode has a built-in default for exporting links. If you are happy with
8170 this default, there is no need to define an export function for the link
8171 type. For a simple example of an export function, see `org-bbdb.el'."
8172 (add-to-list 'org-link-types type t)
8173 (org-make-link-regexps)
8174 (if (assoc type org-link-protocols)
8175 (setcdr (assoc type org-link-protocols) (list follow export))
8176 (push (list type follow export) org-link-protocols)))
8178 (defvar org-agenda-buffer-name)
8180 ;;;###autoload
8181 (defun org-store-link (arg)
8182 "\\<org-mode-map>Store an org-link to the current location.
8183 This link is added to `org-stored-links' and can later be inserted
8184 into an org-buffer with \\[org-insert-link].
8186 For some link types, a prefix arg is interpreted:
8187 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8188 For file links, arg negates `org-context-in-file-links'."
8189 (interactive "P")
8190 (org-load-modules-maybe)
8191 (setq org-store-link-plist nil) ; reset
8192 (let ((outline-regexp (org-get-limited-outline-regexp))
8193 link cpltxt desc description search txt custom-id)
8194 (cond
8196 ((run-hook-with-args-until-success 'org-store-link-functions)
8197 (setq link (plist-get org-store-link-plist :link)
8198 desc (or (plist-get org-store-link-plist :description) link)))
8200 ((equal (buffer-name) "*Org Edit Src Example*")
8201 (let (label gc)
8202 (while (or (not label)
8203 (save-excursion
8204 (save-restriction
8205 (widen)
8206 (goto-char (point-min))
8207 (re-search-forward
8208 (regexp-quote (format org-coderef-label-format label))
8209 nil t))))
8210 (when label (message "Label exists already") (sit-for 2))
8211 (setq label (read-string "Code line label: " label)))
8212 (end-of-line 1)
8213 (setq link (format org-coderef-label-format label))
8214 (setq gc (- 79 (length link)))
8215 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8216 (insert link)
8217 (setq link (concat "(" label ")") desc nil)))
8219 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8220 ;; We are in the agenda, link to referenced location
8221 (let ((m (or (get-text-property (point) 'org-hd-marker)
8222 (get-text-property (point) 'org-marker))))
8223 (when m
8224 (org-with-point-at m
8225 (if (interactive-p)
8226 (call-interactively 'org-store-link)
8227 (org-store-link nil))))))
8229 ((eq major-mode 'calendar-mode)
8230 (let ((cd (calendar-cursor-to-date)))
8231 (setq link
8232 (format-time-string
8233 (car org-time-stamp-formats)
8234 (apply 'encode-time
8235 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8236 nil nil nil))))
8237 (org-store-link-props :type "calendar" :date cd)))
8239 ((eq major-mode 'w3-mode)
8240 (setq cpltxt (if (and (buffer-name)
8241 (not (string-match "Untitled" (buffer-name))))
8242 (buffer-name)
8243 (url-view-url t))
8244 link (org-make-link (url-view-url t)))
8245 (org-store-link-props :type "w3" :url (url-view-url t)))
8247 ((eq major-mode 'w3m-mode)
8248 (setq cpltxt (or w3m-current-title w3m-current-url)
8249 link (org-make-link w3m-current-url))
8250 (org-store-link-props :type "w3m" :url (url-view-url t)))
8252 ((setq search (run-hook-with-args-until-success
8253 'org-create-file-search-functions))
8254 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8255 "::" search))
8256 (setq cpltxt (or description link)))
8258 ((eq major-mode 'image-mode)
8259 (setq cpltxt (concat "file:"
8260 (abbreviate-file-name buffer-file-name))
8261 link (org-make-link cpltxt))
8262 (org-store-link-props :type "image" :file buffer-file-name))
8264 ((eq major-mode 'dired-mode)
8265 ;; link to the file in the current line
8266 (let ((file (dired-get-filename nil t)))
8267 (setq file (if file
8268 (abbreviate-file-name
8269 (expand-file-name (dired-get-filename nil t)))
8270 ;; otherwise, no file so use current directory.
8271 default-directory))
8272 (setq cpltxt (concat "file:" file)
8273 link (org-make-link cpltxt))))
8275 ((and buffer-file-name (org-mode-p))
8276 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
8277 (cond
8278 ((org-in-regexp "<<\\(.*?\\)>>")
8279 (setq cpltxt
8280 (concat "file:"
8281 (abbreviate-file-name buffer-file-name)
8282 "::" (match-string 1))
8283 link (org-make-link cpltxt)))
8284 ((and (featurep 'org-id)
8285 (or (eq org-link-to-org-use-id t)
8286 (and (eq org-link-to-org-use-id 'create-if-interactive)
8287 (interactive-p))
8288 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
8289 (interactive-p)
8290 (not custom-id))
8291 (and org-link-to-org-use-id
8292 (condition-case nil
8293 (org-entry-get nil "ID")
8294 (error nil)))))
8295 ;; We can make a link using the ID.
8296 (setq link (condition-case nil
8297 (prog1 (org-id-store-link)
8298 (setq desc (plist-get org-store-link-plist
8299 :description)))
8300 (error
8301 ;; probably before first headline, link to file only
8302 (concat "file:"
8303 (abbreviate-file-name buffer-file-name))))))
8305 ;; Just link to current headline
8306 (setq cpltxt (concat "file:"
8307 (abbreviate-file-name buffer-file-name)))
8308 ;; Add a context search string
8309 (when (org-xor org-context-in-file-links arg)
8310 (setq txt (cond
8311 ((org-on-heading-p) nil)
8312 ((org-region-active-p)
8313 (buffer-substring (region-beginning) (region-end)))
8314 (t nil)))
8315 (when (or (null txt) (string-match "\\S-" txt))
8316 (setq cpltxt
8317 (concat cpltxt "::"
8318 (condition-case nil
8319 (org-make-org-heading-search-string txt)
8320 (error "")))
8321 desc (or (nth 4 (ignore-errors
8322 (org-heading-components))) "NONE"))))
8323 (if (string-match "::\\'" cpltxt)
8324 (setq cpltxt (substring cpltxt 0 -2)))
8325 (setq link (org-make-link cpltxt)))))
8327 ((buffer-file-name (buffer-base-buffer))
8328 ;; Just link to this file here.
8329 (setq cpltxt (concat "file:"
8330 (abbreviate-file-name
8331 (buffer-file-name (buffer-base-buffer)))))
8332 ;; Add a context string
8333 (when (org-xor org-context-in-file-links arg)
8334 (setq txt (if (org-region-active-p)
8335 (buffer-substring (region-beginning) (region-end))
8336 (buffer-substring (point-at-bol) (point-at-eol))))
8337 ;; Only use search option if there is some text.
8338 (when (string-match "\\S-" txt)
8339 (setq cpltxt
8340 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8341 desc "NONE")))
8342 (setq link (org-make-link cpltxt)))
8344 ((interactive-p)
8345 (error "Cannot link to a buffer which is not visiting a file"))
8347 (t (setq link nil)))
8349 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8350 (setq link (or link cpltxt)
8351 desc (or desc cpltxt))
8352 (if (equal desc "NONE") (setq desc nil))
8354 (if (and (or (interactive-p) executing-kbd-macro) link)
8355 (progn
8356 (setq org-stored-links
8357 (cons (list link desc) org-stored-links))
8358 (message "Stored: %s" (or desc link))
8359 (when custom-id
8360 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8361 "::#" custom-id))
8362 (setq org-stored-links
8363 (cons (list link desc) org-stored-links))))
8364 (and link (org-make-link-string link desc)))))
8366 (defun org-store-link-props (&rest plist)
8367 "Store link properties, extract names and addresses."
8368 (let (x adr)
8369 (when (setq x (plist-get plist :from))
8370 (setq adr (mail-extract-address-components x))
8371 (setq plist (plist-put plist :fromname (car adr)))
8372 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8373 (when (setq x (plist-get plist :to))
8374 (setq adr (mail-extract-address-components x))
8375 (setq plist (plist-put plist :toname (car adr)))
8376 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8377 (let ((from (plist-get plist :from))
8378 (to (plist-get plist :to)))
8379 (when (and from to org-from-is-user-regexp)
8380 (setq plist
8381 (plist-put plist :fromto
8382 (if (string-match org-from-is-user-regexp from)
8383 (concat "to %t")
8384 (concat "from %f"))))))
8385 (setq org-store-link-plist plist))
8387 (defun org-add-link-props (&rest plist)
8388 "Add these properties to the link property list."
8389 (let (key value)
8390 (while plist
8391 (setq key (pop plist) value (pop plist))
8392 (setq org-store-link-plist
8393 (plist-put org-store-link-plist key value)))))
8395 (defun org-email-link-description (&optional fmt)
8396 "Return the description part of an email link.
8397 This takes information from `org-store-link-plist' and formats it
8398 according to FMT (default from `org-email-link-description-format')."
8399 (setq fmt (or fmt org-email-link-description-format))
8400 (let* ((p org-store-link-plist)
8401 (to (plist-get p :toaddress))
8402 (from (plist-get p :fromaddress))
8403 (table
8404 (list
8405 (cons "%c" (plist-get p :fromto))
8406 (cons "%F" (plist-get p :from))
8407 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8408 (cons "%T" (plist-get p :to))
8409 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8410 (cons "%s" (plist-get p :subject))
8411 (cons "%m" (plist-get p :message-id)))))
8412 (when (string-match "%c" fmt)
8413 ;; Check if the user wrote this message
8414 (if (and org-from-is-user-regexp from to
8415 (save-match-data (string-match org-from-is-user-regexp from)))
8416 (setq fmt (replace-match "to %t" t t fmt))
8417 (setq fmt (replace-match "from %f" t t fmt))))
8418 (org-replace-escapes fmt table)))
8420 (defun org-make-org-heading-search-string (&optional string heading)
8421 "Make search string for STRING or current headline."
8422 (interactive)
8423 (let ((s (or string (org-get-heading))))
8424 (unless (and string (not heading))
8425 ;; We are using a headline, clean up garbage in there.
8426 (if (string-match org-todo-regexp s)
8427 (setq s (replace-match "" t t s)))
8428 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
8429 (setq s (replace-match "" t t s)))
8430 (setq s (org-trim s))
8431 (if (string-match (concat "^\\(" org-quote-string "\\|"
8432 org-comment-string "\\)") s)
8433 (setq s (replace-match "" t t s)))
8434 (while (string-match org-ts-regexp s)
8435 (setq s (replace-match "" t t s))))
8436 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
8437 (setq s (replace-match " " t t s)))
8438 (or string (setq s (concat "*" s))) ; Add * for headlines
8439 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8441 (defun org-make-link (&rest strings)
8442 "Concatenate STRINGS."
8443 (apply 'concat strings))
8445 (defun org-make-link-string (link &optional description)
8446 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8447 (unless (string-match "\\S-" link)
8448 (error "Empty link"))
8449 (when (and description
8450 (stringp description)
8451 (not (string-match "\\S-" description)))
8452 (setq description nil))
8453 (when (stringp description)
8454 ;; Remove brackets from the description, they are fatal.
8455 (while (string-match "\\[" description)
8456 (setq description (replace-match "{" t t description)))
8457 (while (string-match "\\]" description)
8458 (setq description (replace-match "}" t t description))))
8459 (when (equal (org-link-escape link) description)
8460 ;; No description needed, it is identical
8461 (setq description nil))
8462 (when (and (not description)
8463 (not (equal link (org-link-escape link))))
8464 (setq description (org-extract-attributes link)))
8465 (concat "[[" (org-link-escape link) "]"
8466 (if description (concat "[" description "]") "")
8467 "]"))
8469 (defconst org-link-escape-chars
8470 '((?\ . "%20")
8471 (?\[ . "%5B")
8472 (?\] . "%5D")
8473 (?\340 . "%E0") ; `a
8474 (?\342 . "%E2") ; ^a
8475 (?\347 . "%E7") ; ,c
8476 (?\350 . "%E8") ; `e
8477 (?\351 . "%E9") ; 'e
8478 (?\352 . "%EA") ; ^e
8479 (?\356 . "%EE") ; ^i
8480 (?\364 . "%F4") ; ^o
8481 (?\371 . "%F9") ; `u
8482 (?\373 . "%FB") ; ^u
8483 (?\; . "%3B")
8484 ;; (?? . "%3F")
8485 (?= . "%3D")
8486 (?+ . "%2B")
8488 "Association list of escapes for some characters problematic in links.
8489 This is the list that is used for internal purposes.")
8491 (defvar org-url-encoding-use-url-hexify nil)
8493 (defconst org-link-escape-chars-browser
8494 '((?\ . "%20")) ; 32 for the SPC char
8495 "Association list of escapes for some characters problematic in links.
8496 This is the list that is used before handing over to the browser.")
8498 (defun org-link-escape (text &optional table)
8499 "Escape characters in TEXT that are problematic for links."
8500 (if (and org-url-encoding-use-url-hexify (not table))
8501 (url-hexify-string text)
8502 (setq table (or table org-link-escape-chars))
8503 (when text
8504 (let ((re (mapconcat (lambda (x) (regexp-quote
8505 (char-to-string (car x))))
8506 table "\\|")))
8507 (while (string-match re text)
8508 (setq text
8509 (replace-match
8510 (cdr (assoc (string-to-char (match-string 0 text))
8511 table))
8512 t t text)))
8513 text))))
8515 (defun org-link-unescape (text &optional table)
8516 "Reverse the action of `org-link-escape'."
8517 (if (and org-url-encoding-use-url-hexify (not table))
8518 (url-unhex-string text)
8519 (setq table (or table org-link-escape-chars))
8520 (when text
8521 (let ((case-fold-search t)
8522 (re (mapconcat (lambda (x) (regexp-quote (downcase (cdr x))))
8523 table "\\|")))
8524 (while (string-match re text)
8525 (setq text
8526 (replace-match
8527 (char-to-string (car (rassoc (upcase (match-string 0 text))
8528 table)))
8529 t t text)))
8530 text))))
8532 (defun org-xor (a b)
8533 "Exclusive or."
8534 (if a (not b) b))
8536 (defun org-fixup-message-id-for-http (s)
8537 "Replace special characters in a message id, so it can be used in an http query."
8538 (when (string-match "%" s)
8539 (setq s (mapconcat (lambda (c)
8540 (if (eq c ?%)
8541 "%25"
8542 (char-to-string c)))
8543 s "")))
8544 (while (string-match "<" s)
8545 (setq s (replace-match "%3C" t t s)))
8546 (while (string-match ">" s)
8547 (setq s (replace-match "%3E" t t s)))
8548 (while (string-match "@" s)
8549 (setq s (replace-match "%40" t t s)))
8552 ;;;###autoload
8553 (defun org-insert-link-global ()
8554 "Insert a link like Org-mode does.
8555 This command can be called in any mode to insert a link in Org-mode syntax."
8556 (interactive)
8557 (org-load-modules-maybe)
8558 (org-run-like-in-org-mode 'org-insert-link))
8560 (defun org-insert-link (&optional complete-file link-location)
8561 "Insert a link. At the prompt, enter the link.
8563 Completion can be used to insert any of the link protocol prefixes like
8564 http or ftp in use.
8566 The history can be used to select a link previously stored with
8567 `org-store-link'. When the empty string is entered (i.e. if you just
8568 press RET at the prompt), the link defaults to the most recently
8569 stored link. As SPC triggers completion in the minibuffer, you need to
8570 use M-SPC or C-q SPC to force the insertion of a space character.
8572 You will also be prompted for a description, and if one is given, it will
8573 be displayed in the buffer instead of the link.
8575 If there is already a link at point, this command will allow you to edit link
8576 and description parts.
8578 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
8579 be selected using completion. The path to the file will be relative to the
8580 current directory if the file is in the current directory or a subdirectory.
8581 Otherwise, the link will be the absolute path as completed in the minibuffer
8582 \(i.e. normally ~/path/to/file). You can configure this behavior using the
8583 option `org-link-file-path-type'.
8585 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
8586 the current directory or below.
8588 With three \\[universal-argument] prefixes, negate the meaning of
8589 `org-keep-stored-link-after-insertion'.
8591 If `org-make-link-description-function' is non-nil, this function will be
8592 called with the link target, and the result will be the default
8593 link description.
8595 If the LINK-LOCATION parameter is non-nil, this value will be
8596 used as the link location instead of reading one interactively."
8597 (interactive "P")
8598 (let* ((wcf (current-window-configuration))
8599 (region (if (org-region-active-p)
8600 (buffer-substring (region-beginning) (region-end))))
8601 (remove (and region (list (region-beginning) (region-end))))
8602 (desc region)
8603 tmphist ; byte-compile incorrectly complains about this
8604 (link link-location)
8605 entry file all-prefixes)
8606 (cond
8607 (link-location) ; specified by arg, just use it.
8608 ((org-in-regexp org-bracket-link-regexp 1)
8609 ;; We do have a link at point, and we are going to edit it.
8610 (setq remove (list (match-beginning 0) (match-end 0)))
8611 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
8612 (setq link (read-string "Link: "
8613 (org-link-unescape
8614 (org-match-string-no-properties 1)))))
8615 ((or (org-in-regexp org-angle-link-re)
8616 (org-in-regexp org-plain-link-re))
8617 ;; Convert to bracket link
8618 (setq remove (list (match-beginning 0) (match-end 0))
8619 link (read-string "Link: "
8620 (org-remove-angle-brackets (match-string 0)))))
8621 ((member complete-file '((4) (16)))
8622 ;; Completing read for file names.
8623 (setq link (org-file-complete-link complete-file)))
8625 ;; Read link, with completion for stored links.
8626 (with-output-to-temp-buffer "*Org Links*"
8627 (princ "Insert a link.
8628 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
8629 (when org-stored-links
8630 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
8631 (princ (mapconcat
8632 (lambda (x)
8633 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
8634 (reverse org-stored-links) "\n"))))
8635 (let ((cw (selected-window)))
8636 (select-window (get-buffer-window "*Org Links*" 'visible))
8637 (setq truncate-lines t)
8638 (unless (pos-visible-in-window-p (point-max))
8639 (org-fit-window-to-buffer))
8640 (and (window-live-p cw) (select-window cw)))
8641 ;; Fake a link history, containing the stored links.
8642 (setq tmphist (append (mapcar 'car org-stored-links)
8643 org-insert-link-history))
8644 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
8645 (mapcar 'car org-link-abbrev-alist)
8646 org-link-types))
8647 (unwind-protect
8648 (progn
8649 (setq link
8650 (let ((org-completion-use-ido nil)
8651 (org-completion-use-iswitchb nil))
8652 (org-completing-read
8653 "Link: "
8654 (append
8655 (mapcar (lambda (x) (list (concat x ":")))
8656 all-prefixes)
8657 (mapcar 'car org-stored-links))
8658 nil nil nil
8659 'tmphist
8660 (car (car org-stored-links)))))
8661 (if (not (string-match "\\S-" link))
8662 (error "No link selected"))
8663 (if (or (member link all-prefixes)
8664 (and (equal ":" (substring link -1))
8665 (member (substring link 0 -1) all-prefixes)
8666 (setq link (substring link 0 -1))))
8667 (setq link (org-link-try-special-completion link))))
8668 (set-window-configuration wcf)
8669 (kill-buffer "*Org Links*"))
8670 (setq entry (assoc link org-stored-links))
8671 (or entry (push link org-insert-link-history))
8672 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
8673 (not org-keep-stored-link-after-insertion))
8674 (setq org-stored-links (delq (assoc link org-stored-links)
8675 org-stored-links)))
8676 (setq desc (or desc (nth 1 entry)))))
8678 (if (string-match org-plain-link-re link)
8679 ;; URL-like link, normalize the use of angular brackets.
8680 (setq link (org-make-link (org-remove-angle-brackets link))))
8682 ;; Check if we are linking to the current file with a search option
8683 ;; If yes, simplify the link by using only the search option.
8684 (when (and buffer-file-name
8685 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
8686 (let* ((path (match-string 1 link))
8687 (case-fold-search nil)
8688 (search (match-string 2 link)))
8689 (save-match-data
8690 (if (equal (file-truename buffer-file-name) (file-truename path))
8691 ;; We are linking to this same file, with a search option
8692 (setq link search)))))
8694 ;; Check if we can/should use a relative path. If yes, simplify the link
8695 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
8696 (let* ((type (match-string 1 link))
8697 (path (match-string 2 link))
8698 (origpath path)
8699 (case-fold-search nil))
8700 (cond
8701 ((or (eq org-link-file-path-type 'absolute)
8702 (equal complete-file '(16)))
8703 (setq path (abbreviate-file-name (expand-file-name path))))
8704 ((eq org-link-file-path-type 'noabbrev)
8705 (setq path (expand-file-name path)))
8706 ((eq org-link-file-path-type 'relative)
8707 (setq path (file-relative-name path)))
8709 (save-match-data
8710 (if (string-match (concat "^" (regexp-quote
8711 (expand-file-name
8712 (file-name-as-directory
8713 default-directory))))
8714 (expand-file-name path))
8715 ;; We are linking a file with relative path name.
8716 (setq path (substring (expand-file-name path)
8717 (match-end 0)))
8718 (setq path (abbreviate-file-name (expand-file-name path)))))))
8719 (setq link (concat type path))
8720 (if (equal desc origpath)
8721 (setq desc path))))
8723 (if org-make-link-description-function
8724 (setq desc (funcall org-make-link-description-function link desc)))
8726 (setq desc (read-string "Description: " desc))
8727 (unless (string-match "\\S-" desc) (setq desc nil))
8728 (if remove (apply 'delete-region remove))
8729 (insert (org-make-link-string link desc))))
8731 (defun org-link-try-special-completion (type)
8732 "If there is completion support for link type TYPE, offer it."
8733 (let ((fun (intern (concat "org-" type "-complete-link"))))
8734 (if (functionp fun)
8735 (funcall fun)
8736 (read-string "Link (no completion support): " (concat type ":")))))
8738 (defun org-file-complete-link (&optional arg)
8739 "Create a file link using completion."
8740 (let (file link)
8741 (setq file (read-file-name "File: "))
8742 (let ((pwd (file-name-as-directory (expand-file-name ".")))
8743 (pwd1 (file-name-as-directory (abbreviate-file-name
8744 (expand-file-name ".")))))
8745 (cond
8746 ((equal arg '(16))
8747 (setq link (org-make-link
8748 "file:"
8749 (abbreviate-file-name (expand-file-name file)))))
8750 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
8751 (setq link (org-make-link "file:" (match-string 1 file))))
8752 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
8753 (expand-file-name file))
8754 (setq link (org-make-link
8755 "file:" (match-string 1 (expand-file-name file)))))
8756 (t (setq link (org-make-link "file:" file)))))
8757 link))
8759 (defun org-completing-read (&rest args)
8760 "Completing-read with SPACE being a normal character."
8761 (let ((minibuffer-local-completion-map
8762 (copy-keymap minibuffer-local-completion-map)))
8763 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
8764 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
8765 (apply 'org-icompleting-read args)))
8767 (defun org-completing-read-no-i (&rest args)
8768 (let (org-completion-use-ido org-completion-use-iswitchb)
8769 (apply 'org-completing-read args)))
8771 (defun org-iswitchb-completing-read (prompt choices &rest args)
8772 "Use iswitch as a completing-read replacement to choose from choices.
8773 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
8774 from."
8775 (let* ((iswitchb-use-virtual-buffers nil)
8776 (iswitchb-make-buflist-hook
8777 (lambda ()
8778 (setq iswitchb-temp-buflist choices))))
8779 (iswitchb-read-buffer prompt)))
8781 (defun org-icompleting-read (&rest args)
8782 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
8783 (org-without-partial-completion
8784 (if (and org-completion-use-ido
8785 (fboundp 'ido-completing-read)
8786 (boundp 'ido-mode) ido-mode
8787 (listp (second args)))
8788 (let ((ido-enter-matching-directory nil))
8789 (apply 'ido-completing-read (concat (car args))
8790 (if (consp (car (nth 1 args)))
8791 (mapcar (lambda (x) (car x)) (nth 1 args))
8792 (nth 1 args))
8793 (cddr args)))
8794 (if (and org-completion-use-iswitchb
8795 (boundp 'iswitchb-mode) iswitchb-mode
8796 (listp (second args)))
8797 (apply 'org-iswitchb-completing-read (concat (car args))
8798 (if (consp (car (nth 1 args)))
8799 (mapcar (lambda (x) (car x)) (nth 1 args))
8800 (nth 1 args))
8801 (cddr args))
8802 (apply 'completing-read args)))))
8804 (defun org-extract-attributes (s)
8805 "Extract the attributes cookie from a string and set as text property."
8806 (let (a attr (start 0) key value)
8807 (save-match-data
8808 (when (string-match "{{\\([^}]+\\)}}$" s)
8809 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
8810 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
8811 (setq key (match-string 1 a) value (match-string 2 a)
8812 start (match-end 0)
8813 attr (plist-put attr (intern key) value))))
8814 (org-add-props s nil 'org-attr attr))
8817 (defun org-extract-attributes-from-string (tag)
8818 (let (key value attr)
8819 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
8820 (setq key (match-string 1 tag) value (match-string 2 tag)
8821 tag (replace-match "" t t tag)
8822 attr (plist-put attr (intern key) value)))
8823 (cons tag attr)))
8825 (defun org-attributes-to-string (plist)
8826 "Format a property list into an HTML attribute list."
8827 (let ((s "") key value)
8828 (while plist
8829 (setq key (pop plist) value (pop plist))
8830 (and value
8831 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
8834 ;;; Opening/following a link
8836 (defvar org-link-search-failed nil)
8838 (defvar org-open-link-functions nil
8839 "Hook for functions finding a plain text link.
8840 These functions must take a single argument, the link content.
8841 They will be called for links that look like [[link text][description]]
8842 when LINK TEXT does not have a protocol like \"http:\" and does not look
8843 like a filename (e.g. \"./blue.png\").
8845 These functions will be called *before* Org attempts to resolve the
8846 link by doing text searches in the current buffer - so if you want a
8847 link \"[[target]]\" to still find \"<<target>>\", your function should
8848 handle this as a special case.
8850 When the function does handle the link, it must return a non-nil value.
8851 If it decides that it is not responsible for this link, it must return
8852 nil to indicate that that Org-mode can continue with other options
8853 like exact and fuzzy text search.")
8855 (defun org-next-link ()
8856 "Move forward to the next link.
8857 If the link is in hidden text, expose it."
8858 (interactive)
8859 (when (and org-link-search-failed (eq this-command last-command))
8860 (goto-char (point-min))
8861 (message "Link search wrapped back to beginning of buffer"))
8862 (setq org-link-search-failed nil)
8863 (let* ((pos (point))
8864 (ct (org-context))
8865 (a (assoc :link ct)))
8866 (if a (goto-char (nth 2 a)))
8867 (if (re-search-forward org-any-link-re nil t)
8868 (progn
8869 (goto-char (match-beginning 0))
8870 (if (org-invisible-p) (org-show-context)))
8871 (goto-char pos)
8872 (setq org-link-search-failed t)
8873 (error "No further link found"))))
8875 (defun org-previous-link ()
8876 "Move backward to the previous link.
8877 If the link is in hidden text, expose it."
8878 (interactive)
8879 (when (and org-link-search-failed (eq this-command last-command))
8880 (goto-char (point-max))
8881 (message "Link search wrapped back to end of buffer"))
8882 (setq org-link-search-failed nil)
8883 (let* ((pos (point))
8884 (ct (org-context))
8885 (a (assoc :link ct)))
8886 (if a (goto-char (nth 1 a)))
8887 (if (re-search-backward org-any-link-re nil t)
8888 (progn
8889 (goto-char (match-beginning 0))
8890 (if (org-invisible-p) (org-show-context)))
8891 (goto-char pos)
8892 (setq org-link-search-failed t)
8893 (error "No further link found"))))
8895 (defun org-translate-link (s)
8896 "Translate a link string if a translation function has been defined."
8897 (if (and org-link-translation-function
8898 (fboundp org-link-translation-function)
8899 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
8900 (progn
8901 (setq s (funcall org-link-translation-function
8902 (match-string 1) (match-string 2)))
8903 (concat (car s) ":" (cdr s)))
8906 (defun org-translate-link-from-planner (type path)
8907 "Translate a link from Emacs Planner syntax so that Org can follow it.
8908 This is still an experimental function, your mileage may vary."
8909 (cond
8910 ((member type '("http" "https" "news" "ftp"))
8911 ;; standard Internet links are the same.
8912 nil)
8913 ((and (equal type "irc") (string-match "^//" path))
8914 ;; Planner has two / at the beginning of an irc link, we have 1.
8915 ;; We should have zero, actually....
8916 (setq path (substring path 1)))
8917 ((and (equal type "lisp") (string-match "^/" path))
8918 ;; Planner has a slash, we do not.
8919 (setq type "elisp" path (substring path 1)))
8920 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
8921 ;; A typical message link. Planner has the id after the final slash,
8922 ;; we separate it with a hash mark
8923 (setq path (concat (match-string 1 path) "#"
8924 (org-remove-angle-brackets (match-string 2 path)))))
8926 (cons type path))
8928 (defun org-find-file-at-mouse (ev)
8929 "Open file link or URL at mouse."
8930 (interactive "e")
8931 (mouse-set-point ev)
8932 (org-open-at-point 'in-emacs))
8934 (defun org-open-at-mouse (ev)
8935 "Open file link or URL at mouse."
8936 (interactive "e")
8937 (mouse-set-point ev)
8938 (if (eq major-mode 'org-agenda-mode)
8939 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
8940 (org-open-at-point))
8942 (defvar org-window-config-before-follow-link nil
8943 "The window configuration before following a link.
8944 This is saved in case the need arises to restore it.")
8946 (defvar org-open-link-marker (make-marker)
8947 "Marker pointing to the location where `org-open-at-point; was called.")
8949 ;;;###autoload
8950 (defun org-open-at-point-global ()
8951 "Follow a link like Org-mode does.
8952 This command can be called in any mode to follow a link that has
8953 Org-mode syntax."
8954 (interactive)
8955 (org-run-like-in-org-mode 'org-open-at-point))
8957 ;;;###autoload
8958 (defun org-open-link-from-string (s &optional arg reference-buffer)
8959 "Open a link in the string S, as if it was in Org-mode."
8960 (interactive "sLink: \nP")
8961 (let ((reference-buffer (or reference-buffer (current-buffer))))
8962 (with-temp-buffer
8963 (let ((org-inhibit-startup t))
8964 (org-mode)
8965 (insert s)
8966 (goto-char (point-min))
8967 (when reference-buffer
8968 (setq org-link-abbrev-alist-local
8969 (with-current-buffer reference-buffer
8970 org-link-abbrev-alist-local)))
8971 (org-open-at-point arg reference-buffer)))))
8973 (defun org-open-at-point (&optional in-emacs reference-buffer)
8974 "Open link at or after point.
8975 If there is no link at point, this function will search forward up to
8976 the end of the current line.
8977 Normally, files will be opened by an appropriate application. If the
8978 optional argument IN-EMACS is non-nil, Emacs will visit the file.
8979 With a double prefix argument, try to open outside of Emacs, in the
8980 application the system uses for this file type."
8981 (interactive "P")
8982 ;; if in a code block, then open the block's results
8983 (unless (call-interactively #'org-babel-open-src-block-result)
8984 (org-load-modules-maybe)
8985 (move-marker org-open-link-marker (point))
8986 (setq org-window-config-before-follow-link (current-window-configuration))
8987 (org-remove-occur-highlights nil nil t)
8988 (cond
8989 ((and (org-on-heading-p)
8990 (not (org-in-regexp
8991 (concat org-plain-link-re "\\|"
8992 org-bracket-link-regexp "\\|"
8993 org-angle-link-re "\\|"
8994 "[ \t]:[^ \t\n]+:[ \t]*$")))
8995 (not (get-text-property (point) 'org-linked-text)))
8996 (or (org-offer-links-in-entry in-emacs)
8997 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
8998 ((org-at-timestamp-p t) (org-follow-timestamp-link))
8999 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9000 (org-footnote-action))
9002 (let (type path link line search (pos (point)))
9003 (catch 'match
9004 (save-excursion
9005 (skip-chars-forward "^]\n\r")
9006 (when (org-in-regexp org-bracket-link-regexp 1)
9007 (setq link (org-extract-attributes
9008 (org-link-unescape (org-match-string-no-properties 1))))
9009 (while (string-match " *\n *" link)
9010 (setq link (replace-match " " t t link)))
9011 (setq link (org-link-expand-abbrev link))
9012 (cond
9013 ((or (file-name-absolute-p link)
9014 (string-match "^\\.\\.?/" link))
9015 (setq type "file" path link))
9016 ((string-match org-link-re-with-space3 link)
9017 (setq type (match-string 1 link) path (match-string 2 link)))
9018 (t (setq type "thisfile" path link)))
9019 (throw 'match t)))
9021 (when (get-text-property (point) 'org-linked-text)
9022 (setq type "thisfile"
9023 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9024 (1+ (point)) (point))
9025 path (buffer-substring
9026 (previous-single-property-change pos 'org-linked-text)
9027 (next-single-property-change pos 'org-linked-text)))
9028 (throw 'match t))
9030 (save-excursion
9031 (when (or (org-in-regexp org-angle-link-re)
9032 (org-in-regexp org-plain-link-re))
9033 (setq type (match-string 1) path (match-string 2))
9034 (throw 'match t)))
9035 (save-excursion
9036 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
9037 (setq type "tags"
9038 path (match-string 1))
9039 (while (string-match ":" path)
9040 (setq path (replace-match "+" t t path)))
9041 (throw 'match t)))
9042 (when (org-in-regexp "<\\([^><\n]+\\)>")
9043 (setq type "tree-match"
9044 path (match-string 1))
9045 (throw 'match t)))
9046 (unless path
9047 (error "No link found"))
9049 ;; switch back to reference buffer
9050 ;; needed when if called in a temporary buffer through
9051 ;; org-open-link-from-string
9052 (with-current-buffer (or reference-buffer (current-buffer))
9054 ;; Remove any trailing spaces in path
9055 (if (string-match " +\\'" path)
9056 (setq path (replace-match "" t t path)))
9057 (if (and org-link-translation-function
9058 (fboundp org-link-translation-function))
9059 ;; Check if we need to translate the link
9060 (let ((tmp (funcall org-link-translation-function type path)))
9061 (setq type (car tmp) path (cdr tmp))))
9063 (cond
9065 ((assoc type org-link-protocols)
9066 (funcall (nth 1 (assoc type org-link-protocols)) path))
9068 ((equal type "mailto")
9069 (let ((cmd (car org-link-mailto-program))
9070 (args (cdr org-link-mailto-program)) args1
9071 (address path) (subject "") a)
9072 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9073 (setq address (match-string 1 path)
9074 subject (org-link-escape (match-string 2 path))))
9075 (while args
9076 (cond
9077 ((not (stringp (car args))) (push (pop args) args1))
9078 (t (setq a (pop args))
9079 (if (string-match "%a" a)
9080 (setq a (replace-match address t t a)))
9081 (if (string-match "%s" a)
9082 (setq a (replace-match subject t t a)))
9083 (push a args1))))
9084 (apply cmd (nreverse args1))))
9086 ((member type '("http" "https" "ftp" "news"))
9087 (browse-url (concat type ":" (org-link-escape
9088 path org-link-escape-chars-browser))))
9090 ((string= type "doi")
9091 (browse-url (concat "http://dx.doi.org/"
9092 (org-link-escape
9093 path org-link-escape-chars-browser))))
9095 ((member type '("message"))
9096 (browse-url (concat type ":" path)))
9098 ((string= type "tags")
9099 (org-tags-view in-emacs path))
9101 ((string= type "tree-match")
9102 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9104 ((string= type "file")
9105 (if (string-match "::\\([0-9]+\\)\\'" path)
9106 (setq line (string-to-number (match-string 1 path))
9107 path (substring path 0 (match-beginning 0)))
9108 (if (string-match "::\\(.+\\)\\'" path)
9109 (setq search (match-string 1 path)
9110 path (substring path 0 (match-beginning 0)))))
9111 (if (string-match "[*?{]" (file-name-nondirectory path))
9112 (dired path)
9113 (org-open-file path in-emacs line search)))
9115 ((string= type "news")
9116 (require 'org-gnus)
9117 (org-gnus-follow-link path))
9119 ((string= type "shell")
9120 (let ((cmd path))
9121 (if (or (not org-confirm-shell-link-function)
9122 (funcall org-confirm-shell-link-function
9123 (format "Execute \"%s\" in shell? "
9124 (org-add-props cmd nil
9125 'face 'org-warning))))
9126 (progn
9127 (message "Executing %s" cmd)
9128 (shell-command cmd))
9129 (error "Abort"))))
9131 ((string= type "elisp")
9132 (let ((cmd path))
9133 (if (or (not org-confirm-elisp-link-function)
9134 (funcall org-confirm-elisp-link-function
9135 (format "Execute \"%s\" as elisp? "
9136 (org-add-props cmd nil
9137 'face 'org-warning))))
9138 (message "%s => %s" cmd
9139 (if (equal (string-to-char cmd) ?\()
9140 (eval (read cmd))
9141 (call-interactively (read cmd))))
9142 (error "Abort"))))
9144 ((and (string= type "thisfile")
9145 (run-hook-with-args-until-success
9146 'org-open-link-functions path)))
9148 ((string= type "thisfile")
9149 (if in-emacs
9150 (switch-to-buffer-other-window
9151 (org-get-buffer-for-internal-link (current-buffer)))
9152 (org-mark-ring-push))
9153 (let ((cmd `(org-link-search
9154 ,path
9155 ,(cond ((equal in-emacs '(4)) 'occur)
9156 ((equal in-emacs '(16)) 'org-occur)
9157 (t nil))
9158 ,pos)))
9159 (condition-case nil (eval cmd)
9160 (error (progn (widen) (eval cmd))))))
9163 (browse-url-at-point)))))))
9164 (move-marker org-open-link-marker nil)
9165 (run-hook-with-args 'org-follow-link-hook)))
9167 (defun org-offer-links-in-entry (&optional nth zero)
9168 "Offer links in the current entry and follow the selected link.
9169 If there is only one link, follow it immediately as well.
9170 If NTH is an integer, immediately pick the NTH link found.
9171 If ZERO is a string, check also this string for a link, and if
9172 there is one, offer it as link number zero."
9173 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9174 "\\(" org-angle-link-re "\\)\\|"
9175 "\\(" org-plain-link-re "\\)"))
9176 (cnt ?0)
9177 (in-emacs (if (integerp nth) nil nth))
9178 have-zero end links link c)
9179 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9180 (push (match-string 0 zero) links)
9181 (setq cnt (1- cnt) have-zero t))
9182 (save-excursion
9183 (org-back-to-heading t)
9184 (setq end (save-excursion (outline-next-heading) (point)))
9185 (while (re-search-forward re end t)
9186 (push (match-string 0) links))
9187 (setq links (org-uniquify (reverse links))))
9189 (cond
9190 ((null links)
9191 (message "No links"))
9192 ((equal (length links) 1)
9193 (setq link (list (car links))))
9194 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9195 (setq link (nth (if have-zero nth (1- nth)) links)))
9196 (t ; we have to select a link
9197 (save-excursion
9198 (save-window-excursion
9199 (delete-other-windows)
9200 (with-output-to-temp-buffer "*Select Link*"
9201 (mapc (lambda (l)
9202 (if (not (string-match org-bracket-link-regexp l))
9203 (princ (format "[%c] %s\n" (incf cnt)
9204 (org-remove-angle-brackets l)))
9205 (if (match-end 3)
9206 (princ (format "[%c] %s (%s)\n" (incf cnt)
9207 (match-string 3 l) (match-string 1 l)))
9208 (princ (format "[%c] %s\n" (incf cnt)
9209 (match-string 1 l))))))
9210 links))
9211 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9212 (message "Select link to open, RET to open all:")
9213 (setq c (read-char-exclusive))
9214 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9215 (when (equal c ?q) (error "Abort"))
9216 (if (equal c ?\C-m)
9217 (setq link links)
9218 (setq nth (- c ?0))
9219 (if have-zero (setq nth (1+ nth)))
9220 (unless (and (integerp nth) (>= (length links) nth))
9221 (error "Invalid link selection"))
9222 (setq link (list (nth (1- nth) links))))))
9223 (if link
9224 (let ((buf (current-buffer)))
9225 (dolist (l link)
9226 (org-open-link-from-string l in-emacs buf))
9228 nil)))
9230 ;; Add special file links that specify the way of opening
9232 (org-add-link-type "file+sys" 'org-open-file-with-system)
9233 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9234 (defun org-open-file-with-system (path)
9235 "Open file at PATH using the system way of opening it."
9236 (org-open-file path 'system))
9237 (defun org-open-file-with-emacs (path)
9238 "Open file at PATH in Emacs."
9239 (org-open-file path 'emacs))
9240 (defun org-remove-file-link-modifiers ()
9241 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9242 (goto-char (point-min))
9243 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9244 (org-if-unprotected
9245 (replace-match "file:" t t))))
9246 (eval-after-load "org-exp"
9247 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9248 'org-remove-file-link-modifiers))
9250 ;;;; Time estimates
9252 (defun org-get-effort (&optional pom)
9253 "Get the effort estimate for the current entry."
9254 (org-entry-get pom org-effort-property))
9256 ;;; File search
9258 (defvar org-create-file-search-functions nil
9259 "List of functions to construct the right search string for a file link.
9260 These functions are called in turn with point at the location to
9261 which the link should point.
9263 A function in the hook should first test if it would like to
9264 handle this file type, for example by checking the `major-mode'
9265 or the file extension. If it decides not to handle this file, it
9266 should just return nil to give other functions a chance. If it
9267 does handle the file, it must return the search string to be used
9268 when following the link. The search string will be part of the
9269 file link, given after a double colon, and `org-open-at-point'
9270 will automatically search for it. If special measures must be
9271 taken to make the search successful, another function should be
9272 added to the companion hook `org-execute-file-search-functions',
9273 which see.
9275 A function in this hook may also use `setq' to set the variable
9276 `description' to provide a suggestion for the descriptive text to
9277 be used for this link when it gets inserted into an Org-mode
9278 buffer with \\[org-insert-link].")
9280 (defvar org-execute-file-search-functions nil
9281 "List of functions to execute a file search triggered by a link.
9283 Functions added to this hook must accept a single argument, the
9284 search string that was part of the file link, the part after the
9285 double colon. The function must first check if it would like to
9286 handle this search, for example by checking the `major-mode' or
9287 the file extension. If it decides not to handle this search, it
9288 should just return nil to give other functions a chance. If it
9289 does handle the search, it must return a non-nil value to keep
9290 other functions from trying.
9292 Each function can access the current prefix argument through the
9293 variable `current-prefix-argument'. Note that a single prefix is
9294 used to force opening a link in Emacs, so it may be good to only
9295 use a numeric or double prefix to guide the search function.
9297 In case this is needed, a function in this hook can also restore
9298 the window configuration before `org-open-at-point' was called using:
9300 (set-window-configuration org-window-config-before-follow-link)")
9302 (defun org-link-search (s &optional type avoid-pos)
9303 "Search for a link search option.
9304 If S is surrounded by forward slashes, it is interpreted as a
9305 regular expression. In org-mode files, this will create an `org-occur'
9306 sparse tree. In ordinary files, `occur' will be used to list matches.
9307 If the current buffer is in `dired-mode', grep will be used to search
9308 in all files. If AVOID-POS is given, ignore matches near that position."
9309 (let ((case-fold-search t)
9310 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9311 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9312 (append '(("") (" ") ("\t") ("\n"))
9313 org-emphasis-alist)
9314 "\\|") "\\)"))
9315 (pos (point))
9316 (pre nil) (post nil)
9317 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9318 (cond
9319 ;; First check if there are any special
9320 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9321 ;; Now try the builtin stuff
9322 ((and (equal (string-to-char s0) ?#)
9323 (> (length s0) 1)
9324 (save-excursion
9325 (goto-char (point-min))
9326 (and
9327 (re-search-forward
9328 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9329 (setq type 'dedicated
9330 pos (match-beginning 0))))
9331 ;; There is an exact target for this
9332 (goto-char pos)
9333 (org-back-to-heading t)))
9334 ((save-excursion
9335 (goto-char (point-min))
9336 (and
9337 (re-search-forward
9338 (concat "<<" (regexp-quote s0) ">>") nil t)
9339 (setq type 'dedicated
9340 pos (match-beginning 0))))
9341 ;; There is an exact target for this
9342 (goto-char pos))
9343 ((and (string-match "^(\\(.*\\))$" s0)
9344 (save-excursion
9345 (goto-char (point-min))
9346 (and
9347 (re-search-forward
9348 (concat "[^[]" (regexp-quote
9349 (format org-coderef-label-format
9350 (match-string 1 s0))))
9351 nil t)
9352 (setq type 'dedicated
9353 pos (1+ (match-beginning 0))))))
9354 ;; There is a coderef target for this
9355 (goto-char pos))
9356 ((string-match "^/\\(.*\\)/$" s)
9357 ;; A regular expression
9358 (cond
9359 ((org-mode-p)
9360 (org-occur (match-string 1 s)))
9361 ;;((eq major-mode 'dired-mode)
9362 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9363 (t (org-do-occur (match-string 1 s)))))
9365 ;; A normal search strings
9366 (when (equal (string-to-char s) ?*)
9367 ;; Anchor on headlines, post may include tags.
9368 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
9369 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
9370 s (substring s 1)))
9371 (remove-text-properties
9372 0 (length s)
9373 '(face nil mouse-face nil keymap nil fontified nil) s)
9374 ;; Make a series of regular expressions to find a match
9375 (setq words (org-split-string s "[ \n\r\t]+")
9377 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9378 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
9379 "\\)" markers)
9380 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9381 re2a (concat "[ \t\r\n]" re2a_)
9382 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9383 re4 (concat "[^a-zA-Z_]" re4_)
9385 re1 (concat pre re2 post)
9386 re3 (concat pre (if pre re4_ re4) post)
9387 re5 (concat pre ".*" re4)
9388 re2 (concat pre re2)
9389 re2a (concat pre (if pre re2a_ re2a))
9390 re4 (concat pre (if pre re4_ re4))
9391 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9392 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9393 re5 "\\)"
9395 (cond
9396 ((eq type 'org-occur) (org-occur reall))
9397 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9398 (t (goto-char (point-min))
9399 (setq type 'fuzzy)
9400 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
9401 (org-search-not-self 1 re1 nil t)
9402 (org-search-not-self 1 re2 nil t)
9403 (org-search-not-self 1 re2a nil t)
9404 (org-search-not-self 1 re3 nil t)
9405 (org-search-not-self 1 re4 nil t)
9406 (org-search-not-self 1 re5 nil t)
9408 (goto-char (match-beginning 1))
9409 (goto-char pos)
9410 (error "No match")))))
9412 ;; Normal string-search
9413 (goto-char (point-min))
9414 (if (search-forward s nil t)
9415 (goto-char (match-beginning 0))
9416 (error "No match"))))
9417 (and (org-mode-p) (org-show-context 'link-search))
9418 type))
9420 (defun org-search-not-self (group &rest args)
9421 "Execute `re-search-forward', but only accept matches that do not
9422 enclose the position of `org-open-link-marker'."
9423 (let ((m org-open-link-marker))
9424 (catch 'exit
9425 (while (apply 're-search-forward args)
9426 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
9427 (goto-char (match-end group))
9428 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
9429 (> (match-beginning 0) (marker-position m))
9430 (< (match-end 0) (marker-position m)))
9431 (save-match-data
9432 (or (not (org-in-regexp
9433 org-bracket-link-analytic-regexp 1))
9434 (not (match-end 4)) ; no description
9435 (and (<= (match-beginning 4) (point))
9436 (>= (match-end 4) (point))))))
9437 (throw 'exit (point))))))))
9439 (defun org-get-buffer-for-internal-link (buffer)
9440 "Return a buffer to be used for displaying the link target of internal links."
9441 (cond
9442 ((not org-display-internal-link-with-indirect-buffer)
9443 buffer)
9444 ((string-match "(Clone)$" (buffer-name buffer))
9445 (message "Buffer is already a clone, not making another one")
9446 ;; we also do not modify visibility in this case
9447 buffer)
9448 (t ; make a new indirect buffer for displaying the link
9449 (let* ((bn (buffer-name buffer))
9450 (ibn (concat bn "(Clone)"))
9451 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
9452 (with-current-buffer ib (org-overview))
9453 ib))))
9455 (defun org-do-occur (regexp &optional cleanup)
9456 "Call the Emacs command `occur'.
9457 If CLEANUP is non-nil, remove the printout of the regular expression
9458 in the *Occur* buffer. This is useful if the regex is long and not useful
9459 to read."
9460 (occur regexp)
9461 (when cleanup
9462 (let ((cwin (selected-window)) win beg end)
9463 (when (setq win (get-buffer-window "*Occur*"))
9464 (select-window win))
9465 (goto-char (point-min))
9466 (when (re-search-forward "match[a-z]+" nil t)
9467 (setq beg (match-end 0))
9468 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9469 (setq end (1- (match-beginning 0)))))
9470 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
9471 (goto-char (point-min))
9472 (select-window cwin))))
9474 ;;; The mark ring for links jumps
9476 (defvar org-mark-ring nil
9477 "Mark ring for positions before jumps in Org-mode.")
9478 (defvar org-mark-ring-last-goto nil
9479 "Last position in the mark ring used to go back.")
9480 ;; Fill and close the ring
9481 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9482 (loop for i from 1 to org-mark-ring-length do
9483 (push (make-marker) org-mark-ring))
9484 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
9485 org-mark-ring)
9487 (defun org-mark-ring-push (&optional pos buffer)
9488 "Put the current position or POS into the mark ring and rotate it."
9489 (interactive)
9490 (setq pos (or pos (point)))
9491 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
9492 (move-marker (car org-mark-ring)
9493 (or pos (point))
9494 (or buffer (current-buffer)))
9495 (message "%s"
9496 (substitute-command-keys
9497 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
9499 (defun org-mark-ring-goto (&optional n)
9500 "Jump to the previous position in the mark ring.
9501 With prefix arg N, jump back that many stored positions. When
9502 called several times in succession, walk through the entire ring.
9503 Org-mode commands jumping to a different position in the current file,
9504 or to another Org-mode file, automatically push the old position
9505 onto the ring."
9506 (interactive "p")
9507 (let (p m)
9508 (if (eq last-command this-command)
9509 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
9510 (setq p org-mark-ring))
9511 (setq org-mark-ring-last-goto p)
9512 (setq m (car p))
9513 (switch-to-buffer (marker-buffer m))
9514 (goto-char m)
9515 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
9517 (defun org-remove-angle-brackets (s)
9518 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
9519 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
9521 (defun org-add-angle-brackets (s)
9522 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
9523 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
9525 (defun org-remove-double-quotes (s)
9526 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
9527 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
9530 ;;; Following specific links
9532 (defun org-follow-timestamp-link ()
9533 (cond
9534 ((org-at-date-range-p t)
9535 (let ((org-agenda-start-on-weekday)
9536 (t1 (match-string 1))
9537 (t2 (match-string 2)))
9538 (setq t1 (time-to-days (org-time-string-to-time t1))
9539 t2 (time-to-days (org-time-string-to-time t2)))
9540 (org-agenda-list nil t1 (1+ (- t2 t1)))))
9541 ((org-at-timestamp-p t)
9542 (org-agenda-list nil (time-to-days (org-time-string-to-time
9543 (substring (match-string 1) 0 10)))
9545 (t (error "This should not happen"))))
9548 ;;; Following file links
9549 (defvar org-wait nil)
9550 (defun org-open-file (path &optional in-emacs line search)
9551 "Open the file at PATH.
9552 First, this expands any special file name abbreviations. Then the
9553 configuration variable `org-file-apps' is checked if it contains an
9554 entry for this file type, and if yes, the corresponding command is launched.
9556 If no application is found, Emacs simply visits the file.
9558 With optional prefix argument IN-EMACS, Emacs will visit the file.
9559 With a double \\[universal-argument] \\[universal-argument] \
9560 prefix arg, Org tries to avoid opening in Emacs
9561 and to use an external application to visit the file.
9563 Optional LINE specifies a line to go to, optional SEARCH a string
9564 to search for. If LINE or SEARCH is given, the file will be
9565 opened in Emacs, unless an entry from org-file-apps that makes
9566 use of groups in a regexp matches.
9567 If the file does not exist, an error is thrown."
9568 (let* ((file (if (equal path "")
9569 buffer-file-name
9570 (substitute-in-file-name (expand-file-name path))))
9571 (file-apps (append org-file-apps (org-default-apps)))
9572 (apps (org-remove-if
9573 'org-file-apps-entry-match-against-dlink-p file-apps))
9574 (apps-dlink (org-remove-if-not
9575 'org-file-apps-entry-match-against-dlink-p file-apps))
9576 (remp (and (assq 'remote apps) (org-file-remote-p file)))
9577 (dirp (if remp nil (file-directory-p file)))
9578 (file (if (and dirp org-open-directory-means-index-dot-org)
9579 (concat (file-name-as-directory file) "index.org")
9580 file))
9581 (a-m-a-p (assq 'auto-mode apps))
9582 (dfile (downcase file))
9583 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
9584 (link (cond ((and (eq line nil)
9585 (eq search nil))
9586 file)
9587 (line
9588 (concat file "::" (number-to-string line)))
9589 (search
9590 (concat file "::" search))))
9591 (dlink (downcase link))
9592 (old-buffer (current-buffer))
9593 (old-pos (point))
9594 (old-mode major-mode)
9595 ext cmd link-match-data)
9596 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
9597 (setq ext (match-string 1 dfile))
9598 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
9599 (setq ext (match-string 1 dfile))))
9600 (cond
9601 ((member in-emacs '((16) system))
9602 (setq cmd (cdr (assoc 'system apps))))
9603 (in-emacs (setq cmd 'emacs))
9605 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
9606 (and dirp (cdr (assoc 'directory apps)))
9607 ; first, try matching against apps-dlink
9608 ; if we get a match here, store the match data for later
9609 (let ((match (assoc-default dlink apps-dlink
9610 'string-match)))
9611 (if match
9612 (progn (setq link-match-data (match-data))
9613 match)
9614 (progn (setq in-emacs (or in-emacs line search))
9615 nil))) ; if we have no match in apps-dlink,
9616 ; always open the file in emacs if line or search
9617 ; is given (for backwards compatibility)
9618 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
9619 'string-match)
9620 (cdr (assoc ext apps))
9621 (cdr (assoc t apps))))))
9622 (when (eq cmd 'system)
9623 (setq cmd (cdr (assoc 'system apps))))
9624 (when (eq cmd 'default)
9625 (setq cmd (cdr (assoc t apps))))
9626 (when (eq cmd 'mailcap)
9627 (require 'mailcap)
9628 (mailcap-parse-mailcaps)
9629 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
9630 (command (mailcap-mime-info mime-type)))
9631 (if (stringp command)
9632 (setq cmd command)
9633 (setq cmd 'emacs))))
9634 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
9635 (not (file-exists-p file))
9636 (not org-open-non-existing-files))
9637 (error "No such file: %s" file))
9638 (cond
9639 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
9640 ;; Remove quotes around the file name - we'll use shell-quote-argument.
9641 (while (string-match "['\"]%s['\"]" cmd)
9642 (setq cmd (replace-match "%s" t t cmd)))
9643 (while (string-match "%s" cmd)
9644 (setq cmd (replace-match
9645 (save-match-data
9646 (shell-quote-argument
9647 (convert-standard-filename file)))
9648 t t cmd)))
9650 ;; Replace "%1", "%2" etc. in command with group matches from regex
9651 (save-match-data
9652 (let ((match-index 1)
9653 (number-of-groups (- (/ (length link-match-data) 2) 1)))
9654 (set-match-data link-match-data)
9655 (while (<= match-index number-of-groups)
9656 (let ((regex (concat "%" (number-to-string match-index)))
9657 (replace-with (match-string match-index dlink)))
9658 (while (string-match regex cmd)
9659 (setq cmd (replace-match replace-with t t cmd))))
9660 (setq match-index (+ match-index 1)))))
9662 (save-window-excursion
9663 (start-process-shell-command cmd nil cmd)
9664 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
9666 ((or (stringp cmd)
9667 (eq cmd 'emacs))
9668 (funcall (cdr (assq 'file org-link-frame-setup)) file)
9669 (widen)
9670 (if line (org-goto-line line)
9671 (if search (org-link-search search))))
9672 ((consp cmd)
9673 (let ((file (convert-standard-filename file)))
9674 (save-match-data
9675 (set-match-data link-match-data)
9676 (eval cmd))))
9677 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
9678 (and (org-mode-p) (eq old-mode 'org-mode)
9679 (or (not (equal old-buffer (current-buffer)))
9680 (not (equal old-pos (point))))
9681 (org-mark-ring-push old-pos old-buffer))))
9683 (defun org-file-apps-entry-match-against-dlink-p (entry)
9684 "This function returns non-nil if `entry' uses a regular
9685 expression which should be matched against the whole link by
9686 org-open-file.
9688 It assumes that is the case when the entry uses a regular
9689 expression which has at least one grouping construct and the
9690 action is either a lisp form or a command string containing
9691 '%1', i.e. using at least one subexpression match as a
9692 parameter."
9693 (let ((selector (car entry))
9694 (action (cdr entry)))
9695 (if (stringp selector)
9696 (and (> (regexp-opt-depth selector) 0)
9697 (or (and (stringp action)
9698 (string-match "%[0-9]" action))
9699 (consp action)))
9700 nil)))
9702 (defun org-default-apps ()
9703 "Return the default applications for this operating system."
9704 (cond
9705 ((eq system-type 'darwin)
9706 org-file-apps-defaults-macosx)
9707 ((eq system-type 'windows-nt)
9708 org-file-apps-defaults-windowsnt)
9709 (t org-file-apps-defaults-gnu)))
9711 (defun org-apps-regexp-alist (list &optional add-auto-mode)
9712 "Convert extensions to regular expressions in the cars of LIST.
9713 Also, weed out any non-string entries, because the return value is used
9714 only for regexp matching.
9715 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
9716 point to the symbol `emacs', indicating that the file should
9717 be opened in Emacs."
9718 (append
9719 (delq nil
9720 (mapcar (lambda (x)
9721 (if (not (stringp (car x)))
9723 (if (string-match "\\W" (car x))
9725 (cons (concat "\\." (car x) "\\'") (cdr x)))))
9726 list))
9727 (if add-auto-mode
9728 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
9730 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
9731 (defun org-file-remote-p (file)
9732 "Test whether FILE specifies a location on a remote system.
9733 Return non-nil if the location is indeed remote.
9735 For example, the filename \"/user@host:/foo\" specifies a location
9736 on the system \"/user@host:\"."
9737 (cond ((fboundp 'file-remote-p)
9738 (file-remote-p file))
9739 ((fboundp 'tramp-handle-file-remote-p)
9740 (tramp-handle-file-remote-p file))
9741 ((and (boundp 'ange-ftp-name-format)
9742 (string-match (car ange-ftp-name-format) file))
9744 (t nil)))
9747 ;;;; Refiling
9749 (defun org-get-org-file ()
9750 "Read a filename, with default directory `org-directory'."
9751 (let ((default (or org-default-notes-file remember-data-file)))
9752 (read-file-name (format "File name [%s]: " default)
9753 (file-name-as-directory org-directory)
9754 default)))
9756 (defun org-notes-order-reversed-p ()
9757 "Check if the current file should receive notes in reversed order."
9758 (cond
9759 ((not org-reverse-note-order) nil)
9760 ((eq t org-reverse-note-order) t)
9761 ((not (listp org-reverse-note-order)) nil)
9762 (t (catch 'exit
9763 (let ((all org-reverse-note-order)
9764 entry)
9765 (while (setq entry (pop all))
9766 (if (string-match (car entry) buffer-file-name)
9767 (throw 'exit (cdr entry))))
9768 nil)))))
9770 (defvar org-refile-target-table nil
9771 "The list of refile targets, created by `org-refile'.")
9773 (defvar org-agenda-new-buffers nil
9774 "Buffers created to visit agenda files.")
9776 (defvar org-refile-cache nil
9777 "Cache for refile targets.")
9780 (defvar org-refile-markers nil
9781 "All the markers used for caching refile locations.")
9783 (defun org-refile-marker (pos)
9784 "Get a new refile marker, but only if caching is in use."
9785 (if (not org-refile-use-cache)
9787 (let ((m (make-marker)))
9788 (move-marker m pos)
9789 (push m org-refile-markers)
9790 m)))
9792 (defun org-refile-cache-clear ()
9793 "Clear the refile cache and disable all the markers."
9794 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
9795 (setq org-refile-markers nil)
9796 (setq org-refile-cache nil)
9797 (message "Refile cache has been cleared"))
9799 (defun org-refile-cache-check-set (set)
9800 "Check if all the markers in the cache still have live buffers."
9801 (let (marker)
9802 (catch 'exit
9803 (while (and set (setq marker (nth 3 (pop set))))
9804 ;; if org-refile-use-outline-path is 'file, marker may be nil
9805 (when (and marker (null (marker-buffer marker)))
9806 (message "not found") (sit-for 3)
9807 (throw 'exit nil)))
9808 t)))
9810 (defun org-refile-cache-put (set &rest identifiers)
9811 "Push the refile targets SET into the cache, under IDENTIFIERS."
9812 (let* ((key (sha1 (prin1-to-string identifiers)))
9813 (entry (assoc key org-refile-cache)))
9814 (if entry
9815 (setcdr entry set)
9816 (push (cons key set) org-refile-cache))))
9818 (defun org-refile-cache-get (&rest identifiers)
9819 "Retrieve the cached value for refile targets given by IDENTIFIERS."
9820 (cond
9821 ((not org-refile-cache) nil)
9822 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
9824 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
9825 org-refile-cache))))
9826 (and set (org-refile-cache-check-set set) set)))))
9828 (defun org-get-refile-targets (&optional default-buffer)
9829 "Produce a table with refile targets."
9830 (let ((case-fold-search nil)
9831 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
9832 (entries (or org-refile-targets '((nil . (:level . 1)))))
9833 targets tgs txt re files f desc descre fast-path-p level pos0)
9834 (message "Getting targets...")
9835 (with-current-buffer (or default-buffer (current-buffer))
9836 (while (setq entry (pop entries))
9837 (setq files (car entry) desc (cdr entry))
9838 (setq fast-path-p nil)
9839 (cond
9840 ((null files) (setq files (list (current-buffer))))
9841 ((eq files 'org-agenda-files)
9842 (setq files (org-agenda-files 'unrestricted)))
9843 ((and (symbolp files) (fboundp files))
9844 (setq files (funcall files)))
9845 ((and (symbolp files) (boundp files))
9846 (setq files (symbol-value files))))
9847 (if (stringp files) (setq files (list files)))
9848 (cond
9849 ((eq (car desc) :tag)
9850 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
9851 ((eq (car desc) :todo)
9852 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
9853 ((eq (car desc) :regexp)
9854 (setq descre (cdr desc)))
9855 ((eq (car desc) :level)
9856 (setq descre (concat "^\\*\\{" (number-to-string
9857 (if org-odd-levels-only
9858 (1- (* 2 (cdr desc)))
9859 (cdr desc)))
9860 "\\}[ \t]")))
9861 ((eq (car desc) :maxlevel)
9862 (setq fast-path-p t)
9863 (setq descre (concat "^\\*\\{1," (number-to-string
9864 (if org-odd-levels-only
9865 (1- (* 2 (cdr desc)))
9866 (cdr desc)))
9867 "\\}[ \t]")))
9868 (t (error "Bad refiling target description %s" desc)))
9869 (while (setq f (pop files))
9870 (with-current-buffer
9871 (if (bufferp f) f (org-get-agenda-file-buffer f))
9873 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
9874 (progn
9875 (if (bufferp f) (setq f (buffer-file-name
9876 (buffer-base-buffer f))))
9877 (setq f (and f (expand-file-name f)))
9878 (if (eq org-refile-use-outline-path 'file)
9879 (push (list (file-name-nondirectory f) f nil nil) tgs))
9880 (save-excursion
9881 (save-restriction
9882 (widen)
9883 (goto-char (point-min))
9884 (while (re-search-forward descre nil t)
9885 (goto-char (setq pos0 (point-at-bol)))
9886 (catch 'next
9887 (when org-refile-target-verify-function
9888 (save-match-data
9889 (or (funcall org-refile-target-verify-function)
9890 (throw 'next t))))
9891 (when (looking-at org-complex-heading-regexp)
9892 (setq level (org-reduced-level
9893 (- (match-end 1) (match-beginning 1)))
9894 txt (org-link-display-format (match-string 4))
9895 re (concat "^" (regexp-quote
9896 (buffer-substring
9897 (match-beginning 1)
9898 (match-end 4)))))
9899 (if (match-end 5) (setq re (concat
9900 re "[ \t]+"
9901 (regexp-quote
9902 (match-string 5)))))
9903 (setq re (concat re "[ \t]*$"))
9904 (when org-refile-use-outline-path
9905 (setq txt (mapconcat
9906 'org-protect-slash
9907 (append
9908 (if (eq org-refile-use-outline-path
9909 'file)
9910 (list (file-name-nondirectory
9911 (buffer-file-name
9912 (buffer-base-buffer))))
9913 (if (eq org-refile-use-outline-path
9914 'full-file-path)
9915 (list (buffer-file-name
9916 (buffer-base-buffer)))))
9917 (org-get-outline-path fast-path-p
9918 level txt)
9919 (list txt))
9920 "/")))
9921 (push (list txt f re (org-refile-marker (point)))
9922 tgs)))
9923 (when (= (point) pos0)
9924 ;; verification function has not moved point
9925 (goto-char (point-at-eol))))))))
9926 (when org-refile-use-cache
9927 (org-refile-cache-put tgs (buffer-file-name) descre))
9928 (setq targets (append tgs targets))
9929 ))))
9930 (message "Getting targets...done")
9931 (nreverse targets)))
9933 (defun org-protect-slash (s)
9934 (while (string-match "/" s)
9935 (setq s (replace-match "\\" t t s)))
9938 (defvar org-olpa (make-vector 20 nil))
9940 (defun org-get-outline-path (&optional fastp level heading)
9941 "Return the outline path to the current entry, as a list.
9943 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
9944 routine which makes outline path derivations for an entire file,
9945 avoiding backtracing. Refile target collection makes use of that."
9946 (if fastp
9947 (progn
9948 (if (> level 19)
9949 (error "Outline path failure, more than 19 levels"))
9950 (loop for i from level upto 19 do
9951 (aset org-olpa i nil))
9952 (prog1
9953 (delq nil (append org-olpa nil))
9954 (aset org-olpa level heading)))
9955 (let (rtn case-fold-search)
9956 (save-excursion
9957 (save-restriction
9958 (widen)
9959 (while (org-up-heading-safe)
9960 (when (looking-at org-complex-heading-regexp)
9961 (push (org-match-string-no-properties 4) rtn)))
9962 rtn)))))
9964 (defun org-format-outline-path (path &optional width prefix)
9965 "Format the outline path PATH for display.
9966 Width is the maximum number of characters that is available.
9967 Prefix is a prefix to be included in the returned string,
9968 such as the file name."
9969 (setq width (or width 79))
9970 (if prefix (setq width (- width (length prefix))))
9971 (if (not path)
9972 (or prefix "")
9973 (let* ((nsteps (length path))
9974 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
9975 (maxwidth (if (<= total-width width)
9976 10000 ;; everything fits
9977 ;; we need to shorten the level headings
9978 (/ (- width nsteps) nsteps)))
9979 (org-odd-levels-only nil)
9980 (n 0)
9981 (total (1+ (length prefix))))
9982 (setq maxwidth (max maxwidth 10))
9983 (concat prefix
9984 (mapconcat
9985 (lambda (h)
9986 (setq n (1+ n))
9987 (if (and (= n nsteps) (< maxwidth 10000))
9988 (setq maxwidth (- total-width total)))
9989 (if (< (length h) maxwidth)
9990 (progn (setq total (+ total (length h) 1)) h)
9991 (setq h (substring h 0 (- maxwidth 2))
9992 total (+ total maxwidth 1))
9993 (if (string-match "[ \t]+\\'" h)
9994 (setq h (substring h 0 (match-beginning 0))))
9995 (setq h (concat h "..")))
9996 (org-add-props h nil 'face
9997 (nth (% (1- n) org-n-level-faces)
9998 org-level-faces))
10000 path "/")))))
10002 (defun org-display-outline-path (&optional file current)
10003 "Display the current outline path in the echo area."
10004 (interactive "P")
10005 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10006 (case-fold-search nil)
10007 (path (and (org-mode-p) (org-get-outline-path))))
10008 (if current (setq path (append path
10009 (save-excursion
10010 (org-back-to-heading t)
10011 (if (looking-at org-complex-heading-regexp)
10012 (list (match-string 4)))))))
10013 (message "%s"
10014 (org-format-outline-path
10015 path
10016 (1- (frame-width))
10017 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10019 (defvar org-refile-history nil
10020 "History for refiling operations.")
10022 (defvar org-after-refile-insert-hook nil
10023 "Hook run after `org-refile' has inserted its stuff at the new location.
10024 Note that this is still *before* the stuff will be removed from
10025 the *old* location.")
10027 (defvar org-capture-last-stored-marker)
10028 (defun org-refile (&optional goto default-buffer rfloc)
10029 "Move the entry at point to another heading.
10030 The list of target headings is compiled using the information in
10031 `org-refile-targets', which see. This list is created before each use
10032 and will therefore always be up-to-date.
10034 At the target location, the entry is filed as a subitem of the target heading.
10035 Depending on `org-reverse-note-order', the new subitem will either be the
10036 first or the last subitem.
10038 If there is an active region, all entries in that region will be moved.
10039 However, the region must fulfill the requirement that the first heading
10040 is the first one sets the top-level of the moved text - at most siblings
10041 below it are allowed.
10043 With prefix arg GOTO, the command will only visit the target location,
10044 not actually move anything.
10045 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10046 go to the location where the last refiling
10047 operation has put the subtree.
10048 With a prefix argument of `2', refile to the running clock.
10050 RFLOC can be a refile location obtained in a different way.
10052 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10054 If you are using target caching (see `org-refile-use-cache'),
10055 You have to clear the target cache in order to find new targets.
10056 This can be done with a 0 prefix: `C-0 C-c C-w'"
10057 (interactive "P")
10058 (if (member goto '(0 (64)))
10059 (org-refile-cache-clear)
10060 (let* ((cbuf (current-buffer))
10061 (regionp (org-region-active-p))
10062 (region-start (and regionp (region-beginning)))
10063 (region-end (and regionp (region-end)))
10064 (region-length (and regionp (- region-end region-start)))
10065 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10066 pos it nbuf file re level reversed)
10067 (setq last-command nil)
10068 (when regionp
10069 (goto-char region-start)
10070 (or (bolp) (goto-char (point-at-bol)))
10071 (setq region-start (point))
10072 (unless (org-kill-is-subtree-p
10073 (buffer-substring region-start region-end))
10074 (error "The region is not a (sequence of) subtree(s)")))
10075 (if (equal goto '(16))
10076 (org-refile-goto-last-stored)
10077 (when (or
10078 (and (equal goto 2)
10079 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10080 (prog1
10081 (setq it (list (or org-clock-heading "running clock")
10082 (buffer-file-name
10083 (marker-buffer org-clock-hd-marker))
10085 (marker-position org-clock-hd-marker)))
10086 (setq goto nil)))
10087 (setq it (or rfloc
10088 (save-excursion
10089 (org-refile-get-location
10090 (if goto "Goto: " "Refile to: ") default-buffer
10091 org-refile-allow-creating-parent-nodes)))))
10092 (setq file (nth 1 it)
10093 re (nth 2 it)
10094 pos (nth 3 it))
10095 (if (and (not goto)
10097 (equal (buffer-file-name) file)
10098 (if regionp
10099 (and (>= pos region-start)
10100 (<= pos region-end))
10101 (and (>= pos (point))
10102 (< pos (save-excursion
10103 (org-end-of-subtree t t))))))
10104 (error "Cannot refile to position inside the tree or region"))
10106 (setq nbuf (or (find-buffer-visiting file)
10107 (find-file-noselect file)))
10108 (if goto
10109 (progn
10110 (switch-to-buffer nbuf)
10111 (goto-char pos)
10112 (org-show-context 'org-goto))
10113 (if regionp
10114 (progn
10115 (org-kill-new (buffer-substring region-start region-end))
10116 (org-save-markers-in-region region-start region-end))
10117 (org-copy-subtree 1 nil t))
10118 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10119 (find-file-noselect file)))
10120 (setq reversed (org-notes-order-reversed-p))
10121 (save-excursion
10122 (save-restriction
10123 (widen)
10124 (if pos
10125 (progn
10126 (goto-char pos)
10127 (looking-at outline-regexp)
10128 (setq level (org-get-valid-level (funcall outline-level) 1))
10129 (goto-char
10130 (if reversed
10131 (or (outline-next-heading) (point-max))
10132 (or (save-excursion (org-get-next-sibling))
10133 (org-end-of-subtree t t)
10134 (point-max)))))
10135 (setq level 1)
10136 (if (not reversed)
10137 (goto-char (point-max))
10138 (goto-char (point-min))
10139 (or (outline-next-heading) (goto-char (point-max)))))
10140 (if (not (bolp)) (newline))
10141 (org-paste-subtree level)
10142 (when org-log-refile
10143 (org-add-log-setup 'refile nil nil 'findpos
10144 org-log-refile)
10145 (unless (eq org-log-refile 'note)
10146 (save-excursion (org-add-log-note))))
10147 (and org-auto-align-tags (org-set-tags nil t))
10148 (bookmark-set "org-refile-last-stored")
10149 ;; If we are refiling for capture, make sure that the
10150 ;; last-capture pointers point here
10151 (when (org-bound-and-true-p org-refile-for-capture)
10152 (bookmark-set "org-capture-last-stored-marker")
10153 (move-marker org-capture-last-stored-marker (point)))
10154 (if (fboundp 'deactivate-mark) (deactivate-mark))
10155 (run-hooks 'org-after-refile-insert-hook))))
10156 (if regionp
10157 (delete-region (point) (+ (point) region-length))
10158 (org-cut-subtree))
10159 (when (featurep 'org-inlinetask)
10160 (org-inlinetask-remove-END-maybe))
10161 (setq org-markers-to-move nil)
10162 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10164 (defun org-refile-goto-last-stored ()
10165 "Go to the location where the last refile was stored."
10166 (interactive)
10167 (bookmark-jump "org-refile-last-stored")
10168 (message "This is the location of the last refile"))
10170 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
10171 "Prompt the user for a refile location, using PROMPT."
10172 (let ((org-refile-targets org-refile-targets)
10173 (org-refile-use-outline-path org-refile-use-outline-path))
10174 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
10175 (unless org-refile-target-table
10176 (error "No refile targets"))
10177 (let* ((cbuf (current-buffer))
10178 (partial-completion-mode nil)
10179 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10180 (cfunc (if (and org-refile-use-outline-path
10181 org-outline-path-complete-in-steps)
10182 'org-olpath-completing-read
10183 'org-icompleting-read))
10184 (extra (if org-refile-use-outline-path "/" ""))
10185 (filename (and cfn (expand-file-name cfn)))
10186 (tbl (mapcar
10187 (lambda (x)
10188 (if (and (not (member org-refile-use-outline-path
10189 '(file full-file-path)))
10190 (not (equal filename (nth 1 x))))
10191 (cons (concat (car x) extra " ("
10192 (file-name-nondirectory (nth 1 x)) ")")
10193 (cdr x))
10194 (cons (concat (car x) extra) (cdr x))))
10195 org-refile-target-table))
10196 (completion-ignore-case t)
10197 pa answ parent-target child parent old-hist)
10198 (setq old-hist org-refile-history)
10199 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10200 nil 'org-refile-history))
10201 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10202 (if pa
10203 (progn
10204 (when (or (not org-refile-history)
10205 (not (eq old-hist org-refile-history))
10206 (not (equal (car pa) (car org-refile-history))))
10207 (setq org-refile-history
10208 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10209 org-refile-history
10210 (cdr org-refile-history))))
10211 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10212 (pop org-refile-history)))
10214 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10215 (progn
10216 (setq parent (match-string 1 answ)
10217 child (match-string 2 answ))
10218 (setq parent-target (or (assoc parent tbl)
10219 (assoc (concat parent "/") tbl)))
10220 (when (and parent-target
10221 (or (eq new-nodes t)
10222 (and (eq new-nodes 'confirm)
10223 (y-or-n-p (format "Create new node \"%s\"? "
10224 child)))))
10225 (org-refile-new-child parent-target child)))
10226 (error "Invalid target location")))))
10228 (defun org-refile-new-child (parent-target child)
10229 "Use refile target PARENT-TARGET to add new CHILD below it."
10230 (unless parent-target
10231 (error "Cannot find parent for new node"))
10232 (let ((file (nth 1 parent-target))
10233 (pos (nth 3 parent-target))
10234 level)
10235 (with-current-buffer (or (find-buffer-visiting file)
10236 (find-file-noselect file))
10237 (save-excursion
10238 (save-restriction
10239 (widen)
10240 (if pos
10241 (goto-char pos)
10242 (goto-char (point-max))
10243 (if (not (bolp)) (newline)))
10244 (when (looking-at outline-regexp)
10245 (setq level (funcall outline-level))
10246 (org-end-of-subtree t t))
10247 (org-back-over-empty-lines)
10248 (insert "\n" (make-string
10249 (if pos (org-get-valid-level level 1) 1) ?*)
10250 " " child "\n")
10251 (beginning-of-line 0)
10252 (list (concat (car parent-target) "/" child) file "" (point)))))))
10254 (defun org-olpath-completing-read (prompt collection &rest args)
10255 "Read an outline path like a file name."
10256 (let ((thetable collection)
10257 (org-completion-use-ido nil) ; does not work with ido.
10258 (org-completion-use-iswitchb nil)) ; or iswitchb
10259 (apply
10260 'org-icompleting-read prompt
10261 (lambda (string predicate &optional flag)
10262 (let (rtn r f (l (length string)))
10263 (cond
10264 ((eq flag nil)
10265 ;; try completion
10266 (try-completion string thetable))
10267 ((eq flag t)
10268 ;; all-completions
10269 (setq rtn (all-completions string thetable predicate))
10270 (mapcar
10271 (lambda (x)
10272 (setq r (substring x l))
10273 (if (string-match " ([^)]*)$" x)
10274 (setq f (match-string 0 x))
10275 (setq f ""))
10276 (if (string-match "/" r)
10277 (concat string (substring r 0 (match-end 0)) f)
10279 rtn))
10280 ((eq flag 'lambda)
10281 ;; exact match?
10282 (assoc string thetable)))
10284 args)))
10286 ;;;; Dynamic blocks
10288 (defun org-find-dblock (name)
10289 "Find the first dynamic block with name NAME in the buffer.
10290 If not found, stay at current position and return nil."
10291 (let (pos)
10292 (save-excursion
10293 (goto-char (point-min))
10294 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
10295 nil t)
10296 (match-beginning 0))))
10297 (if pos (goto-char pos))
10298 pos))
10300 (defconst org-dblock-start-re
10301 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10302 "Matches the start line of a dynamic block, with parameters.")
10304 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
10305 "Matches the end of a dynamic block.")
10307 (defun org-create-dblock (plist)
10308 "Create a dynamic block section, with parameters taken from PLIST.
10309 PLIST must contain a :name entry which is used as name of the block."
10310 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
10311 (end-of-line 1)
10312 (newline))
10313 (let ((col (current-column))
10314 (name (plist-get plist :name)))
10315 (insert "#+BEGIN: " name)
10316 (while plist
10317 (if (eq (car plist) :name)
10318 (setq plist (cddr plist))
10319 (insert " " (prin1-to-string (pop plist)))))
10320 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
10321 (beginning-of-line -2)))
10323 (defun org-prepare-dblock ()
10324 "Prepare dynamic block for refresh.
10325 This empties the block, puts the cursor at the insert position and returns
10326 the property list including an extra property :name with the block name."
10327 (unless (looking-at org-dblock-start-re)
10328 (error "Not at a dynamic block"))
10329 (let* ((begdel (1+ (match-end 0)))
10330 (name (org-no-properties (match-string 1)))
10331 (params (append (list :name name)
10332 (read (concat "(" (match-string 3) ")")))))
10333 (save-excursion
10334 (beginning-of-line 1)
10335 (skip-chars-forward " \t")
10336 (setq params (plist-put params :indentation-column (current-column))))
10337 (unless (re-search-forward org-dblock-end-re nil t)
10338 (error "Dynamic block not terminated"))
10339 (setq params
10340 (append params
10341 (list :content (buffer-substring
10342 begdel (match-beginning 0)))))
10343 (delete-region begdel (match-beginning 0))
10344 (goto-char begdel)
10345 (open-line 1)
10346 params))
10348 (defun org-map-dblocks (&optional command)
10349 "Apply COMMAND to all dynamic blocks in the current buffer.
10350 If COMMAND is not given, use `org-update-dblock'."
10351 (let ((cmd (or command 'org-update-dblock)))
10352 (save-excursion
10353 (goto-char (point-min))
10354 (while (re-search-forward org-dblock-start-re nil t)
10355 (goto-char (match-beginning 0))
10356 (save-excursion
10357 (condition-case nil
10358 (funcall cmd)
10359 (error (message "Error during update of dynamic block"))))
10360 (unless (re-search-forward org-dblock-end-re nil t)
10361 (error "Dynamic block not terminated"))))))
10363 (defun org-dblock-update (&optional arg)
10364 "User command for updating dynamic blocks.
10365 Update the dynamic block at point. With prefix ARG, update all dynamic
10366 blocks in the buffer."
10367 (interactive "P")
10368 (if arg
10369 (org-update-all-dblocks)
10370 (or (looking-at org-dblock-start-re)
10371 (org-beginning-of-dblock))
10372 (org-update-dblock)))
10374 (defun org-update-dblock ()
10375 "Update the dynamic block at point.
10376 This means to empty the block, parse for parameters and then call
10377 the correct writing function."
10378 (save-window-excursion
10379 (let* ((pos (point))
10380 (line (org-current-line))
10381 (params (org-prepare-dblock))
10382 (name (plist-get params :name))
10383 (indent (plist-get params :indentation-column))
10384 (cmd (intern (concat "org-dblock-write:" name))))
10385 (message "Updating dynamic block `%s' at line %d..." name line)
10386 (funcall cmd params)
10387 (message "Updating dynamic block `%s' at line %d...done" name line)
10388 (goto-char pos)
10389 (when (and indent (> indent 0))
10390 (setq indent (make-string indent ?\ ))
10391 (save-excursion
10392 (org-beginning-of-dblock)
10393 (forward-line 1)
10394 (while (not (looking-at org-dblock-end-re))
10395 (insert indent)
10396 (beginning-of-line 2))
10397 (when (looking-at org-dblock-end-re)
10398 (and (looking-at "[ \t]+")
10399 (replace-match ""))
10400 (insert indent)))))))
10402 (defun org-beginning-of-dblock ()
10403 "Find the beginning of the dynamic block at point.
10404 Error if there is no such block at point."
10405 (let ((pos (point))
10406 beg)
10407 (end-of-line 1)
10408 (if (and (re-search-backward org-dblock-start-re nil t)
10409 (setq beg (match-beginning 0))
10410 (re-search-forward org-dblock-end-re nil t)
10411 (> (match-end 0) pos))
10412 (goto-char beg)
10413 (goto-char pos)
10414 (error "Not in a dynamic block"))))
10416 (defun org-update-all-dblocks ()
10417 "Update all dynamic blocks in the buffer.
10418 This function can be used in a hook."
10419 (when (org-mode-p)
10420 (org-map-dblocks 'org-update-dblock)))
10423 ;;;; Completion
10425 (defconst org-additional-option-like-keywords
10426 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
10427 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
10428 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
10429 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX"
10430 "BEGIN:" "END:"
10431 "ORGTBL" "TBLFM:" "TBLNAME:"
10432 "BEGIN_EXAMPLE" "END_EXAMPLE"
10433 "BEGIN_QUOTE" "END_QUOTE"
10434 "BEGIN_VERSE" "END_VERSE"
10435 "BEGIN_CENTER" "END_CENTER"
10436 "BEGIN_SRC" "END_SRC"
10437 "CATEGORY" "COLUMNS"
10438 "CAPTION" "LABEL"
10439 "SETUPFILE"
10440 "BIND"
10441 "MACRO"))
10443 (defcustom org-structure-template-alist
10445 ("s" "#+begin_src ?\n\n#+end_src"
10446 "<src lang=\"?\">\n\n</src>")
10447 ("e" "#+begin_example\n?\n#+end_example"
10448 "<example>\n?\n</example>")
10449 ("q" "#+begin_quote\n?\n#+end_quote"
10450 "<quote>\n?\n</quote>")
10451 ("v" "#+begin_verse\n?\n#+end_verse"
10452 "<verse>\n?\n/verse>")
10453 ("c" "#+begin_center\n?\n#+end_center"
10454 "<center>\n?\n/center>")
10455 ("l" "#+begin_latex\n?\n#+end_latex"
10456 "<literal style=\"latex\">\n?\n</literal>")
10457 ("L" "#+latex: "
10458 "<literal style=\"latex\">?</literal>")
10459 ("h" "#+begin_html\n?\n#+end_html"
10460 "<literal style=\"html\">\n?\n</literal>")
10461 ("H" "#+html: "
10462 "<literal style=\"html\">?</literal>")
10463 ("a" "#+begin_ascii\n?\n#+end_ascii")
10464 ("A" "#+ascii: ")
10465 ("i" "#+include %file ?"
10466 "<include file=%file markup=\"?\">")
10468 "Structure completion elements.
10469 This is a list of abbreviation keys and values. The value gets inserted
10470 if you type `<' followed by the key and then press the completion key,
10471 usually `M-TAB'. %file will be replaced by a file name after prompting
10472 for the file using completion.
10473 There are two templates for each key, the first uses the original Org syntax,
10474 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
10475 the default when the /org-mtags.el/ module has been loaded. See also the
10476 variable `org-mtags-prefer-muse-templates'.
10477 This is an experimental feature, it is undecided if it is going to stay in."
10478 :group 'org-completion
10479 :type '(repeat
10480 (string :tag "Key")
10481 (string :tag "Template")
10482 (string :tag "Muse Template")))
10484 (defun org-try-structure-completion ()
10485 "Try to complete a structure template before point.
10486 This looks for strings like \"<e\" on an otherwise empty line and
10487 expands them."
10488 (let ((l (buffer-substring (point-at-bol) (point)))
10490 (when (and (looking-at "[ \t]*$")
10491 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
10492 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
10493 (org-complete-expand-structure-template (+ -1 (point-at-bol)
10494 (match-beginning 1)) a)
10495 t)))
10497 (defun org-complete-expand-structure-template (start cell)
10498 "Expand a structure template."
10499 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
10500 (rpl (nth (if musep 2 1) cell))
10501 (ind ""))
10502 (delete-region start (point))
10503 (when (string-match "\\`#\\+" rpl)
10504 (cond
10505 ((bolp))
10506 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
10507 (setq ind (buffer-substring (point-at-bol) (point))))
10508 (t (newline))))
10509 (setq start (point))
10510 (if (string-match "%file" rpl)
10511 (setq rpl (replace-match
10512 (concat
10513 "\""
10514 (save-match-data
10515 (abbreviate-file-name (read-file-name "Include file: ")))
10516 "\"")
10517 t t rpl)))
10518 (setq rpl (mapconcat 'identity (split-string rpl "\n")
10519 (concat "\n" ind)))
10520 (insert rpl)
10521 (if (re-search-backward "\\?" start t) (delete-char 1))))
10524 (defun org-complete (&optional arg)
10525 "Perform completion on word at point.
10526 At the beginning of a headline, this completes TODO keywords as given in
10527 `org-todo-keywords'.
10528 If the current word is preceded by a backslash, completes the TeX symbols
10529 that are supported for HTML support.
10530 If the current word is preceded by \"#+\", completes special words for
10531 setting file options.
10532 In the line after \"#+STARTUP:, complete valid keywords.\"
10533 At all other locations, this simply calls the value of
10534 `org-completion-fallback-command'."
10535 (interactive "P")
10536 (org-without-partial-completion
10537 (catch 'exit
10538 (let* ((a nil)
10539 (end (point))
10540 (beg1 (save-excursion
10541 (skip-chars-backward (org-re "[:alnum:]_@"))
10542 (point)))
10543 (beg (save-excursion
10544 (skip-chars-backward "a-zA-Z0-9_:$")
10545 (point)))
10546 (confirm (lambda (x) (stringp (car x))))
10547 (searchhead (equal (char-before beg) ?*))
10548 (struct
10549 (when (and (member (char-before beg1) '(?. ?<))
10550 (setq a (assoc (buffer-substring beg1 (point))
10551 org-structure-template-alist)))
10552 (org-complete-expand-structure-template (1- beg1) a)
10553 (throw 'exit t)))
10554 (tag (and (equal (char-before beg1) ?:)
10555 (equal (char-after (point-at-bol)) ?*)))
10556 (prop (and (equal (char-before beg1) ?:)
10557 (not (equal (char-after (point-at-bol)) ?*))))
10558 (texp (equal (char-before beg) ?\\))
10559 (link (equal (char-before beg) ?\[))
10560 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
10561 beg)
10562 "#+"))
10563 (startup (string-match "^#\\+STARTUP:.*"
10564 (buffer-substring (point-at-bol) (point))))
10565 (completion-ignore-case opt)
10566 (type nil)
10567 (tbl nil)
10568 (table (cond
10569 (opt
10570 (setq type :opt)
10571 (require 'org-exp)
10572 (append
10573 (delq nil
10574 (mapcar
10575 (lambda (x)
10576 (if (string-match
10577 "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
10578 (cons (match-string 2 x)
10579 (match-string 1 x))))
10580 (org-split-string (org-get-current-options) "\n")))
10581 (mapcar 'list org-additional-option-like-keywords)))
10582 (startup
10583 (setq type :startup)
10584 org-startup-options)
10585 (link (append org-link-abbrev-alist-local
10586 org-link-abbrev-alist))
10587 (texp
10588 (setq type :tex)
10589 (append org-entities-user org-entities))
10590 ((string-match "\\`\\*+[ \t]+\\'"
10591 (buffer-substring (point-at-bol) beg))
10592 (setq type :todo)
10593 (mapcar 'list org-todo-keywords-1))
10594 (searchhead
10595 (setq type :searchhead)
10596 (save-excursion
10597 (goto-char (point-min))
10598 (while (re-search-forward org-todo-line-regexp nil t)
10599 (push (list
10600 (org-make-org-heading-search-string
10601 (match-string 3) t))
10602 tbl)))
10603 tbl)
10604 (tag (setq type :tag beg beg1)
10605 (or org-tag-alist (org-get-buffer-tags)))
10606 (prop (setq type :prop beg beg1)
10607 (mapcar 'list (org-buffer-property-keys nil t t)))
10608 (t (progn
10609 (call-interactively org-completion-fallback-command)
10610 (throw 'exit nil)))))
10611 (pattern (buffer-substring-no-properties beg end))
10612 (completion (try-completion pattern table confirm)))
10613 (cond ((eq completion t)
10614 (if (not (assoc (upcase pattern) table))
10615 (message "Already complete")
10616 (if (and (equal type :opt)
10617 (not (member (car (assoc (upcase pattern) table))
10618 org-additional-option-like-keywords)))
10619 (insert (substring (cdr (assoc (upcase pattern) table))
10620 (length pattern)))
10621 (if (memq type '(:tag :prop)) (insert ":")))))
10622 ((null completion)
10623 (message "Can't find completion for \"%s\"" pattern)
10624 (ding))
10625 ((not (string= pattern completion))
10626 (delete-region beg end)
10627 (if (string-match " +$" completion)
10628 (setq completion (replace-match "" t t completion)))
10629 (insert completion)
10630 (if (get-buffer-window "*Completions*")
10631 (delete-window (get-buffer-window "*Completions*")))
10632 (if (assoc completion table)
10633 (if (eq type :todo) (insert " ")
10634 (if (memq type '(:tag :prop)) (insert ":"))))
10635 (if (and (equal type :opt) (assoc completion table))
10636 (message "%s" (substitute-command-keys
10637 "Press \\[org-complete] again to insert example settings"))))
10639 (message "Making completion list...")
10640 (let ((list (sort (all-completions pattern table confirm)
10641 'string<)))
10642 (with-output-to-temp-buffer "*Completions*"
10643 (condition-case nil
10644 ;; Protection needed for XEmacs and emacs 21
10645 (display-completion-list list pattern)
10646 (error (display-completion-list list)))))
10647 (message "Making completion list...%s" "done")))))))
10649 ;;;; TODO, DEADLINE, Comments
10651 (defun org-toggle-comment ()
10652 "Change the COMMENT state of an entry."
10653 (interactive)
10654 (save-excursion
10655 (org-back-to-heading)
10656 (let (case-fold-search)
10657 (if (looking-at (concat outline-regexp
10658 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
10659 (replace-match "" t t nil 1)
10660 (if (looking-at outline-regexp)
10661 (progn
10662 (goto-char (match-end 0))
10663 (insert org-comment-string " ")))))))
10665 (defvar org-last-todo-state-is-todo nil
10666 "This is non-nil when the last TODO state change led to a TODO state.
10667 If the last change removed the TODO tag or switched to DONE, then
10668 this is nil.")
10670 (defvar org-setting-tags nil) ; dynamically skipped
10672 (defun org-parse-local-options (string var)
10673 "Parse STRING for startup setting relevant for variable VAR."
10674 (let ((rtn (symbol-value var))
10675 e opts)
10676 (save-match-data
10677 (if (or (not string) (not (string-match "\\S-" string)))
10679 (setq opts (delq nil (mapcar (lambda (x)
10680 (setq e (assoc x org-startup-options))
10681 (if (eq (nth 1 e) var) e nil))
10682 (org-split-string string "[ \t]+"))))
10683 (if (not opts)
10685 (setq rtn nil)
10686 (while (setq e (pop opts))
10687 (if (not (nth 3 e))
10688 (setq rtn (nth 2 e))
10689 (if (not (listp rtn)) (setq rtn nil))
10690 (push (nth 2 e) rtn)))
10691 rtn)))))
10693 (defvar org-todo-setup-filter-hook nil
10694 "Hook for functions that pre-filter todo specs.
10695 Each function takes a todo spec and returns either nil or the spec
10696 transformed into canonical form." )
10698 (defvar org-todo-get-default-hook nil
10699 "Hook for functions that get a default item for todo.
10700 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
10701 nil or a string to be used for the todo mark." )
10703 (defvar org-agenda-headline-snapshot-before-repeat)
10705 (defun org-todo (&optional arg)
10706 "Change the TODO state of an item.
10707 The state of an item is given by a keyword at the start of the heading,
10708 like
10709 *** TODO Write paper
10710 *** DONE Call mom
10712 The different keywords are specified in the variable `org-todo-keywords'.
10713 By default the available states are \"TODO\" and \"DONE\".
10714 So for this example: when the item starts with TODO, it is changed to DONE.
10715 When it starts with DONE, the DONE is removed. And when neither TODO nor
10716 DONE are present, add TODO at the beginning of the heading.
10718 With \\[universal-argument] prefix arg, use completion to determine the new \
10719 state.
10720 With numeric prefix arg, switch to that state.
10721 With a double \\[universal-argument] prefix, switch to the next set of TODO \
10722 keywords (nextset).
10723 With a triple \\[universal-argument] prefix, circumvent any state blocking.
10725 For calling through lisp, arg is also interpreted in the following way:
10726 'none -> empty state
10727 \"\"(empty string) -> switch to empty state
10728 'done -> switch to DONE
10729 'nextset -> switch to the next set of keywords
10730 'previousset -> switch to the previous set of keywords
10731 \"WAITING\" -> switch to the specified keyword, but only if it
10732 really is a member of `org-todo-keywords'."
10733 (interactive "P")
10734 (if (equal arg '(16)) (setq arg 'nextset))
10735 (let ((org-blocker-hook org-blocker-hook)
10736 (case-fold-search nil))
10737 (when (equal arg '(64))
10738 (setq arg nil org-blocker-hook nil))
10739 (when (and org-blocker-hook
10740 (or org-inhibit-blocking
10741 (org-entry-get nil "NOBLOCKING")))
10742 (setq org-blocker-hook nil))
10743 (save-excursion
10744 (catch 'exit
10745 (org-back-to-heading t)
10746 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
10747 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
10748 (looking-at " *"))
10749 (let* ((match-data (match-data))
10750 (startpos (point-at-bol))
10751 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
10752 (org-log-done org-log-done)
10753 (org-log-repeat org-log-repeat)
10754 (org-todo-log-states org-todo-log-states)
10755 (this (match-string 1))
10756 (hl-pos (match-beginning 0))
10757 (head (org-get-todo-sequence-head this))
10758 (ass (assoc head org-todo-kwd-alist))
10759 (interpret (nth 1 ass))
10760 (done-word (nth 3 ass))
10761 (final-done-word (nth 4 ass))
10762 (last-state (or this ""))
10763 (completion-ignore-case t)
10764 (member (member this org-todo-keywords-1))
10765 (tail (cdr member))
10766 (state (cond
10767 ((and org-todo-key-trigger
10768 (or (and (equal arg '(4))
10769 (eq org-use-fast-todo-selection 'prefix))
10770 (and (not arg) org-use-fast-todo-selection
10771 (not (eq org-use-fast-todo-selection
10772 'prefix)))))
10773 ;; Use fast selection
10774 (org-fast-todo-selection))
10775 ((and (equal arg '(4))
10776 (or (not org-use-fast-todo-selection)
10777 (not org-todo-key-trigger)))
10778 ;; Read a state with completion
10779 (org-icompleting-read
10780 "State: " (mapcar (lambda(x) (list x))
10781 org-todo-keywords-1)
10782 nil t))
10783 ((eq arg 'right)
10784 (if this
10785 (if tail (car tail) nil)
10786 (car org-todo-keywords-1)))
10787 ((eq arg 'left)
10788 (if (equal member org-todo-keywords-1)
10790 (if this
10791 (nth (- (length org-todo-keywords-1)
10792 (length tail) 2)
10793 org-todo-keywords-1)
10794 (org-last org-todo-keywords-1))))
10795 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
10796 (setq arg nil))) ; hack to fall back to cycling
10797 (arg
10798 ;; user or caller requests a specific state
10799 (cond
10800 ((equal arg "") nil)
10801 ((eq arg 'none) nil)
10802 ((eq arg 'done) (or done-word (car org-done-keywords)))
10803 ((eq arg 'nextset)
10804 (or (car (cdr (member head org-todo-heads)))
10805 (car org-todo-heads)))
10806 ((eq arg 'previousset)
10807 (let ((org-todo-heads (reverse org-todo-heads)))
10808 (or (car (cdr (member head org-todo-heads)))
10809 (car org-todo-heads))))
10810 ((car (member arg org-todo-keywords-1)))
10811 ((stringp arg)
10812 (error "State `%s' not valid in this file" arg))
10813 ((nth (1- (prefix-numeric-value arg))
10814 org-todo-keywords-1))))
10815 ((null member) (or head (car org-todo-keywords-1)))
10816 ((equal this final-done-word) nil) ;; -> make empty
10817 ((null tail) nil) ;; -> first entry
10818 ((memq interpret '(type priority))
10819 (if (eq this-command last-command)
10820 (car tail)
10821 (if (> (length tail) 0)
10822 (or done-word (car org-done-keywords))
10823 nil)))
10825 (car tail))))
10826 (state (or
10827 (run-hook-with-args-until-success
10828 'org-todo-get-default-hook state last-state)
10829 state))
10830 (next (if state (concat " " state " ") " "))
10831 (change-plist (list :type 'todo-state-change :from this :to state
10832 :position startpos))
10833 dolog now-done-p)
10834 (when org-blocker-hook
10835 (setq org-last-todo-state-is-todo
10836 (not (member this org-done-keywords)))
10837 (unless (save-excursion
10838 (save-match-data
10839 (run-hook-with-args-until-failure
10840 'org-blocker-hook change-plist)))
10841 (if (interactive-p)
10842 (error "TODO state change from %s to %s blocked" this state)
10843 ;; fail silently
10844 (message "TODO state change from %s to %s blocked" this state)
10845 (throw 'exit nil))))
10846 (store-match-data match-data)
10847 (replace-match next t t)
10848 (unless (pos-visible-in-window-p hl-pos)
10849 (message "TODO state changed to %s" (org-trim next)))
10850 (unless head
10851 (setq head (org-get-todo-sequence-head state)
10852 ass (assoc head org-todo-kwd-alist)
10853 interpret (nth 1 ass)
10854 done-word (nth 3 ass)
10855 final-done-word (nth 4 ass)))
10856 (when (memq arg '(nextset previousset))
10857 (message "Keyword-Set %d/%d: %s"
10858 (- (length org-todo-sets) -1
10859 (length (memq (assoc state org-todo-sets) org-todo-sets)))
10860 (length org-todo-sets)
10861 (mapconcat 'identity (assoc state org-todo-sets) " ")))
10862 (setq org-last-todo-state-is-todo
10863 (not (member state org-done-keywords)))
10864 (setq now-done-p (and (member state org-done-keywords)
10865 (not (member this org-done-keywords))))
10866 (and logging (org-local-logging logging))
10867 (when (and (or org-todo-log-states org-log-done)
10868 (not (eq org-inhibit-logging t))
10869 (not (memq arg '(nextset previousset))))
10870 ;; we need to look at recording a time and note
10871 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
10872 (nth 2 (assoc this org-todo-log-states))))
10873 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
10874 (setq dolog 'time))
10875 (when (and state
10876 (member state org-not-done-keywords)
10877 (not (member this org-not-done-keywords)))
10878 ;; This is now a todo state and was not one before
10879 ;; If there was a CLOSED time stamp, get rid of it.
10880 (org-add-planning-info nil nil 'closed))
10881 (when (and now-done-p org-log-done)
10882 ;; It is now done, and it was not done before
10883 (org-add-planning-info 'closed (org-current-time))
10884 (if (and (not dolog) (eq 'note org-log-done))
10885 (org-add-log-setup 'done state this 'findpos 'note)))
10886 (when (and state dolog)
10887 ;; This is a non-nil state, and we need to log it
10888 (org-add-log-setup 'state state this 'findpos dolog)))
10889 ;; Fixup tag positioning
10890 (org-todo-trigger-tag-changes state)
10891 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
10892 (when org-provide-todo-statistics
10893 (org-update-parent-todo-statistics))
10894 (run-hooks 'org-after-todo-state-change-hook)
10895 (if (and arg (not (member state org-done-keywords)))
10896 (setq head (org-get-todo-sequence-head state)))
10897 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
10898 ;; Do we need to trigger a repeat?
10899 (when now-done-p
10900 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
10901 ;; This is for the agenda, take a snapshot of the headline.
10902 (save-match-data
10903 (setq org-agenda-headline-snapshot-before-repeat
10904 (org-get-heading))))
10905 (org-auto-repeat-maybe state))
10906 ;; Fixup cursor location if close to the keyword
10907 (if (and (outline-on-heading-p)
10908 (not (bolp))
10909 (save-excursion (beginning-of-line 1)
10910 (looking-at org-todo-line-regexp))
10911 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
10912 (progn
10913 (goto-char (or (match-end 2) (match-end 1)))
10914 (and (looking-at " ") (just-one-space))))
10915 (when org-trigger-hook
10916 (save-excursion
10917 (run-hook-with-args 'org-trigger-hook change-plist))))))))
10919 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
10920 "Block turning an entry into a TODO, using the hierarchy.
10921 This checks whether the current task should be blocked from state
10922 changes. Such blocking occurs when:
10924 1. The task has children which are not all in a completed state.
10926 2. A task has a parent with the property :ORDERED:, and there
10927 are siblings prior to the current task with incomplete
10928 status.
10930 3. The parent of the task is blocked because it has siblings that should
10931 be done first, or is child of a block grandparent TODO entry."
10933 (if (not org-enforce-todo-dependencies)
10934 t ; if locally turned off don't block
10935 (catch 'dont-block
10936 ;; If this is not a todo state change, or if this entry is already DONE,
10937 ;; do not block
10938 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10939 (member (plist-get change-plist :from)
10940 (cons 'done org-done-keywords))
10941 (member (plist-get change-plist :to)
10942 (cons 'todo org-not-done-keywords))
10943 (not (plist-get change-plist :to)))
10944 (throw 'dont-block t))
10945 ;; If this task has children, and any are undone, it's blocked
10946 (save-excursion
10947 (org-back-to-heading t)
10948 (let ((this-level (funcall outline-level)))
10949 (outline-next-heading)
10950 (let ((child-level (funcall outline-level)))
10951 (while (and (not (eobp))
10952 (> child-level this-level))
10953 ;; this todo has children, check whether they are all
10954 ;; completed
10955 (if (and (not (org-entry-is-done-p))
10956 (org-entry-is-todo-p))
10957 (throw 'dont-block nil))
10958 (outline-next-heading)
10959 (setq child-level (funcall outline-level))))))
10960 ;; Otherwise, if the task's parent has the :ORDERED: property, and
10961 ;; any previous siblings are undone, it's blocked
10962 (save-excursion
10963 (org-back-to-heading t)
10964 (let* ((pos (point))
10965 (parent-pos (and (org-up-heading-safe) (point))))
10966 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10967 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
10968 (forward-line 1)
10969 (re-search-forward org-not-done-heading-regexp pos t))
10970 (throw 'dont-block nil)) ; block, there is an older sibling not done.
10971 ;; Search further up the hierarchy, to see if an anchestor is blocked
10972 (while t
10973 (goto-char parent-pos)
10974 (if (not (looking-at org-not-done-heading-regexp))
10975 (throw 'dont-block t)) ; do not block, parent is not a TODO
10976 (setq pos (point))
10977 (setq parent-pos (and (org-up-heading-safe) (point)))
10978 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10979 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
10980 (forward-line 1)
10981 (re-search-forward org-not-done-heading-regexp pos t))
10982 (throw 'dont-block nil)))))))) ; block, older sibling not done.
10984 (defcustom org-track-ordered-property-with-tag nil
10985 "Should the ORDERED property also be shown as a tag?
10986 The ORDERED property decides if an entry should require subtasks to be
10987 completed in sequence. Since a property is not very visible, setting
10988 this option means that toggling the ORDERED property with the command
10989 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
10990 not relevant for the behavior, but it makes things more visible.
10992 Note that toggling the tag with tags commands will not change the property
10993 and therefore not influence behavior!
10995 This can be t, meaning the tag ORDERED should be used, It can also be a
10996 string to select a different tag for this task."
10997 :group 'org-todo
10998 :type '(choice
10999 (const :tag "No tracking" nil)
11000 (const :tag "Track with ORDERED tag" t)
11001 (string :tag "Use other tag")))
11003 (defun org-toggle-ordered-property ()
11004 "Toggle the ORDERED property of the current entry.
11005 For better visibility, you can track the value of this property with a tag.
11006 See variable `org-track-ordered-property-with-tag'."
11007 (interactive)
11008 (let* ((t1 org-track-ordered-property-with-tag)
11009 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11010 (save-excursion
11011 (org-back-to-heading)
11012 (if (org-entry-get nil "ORDERED")
11013 (progn
11014 (org-delete-property "ORDERED")
11015 (and tag (org-toggle-tag tag 'off))
11016 (message "Subtasks can be completed in arbitrary order"))
11017 (org-entry-put nil "ORDERED" "t")
11018 (and tag (org-toggle-tag tag 'on))
11019 (message "Subtasks must be completed in sequence")))))
11021 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11022 (defun org-block-todo-from-checkboxes (change-plist)
11023 "Block turning an entry into a TODO, using checkboxes.
11024 This checks whether the current task should be blocked from state
11025 changes because there are unchecked boxes in this entry."
11026 (if (not org-enforce-todo-checkbox-dependencies)
11027 t ; if locally turned off don't block
11028 (catch 'dont-block
11029 ;; If this is not a todo state change, or if this entry is already DONE,
11030 ;; do not block
11031 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11032 (member (plist-get change-plist :from)
11033 (cons 'done org-done-keywords))
11034 (member (plist-get change-plist :to)
11035 (cons 'todo org-not-done-keywords))
11036 (not (plist-get change-plist :to)))
11037 (throw 'dont-block t))
11038 ;; If this task has checkboxes that are not checked, it's blocked
11039 (save-excursion
11040 (org-back-to-heading t)
11041 (let ((beg (point)) end)
11042 (outline-next-heading)
11043 (setq end (point))
11044 (goto-char beg)
11045 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
11046 end t)
11047 (progn
11048 (if (boundp 'org-blocked-by-checkboxes)
11049 (setq org-blocked-by-checkboxes t))
11050 (throw 'dont-block nil)))))
11051 t))) ; do not block
11053 (defun org-entry-blocked-p ()
11054 "Is the current entry blocked?"
11055 (if (org-entry-get nil "NOBLOCKING")
11056 nil ;; Never block this entry
11057 (not
11058 (run-hook-with-args-until-failure
11059 'org-blocker-hook
11060 (list :type 'todo-state-change
11061 :position (point)
11062 :from 'todo
11063 :to 'done)))))
11065 (defun org-update-statistics-cookies (all)
11066 "Update the statistics cookie, either from TODO or from checkboxes.
11067 This should be called with the cursor in a line with a statistics cookie."
11068 (interactive "P")
11069 (if all
11070 (progn
11071 (org-update-checkbox-count 'all)
11072 (org-map-entries 'org-update-parent-todo-statistics))
11073 (if (not (org-on-heading-p))
11074 (org-update-checkbox-count)
11075 (let ((pos (move-marker (make-marker) (point)))
11076 end l1 l2)
11077 (ignore-errors (org-back-to-heading t))
11078 (if (not (org-on-heading-p))
11079 (org-update-checkbox-count)
11080 (setq l1 (org-outline-level))
11081 (setq end (save-excursion
11082 (outline-next-heading)
11083 (if (org-on-heading-p) (setq l2 (org-outline-level)))
11084 (point)))
11085 (if (and (save-excursion
11086 (re-search-forward
11087 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11088 (not (save-excursion (re-search-forward
11089 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11090 (org-update-checkbox-count)
11091 (if (and l2 (> l2 l1))
11092 (progn
11093 (goto-char end)
11094 (org-update-parent-todo-statistics))
11095 (goto-char pos)
11096 (beginning-of-line 1)
11097 (while (re-search-forward
11098 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11099 (point-at-eol) t)
11100 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11101 (goto-char pos)
11102 (move-marker pos nil)))))
11104 (defvar org-entry-property-inherited-from) ;; defined below
11105 (defun org-update-parent-todo-statistics ()
11106 "Update any statistics cookie in the parent of the current headline.
11107 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11108 the entire subtree and this will travel up the hierarchy and update
11109 statistics everywhere."
11110 (interactive)
11111 (let* ((lim 0) prop
11112 (recursive (or (not org-hierarchical-todo-statistics)
11113 (string-match
11114 "\\<recursive\\>"
11115 (or (setq prop (org-entry-get
11116 nil "COOKIE_DATA" 'inherit)) ""))))
11117 (lim (or (and prop (marker-position
11118 org-entry-property-inherited-from))
11119 lim))
11120 (first t)
11121 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11122 level ltoggle l1 new ndel
11123 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
11124 (catch 'exit
11125 (save-excursion
11126 (beginning-of-line 1)
11127 (if (org-at-heading-p)
11128 (setq ltoggle (funcall outline-level))
11129 (error "This should not happen"))
11130 (while (and (setq level (org-up-heading-safe))
11131 (or recursive first)
11132 (>= (point) lim))
11133 (setq first nil cookie-present nil)
11134 (unless (and level
11135 (not (string-match
11136 "\\<checkbox\\>"
11137 (downcase
11138 (or (org-entry-get
11139 nil "COOKIE_DATA")
11140 "")))))
11141 (throw 'exit nil))
11142 (while (re-search-forward box-re (point-at-eol) t)
11143 (setq cnt-all 0 cnt-done 0 cookie-present t)
11144 (setq is-percent (match-end 2))
11145 (save-match-data
11146 (unless (outline-next-heading) (throw 'exit nil))
11147 (while (and (looking-at org-complex-heading-regexp)
11148 (> (setq l1 (length (match-string 1))) level))
11149 (setq kwd (and (or recursive (= l1 ltoggle))
11150 (match-string 2)))
11151 (if (or (eq org-provide-todo-statistics 'all-headlines)
11152 (and (listp org-provide-todo-statistics)
11153 (or (member kwd org-provide-todo-statistics)
11154 (member kwd org-done-keywords))))
11155 (setq cnt-all (1+ cnt-all))
11156 (if (eq org-provide-todo-statistics t)
11157 (and kwd (setq cnt-all (1+ cnt-all)))))
11158 (and (member kwd org-done-keywords)
11159 (setq cnt-done (1+ cnt-done)))
11160 (outline-next-heading)))
11161 (setq new
11162 (if is-percent
11163 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11164 (format "[%d/%d]" cnt-done cnt-all))
11165 ndel (- (match-end 0) (match-beginning 0)))
11166 (goto-char (match-beginning 0))
11167 (insert new)
11168 (delete-region (point) (+ (point) ndel)))
11169 (when cookie-present
11170 (run-hook-with-args 'org-after-todo-statistics-hook
11171 cnt-done (- cnt-all cnt-done))))))
11172 (run-hooks 'org-todo-statistics-hook)))
11174 (defvar org-after-todo-statistics-hook nil
11175 "Hook that is called after a TODO statistics cookie has been updated.
11176 Each function is called with two arguments: the number of not-done entries
11177 and the number of done entries.
11179 For example, the following function, when added to this hook, will switch
11180 an entry to DONE when all children are done, and back to TODO when new
11181 entries are set to a TODO status. Note that this hook is only called
11182 when there is a statistics cookie in the headline!
11184 (defun org-summary-todo (n-done n-not-done)
11185 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11186 (let (org-log-done org-log-states) ; turn off logging
11187 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11190 (defvar org-todo-statistics-hook nil
11191 "Hook that is run whenever Org thinks TODO statistics should be updated.
11192 This hook runs even if there is no statistics cookie present, in which case
11193 `org-after-todo-statistics-hook' would not run.")
11195 (defun org-todo-trigger-tag-changes (state)
11196 "Apply the changes defined in `org-todo-state-tags-triggers'."
11197 (let ((l org-todo-state-tags-triggers)
11198 changes)
11199 (when (or (not state) (equal state ""))
11200 (setq changes (append changes (cdr (assoc "" l)))))
11201 (when (and (stringp state) (> (length state) 0))
11202 (setq changes (append changes (cdr (assoc state l)))))
11203 (when (member state org-not-done-keywords)
11204 (setq changes (append changes (cdr (assoc 'todo l)))))
11205 (when (member state org-done-keywords)
11206 (setq changes (append changes (cdr (assoc 'done l)))))
11207 (dolist (c changes)
11208 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11210 (defun org-local-logging (value)
11211 "Get logging settings from a property VALUE."
11212 (let* (words w a)
11213 ;; directly set the variables, they are already local.
11214 (setq org-log-done nil
11215 org-log-repeat nil
11216 org-todo-log-states nil)
11217 (setq words (org-split-string value))
11218 (while (setq w (pop words))
11219 (cond
11220 ((setq a (assoc w org-startup-options))
11221 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11222 (set (nth 1 a) (nth 2 a))))
11223 ((setq a (org-extract-log-state-settings w))
11224 (and (member (car a) org-todo-keywords-1)
11225 (push a org-todo-log-states)))))))
11227 (defun org-get-todo-sequence-head (kwd)
11228 "Return the head of the TODO sequence to which KWD belongs.
11229 If KWD is not set, check if there is a text property remembering the
11230 right sequence."
11231 (let (p)
11232 (cond
11233 ((not kwd)
11234 (or (get-text-property (point-at-bol) 'org-todo-head)
11235 (progn
11236 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11237 nil (point-at-eol)))
11238 (get-text-property p 'org-todo-head))))
11239 ((not (member kwd org-todo-keywords-1))
11240 (car org-todo-keywords-1))
11241 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11243 (defun org-fast-todo-selection ()
11244 "Fast TODO keyword selection with single keys.
11245 Returns the new TODO keyword, or nil if no state change should occur."
11246 (let* ((fulltable org-todo-key-alist)
11247 (done-keywords org-done-keywords) ;; needed for the faces.
11248 (maxlen (apply 'max (mapcar
11249 (lambda (x)
11250 (if (stringp (car x)) (string-width (car x)) 0))
11251 fulltable)))
11252 (expert nil)
11253 (fwidth (+ maxlen 3 1 3))
11254 (ncol (/ (- (window-width) 4) fwidth))
11255 tg cnt e c tbl
11256 groups ingroup)
11257 (save-excursion
11258 (save-window-excursion
11259 (if expert
11260 (set-buffer (get-buffer-create " *Org todo*"))
11261 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11262 (erase-buffer)
11263 (org-set-local 'org-done-keywords done-keywords)
11264 (setq tbl fulltable cnt 0)
11265 (while (setq e (pop tbl))
11266 (cond
11267 ((equal e '(:startgroup))
11268 (push '() groups) (setq ingroup t)
11269 (when (not (= cnt 0))
11270 (setq cnt 0)
11271 (insert "\n"))
11272 (insert "{ "))
11273 ((equal e '(:endgroup))
11274 (setq ingroup nil cnt 0)
11275 (insert "}\n"))
11276 ((equal e '(:newline))
11277 (when (not (= cnt 0))
11278 (setq cnt 0)
11279 (insert "\n")
11280 (setq e (car tbl))
11281 (while (equal (car tbl) '(:newline))
11282 (insert "\n")
11283 (setq tbl (cdr tbl)))))
11285 (setq tg (car e) c (cdr e))
11286 (if ingroup (push tg (car groups)))
11287 (setq tg (org-add-props tg nil 'face
11288 (org-get-todo-face tg)))
11289 (if (and (= cnt 0) (not ingroup)) (insert " "))
11290 (insert "[" c "] " tg (make-string
11291 (- fwidth 4 (length tg)) ?\ ))
11292 (when (= (setq cnt (1+ cnt)) ncol)
11293 (insert "\n")
11294 (if ingroup (insert " "))
11295 (setq cnt 0)))))
11296 (insert "\n")
11297 (goto-char (point-min))
11298 (if (not expert) (org-fit-window-to-buffer))
11299 (message "[a-z..]:Set [SPC]:clear")
11300 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11301 (cond
11302 ((or (= c ?\C-g)
11303 (and (= c ?q) (not (rassoc c fulltable))))
11304 (setq quit-flag t))
11305 ((= c ?\ ) nil)
11306 ((setq e (rassoc c fulltable) tg (car e))
11308 (t (setq quit-flag t)))))))
11310 (defun org-entry-is-todo-p ()
11311 (member (org-get-todo-state) org-not-done-keywords))
11313 (defun org-entry-is-done-p ()
11314 (member (org-get-todo-state) org-done-keywords))
11316 (defun org-get-todo-state ()
11317 (save-excursion
11318 (org-back-to-heading t)
11319 (and (looking-at org-todo-line-regexp)
11320 (match-end 2)
11321 (match-string 2))))
11323 (defun org-at-date-range-p (&optional inactive-ok)
11324 "Is the cursor inside a date range?"
11325 (interactive)
11326 (save-excursion
11327 (catch 'exit
11328 (let ((pos (point)))
11329 (skip-chars-backward "^[<\r\n")
11330 (skip-chars-backward "<[")
11331 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11332 (>= (match-end 0) pos)
11333 (throw 'exit t))
11334 (skip-chars-backward "^<[\r\n")
11335 (skip-chars-backward "<[")
11336 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11337 (>= (match-end 0) pos)
11338 (throw 'exit t)))
11339 nil)))
11341 (defun org-get-repeat (&optional tagline)
11342 "Check if there is a deadline/schedule with repeater in this entry."
11343 (save-match-data
11344 (save-excursion
11345 (org-back-to-heading t)
11346 (and (re-search-forward (if tagline
11347 (concat tagline "\\s-*" org-repeat-re)
11348 org-repeat-re)
11349 (org-entry-end-position) t)
11350 (match-string-no-properties 1)))))
11352 (defvar org-last-changed-timestamp)
11353 (defvar org-last-inserted-timestamp)
11354 (defvar org-log-post-message)
11355 (defvar org-log-note-purpose)
11356 (defvar org-log-note-how)
11357 (defvar org-log-note-extra)
11358 (defun org-auto-repeat-maybe (done-word)
11359 "Check if the current headline contains a repeated deadline/schedule.
11360 If yes, set TODO state back to what it was and change the base date
11361 of repeating deadline/scheduled time stamps to new date.
11362 This function is run automatically after each state change to a DONE state."
11363 ;; last-state is dynamically scoped into this function
11364 (let* ((repeat (org-get-repeat))
11365 (aa (assoc last-state org-todo-kwd-alist))
11366 (interpret (nth 1 aa))
11367 (head (nth 2 aa))
11368 (whata '(("d" . day) ("m" . month) ("y" . year)))
11369 (msg "Entry repeats: ")
11370 (org-log-done nil)
11371 (org-todo-log-states nil)
11372 (nshiftmax 10) (nshift 0)
11373 re type n what ts time to-state)
11374 (when repeat
11375 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11376 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11377 org-todo-repeat-to-state))
11378 (unless (and to-state (member to-state org-todo-keywords-1))
11379 (setq to-state (if (eq interpret 'type) last-state head)))
11380 (org-todo to-state)
11381 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11382 (org-entry-put nil "LAST_REPEAT" (format-time-string
11383 (org-time-stamp-format t t))))
11384 (when org-log-repeat
11385 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11386 (memq 'org-add-log-note post-command-hook))
11387 ;; OK, we are already setup for some record
11388 (if (eq org-log-repeat 'note)
11389 ;; make sure we take a note, not only a time stamp
11390 (setq org-log-note-how 'note))
11391 ;; Set up for taking a record
11392 (org-add-log-setup 'state (or done-word (car org-done-keywords))
11393 last-state
11394 'findpos org-log-repeat)))
11395 (org-back-to-heading t)
11396 (org-add-planning-info nil nil 'closed)
11397 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11398 org-deadline-time-regexp "\\)\\|\\("
11399 org-ts-regexp "\\)"))
11400 (while (re-search-forward
11401 re (save-excursion (outline-next-heading) (point)) t)
11402 (setq type (if (match-end 1) org-scheduled-string
11403 (if (match-end 3) org-deadline-string "Plain:"))
11404 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
11405 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
11406 (setq n (string-to-number (match-string 2 ts))
11407 what (match-string 3 ts))
11408 (if (equal what "w") (setq n (* n 7) what "d"))
11409 ;; Preparation, see if we need to modify the start date for the change
11410 (when (match-end 1)
11411 (setq time (save-match-data (org-time-string-to-time ts)))
11412 (cond
11413 ((equal (match-string 1 ts) ".")
11414 ;; Shift starting date to today
11415 (org-timestamp-change
11416 (- (time-to-days (current-time)) (time-to-days time))
11417 'day))
11418 ((equal (match-string 1 ts) "+")
11419 (while (or (= nshift 0)
11420 (<= (time-to-days time) (time-to-days (current-time))))
11421 (when (= (incf nshift) nshiftmax)
11422 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
11423 (error "Abort")))
11424 (org-timestamp-change n (cdr (assoc what whata)))
11425 (org-at-timestamp-p t)
11426 (setq ts (match-string 1))
11427 (setq time (save-match-data (org-time-string-to-time ts))))
11428 (org-timestamp-change (- n) (cdr (assoc what whata)))
11429 ;; rematch, so that we have everything in place for the real shift
11430 (org-at-timestamp-p t)
11431 (setq ts (match-string 1))
11432 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
11433 (org-timestamp-change n (cdr (assoc what whata)))
11434 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
11435 (setq org-log-post-message msg)
11436 (message "%s" msg))))
11438 (defun org-show-todo-tree (arg)
11439 "Make a compact tree which shows all headlines marked with TODO.
11440 The tree will show the lines where the regexp matches, and all higher
11441 headlines above the match.
11442 With a \\[universal-argument] prefix, prompt for a regexp to match.
11443 With a numeric prefix N, construct a sparse tree for the Nth element
11444 of `org-todo-keywords-1'."
11445 (interactive "P")
11446 (let ((case-fold-search nil)
11447 (kwd-re
11448 (cond ((null arg) org-not-done-regexp)
11449 ((equal arg '(4))
11450 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
11451 (mapcar 'list org-todo-keywords-1))))
11452 (concat "\\("
11453 (mapconcat 'identity (org-split-string kwd "|") "\\|")
11454 "\\)\\>")))
11455 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
11456 (regexp-quote (nth (1- (prefix-numeric-value arg))
11457 org-todo-keywords-1)))
11458 (t (error "Invalid prefix argument: %s" arg)))))
11459 (message "%d TODO entries found"
11460 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
11462 (defun org-deadline (&optional remove time)
11463 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
11464 With argument REMOVE, remove any deadline from the item.
11465 When TIME is set, it should be an internal time specification, and the
11466 scheduling will use the corresponding date."
11467 (interactive "P")
11468 (let* ((old-date (org-entry-get nil "DEADLINE"))
11469 (repeater (and old-date
11470 (string-match "\\([.+]+[0-9]+[dwmy]\\) ?" old-date)
11471 (match-string 1 old-date))))
11472 (if remove
11473 (progn
11474 (when (and old-date org-log-redeadline)
11475 (org-add-log-setup 'deldeadline nil old-date 'findpos
11476 org-log-redeadline))
11477 (org-remove-timestamp-with-keyword org-deadline-string)
11478 (message "Item no longer has a deadline."))
11479 (org-add-planning-info 'deadline time 'closed)
11480 (when (and old-date org-log-redeadline
11481 (not (equal old-date
11482 (substring org-last-inserted-timestamp 1 -1))))
11483 (org-add-log-setup 'redeadline nil old-date 'findpos
11484 org-log-redeadline))
11485 (when repeater
11486 (save-excursion
11487 (org-back-to-heading t)
11488 (when (re-search-forward (concat org-deadline-string " "
11489 org-last-inserted-timestamp)
11490 (save-excursion
11491 (outline-next-heading) (point)) t)
11492 (goto-char (1- (match-end 0)))
11493 (insert " " repeater)
11494 (setq org-last-inserted-timestamp
11495 (concat (substring org-last-inserted-timestamp 0 -1)
11496 " " repeater
11497 (substring org-last-inserted-timestamp -1))))))
11498 (message "Deadline on %s" org-last-inserted-timestamp))))
11500 (defun org-schedule (&optional remove time)
11501 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
11502 With argument REMOVE, remove any scheduling date from the item.
11503 When TIME is set, it should be an internal time specification, and the
11504 scheduling will use the corresponding date."
11505 (interactive "P")
11506 (let* ((old-date (org-entry-get nil "SCHEDULED"))
11507 (repeater (and old-date
11508 (string-match "\\([.+]+[0-9]+[dwmy]\\) ?" old-date)
11509 (match-string 1 old-date))))
11510 (if remove
11511 (progn
11512 (when (and old-date org-log-reschedule)
11513 (org-add-log-setup 'delschedule nil old-date 'findpos
11514 org-log-reschedule))
11515 (org-remove-timestamp-with-keyword org-scheduled-string)
11516 (message "Item is no longer scheduled."))
11517 (org-add-planning-info 'scheduled time 'closed)
11518 (when (and old-date org-log-reschedule
11519 (not (equal old-date
11520 (substring org-last-inserted-timestamp 1 -1))))
11521 (org-add-log-setup 'reschedule nil old-date 'findpos
11522 org-log-reschedule))
11523 (when repeater
11524 (save-excursion
11525 (org-back-to-heading t)
11526 (when (re-search-forward (concat org-scheduled-string " "
11527 org-last-inserted-timestamp)
11528 (save-excursion
11529 (outline-next-heading) (point)) t)
11530 (goto-char (1- (match-end 0)))
11531 (insert " " repeater)
11532 (setq org-last-inserted-timestamp
11533 (concat (substring org-last-inserted-timestamp 0 -1)
11534 " " repeater
11535 (substring org-last-inserted-timestamp -1))))))
11536 (message "Scheduled to %s" org-last-inserted-timestamp))))
11538 (defun org-get-scheduled-time (pom &optional inherit)
11539 "Get the scheduled time as a time tuple, of a format suitable
11540 for calling org-schedule with, or if there is no scheduling,
11541 returns nil."
11542 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
11543 (when time
11544 (apply 'encode-time (org-parse-time-string time)))))
11546 (defun org-get-deadline-time (pom &optional inherit)
11547 "Get the deadline as a time tuple, of a format suitable for
11548 calling org-deadline with, or if there is no scheduling, returns
11549 nil."
11550 (let ((time (org-entry-get pom "DEADLINE" inherit)))
11551 (when time
11552 (apply 'encode-time (org-parse-time-string time)))))
11554 (defun org-remove-timestamp-with-keyword (keyword)
11555 "Remove all time stamps with KEYWORD in the current entry."
11556 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
11557 beg)
11558 (save-excursion
11559 (org-back-to-heading t)
11560 (setq beg (point))
11561 (outline-next-heading)
11562 (while (re-search-backward re beg t)
11563 (replace-match "")
11564 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
11565 (equal (char-before) ?\ ))
11566 (backward-delete-char 1)
11567 (if (string-match "^[ \t]*$" (buffer-substring
11568 (point-at-bol) (point-at-eol)))
11569 (delete-region (point-at-bol)
11570 (min (point-max) (1+ (point-at-eol))))))))))
11572 (defun org-add-planning-info (what &optional time &rest remove)
11573 "Insert new timestamp with keyword in the line directly after the headline.
11574 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
11575 If non is given, the user is prompted for a date.
11576 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
11577 be removed."
11578 (interactive)
11579 (let (org-time-was-given org-end-time-was-given ts
11580 end default-time default-input)
11582 (catch 'exit
11583 (when (and (not time) (memq what '(scheduled deadline)))
11584 ;; Try to get a default date/time from existing timestamp
11585 (save-excursion
11586 (org-back-to-heading t)
11587 (setq end (save-excursion (outline-next-heading) (point)))
11588 (when (re-search-forward (if (eq what 'scheduled)
11589 org-scheduled-time-regexp
11590 org-deadline-time-regexp)
11591 end t)
11592 (setq ts (match-string 1)
11593 default-time
11594 (apply 'encode-time (org-parse-time-string ts))
11595 default-input (and ts (org-get-compact-tod ts))))))
11596 (when what
11597 ;; If necessary, get the time from the user
11598 (setq time (or time (org-read-date nil 'to-time nil nil
11599 default-time default-input))))
11601 (when (and org-insert-labeled-timestamps-at-point
11602 (member what '(scheduled deadline)))
11603 (insert
11604 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
11605 (org-insert-time-stamp time org-time-was-given
11606 nil nil nil (list org-end-time-was-given))
11607 (setq what nil))
11608 (save-excursion
11609 (save-restriction
11610 (let (col list elt ts buffer-invisibility-spec)
11611 (org-back-to-heading t)
11612 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
11613 (goto-char (match-end 1))
11614 (setq col (current-column))
11615 (goto-char (match-end 0))
11616 (if (eobp) (insert "\n") (forward-char 1))
11617 (when (and (not what)
11618 (not (looking-at
11619 (concat "[ \t]*"
11620 org-keyword-time-not-clock-regexp))))
11621 ;; Nothing to add, nothing to remove...... :-)
11622 (throw 'exit nil))
11623 (if (and (not (looking-at outline-regexp))
11624 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
11625 "[^\r\n]*"))
11626 (not (equal (match-string 1) org-clock-string)))
11627 (narrow-to-region (match-beginning 0) (match-end 0))
11628 (insert-before-markers "\n")
11629 (backward-char 1)
11630 (narrow-to-region (point) (point))
11631 (and org-adapt-indentation (org-indent-to-column col)))
11632 ;; Check if we have to remove something.
11633 (setq list (cons what remove))
11634 (while list
11635 (setq elt (pop list))
11636 (goto-char (point-min))
11637 (when (or (and (eq elt 'scheduled)
11638 (re-search-forward org-scheduled-time-regexp nil t))
11639 (and (eq elt 'deadline)
11640 (re-search-forward org-deadline-time-regexp nil t))
11641 (and (eq elt 'closed)
11642 (re-search-forward org-closed-time-regexp nil t)))
11643 (replace-match "")
11644 (if (looking-at "--+<[^>]+>") (replace-match ""))
11645 (skip-chars-backward " ")
11646 (if (looking-at " +") (replace-match ""))))
11647 (goto-char (point-max))
11648 (and org-adapt-indentation (bolp) (org-indent-to-column col))
11649 (when what
11650 (insert
11651 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
11652 (cond ((eq what 'scheduled) org-scheduled-string)
11653 ((eq what 'deadline) org-deadline-string)
11654 ((eq what 'closed) org-closed-string))
11655 " ")
11656 (setq ts (org-insert-time-stamp
11657 time
11658 (or org-time-was-given
11659 (and (eq what 'closed) org-log-done-with-time))
11660 (eq what 'closed)
11661 nil nil (list org-end-time-was-given)))
11662 (end-of-line 1))
11663 (goto-char (point-min))
11664 (widen)
11665 (if (and (looking-at "[ \t]*\n")
11666 (equal (char-before) ?\n))
11667 (delete-region (1- (point)) (point-at-eol)))
11668 ts))))))
11670 (defvar org-log-note-marker (make-marker))
11671 (defvar org-log-note-purpose nil)
11672 (defvar org-log-note-state nil)
11673 (defvar org-log-note-previous-state nil)
11674 (defvar org-log-note-how nil)
11675 (defvar org-log-note-extra nil)
11676 (defvar org-log-note-window-configuration nil)
11677 (defvar org-log-note-return-to (make-marker))
11678 (defvar org-log-post-message nil
11679 "Message to be displayed after a log note has been stored.
11680 The auto-repeater uses this.")
11682 (defun org-add-note ()
11683 "Add a note to the current entry.
11684 This is done in the same way as adding a state change note."
11685 (interactive)
11686 (org-add-log-setup 'note nil nil 'findpos nil))
11688 (defvar org-property-end-re)
11689 (defun org-add-log-setup (&optional purpose state prev-state
11690 findpos how &optional extra)
11691 "Set up the post command hook to take a note.
11692 If this is about to TODO state change, the new state is expected in STATE.
11693 When FINDPOS is non-nil, find the correct position for the note in
11694 the current entry. If not, assume that it can be inserted at point.
11695 HOW is an indicator what kind of note should be created.
11696 EXTRA is additional text that will be inserted into the notes buffer."
11697 (let* ((org-log-into-drawer (org-log-into-drawer))
11698 (drawer (cond ((stringp org-log-into-drawer)
11699 org-log-into-drawer)
11700 (org-log-into-drawer "LOGBOOK")
11701 (t nil))))
11702 (save-restriction
11703 (save-excursion
11704 (when findpos
11705 (org-back-to-heading t)
11706 (narrow-to-region (point) (save-excursion
11707 (outline-next-heading) (point)))
11708 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
11709 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
11710 "[^\r\n]*\\)?"))
11711 (goto-char (match-end 0))
11712 (cond
11713 (drawer
11714 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
11715 nil t)
11716 (progn
11717 (goto-char (match-end 0))
11718 (or org-log-states-order-reversed
11719 (and (re-search-forward org-property-end-re nil t)
11720 (goto-char (1- (match-beginning 0))))))
11721 (insert "\n:" drawer ":\n:END:")
11722 (beginning-of-line 0)
11723 (org-indent-line-function)
11724 (beginning-of-line 2)
11725 (org-indent-line-function)
11726 (end-of-line 0)))
11727 ((and org-log-state-notes-insert-after-drawers
11728 (save-excursion
11729 (forward-line) (looking-at org-drawer-regexp)))
11730 (forward-line)
11731 (while (looking-at org-drawer-regexp)
11732 (goto-char (match-end 0))
11733 (re-search-forward org-property-end-re (point-max) t)
11734 (forward-line))
11735 (forward-line -1)))
11736 (unless org-log-states-order-reversed
11737 (and (= (char-after) ?\n) (forward-char 1))
11738 (org-skip-over-state-notes)
11739 (skip-chars-backward " \t\n\r")))
11740 (move-marker org-log-note-marker (point))
11741 (setq org-log-note-purpose purpose
11742 org-log-note-state state
11743 org-log-note-previous-state prev-state
11744 org-log-note-how how
11745 org-log-note-extra extra)
11746 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
11748 (defun org-skip-over-state-notes ()
11749 "Skip past the list of State notes in an entry."
11750 (if (looking-at "\n[ \t]*- State") (forward-char 1))
11751 (while (looking-at "[ \t]*- State")
11752 (condition-case nil
11753 (org-next-item)
11754 (error (org-end-of-item)))))
11756 (defun org-add-log-note (&optional purpose)
11757 "Pop up a window for taking a note, and add this note later at point."
11758 (remove-hook 'post-command-hook 'org-add-log-note)
11759 (setq org-log-note-window-configuration (current-window-configuration))
11760 (delete-other-windows)
11761 (move-marker org-log-note-return-to (point))
11762 (switch-to-buffer (marker-buffer org-log-note-marker))
11763 (goto-char org-log-note-marker)
11764 (org-switch-to-buffer-other-window "*Org Note*")
11765 (erase-buffer)
11766 (if (memq org-log-note-how '(time state))
11767 (let (current-prefix-arg) (org-store-log-note))
11768 (let ((org-inhibit-startup t)) (org-mode))
11769 (insert (format "# Insert note for %s.
11770 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
11771 (cond
11772 ((eq org-log-note-purpose 'clock-out) "stopped clock")
11773 ((eq org-log-note-purpose 'done) "closed todo item")
11774 ((eq org-log-note-purpose 'state)
11775 (format "state change from \"%s\" to \"%s\""
11776 (or org-log-note-previous-state "")
11777 (or org-log-note-state "")))
11778 ((eq org-log-note-purpose 'reschedule)
11779 "rescheduling")
11780 ((eq org-log-note-purpose 'delschedule)
11781 "no longer scheduled")
11782 ((eq org-log-note-purpose 'redeadline)
11783 "changing deadline")
11784 ((eq org-log-note-purpose 'deldeadline)
11785 "removing deadline")
11786 ((eq org-log-note-purpose 'refile)
11787 "refiling")
11788 ((eq org-log-note-purpose 'note)
11789 "this entry")
11790 (t (error "This should not happen")))))
11791 (if org-log-note-extra (insert org-log-note-extra))
11792 (org-set-local 'org-finish-function 'org-store-log-note)))
11794 (defvar org-note-abort nil) ; dynamically scoped
11795 (defun org-store-log-note ()
11796 "Finish taking a log note, and insert it to where it belongs."
11797 (let ((txt (buffer-string))
11798 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
11799 lines ind)
11800 (kill-buffer (current-buffer))
11801 (while (string-match "\\`#.*\n[ \t\n]*" txt)
11802 (setq txt (replace-match "" t t txt)))
11803 (if (string-match "\\s-+\\'" txt)
11804 (setq txt (replace-match "" t t txt)))
11805 (setq lines (org-split-string txt "\n"))
11806 (when (and note (string-match "\\S-" note))
11807 (setq note
11808 (org-replace-escapes
11809 note
11810 (list (cons "%u" (user-login-name))
11811 (cons "%U" user-full-name)
11812 (cons "%t" (format-time-string
11813 (org-time-stamp-format 'long 'inactive)
11814 (current-time)))
11815 (cons "%T" (format-time-string
11816 (org-time-stamp-format 'long nil)
11817 (current-time)))
11818 (cons "%s" (if org-log-note-state
11819 (concat "\"" org-log-note-state "\"")
11820 ""))
11821 (cons "%S" (if org-log-note-previous-state
11822 (concat "\"" org-log-note-previous-state "\"")
11823 "\"\"")))))
11824 (if lines (setq note (concat note " \\\\")))
11825 (push note lines))
11826 (when (or current-prefix-arg org-note-abort)
11827 (when org-log-into-drawer
11828 (org-remove-empty-drawer-at
11829 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
11830 org-log-note-marker))
11831 (setq lines nil))
11832 (when lines
11833 (with-current-buffer (marker-buffer org-log-note-marker)
11834 (save-excursion
11835 (goto-char org-log-note-marker)
11836 (move-marker org-log-note-marker nil)
11837 (end-of-line 1)
11838 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
11839 (insert "- " (pop lines))
11840 (org-indent-line-function)
11841 (beginning-of-line 1)
11842 (looking-at "[ \t]*")
11843 (setq ind (concat (match-string 0) " "))
11844 (end-of-line 1)
11845 (while lines (insert "\n" ind (pop lines)))
11846 (message "Note stored")
11847 (org-back-to-heading t)
11848 (org-cycle-hide-drawers 'children)))))
11849 (set-window-configuration org-log-note-window-configuration)
11850 (with-current-buffer (marker-buffer org-log-note-return-to)
11851 (goto-char org-log-note-return-to))
11852 (move-marker org-log-note-return-to nil)
11853 (and org-log-post-message (message "%s" org-log-post-message)))
11855 (defun org-remove-empty-drawer-at (drawer pos)
11856 "Remove an empty drawer DRAWER at position POS.
11857 POS may also be a marker."
11858 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
11859 (save-excursion
11860 (save-restriction
11861 (widen)
11862 (goto-char pos)
11863 (if (org-in-regexp
11864 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
11865 (replace-match ""))))))
11867 (defun org-sparse-tree (&optional arg)
11868 "Create a sparse tree, prompt for the details.
11869 This command can create sparse trees. You first need to select the type
11870 of match used to create the tree:
11872 t Show all TODO entries.
11873 T Show entries with a specific TODO keyword.
11874 m Show entries selected by a tags/property match.
11875 p Enter a property name and its value (both with completion on existing
11876 names/values) and show entries with that property.
11877 / Show entries matching a regular expression (`r' can be used as well)
11878 d Show deadlines due within `org-deadline-warning-days'.
11879 b Show deadlines and scheduled items before a date.
11880 a Show deadlines and scheduled items after a date."
11881 (interactive "P")
11882 (let (ans kwd value)
11883 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty [d]eadlines\n [b]efore-date [a]fter-date")
11884 (setq ans (read-char-exclusive))
11885 (cond
11886 ((equal ans ?d)
11887 (call-interactively 'org-check-deadlines))
11888 ((equal ans ?b)
11889 (call-interactively 'org-check-before-date))
11890 ((equal ans ?a)
11891 (call-interactively 'org-check-after-date))
11892 ((equal ans ?t)
11893 (org-show-todo-tree nil))
11894 ((equal ans ?T)
11895 (org-show-todo-tree '(4)))
11896 ((member ans '(?T ?m))
11897 (call-interactively 'org-match-sparse-tree))
11898 ((member ans '(?p ?P))
11899 (setq kwd (org-icompleting-read "Property: "
11900 (mapcar 'list (org-buffer-property-keys))))
11901 (setq value (org-icompleting-read "Value: "
11902 (mapcar 'list (org-property-values kwd))))
11903 (unless (string-match "\\`{.*}\\'" value)
11904 (setq value (concat "\"" value "\"")))
11905 (org-match-sparse-tree arg (concat kwd "=" value)))
11906 ((member ans '(?r ?R ?/))
11907 (call-interactively 'org-occur))
11908 (t (error "No such sparse tree command \"%c\"" ans)))))
11910 (defvar org-occur-highlights nil
11911 "List of overlays used for occur matches.")
11912 (make-variable-buffer-local 'org-occur-highlights)
11913 (defvar org-occur-parameters nil
11914 "Parameters of the active org-occur calls.
11915 This is a list, each call to org-occur pushes as cons cell,
11916 containing the regular expression and the callback, onto the list.
11917 The list can contain several entries if `org-occur' has been called
11918 several time with the KEEP-PREVIOUS argument. Otherwise, this list
11919 will only contain one set of parameters. When the highlights are
11920 removed (for example with `C-c C-c', or with the next edit (depending
11921 on `org-remove-highlights-with-change'), this variable is emptied
11922 as well.")
11923 (make-variable-buffer-local 'org-occur-parameters)
11925 (defun org-occur (regexp &optional keep-previous callback)
11926 "Make a compact tree which shows all matches of REGEXP.
11927 The tree will show the lines where the regexp matches, and all higher
11928 headlines above the match. It will also show the heading after the match,
11929 to make sure editing the matching entry is easy.
11930 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
11931 call to `org-occur' will be kept, to allow stacking of calls to this
11932 command.
11933 If CALLBACK is non-nil, it is a function which is called to confirm
11934 that the match should indeed be shown."
11935 (interactive "sRegexp: \nP")
11936 (when (equal regexp "")
11937 (error "Regexp cannot be empty"))
11938 (unless keep-previous
11939 (org-remove-occur-highlights nil nil t))
11940 (push (cons regexp callback) org-occur-parameters)
11941 (let ((cnt 0))
11942 (save-excursion
11943 (goto-char (point-min))
11944 (if (or (not keep-previous) ; do not want to keep
11945 (not org-occur-highlights)) ; no previous matches
11946 ;; hide everything
11947 (org-overview))
11948 (while (re-search-forward regexp nil t)
11949 (when (or (not callback)
11950 (save-match-data (funcall callback)))
11951 (setq cnt (1+ cnt))
11952 (when org-highlight-sparse-tree-matches
11953 (org-highlight-new-match (match-beginning 0) (match-end 0)))
11954 (org-show-context 'occur-tree))))
11955 (when org-remove-highlights-with-change
11956 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
11957 nil 'local))
11958 (unless org-sparse-tree-open-archived-trees
11959 (org-hide-archived-subtrees (point-min) (point-max)))
11960 (run-hooks 'org-occur-hook)
11961 (if (interactive-p)
11962 (message "%d match(es) for regexp %s" cnt regexp))
11963 cnt))
11965 (defun org-show-context (&optional key)
11966 "Make sure point and context are visible.
11967 How much context is shown depends upon the variables
11968 `org-show-hierarchy-above', `org-show-following-heading'. and
11969 `org-show-siblings'."
11970 (let ((heading-p (org-on-heading-p t))
11971 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
11972 (following-p (org-get-alist-option org-show-following-heading key))
11973 (entry-p (org-get-alist-option org-show-entry-below key))
11974 (siblings-p (org-get-alist-option org-show-siblings key)))
11975 (catch 'exit
11976 ;; Show heading or entry text
11977 (if (and heading-p (not entry-p))
11978 (org-flag-heading nil) ; only show the heading
11979 (and (or entry-p (org-invisible-p) (org-invisible-p2))
11980 (org-show-hidden-entry))) ; show entire entry
11981 (when following-p
11982 ;; Show next sibling, or heading below text
11983 (save-excursion
11984 (and (if heading-p (org-goto-sibling) (outline-next-heading))
11985 (org-flag-heading nil))))
11986 (when siblings-p (org-show-siblings))
11987 (when hierarchy-p
11988 ;; show all higher headings, possibly with siblings
11989 (save-excursion
11990 (while (and (condition-case nil
11991 (progn (org-up-heading-all 1) t)
11992 (error nil))
11993 (not (bobp)))
11994 (org-flag-heading nil)
11995 (when siblings-p (org-show-siblings))))))))
11997 (defvar org-reveal-start-hook nil
11998 "Hook run before revealing a location.")
12000 (defun org-reveal (&optional siblings)
12001 "Show current entry, hierarchy above it, and the following headline.
12002 This can be used to show a consistent set of context around locations
12003 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12004 not t for the search context.
12006 With optional argument SIBLINGS, on each level of the hierarchy all
12007 siblings are shown. This repairs the tree structure to what it would
12008 look like when opened with hierarchical calls to `org-cycle'.
12009 With double optional argument \\[universal-argument] \\[universal-argument], \
12010 go to the parent and show the
12011 entire tree."
12012 (interactive "P")
12013 (run-hooks 'org-reveal-start-hook)
12014 (let ((org-show-hierarchy-above t)
12015 (org-show-following-heading t)
12016 (org-show-siblings (if siblings t org-show-siblings)))
12017 (org-show-context nil))
12018 (when (equal siblings '(16))
12019 (save-excursion
12020 (when (org-up-heading-safe)
12021 (org-show-subtree)
12022 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12024 (defun org-highlight-new-match (beg end)
12025 "Highlight from BEG to END and mark the highlight is an occur headline."
12026 (let ((ov (make-overlay beg end)))
12027 (overlay-put ov 'face 'secondary-selection)
12028 (push ov org-occur-highlights)))
12030 (defun org-remove-occur-highlights (&optional beg end noremove)
12031 "Remove the occur highlights from the buffer.
12032 BEG and END are ignored. If NOREMOVE is nil, remove this function
12033 from the `before-change-functions' in the current buffer."
12034 (interactive)
12035 (unless org-inhibit-highlight-removal
12036 (mapc 'delete-overlay org-occur-highlights)
12037 (setq org-occur-highlights nil)
12038 (setq org-occur-parameters nil)
12039 (unless noremove
12040 (remove-hook 'before-change-functions
12041 'org-remove-occur-highlights 'local))))
12043 ;;;; Priorities
12045 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12046 "Regular expression matching the priority indicator.")
12048 (defvar org-remove-priority-next-time nil)
12050 (defun org-priority-up ()
12051 "Increase the priority of the current item."
12052 (interactive)
12053 (org-priority 'up))
12055 (defun org-priority-down ()
12056 "Decrease the priority of the current item."
12057 (interactive)
12058 (org-priority 'down))
12060 (defun org-priority (&optional action)
12061 "Change the priority of an item by ARG.
12062 ACTION can be `set', `up', `down', or a character."
12063 (interactive)
12064 (unless org-enable-priority-commands
12065 (error "Priority commands are disabled"))
12066 (setq action (or action 'set))
12067 (let (current new news have remove)
12068 (save-excursion
12069 (org-back-to-heading t)
12070 (if (looking-at org-priority-regexp)
12071 (setq current (string-to-char (match-string 2))
12072 have t)
12073 (setq current org-default-priority))
12074 (cond
12075 ((eq action 'remove)
12076 (setq remove t new ?\ ))
12077 ((or (eq action 'set)
12078 (if (featurep 'xemacs) (characterp action) (integerp action)))
12079 (if (not (eq action 'set))
12080 (setq new action)
12081 (message "Priority %c-%c, SPC to remove: "
12082 org-highest-priority org-lowest-priority)
12083 (setq new (read-char-exclusive)))
12084 (if (and (= (upcase org-highest-priority) org-highest-priority)
12085 (= (upcase org-lowest-priority) org-lowest-priority))
12086 (setq new (upcase new)))
12087 (cond ((equal new ?\ ) (setq remove t))
12088 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12089 (error "Priority must be between `%c' and `%c'"
12090 org-highest-priority org-lowest-priority))))
12091 ((eq action 'up)
12092 (if (and (not have) (eq last-command this-command))
12093 (setq new org-lowest-priority)
12094 (setq new (if (and org-priority-start-cycle-with-default (not have))
12095 org-default-priority (1- current)))))
12096 ((eq action 'down)
12097 (if (and (not have) (eq last-command this-command))
12098 (setq new org-highest-priority)
12099 (setq new (if (and org-priority-start-cycle-with-default (not have))
12100 org-default-priority (1+ current)))))
12101 (t (error "Invalid action")))
12102 (if (or (< (upcase new) org-highest-priority)
12103 (> (upcase new) org-lowest-priority))
12104 (setq remove t))
12105 (setq news (format "%c" new))
12106 (if have
12107 (if remove
12108 (replace-match "" t t nil 1)
12109 (replace-match news t t nil 2))
12110 (if remove
12111 (error "No priority cookie found in line")
12112 (let ((case-fold-search nil))
12113 (looking-at org-todo-line-regexp))
12114 (if (match-end 2)
12115 (progn
12116 (goto-char (match-end 2))
12117 (insert " [#" news "]"))
12118 (goto-char (match-beginning 3))
12119 (insert "[#" news "] "))))
12120 (org-preserve-lc (org-set-tags nil 'align)))
12121 (if remove
12122 (message "Priority removed")
12123 (message "Priority of current item set to %s" news))))
12125 (defun org-get-priority (s)
12126 "Find priority cookie and return priority."
12127 (save-match-data
12128 (if (not (string-match org-priority-regexp s))
12129 (* 1000 (- org-lowest-priority org-default-priority))
12130 (* 1000 (- org-lowest-priority
12131 (string-to-char (match-string 2 s)))))))
12133 ;;;; Tags
12135 (defvar org-agenda-archives-mode)
12136 (defvar org-map-continue-from nil
12137 "Position from where mapping should continue.
12138 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
12140 (defvar org-scanner-tags nil
12141 "The current tag list while the tags scanner is running.")
12142 (defvar org-trust-scanner-tags nil
12143 "Should `org-get-tags-at' use the tags fro the scanner.
12144 This is for internal dynamical scoping only.
12145 When this is non-nil, the function `org-get-tags-at' will return the value
12146 of `org-scanner-tags' instead of building the list by itself. This
12147 can lead to large speed-ups when the tags scanner is used in a file with
12148 many entries, and when the list of tags is retrieved, for example to
12149 obtain a list of properties. Building the tags list for each entry in such
12150 a file becomes an N^2 operation - but with this variable set, it scales
12151 as N.")
12153 (defun org-scan-tags (action matcher &optional todo-only)
12154 "Scan headline tags with inheritance and produce output ACTION.
12156 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12157 or `agenda' to produce an entry list for an agenda view. It can also be
12158 a Lisp form or a function that should be called at each matched headline, in
12159 this case the return value is a list of all return values from these calls.
12161 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12162 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12163 only lines with a TODO keyword are included in the output."
12164 (require 'org-agenda)
12165 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
12166 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12167 (org-re
12168 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
12169 (props (list 'face 'default
12170 'done-face 'org-agenda-done
12171 'undone-face 'default
12172 'mouse-face 'highlight
12173 'org-not-done-regexp org-not-done-regexp
12174 'org-todo-regexp org-todo-regexp
12175 'help-echo
12176 (format "mouse-2 or RET jump to org file %s"
12177 (abbreviate-file-name
12178 (or (buffer-file-name (buffer-base-buffer))
12179 (buffer-name (buffer-base-buffer)))))))
12180 (case-fold-search nil)
12181 (org-map-continue-from nil)
12182 lspos tags tags-list
12183 (tags-alist (list (cons 0 org-file-tags)))
12184 (llast 0) rtn rtn1 level category i txt
12185 todo marker entry priority)
12186 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12187 (setq action (list 'lambda nil action)))
12188 (save-excursion
12189 (goto-char (point-min))
12190 (when (eq action 'sparse-tree)
12191 (org-overview)
12192 (org-remove-occur-highlights))
12193 (while (re-search-forward re nil t)
12194 (catch :skip
12195 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12196 tags (if (match-end 4) (org-match-string-no-properties 4)))
12197 (goto-char (setq lspos (match-beginning 0)))
12198 (setq level (org-reduced-level (funcall outline-level))
12199 category (org-get-category))
12200 (setq i llast llast level)
12201 ;; remove tag lists from same and sublevels
12202 (while (>= i level)
12203 (when (setq entry (assoc i tags-alist))
12204 (setq tags-alist (delete entry tags-alist)))
12205 (setq i (1- i)))
12206 ;; add the next tags
12207 (when tags
12208 (setq tags (org-split-string tags ":")
12209 tags-alist
12210 (cons (cons level tags) tags-alist)))
12211 ;; compile tags for current headline
12212 (setq tags-list
12213 (if org-use-tag-inheritance
12214 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12215 tags)
12216 org-scanner-tags tags-list)
12217 (when org-use-tag-inheritance
12218 (setcdr (car tags-alist)
12219 (mapcar (lambda (x)
12220 (setq x (copy-sequence x))
12221 (org-add-prop-inherited x))
12222 (cdar tags-alist))))
12223 (when (and tags org-use-tag-inheritance
12224 (or (not (eq t org-use-tag-inheritance))
12225 org-tags-exclude-from-inheritance))
12226 ;; selective inheritance, remove uninherited ones
12227 (setcdr (car tags-alist)
12228 (org-remove-uniherited-tags (cdar tags-alist))))
12229 (when (and (or (not todo-only)
12230 (and (member todo org-not-done-keywords)
12231 (or (not org-agenda-tags-todo-honor-ignore-options)
12232 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
12233 (let ((case-fold-search t)) (eval matcher))
12235 (not (member org-archive-tag tags-list))
12236 ;; we have an archive tag, should we use this anyway?
12237 (or (not org-agenda-skip-archived-trees)
12238 (and (eq action 'agenda) org-agenda-archives-mode))))
12239 (unless (eq action 'sparse-tree) (org-agenda-skip))
12241 ;; select this headline
12243 (cond
12244 ((eq action 'sparse-tree)
12245 (and org-highlight-sparse-tree-matches
12246 (org-get-heading) (match-end 0)
12247 (org-highlight-new-match
12248 (match-beginning 0) (match-beginning 1)))
12249 (org-show-context 'tags-tree))
12250 ((eq action 'agenda)
12251 (setq txt (org-format-agenda-item
12253 (concat
12254 (if (eq org-tags-match-list-sublevels 'indented)
12255 (make-string (1- level) ?.) "")
12256 (org-get-heading))
12257 category
12258 tags-list
12260 priority (org-get-priority txt))
12261 (goto-char lspos)
12262 (setq marker (org-agenda-new-marker))
12263 (org-add-props txt props
12264 'org-marker marker 'org-hd-marker marker 'org-category category
12265 'todo-state todo
12266 'priority priority 'type "tagsmatch")
12267 (push txt rtn))
12268 ((functionp action)
12269 (setq org-map-continue-from nil)
12270 (save-excursion
12271 (setq rtn1 (funcall action))
12272 (push rtn1 rtn)))
12273 (t (error "Invalid action")))
12275 ;; if we are to skip sublevels, jump to end of subtree
12276 (unless org-tags-match-list-sublevels
12277 (org-end-of-subtree t)
12278 (backward-char 1))))
12279 ;; Get the correct position from where to continue
12280 (if org-map-continue-from
12281 (goto-char org-map-continue-from)
12282 (and (= (point) lspos) (end-of-line 1)))))
12283 (when (and (eq action 'sparse-tree)
12284 (not org-sparse-tree-open-archived-trees))
12285 (org-hide-archived-subtrees (point-min) (point-max)))
12286 (nreverse rtn)))
12288 (defun org-remove-uniherited-tags (tags)
12289 "Remove all tags that are not inherited from the list TAGS."
12290 (cond
12291 ((eq org-use-tag-inheritance t)
12292 (if org-tags-exclude-from-inheritance
12293 (org-delete-all org-tags-exclude-from-inheritance tags)
12294 tags))
12295 ((not org-use-tag-inheritance) nil)
12296 ((stringp org-use-tag-inheritance)
12297 (delq nil (mapcar
12298 (lambda (x)
12299 (if (and (string-match org-use-tag-inheritance x)
12300 (not (member x org-tags-exclude-from-inheritance)))
12301 x nil))
12302 tags)))
12303 ((listp org-use-tag-inheritance)
12304 (delq nil (mapcar
12305 (lambda (x)
12306 (if (member x org-use-tag-inheritance) x nil))
12307 tags)))))
12309 (defvar todo-only) ;; dynamically scoped
12311 (defun org-match-sparse-tree (&optional todo-only match)
12312 "Create a sparse tree according to tags string MATCH.
12313 MATCH can contain positive and negative selection of tags, like
12314 \"+WORK+URGENT-WITHBOSS\".
12315 If optional argument TODO-ONLY is non-nil, only select lines that are
12316 also TODO lines."
12317 (interactive "P")
12318 (org-prepare-agenda-buffers (list (current-buffer)))
12319 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
12321 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
12323 (defvar org-cached-props nil)
12324 (defun org-cached-entry-get (pom property)
12325 (if (or (eq t org-use-property-inheritance)
12326 (and (stringp org-use-property-inheritance)
12327 (string-match org-use-property-inheritance property))
12328 (and (listp org-use-property-inheritance)
12329 (member property org-use-property-inheritance)))
12330 ;; Caching is not possible, check it directly
12331 (org-entry-get pom property 'inherit)
12332 ;; Get all properties, so that we can do complicated checks easily
12333 (cdr (assoc property (or org-cached-props
12334 (setq org-cached-props
12335 (org-entry-properties pom)))))))
12337 (defun org-global-tags-completion-table (&optional files)
12338 "Return the list of all tags in all agenda buffer/files."
12339 (save-excursion
12340 (org-uniquify
12341 (delq nil
12342 (apply 'append
12343 (mapcar
12344 (lambda (file)
12345 (set-buffer (find-file-noselect file))
12346 (append (org-get-buffer-tags)
12347 (mapcar (lambda (x) (if (stringp (car-safe x))
12348 (list (car-safe x)) nil))
12349 org-tag-alist)))
12350 (if (and files (car files))
12351 files
12352 (org-agenda-files))))))))
12354 (defun org-make-tags-matcher (match)
12355 "Create the TAGS//TODO matcher form for the selection string MATCH."
12356 ;; todo-only is scoped dynamically into this function, and the function
12357 ;; may change it if the matcher asks for it.
12358 (unless match
12359 ;; Get a new match request, with completion
12360 (let ((org-last-tags-completion-table
12361 (org-global-tags-completion-table)))
12362 (setq match (org-completing-read-no-i
12363 "Match: " 'org-tags-completion-function nil nil nil
12364 'org-tags-history))))
12366 ;; Parse the string and create a lisp form
12367 (let ((match0 match)
12368 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
12369 minus tag mm
12370 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
12371 orterms term orlist re-p str-p level-p level-op time-p
12372 prop-p pn pv po cat-p gv rest)
12373 (if (string-match "/+" match)
12374 ;; match contains also a todo-matching request
12375 (progn
12376 (setq tagsmatch (substring match 0 (match-beginning 0))
12377 todomatch (substring match (match-end 0)))
12378 (if (string-match "^!" todomatch)
12379 (setq todo-only t todomatch (substring todomatch 1)))
12380 (if (string-match "^\\s-*$" todomatch)
12381 (setq todomatch nil)))
12382 ;; only matching tags
12383 (setq tagsmatch match todomatch nil))
12385 ;; Make the tags matcher
12386 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
12387 (setq tagsmatcher t)
12388 (setq orterms (org-split-string tagsmatch "|") orlist nil)
12389 (while (setq term (pop orterms))
12390 (while (and (equal (substring term -1) "\\") orterms)
12391 (setq term (concat term "|" (pop orterms)))) ; repair bad split
12392 (while (string-match re term)
12393 (setq rest (substring term (match-end 0))
12394 minus (and (match-end 1)
12395 (equal (match-string 1 term) "-"))
12396 tag (match-string 2 term)
12397 re-p (equal (string-to-char tag) ?{)
12398 level-p (match-end 4)
12399 prop-p (match-end 5)
12400 mm (cond
12401 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
12402 (level-p
12403 (setq level-op (org-op-to-function (match-string 3 term)))
12404 `(,level-op level ,(string-to-number
12405 (match-string 4 term))))
12406 (prop-p
12407 (setq pn (match-string 5 term)
12408 po (match-string 6 term)
12409 pv (match-string 7 term)
12410 cat-p (equal pn "CATEGORY")
12411 re-p (equal (string-to-char pv) ?{)
12412 str-p (equal (string-to-char pv) ?\")
12413 time-p (save-match-data
12414 (string-match "^\"[[<].*[]>]\"$" pv))
12415 pv (if (or re-p str-p) (substring pv 1 -1) pv))
12416 (if time-p (setq pv (org-matcher-time pv)))
12417 (setq po (org-op-to-function po (if time-p 'time str-p)))
12418 (cond
12419 ((equal pn "CATEGORY")
12420 (setq gv '(get-text-property (point) 'org-category)))
12421 ((equal pn "TODO")
12422 (setq gv 'todo))
12424 (setq gv `(org-cached-entry-get nil ,pn))))
12425 (if re-p
12426 (if (eq po 'org<>)
12427 `(not (string-match ,pv (or ,gv "")))
12428 `(string-match ,pv (or ,gv "")))
12429 (if str-p
12430 `(,po (or ,gv "") ,pv)
12431 `(,po (string-to-number (or ,gv ""))
12432 ,(string-to-number pv) ))))
12433 (t `(member ,tag tags-list)))
12434 mm (if minus (list 'not mm) mm)
12435 term rest)
12436 (push mm tagsmatcher))
12437 (push (if (> (length tagsmatcher) 1)
12438 (cons 'and tagsmatcher)
12439 (car tagsmatcher))
12440 orlist)
12441 (setq tagsmatcher nil))
12442 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
12443 (setq tagsmatcher
12444 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
12445 ;; Make the todo matcher
12446 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
12447 (setq todomatcher t)
12448 (setq orterms (org-split-string todomatch "|") orlist nil)
12449 (while (setq term (pop orterms))
12450 (while (string-match re term)
12451 (setq minus (and (match-end 1)
12452 (equal (match-string 1 term) "-"))
12453 kwd (match-string 2 term)
12454 re-p (equal (string-to-char kwd) ?{)
12455 term (substring term (match-end 0))
12456 mm (if re-p
12457 `(string-match ,(substring kwd 1 -1) todo)
12458 (list 'equal 'todo kwd))
12459 mm (if minus (list 'not mm) mm))
12460 (push mm todomatcher))
12461 (push (if (> (length todomatcher) 1)
12462 (cons 'and todomatcher)
12463 (car todomatcher))
12464 orlist)
12465 (setq todomatcher nil))
12466 (setq todomatcher (if (> (length orlist) 1)
12467 (cons 'or orlist) (car orlist))))
12469 ;; Return the string and lisp forms of the matcher
12470 (setq matcher (if todomatcher
12471 (list 'and tagsmatcher todomatcher)
12472 tagsmatcher))
12473 (cons match0 matcher)))
12475 (defun org-op-to-function (op &optional stringp)
12476 "Turn an operator into the appropriate function."
12477 (setq op
12478 (cond
12479 ((equal op "<" ) '(< string< org-time<))
12480 ((equal op ">" ) '(> org-string> org-time>))
12481 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
12482 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
12483 ((member op '("=" "==")) '(= string= org-time=))
12484 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
12485 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
12487 (defun org<> (a b) (not (= a b)))
12488 (defun org-string<= (a b) (or (string= a b) (string< a b)))
12489 (defun org-string>= (a b) (not (string< a b)))
12490 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
12491 (defun org-string<> (a b) (not (string= a b)))
12492 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
12493 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
12494 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
12495 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
12496 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
12497 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
12498 (defun org-2ft (s)
12499 "Convert S to a floating point time.
12500 If S is already a number, just return it. If it is a string, parse
12501 it as a time string and apply `float-time' to it. If S is nil, just return 0."
12502 (cond
12503 ((numberp s) s)
12504 ((stringp s)
12505 (condition-case nil
12506 (float-time (apply 'encode-time (org-parse-time-string s)))
12507 (error 0.)))
12508 (t 0.)))
12510 (defun org-time-today ()
12511 "Time in seconds today at 0:00.
12512 Returns the float number of seconds since the beginning of the
12513 epoch to the beginning of today (00:00)."
12514 (float-time (apply 'encode-time
12515 (append '(0 0 0) (nthcdr 3 (decode-time))))))
12517 (defun org-matcher-time (s)
12518 "Interpret a time comparison value."
12519 (save-match-data
12520 (cond
12521 ((string= s "<now>") (float-time))
12522 ((string= s "<today>") (org-time-today))
12523 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
12524 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
12525 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
12526 (+ (org-time-today)
12527 (* (string-to-number (match-string 1 s))
12528 (cdr (assoc (match-string 2 s)
12529 '(("d" . 86400.0) ("w" . 604800.0)
12530 ("m" . 2678400.0) ("y" . 31557600.0)))))))
12531 (t (org-2ft s)))))
12533 (defun org-match-any-p (re list)
12534 "Does re match any element of list?"
12535 (setq list (mapcar (lambda (x) (string-match re x)) list))
12536 (delq nil list))
12538 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
12539 (defvar org-tags-overlay (make-overlay 1 1))
12540 (org-detach-overlay org-tags-overlay)
12542 (defun org-get-local-tags-at (&optional pos)
12543 "Get a list of tags defined in the current headline."
12544 (org-get-tags-at pos 'local))
12546 (defun org-get-local-tags ()
12547 "Get a list of tags defined in the current headline."
12548 (org-get-tags-at nil 'local))
12550 (defun org-get-tags-at (&optional pos local)
12551 "Get a list of all headline tags applicable at POS.
12552 POS defaults to point. If tags are inherited, the list contains
12553 the targets in the same sequence as the headlines appear, i.e.
12554 the tags of the current headline come last.
12555 When LOCAL is non-nil, only return tags from the current headline,
12556 ignore inherited ones."
12557 (interactive)
12558 (if (and org-trust-scanner-tags
12559 (or (not pos) (equal pos (point)))
12560 (not local))
12561 org-scanner-tags
12562 (let (tags ltags lastpos parent)
12563 (save-excursion
12564 (save-restriction
12565 (widen)
12566 (goto-char (or pos (point)))
12567 (save-match-data
12568 (catch 'done
12569 (condition-case nil
12570 (progn
12571 (org-back-to-heading t)
12572 (while (not (equal lastpos (point)))
12573 (setq lastpos (point))
12574 (when (looking-at
12575 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
12576 (setq ltags (org-split-string
12577 (org-match-string-no-properties 1) ":"))
12578 (when parent
12579 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
12580 (setq tags (append
12581 (if parent
12582 (org-remove-uniherited-tags ltags)
12583 ltags)
12584 tags)))
12585 (or org-use-tag-inheritance (throw 'done t))
12586 (if local (throw 'done t))
12587 (or (org-up-heading-safe) (error nil))
12588 (setq parent t)))
12589 (error nil)))))
12590 (append (org-remove-uniherited-tags org-file-tags) tags)))))
12592 (defun org-add-prop-inherited (s)
12593 (add-text-properties 0 (length s) '(inherited t) s)
12596 (defun org-toggle-tag (tag &optional onoff)
12597 "Toggle the tag TAG for the current line.
12598 If ONOFF is `on' or `off', don't toggle but set to this state."
12599 (let (res current)
12600 (save-excursion
12601 (org-back-to-heading t)
12602 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
12603 (point-at-eol) t)
12604 (progn
12605 (setq current (match-string 1))
12606 (replace-match ""))
12607 (setq current ""))
12608 (setq current (nreverse (org-split-string current ":")))
12609 (cond
12610 ((eq onoff 'on)
12611 (setq res t)
12612 (or (member tag current) (push tag current)))
12613 ((eq onoff 'off)
12614 (or (not (member tag current)) (setq current (delete tag current))))
12615 (t (if (member tag current)
12616 (setq current (delete tag current))
12617 (setq res t)
12618 (push tag current))))
12619 (end-of-line 1)
12620 (if current
12621 (progn
12622 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
12623 (org-set-tags nil t))
12624 (delete-horizontal-space))
12625 (run-hooks 'org-after-tags-change-hook))
12626 res))
12628 (defun org-align-tags-here (to-col)
12629 ;; Assumes that this is a headline
12630 (let ((pos (point)) (col (current-column)) ncol tags-l p)
12631 (beginning-of-line 1)
12632 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12633 (< pos (match-beginning 2)))
12634 (progn
12635 (setq tags-l (- (match-end 2) (match-beginning 2)))
12636 (goto-char (match-beginning 1))
12637 (insert " ")
12638 (delete-region (point) (1+ (match-beginning 2)))
12639 (setq ncol (max (1+ (current-column))
12640 (1+ col)
12641 (if (> to-col 0)
12642 to-col
12643 (- (abs to-col) tags-l))))
12644 (setq p (point))
12645 (insert (make-string (- ncol (current-column)) ?\ ))
12646 (setq ncol (current-column))
12647 (when indent-tabs-mode (tabify p (point-at-eol)))
12648 (org-move-to-column (min ncol col) t))
12649 (goto-char pos))))
12651 (defun org-set-tags-command (&optional arg just-align)
12652 "Call the set-tags command for the current entry."
12653 (interactive "P")
12654 (if (org-on-heading-p)
12655 (org-set-tags arg just-align)
12656 (save-excursion
12657 (org-back-to-heading t)
12658 (org-set-tags arg just-align))))
12660 (defun org-set-tags-to (data)
12661 "Set the tags of the current entry to DATA, replacing the current tags.
12662 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
12663 If DATA is nil or the empty string, any tags will be removed."
12664 (interactive "sTags: ")
12665 (setq data
12666 (cond
12667 ((eq data nil) "")
12668 ((equal data "") "")
12669 ((stringp data)
12670 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
12671 ":"))
12672 ((listp data)
12673 (concat ":" (mapconcat 'identity data ":") ":"))
12674 (t nil)))
12675 (when data
12676 (save-excursion
12677 (org-back-to-heading t)
12678 (when (looking-at org-complex-heading-regexp)
12679 (if (match-end 5)
12680 (progn
12681 (goto-char (match-beginning 5))
12682 (insert data)
12683 (delete-region (point) (point-at-eol))
12684 (org-set-tags nil 'align))
12685 (goto-char (point-at-eol))
12686 (insert " " data)
12687 (org-set-tags nil 'align)))
12688 (beginning-of-line 1)
12689 (if (looking-at ".*?\\([ \t]+\\)$")
12690 (delete-region (match-beginning 1) (match-end 1))))))
12692 (defun org-align-all-tags ()
12693 "Align the tags i all headings."
12694 (interactive)
12695 (save-excursion
12696 (or (ignore-errors (org-back-to-heading t))
12697 (outline-next-heading))
12698 (if (org-on-heading-p)
12699 (org-set-tags t)
12700 (message "No headings"))))
12702 (defun org-set-tags (&optional arg just-align)
12703 "Set the tags for the current headline.
12704 With prefix ARG, realign all tags in headings in the current buffer."
12705 (interactive "P")
12706 (let* ((re (concat "^" outline-regexp))
12707 (current (org-get-tags-string))
12708 (col (current-column))
12709 (org-setting-tags t)
12710 table current-tags inherited-tags ; computed below when needed
12711 tags p0 c0 c1 rpl)
12712 (if arg
12713 (save-excursion
12714 (goto-char (point-min))
12715 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
12716 (while (re-search-forward re nil t)
12717 (org-set-tags nil t)
12718 (end-of-line 1)))
12719 (message "All tags realigned to column %d" org-tags-column))
12720 (if just-align
12721 (setq tags current)
12722 ;; Get a new set of tags from the user
12723 (save-excursion
12724 (setq table (append org-tag-persistent-alist
12725 (or org-tag-alist (org-get-buffer-tags))
12726 (and org-complete-tags-always-offer-all-agenda-tags
12727 (org-global-tags-completion-table (org-agenda-files))))
12728 org-last-tags-completion-table table
12729 current-tags (org-split-string current ":")
12730 inherited-tags (nreverse
12731 (nthcdr (length current-tags)
12732 (nreverse (org-get-tags-at))))
12733 tags
12734 (if (or (eq t org-use-fast-tag-selection)
12735 (and org-use-fast-tag-selection
12736 (delq nil (mapcar 'cdr table))))
12737 (org-fast-tag-selection
12738 current-tags inherited-tags table
12739 (if org-fast-tag-selection-include-todo org-todo-key-alist))
12740 (let ((org-add-colon-after-tag-completion t))
12741 (org-trim
12742 (org-without-partial-completion
12743 (org-icompleting-read "Tags: " 'org-tags-completion-function
12744 nil nil current 'org-tags-history)))))))
12745 (while (string-match "[-+&]+" tags)
12746 ;; No boolean logic, just a list
12747 (setq tags (replace-match ":" t t tags))))
12749 (if org-tags-sort-function
12750 (setq tags (mapconcat 'identity
12751 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
12752 org-tags-sort-function) ":")))
12754 (if (string-match "\\`[\t ]*\\'" tags)
12755 (setq tags "")
12756 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
12757 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
12759 ;; Insert new tags at the correct column
12760 (beginning-of-line 1)
12761 (cond
12762 ((and (equal current "") (equal tags "")))
12763 ((re-search-forward
12764 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
12765 (point-at-eol) t)
12766 (if (equal tags "")
12767 (setq rpl "")
12768 (goto-char (match-beginning 0))
12769 (setq c0 (current-column) p0 (if (equal (char-before) ?*)
12770 (1+ (point)) (point))
12771 c1 (max (1+ c0) (if (> org-tags-column 0)
12772 org-tags-column
12773 (- (- org-tags-column) (length tags))))
12774 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
12775 (replace-match rpl t t)
12776 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
12777 tags)
12778 (t (error "Tags alignment failed")))
12779 (org-move-to-column col)
12780 (unless just-align
12781 (run-hooks 'org-after-tags-change-hook)))))
12783 (defun org-change-tag-in-region (beg end tag off)
12784 "Add or remove TAG for each entry in the region.
12785 This works in the agenda, and also in an org-mode buffer."
12786 (interactive
12787 (list (region-beginning) (region-end)
12788 (let ((org-last-tags-completion-table
12789 (if (org-mode-p)
12790 (org-get-buffer-tags)
12791 (org-global-tags-completion-table))))
12792 (org-icompleting-read
12793 "Tag: " 'org-tags-completion-function nil nil nil
12794 'org-tags-history))
12795 (progn
12796 (message "[s]et or [r]emove? ")
12797 (equal (read-char-exclusive) ?r))))
12798 (if (fboundp 'deactivate-mark) (deactivate-mark))
12799 (let ((agendap (equal major-mode 'org-agenda-mode))
12800 l1 l2 m buf pos newhead (cnt 0))
12801 (goto-char end)
12802 (setq l2 (1- (org-current-line)))
12803 (goto-char beg)
12804 (setq l1 (org-current-line))
12805 (loop for l from l1 to l2 do
12806 (org-goto-line l)
12807 (setq m (get-text-property (point) 'org-hd-marker))
12808 (when (or (and (org-mode-p) (org-on-heading-p))
12809 (and agendap m))
12810 (setq buf (if agendap (marker-buffer m) (current-buffer))
12811 pos (if agendap m (point)))
12812 (with-current-buffer buf
12813 (save-excursion
12814 (save-restriction
12815 (goto-char pos)
12816 (setq cnt (1+ cnt))
12817 (org-toggle-tag tag (if off 'off 'on))
12818 (setq newhead (org-get-heading)))))
12819 (and agendap (org-agenda-change-all-lines newhead m))))
12820 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
12822 (defun org-tags-completion-function (string predicate &optional flag)
12823 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
12824 (confirm (lambda (x) (stringp (car x)))))
12825 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
12826 (setq s1 (match-string 1 string)
12827 s2 (match-string 2 string))
12828 (setq s1 "" s2 string))
12829 (cond
12830 ((eq flag nil)
12831 ;; try completion
12832 (setq rtn (try-completion s2 ctable confirm))
12833 (if (stringp rtn)
12834 (setq rtn
12835 (concat s1 s2 (substring rtn (length s2))
12836 (if (and org-add-colon-after-tag-completion
12837 (assoc rtn ctable))
12838 ":" ""))))
12839 rtn)
12840 ((eq flag t)
12841 ;; all-completions
12842 (all-completions s2 ctable confirm)
12844 ((eq flag 'lambda)
12845 ;; exact match?
12846 (assoc s2 ctable)))
12849 (defun org-fast-tag-insert (kwd tags face &optional end)
12850 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
12851 (insert (format "%-12s" (concat kwd ":"))
12852 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
12853 (or end "")))
12855 (defun org-fast-tag-show-exit (flag)
12856 (save-excursion
12857 (org-goto-line 3)
12858 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
12859 (replace-match ""))
12860 (when flag
12861 (end-of-line 1)
12862 (org-move-to-column (- (window-width) 19) t)
12863 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
12865 (defun org-set-current-tags-overlay (current prefix)
12866 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
12867 (if (featurep 'xemacs)
12868 (org-overlay-display org-tags-overlay (concat prefix s)
12869 'secondary-selection)
12870 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
12871 (org-overlay-display org-tags-overlay (concat prefix s)))))
12873 (defvar org-last-tag-selection-key nil)
12874 (defun org-fast-tag-selection (current inherited table &optional todo-table)
12875 "Fast tag selection with single keys.
12876 CURRENT is the current list of tags in the headline, INHERITED is the
12877 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
12878 possibly with grouping information. TODO-TABLE is a similar table with
12879 TODO keywords, should these have keys assigned to them.
12880 If the keys are nil, a-z are automatically assigned.
12881 Returns the new tags string, or nil to not change the current settings."
12882 (let* ((fulltable (append table todo-table))
12883 (maxlen (apply 'max (mapcar
12884 (lambda (x)
12885 (if (stringp (car x)) (string-width (car x)) 0))
12886 fulltable)))
12887 (buf (current-buffer))
12888 (expert (eq org-fast-tag-selection-single-key 'expert))
12889 (buffer-tags nil)
12890 (fwidth (+ maxlen 3 1 3))
12891 (ncol (/ (- (window-width) 4) fwidth))
12892 (i-face 'org-done)
12893 (c-face 'org-todo)
12894 tg cnt e c char c1 c2 ntable tbl rtn
12895 ov-start ov-end ov-prefix
12896 (exit-after-next org-fast-tag-selection-single-key)
12897 (done-keywords org-done-keywords)
12898 groups ingroup)
12899 (save-excursion
12900 (beginning-of-line 1)
12901 (if (looking-at
12902 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12903 (setq ov-start (match-beginning 1)
12904 ov-end (match-end 1)
12905 ov-prefix "")
12906 (setq ov-start (1- (point-at-eol))
12907 ov-end (1+ ov-start))
12908 (skip-chars-forward "^\n\r")
12909 (setq ov-prefix
12910 (concat
12911 (buffer-substring (1- (point)) (point))
12912 (if (> (current-column) org-tags-column)
12914 (make-string (- org-tags-column (current-column)) ?\ ))))))
12915 (move-overlay org-tags-overlay ov-start ov-end)
12916 (save-window-excursion
12917 (if expert
12918 (set-buffer (get-buffer-create " *Org tags*"))
12919 (delete-other-windows)
12920 (split-window-vertically)
12921 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
12922 (erase-buffer)
12923 (org-set-local 'org-done-keywords done-keywords)
12924 (org-fast-tag-insert "Inherited" inherited i-face "\n")
12925 (org-fast-tag-insert "Current" current c-face "\n\n")
12926 (org-fast-tag-show-exit exit-after-next)
12927 (org-set-current-tags-overlay current ov-prefix)
12928 (setq tbl fulltable char ?a cnt 0)
12929 (while (setq e (pop tbl))
12930 (cond
12931 ((equal (car e) :startgroup)
12932 (push '() groups) (setq ingroup t)
12933 (when (not (= cnt 0))
12934 (setq cnt 0)
12935 (insert "\n"))
12936 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
12937 ((equal (car e) :endgroup)
12938 (setq ingroup nil cnt 0)
12939 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
12940 ((equal e '(:newline))
12941 (when (not (= cnt 0))
12942 (setq cnt 0)
12943 (insert "\n")
12944 (setq e (car tbl))
12945 (while (equal (car tbl) '(:newline))
12946 (insert "\n")
12947 (setq tbl (cdr tbl)))))
12949 (setq tg (copy-sequence (car e)) c2 nil)
12950 (if (cdr e)
12951 (setq c (cdr e))
12952 ;; automatically assign a character.
12953 (setq c1 (string-to-char
12954 (downcase (substring
12955 tg (if (= (string-to-char tg) ?@) 1 0)))))
12956 (if (or (rassoc c1 ntable) (rassoc c1 table))
12957 (while (or (rassoc char ntable) (rassoc char table))
12958 (setq char (1+ char)))
12959 (setq c2 c1))
12960 (setq c (or c2 char)))
12961 (if ingroup (push tg (car groups)))
12962 (setq tg (org-add-props tg nil 'face
12963 (cond
12964 ((not (assoc tg table))
12965 (org-get-todo-face tg))
12966 ((member tg current) c-face)
12967 ((member tg inherited) i-face)
12968 (t nil))))
12969 (if (and (= cnt 0) (not ingroup)) (insert " "))
12970 (insert "[" c "] " tg (make-string
12971 (- fwidth 4 (length tg)) ?\ ))
12972 (push (cons tg c) ntable)
12973 (when (= (setq cnt (1+ cnt)) ncol)
12974 (insert "\n")
12975 (if ingroup (insert " "))
12976 (setq cnt 0)))))
12977 (setq ntable (nreverse ntable))
12978 (insert "\n")
12979 (goto-char (point-min))
12980 (if (not expert) (org-fit-window-to-buffer))
12981 (setq rtn
12982 (catch 'exit
12983 (while t
12984 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
12985 (if (not groups) "no " "")
12986 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
12987 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12988 (setq org-last-tag-selection-key c)
12989 (cond
12990 ((= c ?\r) (throw 'exit t))
12991 ((= c ?!)
12992 (setq groups (not groups))
12993 (goto-char (point-min))
12994 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
12995 ((= c ?\C-c)
12996 (if (not expert)
12997 (org-fast-tag-show-exit
12998 (setq exit-after-next (not exit-after-next)))
12999 (setq expert nil)
13000 (delete-other-windows)
13001 (split-window-vertically)
13002 (org-switch-to-buffer-other-window " *Org tags*")
13003 (org-fit-window-to-buffer)))
13004 ((or (= c ?\C-g)
13005 (and (= c ?q) (not (rassoc c ntable))))
13006 (org-detach-overlay org-tags-overlay)
13007 (setq quit-flag t))
13008 ((= c ?\ )
13009 (setq current nil)
13010 (if exit-after-next (setq exit-after-next 'now)))
13011 ((= c ?\t)
13012 (condition-case nil
13013 (setq tg (org-icompleting-read
13014 "Tag: "
13015 (or buffer-tags
13016 (with-current-buffer buf
13017 (org-get-buffer-tags)))))
13018 (quit (setq tg "")))
13019 (when (string-match "\\S-" tg)
13020 (add-to-list 'buffer-tags (list tg))
13021 (if (member tg current)
13022 (setq current (delete tg current))
13023 (push tg current)))
13024 (if exit-after-next (setq exit-after-next 'now)))
13025 ((setq e (rassoc c todo-table) tg (car e))
13026 (with-current-buffer buf
13027 (save-excursion (org-todo tg)))
13028 (if exit-after-next (setq exit-after-next 'now)))
13029 ((setq e (rassoc c ntable) tg (car e))
13030 (if (member tg current)
13031 (setq current (delete tg current))
13032 (loop for g in groups do
13033 (if (member tg g)
13034 (mapc (lambda (x)
13035 (setq current (delete x current)))
13036 g)))
13037 (push tg current))
13038 (if exit-after-next (setq exit-after-next 'now))))
13040 ;; Create a sorted list
13041 (setq current
13042 (sort current
13043 (lambda (a b)
13044 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13045 (if (eq exit-after-next 'now) (throw 'exit t))
13046 (goto-char (point-min))
13047 (beginning-of-line 2)
13048 (delete-region (point) (point-at-eol))
13049 (org-fast-tag-insert "Current" current c-face)
13050 (org-set-current-tags-overlay current ov-prefix)
13051 (while (re-search-forward
13052 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
13053 (setq tg (match-string 1))
13054 (add-text-properties
13055 (match-beginning 1) (match-end 1)
13056 (list 'face
13057 (cond
13058 ((member tg current) c-face)
13059 ((member tg inherited) i-face)
13060 (t (get-text-property (match-beginning 1) 'face))))))
13061 (goto-char (point-min)))))
13062 (org-detach-overlay org-tags-overlay)
13063 (if rtn
13064 (mapconcat 'identity current ":")
13065 nil))))
13067 (defun org-get-tags-string ()
13068 "Get the TAGS string in the current headline."
13069 (unless (org-on-heading-p t)
13070 (error "Not on a heading"))
13071 (save-excursion
13072 (beginning-of-line 1)
13073 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13074 (org-match-string-no-properties 1)
13075 "")))
13077 (defun org-get-tags ()
13078 "Get the list of tags specified in the current headline."
13079 (org-split-string (org-get-tags-string) ":"))
13081 (defun org-get-buffer-tags ()
13082 "Get a table of all tags used in the buffer, for completion."
13083 (let (tags)
13084 (save-excursion
13085 (goto-char (point-min))
13086 (while (re-search-forward
13087 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
13088 (when (equal (char-after (point-at-bol 0)) ?*)
13089 (mapc (lambda (x) (add-to-list 'tags x))
13090 (org-split-string (org-match-string-no-properties 1) ":")))))
13091 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13092 (mapcar 'list tags)))
13094 ;;;; The mapping API
13096 ;;;###autoload
13097 (defun org-map-entries (func &optional match scope &rest skip)
13098 "Call FUNC at each headline selected by MATCH in SCOPE.
13100 FUNC is a function or a lisp form. The function will be called without
13101 arguments, with the cursor positioned at the beginning of the headline.
13102 The return values of all calls to the function will be collected and
13103 returned as a list.
13105 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13106 does not need to preserve point. After evaluation, the cursor will be
13107 moved to the end of the line (presumably of the headline of the
13108 processed entry) and search continues from there. Under some
13109 circumstances, this may not produce the wanted results. For example,
13110 if you have removed (e.g. archived) the current (sub)tree it could
13111 mean that the next entry will be skipped entirely. In such cases, you
13112 can specify the position from where search should continue by making
13113 FUNC set the variable `org-map-continue-from' to the desired buffer
13114 position.
13116 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13117 Only headlines that are matched by this query will be considered during
13118 the iteration. When MATCH is nil or t, all headlines will be
13119 visited by the iteration.
13121 SCOPE determines the scope of this command. It can be any of:
13123 nil The current buffer, respecting the restriction if any
13124 tree The subtree started with the entry at point
13125 file The current buffer, without restriction
13126 file-with-archives
13127 The current buffer, and any archives associated with it
13128 agenda All agenda files
13129 agenda-with-archives
13130 All agenda files with any archive files associated with them
13131 \(file1 file2 ...)
13132 If this is a list, all files in the list will be scanned
13134 The remaining args are treated as settings for the skipping facilities of
13135 the scanner. The following items can be given here:
13137 archive skip trees with the archive tag.
13138 comment skip trees with the COMMENT keyword
13139 function or Emacs Lisp form:
13140 will be used as value for `org-agenda-skip-function', so whenever
13141 the function returns t, FUNC will not be called for that
13142 entry and search will continue from the point where the
13143 function leaves it.
13145 If your function needs to retrieve the tags including inherited tags
13146 at the *current* entry, you can use the value of the variable
13147 `org-scanner-tags' which will be much faster than getting the value
13148 with `org-get-tags-at'. If your function gets properties with
13149 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13150 to t around the call to `org-entry-properties' to get the same speedup.
13151 Note that if your function moves around to retrieve tags and properties at
13152 a *different* entry, you cannot use these techniques."
13153 (let* ((org-agenda-archives-mode nil) ; just to make sure
13154 (org-agenda-skip-archived-trees (memq 'archive skip))
13155 (org-agenda-skip-comment-trees (memq 'comment skip))
13156 (org-agenda-skip-function
13157 (car (org-delete-all '(comment archive) skip)))
13158 (org-tags-match-list-sublevels t)
13159 matcher file res
13160 org-todo-keywords-for-agenda
13161 org-done-keywords-for-agenda
13162 org-todo-keyword-alist-for-agenda
13163 org-drawers-for-agenda
13164 org-tag-alist-for-agenda)
13166 (cond
13167 ((eq match t) (setq matcher t))
13168 ((eq match nil) (setq matcher t))
13169 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13171 (save-excursion
13172 (save-restriction
13173 (when (eq scope 'tree)
13174 (org-back-to-heading t)
13175 (org-narrow-to-subtree)
13176 (setq scope nil))
13178 (if (not scope)
13179 (progn
13180 (org-prepare-agenda-buffers
13181 (list (buffer-file-name (current-buffer))))
13182 (setq res (org-scan-tags func matcher)))
13183 ;; Get the right scope
13184 (cond
13185 ((and scope (listp scope) (symbolp (car scope)))
13186 (setq scope (eval scope)))
13187 ((eq scope 'agenda)
13188 (setq scope (org-agenda-files t)))
13189 ((eq scope 'agenda-with-archives)
13190 (setq scope (org-agenda-files t))
13191 (setq scope (org-add-archive-files scope)))
13192 ((eq scope 'file)
13193 (setq scope (list (buffer-file-name))))
13194 ((eq scope 'file-with-archives)
13195 (setq scope (org-add-archive-files (list (buffer-file-name))))))
13196 (org-prepare-agenda-buffers scope)
13197 (while (setq file (pop scope))
13198 (with-current-buffer (org-find-base-buffer-visiting file)
13199 (save-excursion
13200 (save-restriction
13201 (widen)
13202 (goto-char (point-min))
13203 (setq res (append res (org-scan-tags func matcher))))))))))
13204 res))
13206 ;;;; Properties
13208 ;;; Setting and retrieving properties
13210 (defconst org-special-properties
13211 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
13212 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED")
13213 "The special properties valid in Org-mode.
13215 These are properties that are not defined in the property drawer,
13216 but in some other way.")
13218 (defconst org-default-properties
13219 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
13220 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
13221 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
13222 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
13223 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
13224 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
13225 "Some properties that are used by Org-mode for various purposes.
13226 Being in this list makes sure that they are offered for completion.")
13228 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
13229 "Regular expression matching the first line of a property drawer.")
13231 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
13232 "Regular expression matching the last line of a property drawer.")
13234 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
13235 "Regular expression matching the first line of a property drawer.")
13237 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
13238 "Regular expression matching the first line of a property drawer.")
13240 (defconst org-property-drawer-re
13241 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
13242 org-property-end-re "\\)\n?")
13243 "Matches an entire property drawer.")
13245 (defconst org-clock-drawer-re
13246 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
13247 org-property-end-re "\\)\n?")
13248 "Matches an entire clock drawer.")
13250 (defun org-property-action ()
13251 "Do an action on properties."
13252 (interactive)
13253 (let (c)
13254 (org-at-property-p)
13255 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
13256 (setq c (read-char-exclusive))
13257 (cond
13258 ((equal c ?s)
13259 (call-interactively 'org-set-property))
13260 ((equal c ?d)
13261 (call-interactively 'org-delete-property))
13262 ((equal c ?D)
13263 (call-interactively 'org-delete-property-globally))
13264 ((equal c ?c)
13265 (call-interactively 'org-compute-property-at-point))
13266 (t (error "No such property action %c" c)))))
13268 (defun org-set-effort (&optional value)
13269 "Set the effort property of the current entry.
13270 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
13271 allowed value."
13272 (interactive "P")
13273 (if (equal value 0) (setq value 10))
13274 (let* ((completion-ignore-case t)
13275 (prop org-effort-property)
13276 (cur (org-entry-get nil prop))
13277 (allowed (org-property-get-allowed-values nil prop 'table))
13278 (existing (mapcar 'list (org-property-values prop)))
13280 (val (cond
13281 ((stringp value) value)
13282 ((and allowed (integerp value))
13283 (or (car (nth (1- value) allowed))
13284 (car (org-last allowed))))
13285 (allowed
13286 (message "Select 1-9,0, [RET%s]: %s"
13287 (if cur (concat "=" cur) "")
13288 (mapconcat 'car allowed " "))
13289 (setq rpl (read-char-exclusive))
13290 (if (equal rpl ?\r)
13292 (setq rpl (- rpl ?0))
13293 (if (equal rpl 0) (setq rpl 10))
13294 (if (and (> rpl 0) (<= rpl (length allowed)))
13295 (car (nth (1- rpl) allowed))
13296 (org-completing-read "Effort: " allowed nil))))
13298 (let (org-completion-use-ido org-completion-use-iswitchb)
13299 (org-completing-read
13300 (concat "Effort " (if (and cur (string-match "\\S-" cur))
13301 (concat "[" cur "]") "")
13302 ": ")
13303 existing nil nil "" nil cur))))))
13304 (unless (equal (org-entry-get nil prop) val)
13305 (org-entry-put nil prop val))
13306 (message "%s is now %s" prop val)))
13308 (defun org-at-property-p ()
13309 "Is cursor inside a property drawer?"
13310 (save-excursion
13311 (beginning-of-line 1)
13312 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
13313 (save-match-data ;; Used by calling procedures
13314 (let ((p (point))
13315 (range (unless (org-before-first-heading-p)
13316 (org-get-property-block))))
13317 (and range (<= (car range) p) (< p (cdr range))))))))
13319 (defun org-get-property-block (&optional beg end force)
13320 "Return the (beg . end) range of the body of the property drawer.
13321 BEG and END can be beginning and end of subtree, if not given
13322 they will be found.
13323 If the drawer does not exist and FORCE is non-nil, create the drawer."
13324 (catch 'exit
13325 (save-excursion
13326 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
13327 (end (or end (progn (outline-next-heading) (point)))))
13328 (goto-char beg)
13329 (if (re-search-forward org-property-start-re end t)
13330 (setq beg (1+ (match-end 0)))
13331 (if force
13332 (save-excursion
13333 (org-insert-property-drawer)
13334 (setq end (progn (outline-next-heading) (point))))
13335 (throw 'exit nil))
13336 (goto-char beg)
13337 (if (re-search-forward org-property-start-re end t)
13338 (setq beg (1+ (match-end 0)))))
13339 (if (re-search-forward org-property-end-re end t)
13340 (setq end (match-beginning 0))
13341 (or force (throw 'exit nil))
13342 (goto-char beg)
13343 (setq end beg)
13344 (org-indent-line-function)
13345 (insert ":END:\n"))
13346 (cons beg end)))))
13348 (defun org-entry-properties (&optional pom which specific)
13349 "Get all properties of the entry at point-or-marker POM.
13350 This includes the TODO keyword, the tags, time strings for deadline,
13351 scheduled, and clocking, and any additional properties defined in the
13352 entry. The return value is an alist, keys may occur multiple times
13353 if the property key was used several times.
13354 POM may also be nil, in which case the current entry is used.
13355 If WHICH is nil or `all', get all properties. If WHICH is
13356 `special' or `standard', only get that subclass. If WHICH
13357 is a string only get exactly this property. Specific can be a string, the
13358 specific property we are interested in. Specifying it can speed
13359 things up because then unnecessary parsing is avoided."
13360 (setq which (or which 'all))
13361 (org-with-point-at pom
13362 (let ((clockstr (substring org-clock-string 0 -1))
13363 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
13364 (case-fold-search nil)
13365 beg end range props sum-props key key1 value string clocksum)
13366 (save-excursion
13367 (when (condition-case nil
13368 (and (org-mode-p) (org-back-to-heading t))
13369 (error nil))
13370 (setq beg (point))
13371 (setq sum-props (get-text-property (point) 'org-summaries))
13372 (setq clocksum (get-text-property (point) :org-clock-minutes))
13373 (outline-next-heading)
13374 (setq end (point))
13375 (when (memq which '(all special))
13376 ;; Get the special properties, like TODO and tags
13377 (goto-char beg)
13378 (when (and (or (not specific) (string= specific "TODO"))
13379 (looking-at org-todo-line-regexp) (match-end 2))
13380 (push (cons "TODO" (org-match-string-no-properties 2)) props))
13381 (when (and (or (not specific) (string= specific "PRIORITY"))
13382 (looking-at org-priority-regexp))
13383 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
13384 (when (and (or (not specific) (string= specific "TAGS"))
13385 (setq value (org-get-tags-string))
13386 (string-match "\\S-" value))
13387 (push (cons "TAGS" value) props))
13388 (when (and (or (not specific) (string= specific "ALLTAGS"))
13389 (setq value (org-get-tags-at)))
13390 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
13391 ":"))
13392 props))
13393 (when (or (not specific) (string= specific "BLOCKED"))
13394 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
13395 (when (or (not specific)
13396 (member specific
13397 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
13398 "TIMESTAMP" "TIMESTAMP_IA")))
13399 (while (re-search-forward org-maybe-keyword-time-regexp end t)
13400 (setq key (if (match-end 1)
13401 (substring (org-match-string-no-properties 1)
13402 0 -1))
13403 string (if (equal key clockstr)
13404 (org-no-properties
13405 (org-trim
13406 (buffer-substring
13407 (match-beginning 3) (goto-char
13408 (point-at-eol)))))
13409 (substring (org-match-string-no-properties 3)
13410 1 -1)))
13411 ;; Get the correct property name from the key. This is
13412 ;; necessary if the user has configured time keywords.
13413 (setq key1 (concat key ":"))
13414 (cond
13415 ((not key)
13416 (setq key
13417 (if (= (char-after (match-beginning 3)) ?\[)
13418 "TIMESTAMP_IA" "TIMESTAMP")))
13419 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
13420 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
13421 ((equal key1 org-closed-string) (setq key "CLOSED"))
13422 ((equal key1 org-clock-string) (setq key "CLOCK")))
13423 (when (or (equal key "CLOCK") (not (assoc key props)))
13424 (push (cons key string) props))))
13427 (when (memq which '(all standard))
13428 ;; Get the standard properties, like :PROP: ...
13429 (setq range (org-get-property-block beg end))
13430 (when range
13431 (goto-char (car range))
13432 (while (re-search-forward
13433 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
13434 (cdr range) t)
13435 (setq key (org-match-string-no-properties 1)
13436 value (org-trim (or (org-match-string-no-properties 2) "")))
13437 (unless (member key excluded)
13438 (push (cons key (or value "")) props)))))
13439 (if clocksum
13440 (push (cons "CLOCKSUM"
13441 (org-columns-number-to-string (/ (float clocksum) 60.)
13442 'add_times))
13443 props))
13444 (unless (assoc "CATEGORY" props)
13445 (setq value (or (org-get-category)
13446 (progn (org-refresh-category-properties)
13447 (org-get-category))))
13448 (push (cons "CATEGORY" value) props))
13449 (append sum-props (nreverse props)))))))
13451 (defun org-entry-get (pom property &optional inherit literal-nil)
13452 "Get value of PROPERTY for entry at point-or-marker POM.
13453 If INHERIT is non-nil and the entry does not have the property,
13454 then also check higher levels of the hierarchy.
13455 If INHERIT is the symbol `selective', use inheritance only if the setting
13456 in `org-use-property-inheritance' selects PROPERTY for inheritance.
13457 If the property is present but empty, the return value is the empty string.
13458 If the property is not present at all, nil is returned.
13460 If LITERAL-NIL is set, return the string value \"nil\" as a string,
13461 do not interpret it as the list atom nil. This is used for inheritance
13462 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
13463 (org-with-point-at pom
13464 (if (and inherit (if (eq inherit 'selective)
13465 (org-property-inherit-p property)
13467 (org-entry-get-with-inheritance property literal-nil)
13468 (if (member property org-special-properties)
13469 ;; We need a special property. Use `org-entry-properties' to
13470 ;; retrieve it, but specify the wanted property
13471 (cdr (assoc property (org-entry-properties nil 'special property)))
13472 (let ((range (org-get-property-block)))
13473 (if (and range
13474 (goto-char (car range))
13475 (re-search-forward
13476 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
13477 (cdr range) t))
13478 ;; Found the property, return it.
13479 (if (match-end 1)
13480 (if literal-nil
13481 (org-match-string-no-properties 1)
13482 (org-not-nil (org-match-string-no-properties 1)))
13483 "")))))))
13485 (defun org-property-or-variable-value (var &optional inherit)
13486 "Check if there is a property fixing the value of VAR.
13487 If yes, return this value. If not, return the current value of the variable."
13488 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
13489 (if (and prop (stringp prop) (string-match "\\S-" prop))
13490 (read prop)
13491 (symbol-value var))))
13493 (defun org-entry-delete (pom property)
13494 "Delete the property PROPERTY from entry at point-or-marker POM."
13495 (org-with-point-at pom
13496 (if (member property org-special-properties)
13497 nil ; cannot delete these properties.
13498 (let ((range (org-get-property-block)))
13499 (if (and range
13500 (goto-char (car range))
13501 (re-search-forward
13502 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
13503 (cdr range) t))
13504 (progn
13505 (delete-region (match-beginning 0) (1+ (point-at-eol)))
13507 nil)))))
13509 ;; Multi-values properties are properties that contain multiple values
13510 ;; These values are assumed to be single words, separated by whitespace.
13511 (defun org-entry-add-to-multivalued-property (pom property value)
13512 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
13513 (let* ((old (org-entry-get pom property))
13514 (values (and old (org-split-string old "[ \t]"))))
13515 (setq value (org-entry-protect-space value))
13516 (unless (member value values)
13517 (setq values (cons value values))
13518 (org-entry-put pom property
13519 (mapconcat 'identity values " ")))))
13521 (defun org-entry-remove-from-multivalued-property (pom property value)
13522 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
13523 (let* ((old (org-entry-get pom property))
13524 (values (and old (org-split-string old "[ \t]"))))
13525 (setq value (org-entry-protect-space value))
13526 (when (member value values)
13527 (setq values (delete value values))
13528 (org-entry-put pom property
13529 (mapconcat 'identity values " ")))))
13531 (defun org-entry-member-in-multivalued-property (pom property value)
13532 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
13533 (let* ((old (org-entry-get pom property))
13534 (values (and old (org-split-string old "[ \t]"))))
13535 (setq value (org-entry-protect-space value))
13536 (member value values)))
13538 (defun org-entry-get-multivalued-property (pom property)
13539 "Return a list of values in a multivalued property."
13540 (let* ((value (org-entry-get pom property))
13541 (values (and value (org-split-string value "[ \t]"))))
13542 (mapcar 'org-entry-restore-space values)))
13544 (defun org-entry-put-multivalued-property (pom property &rest values)
13545 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
13546 VALUES should be a list of strings. Spaces will be protected."
13547 (org-entry-put pom property
13548 (mapconcat 'org-entry-protect-space values " "))
13549 (let* ((value (org-entry-get pom property))
13550 (values (and value (org-split-string value "[ \t]"))))
13551 (mapcar 'org-entry-restore-space values)))
13553 (defun org-entry-protect-space (s)
13554 "Protect spaces and newline in string S."
13555 (while (string-match " " s)
13556 (setq s (replace-match "%20" t t s)))
13557 (while (string-match "\n" s)
13558 (setq s (replace-match "%0A" t t s)))
13561 (defun org-entry-restore-space (s)
13562 "Restore spaces and newline in string S."
13563 (while (string-match "%20" s)
13564 (setq s (replace-match " " t t s)))
13565 (while (string-match "%0A" s)
13566 (setq s (replace-match "\n" t t s)))
13569 (defvar org-entry-property-inherited-from (make-marker)
13570 "Marker pointing to the entry from where a property was inherited.
13571 Each call to `org-entry-get-with-inheritance' will set this marker to the
13572 location of the entry where the inheritance search matched. If there was
13573 no match, the marker will point nowhere.
13574 Note that also `org-entry-get' calls this function, if the INHERIT flag
13575 is set.")
13577 (defun org-entry-get-with-inheritance (property &optional literal-nil)
13578 "Get entry property, and search higher levels if not present.
13579 The search will stop at the first ancestor which has the property defined.
13580 If the value found is \"nil\", return nil to show that the property
13581 should be considered as undefined (this is the meaning of nil here).
13582 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
13583 (move-marker org-entry-property-inherited-from nil)
13584 (let (tmp)
13585 (save-excursion
13586 (save-restriction
13587 (widen)
13588 (catch 'ex
13589 (while t
13590 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
13591 (org-back-to-heading t)
13592 (move-marker org-entry-property-inherited-from (point))
13593 (throw 'ex tmp))
13594 (or (org-up-heading-safe) (throw 'ex nil)))))
13595 (setq tmp (or tmp
13596 (cdr (assoc property org-file-properties))
13597 (cdr (assoc property org-global-properties))
13598 (cdr (assoc property org-global-properties-fixed))))
13599 (if literal-nil tmp (org-not-nil tmp)))))
13601 (defvar org-property-changed-functions nil
13602 "Hook called when the value of a property has changed.
13603 Each hook function should accept two arguments, the name of the property
13604 and the new value.")
13606 (defun org-entry-put (pom property value)
13607 "Set PROPERTY to VALUE for entry at point-or-marker POM."
13608 (org-with-point-at pom
13609 (org-back-to-heading t)
13610 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
13611 range)
13612 (cond
13613 ((equal property "TODO")
13614 (when (and (stringp value) (string-match "\\S-" value)
13615 (not (member value org-todo-keywords-1)))
13616 (error "\"%s\" is not a valid TODO state" value))
13617 (if (or (not value)
13618 (not (string-match "\\S-" value)))
13619 (setq value 'none))
13620 (org-todo value)
13621 (org-set-tags nil 'align))
13622 ((equal property "PRIORITY")
13623 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
13624 (string-to-char value) ?\ ))
13625 (org-set-tags nil 'align))
13626 ((equal property "SCHEDULED")
13627 (if (re-search-forward org-scheduled-time-regexp end t)
13628 (cond
13629 ((eq value 'earlier) (org-timestamp-change -1 'day))
13630 ((eq value 'later) (org-timestamp-change 1 'day))
13631 (t (call-interactively 'org-schedule)))
13632 (call-interactively 'org-schedule)))
13633 ((equal property "DEADLINE")
13634 (if (re-search-forward org-deadline-time-regexp end t)
13635 (cond
13636 ((eq value 'earlier) (org-timestamp-change -1 'day))
13637 ((eq value 'later) (org-timestamp-change 1 'day))
13638 (t (call-interactively 'org-deadline)))
13639 (call-interactively 'org-deadline)))
13640 ((member property org-special-properties)
13641 (error "The %s property can not yet be set with `org-entry-put'"
13642 property))
13643 (t ; a non-special property
13644 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
13645 (setq range (org-get-property-block beg end 'force))
13646 (goto-char (car range))
13647 (if (re-search-forward
13648 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
13649 (progn
13650 (delete-region (match-beginning 1) (match-end 1))
13651 (goto-char (match-beginning 1)))
13652 (goto-char (cdr range))
13653 (insert "\n")
13654 (backward-char 1)
13655 (org-indent-line-function)
13656 (insert ":" property ":"))
13657 (and value (insert " " value))
13658 (org-indent-line-function)))))
13659 (run-hook-with-args 'org-property-changed-functions property value)))
13661 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
13662 "Get all property keys in the current buffer.
13663 With INCLUDE-SPECIALS, also list the special properties that reflect things
13664 like tags and TODO state.
13665 With INCLUDE-DEFAULTS, also include properties that has special meaning
13666 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
13667 With INCLUDE-COLUMNS, also include property names given in COLUMN
13668 formats in the current buffer."
13669 (let (rtn range cfmt s p)
13670 (save-excursion
13671 (save-restriction
13672 (widen)
13673 (goto-char (point-min))
13674 (while (re-search-forward org-property-start-re nil t)
13675 (setq range (org-get-property-block))
13676 (goto-char (car range))
13677 (while (re-search-forward
13678 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
13679 (cdr range) t)
13680 (add-to-list 'rtn (org-match-string-no-properties 1)))
13681 (outline-next-heading))))
13683 (when include-specials
13684 (setq rtn (append org-special-properties rtn)))
13686 (when include-defaults
13687 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
13688 (add-to-list 'rtn org-effort-property))
13690 (when include-columns
13691 (save-excursion
13692 (save-restriction
13693 (widen)
13694 (goto-char (point-min))
13695 (while (re-search-forward
13696 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
13697 nil t)
13698 (setq cfmt (match-string 2) s 0)
13699 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
13700 cfmt s)
13701 (setq s (match-end 0)
13702 p (match-string 1 cfmt))
13703 (unless (or (equal p "ITEM")
13704 (member p org-special-properties))
13705 (add-to-list 'rtn (match-string 1 cfmt))))))))
13707 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
13709 (defun org-property-values (key)
13710 "Return a list of all values of property KEY."
13711 (save-excursion
13712 (save-restriction
13713 (widen)
13714 (goto-char (point-min))
13715 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
13716 values)
13717 (while (re-search-forward re nil t)
13718 (add-to-list 'values (org-trim (match-string 1))))
13719 (delete "" values)))))
13721 (defun org-insert-property-drawer ()
13722 "Insert a property drawer into the current entry."
13723 (interactive)
13724 (org-back-to-heading t)
13725 (looking-at outline-regexp)
13726 (let ((indent (if org-adapt-indentation
13727 (- (match-end 0)(match-beginning 0))
13729 (beg (point))
13730 (re (concat "^[ \t]*" org-keyword-time-regexp))
13731 end hiddenp)
13732 (outline-next-heading)
13733 (setq end (point))
13734 (goto-char beg)
13735 (while (re-search-forward re end t))
13736 (setq hiddenp (org-invisible-p))
13737 (end-of-line 1)
13738 (and (equal (char-after) ?\n) (forward-char 1))
13739 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
13740 (if (member (match-string 1) '("CLOCK:" ":END:"))
13741 ;; just skip this line
13742 (beginning-of-line 2)
13743 ;; Drawer start, find the end
13744 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
13745 (beginning-of-line 1)))
13746 (org-skip-over-state-notes)
13747 (skip-chars-backward " \t\n\r")
13748 (if (eq (char-before) ?*) (forward-char 1))
13749 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
13750 (beginning-of-line 0)
13751 (org-indent-to-column indent)
13752 (beginning-of-line 2)
13753 (org-indent-to-column indent)
13754 (beginning-of-line 0)
13755 (if hiddenp
13756 (save-excursion
13757 (org-back-to-heading t)
13758 (hide-entry))
13759 (org-flag-drawer t))))
13761 (defun org-set-property (property value)
13762 "In the current entry, set PROPERTY to VALUE.
13763 When called interactively, this will prompt for a property name, offering
13764 completion on existing and default properties. And then it will prompt
13765 for a value, offering completion either on allowed values (via an inherited
13766 xxx_ALL property) or on existing values in other instances of this property
13767 in the current file."
13768 (interactive
13769 (let* ((completion-ignore-case t)
13770 (keys (org-buffer-property-keys nil t t))
13771 (prop0 (org-icompleting-read "Property: " (mapcar 'list keys)))
13772 (prop (if (member prop0 keys)
13773 prop0
13774 (or (cdr (assoc (downcase prop0)
13775 (mapcar (lambda (x) (cons (downcase x) x))
13776 keys)))
13777 prop0)))
13778 (cur (org-entry-get nil prop))
13779 (prompt (concat prop " value"
13780 (if (and cur (string-match "\\S-" cur))
13781 (concat " [" cur "]") "") ": "))
13782 (allowed (org-property-get-allowed-values nil prop 'table))
13783 (existing (mapcar 'list (org-property-values prop)))
13784 (val (if allowed
13785 (org-completing-read prompt allowed nil
13786 (not (get-text-property 0 'org-unrestricted
13787 (caar allowed))))
13788 (let (org-completion-use-ido org-completion-use-iswitchb)
13789 (org-completing-read prompt existing nil nil "" nil cur)))))
13790 (list prop (if (equal val "") cur val))))
13791 (unless (equal (org-entry-get nil property) value)
13792 (org-entry-put nil property value)))
13794 (defun org-delete-property (property)
13795 "In the current entry, delete PROPERTY."
13796 (interactive
13797 (let* ((completion-ignore-case t)
13798 (prop (org-icompleting-read "Property: "
13799 (org-entry-properties nil 'standard))))
13800 (list prop)))
13801 (message "Property %s %s" property
13802 (if (org-entry-delete nil property)
13803 "deleted"
13804 "was not present in the entry")))
13806 (defun org-delete-property-globally (property)
13807 "Remove PROPERTY globally, from all entries."
13808 (interactive
13809 (let* ((completion-ignore-case t)
13810 (prop (org-icompleting-read
13811 "Globally remove property: "
13812 (mapcar 'list (org-buffer-property-keys)))))
13813 (list prop)))
13814 (save-excursion
13815 (save-restriction
13816 (widen)
13817 (goto-char (point-min))
13818 (let ((cnt 0))
13819 (while (re-search-forward
13820 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
13821 nil t)
13822 (setq cnt (1+ cnt))
13823 (replace-match ""))
13824 (message "Property \"%s\" removed from %d entries" property cnt)))))
13826 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
13828 (defun org-compute-property-at-point ()
13829 "Compute the property at point.
13830 This looks for an enclosing column format, extracts the operator and
13831 then applies it to the property in the column format's scope."
13832 (interactive)
13833 (unless (org-at-property-p)
13834 (error "Not at a property"))
13835 (let ((prop (org-match-string-no-properties 2)))
13836 (org-columns-get-format-and-top-level)
13837 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
13838 (error "No operator defined for property %s" prop))
13839 (org-columns-compute prop)))
13841 (defvar org-property-allowed-value-functions nil
13842 "Hook for functions supplying allowed values for a specific property.
13843 The functions must take a single argument, the name of the property, and
13844 return a flat list of allowed values. If \":ETC\" is one of
13845 the values, this means that these values are intended as defaults for
13846 completion, but that other values should be allowed too.
13847 The functions must return nil if they are not responsible for this
13848 property.")
13850 (defun org-property-get-allowed-values (pom property &optional table)
13851 "Get allowed values for the property PROPERTY.
13852 When TABLE is non-nil, return an alist that can directly be used for
13853 completion."
13854 (let (vals)
13855 (cond
13856 ((equal property "TODO")
13857 (setq vals (org-with-point-at pom
13858 (append org-todo-keywords-1 '("")))))
13859 ((equal property "PRIORITY")
13860 (let ((n org-lowest-priority))
13861 (while (>= n org-highest-priority)
13862 (push (char-to-string n) vals)
13863 (setq n (1- n)))))
13864 ((member property org-special-properties))
13865 ((setq vals (run-hook-with-args-until-success
13866 'org-property-allowed-value-functions property)))
13868 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
13869 (when (and vals (string-match "\\S-" vals))
13870 (setq vals (car (read-from-string (concat "(" vals ")"))))
13871 (setq vals (mapcar (lambda (x)
13872 (cond ((stringp x) x)
13873 ((numberp x) (number-to-string x))
13874 ((symbolp x) (symbol-name x))
13875 (t "???")))
13876 vals)))))
13877 (when (member ":ETC" vals)
13878 (setq vals (remove ":ETC" vals))
13879 (org-add-props (car vals) '(org-unrestricted t)))
13880 (if table (mapcar 'list vals) vals)))
13882 (defun org-property-previous-allowed-value (&optional previous)
13883 "Switch to the next allowed value for this property."
13884 (interactive)
13885 (org-property-next-allowed-value t))
13887 (defun org-property-next-allowed-value (&optional previous)
13888 "Switch to the next allowed value for this property."
13889 (interactive)
13890 (unless (org-at-property-p)
13891 (error "Not at a property"))
13892 (let* ((key (match-string 2))
13893 (value (match-string 3))
13894 (allowed (or (org-property-get-allowed-values (point) key)
13895 (and (member value '("[ ]" "[-]" "[X]"))
13896 '("[ ]" "[X]"))))
13897 nval)
13898 (unless allowed
13899 (error "Allowed values for this property have not been defined"))
13900 (if previous (setq allowed (reverse allowed)))
13901 (if (member value allowed)
13902 (setq nval (car (cdr (member value allowed)))))
13903 (setq nval (or nval (car allowed)))
13904 (if (equal nval value)
13905 (error "Only one allowed value for this property"))
13906 (org-at-property-p)
13907 (replace-match (concat " :" key ": " nval) t t)
13908 (org-indent-line-function)
13909 (beginning-of-line 1)
13910 (skip-chars-forward " \t")
13911 (run-hook-with-args 'org-property-changed-functions key nval)))
13913 (defun org-find-olp (path &optional this-buffer)
13914 "Return a marker pointing to the entry at outline path OLP.
13915 If anything goes wrong, throw an error.
13916 You can wrap this call to catch the error like this:
13918 (condition-case msg
13919 (org-mobile-locate-entry (match-string 4))
13920 (error (nth 1 msg)))
13922 The return value will then be either a string with the error message,
13923 or a marker if everything is OK.
13925 If THIS-BUFFER is set, the outline path does not contain a file,
13926 only headings."
13927 (let* ((file (if this-buffer buffer-file-name (pop path)))
13928 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
13929 (level 1)
13930 (lmin 1)
13931 (lmax 1)
13932 limit re end found pos heading cnt)
13933 (unless buffer (error "File not found :%s" file))
13934 (with-current-buffer buffer
13935 (save-excursion
13936 (save-restriction
13937 (widen)
13938 (setq limit (point-max))
13939 (goto-char (point-min))
13940 (while (setq heading (pop path))
13941 (setq re (format org-complex-heading-regexp-format
13942 (regexp-quote heading)))
13943 (setq cnt 0 pos (point))
13944 (while (re-search-forward re end t)
13945 (setq level (- (match-end 1) (match-beginning 1)))
13946 (if (and (>= level lmin) (<= level lmax))
13947 (setq found (match-beginning 0) cnt (1+ cnt))))
13948 (when (= cnt 0) (error "Heading not found on level %d: %s"
13949 lmax heading))
13950 (when (> cnt 1) (error "Heading not unique on level %d: %s"
13951 lmax heading))
13952 (goto-char found)
13953 (setq lmin (1+ level) lmax (+ lmin (if org-odd-levels-only 1 0)))
13954 (setq end (save-excursion (org-end-of-subtree t t))))
13955 (when (org-on-heading-p)
13956 (move-marker (make-marker) (point))))))))
13958 (defun org-find-entry-with-id (ident)
13959 "Locate the entry that contains the ID property with exact value IDENT.
13960 IDENT can be a string, a symbol or a number, this function will search for
13961 the string representation of it.
13962 Return the position where this entry starts, or nil if there is no such entry."
13963 (interactive "sID: ")
13964 (let ((id (cond
13965 ((stringp ident) ident)
13966 ((symbol-name ident) (symbol-name ident))
13967 ((numberp ident) (number-to-string ident))
13968 (t (error "IDENT %s must be a string, symbol or number" ident))))
13969 (case-fold-search nil))
13970 (save-excursion
13971 (save-restriction
13972 (widen)
13973 (goto-char (point-min))
13974 (when (re-search-forward
13975 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
13976 nil t)
13977 (org-back-to-heading t)
13978 (point))))))
13980 ;;;; Timestamps
13982 (defvar org-last-changed-timestamp nil)
13983 (defvar org-last-inserted-timestamp nil
13984 "The last time stamp inserted with `org-insert-time-stamp'.")
13985 (defvar org-time-was-given) ; dynamically scoped parameter
13986 (defvar org-end-time-was-given) ; dynamically scoped parameter
13987 (defvar org-ts-what) ; dynamically scoped parameter
13989 (defun org-time-stamp (arg &optional inactive)
13990 "Prompt for a date/time and insert a time stamp.
13991 If the user specifies a time like HH:MM, or if this command is called
13992 with a prefix argument, the time stamp will contain date and time.
13993 Otherwise, only the date will be included. All parts of a date not
13994 specified by the user will be filled in from the current date/time.
13995 So if you press just return without typing anything, the time stamp
13996 will represent the current date/time. If there is already a timestamp
13997 at the cursor, it will be modified."
13998 (interactive "P")
13999 (let* ((ts nil)
14000 (default-time
14001 ;; Default time is either today, or, when entering a range,
14002 ;; the range start.
14003 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
14004 (save-excursion
14005 (re-search-backward
14006 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
14007 (- (point) 20) t)))
14008 (apply 'encode-time (org-parse-time-string (match-string 1)))
14009 (current-time)))
14010 (default-input (and ts (org-get-compact-tod ts)))
14011 org-time-was-given org-end-time-was-given time)
14012 (cond
14013 ((and (org-at-timestamp-p t)
14014 (memq last-command '(org-time-stamp org-time-stamp-inactive))
14015 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
14016 (insert "--")
14017 (setq time (let ((this-command this-command))
14018 (org-read-date arg 'totime nil nil
14019 default-time default-input)))
14020 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
14021 ((org-at-timestamp-p t)
14022 (setq time (let ((this-command this-command))
14023 (org-read-date arg 'totime nil nil default-time default-input)))
14024 (when (org-at-timestamp-p t) ; just to get the match data
14025 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
14026 (replace-match "")
14027 (setq org-last-changed-timestamp
14028 (org-insert-time-stamp
14029 time (or org-time-was-given arg)
14030 inactive nil nil (list org-end-time-was-given))))
14031 (message "Timestamp updated"))
14033 (setq time (let ((this-command this-command))
14034 (org-read-date arg 'totime nil nil default-time default-input)))
14035 (org-insert-time-stamp time (or org-time-was-given arg) inactive
14036 nil nil (list org-end-time-was-given))))))
14038 ;; FIXME: can we use this for something else, like computing time differences?
14039 (defun org-get-compact-tod (s)
14040 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
14041 (let* ((t1 (match-string 1 s))
14042 (h1 (string-to-number (match-string 2 s)))
14043 (m1 (string-to-number (match-string 3 s)))
14044 (t2 (and (match-end 4) (match-string 5 s)))
14045 (h2 (and t2 (string-to-number (match-string 6 s))))
14046 (m2 (and t2 (string-to-number (match-string 7 s))))
14047 dh dm)
14048 (if (not t2)
14050 (setq dh (- h2 h1) dm (- m2 m1))
14051 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
14052 (concat t1 "+" (number-to-string dh)
14053 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
14055 (defun org-time-stamp-inactive (&optional arg)
14056 "Insert an inactive time stamp.
14057 An inactive time stamp is enclosed in square brackets instead of angle
14058 brackets. It is inactive in the sense that it does not trigger agenda entries,
14059 does not link to the calendar and cannot be changed with the S-cursor keys.
14060 So these are more for recording a certain time/date."
14061 (interactive "P")
14062 (org-time-stamp arg 'inactive))
14064 (defvar org-date-ovl (make-overlay 1 1))
14065 (overlay-put org-date-ovl 'face 'org-warning)
14066 (org-detach-overlay org-date-ovl)
14068 (defvar org-ans1) ; dynamically scoped parameter
14069 (defvar org-ans2) ; dynamically scoped parameter
14071 (defvar org-plain-time-of-day-regexp) ; defined below
14073 (defvar org-overriding-default-time nil) ; dynamically scoped
14074 (defvar org-read-date-overlay nil)
14075 (defvar org-dcst nil) ; dynamically scoped
14076 (defvar org-read-date-history nil)
14077 (defvar org-read-date-final-answer nil)
14079 (defun org-read-date (&optional with-time to-time from-string prompt
14080 default-time default-input)
14081 "Read a date, possibly a time, and make things smooth for the user.
14082 The prompt will suggest to enter an ISO date, but you can also enter anything
14083 which will at least partially be understood by `parse-time-string'.
14084 Unrecognized parts of the date will default to the current day, month, year,
14085 hour and minute. If this command is called to replace a timestamp at point,
14086 of to enter the second timestamp of a range, the default time is taken
14087 from the existing stamp. Furthermore, the command prefers the future,
14088 so if you are giving a date where the year is not given, and the day-month
14089 combination is already past in the current year, it will assume you
14090 mean next year. For details, see the manual. A few examples:
14092 3-2-5 --> 2003-02-05
14093 feb 15 --> currentyear-02-15
14094 2/15 --> currentyear-02-15
14095 sep 12 9 --> 2009-09-12
14096 12:45 --> today 12:45
14097 22 sept 0:34 --> currentyear-09-22 0:34
14098 12 --> currentyear-currentmonth-12
14099 Fri --> nearest Friday (today or later)
14100 etc.
14102 Furthermore you can specify a relative date by giving, as the *first* thing
14103 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
14104 change in days weeks, months, years.
14105 With a single plus or minus, the date is relative to today. With a double
14106 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
14107 +4d --> four days from today
14108 +4 --> same as above
14109 +2w --> two weeks from today
14110 ++5 --> five days from default date
14112 The function understands only English month and weekday abbreviations,
14113 but this can be configured with the variables `parse-time-months' and
14114 `parse-time-weekdays'.
14116 While prompting, a calendar is popped up - you can also select the
14117 date with the mouse (button 1). The calendar shows a period of three
14118 months. To scroll it to other months, use the keys `>' and `<'.
14119 If you don't like the calendar, turn it off with
14120 \(setq org-read-date-popup-calendar nil)
14122 With optional argument TO-TIME, the date will immediately be converted
14123 to an internal time.
14124 With an optional argument WITH-TIME, the prompt will suggest to also
14125 insert a time. Note that when WITH-TIME is not set, you can still
14126 enter a time, and this function will inform the calling routine about
14127 this change. The calling routine may then choose to change the format
14128 used to insert the time stamp into the buffer to include the time.
14129 With optional argument FROM-STRING, read from this string instead from
14130 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
14131 the time/date that is used for everything that is not specified by the
14132 user."
14133 (require 'parse-time)
14134 (let* ((org-time-stamp-rounding-minutes
14135 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
14136 (org-dcst org-display-custom-times)
14137 (ct (org-current-time))
14138 (def (or org-overriding-default-time default-time ct))
14139 (defdecode (decode-time def))
14140 (dummy (progn
14141 (when (< (nth 2 defdecode) org-extend-today-until)
14142 (setcar (nthcdr 2 defdecode) -1)
14143 (setcar (nthcdr 1 defdecode) 59)
14144 (setq def (apply 'encode-time defdecode)
14145 defdecode (decode-time def)))))
14146 (calendar-frame-setup nil)
14147 (calendar-setup nil)
14148 (calendar-move-hook nil)
14149 (calendar-view-diary-initially-flag nil)
14150 (calendar-view-holidays-initially-flag nil)
14151 (timestr (format-time-string
14152 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
14153 (prompt (concat (if prompt (concat prompt " ") "")
14154 (format "Date+time [%s]: " timestr)))
14155 ans (org-ans0 "") org-ans1 org-ans2 final)
14157 (cond
14158 (from-string (setq ans from-string))
14159 (org-read-date-popup-calendar
14160 (save-excursion
14161 (save-window-excursion
14162 (calendar)
14163 (calendar-forward-day (- (time-to-days def)
14164 (calendar-absolute-from-gregorian
14165 (calendar-current-date))))
14166 (org-eval-in-calendar nil t)
14167 (let* ((old-map (current-local-map))
14168 (map (copy-keymap calendar-mode-map))
14169 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
14170 (org-defkey map (kbd "RET") 'org-calendar-select)
14171 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
14172 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
14173 (org-defkey minibuffer-local-map [(meta shift left)]
14174 (lambda () (interactive)
14175 (org-eval-in-calendar '(calendar-backward-month 1))))
14176 (org-defkey minibuffer-local-map [(meta shift right)]
14177 (lambda () (interactive)
14178 (org-eval-in-calendar '(calendar-forward-month 1))))
14179 (org-defkey minibuffer-local-map [(meta shift up)]
14180 (lambda () (interactive)
14181 (org-eval-in-calendar '(calendar-backward-year 1))))
14182 (org-defkey minibuffer-local-map [(meta shift down)]
14183 (lambda () (interactive)
14184 (org-eval-in-calendar '(calendar-forward-year 1))))
14185 (org-defkey minibuffer-local-map [?\e (shift left)]
14186 (lambda () (interactive)
14187 (org-eval-in-calendar '(calendar-backward-month 1))))
14188 (org-defkey minibuffer-local-map [?\e (shift right)]
14189 (lambda () (interactive)
14190 (org-eval-in-calendar '(calendar-forward-month 1))))
14191 (org-defkey minibuffer-local-map [?\e (shift up)]
14192 (lambda () (interactive)
14193 (org-eval-in-calendar '(calendar-backward-year 1))))
14194 (org-defkey minibuffer-local-map [?\e (shift down)]
14195 (lambda () (interactive)
14196 (org-eval-in-calendar '(calendar-forward-year 1))))
14197 (org-defkey minibuffer-local-map [(shift up)]
14198 (lambda () (interactive)
14199 (org-eval-in-calendar '(calendar-backward-week 1))))
14200 (org-defkey minibuffer-local-map [(shift down)]
14201 (lambda () (interactive)
14202 (org-eval-in-calendar '(calendar-forward-week 1))))
14203 (org-defkey minibuffer-local-map [(shift left)]
14204 (lambda () (interactive)
14205 (org-eval-in-calendar '(calendar-backward-day 1))))
14206 (org-defkey minibuffer-local-map [(shift right)]
14207 (lambda () (interactive)
14208 (org-eval-in-calendar '(calendar-forward-day 1))))
14209 (org-defkey minibuffer-local-map ">"
14210 (lambda () (interactive)
14211 (org-eval-in-calendar '(scroll-calendar-left 1))))
14212 (org-defkey minibuffer-local-map "<"
14213 (lambda () (interactive)
14214 (org-eval-in-calendar '(scroll-calendar-right 1))))
14215 (org-defkey minibuffer-local-map "\C-v"
14216 (lambda () (interactive)
14217 (org-eval-in-calendar
14218 '(calendar-scroll-left-three-months 1))))
14219 (org-defkey minibuffer-local-map "\M-v"
14220 (lambda () (interactive)
14221 (org-eval-in-calendar
14222 '(calendar-scroll-right-three-months 1))))
14223 (run-hooks 'org-read-date-minibuffer-setup-hook)
14224 (unwind-protect
14225 (progn
14226 (use-local-map map)
14227 (add-hook 'post-command-hook 'org-read-date-display)
14228 (setq org-ans0 (read-string prompt default-input
14229 'org-read-date-history nil))
14230 ;; org-ans0: from prompt
14231 ;; org-ans1: from mouse click
14232 ;; org-ans2: from calendar motion
14233 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
14234 (remove-hook 'post-command-hook 'org-read-date-display)
14235 (use-local-map old-map)
14236 (when org-read-date-overlay
14237 (delete-overlay org-read-date-overlay)
14238 (setq org-read-date-overlay nil)))))))
14240 (t ; Naked prompt only
14241 (unwind-protect
14242 (setq ans (read-string prompt default-input
14243 'org-read-date-history timestr))
14244 (when org-read-date-overlay
14245 (delete-overlay org-read-date-overlay)
14246 (setq org-read-date-overlay nil)))))
14248 (setq final (org-read-date-analyze ans def defdecode))
14249 (setq org-read-date-final-answer ans)
14251 (if to-time
14252 (apply 'encode-time final)
14253 (if (and (boundp 'org-time-was-given) org-time-was-given)
14254 (format "%04d-%02d-%02d %02d:%02d"
14255 (nth 5 final) (nth 4 final) (nth 3 final)
14256 (nth 2 final) (nth 1 final))
14257 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
14259 (defvar def)
14260 (defvar defdecode)
14261 (defvar with-time)
14262 (defvar org-read-date-analyze-futurep nil)
14263 (defun org-read-date-display ()
14264 "Display the current date prompt interpretation in the minibuffer."
14265 (when org-read-date-display-live
14266 (when org-read-date-overlay
14267 (delete-overlay org-read-date-overlay))
14268 (let ((p (point)))
14269 (end-of-line 1)
14270 (while (not (equal (buffer-substring
14271 (max (point-min) (- (point) 4)) (point))
14272 " "))
14273 (insert " "))
14274 (goto-char p))
14275 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
14276 " " (or org-ans1 org-ans2)))
14277 (org-end-time-was-given nil)
14278 (f (org-read-date-analyze ans def defdecode))
14279 (fmts (if org-dcst
14280 org-time-stamp-custom-formats
14281 org-time-stamp-formats))
14282 (fmt (if (or with-time
14283 (and (boundp 'org-time-was-given) org-time-was-given))
14284 (cdr fmts)
14285 (car fmts)))
14286 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
14287 (when (and org-end-time-was-given
14288 (string-match org-plain-time-of-day-regexp txt))
14289 (setq txt (concat (substring txt 0 (match-end 0)) "-"
14290 org-end-time-was-given
14291 (substring txt (match-end 0)))))
14292 (when org-read-date-analyze-futurep
14293 (setq txt (concat txt " (=>F)")))
14294 (setq org-read-date-overlay
14295 (make-overlay (1- (point-at-eol)) (point-at-eol)))
14296 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
14298 (defun org-read-date-analyze (ans def defdecode)
14299 "Analyze the combined answer of the date prompt."
14300 ;; FIXME: cleanup and comment
14301 (let ((nowdecode (decode-time (current-time)))
14302 delta deltan deltaw deltadef year month day
14303 hour minute second wday pm h2 m2 tl wday1
14304 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
14305 (setq org-read-date-analyze-futurep nil)
14306 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
14307 (setq ans "+0"))
14309 (when (setq delta (org-read-date-get-relative ans (current-time) def))
14310 (setq ans (replace-match "" t t ans)
14311 deltan (car delta)
14312 deltaw (nth 1 delta)
14313 deltadef (nth 2 delta)))
14315 ;; Check if there is an iso week date in there
14316 ;; If yes, store the info and postpone interpreting it until the rest
14317 ;; of the parsing is done
14318 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
14319 (setq iso-year (if (match-end 1)
14320 (org-small-year-to-year
14321 (string-to-number (match-string 1 ans))))
14322 iso-weekday (if (match-end 3)
14323 (string-to-number (match-string 3 ans)))
14324 iso-week (string-to-number (match-string 2 ans)))
14325 (setq ans (replace-match "" t t ans)))
14327 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
14328 (when (string-match
14329 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
14330 (setq year (if (match-end 2)
14331 (string-to-number (match-string 2 ans))
14332 (progn (setq kill-year t)
14333 (string-to-number (format-time-string "%Y"))))
14334 month (string-to-number (match-string 3 ans))
14335 day (string-to-number (match-string 4 ans)))
14336 (if (< year 100) (setq year (+ 2000 year)))
14337 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14338 t nil ans)))
14339 ;; Help matching american dates, like 5/30 or 5/30/7
14340 (when (string-match
14341 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
14342 (setq year (if (match-end 4)
14343 (string-to-number (match-string 4 ans))
14344 (progn (setq kill-year t)
14345 (string-to-number (format-time-string "%Y"))))
14346 month (string-to-number (match-string 1 ans))
14347 day (string-to-number (match-string 2 ans)))
14348 (if (< year 100) (setq year (+ 2000 year)))
14349 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14350 t nil ans)))
14351 ;; Help matching am/pm times, because `parse-time-string' does not do that.
14352 ;; If there is a time with am/pm, and *no* time without it, we convert
14353 ;; so that matching will be successful.
14354 (loop for i from 1 to 2 do ; twice, for end time as well
14355 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
14356 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
14357 (setq hour (string-to-number (match-string 1 ans))
14358 minute (if (match-end 3)
14359 (string-to-number (match-string 3 ans))
14361 pm (equal ?p
14362 (string-to-char (downcase (match-string 4 ans)))))
14363 (if (and (= hour 12) (not pm))
14364 (setq hour 0)
14365 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
14366 (setq ans (replace-match (format "%02d:%02d" hour minute)
14367 t t ans))))
14369 ;; Check if a time range is given as a duration
14370 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
14371 (setq hour (string-to-number (match-string 1 ans))
14372 h2 (+ hour (string-to-number (match-string 3 ans)))
14373 minute (string-to-number (match-string 2 ans))
14374 m2 (+ minute (if (match-end 5) (string-to-number
14375 (match-string 5 ans))0)))
14376 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
14377 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
14378 t t ans)))
14380 ;; Check if there is a time range
14381 (when (boundp 'org-end-time-was-given)
14382 (setq org-time-was-given nil)
14383 (when (and (string-match org-plain-time-of-day-regexp ans)
14384 (match-end 8))
14385 (setq org-end-time-was-given (match-string 8 ans))
14386 (setq ans (concat (substring ans 0 (match-beginning 7))
14387 (substring ans (match-end 7))))))
14389 (setq tl (parse-time-string ans)
14390 day (or (nth 3 tl) (nth 3 defdecode))
14391 month (or (nth 4 tl)
14392 (if (and org-read-date-prefer-future
14393 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
14394 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
14395 (nth 4 defdecode)))
14396 year (or (and (not kill-year) (nth 5 tl))
14397 (if (and org-read-date-prefer-future
14398 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
14399 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
14400 (nth 5 defdecode)))
14401 hour (or (nth 2 tl) (nth 2 defdecode))
14402 minute (or (nth 1 tl) (nth 1 defdecode))
14403 second (or (nth 0 tl) 0)
14404 wday (nth 6 tl))
14406 (when (and (eq org-read-date-prefer-future 'time)
14407 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
14408 (equal day (nth 3 nowdecode))
14409 (equal month (nth 4 nowdecode))
14410 (equal year (nth 5 nowdecode))
14411 (nth 2 tl)
14412 (or (< (nth 2 tl) (nth 2 nowdecode))
14413 (and (= (nth 2 tl) (nth 2 nowdecode))
14414 (nth 1 tl)
14415 (< (nth 1 tl) (nth 1 nowdecode)))))
14416 (setq day (1+ day)
14417 futurep t))
14419 ;; Special date definitions below
14420 (cond
14421 (iso-week
14422 ;; There was an iso week
14423 (require 'cal-iso)
14424 (setq futurep nil)
14425 (setq year (or iso-year year)
14426 day (or iso-weekday wday 1)
14427 wday nil ; to make sure that the trigger below does not match
14428 iso-date (calendar-gregorian-from-absolute
14429 (calendar-absolute-from-iso
14430 (list iso-week day year))))
14431 ; FIXME: Should we also push ISO weeks into the future?
14432 ; (when (and org-read-date-prefer-future
14433 ; (not iso-year)
14434 ; (< (calendar-absolute-from-gregorian iso-date)
14435 ; (time-to-days (current-time))))
14436 ; (setq year (1+ year)
14437 ; iso-date (calendar-gregorian-from-absolute
14438 ; (calendar-absolute-from-iso
14439 ; (list iso-week day year)))))
14440 (setq month (car iso-date)
14441 year (nth 2 iso-date)
14442 day (nth 1 iso-date)))
14443 (deltan
14444 (setq futurep nil)
14445 (unless deltadef
14446 (let ((now (decode-time (current-time))))
14447 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
14448 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
14449 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
14450 ((equal deltaw "m") (setq month (+ month deltan)))
14451 ((equal deltaw "y") (setq year (+ year deltan)))))
14452 ((and wday (not (nth 3 tl)))
14453 (setq futurep nil)
14454 ;; Weekday was given, but no day, so pick that day in the week
14455 ;; on or after the derived date.
14456 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
14457 (unless (equal wday wday1)
14458 (setq day (+ day (% (- wday wday1 -7) 7))))))
14459 (if (and (boundp 'org-time-was-given)
14460 (nth 2 tl))
14461 (setq org-time-was-given t))
14462 (if (< year 100) (setq year (+ 2000 year)))
14463 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
14464 (setq org-read-date-analyze-futurep futurep)
14465 (list second minute hour day month year)))
14467 (defvar parse-time-weekdays)
14469 (defun org-read-date-get-relative (s today default)
14470 "Check string S for special relative date string.
14471 TODAY and DEFAULT are internal times, for today and for a default.
14472 Return shift list (N what def-flag)
14473 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
14474 N is the number of WHATs to shift.
14475 DEF-FLAG is t when a double ++ or -- indicates shift relative to
14476 the DEFAULT date rather than TODAY."
14477 (when (and
14478 (string-match
14479 (concat
14480 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
14481 "\\([0-9]+\\)?"
14482 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
14483 "\\([ \t]\\|$\\)") s)
14484 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
14485 (let* ((dir (if (> (match-end 1) (match-beginning 1))
14486 (string-to-char (substring (match-string 1 s) -1))
14487 ?+))
14488 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
14489 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
14490 (what (if (match-end 3) (match-string 3 s) "d"))
14491 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
14492 (date (if rel default today))
14493 (wday (nth 6 (decode-time date)))
14494 delta)
14495 (if wday1
14496 (progn
14497 (setq delta (mod (+ 7 (- wday1 wday)) 7))
14498 (if (= dir ?-) (setq delta (- delta 7)))
14499 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
14500 (list delta "d" rel))
14501 (list (* n (if (= dir ?-) -1 1)) what rel)))))
14503 (defun org-order-calendar-date-args (arg1 arg2 arg3)
14504 "Turn a user-specified date into the internal representation.
14505 The internal representation needed by the calendar is (month day year).
14506 This is a wrapper to handle the brain-dead convention in calendar that
14507 user function argument order change dependent on argument order."
14508 (if (boundp 'calendar-date-style)
14509 (cond
14510 ((eq calendar-date-style 'american)
14511 (list arg1 arg2 arg3))
14512 ((eq calendar-date-style 'european)
14513 (list arg2 arg1 arg3))
14514 ((eq calendar-date-style 'iso)
14515 (list arg2 arg3 arg1)))
14516 (if (org-bound-and-true-p european-calendar-style)
14517 (list arg2 arg1 arg3)
14518 (list arg1 arg2 arg3))))
14520 (defun org-eval-in-calendar (form &optional keepdate)
14521 "Eval FORM in the calendar window and return to current window.
14522 Also, store the cursor date in variable org-ans2."
14523 (let ((sf (selected-frame))
14524 (sw (selected-window)))
14525 (select-window (get-buffer-window "*Calendar*" t))
14526 (eval form)
14527 (when (and (not keepdate) (calendar-cursor-to-date))
14528 (let* ((date (calendar-cursor-to-date))
14529 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14530 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
14531 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
14532 (select-window sw)
14533 (org-select-frame-set-input-focus sf)))
14535 (defun org-calendar-select ()
14536 "Return to `org-read-date' with the date currently selected.
14537 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
14538 (interactive)
14539 (when (calendar-cursor-to-date)
14540 (let* ((date (calendar-cursor-to-date))
14541 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14542 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
14543 (if (active-minibuffer-window) (exit-minibuffer))))
14545 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
14546 "Insert a date stamp for the date given by the internal TIME.
14547 WITH-HM means use the stamp format that includes the time of the day.
14548 INACTIVE means use square brackets instead of angular ones, so that the
14549 stamp will not contribute to the agenda.
14550 PRE and POST are optional strings to be inserted before and after the
14551 stamp.
14552 The command returns the inserted time stamp."
14553 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
14554 stamp)
14555 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
14556 (insert-before-markers (or pre ""))
14557 (insert-before-markers (setq stamp (format-time-string fmt time)))
14558 (when (listp extra)
14559 (setq extra (car extra))
14560 (if (and (stringp extra)
14561 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
14562 (setq extra (format "-%02d:%02d"
14563 (string-to-number (match-string 1 extra))
14564 (string-to-number (match-string 2 extra))))
14565 (setq extra nil)))
14566 (when extra
14567 (backward-char 1)
14568 (insert-before-markers extra)
14569 (forward-char 1))
14570 (insert-before-markers (or post ""))
14571 (setq org-last-inserted-timestamp stamp)))
14573 (defun org-toggle-time-stamp-overlays ()
14574 "Toggle the use of custom time stamp formats."
14575 (interactive)
14576 (setq org-display-custom-times (not org-display-custom-times))
14577 (unless org-display-custom-times
14578 (let ((p (point-min)) (bmp (buffer-modified-p)))
14579 (while (setq p (next-single-property-change p 'display))
14580 (if (and (get-text-property p 'display)
14581 (eq (get-text-property p 'face) 'org-date))
14582 (remove-text-properties
14583 p (setq p (next-single-property-change p 'display))
14584 '(display t))))
14585 (set-buffer-modified-p bmp)))
14586 (if (featurep 'xemacs)
14587 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
14588 (org-restart-font-lock)
14589 (setq org-table-may-need-update t)
14590 (if org-display-custom-times
14591 (message "Time stamps are overlayed with custom format")
14592 (message "Time stamp overlays removed")))
14594 (defun org-display-custom-time (beg end)
14595 "Overlay modified time stamp format over timestamp between BEG and END."
14596 (let* ((ts (buffer-substring beg end))
14597 t1 w1 with-hm tf time str w2 (off 0))
14598 (save-match-data
14599 (setq t1 (org-parse-time-string ts t))
14600 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
14601 (setq off (- (match-end 0) (match-beginning 0)))))
14602 (setq end (- end off))
14603 (setq w1 (- end beg)
14604 with-hm (and (nth 1 t1) (nth 2 t1))
14605 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
14606 time (org-fix-decoded-time t1)
14607 str (org-add-props
14608 (format-time-string
14609 (substring tf 1 -1) (apply 'encode-time time))
14610 nil 'mouse-face 'highlight)
14611 w2 (length str))
14612 (if (not (= w2 w1))
14613 (add-text-properties (1+ beg) (+ 2 beg)
14614 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
14615 (if (featurep 'xemacs)
14616 (progn
14617 (put-text-property beg end 'invisible t)
14618 (put-text-property beg end 'end-glyph (make-glyph str)))
14619 (put-text-property beg end 'display str))))
14621 (defun org-translate-time (string)
14622 "Translate all timestamps in STRING to custom format.
14623 But do this only if the variable `org-display-custom-times' is set."
14624 (when org-display-custom-times
14625 (save-match-data
14626 (let* ((start 0)
14627 (re org-ts-regexp-both)
14628 t1 with-hm inactive tf time str beg end)
14629 (while (setq start (string-match re string start))
14630 (setq beg (match-beginning 0)
14631 end (match-end 0)
14632 t1 (save-match-data
14633 (org-parse-time-string (substring string beg end) t))
14634 with-hm (and (nth 1 t1) (nth 2 t1))
14635 inactive (equal (substring string beg (1+ beg)) "[")
14636 tf (funcall (if with-hm 'cdr 'car)
14637 org-time-stamp-custom-formats)
14638 time (org-fix-decoded-time t1)
14639 str (format-time-string
14640 (concat
14641 (if inactive "[" "<") (substring tf 1 -1)
14642 (if inactive "]" ">"))
14643 (apply 'encode-time time))
14644 string (replace-match str t t string)
14645 start (+ start (length str)))))))
14646 string)
14648 (defun org-fix-decoded-time (time)
14649 "Set 0 instead of nil for the first 6 elements of time.
14650 Don't touch the rest."
14651 (let ((n 0))
14652 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
14654 (defun org-days-to-time (timestamp-string)
14655 "Difference between TIMESTAMP-STRING and now in days."
14656 (- (time-to-days (org-time-string-to-time timestamp-string))
14657 (time-to-days (current-time))))
14659 (defun org-deadline-close (timestamp-string &optional ndays)
14660 "Is the time in TIMESTAMP-STRING close to the current date?"
14661 (setq ndays (or ndays (org-get-wdays timestamp-string)))
14662 (and (< (org-days-to-time timestamp-string) ndays)
14663 (not (org-entry-is-done-p))))
14665 (defun org-get-wdays (ts)
14666 "Get the deadline lead time appropriate for timestring TS."
14667 (cond
14668 ((<= org-deadline-warning-days 0)
14669 ;; 0 or negative, enforce this value no matter what
14670 (- org-deadline-warning-days))
14671 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
14672 ;; lead time is specified.
14673 (floor (* (string-to-number (match-string 1 ts))
14674 (cdr (assoc (match-string 2 ts)
14675 '(("d" . 1) ("w" . 7)
14676 ("m" . 30.4) ("y" . 365.25)))))))
14677 ;; go for the default.
14678 (t org-deadline-warning-days)))
14680 (defun org-calendar-select-mouse (ev)
14681 "Return to `org-read-date' with the date currently selected.
14682 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
14683 (interactive "e")
14684 (mouse-set-point ev)
14685 (when (calendar-cursor-to-date)
14686 (let* ((date (calendar-cursor-to-date))
14687 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14688 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
14689 (if (active-minibuffer-window) (exit-minibuffer))))
14691 (defun org-check-deadlines (ndays)
14692 "Check if there are any deadlines due or past due.
14693 A deadline is considered due if it happens within `org-deadline-warning-days'
14694 days from today's date. If the deadline appears in an entry marked DONE,
14695 it is not shown. The prefix arg NDAYS can be used to test that many
14696 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
14697 (interactive "P")
14698 (let* ((org-warn-days
14699 (cond
14700 ((equal ndays '(4)) 100000)
14701 (ndays (prefix-numeric-value ndays))
14702 (t (abs org-deadline-warning-days))))
14703 (case-fold-search nil)
14704 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
14705 (callback
14706 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
14708 (message "%d deadlines past-due or due within %d days"
14709 (org-occur regexp nil callback)
14710 org-warn-days)))
14712 (defun org-check-before-date (date)
14713 "Check if there are deadlines or scheduled entries before DATE."
14714 (interactive (list (org-read-date)))
14715 (let ((case-fold-search nil)
14716 (regexp (concat "\\<\\(" org-deadline-string
14717 "\\|" org-scheduled-string
14718 "\\) *<\\([^>]+\\)>"))
14719 (callback
14720 (lambda () (time-less-p
14721 (org-time-string-to-time (match-string 2))
14722 (org-time-string-to-time date)))))
14723 (message "%d entries before %s"
14724 (org-occur regexp nil callback) date)))
14726 (defun org-check-after-date (date)
14727 "Check if there are deadlines or scheduled entries after DATE."
14728 (interactive (list (org-read-date)))
14729 (let ((case-fold-search nil)
14730 (regexp (concat "\\<\\(" org-deadline-string
14731 "\\|" org-scheduled-string
14732 "\\) *<\\([^>]+\\)>"))
14733 (callback
14734 (lambda () (not
14735 (time-less-p
14736 (org-time-string-to-time (match-string 2))
14737 (org-time-string-to-time date))))))
14738 (message "%d entries after %s"
14739 (org-occur regexp nil callback) date)))
14741 (defun org-evaluate-time-range (&optional to-buffer)
14742 "Evaluate a time range by computing the difference between start and end.
14743 Normally the result is just printed in the echo area, but with prefix arg
14744 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
14745 If the time range is actually in a table, the result is inserted into the
14746 next column.
14747 For time difference computation, a year is assumed to be exactly 365
14748 days in order to avoid rounding problems."
14749 (interactive "P")
14751 (org-clock-update-time-maybe)
14752 (save-excursion
14753 (unless (org-at-date-range-p t)
14754 (goto-char (point-at-bol))
14755 (re-search-forward org-tr-regexp-both (point-at-eol) t))
14756 (if (not (org-at-date-range-p t))
14757 (error "Not at a time-stamp range, and none found in current line")))
14758 (let* ((ts1 (match-string 1))
14759 (ts2 (match-string 2))
14760 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
14761 (match-end (match-end 0))
14762 (time1 (org-time-string-to-time ts1))
14763 (time2 (org-time-string-to-time ts2))
14764 (t1 (org-float-time time1))
14765 (t2 (org-float-time time2))
14766 (diff (abs (- t2 t1)))
14767 (negative (< (- t2 t1) 0))
14768 ;; (ys (floor (* 365 24 60 60)))
14769 (ds (* 24 60 60))
14770 (hs (* 60 60))
14771 (fy "%dy %dd %02d:%02d")
14772 (fy1 "%dy %dd")
14773 (fd "%dd %02d:%02d")
14774 (fd1 "%dd")
14775 (fh "%02d:%02d")
14776 y d h m align)
14777 (if havetime
14778 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
14780 d (floor (/ diff ds)) diff (mod diff ds)
14781 h (floor (/ diff hs)) diff (mod diff hs)
14782 m (floor (/ diff 60)))
14783 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
14785 d (floor (+ (/ diff ds) 0.5))
14786 h 0 m 0))
14787 (if (not to-buffer)
14788 (message "%s" (org-make-tdiff-string y d h m))
14789 (if (org-at-table-p)
14790 (progn
14791 (goto-char match-end)
14792 (setq align t)
14793 (and (looking-at " *|") (goto-char (match-end 0))))
14794 (goto-char match-end))
14795 (if (looking-at
14796 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
14797 (replace-match ""))
14798 (if negative (insert " -"))
14799 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
14800 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
14801 (insert " " (format fh h m))))
14802 (if align (org-table-align))
14803 (message "Time difference inserted")))))
14805 (defun org-make-tdiff-string (y d h m)
14806 (let ((fmt "")
14807 (l nil))
14808 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
14809 l (push y l)))
14810 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
14811 l (push d l)))
14812 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
14813 l (push h l)))
14814 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
14815 l (push m l)))
14816 (apply 'format fmt (nreverse l))))
14818 (defun org-time-string-to-time (s)
14819 (apply 'encode-time (org-parse-time-string s)))
14820 (defun org-time-string-to-seconds (s)
14821 (org-float-time (org-time-string-to-time s)))
14823 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
14824 "Convert a time stamp to an absolute day number.
14825 If there is a specifier for a cyclic time stamp, get the closest date to
14826 DAYNR.
14827 PREFER and SHOW-ALL are passed through to `org-closest-date'.
14828 the variable date is bound by the calendar when this is called."
14829 (cond
14830 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
14831 (if (org-diary-sexp-entry (match-string 1 s) "" date)
14832 daynr
14833 (+ daynr 1000)))
14834 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
14835 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
14836 (time-to-days (current-time))) (match-string 0 s)
14837 prefer show-all))
14838 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
14840 (defun org-days-to-iso-week (days)
14841 "Return the iso week number."
14842 (require 'cal-iso)
14843 (car (calendar-iso-from-absolute days)))
14845 (defun org-small-year-to-year (year)
14846 "Convert 2-digit years into 4-digit years.
14847 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
14848 The year 2000 cannot be abbreviated. Any year larger than 99
14849 is returned unchanged."
14850 (if (< year 38)
14851 (setq year (+ 2000 year))
14852 (if (< year 100)
14853 (setq year (+ 1900 year))))
14854 year)
14856 (defun org-time-from-absolute (d)
14857 "Return the time corresponding to date D.
14858 D may be an absolute day number, or a calendar-type list (month day year)."
14859 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
14860 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
14862 (defun org-calendar-holiday ()
14863 "List of holidays, for Diary display in Org-mode."
14864 (require 'holidays)
14865 (let ((hl (funcall
14866 (if (fboundp 'calendar-check-holidays)
14867 'calendar-check-holidays 'check-calendar-holidays) date)))
14868 (if hl (mapconcat 'identity hl "; "))))
14870 (defun org-diary-sexp-entry (sexp entry date)
14871 "Process a SEXP diary ENTRY for DATE."
14872 (require 'diary-lib)
14873 (let ((result (if calendar-debug-sexp
14874 (let ((stack-trace-on-error t))
14875 (eval (car (read-from-string sexp))))
14876 (condition-case nil
14877 (eval (car (read-from-string sexp)))
14878 (error
14879 (beep)
14880 (message "Bad sexp at line %d in %s: %s"
14881 (org-current-line)
14882 (buffer-file-name) sexp)
14883 (sleep-for 2))))))
14884 (cond ((stringp result) result)
14885 ((and (consp result)
14886 (stringp (cdr result))) (cdr result))
14887 (result entry)
14888 (t nil))))
14890 (defun org-diary-to-ical-string (frombuf)
14891 "Get iCalendar entries from diary entries in buffer FROMBUF.
14892 This uses the icalendar.el library."
14893 (let* ((tmpdir (if (featurep 'xemacs)
14894 (temp-directory)
14895 temporary-file-directory))
14896 (tmpfile (make-temp-name
14897 (expand-file-name "orgics" tmpdir)))
14898 buf rtn b e)
14899 (with-current-buffer frombuf
14900 (icalendar-export-region (point-min) (point-max) tmpfile)
14901 (setq buf (find-buffer-visiting tmpfile))
14902 (set-buffer buf)
14903 (goto-char (point-min))
14904 (if (re-search-forward "^BEGIN:VEVENT" nil t)
14905 (setq b (match-beginning 0)))
14906 (goto-char (point-max))
14907 (if (re-search-backward "^END:VEVENT" nil t)
14908 (setq e (match-end 0)))
14909 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
14910 (kill-buffer buf)
14911 (delete-file tmpfile)
14912 rtn))
14914 (defun org-closest-date (start current change prefer show-all)
14915 "Find the date closest to CURRENT that is consistent with START and CHANGE.
14916 When PREFER is `past' return a date that is either CURRENT or past.
14917 When PREFER is `future', return a date that is either CURRENT or future.
14918 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
14919 ;; Make the proper lists from the dates
14920 (catch 'exit
14921 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
14922 dn dw sday cday n1 n2 n0
14923 d m y y1 y2 date1 date2 nmonths nm ny m2)
14925 (setq start (org-date-to-gregorian start)
14926 current (org-date-to-gregorian
14927 (if show-all
14928 current
14929 (time-to-days (current-time))))
14930 sday (calendar-absolute-from-gregorian start)
14931 cday (calendar-absolute-from-gregorian current))
14933 (if (<= cday sday) (throw 'exit sday))
14935 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
14936 (setq dn (string-to-number (match-string 1 change))
14937 dw (cdr (assoc (match-string 2 change) a1)))
14938 (error "Invalid change specifier: %s" change))
14939 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
14940 (cond
14941 ((eq dw 'day)
14942 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
14943 n2 (+ n1 dn)))
14944 ((eq dw 'year)
14945 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
14946 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
14947 (setq date1 (list m d y1)
14948 n1 (calendar-absolute-from-gregorian date1)
14949 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
14950 n2 (calendar-absolute-from-gregorian date2)))
14951 ((eq dw 'month)
14952 ;; approx number of month between the two dates
14953 (setq nmonths (floor (/ (- cday sday) 30.436875)))
14954 ;; How often does dn fit in there?
14955 (setq d (nth 1 start) m (car start) y (nth 2 start)
14956 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
14957 m (+ m nm)
14958 ny (floor (/ m 12))
14959 y (+ y ny)
14960 m (- m (* ny 12)))
14961 (while (> m 12) (setq m (- m 12) y (1+ y)))
14962 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
14963 (setq m2 (+ m dn) y2 y)
14964 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
14965 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
14966 (while (<= n2 cday)
14967 (setq n1 n2 m m2 y y2)
14968 (setq m2 (+ m dn) y2 y)
14969 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
14970 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
14971 ;; Make sure n1 is the earlier date
14972 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
14973 (if show-all
14974 (cond
14975 ((eq prefer 'past) (if (= cday n2) n2 n1))
14976 ((eq prefer 'future) (if (= cday n1) n1 n2))
14977 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
14978 (cond
14979 ((eq prefer 'past) (if (= cday n2) n2 n1))
14980 ((eq prefer 'future) (if (= cday n1) n1 n2))
14981 (t (if (= cday n1) n1 n2)))))))
14983 (defun org-date-to-gregorian (date)
14984 "Turn any specification of DATE into a Gregorian date for the calendar."
14985 (cond ((integerp date) (calendar-gregorian-from-absolute date))
14986 ((and (listp date) (= (length date) 3)) date)
14987 ((stringp date)
14988 (setq date (org-parse-time-string date))
14989 (list (nth 4 date) (nth 3 date) (nth 5 date)))
14990 ((listp date)
14991 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
14993 (defun org-parse-time-string (s &optional nodefault)
14994 "Parse the standard Org-mode time string.
14995 This should be a lot faster than the normal `parse-time-string'.
14996 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
14997 hour and minute fields will be nil if not given."
14998 (if (string-match org-ts-regexp0 s)
14999 (list 0
15000 (if (or (match-beginning 8) (not nodefault))
15001 (string-to-number (or (match-string 8 s) "0")))
15002 (if (or (match-beginning 7) (not nodefault))
15003 (string-to-number (or (match-string 7 s) "0")))
15004 (string-to-number (match-string 4 s))
15005 (string-to-number (match-string 3 s))
15006 (string-to-number (match-string 2 s))
15007 nil nil nil)
15008 (error "Not a standard Org-mode time string: %s" s)))
15010 (defun org-timestamp-up (&optional arg)
15011 "Increase the date item at the cursor by one.
15012 If the cursor is on the year, change the year. If it is on the month or
15013 the day, change that.
15014 With prefix ARG, change by that many units."
15015 (interactive "p")
15016 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
15018 (defun org-timestamp-down (&optional arg)
15019 "Decrease the date item at the cursor by one.
15020 If the cursor is on the year, change the year. If it is on the month or
15021 the day, change that.
15022 With prefix ARG, change by that many units."
15023 (interactive "p")
15024 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
15026 (defun org-timestamp-up-day (&optional arg)
15027 "Increase the date in the time stamp by one day.
15028 With prefix ARG, change that many days."
15029 (interactive "p")
15030 (if (and (not (org-at-timestamp-p t))
15031 (org-on-heading-p))
15032 (org-todo 'up)
15033 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
15035 (defun org-timestamp-down-day (&optional arg)
15036 "Decrease the date in the time stamp by one day.
15037 With prefix ARG, change that many days."
15038 (interactive "p")
15039 (if (and (not (org-at-timestamp-p t))
15040 (org-on-heading-p))
15041 (org-todo 'down)
15042 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
15044 (defun org-at-timestamp-p (&optional inactive-ok)
15045 "Determine if the cursor is in or at a timestamp."
15046 (interactive)
15047 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
15048 (pos (point))
15049 (ans (or (looking-at tsr)
15050 (save-excursion
15051 (skip-chars-backward "^[<\n\r\t")
15052 (if (> (point) (point-min)) (backward-char 1))
15053 (and (looking-at tsr)
15054 (> (- (match-end 0) pos) -1))))))
15055 (and ans
15056 (boundp 'org-ts-what)
15057 (setq org-ts-what
15058 (cond
15059 ((= pos (match-beginning 0)) 'bracket)
15060 ((= pos (1- (match-end 0))) 'bracket)
15061 ((org-pos-in-match-range pos 2) 'year)
15062 ((org-pos-in-match-range pos 3) 'month)
15063 ((org-pos-in-match-range pos 7) 'hour)
15064 ((org-pos-in-match-range pos 8) 'minute)
15065 ((or (org-pos-in-match-range pos 4)
15066 (org-pos-in-match-range pos 5)) 'day)
15067 ((and (> pos (or (match-end 8) (match-end 5)))
15068 (< pos (match-end 0)))
15069 (- pos (or (match-end 8) (match-end 5))))
15070 (t 'day))))
15071 ans))
15073 (defun org-toggle-timestamp-type ()
15074 "Toggle the type (<active> or [inactive]) of a time stamp."
15075 (interactive)
15076 (when (org-at-timestamp-p t)
15077 (let ((beg (match-beginning 0)) (end (match-end 0))
15078 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
15079 (save-excursion
15080 (goto-char beg)
15081 (while (re-search-forward "[][<>]" end t)
15082 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
15083 t t)))
15084 (message "Timestamp is now %sactive"
15085 (if (equal (char-after beg) ?<) "" "in")))))
15087 (defun org-timestamp-change (n &optional what updown)
15088 "Change the date in the time stamp at point.
15089 The date will be changed by N times WHAT. WHAT can be `day', `month',
15090 `year', `minute', `second'. If WHAT is not given, the cursor position
15091 in the timestamp determines what will be changed."
15092 (let ((pos (point))
15093 with-hm inactive
15094 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
15095 org-ts-what
15096 extra rem
15097 ts time time0)
15098 (if (not (org-at-timestamp-p t))
15099 (error "Not at a timestamp"))
15100 (if (and (not what) (eq org-ts-what 'bracket))
15101 (org-toggle-timestamp-type)
15102 (if (and (not what) (not (eq org-ts-what 'day))
15103 org-display-custom-times
15104 (get-text-property (point) 'display)
15105 (not (get-text-property (1- (point)) 'display)))
15106 (setq org-ts-what 'day))
15107 (setq org-ts-what (or what org-ts-what)
15108 inactive (= (char-after (match-beginning 0)) ?\[)
15109 ts (match-string 0))
15110 (replace-match "")
15111 (if (string-match
15112 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
15114 (setq extra (match-string 1 ts)))
15115 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
15116 (setq with-hm t))
15117 (setq time0 (org-parse-time-string ts))
15118 (when (and updown
15119 (eq org-ts-what 'minute)
15120 (not current-prefix-arg))
15121 ;; This looks like s-up and s-down. Change by one rounding step.
15122 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
15123 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
15124 (setcar (cdr time0) (+ (nth 1 time0)
15125 (if (> n 0) (- rem) (- dm rem))))))
15126 (setq time
15127 (encode-time (or (car time0) 0)
15128 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
15129 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
15130 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
15131 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
15132 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
15133 (nthcdr 6 time0)))
15134 (when (and (member org-ts-what '(hour minute))
15135 extra
15136 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
15137 (setq extra (org-modify-ts-extra
15138 extra
15139 (if (eq org-ts-what 'hour) 2 5)
15140 n dm)))
15141 (when (integerp org-ts-what)
15142 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
15143 (if (eq what 'calendar)
15144 (let ((cal-date (org-get-date-from-calendar)))
15145 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
15146 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
15147 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
15148 (setcar time0 (or (car time0) 0))
15149 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
15150 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
15151 (setq time (apply 'encode-time time0))))
15152 (setq org-last-changed-timestamp
15153 (org-insert-time-stamp time with-hm inactive nil nil extra))
15154 (org-clock-update-time-maybe)
15155 (goto-char pos)
15156 ;; Try to recenter the calendar window, if any
15157 (if (and org-calendar-follow-timestamp-change
15158 (get-buffer-window "*Calendar*" t)
15159 (memq org-ts-what '(day month year)))
15160 (org-recenter-calendar (time-to-days time))))))
15162 (defun org-modify-ts-extra (s pos n dm)
15163 "Change the different parts of the lead-time and repeat fields in timestamp."
15164 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
15165 ng h m new rem)
15166 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
15167 (cond
15168 ((or (org-pos-in-match-range pos 2)
15169 (org-pos-in-match-range pos 3))
15170 (setq m (string-to-number (match-string 3 s))
15171 h (string-to-number (match-string 2 s)))
15172 (if (org-pos-in-match-range pos 2)
15173 (setq h (+ h n))
15174 (setq n (* dm (org-no-warnings (signum n))))
15175 (when (not (= 0 (setq rem (% m dm))))
15176 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
15177 (setq m (+ m n)))
15178 (if (< m 0) (setq m (+ m 60) h (1- h)))
15179 (if (> m 59) (setq m (- m 60) h (1+ h)))
15180 (setq h (min 24 (max 0 h)))
15181 (setq ng 1 new (format "-%02d:%02d" h m)))
15182 ((org-pos-in-match-range pos 6)
15183 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
15184 ((org-pos-in-match-range pos 5)
15185 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
15187 ((org-pos-in-match-range pos 9)
15188 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
15189 ((org-pos-in-match-range pos 8)
15190 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
15192 (when ng
15193 (setq s (concat
15194 (substring s 0 (match-beginning ng))
15196 (substring s (match-end ng))))))
15199 (defun org-recenter-calendar (date)
15200 "If the calendar is visible, recenter it to DATE."
15201 (let* ((win (selected-window))
15202 (cwin (get-buffer-window "*Calendar*" t))
15203 (calendar-move-hook nil))
15204 (when cwin
15205 (select-window cwin)
15206 (calendar-goto-date (if (listp date) date
15207 (calendar-gregorian-from-absolute date)))
15208 (select-window win))))
15210 (defun org-goto-calendar (&optional arg)
15211 "Go to the Emacs calendar at the current date.
15212 If there is a time stamp in the current line, go to that date.
15213 A prefix ARG can be used to force the current date."
15214 (interactive "P")
15215 (let ((tsr org-ts-regexp) diff
15216 (calendar-move-hook nil)
15217 (calendar-view-holidays-initially-flag nil)
15218 (calendar-view-diary-initially-flag nil))
15219 (if (or (org-at-timestamp-p)
15220 (save-excursion
15221 (beginning-of-line 1)
15222 (looking-at (concat ".*" tsr))))
15223 (let ((d1 (time-to-days (current-time)))
15224 (d2 (time-to-days
15225 (org-time-string-to-time (match-string 1)))))
15226 (setq diff (- d2 d1))))
15227 (calendar)
15228 (calendar-goto-today)
15229 (if (and diff (not arg)) (calendar-forward-day diff))))
15231 (defun org-get-date-from-calendar ()
15232 "Return a list (month day year) of date at point in calendar."
15233 (with-current-buffer "*Calendar*"
15234 (save-match-data
15235 (calendar-cursor-to-date))))
15237 (defun org-date-from-calendar ()
15238 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
15239 If there is already a time stamp at the cursor position, update it."
15240 (interactive)
15241 (if (org-at-timestamp-p t)
15242 (org-timestamp-change 0 'calendar)
15243 (let ((cal-date (org-get-date-from-calendar)))
15244 (org-insert-time-stamp
15245 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
15247 (defun org-minutes-to-hh:mm-string (m)
15248 "Compute H:MM from a number of minutes."
15249 (let ((h (/ m 60)))
15250 (setq m (- m (* 60 h)))
15251 (format org-time-clocksum-format h m)))
15253 (defun org-hh:mm-string-to-minutes (s)
15254 "Convert a string H:MM to a number of minutes.
15255 If the string is just a number, interpret it as minutes.
15256 In fact, the first hh:mm or number in the string will be taken,
15257 there can be extra stuff in the string.
15258 If no number is found, the return value is 0."
15259 (cond
15260 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
15261 (+ (* (string-to-number (match-string 1 s)) 60)
15262 (string-to-number (match-string 2 s))))
15263 ((string-match "\\([0-9]+\\)" s)
15264 (string-to-number (match-string 1 s)))
15265 (t 0)))
15267 ;;;; Files
15269 (defun org-save-all-org-buffers ()
15270 "Save all Org-mode buffers without user confirmation."
15271 (interactive)
15272 (message "Saving all Org-mode buffers...")
15273 (save-some-buffers t 'org-mode-p)
15274 (when (featurep 'org-id) (org-id-locations-save))
15275 (message "Saving all Org-mode buffers... done"))
15277 (defun org-revert-all-org-buffers ()
15278 "Revert all Org-mode buffers.
15279 Prompt for confirmation when there are unsaved changes.
15280 Be sure you know what you are doing before letting this function
15281 overwrite your changes.
15283 This function is useful in a setup where one tracks org files
15284 with a version control system, to revert on one machine after pulling
15285 changes from another. I believe the procedure must be like this:
15287 1. M-x org-save-all-org-buffers
15288 2. Pull changes from the other machine, resolve conflicts
15289 3. M-x org-revert-all-org-buffers"
15290 (interactive)
15291 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
15292 (error "Abort"))
15293 (save-excursion
15294 (save-window-excursion
15295 (mapc
15296 (lambda (b)
15297 (when (and (with-current-buffer b (org-mode-p))
15298 (with-current-buffer b buffer-file-name))
15299 (switch-to-buffer b)
15300 (revert-buffer t 'no-confirm)))
15301 (buffer-list))
15302 (when (and (featurep 'org-id) org-id-track-globally)
15303 (org-id-locations-load)))))
15305 ;;;; Agenda files
15307 ;;;###autoload
15308 (defun org-switchb (&optional arg)
15309 "Switch between Org buffers.
15310 With a prefix argument, restrict available to files.
15311 With two prefix arguments, restrict available buffers to agenda files.
15313 Defaults to `iswitchb' for buffer name completion.
15314 Set `org-completion-use-ido' to make it use ido instead."
15315 (interactive "P")
15316 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
15317 ((equal arg '(16)) (org-buffer-list 'agenda))
15318 (t (org-buffer-list))))
15319 (org-completion-use-iswitchb org-completion-use-iswitchb)
15320 (org-completion-use-ido org-completion-use-ido))
15321 (unless (or org-completion-use-ido org-completion-use-iswitchb)
15322 (setq org-completion-use-iswitchb t))
15323 (switch-to-buffer
15324 (org-icompleting-read "Org buffer: "
15325 (mapcar 'list (mapcar 'buffer-name blist))
15326 nil t))))
15328 ;;; Define some older names previously used for this functionality
15329 ;;;###autoload
15330 (defalias 'org-ido-switchb 'org-switchb)
15331 ;;;###autoload
15332 (defalias 'org-iswitchb 'org-switchb)
15334 (defun org-buffer-list (&optional predicate exclude-tmp)
15335 "Return a list of Org buffers.
15336 PREDICATE can be `export', `files' or `agenda'.
15338 export restrict the list to Export buffers.
15339 files restrict the list to buffers visiting Org files.
15340 agenda restrict the list to buffers visiting agenda files.
15342 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
15343 (let* ((bfn nil)
15344 (agenda-files (and (eq predicate 'agenda)
15345 (mapcar 'file-truename (org-agenda-files t))))
15346 (filter
15347 (cond
15348 ((eq predicate 'files)
15349 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
15350 ((eq predicate 'export)
15351 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
15352 ((eq predicate 'agenda)
15353 (lambda (b)
15354 (with-current-buffer b
15355 (and (eq major-mode 'org-mode)
15356 (setq bfn (buffer-file-name b))
15357 (member (file-truename bfn) agenda-files)))))
15358 (t (lambda (b) (with-current-buffer b
15359 (or (eq major-mode 'org-mode)
15360 (string-match "\*Org .*Export"
15361 (buffer-name b)))))))))
15362 (delq nil
15363 (mapcar
15364 (lambda(b)
15365 (if (and (funcall filter b)
15366 (or (not exclude-tmp)
15367 (not (string-match "tmp" (buffer-name b)))))
15369 nil))
15370 (buffer-list)))))
15372 (defun org-agenda-files (&optional unrestricted archives)
15373 "Get the list of agenda files.
15374 Optional UNRESTRICTED means return the full list even if a restriction
15375 is currently in place.
15376 When ARCHIVES is t, include all archive files that are really being
15377 used by the agenda files. If ARCHIVE is `ifmode', do this only if
15378 `org-agenda-archives-mode' is t."
15379 (let ((files
15380 (cond
15381 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
15382 ((stringp org-agenda-files) (org-read-agenda-file-list))
15383 ((listp org-agenda-files) org-agenda-files)
15384 (t (error "Invalid value of `org-agenda-files'")))))
15385 (setq files (apply 'append
15386 (mapcar (lambda (f)
15387 (if (file-directory-p f)
15388 (directory-files
15389 f t org-agenda-file-regexp)
15390 (list f)))
15391 files)))
15392 (when org-agenda-skip-unavailable-files
15393 (setq files (delq nil
15394 (mapcar (function
15395 (lambda (file)
15396 (and (file-readable-p file) file)))
15397 files))))
15398 (when (or (eq archives t)
15399 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
15400 (setq files (org-add-archive-files files)))
15401 files))
15403 (defun org-agenda-file-p (&optional file)
15404 "Return non-nil, if FILE is an agenda file.
15405 If FILE is omitted, use the file associated with the current
15406 buffer."
15407 (member (or file (buffer-file-name))
15408 (org-agenda-files t)))
15410 (defun org-edit-agenda-file-list ()
15411 "Edit the list of agenda files.
15412 Depending on setup, this either uses customize to edit the variable
15413 `org-agenda-files', or it visits the file that is holding the list. In the
15414 latter case, the buffer is set up in a way that saving it automatically kills
15415 the buffer and restores the previous window configuration."
15416 (interactive)
15417 (if (stringp org-agenda-files)
15418 (let ((cw (current-window-configuration)))
15419 (find-file org-agenda-files)
15420 (org-set-local 'org-window-configuration cw)
15421 (org-add-hook 'after-save-hook
15422 (lambda ()
15423 (set-window-configuration
15424 (prog1 org-window-configuration
15425 (kill-buffer (current-buffer))))
15426 (org-install-agenda-files-menu)
15427 (message "New agenda file list installed"))
15428 nil 'local)
15429 (message "%s" (substitute-command-keys
15430 "Edit list and finish with \\[save-buffer]")))
15431 (customize-variable 'org-agenda-files)))
15433 (defun org-store-new-agenda-file-list (list)
15434 "Set new value for the agenda file list and save it correctly."
15435 (if (stringp org-agenda-files)
15436 (let ((fe (org-read-agenda-file-list t)) b u)
15437 (while (setq b (find-buffer-visiting org-agenda-files))
15438 (kill-buffer b))
15439 (with-temp-file org-agenda-files
15440 (insert
15441 (mapconcat
15442 (lambda (f) ;; Keep un-expanded entries.
15443 (if (setq u (assoc f fe))
15444 (cdr u)
15446 list "\n")
15447 "\n")))
15448 (let ((org-mode-hook nil) (org-inhibit-startup t)
15449 (org-insert-mode-line-in-empty-file nil))
15450 (setq org-agenda-files list)
15451 (customize-save-variable 'org-agenda-files org-agenda-files))))
15453 (defun org-read-agenda-file-list (&optional pair-with-expansion)
15454 "Read the list of agenda files from a file.
15455 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
15456 filenames, used by `org-store-new-agenda-file-list' to write back
15457 un-expanded file names."
15458 (when (file-directory-p org-agenda-files)
15459 (error "`org-agenda-files' cannot be a single directory"))
15460 (when (stringp org-agenda-files)
15461 (with-temp-buffer
15462 (insert-file-contents org-agenda-files)
15463 (mapcar
15464 (lambda (f)
15465 (let ((e (expand-file-name (substitute-in-file-name f)
15466 org-directory)))
15467 (if pair-with-expansion
15468 (cons e f)
15469 e)))
15470 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
15472 ;;;###autoload
15473 (defun org-cycle-agenda-files ()
15474 "Cycle through the files in `org-agenda-files'.
15475 If the current buffer visits an agenda file, find the next one in the list.
15476 If the current buffer does not, find the first agenda file."
15477 (interactive)
15478 (let* ((fs (org-agenda-files t))
15479 (files (append fs (list (car fs))))
15480 (tcf (if buffer-file-name (file-truename buffer-file-name)))
15481 file)
15482 (unless files (error "No agenda files"))
15483 (catch 'exit
15484 (while (setq file (pop files))
15485 (if (equal (file-truename file) tcf)
15486 (when (car files)
15487 (find-file (car files))
15488 (throw 'exit t))))
15489 (find-file (car fs)))
15490 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
15492 (defun org-agenda-file-to-front (&optional to-end)
15493 "Move/add the current file to the top of the agenda file list.
15494 If the file is not present in the list, it is added to the front. If it is
15495 present, it is moved there. With optional argument TO-END, add/move to the
15496 end of the list."
15497 (interactive "P")
15498 (let ((org-agenda-skip-unavailable-files nil)
15499 (file-alist (mapcar (lambda (x)
15500 (cons (file-truename x) x))
15501 (org-agenda-files t)))
15502 (ctf (file-truename buffer-file-name))
15503 x had)
15504 (setq x (assoc ctf file-alist) had x)
15506 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
15507 (if to-end
15508 (setq file-alist (append (delq x file-alist) (list x)))
15509 (setq file-alist (cons x (delq x file-alist))))
15510 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
15511 (org-install-agenda-files-menu)
15512 (message "File %s to %s of agenda file list"
15513 (if had "moved" "added") (if to-end "end" "front"))))
15515 (defun org-remove-file (&optional file)
15516 "Remove current file from the list of files in variable `org-agenda-files'.
15517 These are the files which are being checked for agenda entries.
15518 Optional argument FILE means use this file instead of the current."
15519 (interactive)
15520 (let* ((org-agenda-skip-unavailable-files nil)
15521 (file (or file buffer-file-name))
15522 (true-file (file-truename file))
15523 (afile (abbreviate-file-name file))
15524 (files (delq nil (mapcar
15525 (lambda (x)
15526 (if (equal true-file
15527 (file-truename x))
15528 nil x))
15529 (org-agenda-files t)))))
15530 (if (not (= (length files) (length (org-agenda-files t))))
15531 (progn
15532 (org-store-new-agenda-file-list files)
15533 (org-install-agenda-files-menu)
15534 (message "Removed file: %s" afile))
15535 (message "File was not in list: %s (not removed)" afile))))
15537 (defun org-file-menu-entry (file)
15538 (vector file (list 'find-file file) t))
15540 (defun org-check-agenda-file (file)
15541 "Make sure FILE exists. If not, ask user what to do."
15542 (when (not (file-exists-p file))
15543 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
15544 (abbreviate-file-name file))
15545 (let ((r (downcase (read-char-exclusive))))
15546 (cond
15547 ((equal r ?r)
15548 (org-remove-file file)
15549 (throw 'nextfile t))
15550 (t (error "Abort"))))))
15552 (defun org-get-agenda-file-buffer (file)
15553 "Get a buffer visiting FILE. If the buffer needs to be created, add
15554 it to the list of buffers which might be released later."
15555 (let ((buf (org-find-base-buffer-visiting file)))
15556 (if buf
15557 buf ; just return it
15558 ;; Make a new buffer and remember it
15559 (setq buf (find-file-noselect file))
15560 (if buf (push buf org-agenda-new-buffers))
15561 buf)))
15563 (defun org-release-buffers (blist)
15564 "Release all buffers in list, asking the user for confirmation when needed.
15565 When a buffer is unmodified, it is just killed. When modified, it is saved
15566 \(if the user agrees) and then killed."
15567 (let (buf file)
15568 (while (setq buf (pop blist))
15569 (setq file (buffer-file-name buf))
15570 (when (and (buffer-modified-p buf)
15571 file
15572 (y-or-n-p (format "Save file %s? " file)))
15573 (with-current-buffer buf (save-buffer)))
15574 (kill-buffer buf))))
15576 (defun org-prepare-agenda-buffers (files)
15577 "Create buffers for all agenda files, protect archived trees and comments."
15578 (interactive)
15579 (let ((pa '(:org-archived t))
15580 (pc '(:org-comment t))
15581 (pall '(:org-archived t :org-comment t))
15582 (inhibit-read-only t)
15583 (rea (concat ":" org-archive-tag ":"))
15584 bmp file re)
15585 (save-excursion
15586 (save-restriction
15587 (while (setq file (pop files))
15588 (catch 'nextfile
15589 (if (bufferp file)
15590 (set-buffer file)
15591 (org-check-agenda-file file)
15592 (set-buffer (org-get-agenda-file-buffer file)))
15593 (widen)
15594 (setq bmp (buffer-modified-p))
15595 (org-refresh-category-properties)
15596 (setq org-todo-keywords-for-agenda
15597 (append org-todo-keywords-for-agenda org-todo-keywords-1))
15598 (setq org-done-keywords-for-agenda
15599 (append org-done-keywords-for-agenda org-done-keywords))
15600 (setq org-todo-keyword-alist-for-agenda
15601 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
15602 (setq org-drawers-for-agenda
15603 (append org-drawers-for-agenda org-drawers))
15604 (setq org-tag-alist-for-agenda
15605 (append org-tag-alist-for-agenda org-tag-alist))
15607 (save-excursion
15608 (remove-text-properties (point-min) (point-max) pall)
15609 (when org-agenda-skip-archived-trees
15610 (goto-char (point-min))
15611 (while (re-search-forward rea nil t)
15612 (if (org-on-heading-p t)
15613 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
15614 (goto-char (point-min))
15615 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
15616 (while (re-search-forward re nil t)
15617 (add-text-properties
15618 (match-beginning 0) (org-end-of-subtree t) pc)))
15619 (set-buffer-modified-p bmp)))))
15620 (setq org-todo-keywords-for-agenda
15621 (org-uniquify org-todo-keywords-for-agenda))
15622 (setq org-todo-keyword-alist-for-agenda
15623 (org-uniquify org-todo-keyword-alist-for-agenda)
15624 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
15626 ;;;; Embedded LaTeX
15628 (defvar org-cdlatex-mode-map (make-sparse-keymap)
15629 "Keymap for the minor `org-cdlatex-mode'.")
15631 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
15632 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
15633 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
15634 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
15635 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
15637 (defvar org-cdlatex-texmathp-advice-is-done nil
15638 "Flag remembering if we have applied the advice to texmathp already.")
15640 (define-minor-mode org-cdlatex-mode
15641 "Toggle the minor `org-cdlatex-mode'.
15642 This mode supports entering LaTeX environment and math in LaTeX fragments
15643 in Org-mode.
15644 \\{org-cdlatex-mode-map}"
15645 nil " OCDL" nil
15646 (when org-cdlatex-mode (require 'cdlatex))
15647 (unless org-cdlatex-texmathp-advice-is-done
15648 (setq org-cdlatex-texmathp-advice-is-done t)
15649 (defadvice texmathp (around org-math-always-on activate)
15650 "Always return t in org-mode buffers.
15651 This is because we want to insert math symbols without dollars even outside
15652 the LaTeX math segments. If Orgmode thinks that point is actually inside
15653 an embedded LaTeX fragment, let texmathp do its job.
15654 \\[org-cdlatex-mode-map]"
15655 (interactive)
15656 (let (p)
15657 (cond
15658 ((not (org-mode-p)) ad-do-it)
15659 ((eq this-command 'cdlatex-math-symbol)
15660 (setq ad-return-value t
15661 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
15663 (let ((p (org-inside-LaTeX-fragment-p)))
15664 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
15665 (setq ad-return-value t
15666 texmathp-why '("Org-mode embedded math" . 0))
15667 (if p ad-do-it)))))))))
15669 (defun turn-on-org-cdlatex ()
15670 "Unconditionally turn on `org-cdlatex-mode'."
15671 (org-cdlatex-mode 1))
15673 (defun org-inside-LaTeX-fragment-p ()
15674 "Test if point is inside a LaTeX fragment.
15675 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
15676 sequence appearing also before point.
15677 Even though the matchers for math are configurable, this function assumes
15678 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
15679 delimiters are skipped when they have been removed by customization.
15680 The return value is nil, or a cons cell with the delimiter and
15681 and the position of this delimiter.
15683 This function does a reasonably good job, but can locally be fooled by
15684 for example currency specifications. For example it will assume being in
15685 inline math after \"$22.34\". The LaTeX fragment formatter will only format
15686 fragments that are properly closed, but during editing, we have to live
15687 with the uncertainty caused by missing closing delimiters. This function
15688 looks only before point, not after."
15689 (catch 'exit
15690 (let ((pos (point))
15691 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
15692 (lim (progn
15693 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
15694 (point)))
15695 dd-on str (start 0) m re)
15696 (goto-char pos)
15697 (when dodollar
15698 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
15699 re (nth 1 (assoc "$" org-latex-regexps)))
15700 (while (string-match re str start)
15701 (cond
15702 ((= (match-end 0) (length str))
15703 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
15704 ((= (match-end 0) (- (length str) 5))
15705 (throw 'exit nil))
15706 (t (setq start (match-end 0))))))
15707 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
15708 (goto-char pos)
15709 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
15710 (and (match-beginning 2) (throw 'exit nil))
15711 ;; count $$
15712 (while (re-search-backward "\\$\\$" lim t)
15713 (setq dd-on (not dd-on)))
15714 (goto-char pos)
15715 (if dd-on (cons "$$" m))))))
15717 (defun org-inside-latex-macro-p ()
15718 "Is point inside a LaTeX macro or its arguments?"
15719 (save-match-data
15720 (org-in-regexp
15721 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
15723 (defun org-try-cdlatex-tab ()
15724 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
15725 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
15726 - inside a LaTeX fragment, or
15727 - after the first word in a line, where an abbreviation expansion could
15728 insert a LaTeX environment."
15729 (when org-cdlatex-mode
15730 (cond
15731 ((save-excursion
15732 (skip-chars-backward "a-zA-Z0-9*")
15733 (skip-chars-backward " \t")
15734 (bolp))
15735 (cdlatex-tab) t)
15736 ((org-inside-LaTeX-fragment-p)
15737 (cdlatex-tab) t)
15738 (t nil))))
15740 (defun org-cdlatex-underscore-caret (&optional arg)
15741 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
15742 Revert to the normal definition outside of these fragments."
15743 (interactive "P")
15744 (if (org-inside-LaTeX-fragment-p)
15745 (call-interactively 'cdlatex-sub-superscript)
15746 (let (org-cdlatex-mode)
15747 (call-interactively (key-binding (vector last-input-event))))))
15749 (defun org-cdlatex-math-modify (&optional arg)
15750 "Execute `cdlatex-math-modify' in LaTeX fragments.
15751 Revert to the normal definition outside of these fragments."
15752 (interactive "P")
15753 (if (org-inside-LaTeX-fragment-p)
15754 (call-interactively 'cdlatex-math-modify)
15755 (let (org-cdlatex-mode)
15756 (call-interactively (key-binding (vector last-input-event))))))
15758 (defvar org-latex-fragment-image-overlays nil
15759 "List of overlays carrying the images of latex fragments.")
15760 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
15762 (defun org-remove-latex-fragment-image-overlays ()
15763 "Remove all overlays with LaTeX fragment images in current buffer."
15764 (mapc 'delete-overlay org-latex-fragment-image-overlays)
15765 (setq org-latex-fragment-image-overlays nil))
15767 (defun org-preview-latex-fragment (&optional subtree)
15768 "Preview the LaTeX fragment at point, or all locally or globally.
15769 If the cursor is in a LaTeX fragment, create the image and overlay
15770 it over the source code. If there is no fragment at point, display
15771 all fragments in the current text, from one headline to the next. With
15772 prefix SUBTREE, display all fragments in the current subtree. With a
15773 double prefix arg \\[universal-argument] \\[universal-argument], or when \
15774 the cursor is before the first headline,
15775 display all fragments in the buffer.
15776 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
15777 (interactive "P")
15778 (org-remove-latex-fragment-image-overlays)
15779 (save-excursion
15780 (save-restriction
15781 (let (beg end at msg)
15782 (cond
15783 ((or (equal subtree '(16))
15784 (not (save-excursion
15785 (re-search-backward (concat "^" outline-regexp) nil t))))
15786 (setq beg (point-min) end (point-max)
15787 msg "Creating images for buffer...%s"))
15788 ((equal subtree '(4))
15789 (org-back-to-heading)
15790 (setq beg (point) end (org-end-of-subtree t)
15791 msg "Creating images for subtree...%s"))
15793 (if (setq at (org-inside-LaTeX-fragment-p))
15794 (goto-char (max (point-min) (- (cdr at) 2)))
15795 (org-back-to-heading))
15796 (setq beg (point) end (progn (outline-next-heading) (point))
15797 msg (if at "Creating image...%s"
15798 "Creating images for entry...%s"))))
15799 (message msg "")
15800 (narrow-to-region beg end)
15801 (goto-char beg)
15802 (org-format-latex
15803 (concat "ltxpng/" (file-name-sans-extension
15804 (file-name-nondirectory
15805 buffer-file-name)))
15806 default-directory 'overlays msg at 'forbuffer)
15807 (message msg "done. Use `C-c C-c' to remove images.")))))
15809 (defvar org-latex-regexps
15810 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
15811 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
15812 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
15813 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
15814 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
15815 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
15816 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
15817 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
15818 "Regular expressions for matching embedded LaTeX.")
15820 (defun org-format-latex (prefix &optional dir overlays msg at
15821 forbuffer protect-only)
15822 "Replace LaTeX fragments with links to an image, and produce images.
15823 Some of the options can be changed using the variable
15824 `org-format-latex-options'."
15825 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
15826 (let* ((prefixnodir (file-name-nondirectory prefix))
15827 (absprefix (expand-file-name prefix dir))
15828 (todir (file-name-directory absprefix))
15829 (opt org-format-latex-options)
15830 (matchers (plist-get opt :matchers))
15831 (re-list org-latex-regexps)
15832 (org-format-latex-header-extra
15833 (plist-get (org-infile-export-plist) :latex-header-extra))
15834 (cnt 0) txt hash link beg end re e checkdir
15835 executables-checked
15836 m n block linkfile movefile ov)
15837 ;; Check the different regular expressions
15838 (while (setq e (pop re-list))
15839 (setq m (car e) re (nth 1 e) n (nth 2 e)
15840 block (if (nth 3 e) "\n\n" ""))
15841 (when (member m matchers)
15842 (goto-char (point-min))
15843 (while (re-search-forward re nil t)
15844 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
15845 (not (get-text-property (match-beginning n)
15846 'org-protected))
15847 (or (not overlays)
15848 (not (eq (get-char-property (match-beginning n)
15849 'org-overlay-type)
15850 'org-latex-overlay))))
15851 (if protect-only
15852 (add-text-properties (match-beginning n) (match-end n)
15853 '(org-protected t))
15854 (setq txt (match-string n)
15855 beg (match-beginning n) end (match-end n)
15856 cnt (1+ cnt))
15857 (let (print-length print-level) ; make sure full list is printed
15858 (setq hash (sha1 (prin1-to-string
15859 (list org-format-latex-header
15860 org-format-latex-header-extra
15861 org-export-latex-default-packages-alist
15862 org-export-latex-packages-alist
15863 org-format-latex-options
15864 forbuffer txt)))
15865 linkfile (format "%s_%s.png" prefix hash)
15866 movefile (format "%s_%s.png" absprefix hash)))
15867 (setq link (concat block "[[file:" linkfile "]]" block))
15868 (if msg (message msg cnt))
15869 (goto-char beg)
15870 (unless checkdir ; make sure the directory exists
15871 (setq checkdir t)
15872 (or (file-directory-p todir) (make-directory todir)))
15874 (unless executables-checked
15875 (org-check-external-command
15876 "latex" "needed to convert LaTeX fragments to images")
15877 (org-check-external-command
15878 "dvipng" "needed to convert LaTeX fragments to images")
15879 (setq executables-checked t))
15881 (unless (file-exists-p movefile)
15882 (org-create-formula-image
15883 txt movefile opt forbuffer))
15884 (if overlays
15885 (progn
15886 (mapc (lambda (o)
15887 (if (eq (overlay-get o 'org-overlay-type)
15888 'org-latex-overlay)
15889 (delete-overlay o)))
15890 (overlays-in beg end))
15891 (setq ov (make-overlay beg end))
15892 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
15893 (if (featurep 'xemacs)
15894 (progn
15895 (overlay-put ov 'invisible t)
15896 (overlay-put
15897 ov 'end-glyph
15898 (make-glyph (vector 'png :file movefile))))
15899 (overlay-put
15900 ov 'display
15901 (list 'image :type 'png :file movefile :ascent 'center)))
15902 (push ov org-latex-fragment-image-overlays)
15903 (goto-char end))
15904 (delete-region beg end)
15905 (insert (org-add-props link
15906 (list 'org-latex-src
15907 (replace-regexp-in-string "\"" "" txt))))))))))))
15909 ;; This function borrows from Ganesh Swami's latex2png.el
15910 (defun org-create-formula-image (string tofile options buffer)
15911 "This calls dvipng."
15912 (require 'org-latex)
15913 (let* ((tmpdir (if (featurep 'xemacs)
15914 (temp-directory)
15915 temporary-file-directory))
15916 (texfilebase (make-temp-name
15917 (expand-file-name "orgtex" tmpdir)))
15918 (texfile (concat texfilebase ".tex"))
15919 (dvifile (concat texfilebase ".dvi"))
15920 (pngfile (concat texfilebase ".png"))
15921 (fnh (if (featurep 'xemacs)
15922 (font-height (get-face-font 'default))
15923 (face-attribute 'default :height nil)))
15924 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
15925 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
15926 (fg (or (plist-get options (if buffer :foreground :html-foreground))
15927 "Black"))
15928 (bg (or (plist-get options (if buffer :background :html-background))
15929 "Transparent")))
15930 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
15931 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
15932 (with-temp-file texfile
15933 (insert (org-splice-latex-header
15934 org-format-latex-header
15935 org-export-latex-default-packages-alist
15936 org-export-latex-packages-alist t
15937 org-format-latex-header-extra))
15938 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
15939 (require 'org-latex)
15940 (org-export-latex-fix-inputenc))
15941 (let ((dir default-directory))
15942 (condition-case nil
15943 (progn
15944 (cd tmpdir)
15945 (call-process "latex" nil nil nil texfile))
15946 (error nil))
15947 (cd dir))
15948 (if (not (file-exists-p dvifile))
15949 (progn (message "Failed to create dvi file from %s" texfile) nil)
15950 (condition-case nil
15951 (call-process "dvipng" nil nil nil
15952 "-fg" fg "-bg" bg
15953 "-D" dpi
15954 ;;"-x" scale "-y" scale
15955 "-T" "tight"
15956 "-o" pngfile
15957 dvifile)
15958 (error nil))
15959 (if (not (file-exists-p pngfile))
15960 (if org-format-latex-signal-error
15961 (error "Failed to create png file from %s" texfile)
15962 (message "Failed to create png file from %s" texfile)
15963 nil)
15964 ;; Use the requested file name and clean up
15965 (copy-file pngfile tofile 'replace)
15966 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
15967 (delete-file (concat texfilebase e)))
15968 pngfile))))
15970 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
15971 "Fill a LaTeX header template TPL.
15972 In the template, the following place holders will be recognized:
15974 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
15975 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
15976 [PACKAGES] \\usepackage statements for PKG
15977 [NO-PACKAGES] do not include PKG
15978 [EXTRA] the string EXTRA
15979 [NO-EXTRA] do not include EXTRA
15981 For backward compatibility, if both the positive and the negative place
15982 holder is missing, the positive one (without the \"NO-\") will be
15983 assumed to be present at the end of the template.
15984 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
15985 EXTRA is a string.
15986 SNIPPETS-P indicates if this is run to create snippet images for HTML."
15987 (let (rpl (end ""))
15988 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
15989 (setq rpl (if (or (match-end 1) (not def-pkg))
15990 "" (org-latex-packages-to-string def-pkg snippets-p t))
15991 tpl (replace-match rpl t t tpl))
15992 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
15994 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
15995 (setq rpl (if (or (match-end 1) (not pkg))
15996 "" (org-latex-packages-to-string pkg snippets-p t))
15997 tpl (replace-match rpl t t tpl))
15998 (if pkg (setq end
15999 (concat end "\n"
16000 (org-latex-packages-to-string pkg snippets-p)))))
16002 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
16003 (setq rpl (if (or (match-end 1) (not extra))
16004 "" (concat extra "\n"))
16005 tpl (replace-match rpl t t tpl))
16006 (if (and extra (string-match "\\S-" extra))
16007 (setq end (concat end "\n" extra))))
16009 (if (string-match "\\S-" end)
16010 (concat tpl "\n" end)
16011 tpl)))
16013 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
16014 "Turn an alist of packages into a string with the \\usepackage macros."
16015 (setq pkg (mapconcat (lambda(p)
16016 (cond
16017 ((stringp p) p)
16018 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
16019 (format "%% Package %s omitted" (cadr p)))
16020 ((equal "" (car p))
16021 (format "\\usepackage{%s}" (cadr p)))
16023 (format "\\usepackage[%s]{%s}"
16024 (car p) (cadr p)))))
16026 "\n"))
16027 (if newline (concat pkg "\n") pkg))
16029 (defun org-dvipng-color (attr)
16030 "Return an rgb color specification for dvipng."
16031 (apply 'format "rgb %s %s %s"
16032 (mapcar 'org-normalize-color
16033 (color-values (face-attribute 'default attr nil)))))
16035 (defun org-normalize-color (value)
16036 "Return string to be used as color value for an RGB component."
16037 (format "%g" (/ value 65535.0)))
16039 ;; Image display
16042 (defvar org-inline-image-overlays nil)
16043 (make-variable-buffer-local 'org-inline-image-overlays)
16045 (defun org-toggle-inline-images (&optional include-linked)
16046 "Toggle the display of inline images.
16047 INCLUDE-LINKED is passed to `org-display-inline-images'."
16048 (interactive "P")
16049 (if org-inline-image-overlays
16050 (progn
16051 (org-remove-inline-images)
16052 (message "Inline image display turned off"))
16053 (org-display-inline-images include-linked)
16054 (if org-inline-image-overlays
16055 (message "%d images displayed inline"
16056 (length org-inline-image-overlays))
16057 (message "No images to display inline"))))
16059 (defun org-display-inline-images (&optional include-linked refresh beg end)
16060 "Display inline images.
16061 Normally only links without a description part are inlined, because this
16062 is how it will work for export. When INCLUDE-LINKED is set, also links
16063 with a description part will be inlined. This can be nice for a quick
16064 look at those images, but it does not reflect what exported files will look
16065 like.
16066 When REFRESH is set, refresh existing images between BEG and END.
16067 This will create new image displays only if necessary.
16068 BEG and END default to the buffer boundaries."
16069 (interactive "P")
16070 (unless refresh
16071 (org-remove-inline-images)
16072 (clear-image-cache))
16073 (save-excursion
16074 (save-restriction
16075 (widen)
16076 (setq beg (or beg (point-min)) end (or end (point-max)))
16077 (goto-char (point-min))
16078 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([-+~.:/\\_0-9a-zA-Z ]+"
16079 (substring (org-image-file-name-regexp) 0 -2)
16080 "\\)\\]" (if include-linked "" "\\]")))
16081 old file ov img)
16082 (while (re-search-forward re end t)
16083 (setq old (get-char-property-and-overlay (match-beginning 1)
16084 'org-image-overlay))
16085 (setq file (expand-file-name
16086 (concat (or (match-string 3) "") (match-string 4))))
16087 (when (file-exists-p file)
16088 (if (and (car-safe old) refresh)
16089 (image-refresh (overlay-get (cdr old) 'display))
16090 (setq img (create-image file))
16091 (when img
16092 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
16093 (overlay-put ov 'display img)
16094 (overlay-put ov 'face 'default)
16095 (overlay-put ov 'org-image-overlay t)
16096 (overlay-put ov 'modification-hooks
16097 (list 'org-display-inline-modification-hook))
16098 (push ov org-inline-image-overlays)))))))))
16100 (defun org-display-inline-modification-hook (ov after beg end &optional len)
16101 "Remove inline-display overlay if a corresponding region is modified."
16102 (let ((inhibit-modification-hooks t))
16103 (when (and ov after)
16104 (delete ov org-inline-image-overlays)
16105 (delete-overlay ov))))
16107 (defun org-remove-inline-images ()
16108 "Remove inline display of images."
16109 (interactive)
16110 (mapc 'delete-overlay org-inline-image-overlays)
16111 (setq org-inline-image-overlays nil))
16113 ;;;; Key bindings
16115 ;; Make `C-c C-x' a prefix key
16116 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
16118 ;; TAB key with modifiers
16119 (org-defkey org-mode-map "\C-i" 'org-cycle)
16120 (org-defkey org-mode-map [(tab)] 'org-cycle)
16121 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
16122 (org-defkey org-mode-map [(meta tab)] 'org-complete)
16123 (org-defkey org-mode-map "\M-\t" 'org-complete)
16124 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
16125 ;; The following line is necessary under Suse GNU/Linux
16126 (unless (featurep 'xemacs)
16127 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
16128 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
16129 (define-key org-mode-map [backtab] 'org-shifttab)
16131 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
16132 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
16133 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
16135 ;; Cursor keys with modifiers
16136 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
16137 (org-defkey org-mode-map [(meta right)] 'org-metaright)
16138 (org-defkey org-mode-map [(meta up)] 'org-metaup)
16139 (org-defkey org-mode-map [(meta down)] 'org-metadown)
16141 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
16142 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
16143 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
16144 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
16146 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
16147 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
16148 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
16149 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
16151 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
16152 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
16154 ;; Babel keys
16155 (define-key org-mode-map org-babel-key-prefix org-babel-map)
16156 (mapc (lambda (pair)
16157 (define-key org-babel-map (car pair) (cdr pair)))
16158 org-babel-key-bindings)
16160 ;;; Extra keys for tty access.
16161 ;; We only set them when really needed because otherwise the
16162 ;; menus don't show the simple keys
16164 (when (or org-use-extra-keys
16165 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
16166 (not window-system))
16167 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
16168 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
16169 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
16170 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
16171 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
16172 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
16173 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
16174 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
16175 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
16176 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
16177 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
16178 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
16179 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
16180 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
16181 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
16182 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
16183 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
16184 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
16185 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
16186 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
16187 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
16188 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
16189 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
16190 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
16191 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
16192 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
16193 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
16194 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
16196 ;; All the other keys
16198 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
16199 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
16200 (if (boundp 'narrow-map)
16201 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
16202 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
16203 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
16204 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
16205 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
16206 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
16207 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
16208 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
16209 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
16210 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
16211 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
16212 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
16213 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
16214 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
16215 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
16216 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
16217 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
16218 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
16219 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
16220 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
16221 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
16222 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
16223 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
16224 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
16225 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
16226 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
16227 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
16228 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
16229 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
16230 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
16231 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
16232 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
16233 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
16234 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
16235 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
16236 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
16237 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
16238 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
16239 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
16240 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
16241 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
16242 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
16243 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
16244 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
16245 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
16246 (org-defkey org-mode-map "\C-c^" 'org-sort)
16247 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
16248 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
16249 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
16250 (org-defkey org-mode-map "\C-m" 'org-return)
16251 (org-defkey org-mode-map "\C-j" 'org-return-indent)
16252 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
16253 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
16254 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
16255 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
16256 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
16257 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
16258 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
16259 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
16260 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
16261 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
16262 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
16263 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
16264 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
16265 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
16266 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
16267 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
16268 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
16269 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
16270 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
16271 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
16273 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
16274 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
16275 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
16276 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
16278 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
16279 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
16280 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
16281 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
16282 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
16283 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
16284 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
16285 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
16286 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
16287 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
16288 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
16289 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
16290 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
16291 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
16292 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
16293 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
16294 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
16296 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
16297 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
16298 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
16299 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
16301 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
16303 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
16305 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
16306 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
16308 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
16311 (when (featurep 'xemacs)
16312 (org-defkey org-mode-map 'button3 'popup-mode-menu))
16315 (defconst org-speed-commands-default
16317 ("Outline Navigation")
16318 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
16319 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
16320 ("f" . (org-speed-move-safe 'org-forward-same-level))
16321 ("b" . (org-speed-move-safe 'org-backward-same-level))
16322 ("u" . (org-speed-move-safe 'outline-up-heading))
16323 ("j" . org-goto)
16324 ("g" . (org-refile t))
16325 ("Outline Visibility")
16326 ("c" . org-cycle)
16327 ("C" . org-shifttab)
16328 (" " . org-display-outline-path)
16329 ("Outline Structure Editing")
16330 ("U" . org-shiftmetaup)
16331 ("D" . org-shiftmetadown)
16332 ("r" . org-metaright)
16333 ("l" . org-metaleft)
16334 ("R" . org-shiftmetaright)
16335 ("L" . org-shiftmetaleft)
16336 ("i" . (progn (forward-char 1) (call-interactively
16337 'org-insert-heading-respect-content)))
16338 ("^" . org-sort)
16339 ("w" . org-refile)
16340 ("a" . org-archive-subtree-default-with-confirmation)
16341 ("." . outline-mark-subtree)
16342 ("Clock Commands")
16343 ("I" . org-clock-in)
16344 ("O" . org-clock-out)
16345 ("Meta Data Editing")
16346 ("t" . org-todo)
16347 ("0" . (org-priority ?\ ))
16348 ("1" . (org-priority ?A))
16349 ("2" . (org-priority ?B))
16350 ("3" . (org-priority ?C))
16351 (";" . org-set-tags-command)
16352 ("e" . org-set-effort)
16353 ("Agenda Views etc")
16354 ("v" . org-agenda)
16355 ("/" . org-sparse-tree)
16356 ("Misc")
16357 ("o" . org-open-at-point)
16358 ("?" . org-speed-command-help)
16360 "The default speed commands.")
16362 (defun org-print-speed-command (e)
16363 (if (> (length (car e)) 1)
16364 (progn
16365 (princ "\n")
16366 (princ (car e))
16367 (princ "\n")
16368 (princ (make-string (length (car e)) ?-))
16369 (princ "\n"))
16370 (princ (car e))
16371 (princ " ")
16372 (if (symbolp (cdr e))
16373 (princ (symbol-name (cdr e)))
16374 (prin1 (cdr e)))
16375 (princ "\n")))
16377 (defun org-speed-command-help ()
16378 "Show the available speed commands."
16379 (interactive)
16380 (if (not org-use-speed-commands)
16381 (error "Speed commands are not activated, customize `org-use-speed-commands'")
16382 (with-output-to-temp-buffer "*Help*"
16383 (princ "User-defined Speed commands\n===========================\n")
16384 (mapc 'org-print-speed-command org-speed-commands-user)
16385 (princ "\n")
16386 (princ "Built-in Speed commands\n=======================\n")
16387 (mapc 'org-print-speed-command org-speed-commands-default))
16388 (with-current-buffer "*Help*"
16389 (setq truncate-lines t))))
16391 (defun org-speed-move-safe (cmd)
16392 "Execute CMD, but make sure that the cursor always ends up in a headline.
16393 If not, return to the original position and throw an error."
16394 (interactive)
16395 (let ((pos (point)))
16396 (call-interactively cmd)
16397 (unless (and (bolp) (org-on-heading-p))
16398 (goto-char pos)
16399 (error "Boundary reached while executing %s" cmd))))
16401 (defvar org-self-insert-command-undo-counter 0)
16403 (defvar org-table-auto-blank-field) ; defined in org-table.el
16404 (defvar org-speed-command nil)
16405 (defun org-self-insert-command (N)
16406 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
16407 If the cursor is in a table looking at whitespace, the whitespace is
16408 overwritten, and the table is not marked as requiring realignment."
16409 (interactive "p")
16410 (cond
16411 ((and org-use-speed-commands
16412 (or (and (bolp) (looking-at outline-regexp))
16413 (and (functionp org-use-speed-commands)
16414 (funcall org-use-speed-commands)))
16415 (setq
16416 org-speed-command
16417 (or (cdr (assoc (this-command-keys) org-speed-commands-user))
16418 (cdr (assoc (this-command-keys) org-speed-commands-default)))))
16419 (cond
16420 ((commandp org-speed-command)
16421 (setq this-command org-speed-command)
16422 (call-interactively org-speed-command))
16423 ((functionp org-speed-command)
16424 (funcall org-speed-command))
16425 ((and org-speed-command (listp org-speed-command))
16426 (eval org-speed-command))
16427 (t (let (org-use-speed-commands)
16428 (call-interactively 'org-self-insert-command)))))
16429 ((and
16430 (org-table-p)
16431 (progn
16432 ;; check if we blank the field, and if that triggers align
16433 (and (featurep 'org-table) org-table-auto-blank-field
16434 (member last-command
16435 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
16436 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
16437 ;; got extra space, this field does not determine column width
16438 (let (org-table-may-need-update) (org-table-blank-field))
16439 ;; no extra space, this field may determine column width
16440 (org-table-blank-field)))
16442 (eq N 1)
16443 (looking-at "[^|\n]* |"))
16444 (let (org-table-may-need-update)
16445 (goto-char (1- (match-end 0)))
16446 (delete-backward-char 1)
16447 (goto-char (match-beginning 0))
16448 (self-insert-command N)))
16450 (setq org-table-may-need-update t)
16451 (self-insert-command N)
16452 (org-fix-tags-on-the-fly)
16453 (if org-self-insert-cluster-for-undo
16454 (if (not (eq last-command 'org-self-insert-command))
16455 (setq org-self-insert-command-undo-counter 1)
16456 (if (>= org-self-insert-command-undo-counter 20)
16457 (setq org-self-insert-command-undo-counter 1)
16458 (and (> org-self-insert-command-undo-counter 0)
16459 buffer-undo-list
16460 (not (cadr buffer-undo-list)) ; remove nil entry
16461 (setcdr buffer-undo-list (cddr buffer-undo-list)))
16462 (setq org-self-insert-command-undo-counter
16463 (1+ org-self-insert-command-undo-counter))))))))
16465 (defun org-fix-tags-on-the-fly ()
16466 (when (and (equal (char-after (point-at-bol)) ?*)
16467 (org-on-heading-p))
16468 (org-align-tags-here org-tags-column)))
16470 (defun org-delete-backward-char (N)
16471 "Like `delete-backward-char', insert whitespace at field end in tables.
16472 When deleting backwards, in tables this function will insert whitespace in
16473 front of the next \"|\" separator, to keep the table aligned. The table will
16474 still be marked for re-alignment if the field did fill the entire column,
16475 because, in this case the deletion might narrow the column."
16476 (interactive "p")
16477 (if (and (org-table-p)
16478 (eq N 1)
16479 (string-match "|" (buffer-substring (point-at-bol) (point)))
16480 (looking-at ".*?|"))
16481 (let ((pos (point))
16482 (noalign (looking-at "[^|\n\r]* |"))
16483 (c org-table-may-need-update))
16484 (backward-delete-char N)
16485 (skip-chars-forward "^|")
16486 (insert " ")
16487 (goto-char (1- pos))
16488 ;; noalign: if there were two spaces at the end, this field
16489 ;; does not determine the width of the column.
16490 (if noalign (setq org-table-may-need-update c)))
16491 (backward-delete-char N)
16492 (org-fix-tags-on-the-fly)))
16494 (defun org-delete-char (N)
16495 "Like `delete-char', but insert whitespace at field end in tables.
16496 When deleting characters, in tables this function will insert whitespace in
16497 front of the next \"|\" separator, to keep the table aligned. The table will
16498 still be marked for re-alignment if the field did fill the entire column,
16499 because, in this case the deletion might narrow the column."
16500 (interactive "p")
16501 (if (and (org-table-p)
16502 (not (bolp))
16503 (not (= (char-after) ?|))
16504 (eq N 1))
16505 (if (looking-at ".*?|")
16506 (let ((pos (point))
16507 (noalign (looking-at "[^|\n\r]* |"))
16508 (c org-table-may-need-update))
16509 (replace-match (concat
16510 (substring (match-string 0) 1 -1)
16511 " |"))
16512 (goto-char pos)
16513 ;; noalign: if there were two spaces at the end, this field
16514 ;; does not determine the width of the column.
16515 (if noalign (setq org-table-may-need-update c)))
16516 (delete-char N))
16517 (delete-char N)
16518 (org-fix-tags-on-the-fly)))
16520 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
16521 (put 'org-self-insert-command 'delete-selection t)
16522 (put 'orgtbl-self-insert-command 'delete-selection t)
16523 (put 'org-delete-char 'delete-selection 'supersede)
16524 (put 'org-delete-backward-char 'delete-selection 'supersede)
16525 (put 'org-yank 'delete-selection 'yank)
16527 ;; Make `flyspell-mode' delay after some commands
16528 (put 'org-self-insert-command 'flyspell-delayed t)
16529 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
16530 (put 'org-delete-char 'flyspell-delayed t)
16531 (put 'org-delete-backward-char 'flyspell-delayed t)
16533 ;; Make pabbrev-mode expand after org-mode commands
16534 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
16535 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
16537 ;; How to do this: Measure non-white length of current string
16538 ;; If equal to column width, we should realign.
16540 (defun org-remap (map &rest commands)
16541 "In MAP, remap the functions given in COMMANDS.
16542 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
16543 (let (new old)
16544 (while commands
16545 (setq old (pop commands) new (pop commands))
16546 (if (fboundp 'command-remapping)
16547 (org-defkey map (vector 'remap old) new)
16548 (substitute-key-definition old new map global-map)))))
16550 (when (eq org-enable-table-editor 'optimized)
16551 ;; If the user wants maximum table support, we need to hijack
16552 ;; some standard editing functions
16553 (org-remap org-mode-map
16554 'self-insert-command 'org-self-insert-command
16555 'delete-char 'org-delete-char
16556 'delete-backward-char 'org-delete-backward-char)
16557 (org-defkey org-mode-map "|" 'org-force-self-insert))
16559 (defvar org-ctrl-c-ctrl-c-hook nil
16560 "Hook for functions attaching themselves to `C-c C-c'.
16561 This can be used to add additional functionality to the C-c C-c key which
16562 executes context-dependent commands.
16563 Each function will be called with no arguments. The function must check
16564 if the context is appropriate for it to act. If yes, it should do its
16565 thing and then return a non-nil value. If the context is wrong,
16566 just do nothing and return nil.")
16568 (defvar org-tab-first-hook nil
16569 "Hook for functions to attach themselves to TAB.
16570 See `org-ctrl-c-ctrl-c-hook' for more information.
16571 This hook runs as the first action when TAB is pressed, even before
16572 `org-cycle' messes around with the `outline-regexp' to cater for
16573 inline tasks and plain list item folding.
16574 If any function in this hook returns t, any other actions that
16575 would have been caused by TAB (such as table field motion or visibility
16576 cycling) will not occur.")
16578 (defvar org-tab-after-check-for-table-hook nil
16579 "Hook for functions to attach themselves to TAB.
16580 See `org-ctrl-c-ctrl-c-hook' for more information.
16581 This hook runs after it has been established that the cursor is not in a
16582 table, but before checking if the cursor is in a headline or if global cycling
16583 should be done.
16584 If any function in this hook returns t, not other actions like visibility
16585 cycling will be done.")
16587 (defvar org-tab-after-check-for-cycling-hook nil
16588 "Hook for functions to attach themselves to TAB.
16589 See `org-ctrl-c-ctrl-c-hook' for more information.
16590 This hook runs after it has been established that not table field motion and
16591 not visibility should be done because of current context. This is probably
16592 the place where a package like yasnippets can hook in.")
16594 (defvar org-tab-before-tab-emulation-hook nil
16595 "Hook for functions to attach themselves to TAB.
16596 See `org-ctrl-c-ctrl-c-hook' for more information.
16597 This hook runs after every other options for TAB have been exhausted, but
16598 before indentation and \t insertion takes place.")
16600 (defvar org-metaleft-hook nil
16601 "Hook for functions attaching themselves to `M-left'.
16602 See `org-ctrl-c-ctrl-c-hook' for more information.")
16603 (defvar org-metaright-hook nil
16604 "Hook for functions attaching themselves to `M-right'.
16605 See `org-ctrl-c-ctrl-c-hook' for more information.")
16606 (defvar org-metaup-hook nil
16607 "Hook for functions attaching themselves to `M-up'.
16608 See `org-ctrl-c-ctrl-c-hook' for more information.")
16609 (defvar org-metadown-hook nil
16610 "Hook for functions attaching themselves to `M-down'.
16611 See `org-ctrl-c-ctrl-c-hook' for more information.")
16612 (defvar org-shiftmetaleft-hook nil
16613 "Hook for functions attaching themselves to `M-S-left'.
16614 See `org-ctrl-c-ctrl-c-hook' for more information.")
16615 (defvar org-shiftmetaright-hook nil
16616 "Hook for functions attaching themselves to `M-S-right'.
16617 See `org-ctrl-c-ctrl-c-hook' for more information.")
16618 (defvar org-shiftmetaup-hook nil
16619 "Hook for functions attaching themselves to `M-S-up'.
16620 See `org-ctrl-c-ctrl-c-hook' for more information.")
16621 (defvar org-shiftmetadown-hook nil
16622 "Hook for functions attaching themselves to `M-S-down'.
16623 See `org-ctrl-c-ctrl-c-hook' for more information.")
16624 (defvar org-metareturn-hook nil
16625 "Hook for functions attaching themselves to `M-RET'.
16626 See `org-ctrl-c-ctrl-c-hook' for more information.")
16627 (defvar org-shiftup-hook nil
16628 "Hook for functions attaching themselves to `S-up'.
16629 See `org-ctrl-c-ctrl-c-hook' for more information.")
16630 (defvar org-shiftup-final-hook nil
16631 "Hook for functions attaching themselves to `S-up'.
16632 This one runs after all other options except shift-select have been excluded.
16633 See `org-ctrl-c-ctrl-c-hook' for more information.")
16634 (defvar org-shiftdown-hook nil
16635 "Hook for functions attaching themselves to `S-down'.
16636 See `org-ctrl-c-ctrl-c-hook' for more information.")
16637 (defvar org-shiftdown-final-hook nil
16638 "Hook for functions attaching themselves to `S-down'.
16639 This one runs after all other options except shift-select have been excluded.
16640 See `org-ctrl-c-ctrl-c-hook' for more information.")
16641 (defvar org-shiftleft-hook nil
16642 "Hook for functions attaching themselves to `S-left'.
16643 See `org-ctrl-c-ctrl-c-hook' for more information.")
16644 (defvar org-shiftleft-final-hook nil
16645 "Hook for functions attaching themselves to `S-left'.
16646 This one runs after all other options except shift-select have been excluded.
16647 See `org-ctrl-c-ctrl-c-hook' for more information.")
16648 (defvar org-shiftright-hook nil
16649 "Hook for functions attaching themselves to `S-right'.
16650 See `org-ctrl-c-ctrl-c-hook' for more information.")
16651 (defvar org-shiftright-final-hook nil
16652 "Hook for functions attaching themselves to `S-right'.
16653 This one runs after all other options except shift-select have been excluded.
16654 See `org-ctrl-c-ctrl-c-hook' for more information.")
16656 (defun org-modifier-cursor-error ()
16657 "Throw an error, a modified cursor command was applied in wrong context."
16658 (error "This command is active in special context like tables, headlines or items"))
16660 (defun org-shiftselect-error ()
16661 "Throw an error because Shift-Cursor command was applied in wrong context."
16662 (if (and (boundp 'shift-select-mode) shift-select-mode)
16663 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
16664 (error "This command works only in special context like headlines or timestamps")))
16666 (defun org-call-for-shift-select (cmd)
16667 (let ((this-command-keys-shift-translated t))
16668 (call-interactively cmd)))
16670 (defun org-shifttab (&optional arg)
16671 "Global visibility cycling or move to previous table field.
16672 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
16673 on context.
16674 See the individual commands for more information."
16675 (interactive "P")
16676 (cond
16677 ((org-at-table-p) (call-interactively 'org-table-previous-field))
16678 ((integerp arg)
16679 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
16680 (message "Content view to level: %d" arg)
16681 (org-content (prefix-numeric-value arg2))
16682 (setq org-cycle-global-status 'overview)))
16683 (t (call-interactively 'org-global-cycle))))
16685 (defun org-shiftmetaleft ()
16686 "Promote subtree or delete table column.
16687 Calls `org-promote-subtree', `org-outdent-item',
16688 or `org-table-delete-column', depending on context.
16689 See the individual commands for more information."
16690 (interactive)
16691 (cond
16692 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
16693 ((org-at-table-p) (call-interactively 'org-table-delete-column))
16694 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
16695 ((org-at-item-p) (call-interactively 'org-outdent-item-tree))
16696 (t (org-modifier-cursor-error))))
16698 (defun org-shiftmetaright ()
16699 "Demote subtree or insert table column.
16700 Calls `org-demote-subtree', `org-indent-item',
16701 or `org-table-insert-column', depending on context.
16702 See the individual commands for more information."
16703 (interactive)
16704 (cond
16705 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
16706 ((org-at-table-p) (call-interactively 'org-table-insert-column))
16707 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
16708 ((org-at-item-p) (call-interactively 'org-indent-item-tree))
16709 (t (org-modifier-cursor-error))))
16711 (defun org-shiftmetaup (&optional arg)
16712 "Move subtree up or kill table row.
16713 Calls `org-move-subtree-up' or `org-table-kill-row' or
16714 `org-move-item-up' depending on context. See the individual commands
16715 for more information."
16716 (interactive "P")
16717 (cond
16718 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
16719 ((org-at-table-p) (call-interactively 'org-table-kill-row))
16720 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
16721 ((org-at-item-p) (call-interactively 'org-move-item-up))
16722 (t (org-modifier-cursor-error))))
16724 (defun org-shiftmetadown (&optional arg)
16725 "Move subtree down or insert table row.
16726 Calls `org-move-subtree-down' or `org-table-insert-row' or
16727 `org-move-item-down', depending on context. See the individual
16728 commands for more information."
16729 (interactive "P")
16730 (cond
16731 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
16732 ((org-at-table-p) (call-interactively 'org-table-insert-row))
16733 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
16734 ((org-at-item-p) (call-interactively 'org-move-item-down))
16735 (t (org-modifier-cursor-error))))
16737 (defsubst org-hidden-tree-error ()
16738 (error
16739 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
16741 (defun org-metaleft (&optional arg)
16742 "Promote heading or move table column to left.
16743 Calls `org-do-promote' or `org-table-move-column', depending on context.
16744 With no specific context, calls the Emacs default `backward-word'.
16745 See the individual commands for more information."
16746 (interactive "P")
16747 (cond
16748 ((run-hook-with-args-until-success 'org-metaleft-hook))
16749 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
16750 ((or (org-on-heading-p)
16751 (and (org-region-active-p)
16752 (save-excursion
16753 (goto-char (region-beginning))
16754 (org-on-heading-p))))
16755 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
16756 (call-interactively 'org-do-promote))
16757 ((or (org-at-item-p)
16758 (and (org-region-active-p)
16759 (save-excursion
16760 (goto-char (region-beginning))
16761 (org-at-item-p))))
16762 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
16763 (call-interactively 'org-outdent-item))
16764 (t (call-interactively 'backward-word))))
16766 (defun org-metaright (&optional arg)
16767 "Demote subtree or move table column to right.
16768 Calls `org-do-demote' or `org-table-move-column', depending on context.
16769 With no specific context, calls the Emacs default `forward-word'.
16770 See the individual commands for more information."
16771 (interactive "P")
16772 (cond
16773 ((run-hook-with-args-until-success 'org-metaright-hook))
16774 ((org-at-table-p) (call-interactively 'org-table-move-column))
16775 ((or (org-on-heading-p)
16776 (and (org-region-active-p)
16777 (save-excursion
16778 (goto-char (region-beginning))
16779 (org-on-heading-p))))
16780 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
16781 (call-interactively 'org-do-demote))
16782 ((or (org-at-item-p)
16783 (and (org-region-active-p)
16784 (save-excursion
16785 (goto-char (region-beginning))
16786 (org-at-item-p))))
16787 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
16788 (call-interactively 'org-indent-item))
16789 (t (call-interactively 'forward-word))))
16791 (defun org-check-for-hidden (what)
16792 "Check if there are hidden headlines/items in the current visual line.
16793 WHAT can be either `headlines' or `items'. If the current line is
16794 an outline or item heading and it has a folded subtree below it,
16795 this function returns t, nil otherwise."
16796 (let ((re (cond
16797 ((eq what 'headlines) (concat "^" org-outline-regexp))
16798 ((eq what 'items) (concat "^" (org-item-re t)))
16799 (t (error "This should not happen"))))
16800 beg end)
16801 (save-excursion
16802 (catch 'exit
16803 (unless (org-region-active-p)
16804 (setq beg (point-at-bol))
16805 (beginning-of-line 2)
16806 (while (and (not (eobp)) ;; this is like `next-line'
16807 (get-char-property (1- (point)) 'invisible))
16808 (beginning-of-line 2))
16809 (setq end (point))
16810 (goto-char beg)
16811 (goto-char (point-at-eol))
16812 (setq end (max end (point)))
16813 (while (re-search-forward re end t)
16814 (if (get-char-property (match-beginning 0) 'invisible)
16815 (throw 'exit t))))
16816 nil))))
16818 (defun org-metaup (&optional arg)
16819 "Move subtree up or move table row up.
16820 Calls `org-move-subtree-up' or `org-table-move-row' or
16821 `org-move-item-up', depending on context. See the individual commands
16822 for more information."
16823 (interactive "P")
16824 (cond
16825 ((run-hook-with-args-until-success 'org-metaup-hook))
16826 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
16827 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
16828 ((org-at-item-p) (call-interactively 'org-move-item-up))
16829 (t (transpose-lines 1) (beginning-of-line -1))))
16831 (defun org-metadown (&optional arg)
16832 "Move subtree down or move table row down.
16833 Calls `org-move-subtree-down' or `org-table-move-row' or
16834 `org-move-item-down', depending on context. See the individual
16835 commands for more information."
16836 (interactive "P")
16837 (cond
16838 ((run-hook-with-args-until-success 'org-metadown-hook))
16839 ((org-at-table-p) (call-interactively 'org-table-move-row))
16840 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
16841 ((org-at-item-p) (call-interactively 'org-move-item-down))
16842 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
16844 (defun org-shiftup (&optional arg)
16845 "Increase item in timestamp or increase priority of current headline.
16846 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
16847 depending on context. See the individual commands for more information."
16848 (interactive "P")
16849 (cond
16850 ((run-hook-with-args-until-success 'org-shiftup-hook))
16851 ((and org-support-shift-select (org-region-active-p))
16852 (org-call-for-shift-select 'previous-line))
16853 ((org-at-timestamp-p t)
16854 (call-interactively (if org-edit-timestamp-down-means-later
16855 'org-timestamp-down 'org-timestamp-up)))
16856 ((and (not (eq org-support-shift-select 'always))
16857 org-enable-priority-commands
16858 (org-on-heading-p))
16859 (call-interactively 'org-priority-up))
16860 ((and (not org-support-shift-select) (org-at-item-p))
16861 (call-interactively 'org-previous-item))
16862 ((org-clocktable-try-shift 'up arg))
16863 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
16864 (org-support-shift-select
16865 (org-call-for-shift-select 'previous-line))
16866 (t (org-shiftselect-error))))
16868 (defun org-shiftdown (&optional arg)
16869 "Decrease item in timestamp or decrease priority of current headline.
16870 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
16871 depending on context. See the individual commands for more information."
16872 (interactive "P")
16873 (cond
16874 ((run-hook-with-args-until-success 'org-shiftdown-hook))
16875 ((and org-support-shift-select (org-region-active-p))
16876 (org-call-for-shift-select 'next-line))
16877 ((org-at-timestamp-p t)
16878 (call-interactively (if org-edit-timestamp-down-means-later
16879 'org-timestamp-up 'org-timestamp-down)))
16880 ((and (not (eq org-support-shift-select 'always))
16881 org-enable-priority-commands
16882 (org-on-heading-p))
16883 (call-interactively 'org-priority-down))
16884 ((and (not org-support-shift-select) (org-at-item-p))
16885 (call-interactively 'org-next-item))
16886 ((org-clocktable-try-shift 'down arg))
16887 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
16888 (org-support-shift-select
16889 (org-call-for-shift-select 'next-line))
16890 (t (org-shiftselect-error))))
16892 (defun org-shiftright (&optional arg)
16893 "Cycle the thing at point or in the current line, depending on context.
16894 Depending on context, this does one of the following:
16896 - switch a timestamp at point one day into the future
16897 - on a headline, switch to the next TODO keyword.
16898 - on an item, switch entire list to the next bullet type
16899 - on a property line, switch to the next allowed value
16900 - on a clocktable definition line, move time block into the future"
16901 (interactive "P")
16902 (cond
16903 ((run-hook-with-args-until-success 'org-shiftright-hook))
16904 ((and org-support-shift-select (org-region-active-p))
16905 (org-call-for-shift-select 'forward-char))
16906 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
16907 ((and (not (eq org-support-shift-select 'always))
16908 (org-on-heading-p))
16909 (let ((org-inhibit-logging
16910 (not org-treat-S-cursor-todo-selection-as-state-change))
16911 (org-inhibit-blocking
16912 (not org-treat-S-cursor-todo-selection-as-state-change)))
16913 (org-call-with-arg 'org-todo 'right)))
16914 ((or (and org-support-shift-select
16915 (not (eq org-support-shift-select 'always))
16916 (org-at-item-bullet-p))
16917 (and (not org-support-shift-select) (org-at-item-p)))
16918 (org-call-with-arg 'org-cycle-list-bullet nil))
16919 ((and (not (eq org-support-shift-select 'always))
16920 (org-at-property-p))
16921 (call-interactively 'org-property-next-allowed-value))
16922 ((org-clocktable-try-shift 'right arg))
16923 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
16924 (org-support-shift-select
16925 (org-call-for-shift-select 'forward-char))
16926 (t (org-shiftselect-error))))
16928 (defun org-shiftleft (&optional arg)
16929 "Cycle the thing at point or in the current line, depending on context.
16930 Depending on context, this does one of the following:
16932 - switch a timestamp at point one day into the past
16933 - on a headline, switch to the previous TODO keyword.
16934 - on an item, switch entire list to the previous bullet type
16935 - on a property line, switch to the previous allowed value
16936 - on a clocktable definition line, move time block into the past"
16937 (interactive "P")
16938 (cond
16939 ((run-hook-with-args-until-success 'org-shiftleft-hook))
16940 ((and org-support-shift-select (org-region-active-p))
16941 (org-call-for-shift-select 'backward-char))
16942 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
16943 ((and (not (eq org-support-shift-select 'always))
16944 (org-on-heading-p))
16945 (let ((org-inhibit-logging
16946 (not org-treat-S-cursor-todo-selection-as-state-change))
16947 (org-inhibit-blocking
16948 (not org-treat-S-cursor-todo-selection-as-state-change)))
16949 (org-call-with-arg 'org-todo 'left)))
16950 ((or (and org-support-shift-select
16951 (not (eq org-support-shift-select 'always))
16952 (org-at-item-bullet-p))
16953 (and (not org-support-shift-select) (org-at-item-p)))
16954 (org-call-with-arg 'org-cycle-list-bullet 'previous))
16955 ((and (not (eq org-support-shift-select 'always))
16956 (org-at-property-p))
16957 (call-interactively 'org-property-previous-allowed-value))
16958 ((org-clocktable-try-shift 'left arg))
16959 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
16960 (org-support-shift-select
16961 (org-call-for-shift-select 'backward-char))
16962 (t (org-shiftselect-error))))
16964 (defun org-shiftcontrolright ()
16965 "Switch to next TODO set."
16966 (interactive)
16967 (cond
16968 ((and org-support-shift-select (org-region-active-p))
16969 (org-call-for-shift-select 'forward-word))
16970 ((and (not (eq org-support-shift-select 'always))
16971 (org-on-heading-p))
16972 (org-call-with-arg 'org-todo 'nextset))
16973 (org-support-shift-select
16974 (org-call-for-shift-select 'forward-word))
16975 (t (org-shiftselect-error))))
16977 (defun org-shiftcontrolleft ()
16978 "Switch to previous TODO set."
16979 (interactive)
16980 (cond
16981 ((and org-support-shift-select (org-region-active-p))
16982 (org-call-for-shift-select 'backward-word))
16983 ((and (not (eq org-support-shift-select 'always))
16984 (org-on-heading-p))
16985 (org-call-with-arg 'org-todo 'previousset))
16986 (org-support-shift-select
16987 (org-call-for-shift-select 'backward-word))
16988 (t (org-shiftselect-error))))
16990 (defun org-ctrl-c-ret ()
16991 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
16992 (interactive)
16993 (cond
16994 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
16995 (t (call-interactively 'org-insert-heading))))
16997 (defun org-copy-special ()
16998 "Copy region in table or copy current subtree.
16999 Calls `org-table-copy' or `org-copy-subtree', depending on context.
17000 See the individual commands for more information."
17001 (interactive)
17002 (call-interactively
17003 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
17005 (defun org-cut-special ()
17006 "Cut region in table or cut current subtree.
17007 Calls `org-table-copy' or `org-cut-subtree', depending on context.
17008 See the individual commands for more information."
17009 (interactive)
17010 (call-interactively
17011 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
17013 (defun org-paste-special (arg)
17014 "Paste rectangular region into table, or past subtree relative to level.
17015 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
17016 See the individual commands for more information."
17017 (interactive "P")
17018 (if (org-at-table-p)
17019 (org-table-paste-rectangle)
17020 (org-paste-subtree arg)))
17022 (defun org-edit-special (&optional arg)
17023 "Call a special editor for the stuff at point.
17024 When at a table, call the formula editor with `org-table-edit-formulas'.
17025 When at the first line of an src example, call `org-edit-src-code'.
17026 When in an #+include line, visit the include file. Otherwise call
17027 `ffap' to visit the file at point."
17028 (interactive)
17029 ;; possibly prep session before editing source
17030 (when arg
17031 (let* ((info (org-babel-get-src-block-info))
17032 (lang (nth 0 info))
17033 (params (nth 2 info))
17034 (session (cdr (assoc :session params))))
17035 (when (and info session) ;; we are in a source-code block with a session
17036 (funcall
17037 (intern (concat "org-babel-prep-session:" lang)) session params))))
17038 (cond ;; proceed with `org-edit-special'
17039 ((save-excursion
17040 (beginning-of-line 1)
17041 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
17042 (find-file (org-trim (match-string 1))))
17043 ((org-edit-src-code))
17044 ((org-edit-fixed-width-region))
17045 ((org-at-table.el-p)
17046 (org-edit-src-code))
17047 ((org-at-table-p)
17048 (call-interactively 'org-table-edit-formulas))
17049 (t (call-interactively 'ffap))))
17052 (defun org-ctrl-c-ctrl-c (&optional arg)
17053 "Set tags in headline, or update according to changed information at point.
17055 This command does many different things, depending on context:
17057 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
17058 this is what we do.
17060 - If the cursor is on a statistics cookie, update it.
17062 - If the cursor is in a headline, prompt for tags and insert them
17063 into the current line, aligned to `org-tags-column'. When called
17064 with prefix arg, realign all tags in the current buffer.
17066 - If the cursor is in one of the special #+KEYWORD lines, this
17067 triggers scanning the buffer for these lines and updating the
17068 information.
17070 - If the cursor is inside a table, realign the table. This command
17071 works even if the automatic table editor has been turned off.
17073 - If the cursor is on a #+TBLFM line, re-apply the formulas to
17074 the entire table.
17076 - If the cursor is at a footnote reference or definition, jump to
17077 the corresponding definition or references, respectively.
17079 - If the cursor is a the beginning of a dynamic block, update it.
17081 - If the current buffer is a remember buffer, close note and file
17082 it. A prefix argument of 1 files to the default location
17083 without further interaction. A prefix argument of 2 files to
17084 the currently clocking task.
17086 - If the cursor is on a <<<target>>>, update radio targets and corresponding
17087 links in this buffer.
17089 - If the cursor is on a numbered item in a plain list, renumber the
17090 ordered list.
17092 - If the cursor is on a checkbox, toggle it.
17094 - If the cursor is on a code block, evaluate it. The variable
17095 `org-confirm-babel-evaluate' can be used to control prompting
17096 before code block evaluation, by default every code block
17097 evaluation requires confirmation. Code block evaluation can be
17098 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
17099 (interactive "P")
17100 (let ((org-enable-table-editor t))
17101 (cond
17102 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
17103 org-occur-highlights
17104 org-latex-fragment-image-overlays)
17105 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
17106 (org-remove-occur-highlights)
17107 (org-remove-latex-fragment-image-overlays)
17108 (message "Temporary highlights/overlays removed from current buffer"))
17109 ((and (local-variable-p 'org-finish-function (current-buffer))
17110 (fboundp org-finish-function))
17111 (funcall org-finish-function))
17112 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
17113 ((or (looking-at org-property-start-re)
17114 (org-at-property-p))
17115 (call-interactively 'org-property-action))
17116 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
17117 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
17118 (or (org-on-heading-p) (org-at-item-p)))
17119 (call-interactively 'org-update-statistics-cookies))
17120 ((org-on-heading-p) (call-interactively 'org-set-tags))
17121 ((org-at-table.el-p)
17122 (message "Use C-c ' to edit table.el tables"))
17123 ((org-at-table-p)
17124 (org-table-maybe-eval-formula)
17125 (if arg
17126 (call-interactively 'org-table-recalculate)
17127 (org-table-maybe-recalculate-line))
17128 (call-interactively 'org-table-align))
17129 ((or (org-footnote-at-reference-p)
17130 (org-footnote-at-definition-p))
17131 (call-interactively 'org-footnote-action))
17132 ((org-at-item-checkbox-p)
17133 (call-interactively 'org-toggle-checkbox)
17134 (org-list-send-list 'maybe))
17135 ((org-at-item-p)
17136 (if arg
17137 (call-interactively 'org-toggle-checkbox)
17138 (call-interactively 'org-maybe-renumber-ordered-list))
17139 (org-list-send-list 'maybe))
17140 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
17141 ;; Dynamic block
17142 (beginning-of-line 1)
17143 (save-excursion (org-update-dblock)))
17144 ((save-excursion
17145 (beginning-of-line 1)
17146 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
17147 (cond
17148 ((equal (match-string 1) "TBLFM")
17149 ;; Recalculate the table before this line
17150 (save-excursion
17151 (beginning-of-line 1)
17152 (skip-chars-backward " \r\n\t")
17153 (if (org-at-table-p)
17154 (org-call-with-arg 'org-table-recalculate (or arg t)))))
17156 (let ((org-inhibit-startup-visibility-stuff t)
17157 (org-startup-align-all-tables nil))
17158 (org-save-outline-visibility 'use-markers (org-mode-restart)))
17159 (message "Local setup has been refreshed"))))
17160 ((org-clock-update-time-maybe))
17161 (t (error "C-c C-c can do nothing useful at this location")))))
17163 (defun org-mode-restart ()
17164 "Restart Org-mode, to scan again for special lines.
17165 Also updates the keyword regular expressions."
17166 (interactive)
17167 (org-mode)
17168 (message "Org-mode restarted"))
17170 (defun org-kill-note-or-show-branches ()
17171 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
17172 (interactive)
17173 (if (not org-finish-function)
17174 (progn
17175 (hide-subtree)
17176 (call-interactively 'show-branches))
17177 (let ((org-note-abort t))
17178 (funcall org-finish-function))))
17180 (defun org-return (&optional indent)
17181 "Goto next table row or insert a newline.
17182 Calls `org-table-next-row' or `newline', depending on context.
17183 See the individual commands for more information."
17184 (interactive)
17185 (cond
17186 ((bobp) (if indent (newline-and-indent) (newline)))
17187 ((org-at-table-p)
17188 (org-table-justify-field-maybe)
17189 (call-interactively 'org-table-next-row))
17190 ((and org-return-follows-link
17191 (eq (get-text-property (point) 'face) 'org-link))
17192 (call-interactively 'org-open-at-point))
17193 ((and (org-at-heading-p)
17194 (looking-at
17195 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
17196 (org-show-entry)
17197 (end-of-line 1)
17198 (newline))
17199 (t (if indent (newline-and-indent) (newline)))))
17201 (defun org-return-indent ()
17202 "Goto next table row or insert a newline and indent.
17203 Calls `org-table-next-row' or `newline-and-indent', depending on
17204 context. See the individual commands for more information."
17205 (interactive)
17206 (org-return t))
17208 (defun org-ctrl-c-star ()
17209 "Compute table, or change heading status of lines.
17210 Calls `org-table-recalculate' or `org-toggle-heading',
17211 depending on context."
17212 (interactive)
17213 (cond
17214 ((org-at-table-p)
17215 (call-interactively 'org-table-recalculate))
17217 ;; Convert all lines in region to list items
17218 (call-interactively 'org-toggle-heading))))
17220 (defun org-ctrl-c-minus ()
17221 "Insert separator line in table or modify bullet status of line.
17222 Also turns a plain line or a region of lines into list items.
17223 Calls `org-table-insert-hline', `org-toggle-item', or
17224 `org-cycle-list-bullet', depending on context."
17225 (interactive)
17226 (cond
17227 ((org-at-table-p)
17228 (call-interactively 'org-table-insert-hline))
17229 ((org-region-active-p)
17230 (call-interactively 'org-toggle-item))
17231 ((org-in-item-p)
17232 (call-interactively 'org-cycle-list-bullet))
17234 (call-interactively 'org-toggle-item))))
17236 (defun org-toggle-item ()
17237 "Convert headings or normal lines to items, items to normal lines.
17238 If there is no active region, only the current line is considered.
17240 If the first line in the region is a headline, convert all headlines to items.
17242 If the first line in the region is an item, convert all items to normal lines.
17244 If the first line is normal text, add an item bullet to each line."
17245 (interactive)
17246 (let (l2 l beg end)
17247 (if (org-region-active-p)
17248 (setq beg (region-beginning) end (region-end))
17249 (setq beg (point-at-bol)
17250 end (min (1+ (point-at-eol)) (point-max))))
17251 (save-excursion
17252 (goto-char end)
17253 (setq l2 (org-current-line))
17254 (goto-char beg)
17255 (beginning-of-line 1)
17256 (setq l (1- (org-current-line)))
17257 (if (org-at-item-p)
17258 ;; We already have items, de-itemize
17259 (while (< (setq l (1+ l)) l2)
17260 (when (org-at-item-p)
17261 (goto-char (match-beginning 2))
17262 (delete-region (match-beginning 2) (match-end 2))
17263 (and (looking-at "[ \t]+") (replace-match "")))
17264 (beginning-of-line 2))
17265 (if (org-on-heading-p)
17266 ;; Headings, convert to items
17267 (while (< (setq l (1+ l)) l2)
17268 (if (looking-at org-outline-regexp)
17269 (replace-match "- " t t))
17270 (beginning-of-line 2))
17271 ;; normal lines, turn them into items
17272 (while (< (setq l (1+ l)) l2)
17273 (unless (org-at-item-p)
17274 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
17275 (replace-match "\\1- \\2")))
17276 (beginning-of-line 2)))))))
17278 (defun org-toggle-heading (&optional nstars)
17279 "Convert headings to normal text, or items or text to headings.
17280 If there is no active region, only the current line is considered.
17282 If the first line is a heading, remove the stars from all headlines
17283 in the region.
17285 If the first line is a plain list item, turn all plain list items
17286 into headings.
17288 If the first line is a normal line, turn each and every line in the
17289 region into a heading.
17291 When converting a line into a heading, the number of stars is chosen
17292 such that the lines become children of the current entry. However,
17293 when a prefix argument is given, its value determines the number of
17294 stars to add."
17295 (interactive "P")
17296 (let (l2 l itemp beg end)
17297 (if (org-region-active-p)
17298 (setq beg (region-beginning) end (region-end))
17299 (setq beg (point-at-bol)
17300 end (min (1+ (point-at-eol)) (point-max))))
17301 (save-excursion
17302 (goto-char end)
17303 (setq l2 (org-current-line))
17304 (goto-char beg)
17305 (beginning-of-line 1)
17306 (setq l (1- (org-current-line)))
17307 (if (org-on-heading-p)
17308 ;; We already have headlines, de-star them
17309 (while (< (setq l (1+ l)) l2)
17310 (when (org-on-heading-p t)
17311 (and (looking-at outline-regexp) (replace-match "")))
17312 (beginning-of-line 2))
17313 (setq itemp (org-at-item-p))
17314 (let* ((stars
17315 (if nstars
17316 (make-string (prefix-numeric-value current-prefix-arg)
17318 (save-excursion
17319 (if (re-search-backward org-complex-heading-regexp nil t)
17320 (match-string 1) ""))))
17321 (add-stars (cond (nstars "")
17322 ((equal stars "") "*")
17323 (org-odd-levels-only "**")
17324 (t "*")))
17325 (rpl (concat stars add-stars " ")))
17326 (while (< (setq l (1+ l)) l2)
17327 (if itemp
17328 (and (org-at-item-p) (replace-match rpl t t))
17329 (unless (org-on-heading-p)
17330 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
17331 (replace-match (concat rpl (match-string 2))))))
17332 (beginning-of-line 2)))))))
17334 (defun org-meta-return (&optional arg)
17335 "Insert a new heading or wrap a region in a table.
17336 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
17337 See the individual commands for more information."
17338 (interactive "P")
17339 (cond
17340 ((run-hook-with-args-until-success 'org-metareturn-hook))
17341 ((org-at-table-p)
17342 (call-interactively 'org-table-wrap-region))
17343 (t (call-interactively 'org-insert-heading))))
17345 ;;; Menu entries
17347 ;; Define the Org-mode menus
17348 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
17349 '("Tbl"
17350 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
17351 ["Next Field" org-cycle (org-at-table-p)]
17352 ["Previous Field" org-shifttab (org-at-table-p)]
17353 ["Next Row" org-return (org-at-table-p)]
17354 "--"
17355 ["Blank Field" org-table-blank-field (org-at-table-p)]
17356 ["Edit Field" org-table-edit-field (org-at-table-p)]
17357 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
17358 "--"
17359 ("Column"
17360 ["Move Column Left" org-metaleft (org-at-table-p)]
17361 ["Move Column Right" org-metaright (org-at-table-p)]
17362 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
17363 ["Insert Column" org-shiftmetaright (org-at-table-p)])
17364 ("Row"
17365 ["Move Row Up" org-metaup (org-at-table-p)]
17366 ["Move Row Down" org-metadown (org-at-table-p)]
17367 ["Delete Row" org-shiftmetaup (org-at-table-p)]
17368 ["Insert Row" org-shiftmetadown (org-at-table-p)]
17369 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
17370 "--"
17371 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
17372 ("Rectangle"
17373 ["Copy Rectangle" org-copy-special (org-at-table-p)]
17374 ["Cut Rectangle" org-cut-special (org-at-table-p)]
17375 ["Paste Rectangle" org-paste-special (org-at-table-p)]
17376 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
17377 "--"
17378 ("Calculate"
17379 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
17380 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
17381 ["Edit Formulas" org-edit-special (org-at-table-p)]
17382 "--"
17383 ["Recalculate line" org-table-recalculate (org-at-table-p)]
17384 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
17385 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
17386 "--"
17387 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
17388 "--"
17389 ["Sum Column/Rectangle" org-table-sum
17390 (or (org-at-table-p) (org-region-active-p))]
17391 ["Which Column?" org-table-current-column (org-at-table-p)])
17392 ["Debug Formulas"
17393 org-table-toggle-formula-debugger
17394 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
17395 ["Show Col/Row Numbers"
17396 org-table-toggle-coordinate-overlays
17397 :style toggle
17398 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
17399 "--"
17400 ["Create" org-table-create (and (not (org-at-table-p))
17401 org-enable-table-editor)]
17402 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
17403 ["Import from File" org-table-import (not (org-at-table-p))]
17404 ["Export to File" org-table-export (org-at-table-p)]
17405 "--"
17406 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
17408 (easy-menu-define org-org-menu org-mode-map "Org menu"
17409 '("Org"
17410 ("Show/Hide"
17411 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
17412 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
17413 ["Sparse Tree..." org-sparse-tree t]
17414 ["Reveal Context" org-reveal t]
17415 ["Show All" show-all t]
17416 "--"
17417 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
17418 "--"
17419 ["New Heading" org-insert-heading t]
17420 ("Navigate Headings"
17421 ["Up" outline-up-heading t]
17422 ["Next" outline-next-visible-heading t]
17423 ["Previous" outline-previous-visible-heading t]
17424 ["Next Same Level" outline-forward-same-level t]
17425 ["Previous Same Level" outline-backward-same-level t]
17426 "--"
17427 ["Jump" org-goto t])
17428 ("Edit Structure"
17429 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
17430 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
17431 "--"
17432 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
17433 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
17434 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
17435 "--"
17436 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
17437 "--"
17438 ["Promote Heading" org-metaleft (not (org-at-table-p))]
17439 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
17440 ["Demote Heading" org-metaright (not (org-at-table-p))]
17441 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
17442 "--"
17443 ["Sort Region/Children" org-sort (not (org-at-table-p))]
17444 "--"
17445 ["Convert to odd levels" org-convert-to-odd-levels t]
17446 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
17447 ("Editing"
17448 ["Emphasis..." org-emphasize t]
17449 ["Edit Source Example" org-edit-special t]
17450 "--"
17451 ["Footnote new/jump" org-footnote-action t]
17452 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
17453 ("Archive"
17454 ["Archive (default method)" org-archive-subtree-default t]
17455 "--"
17456 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
17457 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
17458 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
17460 "--"
17461 ("Hyperlinks"
17462 ["Store Link (Global)" org-store-link t]
17463 ["Find existing link to here" org-occur-link-in-agenda-files t]
17464 ["Insert Link" org-insert-link t]
17465 ["Follow Link" org-open-at-point t]
17466 "--"
17467 ["Next link" org-next-link t]
17468 ["Previous link" org-previous-link t]
17469 "--"
17470 ["Descriptive Links"
17471 (progn (add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
17472 :style radio
17473 :selected (member '(org-link) buffer-invisibility-spec)]
17474 ["Literal Links"
17475 (progn
17476 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
17477 :style radio
17478 :selected (not (member '(org-link) buffer-invisibility-spec))])
17479 "--"
17480 ("TODO Lists"
17481 ["TODO/DONE/-" org-todo t]
17482 ("Select keyword"
17483 ["Next keyword" org-shiftright (org-on-heading-p)]
17484 ["Previous keyword" org-shiftleft (org-on-heading-p)]
17485 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
17486 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
17487 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
17488 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
17489 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
17490 "--"
17491 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
17492 :selected org-enforce-todo-dependencies :style toggle :active t]
17493 "Settings for tree at point"
17494 ["Do Children sequentially" org-toggle-ordered-property :style radio
17495 :selected (ignore-errors (org-entry-get nil "ORDERED"))
17496 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
17497 ["Do Children parallel" org-toggle-ordered-property :style radio
17498 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
17499 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
17500 "--"
17501 ["Set Priority" org-priority t]
17502 ["Priority Up" org-shiftup t]
17503 ["Priority Down" org-shiftdown t]
17504 "--"
17505 ["Get news from all feeds" org-feed-update-all t]
17506 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
17507 ["Customize feeds" (customize-variable 'org-feed-alist) t])
17508 ("TAGS and Properties"
17509 ["Set Tags" org-set-tags-command t]
17510 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
17511 "--"
17512 ["Set property" org-set-property t]
17513 ["Column view of properties" org-columns t]
17514 ["Insert Column View DBlock" org-insert-columns-dblock t])
17515 ("Dates and Scheduling"
17516 ["Timestamp" org-time-stamp t]
17517 ["Timestamp (inactive)" org-time-stamp-inactive t]
17518 ("Change Date"
17519 ["1 Day Later" org-shiftright t]
17520 ["1 Day Earlier" org-shiftleft t]
17521 ["1 ... Later" org-shiftup t]
17522 ["1 ... Earlier" org-shiftdown t])
17523 ["Compute Time Range" org-evaluate-time-range t]
17524 ["Schedule Item" org-schedule t]
17525 ["Deadline" org-deadline t]
17526 "--"
17527 ["Custom time format" org-toggle-time-stamp-overlays
17528 :style radio :selected org-display-custom-times]
17529 "--"
17530 ["Goto Calendar" org-goto-calendar t]
17531 ["Date from Calendar" org-date-from-calendar t]
17532 "--"
17533 ["Start/Restart Timer" org-timer-start t]
17534 ["Pause/Continue Timer" org-timer-pause-or-continue t]
17535 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
17536 ["Insert Timer String" org-timer t]
17537 ["Insert Timer Item" org-timer-item t])
17538 ("Logging work"
17539 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
17540 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
17541 ["Clock out" org-clock-out t]
17542 ["Clock cancel" org-clock-cancel t]
17543 "--"
17544 ["Mark as default task" org-clock-mark-default-task t]
17545 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
17546 ["Goto running clock" org-clock-goto t]
17547 "--"
17548 ["Display times" org-clock-display t]
17549 ["Create clock table" org-clock-report t]
17550 "--"
17551 ["Record DONE time"
17552 (progn (setq org-log-done (not org-log-done))
17553 (message "Switching to %s will %s record a timestamp"
17554 (car org-done-keywords)
17555 (if org-log-done "automatically" "not")))
17556 :style toggle :selected org-log-done])
17557 "--"
17558 ["Agenda Command..." org-agenda t]
17559 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
17560 ("File List for Agenda")
17561 ("Special views current file"
17562 ["TODO Tree" org-show-todo-tree t]
17563 ["Check Deadlines" org-check-deadlines t]
17564 ["Timeline" org-timeline t]
17565 ["Tags/Property tree" org-match-sparse-tree t])
17566 "--"
17567 ["Export/Publish..." org-export t]
17568 ("LaTeX"
17569 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
17570 :selected org-cdlatex-mode]
17571 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
17572 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
17573 ["Modify math symbol" org-cdlatex-math-modify
17574 (org-inside-LaTeX-fragment-p)]
17575 ["Insert citation" org-reftex-citation t]
17576 "--"
17577 ["Export LaTeX fragments as images"
17578 (if (featurep 'org-exp)
17579 (setq org-export-with-LaTeX-fragments
17580 (not org-export-with-LaTeX-fragments))
17581 (require 'org-exp))
17582 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
17583 org-export-with-LaTeX-fragments)]
17584 "--"
17585 ["Template for BEAMER" org-insert-beamer-options-template t])
17586 "--"
17587 ("MobileOrg"
17588 ["Push Files and Views" org-mobile-push t]
17589 ["Get Captured and Flagged" org-mobile-pull t]
17590 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
17591 "--"
17592 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
17593 "--"
17594 ("Documentation"
17595 ["Show Version" org-version t]
17596 ["Info Documentation" org-info t])
17597 ("Customize"
17598 ["Browse Org Group" org-customize t]
17599 "--"
17600 ["Expand This Menu" org-create-customize-menu
17601 (fboundp 'customize-menu-create)])
17602 ["Send bug report" org-submit-bug-report t]
17603 "--"
17604 ("Refresh/Reload"
17605 ["Refresh setup current buffer" org-mode-restart t]
17606 ["Reload Org (after update)" org-reload t]
17607 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
17610 (defun org-info (&optional node)
17611 "Read documentation for Org-mode in the info system.
17612 With optional NODE, go directly to that node."
17613 (interactive)
17614 (info (format "(org)%s" (or node ""))))
17616 ;;;###autoload
17617 (defun org-submit-bug-report ()
17618 "Submit a bug report on Org-mode via mail.
17620 Don't hesitate to report any problems or inaccurate documentation.
17622 If you don't have setup sending mail from (X)Emacs, please copy the
17623 output buffer into your mail program, as it gives us important
17624 information about your Org-mode version and configuration."
17625 (interactive)
17626 (require 'reporter)
17627 (org-load-modules-maybe)
17628 (org-require-autoloaded-modules)
17629 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
17630 (reporter-submit-bug-report
17631 "emacs-orgmode@gnu.org"
17632 (org-version)
17633 (let (list)
17634 (save-window-excursion
17635 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
17636 (delete-other-windows)
17637 (erase-buffer)
17638 (insert "You are about to submit a bug report to the Org-mode mailing list.
17640 We would like to add your full Org-mode and Outline configuration to the
17641 bug report. This greatly simplifies the work of the maintainer and
17642 other experts on the mailing list.
17644 HOWEVER, some variables you have customized may contain private
17645 information. The names of customers, colleagues, or friends, might
17646 appear in the form of file names, tags, todo states, or search strings.
17647 If you answer yes to the prompt, you might want to check and remove
17648 such private information before sending the email.")
17649 (add-text-properties (point-min) (point-max) '(face org-warning))
17650 (when (yes-or-no-p "Include your Org-mode configuration ")
17651 (mapatoms
17652 (lambda (v)
17653 (and (boundp v)
17654 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
17655 (or (and (symbol-value v)
17656 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
17657 (and
17658 (get v 'custom-type) (get v 'standard-value)
17659 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
17660 (push v list)))))
17661 (kill-buffer (get-buffer "*Warn about privacy*"))
17662 list))
17663 nil nil
17664 "Remember to cover the basics, that is, what you expected to happen and
17665 what in fact did happen. You don't know how to make a good report? See
17667 http://orgmode.org/manual/Feedback.html#Feedback
17669 Your bug report will be posted to the Org-mode mailing list.
17670 ------------------------------------------------------------------------")
17671 (save-excursion
17672 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
17673 (replace-match "\\1Bug: \\3 [\\2]")))))
17676 (defun org-install-agenda-files-menu ()
17677 (let ((bl (buffer-list)))
17678 (save-excursion
17679 (while bl
17680 (set-buffer (pop bl))
17681 (if (org-mode-p) (setq bl nil)))
17682 (when (org-mode-p)
17683 (easy-menu-change
17684 '("Org") "File List for Agenda"
17685 (append
17686 (list
17687 ["Edit File List" (org-edit-agenda-file-list) t]
17688 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
17689 ["Remove Current File from List" org-remove-file t]
17690 ["Cycle through agenda files" org-cycle-agenda-files t]
17691 ["Occur in all agenda files" org-occur-in-agenda-files t]
17692 "--")
17693 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
17695 ;;;; Documentation
17697 ;;;###autoload
17698 (defun org-require-autoloaded-modules ()
17699 (interactive)
17700 (mapc 'require
17701 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
17702 org-docbook org-exp org-html org-icalendar
17703 org-id org-latex
17704 org-publish org-remember org-table
17705 org-timer org-xoxo)))
17707 ;;;###autoload
17708 (defun org-reload (&optional uncompiled)
17709 "Reload all org lisp files.
17710 With prefix arg UNCOMPILED, load the uncompiled versions."
17711 (interactive "P")
17712 (require 'find-func)
17713 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
17714 (dir-org (file-name-directory (org-find-library-name "org")))
17715 (dir-org-contrib (ignore-errors
17716 (file-name-directory
17717 (org-find-library-name "org-contribdir"))))
17718 (babel-files
17719 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
17720 (append (list nil "comint" "eval" "exp" "keys"
17721 "lob" "ref" "table" "tangle")
17722 (delq nil
17723 (mapcar
17724 (lambda (lang)
17725 (when (cdr lang) (symbol-name (car lang))))
17726 org-babel-load-languages)))))
17727 (files
17728 (append (directory-files dir-org t file-re)
17729 babel-files
17730 (and dir-org-contrib
17731 (directory-files dir-org-contrib t file-re))))
17732 (remove-re (concat (if (featurep 'xemacs)
17733 "org-colview" "org-colview-xemacs")
17734 "\\'")))
17735 (setq files (mapcar 'file-name-sans-extension files))
17736 (setq files (mapcar
17737 (lambda (x) (if (string-match remove-re x) nil x))
17738 files))
17739 (setq files (delq nil files))
17740 (mapc
17741 (lambda (f)
17742 (when (featurep (intern (file-name-nondirectory f)))
17743 (if (and (not uncompiled)
17744 (file-exists-p (concat f ".elc")))
17745 (load (concat f ".elc") nil nil t)
17746 (load (concat f ".el") nil nil t))))
17747 files))
17748 (org-version))
17750 ;;;###autoload
17751 (defun org-customize ()
17752 "Call the customize function with org as argument."
17753 (interactive)
17754 (org-load-modules-maybe)
17755 (org-require-autoloaded-modules)
17756 (customize-browse 'org))
17758 (defun org-create-customize-menu ()
17759 "Create a full customization menu for Org-mode, insert it into the menu."
17760 (interactive)
17761 (org-load-modules-maybe)
17762 (org-require-autoloaded-modules)
17763 (if (fboundp 'customize-menu-create)
17764 (progn
17765 (easy-menu-change
17766 '("Org") "Customize"
17767 `(["Browse Org group" org-customize t]
17768 "--"
17769 ,(customize-menu-create 'org)
17770 ["Set" Custom-set t]
17771 ["Save" Custom-save t]
17772 ["Reset to Current" Custom-reset-current t]
17773 ["Reset to Saved" Custom-reset-saved t]
17774 ["Reset to Standard Settings" Custom-reset-standard t]))
17775 (message "\"Org\"-menu now contains full customization menu"))
17776 (error "Cannot expand menu (outdated version of cus-edit.el)")))
17778 ;;;; Miscellaneous stuff
17780 ;;; Generally useful functions
17782 (defun org-get-at-bol (property)
17783 "Get text property PROPERTY at beginning of line."
17784 (get-text-property (point-at-bol) property))
17786 (defun org-find-text-property-in-string (prop s)
17787 "Return the first non-nil value of property PROP in string S."
17788 (or (get-text-property 0 prop s)
17789 (get-text-property (or (next-single-property-change 0 prop s) 0)
17790 prop s)))
17792 (defun org-display-warning (message) ;; Copied from Emacs-Muse
17793 "Display the given MESSAGE as a warning."
17794 (if (fboundp 'display-warning)
17795 (display-warning 'org message
17796 (if (featurep 'xemacs) 'warning :warning))
17797 (let ((buf (get-buffer-create "*Org warnings*")))
17798 (with-current-buffer buf
17799 (goto-char (point-max))
17800 (insert "Warning (Org): " message)
17801 (unless (bolp)
17802 (newline)))
17803 (display-buffer buf)
17804 (sit-for 0))))
17806 (defun org-in-commented-line ()
17807 "Is point in a line starting with `#'?"
17808 (equal (char-after (point-at-bol)) ?#))
17810 (defun org-in-indented-comment-line ()
17811 "Is point in a line starting with `#' after some white space?"
17812 (save-excursion
17813 (save-match-data
17814 (goto-char (point-at-bol))
17815 (looking-at "[ \t]*#"))))
17817 (defun org-in-verbatim-emphasis ()
17818 (save-match-data
17819 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
17821 (defun org-goto-marker-or-bmk (marker &optional bookmark)
17822 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
17823 (if (and marker (marker-buffer marker)
17824 (buffer-live-p (marker-buffer marker)))
17825 (progn
17826 (switch-to-buffer (marker-buffer marker))
17827 (if (or (> marker (point-max)) (< marker (point-min)))
17828 (widen))
17829 (goto-char marker)
17830 (org-show-context 'org-goto))
17831 (if bookmark
17832 (bookmark-jump bookmark)
17833 (error "Cannot find location"))))
17835 (defun org-quote-csv-field (s)
17836 "Quote field for inclusion in CSV material."
17837 (if (string-match "[\",]" s)
17838 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
17841 (defun org-plist-delete (plist property)
17842 "Delete PROPERTY from PLIST.
17843 This is in contrast to merely setting it to 0."
17844 (let (p)
17845 (while plist
17846 (if (not (eq property (car plist)))
17847 (setq p (plist-put p (car plist) (nth 1 plist))))
17848 (setq plist (cddr plist)))
17851 (defun org-force-self-insert (N)
17852 "Needed to enforce self-insert under remapping."
17853 (interactive "p")
17854 (self-insert-command N))
17856 (defun org-string-width (s)
17857 "Compute width of string, ignoring invisible characters.
17858 This ignores character with invisibility property `org-link', and also
17859 characters with property `org-cwidth', because these will become invisible
17860 upon the next fontification round."
17861 (let (b l)
17862 (when (or (eq t buffer-invisibility-spec)
17863 (assq 'org-link buffer-invisibility-spec))
17864 (while (setq b (text-property-any 0 (length s)
17865 'invisible 'org-link s))
17866 (setq s (concat (substring s 0 b)
17867 (substring s (or (next-single-property-change
17868 b 'invisible s) (length s)))))))
17869 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
17870 (setq s (concat (substring s 0 b)
17871 (substring s (or (next-single-property-change
17872 b 'org-cwidth s) (length s))))))
17873 (setq l (string-width s) b -1)
17874 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
17875 (setq l (- l (get-text-property b 'org-dwidth-n s))))
17878 (defun org-get-indentation (&optional line)
17879 "Get the indentation of the current line, interpreting tabs.
17880 When LINE is given, assume it represents a line and compute its indentation."
17881 (if line
17882 (if (string-match "^ *" (org-remove-tabs line))
17883 (match-end 0))
17884 (save-excursion
17885 (beginning-of-line 1)
17886 (skip-chars-forward " \t")
17887 (current-column))))
17889 (defun org-remove-tabs (s &optional width)
17890 "Replace tabulators in S with spaces.
17891 Assumes that s is a single line, starting in column 0."
17892 (setq width (or width tab-width))
17893 (while (string-match "\t" s)
17894 (setq s (replace-match
17895 (make-string
17896 (- (* width (/ (+ (match-beginning 0) width) width))
17897 (match-beginning 0)) ?\ )
17898 t t s)))
17901 (defun org-fix-indentation (line ind)
17902 "Fix indentation in LINE.
17903 IND is a cons cell with target and minimum indentation.
17904 If the current indentation in LINE is smaller than the minimum,
17905 leave it alone. If it is larger than ind, set it to the target."
17906 (let* ((l (org-remove-tabs line))
17907 (i (org-get-indentation l))
17908 (i1 (car ind)) (i2 (cdr ind)))
17909 (if (>= i i2) (setq l (substring line i2)))
17910 (if (> i1 0)
17911 (concat (make-string i1 ?\ ) l)
17912 l)))
17914 (defun org-remove-indentation (code &optional n)
17915 "Remove the maximum common indentation from the lines in CODE.
17916 N may optionally be the number of spaces to remove."
17917 (with-temp-buffer
17918 (insert code)
17919 (org-do-remove-indentation n)
17920 (buffer-string)))
17922 (defun org-do-remove-indentation (&optional n)
17923 "Remove the maximum common indentation from the buffer."
17924 (untabify (point-min) (point-max))
17925 (let ((min 10000) re)
17926 (if n
17927 (setq min n)
17928 (goto-char (point-min))
17929 (while (re-search-forward "^ *[^ \n]" nil t)
17930 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
17931 (unless (or (= min 0) (= min 10000))
17932 (setq re (format "^ \\{%d\\}" min))
17933 (goto-char (point-min))
17934 (while (re-search-forward re nil t)
17935 (replace-match "")
17936 (end-of-line 1))
17937 min)))
17939 (defun org-fill-template (template alist)
17940 "Find each %key of ALIST in TEMPLATE and replace it."
17941 (let ((case-fold-search nil)
17942 entry key value)
17943 (setq alist (sort (copy-sequence alist)
17944 (lambda (a b) (< (length (car a)) (length (car b))))))
17945 (while (setq entry (pop alist))
17946 (setq template
17947 (replace-regexp-in-string
17948 (concat "%" (regexp-quote (car entry)))
17949 (cdr entry) template t t)))
17950 template))
17952 (defun org-base-buffer (buffer)
17953 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
17954 (if (not buffer)
17955 buffer
17956 (or (buffer-base-buffer buffer)
17957 buffer)))
17959 (defun org-trim (s)
17960 "Remove whitespace at beginning and end of string."
17961 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
17962 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
17965 (defun org-wrap (string &optional width lines)
17966 "Wrap string to either a number of lines, or a width in characters.
17967 If WIDTH is non-nil, the string is wrapped to that width, however many lines
17968 that costs. If there is a word longer than WIDTH, the text is actually
17969 wrapped to the length of that word.
17970 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
17971 many lines, whatever width that takes.
17972 The return value is a list of lines, without newlines at the end."
17973 (let* ((words (org-split-string string "[ \t\n]+"))
17974 (maxword (apply 'max (mapcar 'org-string-width words)))
17975 w ll)
17976 (cond (width
17977 (org-do-wrap words (max maxword width)))
17978 (lines
17979 (setq w maxword)
17980 (setq ll (org-do-wrap words maxword))
17981 (if (<= (length ll) lines)
17983 (setq ll words)
17984 (while (> (length ll) lines)
17985 (setq w (1+ w))
17986 (setq ll (org-do-wrap words w)))
17987 ll))
17988 (t (error "Cannot wrap this")))))
17990 (defun org-do-wrap (words width)
17991 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
17992 (let (lines line)
17993 (while words
17994 (setq line (pop words))
17995 (while (and words (< (+ (length line) (length (car words))) width))
17996 (setq line (concat line " " (pop words))))
17997 (setq lines (push line lines)))
17998 (nreverse lines)))
18000 (defun org-split-string (string &optional separators)
18001 "Splits STRING into substrings at SEPARATORS.
18002 No empty strings are returned if there are matches at the beginning
18003 and end of string."
18004 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
18005 (start 0)
18006 notfirst
18007 (list nil))
18008 (while (and (string-match rexp string
18009 (if (and notfirst
18010 (= start (match-beginning 0))
18011 (< start (length string)))
18012 (1+ start) start))
18013 (< (match-beginning 0) (length string)))
18014 (setq notfirst t)
18015 (or (eq (match-beginning 0) 0)
18016 (and (eq (match-beginning 0) (match-end 0))
18017 (eq (match-beginning 0) start))
18018 (setq list
18019 (cons (substring string start (match-beginning 0))
18020 list)))
18021 (setq start (match-end 0)))
18022 (or (eq start (length string))
18023 (setq list
18024 (cons (substring string start)
18025 list)))
18026 (nreverse list)))
18028 (defun org-quote-vert (s)
18029 "Replace \"|\" with \"\\vert\"."
18030 (while (string-match "|" s)
18031 (setq s (replace-match "\\vert" t t s)))
18034 (defun org-uuidgen-p (s)
18035 "Is S an ID created by UUIDGEN?"
18036 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
18038 (defun org-context ()
18039 "Return a list of contexts of the current cursor position.
18040 If several contexts apply, all are returned.
18041 Each context entry is a list with a symbol naming the context, and
18042 two positions indicating start and end of the context. Possible
18043 contexts are:
18045 :headline anywhere in a headline
18046 :headline-stars on the leading stars in a headline
18047 :todo-keyword on a TODO keyword (including DONE) in a headline
18048 :tags on the TAGS in a headline
18049 :priority on the priority cookie in a headline
18050 :item on the first line of a plain list item
18051 :item-bullet on the bullet/number of a plain list item
18052 :checkbox on the checkbox in a plain list item
18053 :table in an org-mode table
18054 :table-special on a special filed in a table
18055 :table-table in a table.el table
18056 :link on a hyperlink
18057 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
18058 :target on a <<target>>
18059 :radio-target on a <<<radio-target>>>
18060 :latex-fragment on a LaTeX fragment
18061 :latex-preview on a LaTeX fragment with overlayed preview image
18063 This function expects the position to be visible because it uses font-lock
18064 faces as a help to recognize the following contexts: :table-special, :link,
18065 and :keyword."
18066 (let* ((f (get-text-property (point) 'face))
18067 (faces (if (listp f) f (list f)))
18068 (p (point)) clist o)
18069 ;; First the large context
18070 (cond
18071 ((org-on-heading-p t)
18072 (push (list :headline (point-at-bol) (point-at-eol)) clist)
18073 (when (progn
18074 (beginning-of-line 1)
18075 (looking-at org-todo-line-tags-regexp))
18076 (push (org-point-in-group p 1 :headline-stars) clist)
18077 (push (org-point-in-group p 2 :todo-keyword) clist)
18078 (push (org-point-in-group p 4 :tags) clist))
18079 (goto-char p)
18080 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
18081 (if (looking-at "\\[#[A-Z0-9]\\]")
18082 (push (org-point-in-group p 0 :priority) clist)))
18084 ((org-at-item-p)
18085 (push (org-point-in-group p 2 :item-bullet) clist)
18086 (push (list :item (point-at-bol)
18087 (save-excursion (org-end-of-item) (point)))
18088 clist)
18089 (and (org-at-item-checkbox-p)
18090 (push (org-point-in-group p 0 :checkbox) clist)))
18092 ((org-at-table-p)
18093 (push (list :table (org-table-begin) (org-table-end)) clist)
18094 (if (memq 'org-formula faces)
18095 (push (list :table-special
18096 (previous-single-property-change p 'face)
18097 (next-single-property-change p 'face)) clist)))
18098 ((org-at-table-p 'any)
18099 (push (list :table-table) clist)))
18100 (goto-char p)
18102 ;; Now the small context
18103 (cond
18104 ((org-at-timestamp-p)
18105 (push (org-point-in-group p 0 :timestamp) clist))
18106 ((memq 'org-link faces)
18107 (push (list :link
18108 (previous-single-property-change p 'face)
18109 (next-single-property-change p 'face)) clist))
18110 ((memq 'org-special-keyword faces)
18111 (push (list :keyword
18112 (previous-single-property-change p 'face)
18113 (next-single-property-change p 'face)) clist))
18114 ((org-on-target-p)
18115 (push (org-point-in-group p 0 :target) clist)
18116 (goto-char (1- (match-beginning 0)))
18117 (if (looking-at org-radio-target-regexp)
18118 (push (org-point-in-group p 0 :radio-target) clist))
18119 (goto-char p))
18120 ((setq o (car (delq nil
18121 (mapcar
18122 (lambda (x)
18123 (if (memq x org-latex-fragment-image-overlays) x))
18124 (overlays-at (point))))))
18125 (push (list :latex-fragment
18126 (overlay-start o) (overlay-end o)) clist)
18127 (push (list :latex-preview
18128 (overlay-start o) (overlay-end o)) clist))
18129 ((org-inside-LaTeX-fragment-p)
18130 ;; FIXME: positions wrong.
18131 (push (list :latex-fragment (point) (point)) clist)))
18133 (setq clist (nreverse (delq nil clist)))
18134 clist))
18136 ;; FIXME: Compare with at-regexp-p Do we need both?
18137 (defun org-in-regexp (re &optional nlines visually)
18138 "Check if point is inside a match of regexp.
18139 Normally only the current line is checked, but you can include NLINES extra
18140 lines both before and after point into the search.
18141 If VISUALLY is set, require that the cursor is not after the match but
18142 really on, so that the block visually is on the match."
18143 (catch 'exit
18144 (let ((pos (point))
18145 (eol (point-at-eol (+ 1 (or nlines 0))))
18146 (inc (if visually 1 0)))
18147 (save-excursion
18148 (beginning-of-line (- 1 (or nlines 0)))
18149 (while (re-search-forward re eol t)
18150 (if (and (<= (match-beginning 0) pos)
18151 (>= (+ inc (match-end 0)) pos))
18152 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
18154 (defun org-at-regexp-p (regexp)
18155 "Is point inside a match of REGEXP in the current line?"
18156 (catch 'exit
18157 (save-excursion
18158 (let ((pos (point)) (end (point-at-eol)))
18159 (beginning-of-line 1)
18160 (while (re-search-forward regexp end t)
18161 (if (and (<= (match-beginning 0) pos)
18162 (>= (match-end 0) pos))
18163 (throw 'exit t)))
18164 nil))))
18166 (defun org-in-regexps-block-p (start-re end-re)
18167 "Return t if the current point is between matches of START-RE and END-RE.
18168 This will also return to if point is on one of the two matches."
18169 (interactive)
18170 (let ((p (point)))
18171 (save-excursion
18172 (and (or (org-at-regexp-p start-re)
18173 (re-search-backward start-re nil t))
18174 (re-search-forward end-re nil t)
18175 (>= (point) p)))))
18177 (defun org-occur-in-agenda-files (regexp &optional nlines)
18178 "Call `multi-occur' with buffers for all agenda files."
18179 (interactive "sOrg-files matching: \np")
18180 (let* ((files (org-agenda-files))
18181 (tnames (mapcar 'file-truename files))
18182 (extra org-agenda-text-search-extra-files)
18184 (when (eq (car extra) 'agenda-archives)
18185 (setq extra (cdr extra))
18186 (setq files (org-add-archive-files files)))
18187 (while (setq f (pop extra))
18188 (unless (member (file-truename f) tnames)
18189 (add-to-list 'files f 'append)
18190 (add-to-list 'tnames (file-truename f) 'append)))
18191 (multi-occur
18192 (mapcar (lambda (x)
18193 (with-current-buffer
18194 (or (get-file-buffer x) (find-file-noselect x))
18195 (widen)
18196 (current-buffer)))
18197 files)
18198 regexp)))
18200 (if (boundp 'occur-mode-find-occurrence-hook)
18201 ;; Emacs 23
18202 (add-hook 'occur-mode-find-occurrence-hook
18203 (lambda ()
18204 (when (org-mode-p)
18205 (org-reveal))))
18206 ;; Emacs 22
18207 (defadvice occur-mode-goto-occurrence
18208 (after org-occur-reveal activate)
18209 (and (org-mode-p) (org-reveal)))
18210 (defadvice occur-mode-goto-occurrence-other-window
18211 (after org-occur-reveal activate)
18212 (and (org-mode-p) (org-reveal)))
18213 (defadvice occur-mode-display-occurrence
18214 (after org-occur-reveal activate)
18215 (when (org-mode-p)
18216 (let ((pos (occur-mode-find-occurrence)))
18217 (with-current-buffer (marker-buffer pos)
18218 (save-excursion
18219 (goto-char pos)
18220 (org-reveal)))))))
18222 (defun org-occur-link-in-agenda-files ()
18223 "Create a link and search for it in the agendas.
18224 The link is not stored in `org-stored-links', it is just created
18225 for the search purpose."
18226 (interactive)
18227 (let ((link (condition-case nil
18228 (org-store-link nil)
18229 (error "Unable to create a link to here"))))
18230 (org-occur-in-agenda-files (regexp-quote link))))
18232 (defun org-uniquify (list)
18233 "Remove duplicate elements from LIST."
18234 (let (res)
18235 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
18236 res))
18238 (defun org-delete-all (elts list)
18239 "Remove all elements in ELTS from LIST."
18240 (while elts
18241 (setq list (delete (pop elts) list)))
18242 list)
18244 (defun org-count (cl-item cl-seq)
18245 "Count the number of occurrences of ITEM in SEQ.
18246 Taken from `count' in cl-seq.el with all keyword arguments removed."
18247 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
18248 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
18249 (while (< cl-start cl-end)
18250 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
18251 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
18252 (setq cl-start (1+ cl-start)))
18253 cl-count))
18255 (defun org-remove-if (predicate seq)
18256 "Remove everything from SEQ that fulfills PREDICATE."
18257 (let (res e)
18258 (while seq
18259 (setq e (pop seq))
18260 (if (not (funcall predicate e)) (push e res)))
18261 (nreverse res)))
18263 (defun org-remove-if-not (predicate seq)
18264 "Remove everything from SEQ that does not fulfill PREDICATE."
18265 (let (res e)
18266 (while seq
18267 (setq e (pop seq))
18268 (if (funcall predicate e) (push e res)))
18269 (nreverse res)))
18271 (defun org-back-over-empty-lines ()
18272 "Move backwards over whitespace, to the beginning of the first empty line.
18273 Returns the number of empty lines passed."
18274 (let ((pos (point)))
18275 (skip-chars-backward " \t\n\r")
18276 (beginning-of-line 2)
18277 (goto-char (min (point) pos))
18278 (count-lines (point) pos)))
18280 (defun org-skip-whitespace ()
18281 (skip-chars-forward " \t\n\r"))
18283 (defun org-point-in-group (point group &optional context)
18284 "Check if POINT is in match-group GROUP.
18285 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
18286 match. If the match group does not exist or point is not inside it,
18287 return nil."
18288 (and (match-beginning group)
18289 (>= point (match-beginning group))
18290 (<= point (match-end group))
18291 (if context
18292 (list context (match-beginning group) (match-end group))
18293 t)))
18295 (defun org-switch-to-buffer-other-window (&rest args)
18296 "Switch to buffer in a second window on the current frame.
18297 In particular, do not allow pop-up frames.
18298 Returns the newly created buffer."
18299 (let (pop-up-frames special-display-buffer-names special-display-regexps
18300 special-display-function)
18301 (apply 'switch-to-buffer-other-window args)))
18303 (defun org-combine-plists (&rest plists)
18304 "Create a single property list from all plists in PLISTS.
18305 The process starts by copying the first list, and then setting properties
18306 from the other lists. Settings in the last list are the most significant
18307 ones and overrule settings in the other lists."
18308 (let ((rtn (copy-sequence (pop plists)))
18309 p v ls)
18310 (while plists
18311 (setq ls (pop plists))
18312 (while ls
18313 (setq p (pop ls) v (pop ls))
18314 (setq rtn (plist-put rtn p v))))
18315 rtn))
18317 (defun org-move-line-down (arg)
18318 "Move the current line down. With prefix argument, move it past ARG lines."
18319 (interactive "p")
18320 (let ((col (current-column))
18321 beg end pos)
18322 (beginning-of-line 1) (setq beg (point))
18323 (beginning-of-line 2) (setq end (point))
18324 (beginning-of-line (+ 1 arg))
18325 (setq pos (move-marker (make-marker) (point)))
18326 (insert (delete-and-extract-region beg end))
18327 (goto-char pos)
18328 (org-move-to-column col)))
18330 (defun org-move-line-up (arg)
18331 "Move the current line up. With prefix argument, move it past ARG lines."
18332 (interactive "p")
18333 (let ((col (current-column))
18334 beg end pos)
18335 (beginning-of-line 1) (setq beg (point))
18336 (beginning-of-line 2) (setq end (point))
18337 (beginning-of-line (- arg))
18338 (setq pos (move-marker (make-marker) (point)))
18339 (insert (delete-and-extract-region beg end))
18340 (goto-char pos)
18341 (org-move-to-column col)))
18343 (defun org-replace-escapes (string table)
18344 "Replace %-escapes in STRING with values in TABLE.
18345 TABLE is an association list with keys like \"%a\" and string values.
18346 The sequences in STRING may contain normal field width and padding information,
18347 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
18348 so values can contain further %-escapes if they are define later in TABLE."
18349 (let ((tbl (copy-alist table))
18350 (case-fold-search nil)
18351 (pchg 0)
18352 e re rpl)
18353 (while (setq e (pop tbl))
18354 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
18355 (when (and (cdr e) (string-match re (cdr e)))
18356 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
18357 (safe "SREF"))
18358 (add-text-properties 0 3 (list 'sref sref) safe)
18359 (setcdr e (replace-match safe t t (cdr e)))))
18360 (while (string-match re string)
18361 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
18362 (cdr e)))
18363 (setq string (replace-match rpl t t string))))
18364 (while (setq pchg (next-property-change pchg string))
18365 (let ((sref (get-text-property pchg 'sref string)))
18366 (when (and sref (string-match "SREF" string pchg))
18367 (setq string (replace-match sref t t string)))))
18368 string))
18370 (defun org-sublist (list start end)
18371 "Return a section of LIST, from START to END.
18372 Counting starts at 1."
18373 (let (rtn (c start))
18374 (setq list (nthcdr (1- start) list))
18375 (while (and list (<= c end))
18376 (push (pop list) rtn)
18377 (setq c (1+ c)))
18378 (nreverse rtn)))
18380 (defun org-find-base-buffer-visiting (file)
18381 "Like `find-buffer-visiting' but always return the base buffer and
18382 not an indirect buffer."
18383 (let ((buf (or (get-file-buffer file)
18384 (find-buffer-visiting file))))
18385 (if buf
18386 (or (buffer-base-buffer buf) buf)
18387 nil)))
18389 (defun org-image-file-name-regexp (&optional extensions)
18390 "Return regexp matching the file names of images.
18391 If EXTENSIONS is given, only match these."
18392 (if (and (not extensions) (fboundp 'image-file-name-regexp))
18393 (image-file-name-regexp)
18394 (let ((image-file-name-extensions
18395 (or extensions
18396 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
18397 "xbm" "xpm" "pbm" "pgm" "ppm"))))
18398 (concat "\\."
18399 (regexp-opt (nconc (mapcar 'upcase
18400 image-file-name-extensions)
18401 image-file-name-extensions)
18403 "\\'"))))
18405 (defun org-file-image-p (file &optional extensions)
18406 "Return non-nil if FILE is an image."
18407 (save-match-data
18408 (string-match (org-image-file-name-regexp extensions) file)))
18410 (defun org-get-cursor-date ()
18411 "Return the date at cursor in as a time.
18412 This works in the calendar and in the agenda, anywhere else it just
18413 returns the current time."
18414 (let (date day defd)
18415 (cond
18416 ((eq major-mode 'calendar-mode)
18417 (setq date (calendar-cursor-to-date)
18418 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18419 ((eq major-mode 'org-agenda-mode)
18420 (setq day (get-text-property (point) 'day))
18421 (if day
18422 (setq date (calendar-gregorian-from-absolute day)
18423 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
18424 (nth 2 date))))))
18425 (or defd (current-time))))
18427 (defvar org-agenda-action-marker (make-marker)
18428 "Marker pointing to the entry for the next agenda action.")
18430 (defun org-mark-entry-for-agenda-action ()
18431 "Mark the current entry as target of an agenda action.
18432 Agenda actions are actions executed from the agenda with the key `k',
18433 which make use of the date at the cursor."
18434 (interactive)
18435 (move-marker org-agenda-action-marker
18436 (save-excursion (org-back-to-heading t) (point))
18437 (current-buffer))
18438 (message
18439 "Entry marked for action; press `k' at desired date in agenda or calendar"))
18441 ;;; Paragraph filling stuff.
18442 ;; We want this to be just right, so use the full arsenal.
18444 (defun org-indent-line-function ()
18445 "Indent line like previous, but further if previous was headline or item."
18446 (interactive)
18447 (let* ((pos (point))
18448 (itemp (org-at-item-p))
18449 (case-fold-search t)
18450 (org-drawer-regexp (or org-drawer-regexp "\000"))
18451 column bpos bcol tpos tcol bullet btype bullet-type)
18452 ;; Find the previous relevant line
18453 (beginning-of-line 1)
18454 (cond
18455 ((looking-at "#") (setq column 0))
18456 ((looking-at "\\*+ ") (setq column 0))
18457 ((and (looking-at "[ \t]*:END:")
18458 (save-excursion (re-search-backward org-drawer-regexp nil t)))
18459 (save-excursion
18460 (goto-char (1- (match-beginning 1)))
18461 (setq column (current-column))))
18462 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
18463 (save-excursion
18464 (re-search-backward
18465 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
18466 (setq column (org-get-indentation (match-string 0))))
18468 (beginning-of-line 0)
18469 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
18470 (not (looking-at "[ \t]*:END:"))
18471 (not (looking-at org-drawer-regexp)))
18472 (beginning-of-line 0))
18473 (cond
18474 ((looking-at "\\*+[ \t]+")
18475 (if (not org-adapt-indentation)
18476 (setq column 0)
18477 (goto-char (match-end 0))
18478 (setq column (current-column))))
18479 ((looking-at org-drawer-regexp)
18480 (goto-char (1- (match-beginning 1)))
18481 (setq column (current-column)))
18482 ((looking-at "\\([ \t]*\\):END:")
18483 (goto-char (match-end 1))
18484 (setq column (current-column)))
18485 ((org-in-item-p)
18486 (org-beginning-of-item)
18487 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
18488 (setq bpos (match-beginning 1) tpos (match-end 0)
18489 bcol (progn (goto-char bpos) (current-column))
18490 tcol (progn (goto-char tpos) (current-column))
18491 bullet (match-string 1)
18492 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
18493 (if (> tcol (+ bcol org-description-max-indent))
18494 (setq tcol (+ bcol 5)))
18495 (if (not itemp)
18496 (setq column tcol)
18497 (goto-char pos)
18498 (beginning-of-line 1)
18499 (if (looking-at "\\S-")
18500 (progn
18501 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
18502 (setq bullet (match-string 1)
18503 btype (if (string-match "[0-9]" bullet) "n" bullet))
18504 (setq column (if (equal btype bullet-type) bcol tcol)))
18505 (setq column (org-get-indentation)))))
18506 (t (setq column (org-get-indentation))))))
18507 (goto-char pos)
18508 (if (<= (current-column) (current-indentation))
18509 (org-indent-line-to column)
18510 (save-excursion (org-indent-line-to column)))
18511 (setq column (current-column))
18512 (beginning-of-line 1)
18513 (if (looking-at
18514 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
18515 (replace-match (concat (match-string 1)
18516 (format org-property-format
18517 (match-string 2) (match-string 3)))
18518 t t))
18519 (org-move-to-column column)))
18521 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
18522 "Variable to store copy of `adaptive-fill-regexp'.
18523 Since `adaptive-fill-regexp' is set to never match, we need to
18524 store a backup of its value before entering `org-mode' so that
18525 the functionality can be provided as a fall-back.")
18527 (defun org-set-autofill-regexps ()
18528 (interactive)
18529 ;; In the paragraph separator we include headlines, because filling
18530 ;; text in a line directly attached to a headline would otherwise
18531 ;; fill the headline as well.
18532 (org-set-local 'comment-start-skip "^#+[ \t]*")
18533 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
18534 ;; The paragraph starter includes hand-formatted lists.
18535 (org-set-local
18536 'paragraph-start
18537 (concat
18538 "\f" "\\|"
18539 "[ ]*$" "\\|"
18540 "\\*+ " "\\|"
18541 "[ \t]*#" "\\|"
18542 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
18543 "[ \t]*[:|]" "\\|"
18544 "\\$\\$" "\\|"
18545 "\\\\\\(begin\\|end\\|[][]\\)"))
18546 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
18547 ;; But only if the user has not turned off tables or fixed-width regions
18548 (org-set-local
18549 'auto-fill-inhibit-regexp
18550 (concat "\\*+ \\|#\\+"
18551 "\\|[ \t]*" org-keyword-time-regexp
18552 (if (or org-enable-table-editor org-enable-fixed-width-editor)
18553 (concat
18554 "\\|[ \t]*["
18555 (if org-enable-table-editor "|" "")
18556 (if org-enable-fixed-width-editor ":" "")
18557 "]"))))
18558 ;; We use our own fill-paragraph function, to make sure that tables
18559 ;; and fixed-width regions are not wrapped. That function will pass
18560 ;; through to `fill-paragraph' when appropriate.
18561 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
18562 ;; Adaptive filling: To get full control, first make sure that
18563 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
18564 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
18565 (org-set-local 'org-adaptive-fill-regexp-backup
18566 adaptive-fill-regexp))
18567 (org-set-local 'adaptive-fill-regexp "\000")
18568 (org-set-local 'adaptive-fill-function
18569 'org-adaptive-fill-function)
18570 (org-set-local
18571 'align-mode-rules-list
18572 '((org-in-buffer-settings
18573 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
18574 (modes . '(org-mode))))))
18576 (defun org-fill-paragraph (&optional justify)
18577 "Re-align a table, pass through to fill-paragraph if no table."
18578 (let ((table-p (org-at-table-p))
18579 (table.el-p (org-at-table.el-p)))
18580 (cond ((and (equal (char-after (point-at-bol)) ?*)
18581 (save-excursion (goto-char (point-at-bol))
18582 (looking-at outline-regexp)))
18583 t) ; skip headlines
18584 (table.el-p t) ; skip table.el tables
18585 (table-p (org-table-align) t) ; align org-mode tables
18586 (t nil)))) ; call paragraph-fill
18588 ;; For reference, this is the default value of adaptive-fill-regexp
18589 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
18591 (defun org-adaptive-fill-function ()
18592 "Return a fill prefix for org-mode files.
18593 In particular, this makes sure hanging paragraphs for hand-formatted lists
18594 work correctly."
18595 (cond
18596 ;; Comment line
18597 ((looking-at "#[ \t]+")
18598 (match-string-no-properties 0))
18599 ;; Description list
18600 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
18601 (save-excursion
18602 (if (> (match-end 1) (+ (match-beginning 1)
18603 org-description-max-indent))
18604 (goto-char (+ (match-beginning 1) 5))
18605 (goto-char (match-end 0)))
18606 (make-string (current-column) ?\ )))
18607 ;; Ordered or unordered list
18608 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)")
18609 (save-excursion
18610 (goto-char (match-end 0))
18611 (make-string (current-column) ?\ )))
18612 ;; Other text
18613 ((looking-at org-adaptive-fill-regexp-backup)
18614 (match-string-no-properties 0))))
18616 ;;; Other stuff.
18618 (defun org-toggle-fixed-width-section (arg)
18619 "Toggle the fixed-width export.
18620 If there is no active region, the QUOTE keyword at the current headline is
18621 inserted or removed. When present, it causes the text between this headline
18622 and the next to be exported as fixed-width text, and unmodified.
18623 If there is an active region, this command adds or removes a colon as the
18624 first character of this line. If the first character of a line is a colon,
18625 this line is also exported in fixed-width font."
18626 (interactive "P")
18627 (let* ((cc 0)
18628 (regionp (org-region-active-p))
18629 (beg (if regionp (region-beginning) (point)))
18630 (end (if regionp (region-end)))
18631 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
18632 (case-fold-search nil)
18633 (re "[ \t]*\\(: \\)")
18634 off)
18635 (if regionp
18636 (save-excursion
18637 (goto-char beg)
18638 (setq cc (current-column))
18639 (beginning-of-line 1)
18640 (setq off (looking-at re))
18641 (while (> nlines 0)
18642 (setq nlines (1- nlines))
18643 (beginning-of-line 1)
18644 (cond
18645 (arg
18646 (org-move-to-column cc t)
18647 (insert ": \n")
18648 (forward-line -1))
18649 ((and off (looking-at re))
18650 (replace-match "" t t nil 1))
18651 ((not off) (org-move-to-column cc t) (insert ": ")))
18652 (forward-line 1)))
18653 (save-excursion
18654 (org-back-to-heading)
18655 (if (looking-at (concat outline-regexp
18656 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
18657 (replace-match "" t t nil 1)
18658 (if (looking-at outline-regexp)
18659 (progn
18660 (goto-char (match-end 0))
18661 (insert org-quote-string " "))))))))
18663 (defun org-reftex-citation ()
18664 "Use reftex-citation to insert a citation into the buffer.
18665 This looks for a line like
18667 #+BIBLIOGRAPHY: foo plain option:-d
18669 and derives from it that foo.bib is the bibliography file relevant
18670 for this document. It then installs the necessary environment for RefTeX
18671 to work in this buffer and calls `reftex-citation' to insert a citation
18672 into the buffer.
18674 Export of such citations to both LaTeX and HTML is handled by the contributed
18675 package org-exp-bibtex by Taru Karttunen."
18676 (interactive)
18677 (let ((reftex-docstruct-symbol 'rds)
18678 (reftex-cite-format "\\cite{%l}")
18679 rds bib)
18680 (save-excursion
18681 (save-restriction
18682 (widen)
18683 (let ((case-fold-search t)
18684 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
18685 (if (not (save-excursion
18686 (or (re-search-forward re nil t)
18687 (re-search-backward re nil t))))
18688 (error "No bibliography defined in file")
18689 (setq bib (concat (match-string 1) ".bib")
18690 rds (list (list 'bib bib)))))))
18691 (call-interactively 'reftex-citation)))
18693 ;;;; Functions extending outline functionality
18695 (defun org-beginning-of-line (&optional arg)
18696 "Go to the beginning of the current line. If that is invisible, continue
18697 to a visible line beginning. This makes the function of C-a more intuitive.
18698 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
18699 first attempt, and only move to after the tags when the cursor is already
18700 beyond the end of the headline."
18701 (interactive "P")
18702 (let ((pos (point))
18703 (special (if (consp org-special-ctrl-a/e)
18704 (car org-special-ctrl-a/e)
18705 org-special-ctrl-a/e))
18706 refpos)
18707 (if (org-bound-and-true-p line-move-visual)
18708 (beginning-of-visual-line 1)
18709 (beginning-of-line 1))
18710 (if (and arg (fboundp 'move-beginning-of-line))
18711 (call-interactively 'move-beginning-of-line)
18712 (if (bobp)
18714 (backward-char 1)
18715 (if (org-truely-invisible-p)
18716 (while (and (not (bobp)) (org-truely-invisible-p))
18717 (backward-char 1)
18718 (beginning-of-line 1))
18719 (forward-char 1))))
18720 (when special
18721 (cond
18722 ((and (looking-at org-complex-heading-regexp)
18723 (= (char-after (match-end 1)) ?\ ))
18724 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
18725 (point-at-eol)))
18726 (goto-char
18727 (if (eq special t)
18728 (cond ((> pos refpos) refpos)
18729 ((= pos (point)) refpos)
18730 (t (point)))
18731 (cond ((> pos (point)) (point))
18732 ((not (eq last-command this-command)) (point))
18733 (t refpos)))))
18734 ((org-at-item-p)
18735 (goto-char
18736 (if (eq special t)
18737 (cond ((> pos (match-end 4)) (match-end 4))
18738 ((= pos (point)) (match-end 4))
18739 (t (point)))
18740 (cond ((> pos (point)) (point))
18741 ((not (eq last-command this-command)) (point))
18742 (t (match-end 4))))))))
18743 (org-no-warnings
18744 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
18746 (defun org-end-of-line (&optional arg)
18747 "Go to the end of the line.
18748 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
18749 first attempt, and only move to after the tags when the cursor is already
18750 beyond the end of the headline."
18751 (interactive "P")
18752 (let ((special (if (consp org-special-ctrl-a/e)
18753 (cdr org-special-ctrl-a/e)
18754 org-special-ctrl-a/e)))
18755 (if (or (not special)
18756 (not (org-on-heading-p))
18757 arg)
18758 (call-interactively
18759 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
18760 ((fboundp 'move-end-of-line) 'move-end-of-line)
18761 (t 'end-of-line)))
18762 (let ((pos (point)))
18763 (beginning-of-line 1)
18764 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\)?$"))
18765 (if (eq special t)
18766 (if (or (< pos (match-beginning 1))
18767 (= pos (match-end 0)))
18768 (goto-char (match-beginning 1))
18769 (goto-char (match-end 0)))
18770 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
18771 (goto-char (match-end 0))
18772 (goto-char (match-beginning 1))))
18773 (call-interactively (if (fboundp 'move-end-of-line)
18774 'move-end-of-line
18775 'end-of-line)))))
18776 (org-no-warnings
18777 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
18779 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
18780 (define-key org-mode-map "\C-e" 'org-end-of-line)
18781 (define-key org-mode-map [home] 'org-beginning-of-line)
18782 (define-key org-mode-map [end] 'org-end-of-line)
18784 (defun org-backward-sentence (&optional arg)
18785 "Go to beginning of sentence, or beginning of table field.
18786 This will call `backward-sentence' or `org-table-beginning-of-field',
18787 depending on context."
18788 (interactive "P")
18789 (cond
18790 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
18791 (t (call-interactively 'backward-sentence))))
18793 (defun org-forward-sentence (&optional arg)
18794 "Go to end of sentence, or end of table field.
18795 This will call `forward-sentence' or `org-table-end-of-field',
18796 depending on context."
18797 (interactive "P")
18798 (cond
18799 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
18800 (t (call-interactively 'forward-sentence))))
18802 (define-key org-mode-map "\M-a" 'org-backward-sentence)
18803 (define-key org-mode-map "\M-e" 'org-forward-sentence)
18805 (defun org-kill-line (&optional arg)
18806 "Kill line, to tags or end of line."
18807 (interactive "P")
18808 (cond
18809 ((or (not org-special-ctrl-k)
18810 (bolp)
18811 (not (org-on-heading-p)))
18812 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
18813 org-ctrl-k-protect-subtree)
18814 (if (or (eq org-ctrl-k-protect-subtree 'error)
18815 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
18816 (error "C-k aborted - would kill hidden subtree")))
18817 (call-interactively 'kill-line))
18818 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
18819 (kill-region (point) (match-beginning 1))
18820 (org-set-tags nil t))
18821 (t (kill-region (point) (point-at-eol)))))
18823 (define-key org-mode-map "\C-k" 'org-kill-line)
18825 (defun org-yank (&optional arg)
18826 "Yank. If the kill is a subtree, treat it specially.
18827 This command will look at the current kill and check if is a single
18828 subtree, or a series of subtrees[1]. If it passes the test, and if the
18829 cursor is at the beginning of a line or after the stars of a currently
18830 empty headline, then the yank is handled specially. How exactly depends
18831 on the value of the following variables, both set by default.
18833 org-yank-folded-subtrees
18834 When set, the subtree(s) will be folded after insertion, but only
18835 if doing so would now swallow text after the yanked text.
18837 org-yank-adjusted-subtrees
18838 When set, the subtree will be promoted or demoted in order to
18839 fit into the local outline tree structure, which means that the level
18840 will be adjusted so that it becomes the smaller one of the two
18841 *visible* surrounding headings.
18843 Any prefix to this command will cause `yank' to be called directly with
18844 no special treatment. In particular, a simple \\[universal-argument] prefix \
18845 will just
18846 plainly yank the text as it is.
18848 \[1] The test checks if the first non-white line is a heading
18849 and if there are no other headings with fewer stars."
18850 (interactive "P")
18851 (org-yank-generic 'yank arg))
18853 (defun org-yank-generic (command arg)
18854 "Perform some yank-like command.
18856 This function implements the behavior described in the `org-yank'
18857 documentation. However, it has been generalized to work for any
18858 interactive command with similar behavior."
18860 ;; pretend to be command COMMAND
18861 (setq this-command command)
18863 (if arg
18864 (call-interactively command)
18866 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
18867 (and (org-kill-is-subtree-p)
18868 (or (bolp)
18869 (and (looking-at "[ \t]*$")
18870 (string-match
18871 "\\`\\*+\\'"
18872 (buffer-substring (point-at-bol) (point)))))))
18873 swallowp)
18874 (cond
18875 ((and subtreep org-yank-folded-subtrees)
18876 (let ((beg (point))
18877 end)
18878 (if (and subtreep org-yank-adjusted-subtrees)
18879 (org-paste-subtree nil nil 'for-yank)
18880 (call-interactively command))
18882 (setq end (point))
18883 (goto-char beg)
18884 (when (and (bolp) subtreep
18885 (not (setq swallowp
18886 (org-yank-folding-would-swallow-text beg end))))
18887 (or (looking-at outline-regexp)
18888 (re-search-forward (concat "^" outline-regexp) end t))
18889 (while (and (< (point) end) (looking-at outline-regexp))
18890 (hide-subtree)
18891 (org-cycle-show-empty-lines 'folded)
18892 (condition-case nil
18893 (outline-forward-same-level 1)
18894 (error (goto-char end)))))
18895 (when swallowp
18896 (message
18897 "Inserted text not folded because that would swallow text"))
18899 (goto-char end)
18900 (skip-chars-forward " \t\n\r")
18901 (beginning-of-line 1)
18902 (push-mark beg 'nomsg)))
18903 ((and subtreep org-yank-adjusted-subtrees)
18904 (let ((beg (point-at-bol)))
18905 (org-paste-subtree nil nil 'for-yank)
18906 (push-mark beg 'nomsg)))
18908 (call-interactively command))))))
18910 (defun org-yank-folding-would-swallow-text (beg end)
18911 "Would hide-subtree at BEG swallow any text after END?"
18912 (let (level)
18913 (save-excursion
18914 (goto-char beg)
18915 (when (or (looking-at outline-regexp)
18916 (re-search-forward (concat "^" outline-regexp) end t))
18917 (setq level (org-outline-level)))
18918 (goto-char end)
18919 (skip-chars-forward " \t\r\n\v\f")
18920 (if (or (eobp)
18921 (and (bolp) (looking-at org-outline-regexp)
18922 (<= (org-outline-level) level)))
18923 nil ; Nothing would be swallowed
18924 t)))) ; something would swallow
18926 (define-key org-mode-map "\C-y" 'org-yank)
18928 (defun org-invisible-p ()
18929 "Check if point is at a character currently not visible."
18930 ;; Early versions of noutline don't have `outline-invisible-p'.
18931 (if (fboundp 'outline-invisible-p)
18932 (outline-invisible-p)
18933 (get-char-property (point) 'invisible)))
18935 (defun org-truely-invisible-p ()
18936 "Check if point is at a character currently not visible.
18937 This version does not only check the character property, but also
18938 `visible-mode'."
18939 ;; Early versions of noutline don't have `outline-invisible-p'.
18940 (if (org-bound-and-true-p visible-mode)
18942 (if (fboundp 'outline-invisible-p)
18943 (outline-invisible-p)
18944 (get-char-property (point) 'invisible))))
18946 (defun org-invisible-p2 ()
18947 "Check if point is at a character currently not visible."
18948 (save-excursion
18949 (if (and (eolp) (not (bobp))) (backward-char 1))
18950 ;; Early versions of noutline don't have `outline-invisible-p'.
18951 (if (fboundp 'outline-invisible-p)
18952 (outline-invisible-p)
18953 (get-char-property (point) 'invisible))))
18955 (defun org-back-to-heading (&optional invisible-ok)
18956 "Call `outline-back-to-heading', but provide a better error message."
18957 (condition-case nil
18958 (outline-back-to-heading invisible-ok)
18959 (error (error "Before first headline at position %d in buffer %s"
18960 (point) (current-buffer)))))
18962 (defun org-beginning-of-defun ()
18963 "Go to the beginning of the subtree, i.e. back to the heading."
18964 (org-back-to-heading))
18965 (defun org-end-of-defun ()
18966 "Go to the end of the subtree."
18967 (org-end-of-subtree nil t))
18969 (defun org-before-first-heading-p ()
18970 "Before first heading?"
18971 (save-excursion
18972 (null (re-search-backward "^\\*+ " nil t))))
18974 (defun org-on-heading-p (&optional ignored)
18975 (outline-on-heading-p t))
18976 (defun org-at-heading-p (&optional ignored)
18977 (outline-on-heading-p t))
18979 (defun org-point-at-end-of-empty-headline ()
18980 "If point is at the end of an empty headline, return t, else nil.
18981 If the heading only contains a TODO keyword, it is still still considered
18982 empty."
18983 (and (looking-at "[ \t]*$")
18984 (save-excursion
18985 (beginning-of-line 1)
18986 (looking-at (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp
18987 "\\)?[ \t]*$")))))
18988 (defun org-at-heading-or-item-p ()
18989 (or (org-on-heading-p) (org-at-item-p)))
18991 (defun org-on-target-p ()
18992 (or (org-in-regexp org-radio-target-regexp)
18993 (org-in-regexp org-target-regexp)))
18995 (defun org-up-heading-all (arg)
18996 "Move to the heading line of which the present line is a subheading.
18997 This function considers both visible and invisible heading lines.
18998 With argument, move up ARG levels."
18999 (if (fboundp 'outline-up-heading-all)
19000 (outline-up-heading-all arg) ; emacs 21 version of outline.el
19001 (outline-up-heading arg t))) ; emacs 22 version of outline.el
19003 (defun org-up-heading-safe ()
19004 "Move to the heading line of which the present line is a subheading.
19005 This version will not throw an error. It will return the level of the
19006 headline found, or nil if no higher level is found.
19008 Also, this function will be a lot faster than `outline-up-heading',
19009 because it relies on stars being the outline starters. This can really
19010 make a significant difference in outlines with very many siblings."
19011 (let (start-level re)
19012 (org-back-to-heading t)
19013 (setq start-level (funcall outline-level))
19014 (if (equal start-level 1)
19016 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
19017 (if (re-search-backward re nil t)
19018 (funcall outline-level)))))
19020 (defun org-first-sibling-p ()
19021 "Is this heading the first child of its parents?"
19022 (interactive)
19023 (let ((re (concat "^" outline-regexp))
19024 level l)
19025 (unless (org-at-heading-p t)
19026 (error "Not at a heading"))
19027 (setq level (funcall outline-level))
19028 (save-excursion
19029 (if (not (re-search-backward re nil t))
19031 (setq l (funcall outline-level))
19032 (< l level)))))
19034 (defun org-goto-sibling (&optional previous)
19035 "Goto the next sibling, even if it is invisible.
19036 When PREVIOUS is set, go to the previous sibling instead. Returns t
19037 when a sibling was found. When none is found, return nil and don't
19038 move point."
19039 (let ((fun (if previous 're-search-backward 're-search-forward))
19040 (pos (point))
19041 (re (concat "^" outline-regexp))
19042 level l)
19043 (when (condition-case nil (org-back-to-heading t) (error nil))
19044 (setq level (funcall outline-level))
19045 (catch 'exit
19046 (or previous (forward-char 1))
19047 (while (funcall fun re nil t)
19048 (setq l (funcall outline-level))
19049 (when (< l level) (goto-char pos) (throw 'exit nil))
19050 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
19051 (goto-char pos)
19052 nil))))
19054 (defun org-show-siblings ()
19055 "Show all siblings of the current headline."
19056 (save-excursion
19057 (while (org-goto-sibling) (org-flag-heading nil)))
19058 (save-excursion
19059 (while (org-goto-sibling 'previous)
19060 (org-flag-heading nil))))
19062 (defun org-show-hidden-entry ()
19063 "Show an entry where even the heading is hidden."
19064 (save-excursion
19065 (org-show-entry)))
19067 (defun org-flag-heading (flag &optional entry)
19068 "Flag the current heading. FLAG non-nil means make invisible.
19069 When ENTRY is non-nil, show the entire entry."
19070 (save-excursion
19071 (org-back-to-heading t)
19072 ;; Check if we should show the entire entry
19073 (if entry
19074 (progn
19075 (org-show-entry)
19076 (save-excursion
19077 (and (outline-next-heading)
19078 (org-flag-heading nil))))
19079 (outline-flag-region (max (point-min) (1- (point)))
19080 (save-excursion (outline-end-of-heading) (point))
19081 flag))))
19083 (defun org-get-next-sibling ()
19084 "Move to next heading of the same level, and return point.
19085 If there is no such heading, return nil.
19086 This is like outline-next-sibling, but invisible headings are ok."
19087 (let ((level (funcall outline-level)))
19088 (outline-next-heading)
19089 (while (and (not (eobp)) (> (funcall outline-level) level))
19090 (outline-next-heading))
19091 (if (or (eobp) (< (funcall outline-level) level))
19093 (point))))
19095 (defun org-get-last-sibling ()
19096 "Move to previous heading of the same level, and return point.
19097 If there is no such heading, return nil."
19098 (let ((opoint (point))
19099 (level (funcall outline-level)))
19100 (outline-previous-heading)
19101 (when (and (/= (point) opoint) (outline-on-heading-p t))
19102 (while (and (> (funcall outline-level) level)
19103 (not (bobp)))
19104 (outline-previous-heading))
19105 (if (< (funcall outline-level) level)
19107 (point)))))
19109 (defun org-end-of-subtree (&optional invisible-OK to-heading)
19110 ;; This contains an exact copy of the original function, but it uses
19111 ;; `org-back-to-heading', to make it work also in invisible
19112 ;; trees. And is uses an invisible-OK argument.
19113 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
19114 ;; Furthermore, when used inside Org, finding the end of a large subtree
19115 ;; with many children and grandchildren etc, this can be much faster
19116 ;; than the outline version.
19117 (org-back-to-heading invisible-OK)
19118 (let ((first t)
19119 (level (funcall outline-level)))
19120 (if (and (org-mode-p) (< level 1000))
19121 ;; A true heading (not a plain list item), in Org-mode
19122 ;; This means we can easily find the end by looking
19123 ;; only for the right number of stars. Using a regexp to do
19124 ;; this is so much faster than using a Lisp loop.
19125 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
19126 (forward-char 1)
19127 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
19128 ;; something else, do it the slow way
19129 (while (and (not (eobp))
19130 (or first (> (funcall outline-level) level)))
19131 (setq first nil)
19132 (outline-next-heading)))
19133 (unless to-heading
19134 (if (memq (preceding-char) '(?\n ?\^M))
19135 (progn
19136 ;; Go to end of line before heading
19137 (forward-char -1)
19138 (if (memq (preceding-char) '(?\n ?\^M))
19139 ;; leave blank line before heading
19140 (forward-char -1))))))
19141 (point))
19143 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
19144 "Use Org version in org-mode, for dramatic speed-up."
19145 (if (eq major-mode 'org-mode)
19146 (progn
19147 (org-end-of-subtree nil t)
19148 (unless (eobp) (backward-char 1)))
19149 ad-do-it))
19151 (defun org-forward-same-level (arg &optional invisible-ok)
19152 "Move forward to the arg'th subheading at same level as this one.
19153 Stop at the first and last subheadings of a superior heading."
19154 (interactive "p")
19155 (org-back-to-heading invisible-ok)
19156 (org-on-heading-p)
19157 (let* ((level (- (match-end 0) (match-beginning 0) 1))
19158 (re (format "^\\*\\{1,%d\\} " level))
19160 (forward-char 1)
19161 (while (> arg 0)
19162 (while (and (re-search-forward re nil 'move)
19163 (setq l (- (match-end 0) (match-beginning 0) 1))
19164 (= l level)
19165 (not invisible-ok)
19166 (progn (backward-char 1) (org-invisible-p)))
19167 (if (< l level) (setq arg 1)))
19168 (setq arg (1- arg)))
19169 (beginning-of-line 1)))
19171 (defun org-backward-same-level (arg &optional invisible-ok)
19172 "Move backward to the arg'th subheading at same level as this one.
19173 Stop at the first and last subheadings of a superior heading."
19174 (interactive "p")
19175 (org-back-to-heading)
19176 (org-on-heading-p)
19177 (let* ((level (- (match-end 0) (match-beginning 0) 1))
19178 (re (format "^\\*\\{1,%d\\} " level))
19180 (while (> arg 0)
19181 (while (and (re-search-backward re nil 'move)
19182 (setq l (- (match-end 0) (match-beginning 0) 1))
19183 (= l level)
19184 (not invisible-ok)
19185 (org-invisible-p))
19186 (if (< l level) (setq arg 1)))
19187 (setq arg (1- arg)))))
19189 (defun org-show-subtree ()
19190 "Show everything after this heading at deeper levels."
19191 (outline-flag-region
19192 (point)
19193 (save-excursion
19194 (org-end-of-subtree t t))
19195 nil))
19197 (defun org-show-entry ()
19198 "Show the body directly following this heading.
19199 Show the heading too, if it is currently invisible."
19200 (interactive)
19201 (save-excursion
19202 (condition-case nil
19203 (progn
19204 (org-back-to-heading t)
19205 (outline-flag-region
19206 (max (point-min) (1- (point)))
19207 (save-excursion
19208 (if (re-search-forward
19209 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
19210 (match-beginning 1)
19211 (point-max)))
19212 nil)
19213 (org-cycle-hide-drawers 'children))
19214 (error nil))))
19216 (defun org-make-options-regexp (kwds &optional extra)
19217 "Make a regular expression for keyword lines."
19218 (concat
19220 "#?[ \t]*\\+\\("
19221 (mapconcat 'regexp-quote kwds "\\|")
19222 (if extra (concat "\\|" extra))
19223 "\\):[ \t]*"
19224 "\\(.*\\)"))
19226 ;; Make isearch reveal the necessary context
19227 (defun org-isearch-end ()
19228 "Reveal context after isearch exits."
19229 (when isearch-success ; only if search was successful
19230 (if (featurep 'xemacs)
19231 ;; Under XEmacs, the hook is run in the correct place,
19232 ;; we directly show the context.
19233 (org-show-context 'isearch)
19234 ;; In Emacs the hook runs *before* restoring the overlays.
19235 ;; So we have to use a one-time post-command-hook to do this.
19236 ;; (Emacs 22 has a special variable, see function `org-mode')
19237 (unless (and (boundp 'isearch-mode-end-hook-quit)
19238 isearch-mode-end-hook-quit)
19239 ;; Only when the isearch was not quitted.
19240 (org-add-hook 'post-command-hook 'org-isearch-post-command
19241 'append 'local)))))
19243 (defun org-isearch-post-command ()
19244 "Remove self from hook, and show context."
19245 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
19246 (org-show-context 'isearch))
19249 ;;;; Integration with and fixes for other packages
19251 ;;; Imenu support
19253 (defvar org-imenu-markers nil
19254 "All markers currently used by Imenu.")
19255 (make-variable-buffer-local 'org-imenu-markers)
19257 (defun org-imenu-new-marker (&optional pos)
19258 "Return a new marker for use by Imenu, and remember the marker."
19259 (let ((m (make-marker)))
19260 (move-marker m (or pos (point)))
19261 (push m org-imenu-markers)
19264 (defun org-imenu-get-tree ()
19265 "Produce the index for Imenu."
19266 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
19267 (setq org-imenu-markers nil)
19268 (let* ((n org-imenu-depth)
19269 (re (concat "^" outline-regexp))
19270 (subs (make-vector (1+ n) nil))
19271 (last-level 0)
19272 m level head)
19273 (save-excursion
19274 (save-restriction
19275 (widen)
19276 (goto-char (point-max))
19277 (while (re-search-backward re nil t)
19278 (setq level (org-reduced-level (funcall outline-level)))
19279 (when (<= level n)
19280 (looking-at org-complex-heading-regexp)
19281 (setq head (org-link-display-format
19282 (org-match-string-no-properties 4))
19283 m (org-imenu-new-marker))
19284 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
19285 (if (>= level last-level)
19286 (push (cons head m) (aref subs level))
19287 (push (cons head (aref subs (1+ level))) (aref subs level))
19288 (loop for i from (1+ level) to n do (aset subs i nil)))
19289 (setq last-level level)))))
19290 (aref subs 1)))
19292 (eval-after-load "imenu"
19293 '(progn
19294 (add-hook 'imenu-after-jump-hook
19295 (lambda ()
19296 (if (eq major-mode 'org-mode)
19297 (org-show-context 'org-goto))))))
19299 (defun org-link-display-format (link)
19300 "Replace a link with either the description, or the link target
19301 if no description is present"
19302 (save-match-data
19303 (if (string-match org-bracket-link-analytic-regexp link)
19304 (replace-match (if (match-end 5)
19305 (match-string 5 link)
19306 (concat (match-string 1 link)
19307 (match-string 3 link)))
19308 nil t link)
19309 link)))
19311 ;; Speedbar support
19313 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
19314 "Overlay marking the agenda restriction line in speedbar.")
19315 (overlay-put org-speedbar-restriction-lock-overlay
19316 'face 'org-agenda-restriction-lock)
19317 (overlay-put org-speedbar-restriction-lock-overlay
19318 'help-echo "Agendas are currently limited to this item.")
19319 (org-detach-overlay org-speedbar-restriction-lock-overlay)
19321 (defun org-speedbar-set-agenda-restriction ()
19322 "Restrict future agenda commands to the location at point in speedbar.
19323 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
19324 (interactive)
19325 (require 'org-agenda)
19326 (let (p m tp np dir txt)
19327 (cond
19328 ((setq p (text-property-any (point-at-bol) (point-at-eol)
19329 'org-imenu t))
19330 (setq m (get-text-property p 'org-imenu-marker))
19331 (with-current-buffer (marker-buffer m)
19332 (goto-char m)
19333 (org-agenda-set-restriction-lock 'subtree)))
19334 ((setq p (text-property-any (point-at-bol) (point-at-eol)
19335 'speedbar-function 'speedbar-find-file))
19336 (setq tp (previous-single-property-change
19337 (1+ p) 'speedbar-function)
19338 np (next-single-property-change
19339 tp 'speedbar-function)
19340 dir (speedbar-line-directory)
19341 txt (buffer-substring-no-properties (or tp (point-min))
19342 (or np (point-max))))
19343 (with-current-buffer (find-file-noselect
19344 (let ((default-directory dir))
19345 (expand-file-name txt)))
19346 (unless (org-mode-p)
19347 (error "Cannot restrict to non-Org-mode file"))
19348 (org-agenda-set-restriction-lock 'file)))
19349 (t (error "Don't know how to restrict Org-mode's agenda")))
19350 (move-overlay org-speedbar-restriction-lock-overlay
19351 (point-at-bol) (point-at-eol))
19352 (setq current-prefix-arg nil)
19353 (org-agenda-maybe-redo)))
19355 (eval-after-load "speedbar"
19356 '(progn
19357 (speedbar-add-supported-extension ".org")
19358 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
19359 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
19360 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
19361 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19362 (add-hook 'speedbar-visiting-tag-hook
19363 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
19365 ;;; Fixes and Hacks for problems with other packages
19367 ;; Make flyspell not check words in links, to not mess up our keymap
19368 (defun org-mode-flyspell-verify ()
19369 "Don't let flyspell put overlays at active buttons."
19370 (and (not (get-text-property (point) 'keymap))
19371 (not (get-text-property (point) 'org-no-flyspell))))
19373 (defun org-remove-flyspell-overlays-in (beg end)
19374 "Remove flyspell overlays in region."
19375 (and (org-bound-and-true-p flyspell-mode)
19376 (fboundp 'flyspell-delete-region-overlays)
19377 (flyspell-delete-region-overlays beg end))
19378 (add-text-properties beg end '(org-no-flyspell t)))
19380 ;; Make `bookmark-jump' shows the jump location if it was hidden.
19381 (eval-after-load "bookmark"
19382 '(if (boundp 'bookmark-after-jump-hook)
19383 ;; We can use the hook
19384 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
19385 ;; Hook not available, use advice
19386 (defadvice bookmark-jump (after org-make-visible activate)
19387 "Make the position visible."
19388 (org-bookmark-jump-unhide))))
19390 ;; Make sure saveplace shows the location if it was hidden
19391 (eval-after-load "saveplace"
19392 '(defadvice save-place-find-file-hook (after org-make-visible activate)
19393 "Make the position visible."
19394 (org-bookmark-jump-unhide)))
19396 ;; Make sure ecb shows the location if it was hidden
19397 (eval-after-load "ecb"
19398 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
19399 "Make hierarchy visible when jumping into location from ECB tree buffer."
19400 (if (eq major-mode 'org-mode)
19401 (org-show-context))))
19403 (defun org-bookmark-jump-unhide ()
19404 "Unhide the current position, to show the bookmark location."
19405 (and (org-mode-p)
19406 (or (org-invisible-p)
19407 (save-excursion (goto-char (max (point-min) (1- (point))))
19408 (org-invisible-p)))
19409 (org-show-context 'bookmark-jump)))
19411 ;; Make session.el ignore our circular variable
19412 (eval-after-load "session"
19413 '(add-to-list 'session-globals-exclude 'org-mark-ring))
19415 ;;;; Experimental code
19417 (defun org-closed-in-range ()
19418 "Sparse tree of items closed in a certain time range.
19419 Still experimental, may disappear in the future."
19420 (interactive)
19421 ;; Get the time interval from the user.
19422 (let* ((time1 (org-float-time
19423 (org-read-date nil 'to-time nil "Starting date: ")))
19424 (time2 (org-float-time
19425 (org-read-date nil 'to-time nil "End date:")))
19426 ;; callback function
19427 (callback (lambda ()
19428 (let ((time
19429 (org-float-time
19430 (apply 'encode-time
19431 (org-parse-time-string
19432 (match-string 1))))))
19433 ;; check if time in interval
19434 (and (>= time time1) (<= time time2))))))
19435 ;; make tree, check each match with the callback
19436 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
19438 ;;;; Finish up
19440 (provide 'org)
19442 (run-hooks 'org-load-hook)
19444 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
19446 ;;; org.el ends here