org-insert-time-stamp: fix value of org-last-inserted-timestamp
[org-mode.git] / lisp / org.el
blob41c3e90c615a4cc23ec7fe81e17618224e6773d0
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.01trans
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 "Ledger" ledger)
163 (const :tag "Matlab" matlab)
164 (const :tag "Mscgen" mscgen)
165 (const :tag "Ocaml" ocaml)
166 (const :tag "Octave" octave)
167 (const :tag "Perl" perl)
168 (const :tag "Python" python)
169 (const :tag "Ruby" ruby)
170 (const :tag "Sass" sass)
171 (const :tag "Screen" screen)
172 (const :tag "Shell Script" sh)
173 (const :tag "Sql" sql)
174 (const :tag "Sqlite" sqlite))
175 :value-type (boolean :tag "Activate" :value t)))
177 ;;;; Customization variables
178 (defcustom org-clone-delete-id nil
179 "Remove ID property of clones of a subtree.
180 When non-nil, clones of a subtree don't inherit the ID property.
181 Otherwise they inherit the ID property with a new unique
182 identifier."
183 :type 'boolean
184 :group 'org-id)
186 ;;; Version
188 (defconst org-version "7.01trans"
189 "The version number of the file org.el.")
191 (defun org-version (&optional here)
192 "Show the org-mode version in the echo area.
193 With prefix arg HERE, insert it at point."
194 (interactive "P")
195 (let* ((origin default-directory)
196 (version org-version)
197 (git-version)
198 (dir (concat (file-name-directory (locate-library "org")) "../" )))
199 (when (and (file-exists-p (expand-file-name ".git" dir))
200 (executable-find "git"))
201 (unwind-protect
202 (progn
203 (cd dir)
204 (when (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
205 (with-current-buffer "*Shell Command Output*"
206 (goto-char (point-min))
207 (setq git-version (buffer-substring (point) (point-at-eol))))
208 (subst-char-in-string ?- ?. git-version t)
209 (when (string-match "\\S-"
210 (shell-command-to-string
211 "git diff-index --name-only HEAD --"))
212 (setq git-version (concat git-version ".dirty")))
213 (setq version (concat version " (" git-version ")"))))
214 (cd origin)))
215 (setq version (format "Org-mode version %s" version))
216 (if here (insert version))
217 (message version)))
219 ;;; Compatibility constants
221 ;;; The custom variables
223 (defgroup org nil
224 "Outline-based notes management and organizer."
225 :tag "Org"
226 :group 'outlines
227 :group 'calendar)
229 (defcustom org-mode-hook nil
230 "Mode hook for Org-mode, run after the mode was turned on."
231 :group 'org
232 :type 'hook)
234 (defcustom org-load-hook nil
235 "Hook that is run after org.el has been loaded."
236 :group 'org
237 :type 'hook)
239 (defvar org-modules) ; defined below
240 (defvar org-modules-loaded nil
241 "Have the modules been loaded already?")
243 (defun org-load-modules-maybe (&optional force)
244 "Load all extensions listed in `org-modules'."
245 (when (or force (not org-modules-loaded))
246 (mapc (lambda (ext)
247 (condition-case nil (require ext)
248 (error (message "Problems while trying to load feature `%s'" ext))))
249 org-modules)
250 (setq org-modules-loaded t)))
252 (defun org-set-modules (var value)
253 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
254 (set var value)
255 (when (featurep 'org)
256 (org-load-modules-maybe 'force)))
258 (when (org-bound-and-true-p org-modules)
259 (let ((a (member 'org-infojs org-modules)))
260 (and a (setcar a 'org-jsinfo))))
262 (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)
263 "Modules that should always be loaded together with org.el.
264 If a description starts with <C>, the file is not part of Emacs
265 and loading it will require that you have downloaded and properly installed
266 the org-mode distribution.
268 You can also use this system to load external packages (i.e. neither Org
269 core modules, nor modules from the CONTRIB directory). Just add symbols
270 to the end of the list. If the package is called org-xyz.el, then you need
271 to add the symbol `xyz', and the package must have a call to
273 (provide 'org-xyz)"
274 :group 'org
275 :set 'org-set-modules
276 :type
277 '(set :greedy t
278 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
279 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
280 (const :tag " crypt: Encryption of subtrees" org-crypt)
281 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
282 (const :tag " docview: Links to doc-view buffers" org-docview)
283 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
284 (const :tag " id: Global IDs for identifying entries" org-id)
285 (const :tag " info: Links to Info nodes" org-info)
286 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
287 (const :tag " habit: Track your consistency with habits" org-habit)
288 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
289 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
290 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
291 (const :tag " mew Links to Mew folders/messages" org-mew)
292 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
293 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
294 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
295 (const :tag " vm: Links to VM folders/messages" org-vm)
296 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
297 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
298 (const :tag " mouse: Additional mouse support" org-mouse)
299 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
301 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
302 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
303 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
304 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
305 (const :tag "C collector: Collect properties into tables" org-collector)
306 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
307 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
308 (const :tag "C eval: Include command output as text" org-eval)
309 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
310 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
311 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
312 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
313 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
315 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
317 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
318 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
319 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
320 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
321 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
322 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
323 (const :tag "C mtags: Support for muse-like tags" org-mtags)
324 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
325 (const :tag "C registry: A registry for Org-mode links" org-registry)
326 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
327 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
328 (const :tag "C secretary: Team management with org-mode" org-secretary)
329 (const :tag "C special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
330 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
331 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
332 (const :tag "C track: Keep up with Org-mode development" org-track)
333 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
334 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
336 (defcustom org-support-shift-select nil
337 "Non-nil means make shift-cursor commands select text when possible.
339 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
340 selecting a region, or enlarge regions started in this way.
341 In Org-mode, in special contexts, these same keys are used for other
342 purposes, important enough to compete with shift selection. Org tries
343 to balance these needs by supporting `shift-select-mode' outside these
344 special contexts, under control of this variable.
346 The default of this variable is nil, to avoid confusing behavior. Shifted
347 cursor keys will then execute Org commands in the following contexts:
348 - on a headline, changing TODO state (left/right) and priority (up/down)
349 - on a time stamp, changing the time
350 - in a plain list item, changing the bullet type
351 - in a property definition line, switching between allowed values
352 - in the BEGIN line of a clock table (changing the time block).
353 Outside these contexts, the commands will throw an error.
355 When this variable is t and the cursor is not in a special context,
356 Org-mode will support shift-selection for making and enlarging regions.
357 To make this more effective, the bullet cycling will no longer happen
358 anywhere in an item line, but only if the cursor is exactly on the bullet.
360 If you set this variable to the symbol `always', then the keys
361 will not be special in headlines, property lines, and item lines, to make
362 shift selection work there as well. If this is what you want, you can
363 use the following alternative commands: `C-c C-t' and `C-c ,' to
364 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
365 TODO sets, `C-c -' to cycle item bullet types, and properties can be
366 edited by hand or in column view.
368 However, when the cursor is on a timestamp, shift-cursor commands
369 will still edit the time stamp - this is just too good to give up.
371 XEmacs user should have this variable set to nil, because shift-select-mode
372 is Emacs 23 only."
373 :group 'org
374 :type '(choice
375 (const :tag "Never" nil)
376 (const :tag "When outside special context" t)
377 (const :tag "Everywhere except timestamps" always)))
379 (defgroup org-startup nil
380 "Options concerning startup of Org-mode."
381 :tag "Org Startup"
382 :group 'org)
384 (defcustom org-startup-folded t
385 "Non-nil means entering Org-mode will switch to OVERVIEW.
386 This can also be configured on a per-file basis by adding one of
387 the following lines anywhere in the buffer:
389 #+STARTUP: fold (or `overview', this is equivalent)
390 #+STARTUP: nofold (or `showall', this is equivalent)
391 #+STARTUP: content
392 #+STARTUP: showeverything"
393 :group 'org-startup
394 :type '(choice
395 (const :tag "nofold: show all" nil)
396 (const :tag "fold: overview" t)
397 (const :tag "content: all headlines" content)
398 (const :tag "show everything, even drawers" showeverything)))
400 (defcustom org-startup-truncated t
401 "Non-nil means entering Org-mode will set `truncate-lines'.
402 This is useful since some lines containing links can be very long and
403 uninteresting. Also tables look terrible when wrapped."
404 :group 'org-startup
405 :type 'boolean)
407 (defcustom org-startup-indented nil
408 "Non-nil means turn on `org-indent-mode' on startup.
409 This can also be configured on a per-file basis by adding one of
410 the following lines anywhere in the buffer:
412 #+STARTUP: indent
413 #+STARTUP: noindent"
414 :group 'org-structure
415 :type '(choice
416 (const :tag "Not" nil)
417 (const :tag "Globally (slow on startup in large files)" t)))
419 (defcustom org-use-sub-superscripts t
420 "Non-nil means interpret \"_\" and \"^\" for export.
421 When this option is turned on, you can use TeX-like syntax for sub- and
422 superscripts. Several characters after \"_\" or \"^\" will be
423 considered as a single item - so grouping with {} is normally not
424 needed. For example, the following things will be parsed as single
425 sub- or superscripts.
427 10^24 or 10^tau several digits will be considered 1 item.
428 10^-12 or 10^-tau a leading sign with digits or a word
429 x^2-y^3 will be read as x^2 - y^3, because items are
430 terminated by almost any nonword/nondigit char.
431 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
433 Still, ambiguity is possible - so when in doubt use {} to enclose the
434 sub/superscript. If you set this variable to the symbol `{}',
435 the braces are *required* in order to trigger interpretations as
436 sub/superscript. This can be helpful in documents that need \"_\"
437 frequently in plain text.
439 Not all export backends support this, but HTML does.
441 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
442 :group 'org-startup
443 :group 'org-export-translation
444 :type '(choice
445 (const :tag "Always interpret" t)
446 (const :tag "Only with braces" {})
447 (const :tag "Never interpret" nil)))
449 (if (fboundp 'defvaralias)
450 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
453 (defcustom org-startup-with-beamer-mode nil
454 "Non-nil means turn on `org-beamer-mode' on startup.
455 This can also be configured on a per-file basis by adding one of
456 the following lines anywhere in the buffer:
458 #+STARTUP: beamer"
459 :group 'org-startup
460 :type 'boolean)
462 (defcustom org-startup-align-all-tables nil
463 "Non-nil means align all tables when visiting a file.
464 This is useful when the column width in tables is forced with <N> cookies
465 in table fields. Such tables will look correct only after the first re-align.
466 This can also be configured on a per-file basis by adding one of
467 the following lines anywhere in the buffer:
468 #+STARTUP: align
469 #+STARTUP: noalign"
470 :group 'org-startup
471 :type 'boolean)
473 (defcustom org-insert-mode-line-in-empty-file nil
474 "Non-nil means insert the first line setting Org-mode in empty files.
475 When the function `org-mode' is called interactively in an empty file, this
476 normally means that the file name does not automatically trigger Org-mode.
477 To ensure that the file will always be in Org-mode in the future, a
478 line enforcing Org-mode will be inserted into the buffer, if this option
479 has been set."
480 :group 'org-startup
481 :type 'boolean)
483 (defcustom org-replace-disputed-keys nil
484 "Non-nil means use alternative key bindings for some keys.
485 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
486 These keys are also used by other packages like shift-selection-mode'
487 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
488 If you want to use Org-mode together with one of these other modes,
489 or more generally if you would like to move some Org-mode commands to
490 other keys, set this variable and configure the keys with the variable
491 `org-disputed-keys'.
493 This option is only relevant at load-time of Org-mode, and must be set
494 *before* org.el is loaded. Changing it requires a restart of Emacs to
495 become effective."
496 :group 'org-startup
497 :type 'boolean)
499 (defcustom org-use-extra-keys nil
500 "Non-nil means use extra key sequence definitions for certain commands.
501 This happens automatically if you run XEmacs or if `window-system'
502 is nil. This variable lets you do the same manually. You must
503 set it before loading org.
505 Example: on Carbon Emacs 22 running graphically, with an external
506 keyboard on a Powerbook, the default way of setting M-left might
507 not work for either Alt or ESC. Setting this variable will make
508 it work for ESC."
509 :group 'org-startup
510 :type 'boolean)
512 (if (fboundp 'defvaralias)
513 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
515 (defcustom org-disputed-keys
516 '(([(shift up)] . [(meta p)])
517 ([(shift down)] . [(meta n)])
518 ([(shift left)] . [(meta -)])
519 ([(shift right)] . [(meta +)])
520 ([(control shift right)] . [(meta shift +)])
521 ([(control shift left)] . [(meta shift -)]))
522 "Keys for which Org-mode and other modes compete.
523 This is an alist, cars are the default keys, second element specifies
524 the alternative to use when `org-replace-disputed-keys' is t.
526 Keys can be specified in any syntax supported by `define-key'.
527 The value of this option takes effect only at Org-mode's startup,
528 therefore you'll have to restart Emacs to apply it after changing."
529 :group 'org-startup
530 :type 'alist)
532 (defun org-key (key)
533 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
534 Or return the original if not disputed.
535 Also apply the translations defined in `org-xemacs-key-equivalents'."
536 (when org-replace-disputed-keys
537 (let* ((nkey (key-description key))
538 (x (org-find-if (lambda (x)
539 (equal (key-description (car x)) nkey))
540 org-disputed-keys)))
541 (setq key (if x (cdr x) key))))
542 (when (featurep 'xemacs)
543 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
544 key)
546 (defun org-find-if (predicate seq)
547 (catch 'exit
548 (while seq
549 (if (funcall predicate (car seq))
550 (throw 'exit (car seq))
551 (pop seq)))))
553 (defun org-defkey (keymap key def)
554 "Define a key, possibly translated, as returned by `org-key'."
555 (define-key keymap (org-key key) def))
557 (defcustom org-ellipsis nil
558 "The ellipsis to use in the Org-mode outline.
559 When nil, just use the standard three dots. When a string, use that instead,
560 When a face, use the standard 3 dots, but with the specified face.
561 The change affects only Org-mode (which will then use its own display table).
562 Changing this requires executing `M-x org-mode' in a buffer to become
563 effective."
564 :group 'org-startup
565 :type '(choice (const :tag "Default" nil)
566 (face :tag "Face" :value org-warning)
567 (string :tag "String" :value "...#")))
569 (defvar org-display-table nil
570 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
572 (defgroup org-keywords nil
573 "Keywords in Org-mode."
574 :tag "Org Keywords"
575 :group 'org)
577 (defcustom org-deadline-string "DEADLINE:"
578 "String to mark deadline entries.
579 A deadline is this string, followed by a time stamp. Should be a word,
580 terminated by a colon. You can insert a schedule keyword and
581 a timestamp with \\[org-deadline].
582 Changes become only effective after restarting Emacs."
583 :group 'org-keywords
584 :type 'string)
586 (defcustom org-scheduled-string "SCHEDULED:"
587 "String to mark scheduled TODO entries.
588 A schedule is this string, followed by a time stamp. Should be a word,
589 terminated by a colon. You can insert a schedule keyword and
590 a timestamp with \\[org-schedule].
591 Changes become only effective after restarting Emacs."
592 :group 'org-keywords
593 :type 'string)
595 (defcustom org-closed-string "CLOSED:"
596 "String used as the prefix for timestamps logging closing a TODO entry."
597 :group 'org-keywords
598 :type 'string)
600 (defcustom org-clock-string "CLOCK:"
601 "String used as prefix for timestamps clocking work hours on an item."
602 :group 'org-keywords
603 :type 'string)
605 (defcustom org-comment-string "COMMENT"
606 "Entries starting with this keyword will never be exported.
607 An entry can be toggled between COMMENT and normal with
608 \\[org-toggle-comment].
609 Changes become only effective after restarting Emacs."
610 :group 'org-keywords
611 :type 'string)
613 (defcustom org-quote-string "QUOTE"
614 "Entries starting with this keyword will be exported in fixed-width font.
615 Quoting applies only to the text in the entry following the headline, and does
616 not extend beyond the next headline, even if that is lower level.
617 An entry can be toggled between QUOTE and normal with
618 \\[org-toggle-fixed-width-section]."
619 :group 'org-keywords
620 :type 'string)
622 (defconst org-repeat-re
623 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
624 "Regular expression for specifying repeated events.
625 After a match, group 1 contains the repeat expression.")
627 (defgroup org-structure nil
628 "Options concerning the general structure of Org-mode files."
629 :tag "Org Structure"
630 :group 'org)
632 (defgroup org-reveal-location nil
633 "Options about how to make context of a location visible."
634 :tag "Org Reveal Location"
635 :group 'org-structure)
637 (defconst org-context-choice
638 '(choice
639 (const :tag "Always" t)
640 (const :tag "Never" nil)
641 (repeat :greedy t :tag "Individual contexts"
642 (cons
643 (choice :tag "Context"
644 (const agenda)
645 (const org-goto)
646 (const occur-tree)
647 (const tags-tree)
648 (const link-search)
649 (const mark-goto)
650 (const bookmark-jump)
651 (const isearch)
652 (const default))
653 (boolean))))
654 "Contexts for the reveal options.")
656 (defcustom org-show-hierarchy-above '((default . t))
657 "Non-nil means show full hierarchy when revealing a location.
658 Org-mode often shows locations in an org-mode file which might have
659 been invisible before. When this is set, the hierarchy of headings
660 above the exposed location is shown.
661 Turning this off for example for sparse trees makes them very compact.
662 Instead of t, this can also be an alist specifying this option for different
663 contexts. Valid contexts are
664 agenda when exposing an entry from the agenda
665 org-goto when using the command `org-goto' on key C-c C-j
666 occur-tree when using the command `org-occur' on key C-c /
667 tags-tree when constructing a sparse tree based on tags matches
668 link-search when exposing search matches associated with a link
669 mark-goto when exposing the jump goal of a mark
670 bookmark-jump when exposing a bookmark location
671 isearch when exiting from an incremental search
672 default default for all contexts not set explicitly"
673 :group 'org-reveal-location
674 :type org-context-choice)
676 (defcustom org-show-following-heading '((default . nil))
677 "Non-nil means show following heading when revealing a location.
678 Org-mode often shows locations in an org-mode file which might have
679 been invisible before. When this is set, the heading following the
680 match is shown.
681 Turning this off for example for sparse trees makes them very compact,
682 but makes it harder to edit the location of the match. In such a case,
683 use the command \\[org-reveal] to show more context.
684 Instead of t, this can also be an alist specifying this option for different
685 contexts. See `org-show-hierarchy-above' for valid contexts."
686 :group 'org-reveal-location
687 :type org-context-choice)
689 (defcustom org-show-siblings '((default . nil) (isearch t))
690 "Non-nil means show all sibling heading when revealing a location.
691 Org-mode often shows locations in an org-mode file which might have
692 been invisible before. When this is set, the sibling of the current entry
693 heading are all made visible. If `org-show-hierarchy-above' is t,
694 the same happens on each level of the hierarchy above the current entry.
696 By default this is on for the isearch context, off for all other contexts.
697 Turning this off for example for sparse trees makes them very compact,
698 but makes it harder to edit the location of the match. In such a case,
699 use the command \\[org-reveal] to show more context.
700 Instead of t, this can also be an alist specifying this option for different
701 contexts. See `org-show-hierarchy-above' for valid contexts."
702 :group 'org-reveal-location
703 :type org-context-choice)
705 (defcustom org-show-entry-below '((default . nil))
706 "Non-nil means show the entry below a headline when revealing a location.
707 Org-mode often shows locations in an org-mode file which might have
708 been invisible before. When this is set, the text below the headline that is
709 exposed is also shown.
711 By default this is off for all contexts.
712 Instead of t, this can also be an alist specifying this option for different
713 contexts. See `org-show-hierarchy-above' for valid contexts."
714 :group 'org-reveal-location
715 :type org-context-choice)
717 (defcustom org-indirect-buffer-display 'other-window
718 "How should indirect tree buffers be displayed?
719 This applies to indirect buffers created with the commands
720 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
721 Valid values are:
722 current-window Display in the current window
723 other-window Just display in another window.
724 dedicated-frame Create one new frame, and re-use it each time.
725 new-frame Make a new frame each time. Note that in this case
726 previously-made indirect buffers are kept, and you need to
727 kill these buffers yourself."
728 :group 'org-structure
729 :group 'org-agenda-windows
730 :type '(choice
731 (const :tag "In current window" current-window)
732 (const :tag "In current frame, other window" other-window)
733 (const :tag "Each time a new frame" new-frame)
734 (const :tag "One dedicated frame" dedicated-frame)))
736 (defcustom org-use-speed-commands nil
737 "Non-nil means activate single letter commands at beginning of a headline.
738 This may also be a function to test for appropriate locations where speed
739 commands should be active."
740 :group 'org-structure
741 :type '(choice
742 (const :tag "Never" nil)
743 (const :tag "At beginning of headline stars" t)
744 (function)))
746 (defcustom org-speed-commands-user nil
747 "Alist of additional speed commands.
748 This list will be checked before `org-speed-commands-default'
749 when the variable `org-use-speed-commands' is non-nil
750 and when the cursor is at the beginning of a headline.
751 The car if each entry is a string with a single letter, which must
752 be assigned to `self-insert-command' in the global map.
753 The cdr is either a command to be called interactively, a function
754 to be called, or a form to be evaluated.
755 An entry that is just a list with a single string will be interpreted
756 as a descriptive headline that will be added when listing the speed
757 commands in the Help buffer using the `?' speed command."
758 :group 'org-structure
759 :type '(repeat :value ("k" . ignore)
760 (choice :value ("k" . ignore)
761 (list :tag "Descriptive Headline" (string :tag "Headline"))
762 (cons :tag "Letter and Command"
763 (string :tag "Command letter")
764 (choice
765 (function)
766 (sexp))))))
768 (defgroup org-cycle nil
769 "Options concerning visibility cycling in Org-mode."
770 :tag "Org Cycle"
771 :group 'org-structure)
773 (defcustom org-cycle-skip-children-state-if-no-children t
774 "Non-nil means skip CHILDREN state in entries that don't have any."
775 :group 'org-cycle
776 :type 'boolean)
778 (defcustom org-cycle-max-level nil
779 "Maximum level which should still be subject to visibility cycling.
780 Levels higher than this will, for cycling, be treated as text, not a headline.
781 When `org-odd-levels-only' is set, a value of N in this variable actually
782 means 2N-1 stars as the limiting headline.
783 When nil, cycle all levels.
784 Note that the limiting level of cycling is also influenced by
785 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
786 `org-inlinetask-min-level' is, cycling will be limited to levels one less
787 than its value."
788 :group 'org-cycle
789 :type '(choice
790 (const :tag "No limit" nil)
791 (integer :tag "Maximum level")))
793 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
794 "Names of drawers. Drawers are not opened by cycling on the headline above.
795 Drawers only open with a TAB on the drawer line itself. A drawer looks like
796 this:
797 :DRAWERNAME:
798 .....
799 :END:
800 The drawer \"PROPERTIES\" is special for capturing properties through
801 the property API.
803 Drawers can be defined on the per-file basis with a line like:
805 #+DRAWERS: HIDDEN STATE PROPERTIES"
806 :group 'org-structure
807 :group 'org-cycle
808 :type '(repeat (string :tag "Drawer Name")))
810 (defcustom org-hide-block-startup nil
811 "Non-nil means entering Org-mode will fold all blocks.
812 This can also be set in on a per-file basis with
814 #+STARTUP: hideblocks
815 #+STARTUP: showblocks"
816 :group 'org-startup
817 :group 'org-cycle
818 :type 'boolean)
820 (defcustom org-cycle-global-at-bob nil
821 "Cycle globally if cursor is at beginning of buffer and not at a headline.
822 This makes it possible to do global cycling without having to use S-TAB or
823 \\[universal-argument] TAB. For this special case to work, the first line \
824 of the buffer
825 must not be a headline - it may be empty or some other text. When used in
826 this way, `org-cycle-hook' is disables temporarily, to make sure the
827 cursor stays at the beginning of the buffer.
828 When this option is nil, don't do anything special at the beginning
829 of the buffer."
830 :group 'org-cycle
831 :type 'boolean)
833 (defcustom org-cycle-level-after-item/entry-creation t
834 "Non-nil means cycle entry level or item indentation in new empty entries.
836 When the cursor is at the end of an empty headline, i.e with only stars
837 and maybe a TODO keyword, TAB will then switch the entry to become a child,
838 and then all possible ancestor states, before returning to the original state.
839 This makes data entry extremely fast: M-RET to create a new headline,
840 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
842 When the cursor is at the end of an empty plain list item, one TAB will
843 make it a subitem, two or more tabs will back up to make this an item
844 higher up in the item hierarchy."
845 :group 'org-cycle
846 :type 'boolean)
848 (defcustom org-cycle-emulate-tab t
849 "Where should `org-cycle' emulate TAB.
850 nil Never
851 white Only in completely white lines
852 whitestart Only at the beginning of lines, before the first non-white char
853 t Everywhere except in headlines
854 exc-hl-bol Everywhere except at the start of a headline
855 If TAB is used in a place where it does not emulate TAB, the current subtree
856 visibility is cycled."
857 :group 'org-cycle
858 :type '(choice (const :tag "Never" nil)
859 (const :tag "Only in completely white lines" white)
860 (const :tag "Before first char in a line" whitestart)
861 (const :tag "Everywhere except in headlines" t)
862 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
865 (defcustom org-cycle-separator-lines 2
866 "Number of empty lines needed to keep an empty line between collapsed trees.
867 If you leave an empty line between the end of a subtree and the following
868 headline, this empty line is hidden when the subtree is folded.
869 Org-mode will leave (exactly) one empty line visible if the number of
870 empty lines is equal or larger to the number given in this variable.
871 So the default 2 means at least 2 empty lines after the end of a subtree
872 are needed to produce free space between a collapsed subtree and the
873 following headline.
875 If the number is negative, and the number of empty lines is at least -N,
876 all empty lines are shown.
878 Special case: when 0, never leave empty lines in collapsed view."
879 :group 'org-cycle
880 :type 'integer)
881 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
883 (defcustom org-pre-cycle-hook nil
884 "Hook that is run before visibility cycling is happening.
885 The function(s) in this hook must accept a single argument which indicates
886 the new state that will be set right after running this hook. The
887 argument is a symbol. Before a global state change, it can have the values
888 `overview', `content', or `all'. Before a local state change, it can have
889 the values `folded', `children', or `subtree'."
890 :group 'org-cycle
891 :type 'hook)
893 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
894 org-cycle-hide-drawers
895 org-cycle-show-empty-lines
896 org-optimize-window-after-visibility-change)
897 "Hook that is run after `org-cycle' has changed the buffer visibility.
898 The function(s) in this hook must accept a single argument which indicates
899 the new state that was set by the most recent `org-cycle' command. The
900 argument is a symbol. After a global state change, it can have the values
901 `overview', `content', or `all'. After a local state change, it can have
902 the values `folded', `children', or `subtree'."
903 :group 'org-cycle
904 :type 'hook)
906 (defgroup org-edit-structure nil
907 "Options concerning structure editing in Org-mode."
908 :tag "Org Edit Structure"
909 :group 'org-structure)
911 (defcustom org-odd-levels-only nil
912 "Non-nil means skip even levels and only use odd levels for the outline.
913 This has the effect that two stars are being added/taken away in
914 promotion/demotion commands. It also influences how levels are
915 handled by the exporters.
916 Changing it requires restart of `font-lock-mode' to become effective
917 for fontification also in regions already fontified.
918 You may also set this on a per-file basis by adding one of the following
919 lines to the buffer:
921 #+STARTUP: odd
922 #+STARTUP: oddeven"
923 :group 'org-edit-structure
924 :group 'org-appearance
925 :type 'boolean)
927 (defcustom org-adapt-indentation t
928 "Non-nil means adapt indentation to outline node level.
930 When this variable is set, Org assumes that you write outlines by
931 indenting text in each node to align with the headline (after the stars).
932 The following issues are influenced by this variable:
934 - When this is set and the *entire* text in an entry is indented, the
935 indentation is increased by one space in a demotion command, and
936 decreased by one in a promotion command. If any line in the entry
937 body starts with text at column 0, indentation is not changed at all.
939 - Property drawers and planning information is inserted indented when
940 this variable s set. When nil, they will not be indented.
942 - TAB indents a line relative to context. The lines below a headline
943 will be indented when this variable is set.
945 Note that this is all about true indentation, by adding and removing
946 space characters. See also `org-indent.el' which does level-dependent
947 indentation in a virtual way, i.e. at display time in Emacs."
948 :group 'org-edit-structure
949 :type 'boolean)
951 (defcustom org-special-ctrl-a/e nil
952 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
954 When t, `C-a' will bring back the cursor to the beginning of the
955 headline text, i.e. after the stars and after a possible TODO keyword.
956 In an item, this will be the position after the bullet.
957 When the cursor is already at that position, another `C-a' will bring
958 it to the beginning of the line.
960 `C-e' will jump to the end of the headline, ignoring the presence of tags
961 in the headline. A second `C-e' will then jump to the true end of the
962 line, after any tags. This also means that, when this variable is
963 non-nil, `C-e' also will never jump beyond the end of the heading of a
964 folded section, i.e. not after the ellipses.
966 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
967 going to the true line boundary first. Only a directly following, identical
968 keypress will bring the cursor to the special positions.
970 This may also be a cons cell where the behavior for `C-a' and `C-e' is
971 set separately."
972 :group 'org-edit-structure
973 :type '(choice
974 (const :tag "off" nil)
975 (const :tag "on: after stars/bullet and before tags first" t)
976 (const :tag "reversed: true line boundary first" reversed)
977 (cons :tag "Set C-a and C-e separately"
978 (choice :tag "Special C-a"
979 (const :tag "off" nil)
980 (const :tag "on: after stars/bullet first" t)
981 (const :tag "reversed: before stars/bullet first" reversed))
982 (choice :tag "Special C-e"
983 (const :tag "off" nil)
984 (const :tag "on: before tags first" t)
985 (const :tag "reversed: after tags first" reversed)))))
986 (if (fboundp 'defvaralias)
987 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
989 (defcustom org-special-ctrl-k nil
990 "Non-nil means `C-k' will behave specially in headlines.
991 When nil, `C-k' will call the default `kill-line' command.
992 When t, the following will happen while the cursor is in the headline:
994 - When the cursor is at the beginning of a headline, kill the entire
995 line and possible the folded subtree below the line.
996 - When in the middle of the headline text, kill the headline up to the tags.
997 - When after the headline text, kill the tags."
998 :group 'org-edit-structure
999 :type 'boolean)
1001 (defcustom org-ctrl-k-protect-subtree nil
1002 "Non-nil means, do not delete a hidden subtree with C-k.
1003 When set to the symbol `error', simply throw an error when C-k is
1004 used to kill (part-of) a headline that has hidden text behind it.
1005 Any other non-nil value will result in a query to the user, if it is
1006 OK to kill that hidden subtree. When nil, kill without remorse."
1007 :group 'org-edit-structure
1008 :type '(choice
1009 (const :tag "Do not protect hidden subtrees" nil)
1010 (const :tag "Protect hidden subtrees with a security query" t)
1011 (const :tag "Never kill a hidden subtree with C-k" error)))
1013 (defcustom org-yank-folded-subtrees t
1014 "Non-nil means when yanking subtrees, fold them.
1015 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1016 it starts with a heading and all other headings in it are either children
1017 or siblings, then fold all the subtrees. However, do this only if no
1018 text after the yank would be swallowed into a folded tree by this action."
1019 :group 'org-edit-structure
1020 :type 'boolean)
1022 (defcustom org-yank-adjusted-subtrees nil
1023 "Non-nil means when yanking subtrees, adjust the level.
1024 With this setting, `org-paste-subtree' is used to insert the subtree, see
1025 this function for details."
1026 :group 'org-edit-structure
1027 :type 'boolean)
1029 (defcustom org-M-RET-may-split-line '((default . t))
1030 "Non-nil means M-RET will split the line at the cursor position.
1031 When nil, it will go to the end of the line before making a
1032 new line.
1033 You may also set this option in a different way for different
1034 contexts. Valid contexts are:
1036 headline when creating a new headline
1037 item when creating a new item
1038 table in a table field
1039 default the value to be used for all contexts not explicitly
1040 customized"
1041 :group 'org-structure
1042 :group 'org-table
1043 :type '(choice
1044 (const :tag "Always" t)
1045 (const :tag "Never" nil)
1046 (repeat :greedy t :tag "Individual contexts"
1047 (cons
1048 (choice :tag "Context"
1049 (const headline)
1050 (const item)
1051 (const table)
1052 (const default))
1053 (boolean)))))
1056 (defcustom org-insert-heading-respect-content nil
1057 "Non-nil means insert new headings after the current subtree.
1058 When nil, the new heading is created directly after the current line.
1059 The commands \\[org-insert-heading-respect-content] and
1060 \\[org-insert-todo-heading-respect-content] turn this variable on
1061 for the duration of the command."
1062 :group 'org-structure
1063 :type 'boolean)
1065 (defcustom org-blank-before-new-entry '((heading . auto)
1066 (plain-list-item . auto))
1067 "Should `org-insert-heading' leave a blank line before new heading/item?
1068 The value is an alist, with `heading' and `plain-list-item' as car,
1069 and a boolean flag as cdr. For plain lists, if the variable
1070 `org-empty-line-terminates-plain-lists' is set, the setting here
1071 is ignored and no empty line is inserted, to keep the list in tact."
1072 :group 'org-edit-structure
1073 :type '(list
1074 (cons (const heading)
1075 (choice (const :tag "Never" nil)
1076 (const :tag "Always" t)
1077 (const :tag "Auto" auto)))
1078 (cons (const plain-list-item)
1079 (choice (const :tag "Never" nil)
1080 (const :tag "Always" t)
1081 (const :tag "Auto" auto)))))
1083 (defcustom org-insert-heading-hook nil
1084 "Hook being run after inserting a new heading."
1085 :group 'org-edit-structure
1086 :type 'hook)
1088 (defcustom org-enable-fixed-width-editor t
1089 "Non-nil means lines starting with \":\" are treated as fixed-width.
1090 This currently only means they are never auto-wrapped.
1091 When nil, such lines will be treated like ordinary lines.
1092 See also the QUOTE keyword."
1093 :group 'org-edit-structure
1094 :type 'boolean)
1096 (defcustom org-goto-auto-isearch t
1097 "Non-nil means typing characters in `org-goto' starts incremental search."
1098 :group 'org-edit-structure
1099 :type 'boolean)
1101 (defgroup org-sparse-trees nil
1102 "Options concerning sparse trees in Org-mode."
1103 :tag "Org Sparse Trees"
1104 :group 'org-structure)
1106 (defcustom org-highlight-sparse-tree-matches t
1107 "Non-nil means highlight all matches that define a sparse tree.
1108 The highlights will automatically disappear the next time the buffer is
1109 changed by an edit command."
1110 :group 'org-sparse-trees
1111 :type 'boolean)
1113 (defcustom org-remove-highlights-with-change t
1114 "Non-nil means any change to the buffer will remove temporary highlights.
1115 Such highlights are created by `org-occur' and `org-clock-display'.
1116 When nil, `C-c C-c needs to be used to get rid of the highlights.
1117 The highlights created by `org-preview-latex-fragment' always need
1118 `C-c C-c' to be removed."
1119 :group 'org-sparse-trees
1120 :group 'org-time
1121 :type 'boolean)
1124 (defcustom org-occur-hook '(org-first-headline-recenter)
1125 "Hook that is run after `org-occur' has constructed a sparse tree.
1126 This can be used to recenter the window to show as much of the structure
1127 as possible."
1128 :group 'org-sparse-trees
1129 :type 'hook)
1131 (defgroup org-imenu-and-speedbar nil
1132 "Options concerning imenu and speedbar in Org-mode."
1133 :tag "Org Imenu and Speedbar"
1134 :group 'org-structure)
1136 (defcustom org-imenu-depth 2
1137 "The maximum level for Imenu access to Org-mode headlines.
1138 This also applied for speedbar access."
1139 :group 'org-imenu-and-speedbar
1140 :type 'integer)
1142 (defgroup org-table nil
1143 "Options concerning tables in Org-mode."
1144 :tag "Org Table"
1145 :group 'org)
1147 (defcustom org-enable-table-editor 'optimized
1148 "Non-nil means lines starting with \"|\" are handled by the table editor.
1149 When nil, such lines will be treated like ordinary lines.
1151 When equal to the symbol `optimized', the table editor will be optimized to
1152 do the following:
1153 - Automatic overwrite mode in front of whitespace in table fields.
1154 This makes the structure of the table stay in tact as long as the edited
1155 field does not exceed the column width.
1156 - Minimize the number of realigns. Normally, the table is aligned each time
1157 TAB or RET are pressed to move to another field. With optimization this
1158 happens only if changes to a field might have changed the column width.
1159 Optimization requires replacing the functions `self-insert-command',
1160 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1161 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1162 very good at guessing when a re-align will be necessary, but you can always
1163 force one with \\[org-ctrl-c-ctrl-c].
1165 If you would like to use the optimized version in Org-mode, but the
1166 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1168 This variable can be used to turn on and off the table editor during a session,
1169 but in order to toggle optimization, a restart is required.
1171 See also the variable `org-table-auto-blank-field'."
1172 :group 'org-table
1173 :type '(choice
1174 (const :tag "off" nil)
1175 (const :tag "on" t)
1176 (const :tag "on, optimized" optimized)))
1178 (defcustom org-self-insert-cluster-for-undo t
1179 "Non-nil means cluster self-insert commands for undo when possible.
1180 If this is set, then, like in the Emacs command loop, 20 consecutive
1181 characters will be undone together.
1182 This is configurable, because there is some impact on typing performance."
1183 :group 'org-table
1184 :type 'boolean)
1186 (defcustom org-table-tab-recognizes-table.el t
1187 "Non-nil means TAB will automatically notice a table.el table.
1188 When it sees such a table, it moves point into it and - if necessary -
1189 calls `table-recognize-table'."
1190 :group 'org-table-editing
1191 :type 'boolean)
1193 (defgroup org-link nil
1194 "Options concerning links in Org-mode."
1195 :tag "Org Link"
1196 :group 'org)
1198 (defvar org-link-abbrev-alist-local nil
1199 "Buffer-local version of `org-link-abbrev-alist', which see.
1200 The value of this is taken from the #+LINK lines.")
1201 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1203 (defcustom org-link-abbrev-alist nil
1204 "Alist of link abbreviations.
1205 The car of each element is a string, to be replaced at the start of a link.
1206 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1207 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1209 [[linkkey:tag][description]]
1211 The 'linkkey' must be a word word, starting with a letter, followed
1212 by letters, numbers, '-' or '_'.
1214 If REPLACE is a string, the tag will simply be appended to create the link.
1215 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1216 the placeholder \"%h\" will cause a url-encoded version of the tag to
1217 be inserted at that point (see the function `url-hexify-string').
1219 REPLACE may also be a function that will be called with the tag as the
1220 only argument to create the link, which should be returned as a string.
1222 See the manual for examples."
1223 :group 'org-link
1224 :type '(repeat
1225 (cons
1226 (string :tag "Protocol")
1227 (choice
1228 (string :tag "Format")
1229 (function)))))
1231 (defcustom org-descriptive-links t
1232 "Non-nil means hide link part and only show description of bracket links.
1233 Bracket links are like [[link][description]]. This variable sets the initial
1234 state in new org-mode buffers. The setting can then be toggled on a
1235 per-buffer basis from the Org->Hyperlinks menu."
1236 :group 'org-link
1237 :type 'boolean)
1239 (defcustom org-link-file-path-type 'adaptive
1240 "How the path name in file links should be stored.
1241 Valid values are:
1243 relative Relative to the current directory, i.e. the directory of the file
1244 into which the link is being inserted.
1245 absolute Absolute path, if possible with ~ for home directory.
1246 noabbrev Absolute path, no abbreviation of home directory.
1247 adaptive Use relative path for files in the current directory and sub-
1248 directories of it. For other files, use an absolute path."
1249 :group 'org-link
1250 :type '(choice
1251 (const relative)
1252 (const absolute)
1253 (const noabbrev)
1254 (const adaptive)))
1256 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1257 "Types of links that should be activated in Org-mode files.
1258 This is a list of symbols, each leading to the activation of a certain link
1259 type. In principle, it does not hurt to turn on most link types - there may
1260 be a small gain when turning off unused link types. The types are:
1262 bracket The recommended [[link][description]] or [[link]] links with hiding.
1263 angular Links in angular brackets that may contain whitespace like
1264 <bbdb:Carsten Dominik>.
1265 plain Plain links in normal text, no whitespace, like http://google.com.
1266 radio Text that is matched by a radio target, see manual for details.
1267 tag Tag settings in a headline (link to tag search).
1268 date Time stamps (link to calendar).
1269 footnote Footnote labels.
1271 Changing this variable requires a restart of Emacs to become effective."
1272 :group 'org-link
1273 :type '(set :greedy t
1274 (const :tag "Double bracket links (new style)" bracket)
1275 (const :tag "Angular bracket links (old style)" angular)
1276 (const :tag "Plain text links" plain)
1277 (const :tag "Radio target matches" radio)
1278 (const :tag "Tags" tag)
1279 (const :tag "Timestamps" date)
1280 (const :tag "Footnotes" footnote)))
1282 (defcustom org-make-link-description-function nil
1283 "Function to use to generate link descriptions from links.
1284 If nil the link location will be used. This function must take
1285 two parameters; the first is the link and the second the
1286 description `org-insert-link' has generated, and should return the
1287 description to use."
1288 :group 'org-link
1289 :type 'function)
1291 (defgroup org-link-store nil
1292 "Options concerning storing links in Org-mode."
1293 :tag "Org Store Link"
1294 :group 'org-link)
1296 (defcustom org-email-link-description-format "Email %c: %.30s"
1297 "Format of the description part of a link to an email or usenet message.
1298 The following %-escapes will be replaced by corresponding information:
1300 %F full \"From\" field
1301 %f name, taken from \"From\" field, address if no name
1302 %T full \"To\" field
1303 %t first name in \"To\" field, address if no name
1304 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1305 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1306 %s subject
1307 %m message-id.
1309 You may use normal field width specification between the % and the letter.
1310 This is for example useful to limit the length of the subject.
1312 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1313 :group 'org-link-store
1314 :type 'string)
1316 (defcustom org-from-is-user-regexp
1317 (let (r1 r2)
1318 (when (and user-mail-address (not (string= user-mail-address "")))
1319 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1320 (when (and user-full-name (not (string= user-full-name "")))
1321 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1322 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1323 "Regexp matched against the \"From:\" header of an email or usenet message.
1324 It should match if the message is from the user him/herself."
1325 :group 'org-link-store
1326 :type 'regexp)
1328 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1329 "Non-nil means storing a link to an Org file will use entry IDs.
1331 Note that before this variable is even considered, org-id must be loaded,
1332 so please customize `org-modules' and turn it on.
1334 The variable can have the following values:
1336 t Create an ID if needed to make a link to the current entry.
1338 create-if-interactive
1339 If `org-store-link' is called directly (interactively, as a user
1340 command), do create an ID to support the link. But when doing the
1341 job for remember, only use the ID if it already exists. The
1342 purpose of this setting is to avoid proliferation of unwanted
1343 IDs, just because you happen to be in an Org file when you
1344 call `org-remember' that automatically and preemptively
1345 creates a link. If you do want to get an ID link in a remember
1346 template to an entry not having an ID, create it first by
1347 explicitly creating a link to it, using `C-c C-l' first.
1349 create-if-interactive-and-no-custom-id
1350 Like create-if-interactive, but do not create an ID if there is
1351 a CUSTOM_ID property defined in the entry. This is the default.
1353 use-existing
1354 Use existing ID, do not create one.
1356 nil Never use an ID to make a link, instead link using a text search for
1357 the headline text."
1358 :group 'org-link-store
1359 :type '(choice
1360 (const :tag "Create ID to make link" t)
1361 (const :tag "Create if storing link interactively"
1362 create-if-interactive)
1363 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1364 create-if-interactive-and-no-custom-id)
1365 (const :tag "Only use existing" use-existing)
1366 (const :tag "Do not use ID to create link" nil)))
1368 (defcustom org-context-in-file-links t
1369 "Non-nil means file links from `org-store-link' contain context.
1370 A search string will be added to the file name with :: as separator and
1371 used to find the context when the link is activated by the command
1372 `org-open-at-point'.
1373 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1374 negates this setting for the duration of the command."
1375 :group 'org-link-store
1376 :type 'boolean)
1378 (defcustom org-keep-stored-link-after-insertion nil
1379 "Non-nil means keep link in list for entire session.
1381 The command `org-store-link' adds a link pointing to the current
1382 location to an internal list. These links accumulate during a session.
1383 The command `org-insert-link' can be used to insert links into any
1384 Org-mode file (offering completion for all stored links). When this
1385 option is nil, every link which has been inserted once using \\[org-insert-link]
1386 will be removed from the list, to make completing the unused links
1387 more efficient."
1388 :group 'org-link-store
1389 :type 'boolean)
1391 (defgroup org-link-follow nil
1392 "Options concerning following links in Org-mode."
1393 :tag "Org Follow Link"
1394 :group 'org-link)
1396 (defcustom org-link-translation-function nil
1397 "Function to translate links with different syntax to Org syntax.
1398 This can be used to translate links created for example by the Planner
1399 or emacs-wiki packages to Org syntax.
1400 The function must accept two parameters, a TYPE containing the link
1401 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1402 which is everything after the link protocol. It should return a cons
1403 with possibly modified values of type and path.
1404 Org contains a function for this, so if you set this variable to
1405 `org-translate-link-from-planner', you should be able follow many
1406 links created by planner."
1407 :group 'org-link-follow
1408 :type 'function)
1410 (defcustom org-follow-link-hook nil
1411 "Hook that is run after a link has been followed."
1412 :group 'org-link-follow
1413 :type 'hook)
1415 (defcustom org-tab-follows-link nil
1416 "Non-nil means on links TAB will follow the link.
1417 Needs to be set before org.el is loaded.
1418 This really should not be used, it does not make sense, and the
1419 implementation is bad."
1420 :group 'org-link-follow
1421 :type 'boolean)
1423 (defcustom org-return-follows-link nil
1424 "Non-nil means on links RET will follow the link."
1425 :group 'org-link-follow
1426 :type 'boolean)
1428 (defcustom org-mouse-1-follows-link
1429 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1430 "Non-nil means mouse-1 on a link will follow the link.
1431 A longer mouse click will still set point. Does not work on XEmacs.
1432 Needs to be set before org.el is loaded."
1433 :group 'org-link-follow
1434 :type 'boolean)
1436 (defcustom org-mark-ring-length 4
1437 "Number of different positions to be recorded in the ring.
1438 Changing this requires a restart of Emacs to work correctly."
1439 :group 'org-link-follow
1440 :type 'integer)
1442 (defcustom org-link-frame-setup
1443 '((vm . vm-visit-folder-other-frame)
1444 (gnus . org-gnus-no-new-news)
1445 (file . find-file-other-window)
1446 (wl . wl-other-frame))
1447 "Setup the frame configuration for following links.
1448 When following a link with Emacs, it may often be useful to display
1449 this link in another window or frame. This variable can be used to
1450 set this up for the different types of links.
1451 For VM, use any of
1452 `vm-visit-folder'
1453 `vm-visit-folder-other-frame'
1454 For Gnus, use any of
1455 `gnus'
1456 `gnus-other-frame'
1457 `org-gnus-no-new-news'
1458 For FILE, use any of
1459 `find-file'
1460 `find-file-other-window'
1461 `find-file-other-frame'
1462 For Wanderlust use any of
1463 `wl'
1464 `wl-other-frame'
1465 For the calendar, use the variable `calendar-setup'.
1466 For BBDB, it is currently only possible to display the matches in
1467 another window."
1468 :group 'org-link-follow
1469 :type '(list
1470 (cons (const vm)
1471 (choice
1472 (const vm-visit-folder)
1473 (const vm-visit-folder-other-window)
1474 (const vm-visit-folder-other-frame)))
1475 (cons (const gnus)
1476 (choice
1477 (const gnus)
1478 (const gnus-other-frame)
1479 (const org-gnus-no-new-news)))
1480 (cons (const file)
1481 (choice
1482 (const find-file)
1483 (const find-file-other-window)
1484 (const find-file-other-frame)))
1485 (cons (const wl)
1486 (choice
1487 (const wl)
1488 (const wl-other-frame)))))
1490 (defcustom org-display-internal-link-with-indirect-buffer nil
1491 "Non-nil means use indirect buffer to display infile links.
1492 Activating internal links (from one location in a file to another location
1493 in the same file) normally just jumps to the location. When the link is
1494 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1495 is displayed in
1496 another window. When this option is set, the other window actually displays
1497 an indirect buffer clone of the current buffer, to avoid any visibility
1498 changes to the current buffer."
1499 :group 'org-link-follow
1500 :type 'boolean)
1502 (defcustom org-open-non-existing-files nil
1503 "Non-nil means `org-open-file' will open non-existing files.
1504 When nil, an error will be generated.
1505 This variable applies only to external applications because they
1506 might choke on non-existing files. If the link is to a file that
1507 will be opened in Emacs, the variable is ignored."
1508 :group 'org-link-follow
1509 :type 'boolean)
1511 (defcustom org-open-directory-means-index-dot-org nil
1512 "Non-nil means a link to a directory really means to index.org.
1513 When nil, following a directory link will run dired or open a finder/explorer
1514 window on that directory."
1515 :group 'org-link-follow
1516 :type 'boolean)
1518 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1519 "Function and arguments to call for following mailto links.
1520 This is a list with the first element being a Lisp function, and the
1521 remaining elements being arguments to the function. In string arguments,
1522 %a will be replaced by the address, and %s will be replaced by the subject
1523 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1524 :group 'org-link-follow
1525 :type '(choice
1526 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1527 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1528 (const :tag "message-mail" (message-mail "%a" "%s"))
1529 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1531 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1532 "Non-nil means ask for confirmation before executing shell links.
1533 Shell links can be dangerous: just think about a link
1535 [[shell:rm -rf ~/*][Google Search]]
1537 This link would show up in your Org-mode document as \"Google Search\",
1538 but really it would remove your entire home directory.
1539 Therefore we advise against setting this variable to nil.
1540 Just change it to `y-or-n-p' if you want to confirm with a
1541 single keystroke rather than having to type \"yes\"."
1542 :group 'org-link-follow
1543 :type '(choice
1544 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1545 (const :tag "with y-or-n (faster)" y-or-n-p)
1546 (const :tag "no confirmation (dangerous)" nil)))
1547 (put 'org-confirm-shell-link-function
1548 'safe-local-variable
1549 '(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1551 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1552 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1553 Elisp links can be dangerous: just think about a link
1555 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1557 This link would show up in your Org-mode document as \"Google Search\",
1558 but really it would remove your entire home directory.
1559 Therefore we advise against setting this variable to nil.
1560 Just change it to `y-or-n-p' if you want to confirm with a
1561 single keystroke rather than having to type \"yes\"."
1562 :group 'org-link-follow
1563 :type '(choice
1564 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1565 (const :tag "with y-or-n (faster)" y-or-n-p)
1566 (const :tag "no confirmation (dangerous)" nil)))
1567 (put 'org-confirm-shell-link-function
1568 'safe-local-variable
1569 '(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1571 (defconst org-file-apps-defaults-gnu
1572 '((remote . emacs)
1573 (system . mailcap)
1574 (t . mailcap))
1575 "Default file applications on a UNIX or GNU/Linux system.
1576 See `org-file-apps'.")
1578 (defconst org-file-apps-defaults-macosx
1579 '((remote . emacs)
1580 (t . "open %s")
1581 (system . "open %s")
1582 ("ps.gz" . "gv %s")
1583 ("eps.gz" . "gv %s")
1584 ("dvi" . "xdvi %s")
1585 ("fig" . "xfig %s"))
1586 "Default file applications on a MacOS X system.
1587 The system \"open\" is known as a default, but we use X11 applications
1588 for some files for which the OS does not have a good default.
1589 See `org-file-apps'.")
1591 (defconst org-file-apps-defaults-windowsnt
1592 (list
1593 '(remote . emacs)
1594 (cons t
1595 (list (if (featurep 'xemacs)
1596 'mswindows-shell-execute
1597 'w32-shell-execute)
1598 "open" 'file))
1599 (cons 'system
1600 (list (if (featurep 'xemacs)
1601 'mswindows-shell-execute
1602 'w32-shell-execute)
1603 "open" 'file)))
1604 "Default file applications on a Windows NT system.
1605 The system \"open\" is used for most files.
1606 See `org-file-apps'.")
1608 (defcustom org-file-apps
1610 (auto-mode . emacs)
1611 ("\\.mm\\'" . default)
1612 ("\\.x?html?\\'" . default)
1613 ("\\.pdf\\'" . default)
1615 "External applications for opening `file:path' items in a document.
1616 Org-mode uses system defaults for different file types, but
1617 you can use this variable to set the application for a given file
1618 extension. The entries in this list are cons cells where the car identifies
1619 files and the cdr the corresponding command. Possible values for the
1620 file identifier are
1621 \"string\" A string as a file identifier can be interpreted in different
1622 ways, depending on its contents:
1624 - Alphanumeric characters only:
1625 Match links with this file extension.
1626 Example: (\"pdf\" . \"evince %s\")
1627 to open PDFs with evince.
1629 - Regular expression: Match links where the
1630 filename matches the regexp. If you want to
1631 use groups here, use shy groups.
1633 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1634 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1635 to open *.html and *.xhtml with firefox.
1637 - Regular expression which contains (non-shy) groups:
1638 Match links where the whole link, including \"::\", and
1639 anything after that, matches the regexp.
1640 In a custom command string, %1, %2, etc. are replaced with
1641 the parts of the link that were matched by the groups.
1642 For backwards compatibility, if a command string is given
1643 that does not use any of the group matches, this case is
1644 handled identically to the second one (i.e. match against
1645 file name only).
1646 In a custom lisp form, you can access the group matches with
1647 (match-string n link).
1649 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1650 to open [[file:document.pdf::5]] with evince at page 5.
1652 `directory' Matches a directory
1653 `remote' Matches a remote file, accessible through tramp or efs.
1654 Remote files most likely should be visited through Emacs
1655 because external applications cannot handle such paths.
1656 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1657 so all files Emacs knows how to handle. Using this with
1658 command `emacs' will open most files in Emacs. Beware that this
1659 will also open html files inside Emacs, unless you add
1660 (\"html\" . default) to the list as well.
1661 t Default for files not matched by any of the other options.
1662 `system' The system command to open files, like `open' on Windows
1663 and Mac OS X, and mailcap under GNU/Linux. This is the command
1664 that will be selected if you call `C-c C-o' with a double
1665 \\[universal-argument] \\[universal-argument] prefix.
1667 Possible values for the command are:
1668 `emacs' The file will be visited by the current Emacs process.
1669 `default' Use the default application for this file type, which is the
1670 association for t in the list, most likely in the system-specific
1671 part.
1672 This can be used to overrule an unwanted setting in the
1673 system-specific variable.
1674 `system' Use the system command for opening files, like \"open\".
1675 This command is specified by the entry whose car is `system'.
1676 Most likely, the system-specific version of this variable
1677 does define this command, but you can overrule/replace it
1678 here.
1679 string A command to be executed by a shell; %s will be replaced
1680 by the path to the file.
1681 sexp A Lisp form which will be evaluated. The file path will
1682 be available in the Lisp variable `file'.
1683 For more examples, see the system specific constants
1684 `org-file-apps-defaults-macosx'
1685 `org-file-apps-defaults-windowsnt'
1686 `org-file-apps-defaults-gnu'."
1687 :group 'org-link-follow
1688 :type '(repeat
1689 (cons (choice :value ""
1690 (string :tag "Extension")
1691 (const :tag "System command to open files" system)
1692 (const :tag "Default for unrecognized files" t)
1693 (const :tag "Remote file" remote)
1694 (const :tag "Links to a directory" directory)
1695 (const :tag "Any files that have Emacs modes"
1696 auto-mode))
1697 (choice :value ""
1698 (const :tag "Visit with Emacs" emacs)
1699 (const :tag "Use default" default)
1700 (const :tag "Use the system command" system)
1701 (string :tag "Command")
1702 (sexp :tag "Lisp form")))))
1706 (defgroup org-refile nil
1707 "Options concerning refiling entries in Org-mode."
1708 :tag "Org Refile"
1709 :group 'org)
1711 (defcustom org-directory "~/org"
1712 "Directory with org files.
1713 This is just a default location to look for Org files. There is no need
1714 at all to put your files into this directory. It is only used in the
1715 following situations:
1717 1. When a remember template specifies a target file that is not an
1718 absolute path. The path will then be interpreted relative to
1719 `org-directory'
1720 2. When a remember note is filed away in an interactive way (when exiting the
1721 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1722 with `org-directory' as the default path."
1723 :group 'org-refile
1724 :group 'org-remember
1725 :type 'directory)
1727 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1728 "Default target for storing notes.
1729 Used as a fall back file for org-remember.el and org-capture.el, for
1730 templates that do not specify a target file."
1731 :group 'org-refile
1732 :group 'org-remember
1733 :type '(choice
1734 (const :tag "Default from remember-data-file" nil)
1735 file))
1737 (defcustom org-goto-interface 'outline
1738 "The default interface to be used for `org-goto'.
1739 Allowed values are:
1740 outline The interface shows an outline of the relevant file
1741 and the correct heading is found by moving through
1742 the outline or by searching with incremental search.
1743 outline-path-completion Headlines in the current buffer are offered via
1744 completion. This is the interface also used by
1745 the refile command."
1746 :group 'org-refile
1747 :type '(choice
1748 (const :tag "Outline" outline)
1749 (const :tag "Outline-path-completion" outline-path-completion)))
1751 (defcustom org-goto-max-level 5
1752 "Maximum target level when running `org-goto' with refile interface."
1753 :group 'org-refile
1754 :type 'integer)
1756 (defcustom org-reverse-note-order nil
1757 "Non-nil means store new notes at the beginning of a file or entry.
1758 When nil, new notes will be filed to the end of a file or entry.
1759 This can also be a list with cons cells of regular expressions that
1760 are matched against file names, and values."
1761 :group 'org-remember
1762 :group 'org-refile
1763 :type '(choice
1764 (const :tag "Reverse always" t)
1765 (const :tag "Reverse never" nil)
1766 (repeat :tag "By file name regexp"
1767 (cons regexp boolean))))
1769 (defcustom org-log-refile nil
1770 "Information to record when a task is refiled.
1772 Possible values are:
1774 nil Don't add anything
1775 time Add a time stamp to the task
1776 note Prompt for a note and add it with template `org-log-note-headings'
1778 This option can also be set with on a per-file-basis with
1780 #+STARTUP: nologrefile
1781 #+STARTUP: logrefile
1782 #+STARTUP: lognoterefile
1784 You can have local logging settings for a subtree by setting the LOGGING
1785 property to one or more of these keywords.
1787 When bulk-refiling from the agenda, the value `note' is forbidden and
1788 will temporarily be changed to `time'."
1789 :group 'org-refile
1790 :group 'org-progress
1791 :type '(choice
1792 (const :tag "No logging" nil)
1793 (const :tag "Record timestamp" time)
1794 (const :tag "Record timestamp with note." note)))
1796 (defcustom org-refile-targets nil
1797 "Targets for refiling entries with \\[org-refile].
1798 This is list of cons cells. Each cell contains:
1799 - a specification of the files to be considered, either a list of files,
1800 or a symbol whose function or variable value will be used to retrieve
1801 a file name or a list of file names. If you use `org-agenda-files' for
1802 that, all agenda files will be scanned for targets. Nil means consider
1803 headings in the current buffer.
1804 - A specification of how to find candidate refile targets. This may be
1805 any of:
1806 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1807 This tag has to be present in all target headlines, inheritance will
1808 not be considered.
1809 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1810 todo keyword.
1811 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1812 headlines that are refiling targets.
1813 - a cons cell (:level . N). Any headline of level N is considered a target.
1814 Note that, when `org-odd-levels-only' is set, level corresponds to
1815 order in hierarchy, not to the number of stars.
1816 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1817 Note that, when `org-odd-levels-only' is set, level corresponds to
1818 order in hierarchy, not to the number of stars.
1820 You can set the variable `org-refile-target-verify-function' to a function
1821 to verify each headline found by the simple criteria above.
1823 When this variable is nil, all top-level headlines in the current buffer
1824 are used, equivalent to the value `((nil . (:level . 1))'."
1825 :group 'org-refile
1826 :type '(repeat
1827 (cons
1828 (choice :value org-agenda-files
1829 (const :tag "All agenda files" org-agenda-files)
1830 (const :tag "Current buffer" nil)
1831 (function) (variable) (file))
1832 (choice :tag "Identify target headline by"
1833 (cons :tag "Specific tag" (const :value :tag) (string))
1834 (cons :tag "TODO keyword" (const :value :todo) (string))
1835 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1836 (cons :tag "Level number" (const :value :level) (integer))
1837 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1839 (defcustom org-refile-target-verify-function nil
1840 "Function to verify if the headline at point should be a refile target.
1841 The function will be called without arguments, with point at the
1842 beginning of the headline. It should return t and leave point
1843 where it is if the headline is a valid target for refiling.
1845 If the target should not be selected, the function must return nil.
1846 In addition to this, it may move point to a place from where the search
1847 should be continued. For example, the function may decide that the entire
1848 subtree of the current entry should be excluded and move point to the end
1849 of the subtree."
1850 :group 'org-refile
1851 :type 'function)
1853 (defcustom org-refile-use-cache nil
1854 "Non-nil means cache refile targets to speed up the process.
1855 The cache for a particular file will be updated automatically when
1856 the buffer has been killed, or when any of the marker used for flagging
1857 refile targets no longer points at a live buffer.
1858 If you have added new entries to a buffer that might themselves be targets,
1859 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
1860 find that easier, `C-u C-u C-u C-c C-w'."
1861 :group 'org-refile
1862 :type 'boolean)
1864 (defcustom org-refile-use-outline-path nil
1865 "Non-nil means provide refile targets as paths.
1866 So a level 3 headline will be available as level1/level2/level3.
1868 When the value is `file', also include the file name (without directory)
1869 into the path. In this case, you can also stop the completion after
1870 the file name, to get entries inserted as top level in the file.
1872 When `full-file-path', include the full file path."
1873 :group 'org-refile
1874 :type '(choice
1875 (const :tag "Not" nil)
1876 (const :tag "Yes" t)
1877 (const :tag "Start with file name" file)
1878 (const :tag "Start with full file path" full-file-path)))
1880 (defcustom org-outline-path-complete-in-steps t
1881 "Non-nil means complete the outline path in hierarchical steps.
1882 When Org-mode uses the refile interface to select an outline path
1883 \(see variable `org-refile-use-outline-path'), the completion of
1884 the path can be done is a single go, or if can be done in steps down
1885 the headline hierarchy. Going in steps is probably the best if you
1886 do not use a special completion package like `ido' or `icicles'.
1887 However, when using these packages, going in one step can be very
1888 fast, while still showing the whole path to the entry."
1889 :group 'org-refile
1890 :type 'boolean)
1892 (defcustom org-refile-allow-creating-parent-nodes nil
1893 "Non-nil means allow to create new nodes as refile targets.
1894 New nodes are then created by adding \"/new node name\" to the completion
1895 of an existing node. When the value of this variable is `confirm',
1896 new node creation must be confirmed by the user (recommended)
1897 When nil, the completion must match an existing entry.
1899 Note that, if the new heading is not seen by the criteria
1900 listed in `org-refile-targets', multiple instances of the same
1901 heading would be created by trying again to file under the new
1902 heading."
1903 :group 'org-refile
1904 :type '(choice
1905 (const :tag "Never" nil)
1906 (const :tag "Always" t)
1907 (const :tag "Prompt for confirmation" confirm)))
1909 (defgroup org-todo nil
1910 "Options concerning TODO items in Org-mode."
1911 :tag "Org TODO"
1912 :group 'org)
1914 (defgroup org-progress nil
1915 "Options concerning Progress logging in Org-mode."
1916 :tag "Org Progress"
1917 :group 'org-time)
1919 (defvar org-todo-interpretation-widgets
1921 (:tag "Sequence (cycling hits every state)" sequence)
1922 (:tag "Type (cycling directly to DONE)" type))
1923 "The available interpretation symbols for customizing `org-todo-keywords'.
1924 Interested libraries should add to this list.")
1926 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1927 "List of TODO entry keyword sequences and their interpretation.
1928 \\<org-mode-map>This is a list of sequences.
1930 Each sequence starts with a symbol, either `sequence' or `type',
1931 indicating if the keywords should be interpreted as a sequence of
1932 action steps, or as different types of TODO items. The first
1933 keywords are states requiring action - these states will select a headline
1934 for inclusion into the global TODO list Org-mode produces. If one of
1935 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1936 signify that no further action is necessary. If \"|\" is not found,
1937 the last keyword is treated as the only DONE state of the sequence.
1939 The command \\[org-todo] cycles an entry through these states, and one
1940 additional state where no keyword is present. For details about this
1941 cycling, see the manual.
1943 TODO keywords and interpretation can also be set on a per-file basis with
1944 the special #+SEQ_TODO and #+TYP_TODO lines.
1946 Each keyword can optionally specify a character for fast state selection
1947 \(in combination with the variable `org-use-fast-todo-selection')
1948 and specifiers for state change logging, using the same syntax
1949 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1950 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1951 indicates to record a time stamp each time this state is selected.
1953 Each keyword may also specify if a timestamp or a note should be
1954 recorded when entering or leaving the state, by adding additional
1955 characters in the parenthesis after the keyword. This looks like this:
1956 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1957 record only the time of the state change. With X and Y being either
1958 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1959 Y when leaving the state if and only if the *target* state does not
1960 define X. You may omit any of the fast-selection key or X or /Y,
1961 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1963 For backward compatibility, this variable may also be just a list
1964 of keywords - in this case the interpretation (sequence or type) will be
1965 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1966 :group 'org-todo
1967 :group 'org-keywords
1968 :type '(choice
1969 (repeat :tag "Old syntax, just keywords"
1970 (string :tag "Keyword"))
1971 (repeat :tag "New syntax"
1972 (cons
1973 (choice
1974 :tag "Interpretation"
1975 ;;Quick and dirty way to see
1976 ;;`org-todo-interpretations'. This takes the
1977 ;;place of item arguments
1978 :convert-widget
1979 (lambda (widget)
1980 (widget-put widget
1981 :args (mapcar
1982 #'(lambda (x)
1983 (widget-convert
1984 (cons 'const x)))
1985 org-todo-interpretation-widgets))
1986 widget))
1987 (repeat
1988 (string :tag "Keyword"))))))
1990 (defvar org-todo-keywords-1 nil
1991 "All TODO and DONE keywords active in a buffer.")
1992 (make-variable-buffer-local 'org-todo-keywords-1)
1993 (defvar org-todo-keywords-for-agenda nil)
1994 (defvar org-done-keywords-for-agenda nil)
1995 (defvar org-drawers-for-agenda nil)
1996 (defvar org-todo-keyword-alist-for-agenda nil)
1997 (defvar org-tag-alist-for-agenda nil)
1998 (defvar org-agenda-contributing-files nil)
1999 (defvar org-not-done-keywords nil)
2000 (make-variable-buffer-local 'org-not-done-keywords)
2001 (defvar org-done-keywords nil)
2002 (make-variable-buffer-local 'org-done-keywords)
2003 (defvar org-todo-heads nil)
2004 (make-variable-buffer-local 'org-todo-heads)
2005 (defvar org-todo-sets nil)
2006 (make-variable-buffer-local 'org-todo-sets)
2007 (defvar org-todo-log-states nil)
2008 (make-variable-buffer-local 'org-todo-log-states)
2009 (defvar org-todo-kwd-alist nil)
2010 (make-variable-buffer-local 'org-todo-kwd-alist)
2011 (defvar org-todo-key-alist nil)
2012 (make-variable-buffer-local 'org-todo-key-alist)
2013 (defvar org-todo-key-trigger nil)
2014 (make-variable-buffer-local 'org-todo-key-trigger)
2016 (defcustom org-todo-interpretation 'sequence
2017 "Controls how TODO keywords are interpreted.
2018 This variable is in principle obsolete and is only used for
2019 backward compatibility, if the interpretation of todo keywords is
2020 not given already in `org-todo-keywords'. See that variable for
2021 more information."
2022 :group 'org-todo
2023 :group 'org-keywords
2024 :type '(choice (const sequence)
2025 (const type)))
2027 (defcustom org-use-fast-todo-selection t
2028 "Non-nil means use the fast todo selection scheme with C-c C-t.
2029 This variable describes if and under what circumstances the cycling
2030 mechanism for TODO keywords will be replaced by a single-key, direct
2031 selection scheme.
2033 When nil, fast selection is never used.
2035 When the symbol `prefix', it will be used when `org-todo' is called with
2036 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
2037 in an agenda buffer.
2039 When t, fast selection is used by default. In this case, the prefix
2040 argument forces cycling instead.
2042 In all cases, the special interface is only used if access keys have actually
2043 been assigned by the user, i.e. if keywords in the configuration are followed
2044 by a letter in parenthesis, like TODO(t)."
2045 :group 'org-todo
2046 :type '(choice
2047 (const :tag "Never" nil)
2048 (const :tag "By default" t)
2049 (const :tag "Only with C-u C-c C-t" prefix)))
2051 (defcustom org-provide-todo-statistics t
2052 "Non-nil means update todo statistics after insert and toggle.
2053 ALL-HEADLINES means update todo statistics by including headlines
2054 with no TODO keyword as well, counting them as not done.
2055 A list of TODO keywords means the same, but skip keywords that are
2056 not in this list.
2058 When this is set, todo statistics is updated in the parent of the
2059 current entry each time a todo state is changed."
2060 :group 'org-todo
2061 :type '(choice
2062 (const :tag "Yes, only for TODO entries" t)
2063 (const :tag "Yes, including all entries" 'all-headlines)
2064 (repeat :tag "Yes, for TODOs in this list"
2065 (string :tag "TODO keyword"))
2066 (other :tag "No TODO statistics" nil)))
2068 (defcustom org-hierarchical-todo-statistics t
2069 "Non-nil means TODO statistics covers just direct children.
2070 When nil, all entries in the subtree are considered.
2071 This has only an effect if `org-provide-todo-statistics' is set.
2072 To set this to nil for only a single subtree, use a COOKIE_DATA
2073 property and include the word \"recursive\" into the value."
2074 :group 'org-todo
2075 :type 'boolean)
2077 (defcustom org-after-todo-state-change-hook nil
2078 "Hook which is run after the state of a TODO item was changed.
2079 The new state (a string with a TODO keyword, or nil) is available in the
2080 Lisp variable `state'."
2081 :group 'org-todo
2082 :type 'hook)
2084 (defvar org-blocker-hook nil
2085 "Hook for functions that are allowed to block a state change.
2087 Each function gets as its single argument a property list, see
2088 `org-trigger-hook' for more information about this list.
2090 If any of the functions in this hook returns nil, the state change
2091 is blocked.")
2093 (defvar org-trigger-hook nil
2094 "Hook for functions that are triggered by a state change.
2096 Each function gets as its single argument a property list with at least
2097 the following elements:
2099 (:type type-of-change :position pos-at-entry-start
2100 :from old-state :to new-state)
2102 Depending on the type, more properties may be present.
2104 This mechanism is currently implemented for:
2106 TODO state changes
2107 ------------------
2108 :type todo-state-change
2109 :from previous state (keyword as a string), or nil, or a symbol
2110 'todo' or 'done', to indicate the general type of state.
2111 :to new state, like in :from")
2113 (defcustom org-enforce-todo-dependencies nil
2114 "Non-nil means undone TODO entries will block switching the parent to DONE.
2115 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2116 be blocked if any prior sibling is not yet done.
2117 Finally, if the parent is blocked because of ordered siblings of its own,
2118 the child will also be blocked.
2119 This variable needs to be set before org.el is loaded, and you need to
2120 restart Emacs after a change to make the change effective. The only way
2121 to change is while Emacs is running is through the customize interface."
2122 :set (lambda (var val)
2123 (set var val)
2124 (if val
2125 (add-hook 'org-blocker-hook
2126 'org-block-todo-from-children-or-siblings-or-parent)
2127 (remove-hook 'org-blocker-hook
2128 'org-block-todo-from-children-or-siblings-or-parent)))
2129 :group 'org-todo
2130 :type 'boolean)
2132 (defcustom org-enforce-todo-checkbox-dependencies nil
2133 "Non-nil means unchecked boxes will block switching the parent to DONE.
2134 When this is nil, checkboxes have no influence on switching TODO states.
2135 When non-nil, you first need to check off all check boxes before the TODO
2136 entry can be switched to DONE.
2137 This variable needs to be set before org.el is loaded, and you need to
2138 restart Emacs after a change to make the change effective. The only way
2139 to change is while Emacs is running is through the customize interface."
2140 :set (lambda (var val)
2141 (set var val)
2142 (if val
2143 (add-hook 'org-blocker-hook
2144 'org-block-todo-from-checkboxes)
2145 (remove-hook 'org-blocker-hook
2146 'org-block-todo-from-checkboxes)))
2147 :group 'org-todo
2148 :type 'boolean)
2150 (defcustom org-treat-insert-todo-heading-as-state-change nil
2151 "Non-nil means inserting a TODO heading is treated as state change.
2152 So when the command \\[org-insert-todo-heading] is used, state change
2153 logging will apply if appropriate. When nil, the new TODO item will
2154 be inserted directly, and no logging will take place."
2155 :group 'org-todo
2156 :type 'boolean)
2158 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2159 "Non-nil means switching TODO states with S-cursor counts as state change.
2160 This is the default behavior. However, setting this to nil allows a
2161 convenient way to select a TODO state and bypass any logging associated
2162 with that."
2163 :group 'org-todo
2164 :type 'boolean)
2166 (defcustom org-todo-state-tags-triggers nil
2167 "Tag changes that should be triggered by TODO state changes.
2168 This is a list. Each entry is
2170 (state-change (tag . flag) .......)
2172 State-change can be a string with a state, and empty string to indicate the
2173 state that has no TODO keyword, or it can be one of the symbols `todo'
2174 or `done', meaning any not-done or done state, respectively."
2175 :group 'org-todo
2176 :group 'org-tags
2177 :type '(repeat
2178 (cons (choice :tag "When changing to"
2179 (const :tag "Not-done state" todo)
2180 (const :tag "Done state" done)
2181 (string :tag "State"))
2182 (repeat
2183 (cons :tag "Tag action"
2184 (string :tag "Tag")
2185 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2187 (defcustom org-log-done nil
2188 "Information to record when a task moves to the DONE state.
2190 Possible values are:
2192 nil Don't add anything, just change the keyword
2193 time Add a time stamp to the task
2194 note Prompt for a note and add it with template `org-log-note-headings'
2196 This option can also be set with on a per-file-basis with
2198 #+STARTUP: nologdone
2199 #+STARTUP: logdone
2200 #+STARTUP: lognotedone
2202 You can have local logging settings for a subtree by setting the LOGGING
2203 property to one or more of these keywords."
2204 :group 'org-todo
2205 :group 'org-progress
2206 :type '(choice
2207 (const :tag "No logging" nil)
2208 (const :tag "Record CLOSED timestamp" time)
2209 (const :tag "Record CLOSED timestamp with note." note)))
2211 ;; Normalize old uses of org-log-done.
2212 (cond
2213 ((eq org-log-done t) (setq org-log-done 'time))
2214 ((and (listp org-log-done) (memq 'done org-log-done))
2215 (setq org-log-done 'note)))
2217 (defcustom org-log-reschedule nil
2218 "Information to record when the scheduling date of a tasks is modified.
2220 Possible values are:
2222 nil Don't add anything, just change the date
2223 time Add a time stamp to the task
2224 note Prompt for a note and add it with template `org-log-note-headings'
2226 This option can also be set with on a per-file-basis with
2228 #+STARTUP: nologreschedule
2229 #+STARTUP: logreschedule
2230 #+STARTUP: lognotereschedule"
2231 :group 'org-todo
2232 :group 'org-progress
2233 :type '(choice
2234 (const :tag "No logging" nil)
2235 (const :tag "Record timestamp" time)
2236 (const :tag "Record timestamp with note." note)))
2238 (defcustom org-log-redeadline nil
2239 "Information to record when the deadline date of a tasks is modified.
2241 Possible values are:
2243 nil Don't add anything, just change the date
2244 time Add a time stamp to the task
2245 note Prompt for a note and add it with template `org-log-note-headings'
2247 This option can also be set with on a per-file-basis with
2249 #+STARTUP: nologredeadline
2250 #+STARTUP: logredeadline
2251 #+STARTUP: lognoteredeadline
2253 You can have local logging settings for a subtree by setting the LOGGING
2254 property to one or more of these keywords."
2255 :group 'org-todo
2256 :group 'org-progress
2257 :type '(choice
2258 (const :tag "No logging" nil)
2259 (const :tag "Record timestamp" time)
2260 (const :tag "Record timestamp with note." note)))
2262 (defcustom org-log-note-clock-out nil
2263 "Non-nil means record a note when clocking out of an item.
2264 This can also be configured on a per-file basis by adding one of
2265 the following lines anywhere in the buffer:
2267 #+STARTUP: lognoteclock-out
2268 #+STARTUP: nolognoteclock-out"
2269 :group 'org-todo
2270 :group 'org-progress
2271 :type 'boolean)
2273 (defcustom org-log-done-with-time t
2274 "Non-nil means the CLOSED time stamp will contain date and time.
2275 When nil, only the date will be recorded."
2276 :group 'org-progress
2277 :type 'boolean)
2279 (defcustom org-log-note-headings
2280 '((done . "CLOSING NOTE %t")
2281 (state . "State %-12s from %-12S %t")
2282 (note . "Note taken on %t")
2283 (reschedule . "Rescheduled from %S on %t")
2284 (delschedule . "Not scheduled, was %S on %t")
2285 (redeadline . "New deadline from %S on %t")
2286 (deldeadline . "Removed deadline, was %S on %t")
2287 (refile . "Refiled on %t")
2288 (clock-out . ""))
2289 "Headings for notes added to entries.
2290 The value is an alist, with the car being a symbol indicating the note
2291 context, and the cdr is the heading to be used. The heading may also be the
2292 empty string.
2293 %t in the heading will be replaced by a time stamp.
2294 %T will be an active time stamp instead the default inactive one
2295 %s will be replaced by the new TODO state, in double quotes.
2296 %S will be replaced by the old TODO state, in double quotes.
2297 %u will be replaced by the user name.
2298 %U will be replaced by the full user name.
2300 In fact, it is not a good idea to change the `state' entry, because
2301 agenda log mode depends on the format of these entries."
2302 :group 'org-todo
2303 :group 'org-progress
2304 :type '(list :greedy t
2305 (cons (const :tag "Heading when closing an item" done) string)
2306 (cons (const :tag
2307 "Heading when changing todo state (todo sequence only)"
2308 state) string)
2309 (cons (const :tag "Heading when just taking a note" note) string)
2310 (cons (const :tag "Heading when clocking out" clock-out) string)
2311 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2312 (cons (const :tag "Heading when rescheduling" reschedule) string)
2313 (cons (const :tag "Heading when changing deadline" redeadline) string)
2314 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2315 (cons (const :tag "Heading when refiling" refile) string)))
2317 (unless (assq 'note org-log-note-headings)
2318 (push '(note . "%t") org-log-note-headings))
2320 (defcustom org-log-into-drawer nil
2321 "Non-nil means insert state change notes and time stamps into a drawer.
2322 When nil, state changes notes will be inserted after the headline and
2323 any scheduling and clock lines, but not inside a drawer.
2325 The value of this variable should be the name of the drawer to use.
2326 LOGBOOK is proposed at the default drawer for this purpose, you can
2327 also set this to a string to define the drawer of your choice.
2329 A value of t is also allowed, representing \"LOGBOOK\".
2331 If this variable is set, `org-log-state-notes-insert-after-drawers'
2332 will be ignored.
2334 You can set the property LOG_INTO_DRAWER to overrule this setting for
2335 a subtree."
2336 :group 'org-todo
2337 :group 'org-progress
2338 :type '(choice
2339 (const :tag "Not into a drawer" nil)
2340 (const :tag "LOGBOOK" t)
2341 (string :tag "Other")))
2343 (if (fboundp 'defvaralias)
2344 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2346 (defun org-log-into-drawer ()
2347 "Return the value of `org-log-into-drawer', but let properties overrule.
2348 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2349 used instead of the default value."
2350 (let ((p (ignore-errors (org-entry-get nil "LOG_INTO_DRAWER" 'inherit))))
2351 (cond
2352 ((or (not p) (equal p "nil")) org-log-into-drawer)
2353 ((equal p "t") "LOGBOOK")
2354 (t p))))
2356 (defcustom org-log-state-notes-insert-after-drawers nil
2357 "Non-nil means insert state change notes after any drawers in entry.
2358 Only the drawers that *immediately* follow the headline and the
2359 deadline/scheduled line are skipped.
2360 When nil, insert notes right after the heading and perhaps the line
2361 with deadline/scheduling if present.
2363 This variable will have no effect if `org-log-into-drawer' is
2364 set."
2365 :group 'org-todo
2366 :group 'org-progress
2367 :type 'boolean)
2369 (defcustom org-log-states-order-reversed t
2370 "Non-nil means the latest state note will be directly after heading.
2371 When nil, the state change notes will be ordered according to time."
2372 :group 'org-todo
2373 :group 'org-progress
2374 :type 'boolean)
2376 (defcustom org-todo-repeat-to-state nil
2377 "The TODO state to which a repeater should return the repeating task.
2378 By default this is the first task in a TODO sequence, or the previous state
2379 in a TODO_TYP set. But you can specify another task here.
2380 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2381 :group 'org-todo
2382 :type '(choice (const :tag "Head of sequence" nil)
2383 (string :tag "Specific state")))
2385 (defcustom org-log-repeat 'time
2386 "Non-nil means record moving through the DONE state when triggering repeat.
2387 An auto-repeating task is immediately switched back to TODO when
2388 marked DONE. If you are not logging state changes (by adding \"@\"
2389 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2390 record a closing note, there will be no record of the task moving
2391 through DONE. This variable forces taking a note anyway.
2393 nil Don't force a record
2394 time Record a time stamp
2395 note Record a note
2397 This option can also be set with on a per-file-basis with
2399 #+STARTUP: logrepeat
2400 #+STARTUP: lognoterepeat
2401 #+STARTUP: nologrepeat
2403 You can have local logging settings for a subtree by setting the LOGGING
2404 property to one or more of these keywords."
2405 :group 'org-todo
2406 :group 'org-progress
2407 :type '(choice
2408 (const :tag "Don't force a record" nil)
2409 (const :tag "Force recording the DONE state" time)
2410 (const :tag "Force recording a note with the DONE state" note)))
2413 (defgroup org-priorities nil
2414 "Priorities in Org-mode."
2415 :tag "Org Priorities"
2416 :group 'org-todo)
2418 (defcustom org-enable-priority-commands t
2419 "Non-nil means priority commands are active.
2420 When nil, these commands will be disabled, so that you never accidentally
2421 set a priority."
2422 :group 'org-priorities
2423 :type 'boolean)
2425 (defcustom org-highest-priority ?A
2426 "The highest priority of TODO items. A character like ?A, ?B etc.
2427 Must have a smaller ASCII number than `org-lowest-priority'."
2428 :group 'org-priorities
2429 :type 'character)
2431 (defcustom org-lowest-priority ?C
2432 "The lowest priority of TODO items. A character like ?A, ?B etc.
2433 Must have a larger ASCII number than `org-highest-priority'."
2434 :group 'org-priorities
2435 :type 'character)
2437 (defcustom org-default-priority ?B
2438 "The default priority of TODO items.
2439 This is the priority an item get if no explicit priority is given."
2440 :group 'org-priorities
2441 :type 'character)
2443 (defcustom org-priority-start-cycle-with-default t
2444 "Non-nil means start with default priority when starting to cycle.
2445 When this is nil, the first step in the cycle will be (depending on the
2446 command used) one higher or lower that the default priority."
2447 :group 'org-priorities
2448 :type 'boolean)
2450 (defgroup org-time nil
2451 "Options concerning time stamps and deadlines in Org-mode."
2452 :tag "Org Time"
2453 :group 'org)
2455 (defcustom org-insert-labeled-timestamps-at-point nil
2456 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2457 When nil, these labeled time stamps are forces into the second line of an
2458 entry, just after the headline. When scheduling from the global TODO list,
2459 the time stamp will always be forced into the second line."
2460 :group 'org-time
2461 :type 'boolean)
2463 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2464 "Formats for `format-time-string' which are used for time stamps.
2465 It is not recommended to change this constant.")
2467 (defcustom org-time-stamp-rounding-minutes '(0 5)
2468 "Number of minutes to round time stamps to.
2469 These are two values, the first applies when first creating a time stamp.
2470 The second applies when changing it with the commands `S-up' and `S-down'.
2471 When changing the time stamp, this means that it will change in steps
2472 of N minutes, as given by the second value.
2474 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2475 numbers should be factors of 60, so for example 5, 10, 15.
2477 When this is larger than 1, you can still force an exact time stamp by using
2478 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2479 and by using a prefix arg to `S-up/down' to specify the exact number
2480 of minutes to shift."
2481 :group 'org-time
2482 :get '(lambda (var) ; Make sure both elements are there
2483 (if (integerp (default-value var))
2484 (list (default-value var) 5)
2485 (default-value var)))
2486 :type '(list
2487 (integer :tag "when inserting times")
2488 (integer :tag "when modifying times")))
2490 ;; Normalize old customizations of this variable.
2491 (when (integerp org-time-stamp-rounding-minutes)
2492 (setq org-time-stamp-rounding-minutes
2493 (list org-time-stamp-rounding-minutes
2494 org-time-stamp-rounding-minutes)))
2496 (defcustom org-display-custom-times nil
2497 "Non-nil means overlay custom formats over all time stamps.
2498 The formats are defined through the variable `org-time-stamp-custom-formats'.
2499 To turn this on on a per-file basis, insert anywhere in the file:
2500 #+STARTUP: customtime"
2501 :group 'org-time
2502 :set 'set-default
2503 :type 'sexp)
2504 (make-variable-buffer-local 'org-display-custom-times)
2506 (defcustom org-time-stamp-custom-formats
2507 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2508 "Custom formats for time stamps. See `format-time-string' for the syntax.
2509 These are overlayed over the default ISO format if the variable
2510 `org-display-custom-times' is set. Time like %H:%M should be at the
2511 end of the second format. The custom formats are also honored by export
2512 commands, if custom time display is turned on at the time of export."
2513 :group 'org-time
2514 :type 'sexp)
2516 (defun org-time-stamp-format (&optional long inactive)
2517 "Get the right format for a time string."
2518 (let ((f (if long (cdr org-time-stamp-formats)
2519 (car org-time-stamp-formats))))
2520 (if inactive
2521 (concat "[" (substring f 1 -1) "]")
2522 f)))
2524 (defcustom org-time-clocksum-format "%d:%02d"
2525 "The format string used when creating CLOCKSUM lines.
2526 This is also used when org-mode generates a time duration."
2527 :group 'org-time
2528 :type 'string)
2530 (defcustom org-time-clocksum-use-fractional nil
2531 "If non-nil, \\[org-clock-display] uses fractional times.
2532 org-mode generates a time duration."
2533 :group 'org-time
2534 :type 'boolean)
2536 (defcustom org-time-clocksum-fractional-format "%.2f"
2537 "The format string used when creating CLOCKSUM lines, or when
2538 org-mode generates a time duration."
2539 :group 'org-time
2540 :type 'string)
2542 (defcustom org-deadline-warning-days 14
2543 "No. of days before expiration during which a deadline becomes active.
2544 This variable governs the display in sparse trees and in the agenda.
2545 When 0 or negative, it means use this number (the absolute value of it)
2546 even if a deadline has a different individual lead time specified.
2548 Custom commands can set this variable in the options section."
2549 :group 'org-time
2550 :group 'org-agenda-daily/weekly
2551 :type 'integer)
2553 (defcustom org-read-date-prefer-future t
2554 "Non-nil means assume future for incomplete date input from user.
2555 This affects the following situations:
2556 1. The user gives a month but not a year.
2557 For example, if it is April and you enter \"feb 2\", this will be read
2558 as Feb 2, *next* year. \"May 5\", however, will be this year.
2559 2. The user gives a day, but no month.
2560 For example, if today is the 15th, and you enter \"3\", Org-mode will
2561 read this as the third of *next* month. However, if you enter \"17\",
2562 it will be considered as *this* month.
2564 If you set this variable to the symbol `time', then also the following
2565 will work:
2567 3. If the user gives a time, but no day. If the time is before now,
2568 to will be interpreted as tomorrow.
2570 Currently none of this works for ISO week specifications.
2572 When this option is nil, the current day, month and year will always be
2573 used as defaults."
2574 :group 'org-time
2575 :type '(choice
2576 (const :tag "Never" nil)
2577 (const :tag "Check month and day" t)
2578 (const :tag "Check month, day, and time" time)))
2580 (defcustom org-read-date-display-live t
2581 "Non-nil means display current interpretation of date prompt live.
2582 This display will be in an overlay, in the minibuffer."
2583 :group 'org-time
2584 :type 'boolean)
2586 (defcustom org-read-date-popup-calendar t
2587 "Non-nil means pop up a calendar when prompting for a date.
2588 In the calendar, the date can be selected with mouse-1. However, the
2589 minibuffer will also be active, and you can simply enter the date as well.
2590 When nil, only the minibuffer will be available."
2591 :group 'org-time
2592 :type 'boolean)
2593 (if (fboundp 'defvaralias)
2594 (defvaralias 'org-popup-calendar-for-date-prompt
2595 'org-read-date-popup-calendar))
2597 (defcustom org-read-date-minibuffer-setup-hook nil
2598 "Hook to be used to set up keys for the date/time interface.
2599 Add key definitions to `minibuffer-local-map', which will be a temporary
2600 copy."
2601 :group 'org-time
2602 :type 'hook)
2604 (defcustom org-extend-today-until 0
2605 "The hour when your day really ends. Must be an integer.
2606 This has influence for the following applications:
2607 - When switching the agenda to \"today\". It it is still earlier than
2608 the time given here, the day recognized as TODAY is actually yesterday.
2609 - When a date is read from the user and it is still before the time given
2610 here, the current date and time will be assumed to be yesterday, 23:59.
2611 Also, timestamps inserted in remember templates follow this rule.
2613 IMPORTANT: This is a feature whose implementation is and likely will
2614 remain incomplete. Really, it is only here because past midnight seems to
2615 be the favorite working time of John Wiegley :-)"
2616 :group 'org-time
2617 :type 'integer)
2619 (defcustom org-edit-timestamp-down-means-later nil
2620 "Non-nil means S-down will increase the time in a time stamp.
2621 When nil, S-up will increase."
2622 :group 'org-time
2623 :type 'boolean)
2625 (defcustom org-calendar-follow-timestamp-change t
2626 "Non-nil means make the calendar window follow timestamp changes.
2627 When a timestamp is modified and the calendar window is visible, it will be
2628 moved to the new date."
2629 :group 'org-time
2630 :type 'boolean)
2632 (defgroup org-tags nil
2633 "Options concerning tags in Org-mode."
2634 :tag "Org Tags"
2635 :group 'org)
2637 (defcustom org-tag-alist nil
2638 "List of tags allowed in Org-mode files.
2639 When this list is nil, Org-mode will base TAG input on what is already in the
2640 buffer.
2641 The value of this variable is an alist, the car of each entry must be a
2642 keyword as a string, the cdr may be a character that is used to select
2643 that tag through the fast-tag-selection interface.
2644 See the manual for details."
2645 :group 'org-tags
2646 :type '(repeat
2647 (choice
2648 (cons (string :tag "Tag name")
2649 (character :tag "Access char"))
2650 (list :tag "Start radio group"
2651 (const :startgroup)
2652 (option (string :tag "Group description")))
2653 (list :tag "End radio group"
2654 (const :endgroup)
2655 (option (string :tag "Group description")))
2656 (const :tag "New line" (:newline)))))
2658 (defcustom org-tag-persistent-alist nil
2659 "List of tags that will always appear in all Org-mode files.
2660 This is in addition to any in buffer settings or customizations
2661 of `org-tag-alist'.
2662 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2663 The value of this variable is an alist, the car of each entry must be a
2664 keyword as a string, the cdr may be a character that is used to select
2665 that tag through the fast-tag-selection interface.
2666 See the manual for details.
2667 To disable these tags on a per-file basis, insert anywhere in the file:
2668 #+STARTUP: noptag"
2669 :group 'org-tags
2670 :type '(repeat
2671 (choice
2672 (cons (string :tag "Tag name")
2673 (character :tag "Access char"))
2674 (const :tag "Start radio group" (:startgroup))
2675 (const :tag "End radio group" (:endgroup))
2676 (const :tag "New line" (:newline)))))
2678 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2679 "If non-nil, always offer completion for all tags of all agenda files.
2680 Instead of customizing this variable directly, you might want to
2681 set it locally for remember buffers, because there no list of
2682 tags in that file can be created dynamically (there are none).
2684 (add-hook 'org-remember-mode-hook
2685 (lambda ()
2686 (set (make-local-variable
2687 'org-complete-tags-always-offer-all-agenda-tags)
2688 t)))"
2689 :group 'org-tags
2690 :type 'boolean)
2692 (defvar org-file-tags nil
2693 "List of tags that can be inherited by all entries in the file.
2694 The tags will be inherited if the variable `org-use-tag-inheritance'
2695 says they should be.
2696 This variable is populated from #+FILETAGS lines.")
2698 (defcustom org-use-fast-tag-selection 'auto
2699 "Non-nil means use fast tag selection scheme.
2700 This is a special interface to select and deselect tags with single keys.
2701 When nil, fast selection is never used.
2702 When the symbol `auto', fast selection is used if and only if selection
2703 characters for tags have been configured, either through the variable
2704 `org-tag-alist' or through a #+TAGS line in the buffer.
2705 When t, fast selection is always used and selection keys are assigned
2706 automatically if necessary."
2707 :group 'org-tags
2708 :type '(choice
2709 (const :tag "Always" t)
2710 (const :tag "Never" nil)
2711 (const :tag "When selection characters are configured" 'auto)))
2713 (defcustom org-fast-tag-selection-single-key nil
2714 "Non-nil means fast tag selection exits after first change.
2715 When nil, you have to press RET to exit it.
2716 During fast tag selection, you can toggle this flag with `C-c'.
2717 This variable can also have the value `expert'. In this case, the window
2718 displaying the tags menu is not even shown, until you press C-c again."
2719 :group 'org-tags
2720 :type '(choice
2721 (const :tag "No" nil)
2722 (const :tag "Yes" t)
2723 (const :tag "Expert" expert)))
2725 (defvar org-fast-tag-selection-include-todo nil
2726 "Non-nil means fast tags selection interface will also offer TODO states.
2727 This is an undocumented feature, you should not rely on it.")
2729 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2730 "The column to which tags should be indented in a headline.
2731 If this number is positive, it specifies the column. If it is negative,
2732 it means that the tags should be flushright to that column. For example,
2733 -80 works well for a normal 80 character screen."
2734 :group 'org-tags
2735 :type 'integer)
2737 (defcustom org-auto-align-tags t
2738 "Non-nil means realign tags after pro/demotion of TODO state change.
2739 These operations change the length of a headline and therefore shift
2740 the tags around. With this options turned on, after each such operation
2741 the tags are again aligned to `org-tags-column'."
2742 :group 'org-tags
2743 :type 'boolean)
2745 (defcustom org-use-tag-inheritance t
2746 "Non-nil means tags in levels apply also for sublevels.
2747 When nil, only the tags directly given in a specific line apply there.
2748 This may also be a list of tags that should be inherited, or a regexp that
2749 matches tags that should be inherited. Additional control is possible
2750 with the variable `org-tags-exclude-from-inheritance' which gives an
2751 explicit list of tags to be excluded from inheritance., even if the value of
2752 `org-use-tag-inheritance' would select it for inheritance.
2754 If this option is t, a match early-on in a tree can lead to a large
2755 number of matches in the subtree when constructing the agenda or creating
2756 a sparse tree. If you only want to see the first match in a tree during
2757 a search, check out the variable `org-tags-match-list-sublevels'."
2758 :group 'org-tags
2759 :type '(choice
2760 (const :tag "Not" nil)
2761 (const :tag "Always" t)
2762 (repeat :tag "Specific tags" (string :tag "Tag"))
2763 (regexp :tag "Tags matched by regexp")))
2765 (defcustom org-tags-exclude-from-inheritance nil
2766 "List of tags that should never be inherited.
2767 This is a way to exclude a few tags from inheritance. For way to do
2768 the opposite, to actively allow inheritance for selected tags,
2769 see the variable `org-use-tag-inheritance'."
2770 :group 'org-tags
2771 :type '(repeat (string :tag "Tag")))
2773 (defun org-tag-inherit-p (tag)
2774 "Check if TAG is one that should be inherited."
2775 (cond
2776 ((member tag org-tags-exclude-from-inheritance) nil)
2777 ((eq org-use-tag-inheritance t) t)
2778 ((not org-use-tag-inheritance) nil)
2779 ((stringp org-use-tag-inheritance)
2780 (string-match org-use-tag-inheritance tag))
2781 ((listp org-use-tag-inheritance)
2782 (member tag org-use-tag-inheritance))
2783 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2785 (defcustom org-tags-match-list-sublevels t
2786 "Non-nil means list also sublevels of headlines matching a search.
2787 This variable applies to tags/property searches, and also to stuck
2788 projects because this search is based on a tags match as well.
2790 When set to the symbol `indented', sublevels are indented with
2791 leading dots.
2793 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2794 the sublevels of a headline matching a tag search often also match
2795 the same search. Listing all of them can create very long lists.
2796 Setting this variable to nil causes subtrees of a match to be skipped.
2798 This variable is semi-obsolete and probably should always be true. It
2799 is better to limit inheritance to certain tags using the variables
2800 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2801 :group 'org-tags
2802 :type '(choice
2803 (const :tag "No, don't list them" nil)
2804 (const :tag "Yes, do list them" t)
2805 (const :tag "List them, indented with leading dots" indented)))
2807 (defcustom org-tags-sort-function nil
2808 "When set, tags are sorted using this function as a comparator."
2809 :group 'org-tags
2810 :type '(choice
2811 (const :tag "No sorting" nil)
2812 (const :tag "Alphabetical" string<)
2813 (const :tag "Reverse alphabetical" string>)
2814 (function :tag "Custom function" nil)))
2816 (defvar org-tags-history nil
2817 "History of minibuffer reads for tags.")
2818 (defvar org-last-tags-completion-table nil
2819 "The last used completion table for tags.")
2820 (defvar org-after-tags-change-hook nil
2821 "Hook that is run after the tags in a line have changed.")
2823 (defgroup org-properties nil
2824 "Options concerning properties in Org-mode."
2825 :tag "Org Properties"
2826 :group 'org)
2828 (defcustom org-property-format "%-10s %s"
2829 "How property key/value pairs should be formatted by `indent-line'.
2830 When `indent-line' hits a property definition, it will format the line
2831 according to this format, mainly to make sure that the values are
2832 lined-up with respect to each other."
2833 :group 'org-properties
2834 :type 'string)
2836 (defcustom org-use-property-inheritance nil
2837 "Non-nil means properties apply also for sublevels.
2839 This setting is chiefly used during property searches. Turning it on can
2840 cause significant overhead when doing a search, which is why it is not
2841 on by default.
2843 When nil, only the properties directly given in the current entry count.
2844 When t, every property is inherited. The value may also be a list of
2845 properties that should have inheritance, or a regular expression matching
2846 properties that should be inherited.
2848 However, note that some special properties use inheritance under special
2849 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2850 and the properties ending in \"_ALL\" when they are used as descriptor
2851 for valid values of a property.
2853 Note for programmers:
2854 When querying an entry with `org-entry-get', you can control if inheritance
2855 should be used. By default, `org-entry-get' looks only at the local
2856 properties. You can request inheritance by setting the inherit argument
2857 to t (to force inheritance) or to `selective' (to respect the setting
2858 in this variable)."
2859 :group 'org-properties
2860 :type '(choice
2861 (const :tag "Not" nil)
2862 (const :tag "Always" t)
2863 (repeat :tag "Specific properties" (string :tag "Property"))
2864 (regexp :tag "Properties matched by regexp")))
2866 (defun org-property-inherit-p (property)
2867 "Check if PROPERTY is one that should be inherited."
2868 (cond
2869 ((eq org-use-property-inheritance t) t)
2870 ((not org-use-property-inheritance) nil)
2871 ((stringp org-use-property-inheritance)
2872 (string-match org-use-property-inheritance property))
2873 ((listp org-use-property-inheritance)
2874 (member property org-use-property-inheritance))
2875 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2877 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2878 "The default column format, if no other format has been defined.
2879 This variable can be set on the per-file basis by inserting a line
2881 #+COLUMNS: %25ITEM ....."
2882 :group 'org-properties
2883 :type 'string)
2885 (defcustom org-columns-ellipses ".."
2886 "The ellipses to be used when a field in column view is truncated.
2887 When this is the empty string, as many characters as possible are shown,
2888 but then there will be no visual indication that the field has been truncated.
2889 When this is a string of length N, the last N characters of a truncated
2890 field are replaced by this string. If the column is narrower than the
2891 ellipses string, only part of the ellipses string will be shown."
2892 :group 'org-properties
2893 :type 'string)
2895 (defcustom org-columns-modify-value-for-display-function nil
2896 "Function that modifies values for display in column view.
2897 For example, it can be used to cut out a certain part from a time stamp.
2898 The function must take 2 arguments:
2900 column-title The title of the column (*not* the property name)
2901 value The value that should be modified.
2903 The function should return the value that should be displayed,
2904 or nil if the normal value should be used."
2905 :group 'org-properties
2906 :type 'function)
2908 (defcustom org-effort-property "Effort"
2909 "The property that is being used to keep track of effort estimates.
2910 Effort estimates given in this property need to have the format H:MM."
2911 :group 'org-properties
2912 :group 'org-progress
2913 :type '(string :tag "Property"))
2915 (defconst org-global-properties-fixed
2916 '(("VISIBILITY_ALL" . "folded children content all")
2917 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
2918 "List of property/value pairs that can be inherited by any entry.
2920 These are fixed values, for the preset properties. The user variable
2921 that can be used to add to this list is `org-global-properties'.
2923 The entries in this list are cons cells where the car is a property
2924 name and cdr is a string with the value. If the value represents
2925 multiple items like an \"_ALL\" property, separate the items by
2926 spaces.")
2928 (defcustom org-global-properties nil
2929 "List of property/value pairs that can be inherited by any entry.
2931 This list will be combined with the constant `org-global-properties-fixed'.
2933 The entries in this list are cons cells where the car is a property
2934 name and cdr is a string with the value.
2936 You can set buffer-local values for the same purpose in the variable
2937 `org-file-properties' this by adding lines like
2939 #+PROPERTY: NAME VALUE"
2940 :group 'org-properties
2941 :type '(repeat
2942 (cons (string :tag "Property")
2943 (string :tag "Value"))))
2945 (defvar org-file-properties nil
2946 "List of property/value pairs that can be inherited by any entry.
2947 Valid for the current buffer.
2948 This variable is populated from #+PROPERTY lines.")
2949 (make-variable-buffer-local 'org-file-properties)
2951 (defgroup org-agenda nil
2952 "Options concerning agenda views in Org-mode."
2953 :tag "Org Agenda"
2954 :group 'org)
2956 (defvar org-category nil
2957 "Variable used by org files to set a category for agenda display.
2958 Such files should use a file variable to set it, for example
2960 # -*- mode: org; org-category: \"ELisp\"
2962 or contain a special line
2964 #+CATEGORY: ELisp
2966 If the file does not specify a category, then file's base name
2967 is used instead.")
2968 (make-variable-buffer-local 'org-category)
2969 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2971 (defcustom org-agenda-files nil
2972 "The files to be used for agenda display.
2973 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2974 \\[org-remove-file]. You can also use customize to edit the list.
2976 If an entry is a directory, all files in that directory that are matched by
2977 `org-agenda-file-regexp' will be part of the file list.
2979 If the value of the variable is not a list but a single file name, then
2980 the list of agenda files is actually stored and maintained in that file, one
2981 agenda file per line. In this file paths can be given relative to
2982 `org-directory'. Tilde expansion and environment variable substitution
2983 are also made."
2984 :group 'org-agenda
2985 :type '(choice
2986 (repeat :tag "List of files and directories" file)
2987 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2989 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2990 "Regular expression to match files for `org-agenda-files'.
2991 If any element in the list in that variable contains a directory instead
2992 of a normal file, all files in that directory that are matched by this
2993 regular expression will be included."
2994 :group 'org-agenda
2995 :type 'regexp)
2997 (defcustom org-agenda-text-search-extra-files nil
2998 "List of extra files to be searched by text search commands.
2999 These files will be search in addition to the agenda files by the
3000 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3001 Note that these files will only be searched for text search commands,
3002 not for the other agenda views like todo lists, tag searches or the weekly
3003 agenda. This variable is intended to list notes and possibly archive files
3004 that should also be searched by these two commands.
3005 In fact, if the first element in the list is the symbol `agenda-archives',
3006 than all archive files of all agenda files will be added to the search
3007 scope."
3008 :group 'org-agenda
3009 :type '(set :greedy t
3010 (const :tag "Agenda Archives" agenda-archives)
3011 (repeat :inline t (file))))
3013 (if (fboundp 'defvaralias)
3014 (defvaralias 'org-agenda-multi-occur-extra-files
3015 'org-agenda-text-search-extra-files))
3017 (defcustom org-agenda-skip-unavailable-files nil
3018 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3019 A nil value means to remove them, after a query, from the list."
3020 :group 'org-agenda
3021 :type 'boolean)
3023 (defcustom org-calendar-to-agenda-key [?c]
3024 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3025 The command `org-calendar-goto-agenda' will be bound to this key. The
3026 default is the character `c' because then `c' can be used to switch back and
3027 forth between agenda and calendar."
3028 :group 'org-agenda
3029 :type 'sexp)
3031 (defcustom org-calendar-agenda-action-key [?k]
3032 "The key to be installed in `calendar-mode-map' for agenda-action.
3033 The command `org-agenda-action' will be bound to this key. The
3034 default is the character `k' because we use the same key in the agenda."
3035 :group 'org-agenda
3036 :type 'sexp)
3038 (defcustom org-calendar-insert-diary-entry-key [?i]
3039 "The key to be installed in `calendar-mode-map' for adding diary entries.
3040 This option is irrelevant until `org-agenda-diary-file' has been configured
3041 to point to an Org-mode file. When that is the case, the command
3042 `org-agenda-diary-entry' will be bound to the key given here, by default
3043 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3044 if you want to continue doing this, you need to change this to a different
3045 key."
3046 :group 'org-agenda
3047 :type 'sexp)
3049 (defcustom org-agenda-diary-file 'diary-file
3050 "File to which to add new entries with the `i' key in agenda and calendar.
3051 When this is the symbol `diary-file', the functionality in the Emacs
3052 calendar will be used to add entries to the `diary-file'. But when this
3053 points to a file, `org-agenda-diary-entry' will be used instead."
3054 :group 'org-agenda
3055 :type '(choice
3056 (const :tag "The standard Emacs diary file" diary-file)
3057 (file :tag "Special Org file diary entries")))
3059 (eval-after-load "calendar"
3060 '(progn
3061 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3062 'org-calendar-goto-agenda)
3063 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3064 'org-agenda-action)
3065 (add-hook 'calendar-mode-hook
3066 (lambda ()
3067 (unless (eq org-agenda-diary-file 'diary-file)
3068 (define-key calendar-mode-map
3069 org-calendar-insert-diary-entry-key
3070 'org-agenda-diary-entry))))))
3072 (defgroup org-latex nil
3073 "Options for embedding LaTeX code into Org-mode."
3074 :tag "Org LaTeX"
3075 :group 'org)
3077 (defcustom org-format-latex-options
3078 '(:foreground default :background default :scale 1.0
3079 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
3080 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3081 "Options for creating images from LaTeX fragments.
3082 This is a property list with the following properties:
3083 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3084 `default' means use the foreground of the default face.
3085 :background the background color, or \"Transparent\".
3086 `default' means use the background of the default face.
3087 :scale a scaling factor for the size of the images.
3088 :html-foreground, :html-background, :html-scale
3089 the same numbers for HTML export.
3090 :matchers a list indicating which matchers should be used to
3091 find LaTeX fragments. Valid members of this list are:
3092 \"begin\" find environments
3093 \"$1\" find single characters surrounded by $.$
3094 \"$\" find math expressions surrounded by $...$
3095 \"$$\" find math expressions surrounded by $$....$$
3096 \"\\(\" find math expressions surrounded by \\(...\\)
3097 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3098 :group 'org-latex
3099 :type 'plist)
3101 (defcustom org-format-latex-signal-error t
3102 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3103 When nil, just push out a message."
3104 :group 'org-latex
3105 :type 'boolean)
3107 (defcustom org-format-latex-header "\\documentclass{article}
3108 \\usepackage[usenames]{color}
3109 \\usepackage{amsmath}
3110 \\usepackage[mathscr]{eucal}
3111 \\pagestyle{empty} % do not remove
3112 \[PACKAGES]
3113 \[DEFAULT-PACKAGES]
3114 % The settings below are copied from fullpage.sty
3115 \\setlength{\\textwidth}{\\paperwidth}
3116 \\addtolength{\\textwidth}{-3cm}
3117 \\setlength{\\oddsidemargin}{1.5cm}
3118 \\addtolength{\\oddsidemargin}{-2.54cm}
3119 \\setlength{\\evensidemargin}{\\oddsidemargin}
3120 \\setlength{\\textheight}{\\paperheight}
3121 \\addtolength{\\textheight}{-\\headheight}
3122 \\addtolength{\\textheight}{-\\headsep}
3123 \\addtolength{\\textheight}{-\\footskip}
3124 \\addtolength{\\textheight}{-3cm}
3125 \\setlength{\\topmargin}{1.5cm}
3126 \\addtolength{\\topmargin}{-2.54cm}"
3127 "The document header used for processing LaTeX fragments.
3128 It is imperative that this header make sure that no page number
3129 appears on the page. The package defined in the variables
3130 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3131 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3132 will be appended."
3133 :group 'org-latex
3134 :type 'string)
3136 (defvar org-format-latex-header-extra nil)
3138 (defun org-set-packages-alist (var val)
3139 "Set the packages alist and make sure it has 3 elements per entry."
3140 (set var (mapcar (lambda (x)
3141 (if (and (consp x) (= (length x) 2))
3142 (list (car x) (nth 1 x) t)
3144 val)))
3146 (defun org-get-packages-alist (var)
3148 "Get the packages alist and make sure it has 3 elements per entry."
3149 (mapcar (lambda (x)
3150 (if (and (consp x) (= (length x) 2))
3151 (list (car x) (nth 1 x) t)
3153 (default-value var)))
3155 ;; The following variables are defined here because is it also used
3156 ;; when formatting latex fragments. Originally it was part of the
3157 ;; LaTeX exporter, which is why the name includes "export".
3158 (defcustom org-export-latex-default-packages-alist
3159 '(("AUTO" "inputenc" t)
3160 ("T1" "fontenc" t)
3161 ("" "fixltx2e" nil)
3162 ("" "graphicx" t)
3163 ("" "longtable" nil)
3164 ("" "float" nil)
3165 ("" "wrapfig" nil)
3166 ("" "soul" t)
3167 ("" "t1enc" t)
3168 ("" "textcomp" t)
3169 ("" "marvosym" t)
3170 ("" "wasysym" t)
3171 ("" "latexsym" t)
3172 ("" "amssymb" t)
3173 ("" "hyperref" nil)
3174 "\\tolerance=1000"
3176 "Alist of default packages to be inserted in the header.
3177 Change this only if one of the packages here causes an incompatibility
3178 with another package you are using.
3179 The packages in this list are needed by one part or another of Org-mode
3180 to function properly.
3182 - inputenc, fontenc, t1enc: for basic font and character selection
3183 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3184 for interpreting the entities in `org-entities'. You can skip some of these
3185 packages if you don't use any of the symbols in it.
3186 - graphicx: for including images
3187 - float, wrapfig: for figure placement
3188 - longtable: for long tables
3189 - hyperref: for cross references
3191 Therefore you should not modify this variable unless you know what you
3192 are doing. The one reason to change it anyway is that you might be loading
3193 some other package that conflicts with one of the default packages.
3194 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3195 If SNIPPET-FLAG is t, the package also needs to be included when
3196 compiling LaTeX snippets into images for inclusion into HTML."
3197 :group 'org-export-latex
3198 :set 'org-set-packages-alist
3199 :get 'org-get-packages-alist
3200 :type '(repeat
3201 (choice
3202 (list :tag "options/package pair"
3203 (string :tag "options")
3204 (string :tag "package")
3205 (boolean :tag "Snippet"))
3206 (string :tag "A line of LaTeX"))))
3208 (defcustom org-export-latex-packages-alist nil
3209 "Alist of packages to be inserted in every LaTeX header.
3210 These will be inserted after `org-export-latex-default-packages-alist'.
3211 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3212 SNIPPET-FLAG, when t, indicates that this package is also needed when
3213 turning LaTeX snippets into images for inclusion into HTML.
3214 Make sure that you only list packages here which:
3215 - you want in every file
3216 - do not conflict with the default packages in
3217 `org-export-latex-default-packages-alist'
3218 - do not conflict with the setup in `org-format-latex-header'."
3219 :group 'org-export-latex
3220 :set 'org-set-packages-alist
3221 :get 'org-get-packages-alist
3222 :type '(repeat
3223 (choice
3224 (list :tag "options/package pair"
3225 (string :tag "options")
3226 (string :tag "package")
3227 (boolean :tag "Snippet"))
3228 (string :tag "A line of LaTeX"))))
3231 (defgroup org-appearance nil
3232 "Settings for Org-mode appearance."
3233 :tag "Org Appearance"
3234 :group 'org)
3236 (defcustom org-level-color-stars-only nil
3237 "Non-nil means fontify only the stars in each headline.
3238 When nil, the entire headline is fontified.
3239 Changing it requires restart of `font-lock-mode' to become effective
3240 also in regions already fontified."
3241 :group 'org-appearance
3242 :type 'boolean)
3244 (defcustom org-hide-leading-stars nil
3245 "Non-nil means hide the first N-1 stars in a headline.
3246 This works by using the face `org-hide' for these stars. This
3247 face is white for a light background, and black for a dark
3248 background. You may have to customize the face `org-hide' to
3249 make this work.
3250 Changing it requires restart of `font-lock-mode' to become effective
3251 also in regions already fontified.
3252 You may also set this on a per-file basis by adding one of the following
3253 lines to the buffer:
3255 #+STARTUP: hidestars
3256 #+STARTUP: showstars"
3257 :group 'org-appearance
3258 :type 'boolean)
3260 (defcustom org-hidden-keywords nil
3261 "List of keywords that should be hidden when typed in the org buffer.
3262 For example, add #+TITLE to this list in order to make the
3263 document title appear in the buffer without the initial #+TITLE:
3264 keyword."
3265 :group 'org-appearance
3266 :type '(set (const :tag "#+AUTHOR" author)
3267 (const :tag "#+DATE" date)
3268 (const :tag "#+EMAIL" email)
3269 (const :tag "#+TITLE" title)))
3271 (defcustom org-fontify-done-headline nil
3272 "Non-nil means change the face of a headline if it is marked DONE.
3273 Normally, only the TODO/DONE keyword indicates the state of a headline.
3274 When this is non-nil, the headline after the keyword is set to the
3275 `org-headline-done' as an additional indication."
3276 :group 'org-appearance
3277 :type 'boolean)
3279 (defcustom org-fontify-emphasized-text t
3280 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3281 Changing this variable requires a restart of Emacs to take effect."
3282 :group 'org-appearance
3283 :type 'boolean)
3285 (defcustom org-fontify-whole-heading-line nil
3286 "Non-nil means fontify the whole line for headings.
3287 This is useful when setting a background color for the
3288 org-level-* faces."
3289 :group 'org-appearance
3290 :type 'boolean)
3292 (defcustom org-highlight-latex-fragments-and-specials nil
3293 "Non-nil means fontify what is treated specially by the exporters."
3294 :group 'org-appearance
3295 :type 'boolean)
3297 (defcustom org-hide-emphasis-markers nil
3298 "Non-nil mean font-lock should hide the emphasis marker characters."
3299 :group 'org-appearance
3300 :type 'boolean)
3302 (defcustom org-pretty-entities nil
3303 "Non-nil means show entities as UTF8 characters.
3304 When nil, the \\name form remains in the buffer."
3305 :group 'org-appearance
3306 :type 'boolean)
3308 (defcustom org-pretty-entities-include-sub-superscripts t
3309 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3310 :group 'org-appearance
3311 :type 'boolean)
3313 (defvar org-emph-re nil
3314 "Regular expression for matching emphasis.
3315 After a match, the match groups contain these elements:
3316 1 The character before the proper match, or empty at beginning of line
3317 2 The proper match, including the leading and trailing markers
3318 3 The leading marker like * or /, indicating the type of highlighting
3319 4 The text between the emphasis markers, not including the markers
3320 5 The character after the match, empty at the end of a line")
3321 (defvar org-verbatim-re nil
3322 "Regular expression for matching verbatim text.")
3323 (defvar org-emphasis-regexp-components) ; defined just below
3324 (defvar org-emphasis-alist) ; defined just below
3325 (defun org-set-emph-re (var val)
3326 "Set variable and compute the emphasis regular expression."
3327 (set var val)
3328 (when (and (boundp 'org-emphasis-alist)
3329 (boundp 'org-emphasis-regexp-components)
3330 org-emphasis-alist org-emphasis-regexp-components)
3331 (let* ((e org-emphasis-regexp-components)
3332 (pre (car e))
3333 (post (nth 1 e))
3334 (border (nth 2 e))
3335 (body (nth 3 e))
3336 (nl (nth 4 e))
3337 (body1 (concat body "*?"))
3338 (markers (mapconcat 'car org-emphasis-alist ""))
3339 (vmarkers (mapconcat
3340 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3341 org-emphasis-alist "")))
3342 ;; make sure special characters appear at the right position in the class
3343 (if (string-match "\\^" markers)
3344 (setq markers (concat (replace-match "" t t markers) "^")))
3345 (if (string-match "-" markers)
3346 (setq markers (concat (replace-match "" t t markers) "-")))
3347 (if (string-match "\\^" vmarkers)
3348 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3349 (if (string-match "-" vmarkers)
3350 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3351 (if (> nl 0)
3352 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3353 (int-to-string nl) "\\}")))
3354 ;; Make the regexp
3355 (setq org-emph-re
3356 (concat "\\([" pre "]\\|^\\)"
3357 "\\("
3358 "\\([" markers "]\\)"
3359 "\\("
3360 "[^" border "]\\|"
3361 "[^" border "]"
3362 body1
3363 "[^" border "]"
3364 "\\)"
3365 "\\3\\)"
3366 "\\([" post "]\\|$\\)"))
3367 (setq org-verbatim-re
3368 (concat "\\([" pre "]\\|^\\)"
3369 "\\("
3370 "\\([" vmarkers "]\\)"
3371 "\\("
3372 "[^" border "]\\|"
3373 "[^" border "]"
3374 body1
3375 "[^" border "]"
3376 "\\)"
3377 "\\3\\)"
3378 "\\([" post "]\\|$\\)")))))
3380 (defcustom org-emphasis-regexp-components
3381 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3382 "Components used to build the regular expression for emphasis.
3383 This is a list with 6 entries. Terminology: In an emphasis string
3384 like \" *strong word* \", we call the initial space PREMATCH, the final
3385 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3386 and \"trong wor\" is the body. The different components in this variable
3387 specify what is allowed/forbidden in each part:
3389 pre Chars allowed as prematch. Beginning of line will be allowed too.
3390 post Chars allowed as postmatch. End of line will be allowed too.
3391 border The chars *forbidden* as border characters.
3392 body-regexp A regexp like \".\" to match a body character. Don't use
3393 non-shy groups here, and don't allow newline here.
3394 newline The maximum number of newlines allowed in an emphasis exp.
3396 Use customize to modify this, or restart Emacs after changing it."
3397 :group 'org-appearance
3398 :set 'org-set-emph-re
3399 :type '(list
3400 (sexp :tag "Allowed chars in pre ")
3401 (sexp :tag "Allowed chars in post ")
3402 (sexp :tag "Forbidden chars in border ")
3403 (sexp :tag "Regexp for body ")
3404 (integer :tag "number of newlines allowed")
3405 (option (boolean :tag "Please ignore this button"))))
3407 (defcustom org-emphasis-alist
3408 `(("*" bold "<b>" "</b>")
3409 ("/" italic "<i>" "</i>")
3410 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3411 ("=" org-code "<code>" "</code>" verbatim)
3412 ("~" org-verbatim "<code>" "</code>" verbatim)
3413 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3414 "<del>" "</del>")
3416 "Special syntax for emphasized text.
3417 Text starting and ending with a special character will be emphasized, for
3418 example *bold*, _underlined_ and /italic/. This variable sets the marker
3419 characters, the face to be used by font-lock for highlighting in Org-mode
3420 Emacs buffers, and the HTML tags to be used for this.
3421 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3422 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3423 Use customize to modify this, or restart Emacs after changing it."
3424 :group 'org-appearance
3425 :set 'org-set-emph-re
3426 :type '(repeat
3427 (list
3428 (string :tag "Marker character")
3429 (choice
3430 (face :tag "Font-lock-face")
3431 (plist :tag "Face property list"))
3432 (string :tag "HTML start tag")
3433 (string :tag "HTML end tag")
3434 (option (const verbatim)))))
3436 (defvar org-protecting-blocks
3437 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3438 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3439 This is needed for font-lock setup.")
3441 ;;; Miscellaneous options
3443 (defgroup org-completion nil
3444 "Completion in Org-mode."
3445 :tag "Org Completion"
3446 :group 'org)
3448 (defcustom org-completion-use-ido nil
3449 "Non-nil means use ido completion wherever possible.
3450 Note that `ido-mode' must be active for this variable to be relevant.
3451 If you decide to turn this variable on, you might well want to turn off
3452 `org-outline-path-complete-in-steps'.
3453 See also `org-completion-use-iswitchb'."
3454 :group 'org-completion
3455 :type 'boolean)
3457 (defcustom org-completion-use-iswitchb nil
3458 "Non-nil means use iswitchb completion wherever possible.
3459 Note that `iswitchb-mode' must be active for this variable to be relevant.
3460 If you decide to turn this variable on, you might well want to turn off
3461 `org-outline-path-complete-in-steps'.
3462 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3463 :group 'org-completion
3464 :type 'boolean)
3466 (defcustom org-completion-fallback-command 'hippie-expand
3467 "The expansion command called by \\[org-complete] in normal context.
3468 Normal means no org-mode-specific context."
3469 :group 'org-completion
3470 :type 'function)
3472 ;;; Functions and variables from their packages
3473 ;; Declared here to avoid compiler warnings
3475 ;; XEmacs only
3476 (defvar outline-mode-menu-heading)
3477 (defvar outline-mode-menu-show)
3478 (defvar outline-mode-menu-hide)
3479 (defvar zmacs-regions) ; XEmacs regions
3481 ;; Emacs only
3482 (defvar mark-active)
3484 ;; Various packages
3485 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3486 (declare-function calendar-forward-day "cal-move" (arg))
3487 (declare-function calendar-goto-date "cal-move" (date))
3488 (declare-function calendar-goto-today "cal-move" ())
3489 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3490 (defvar calc-embedded-close-formula)
3491 (defvar calc-embedded-open-formula)
3492 (declare-function cdlatex-tab "ext:cdlatex" ())
3493 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3494 (defvar font-lock-unfontify-region-function)
3495 (declare-function iswitchb-read-buffer "iswitchb"
3496 (prompt &optional default require-match start matches-set))
3497 (defvar iswitchb-temp-buflist)
3498 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3499 (defvar org-agenda-tags-todo-honor-ignore-options)
3500 (declare-function org-agenda-skip "org-agenda" ())
3501 (declare-function
3502 org-format-agenda-item "org-agenda"
3503 (extra txt &optional category tags dotime noprefix remove-re habitp))
3504 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3505 (declare-function org-agenda-change-all-lines "org-agenda"
3506 (newhead hdmarker &optional fixface just-this))
3507 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3508 (declare-function org-agenda-maybe-redo "org-agenda" ())
3509 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3510 (beg end))
3511 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3512 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3513 "org-agenda" (&optional end))
3514 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3515 (declare-function org-indent-mode "org-indent" (&optional arg))
3516 (declare-function parse-time-string "parse-time" (string))
3517 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3518 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3519 (defvar remember-data-file)
3520 (defvar texmathp-why)
3521 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3522 (declare-function table--at-cell-p "table" (position &optional object at-column))
3524 (defvar w3m-current-url)
3525 (defvar w3m-current-title)
3527 (defvar org-latex-regexps)
3529 ;;; Autoload and prepare some org modules
3531 ;; Some table stuff that needs to be defined here, because it is used
3532 ;; by the functions setting up org-mode or checking for table context.
3534 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3535 "Detect an org-type or table-type table.")
3536 (defconst org-table-line-regexp "^[ \t]*|"
3537 "Detect an org-type table line.")
3538 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3539 "Detect an org-type table line.")
3540 (defconst org-table-hline-regexp "^[ \t]*|-"
3541 "Detect an org-type table hline.")
3542 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3543 "Detect a table-type table hline.")
3544 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3545 "Detect the first line outside a table when searching from within it.
3546 This works for both table types.")
3548 ;; Autoload the functions in org-table.el that are needed by functions here.
3550 (eval-and-compile
3551 (org-autoload "org-table"
3552 '(org-table-align org-table-begin org-table-blank-field
3553 org-table-convert org-table-convert-region org-table-copy-down
3554 org-table-copy-region org-table-create
3555 org-table-create-or-convert-from-region
3556 org-table-create-with-table.el org-table-current-dline
3557 org-table-cut-region org-table-delete-column org-table-edit-field
3558 org-table-edit-formulas org-table-end org-table-eval-formula
3559 org-table-export org-table-field-info
3560 org-table-get-stored-formulas org-table-goto-column
3561 org-table-hline-and-move org-table-import org-table-insert-column
3562 org-table-insert-hline org-table-insert-row org-table-iterate
3563 org-table-justify-field-maybe org-table-kill-row
3564 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3565 org-table-move-column org-table-move-column-left
3566 org-table-move-column-right org-table-move-row
3567 org-table-move-row-down org-table-move-row-up
3568 org-table-next-field org-table-next-row org-table-paste-rectangle
3569 org-table-previous-field org-table-recalculate
3570 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3571 org-table-toggle-coordinate-overlays
3572 org-table-toggle-formula-debugger org-table-wrap-region
3573 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3574 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3575 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3577 (defun org-at-table-p (&optional table-type)
3578 "Return t if the cursor is inside an org-type table.
3579 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3580 (if org-enable-table-editor
3581 (save-excursion
3582 (beginning-of-line 1)
3583 (looking-at (if table-type org-table-any-line-regexp
3584 org-table-line-regexp)))
3585 nil))
3586 (defsubst org-table-p () (org-at-table-p))
3588 (defun org-at-table.el-p ()
3589 "Return t if and only if we are at a table.el table."
3590 (and (org-at-table-p 'any)
3591 (save-excursion
3592 (goto-char (org-table-begin 'any))
3593 (looking-at org-table1-hline-regexp))))
3594 (defun org-table-recognize-table.el ()
3595 "If there is a table.el table nearby, recognize it and move into it."
3596 (if org-table-tab-recognizes-table.el
3597 (if (org-at-table.el-p)
3598 (progn
3599 (beginning-of-line 1)
3600 (if (looking-at org-table-dataline-regexp)
3602 (if (looking-at org-table1-hline-regexp)
3603 (progn
3604 (beginning-of-line 2)
3605 (if (looking-at org-table-any-border-regexp)
3606 (beginning-of-line -1)))))
3607 (if (re-search-forward "|" (org-table-end t) t)
3608 (progn
3609 (require 'table)
3610 (if (table--at-cell-p (point))
3612 (message "recognizing table.el table...")
3613 (table-recognize-table)
3614 (message "recognizing table.el table...done")))
3615 (error "This should not happen"))
3617 nil)
3618 nil))
3620 (defun org-at-table-hline-p ()
3621 "Return t if the cursor is inside a hline in a table."
3622 (if org-enable-table-editor
3623 (save-excursion
3624 (beginning-of-line 1)
3625 (looking-at org-table-hline-regexp))
3626 nil))
3628 (defvar org-table-clean-did-remove-column nil)
3630 (defun org-table-map-tables (function &optional quietly)
3631 "Apply FUNCTION to the start of all tables in the buffer."
3632 (save-excursion
3633 (save-restriction
3634 (widen)
3635 (goto-char (point-min))
3636 (while (re-search-forward org-table-any-line-regexp nil t)
3637 (unless quietly
3638 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3639 (beginning-of-line 1)
3640 (when (looking-at org-table-line-regexp)
3641 (save-excursion (funcall function))
3642 (or (looking-at org-table-line-regexp)
3643 (forward-char 1)))
3644 (re-search-forward org-table-any-border-regexp nil 1))))
3645 (unless quietly (message "Mapping tables: done")))
3647 ;; Declare and autoload functions from org-exp.el & Co
3649 (declare-function org-default-export-plist "org-exp")
3650 (declare-function org-infile-export-plist "org-exp")
3651 (declare-function org-get-current-options "org-exp")
3652 (eval-and-compile
3653 (org-autoload "org-exp"
3654 '(org-export org-export-visible
3655 org-insert-export-options-template
3656 org-table-clean-before-export))
3657 (org-autoload "org-ascii"
3658 '(org-export-as-ascii org-export-ascii-preprocess
3659 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3660 org-export-region-as-ascii))
3661 (org-autoload "org-latex"
3662 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3663 org-replace-region-by-latex org-export-region-as-latex
3664 org-export-as-latex org-export-as-pdf
3665 org-export-as-pdf-and-open))
3666 (org-autoload "org-html"
3667 '(org-export-as-html-and-open
3668 org-export-as-html-batch org-export-as-html-to-buffer
3669 org-replace-region-by-html org-export-region-as-html
3670 org-export-as-html))
3671 (org-autoload "org-docbook"
3672 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3673 org-replace-region-by-docbook org-export-region-as-docbook
3674 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3675 org-export-as-docbook))
3676 (org-autoload "org-icalendar"
3677 '(org-export-icalendar-this-file
3678 org-export-icalendar-all-agenda-files
3679 org-export-icalendar-combine-agenda-files))
3680 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3681 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3683 ;; Declare and autoload functions from org-agenda.el
3685 (eval-and-compile
3686 (org-autoload "org-agenda"
3687 '(org-agenda org-agenda-list org-search-view
3688 org-todo-list org-tags-view org-agenda-list-stuck-projects
3689 org-diary org-agenda-to-appt
3690 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3692 ;; Autoload org-remember
3694 (eval-and-compile
3695 (org-autoload "org-remember"
3696 '(org-remember-insinuate org-remember-annotation
3697 org-remember-apply-template org-remember org-remember-handler)))
3699 (eval-and-compile
3700 (org-autoload "org-capture"
3701 '(org-capture org-capture-insert-template-here
3702 org-capture-import-remember-templates)))
3704 ;; Autoload org-clock.el
3707 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3708 (beg end))
3709 (declare-function org-clock-update-mode-line "org-clock" ())
3710 (declare-function org-resolve-clocks "org-clock"
3711 (&optional also-non-dangling-p prompt last-valid))
3712 (defvar org-clock-start-time)
3713 (defvar org-clock-marker (make-marker)
3714 "Marker recording the last clock-in.")
3715 (defvar org-clock-hd-marker (make-marker)
3716 "Marker recording the last clock-in, but the headline position.")
3717 (defvar org-clock-heading ""
3718 "The heading of the current clock entry.")
3719 (defun org-clock-is-active ()
3720 "Return non-nil if clock is currently running.
3721 The return value is actually the clock marker."
3722 (marker-buffer org-clock-marker))
3724 (eval-and-compile
3725 (org-autoload
3726 "org-clock"
3727 '(org-clock-in org-clock-out org-clock-cancel
3728 org-clock-goto org-clock-sum org-clock-display
3729 org-clock-remove-overlays org-clock-report
3730 org-clocktable-shift org-dblock-write:clocktable
3731 org-get-clocktable org-resolve-clocks)))
3733 (defun org-clock-update-time-maybe ()
3734 "If this is a CLOCK line, update it and return t.
3735 Otherwise, return nil."
3736 (interactive)
3737 (save-excursion
3738 (beginning-of-line 1)
3739 (skip-chars-forward " \t")
3740 (when (looking-at org-clock-string)
3741 (let ((re (concat "[ \t]*" org-clock-string
3742 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3743 "\\([ \t]*=>.*\\)?\\)?"))
3744 ts te h m s neg)
3745 (cond
3746 ((not (looking-at re))
3747 nil)
3748 ((not (match-end 2))
3749 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3750 (> org-clock-marker (point))
3751 (<= org-clock-marker (point-at-eol)))
3752 ;; The clock is running here
3753 (setq org-clock-start-time
3754 (apply 'encode-time
3755 (org-parse-time-string (match-string 1))))
3756 (org-clock-update-mode-line)))
3758 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3759 (end-of-line 1)
3760 (setq ts (match-string 1)
3761 te (match-string 3))
3762 (setq s (- (org-float-time
3763 (apply 'encode-time (org-parse-time-string te)))
3764 (org-float-time
3765 (apply 'encode-time (org-parse-time-string ts))))
3766 neg (< s 0)
3767 s (abs s)
3768 h (floor (/ s 3600))
3769 s (- s (* 3600 h))
3770 m (floor (/ s 60))
3771 s (- s (* 60 s)))
3772 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3773 t))))))
3775 (defun org-check-running-clock ()
3776 "Check if the current buffer contains the running clock.
3777 If yes, offer to stop it and to save the buffer with the changes."
3778 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3779 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3780 (buffer-name))))
3781 (org-clock-out)
3782 (when (y-or-n-p "Save changed buffer?")
3783 (save-buffer))))
3785 (defun org-clocktable-try-shift (dir n)
3786 "Check if this line starts a clock table, if yes, shift the time block."
3787 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3788 (org-clocktable-shift dir n)))
3790 ;; Autoload org-timer.el
3792 (eval-and-compile
3793 (org-autoload
3794 "org-timer"
3795 '(org-timer-start org-timer org-timer-item
3796 org-timer-change-times-in-region
3797 org-timer-set-timer
3798 org-timer-reset-timers
3799 org-timer-show-remaining-time)))
3801 ;; Autoload org-feed.el
3803 (eval-and-compile
3804 (org-autoload
3805 "org-feed"
3806 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3809 ;; Autoload org-indent.el
3811 ;; Define the variable already here, to make sure we have it.
3812 (defvar org-indent-mode nil
3813 "Non-nil if Org-Indent mode is enabled.
3814 Use the command `org-indent-mode' to change this variable.")
3816 (eval-and-compile
3817 (org-autoload
3818 "org-indent"
3819 '(org-indent-mode)))
3821 ;; Autoload org-mobile.el
3823 (eval-and-compile
3824 (org-autoload
3825 "org-mobile"
3826 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
3828 ;; Autoload archiving code
3829 ;; The stuff that is needed for cycling and tags has to be defined here.
3831 (defgroup org-archive nil
3832 "Options concerning archiving in Org-mode."
3833 :tag "Org Archive"
3834 :group 'org-structure)
3836 (defcustom org-archive-location "%s_archive::"
3837 "The location where subtrees should be archived.
3839 The value of this variable is a string, consisting of two parts,
3840 separated by a double-colon. The first part is a filename and
3841 the second part is a headline.
3843 When the filename is omitted, archiving happens in the same file.
3844 %s in the filename will be replaced by the current file
3845 name (without the directory part). Archiving to a different file
3846 is useful to keep archived entries from contributing to the
3847 Org-mode Agenda.
3849 The archived entries will be filed as subtrees of the specified
3850 headline. When the headline is omitted, the subtrees are simply
3851 filed away at the end of the file, as top-level entries. Also in
3852 the heading you can use %s to represent the file name, this can be
3853 useful when using the same archive for a number of different files.
3855 Here are a few examples:
3856 \"%s_archive::\"
3857 If the current file is Projects.org, archive in file
3858 Projects.org_archive, as top-level trees. This is the default.
3860 \"::* Archived Tasks\"
3861 Archive in the current file, under the top-level headline
3862 \"* Archived Tasks\".
3864 \"~/org/archive.org::\"
3865 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3867 \"~/org/archive.org::From %s\"
3868 Archive in file ~/org/archive.org (absolute path), under headlines
3869 \"From FILENAME\" where file name is the current file name.
3871 \"basement::** Finished Tasks\"
3872 Archive in file ./basement (relative path), as level 3 trees
3873 below the level 2 heading \"** Finished Tasks\".
3875 You may set this option on a per-file basis by adding to the buffer a
3876 line like
3878 #+ARCHIVE: basement::** Finished Tasks
3880 You may also define it locally for a subtree by setting an ARCHIVE property
3881 in the entry. If such a property is found in an entry, or anywhere up
3882 the hierarchy, it will be used."
3883 :group 'org-archive
3884 :type 'string)
3886 (defcustom org-archive-tag "ARCHIVE"
3887 "The tag that marks a subtree as archived.
3888 An archived subtree does not open during visibility cycling, and does
3889 not contribute to the agenda listings.
3890 After changing this, font-lock must be restarted in the relevant buffers to
3891 get the proper fontification."
3892 :group 'org-archive
3893 :group 'org-keywords
3894 :type 'string)
3896 (defcustom org-agenda-skip-archived-trees t
3897 "Non-nil means the agenda will skip any items located in archived trees.
3898 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3899 variable is no longer recommended, you should leave it at the value t.
3900 Instead, use the key `v' to cycle the archives-mode in the agenda."
3901 :group 'org-archive
3902 :group 'org-agenda-skip
3903 :type 'boolean)
3905 (defcustom org-columns-skip-archived-trees t
3906 "Non-nil means ignore archived trees when creating column view."
3907 :group 'org-archive
3908 :group 'org-properties
3909 :type 'boolean)
3911 (defcustom org-cycle-open-archived-trees nil
3912 "Non-nil means `org-cycle' will open archived trees.
3913 An archived tree is a tree marked with the tag ARCHIVE.
3914 When nil, archived trees will stay folded. You can still open them with
3915 normal outline commands like `show-all', but not with the cycling commands."
3916 :group 'org-archive
3917 :group 'org-cycle
3918 :type 'boolean)
3920 (defcustom org-sparse-tree-open-archived-trees nil
3921 "Non-nil means sparse tree construction shows matches in archived trees.
3922 When nil, matches in these trees are highlighted, but the trees are kept in
3923 collapsed state."
3924 :group 'org-archive
3925 :group 'org-sparse-trees
3926 :type 'boolean)
3928 (defun org-cycle-hide-archived-subtrees (state)
3929 "Re-hide all archived subtrees after a visibility state change."
3930 (when (and (not org-cycle-open-archived-trees)
3931 (not (memq state '(overview folded))))
3932 (save-excursion
3933 (let* ((globalp (memq state '(contents all)))
3934 (beg (if globalp (point-min) (point)))
3935 (end (if globalp (point-max) (org-end-of-subtree t))))
3936 (org-hide-archived-subtrees beg end)
3937 (goto-char beg)
3938 (if (looking-at (concat ".*:" org-archive-tag ":"))
3939 (message "%s" (substitute-command-keys
3940 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3942 (defun org-force-cycle-archived ()
3943 "Cycle subtree even if it is archived."
3944 (interactive)
3945 (setq this-command 'org-cycle)
3946 (let ((org-cycle-open-archived-trees t))
3947 (call-interactively 'org-cycle)))
3949 (defun org-hide-archived-subtrees (beg end)
3950 "Re-hide all archived subtrees after a visibility state change."
3951 (save-excursion
3952 (let* ((re (concat ":" org-archive-tag ":")))
3953 (goto-char beg)
3954 (while (re-search-forward re end t)
3955 (when (org-on-heading-p)
3956 (org-flag-subtree t)
3957 (org-end-of-subtree t))))))
3959 (defun org-flag-subtree (flag)
3960 (save-excursion
3961 (org-back-to-heading t)
3962 (outline-end-of-heading)
3963 (outline-flag-region (point)
3964 (progn (org-end-of-subtree t) (point))
3965 flag)))
3967 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3969 (eval-and-compile
3970 (org-autoload "org-archive"
3971 '(org-add-archive-files org-archive-subtree
3972 org-archive-to-archive-sibling org-toggle-archive-tag
3973 org-archive-subtree-default
3974 org-archive-subtree-default-with-confirmation)))
3976 ;; Autoload Column View Code
3978 (declare-function org-columns-number-to-string "org-colview")
3979 (declare-function org-columns-get-format-and-top-level "org-colview")
3980 (declare-function org-columns-compute "org-colview")
3982 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3983 '(org-columns-number-to-string org-columns-get-format-and-top-level
3984 org-columns-compute org-agenda-columns org-columns-remove-overlays
3985 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3987 ;; Autoload ID code
3989 (declare-function org-id-store-link "org-id")
3990 (declare-function org-id-locations-load "org-id")
3991 (declare-function org-id-locations-save "org-id")
3992 (defvar org-id-track-globally)
3993 (org-autoload "org-id"
3994 '(org-id-get-create org-id-new org-id-copy org-id-get
3995 org-id-get-with-outline-path-completion
3996 org-id-get-with-outline-drilling org-id-store-link
3997 org-id-goto org-id-find org-id-store-link))
3999 ;; Autoload Plotting Code
4001 (org-autoload "org-plot"
4002 '(org-plot/gnuplot))
4004 ;;; Variables for pre-computed regular expressions, all buffer local
4006 (defvar org-drawer-regexp nil
4007 "Matches first line of a hidden block.")
4008 (make-variable-buffer-local 'org-drawer-regexp)
4009 (defvar org-todo-regexp nil
4010 "Matches any of the TODO state keywords.")
4011 (make-variable-buffer-local 'org-todo-regexp)
4012 (defvar org-not-done-regexp nil
4013 "Matches any of the TODO state keywords except the last one.")
4014 (make-variable-buffer-local 'org-not-done-regexp)
4015 (defvar org-not-done-heading-regexp nil
4016 "Matches a TODO headline that is not done.")
4017 (make-variable-buffer-local 'org-not-done-regexp)
4018 (defvar org-todo-line-regexp nil
4019 "Matches a headline and puts TODO state into group 2 if present.")
4020 (make-variable-buffer-local 'org-todo-line-regexp)
4021 (defvar org-complex-heading-regexp nil
4022 "Matches a headline and puts everything into groups:
4023 group 1: the stars
4024 group 2: The todo keyword, maybe
4025 group 3: Priority cookie
4026 group 4: True headline
4027 group 5: Tags")
4028 (make-variable-buffer-local 'org-complex-heading-regexp)
4029 (defvar org-complex-heading-regexp-format nil)
4030 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4031 (defvar org-todo-line-tags-regexp nil
4032 "Matches a headline and puts TODO state into group 2 if present.
4033 Also put tags into group 4 if tags are present.")
4034 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4035 (defvar org-nl-done-regexp nil
4036 "Matches newline followed by a headline with the DONE keyword.")
4037 (make-variable-buffer-local 'org-nl-done-regexp)
4038 (defvar org-looking-at-done-regexp nil
4039 "Matches the DONE keyword a point.")
4040 (make-variable-buffer-local 'org-looking-at-done-regexp)
4041 (defvar org-ds-keyword-length 12
4042 "Maximum length of the Deadline and SCHEDULED keywords.")
4043 (make-variable-buffer-local 'org-ds-keyword-length)
4044 (defvar org-deadline-regexp nil
4045 "Matches the DEADLINE keyword.")
4046 (make-variable-buffer-local 'org-deadline-regexp)
4047 (defvar org-deadline-time-regexp nil
4048 "Matches the DEADLINE keyword together with a time stamp.")
4049 (make-variable-buffer-local 'org-deadline-time-regexp)
4050 (defvar org-deadline-line-regexp nil
4051 "Matches the DEADLINE keyword and the rest of the line.")
4052 (make-variable-buffer-local 'org-deadline-line-regexp)
4053 (defvar org-scheduled-regexp nil
4054 "Matches the SCHEDULED keyword.")
4055 (make-variable-buffer-local 'org-scheduled-regexp)
4056 (defvar org-scheduled-time-regexp nil
4057 "Matches the SCHEDULED keyword together with a time stamp.")
4058 (make-variable-buffer-local 'org-scheduled-time-regexp)
4059 (defvar org-closed-time-regexp nil
4060 "Matches the CLOSED keyword together with a time stamp.")
4061 (make-variable-buffer-local 'org-closed-time-regexp)
4063 (defvar org-keyword-time-regexp nil
4064 "Matches any of the 4 keywords, together with the time stamp.")
4065 (make-variable-buffer-local 'org-keyword-time-regexp)
4066 (defvar org-keyword-time-not-clock-regexp nil
4067 "Matches any of the 3 keywords, together with the time stamp.")
4068 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4069 (defvar org-maybe-keyword-time-regexp nil
4070 "Matches a timestamp, possibly preceded by a keyword.")
4071 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4072 (defvar org-planning-or-clock-line-re nil
4073 "Matches a line with planning or clock info.")
4074 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4075 (defvar org-all-time-keywords nil
4076 "List of time keywords.")
4077 (make-variable-buffer-local 'org-all-time-keywords)
4079 (defconst org-plain-time-of-day-regexp
4080 (concat
4081 "\\(\\<[012]?[0-9]"
4082 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4083 "\\(--?"
4084 "\\(\\<[012]?[0-9]"
4085 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4086 "\\)?")
4087 "Regular expression to match a plain time or time range.
4088 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4089 groups carry important information:
4090 0 the full match
4091 1 the first time, range or not
4092 8 the second time, if it is a range.")
4094 (defconst org-plain-time-extension-regexp
4095 (concat
4096 "\\(\\<[012]?[0-9]"
4097 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4098 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4099 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4100 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4101 groups carry important information:
4102 0 the full match
4103 7 hours of duration
4104 9 minutes of duration")
4106 (defconst org-stamp-time-of-day-regexp
4107 (concat
4108 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4109 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4110 "\\(--?"
4111 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4112 "Regular expression to match a timestamp time or time range.
4113 After a match, the following groups carry important information:
4114 0 the full match
4115 1 date plus weekday, for back referencing to make sure both times are on the same day
4116 2 the first time, range or not
4117 4 the second time, if it is a range.")
4119 (defconst org-startup-options
4120 '(("fold" org-startup-folded t)
4121 ("overview" org-startup-folded t)
4122 ("nofold" org-startup-folded nil)
4123 ("showall" org-startup-folded nil)
4124 ("showeverything" org-startup-folded showeverything)
4125 ("content" org-startup-folded content)
4126 ("indent" org-startup-indented t)
4127 ("noindent" org-startup-indented nil)
4128 ("hidestars" org-hide-leading-stars t)
4129 ("showstars" org-hide-leading-stars nil)
4130 ("odd" org-odd-levels-only t)
4131 ("oddeven" org-odd-levels-only nil)
4132 ("align" org-startup-align-all-tables t)
4133 ("noalign" org-startup-align-all-tables nil)
4134 ("customtime" org-display-custom-times t)
4135 ("logdone" org-log-done time)
4136 ("lognotedone" org-log-done note)
4137 ("nologdone" org-log-done nil)
4138 ("lognoteclock-out" org-log-note-clock-out t)
4139 ("nolognoteclock-out" org-log-note-clock-out nil)
4140 ("logrepeat" org-log-repeat state)
4141 ("lognoterepeat" org-log-repeat note)
4142 ("nologrepeat" org-log-repeat nil)
4143 ("logreschedule" org-log-reschedule time)
4144 ("lognotereschedule" org-log-reschedule note)
4145 ("nologreschedule" org-log-reschedule nil)
4146 ("logredeadline" org-log-redeadline time)
4147 ("lognoteredeadline" org-log-redeadline note)
4148 ("nologredeadline" org-log-redeadline nil)
4149 ("logrefile" org-log-refile time)
4150 ("lognoterefile" org-log-refile note)
4151 ("nologrefile" org-log-refile nil)
4152 ("fninline" org-footnote-define-inline t)
4153 ("nofninline" org-footnote-define-inline nil)
4154 ("fnlocal" org-footnote-section nil)
4155 ("fnauto" org-footnote-auto-label t)
4156 ("fnprompt" org-footnote-auto-label nil)
4157 ("fnconfirm" org-footnote-auto-label confirm)
4158 ("fnplain" org-footnote-auto-label plain)
4159 ("fnadjust" org-footnote-auto-adjust t)
4160 ("nofnadjust" org-footnote-auto-adjust nil)
4161 ("constcgs" constants-unit-system cgs)
4162 ("constSI" constants-unit-system SI)
4163 ("noptag" org-tag-persistent-alist nil)
4164 ("hideblocks" org-hide-block-startup t)
4165 ("nohideblocks" org-hide-block-startup nil)
4166 ("beamer" org-startup-with-beamer-mode t)
4167 ("entitiespretty" org-pretty-entities t)
4168 ("entitiesplain" org-pretty-entities nil))
4169 "Variable associated with STARTUP options for org-mode.
4170 Each element is a list of three items: The startup options as written
4171 in the #+STARTUP line, the corresponding variable, and the value to
4172 set this variable to if the option is found. An optional forth element PUSH
4173 means to push this value onto the list in the variable.")
4175 (defun org-set-regexps-and-options ()
4176 "Precompute regular expressions for current buffer."
4177 (when (org-mode-p)
4178 (org-set-local 'org-todo-kwd-alist nil)
4179 (org-set-local 'org-todo-key-alist nil)
4180 (org-set-local 'org-todo-key-trigger nil)
4181 (org-set-local 'org-todo-keywords-1 nil)
4182 (org-set-local 'org-done-keywords nil)
4183 (org-set-local 'org-todo-heads nil)
4184 (org-set-local 'org-todo-sets nil)
4185 (org-set-local 'org-todo-log-states nil)
4186 (org-set-local 'org-file-properties nil)
4187 (org-set-local 'org-file-tags nil)
4188 (let ((re (org-make-options-regexp
4189 '("CATEGORY" "TODO" "COLUMNS"
4190 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4191 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4192 "OPTIONS")
4193 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4194 (splitre "[ \t]+")
4195 (scripts org-use-sub-superscripts)
4196 kwds kws0 kwsa key log value cat arch tags const links hw dws
4197 tail sep kws1 prio props ftags drawers beamer-p
4198 ext-setup-or-nil setup-contents (start 0))
4199 (save-excursion
4200 (save-restriction
4201 (widen)
4202 (goto-char (point-min))
4203 (while (or (and ext-setup-or-nil
4204 (string-match re ext-setup-or-nil start)
4205 (setq start (match-end 0)))
4206 (and (setq ext-setup-or-nil nil start 0)
4207 (re-search-forward re nil t)))
4208 (setq key (upcase (match-string 1 ext-setup-or-nil))
4209 value (org-match-string-no-properties 2 ext-setup-or-nil))
4210 (if (stringp value) (setq value (org-trim value)))
4211 (cond
4212 ((equal key "CATEGORY")
4213 (setq cat value))
4214 ((member key '("SEQ_TODO" "TODO"))
4215 (push (cons 'sequence (org-split-string value splitre)) kwds))
4216 ((equal key "TYP_TODO")
4217 (push (cons 'type (org-split-string value splitre)) kwds))
4218 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4219 ;; general TODO-like setup
4220 (push (cons (intern (downcase (match-string 1 key)))
4221 (org-split-string value splitre)) kwds))
4222 ((equal key "TAGS")
4223 (setq tags (append tags (if tags '("\\n") nil)
4224 (org-split-string value splitre))))
4225 ((equal key "COLUMNS")
4226 (org-set-local 'org-columns-default-format value))
4227 ((equal key "LINK")
4228 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4229 (push (cons (match-string 1 value)
4230 (org-trim (match-string 2 value)))
4231 links)))
4232 ((equal key "PRIORITIES")
4233 (setq prio (org-split-string value " +")))
4234 ((equal key "PROPERTY")
4235 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4236 (push (cons (match-string 1 value) (match-string 2 value))
4237 props)))
4238 ((equal key "FILETAGS")
4239 (when (string-match "\\S-" value)
4240 (setq ftags
4241 (append
4242 ftags
4243 (apply 'append
4244 (mapcar (lambda (x) (org-split-string x ":"))
4245 (org-split-string value)))))))
4246 ((equal key "DRAWERS")
4247 (setq drawers (org-split-string value splitre)))
4248 ((equal key "CONSTANTS")
4249 (setq const (append const (org-split-string value splitre))))
4250 ((equal key "STARTUP")
4251 (let ((opts (org-split-string value splitre))
4252 l var val)
4253 (while (setq l (pop opts))
4254 (when (setq l (assoc l org-startup-options))
4255 (setq var (nth 1 l) val (nth 2 l))
4256 (if (not (nth 3 l))
4257 (set (make-local-variable var) val)
4258 (if (not (listp (symbol-value var)))
4259 (set (make-local-variable var) nil))
4260 (set (make-local-variable var) (symbol-value var))
4261 (add-to-list var val))))))
4262 ((equal key "ARCHIVE")
4263 (setq arch value)
4264 (remove-text-properties 0 (length arch)
4265 '(face t fontified t) arch))
4266 ((equal key "LATEX_CLASS")
4267 (setq beamer-p (equal value "beamer")))
4268 ((equal key "OPTIONS")
4269 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4270 (setq scripts (read (match-string 2 value)))))
4271 ((equal key "SETUPFILE")
4272 (setq setup-contents (org-file-contents
4273 (expand-file-name
4274 (org-remove-double-quotes value))
4275 'noerror))
4276 (if (not ext-setup-or-nil)
4277 (setq ext-setup-or-nil setup-contents start 0)
4278 (setq ext-setup-or-nil
4279 (concat (substring ext-setup-or-nil 0 start)
4280 "\n" setup-contents "\n"
4281 (substring ext-setup-or-nil start)))))
4282 ))))
4283 (org-set-local 'org-use-sub-superscripts scripts)
4284 (when cat
4285 (org-set-local 'org-category (intern cat))
4286 (push (cons "CATEGORY" cat) props))
4287 (when prio
4288 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4289 (setq prio (mapcar 'string-to-char prio))
4290 (org-set-local 'org-highest-priority (nth 0 prio))
4291 (org-set-local 'org-lowest-priority (nth 1 prio))
4292 (org-set-local 'org-default-priority (nth 2 prio)))
4293 (and props (org-set-local 'org-file-properties (nreverse props)))
4294 (and ftags (org-set-local 'org-file-tags
4295 (mapcar 'org-add-prop-inherited ftags)))
4296 (and drawers (org-set-local 'org-drawers drawers))
4297 (and arch (org-set-local 'org-archive-location arch))
4298 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4299 ;; Process the TODO keywords
4300 (unless kwds
4301 ;; Use the global values as if they had been given locally.
4302 (setq kwds (default-value 'org-todo-keywords))
4303 (if (stringp (car kwds))
4304 (setq kwds (list (cons org-todo-interpretation
4305 (default-value 'org-todo-keywords)))))
4306 (setq kwds (reverse kwds)))
4307 (setq kwds (nreverse kwds))
4308 (let (inter kws kw)
4309 (while (setq kws (pop kwds))
4310 (let ((kws (or
4311 (run-hook-with-args-until-success
4312 'org-todo-setup-filter-hook kws)
4313 kws)))
4314 (setq inter (pop kws) sep (member "|" kws)
4315 kws0 (delete "|" (copy-sequence kws))
4316 kwsa nil
4317 kws1 (mapcar
4318 (lambda (x)
4319 ;; 1 2
4320 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4321 (progn
4322 (setq kw (match-string 1 x)
4323 key (and (match-end 2) (match-string 2 x))
4324 log (org-extract-log-state-settings x))
4325 (push (cons kw (and key (string-to-char key))) kwsa)
4326 (and log (push log org-todo-log-states))
4328 (error "Invalid TODO keyword %s" x)))
4329 kws0)
4330 kwsa (if kwsa (append '((:startgroup))
4331 (nreverse kwsa)
4332 '((:endgroup))))
4333 hw (car kws1)
4334 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4335 tail (list inter hw (car dws) (org-last dws))))
4336 (add-to-list 'org-todo-heads hw 'append)
4337 (push kws1 org-todo-sets)
4338 (setq org-done-keywords (append org-done-keywords dws nil))
4339 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4340 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4341 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4342 (setq org-todo-sets (nreverse org-todo-sets)
4343 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4344 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4345 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4346 ;; Process the constants
4347 (when const
4348 (let (e cst)
4349 (while (setq e (pop const))
4350 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4351 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4352 (setq org-table-formula-constants-local cst)))
4354 ;; Process the tags.
4355 (when tags
4356 (let (e tgs)
4357 (while (setq e (pop tags))
4358 (cond
4359 ((equal e "{") (push '(:startgroup) tgs))
4360 ((equal e "}") (push '(:endgroup) tgs))
4361 ((equal e "\\n") (push '(:newline) tgs))
4362 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4363 (push (cons (match-string 1 e)
4364 (string-to-char (match-string 2 e)))
4365 tgs))
4366 (t (push (list e) tgs))))
4367 (org-set-local 'org-tag-alist nil)
4368 (while (setq e (pop tgs))
4369 (or (and (stringp (car e))
4370 (assoc (car e) org-tag-alist))
4371 (push e org-tag-alist)))))
4373 ;; Compute the regular expressions and other local variables
4374 (if (not org-done-keywords)
4375 (setq org-done-keywords (and org-todo-keywords-1
4376 (list (org-last org-todo-keywords-1)))))
4377 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4378 (length org-scheduled-string)
4379 (length org-clock-string)
4380 (length org-closed-string)))
4381 org-drawer-regexp
4382 (concat "^[ \t]*:\\("
4383 (mapconcat 'regexp-quote org-drawers "\\|")
4384 "\\):[ \t]*$")
4385 org-not-done-keywords
4386 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4387 org-todo-regexp
4388 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4389 "\\|") "\\)\\>")
4390 org-not-done-regexp
4391 (concat "\\<\\("
4392 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4393 "\\)\\>")
4394 org-not-done-heading-regexp
4395 (concat "^\\(\\*+\\)[ \t]+\\("
4396 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4397 "\\)\\>")
4398 org-todo-line-regexp
4399 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4400 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4401 "\\)\\>\\)?[ \t]*\\(.*\\)")
4402 org-complex-heading-regexp
4403 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4404 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4405 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4406 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4407 org-complex-heading-regexp-format
4408 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4409 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4410 "\\)\\>\\)?"
4411 "\\(?:[ \t]*\\(\\[#.\\]\\)\\)?"
4412 "\\(?:[ \t]*\\(?:\\[[0-9%%/]+\\]\\)\\)?" ;; stats cookie
4413 "[ \t]*\\(%s\\)"
4414 "\\(?:[ \t]*\\(?:\\[[0-9%%/]+\\]\\)\\)?" ;; stats cookie
4415 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4416 org-nl-done-regexp
4417 (concat "\n\\*+[ \t]+"
4418 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4419 "\\)" "\\>")
4420 org-todo-line-tags-regexp
4421 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4422 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4423 (org-re
4424 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4425 org-looking-at-done-regexp
4426 (concat "^" "\\(?:"
4427 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4428 "\\>")
4429 org-deadline-regexp (concat "\\<" org-deadline-string)
4430 org-deadline-time-regexp
4431 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4432 org-deadline-line-regexp
4433 (concat "\\<\\(" org-deadline-string "\\).*")
4434 org-scheduled-regexp
4435 (concat "\\<" org-scheduled-string)
4436 org-scheduled-time-regexp
4437 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4438 org-closed-time-regexp
4439 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4440 org-keyword-time-regexp
4441 (concat "\\<\\(" org-scheduled-string
4442 "\\|" org-deadline-string
4443 "\\|" org-closed-string
4444 "\\|" org-clock-string "\\)"
4445 " *[[<]\\([^]>]+\\)[]>]")
4446 org-keyword-time-not-clock-regexp
4447 (concat "\\<\\(" org-scheduled-string
4448 "\\|" org-deadline-string
4449 "\\|" org-closed-string
4450 "\\)"
4451 " *[[<]\\([^]>]+\\)[]>]")
4452 org-maybe-keyword-time-regexp
4453 (concat "\\(\\<\\(" org-scheduled-string
4454 "\\|" org-deadline-string
4455 "\\|" org-closed-string
4456 "\\|" org-clock-string "\\)\\)?"
4457 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4458 org-planning-or-clock-line-re
4459 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4460 "\\|" org-deadline-string
4461 "\\|" org-closed-string "\\|" org-clock-string
4462 "\\)\\>\\)")
4463 org-all-time-keywords
4464 (mapcar (lambda (w) (substring w 0 -1))
4465 (list org-scheduled-string org-deadline-string
4466 org-clock-string org-closed-string))
4468 (org-compute-latex-and-specials-regexp)
4469 (org-set-font-lock-defaults))))
4471 (defun org-file-contents (file &optional noerror)
4472 "Return the contents of FILE, as a string."
4473 (if (or (not file)
4474 (not (file-readable-p file)))
4475 (if noerror
4476 (progn
4477 (message "Cannot read file \"%s\"" file)
4478 (ding) (sit-for 2)
4480 (error "Cannot read file \"%s\"" file))
4481 (with-temp-buffer
4482 (insert-file-contents file)
4483 (buffer-string))))
4485 (defun org-extract-log-state-settings (x)
4486 "Extract the log state setting from a TODO keyword string.
4487 This will extract info from a string like \"WAIT(w@/!)\"."
4488 (let (kw key log1 log2)
4489 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4490 (setq kw (match-string 1 x)
4491 key (and (match-end 2) (match-string 2 x))
4492 log1 (and (match-end 3) (match-string 3 x))
4493 log2 (and (match-end 4) (match-string 4 x)))
4494 (and (or log1 log2)
4495 (list kw
4496 (and log1 (if (equal log1 "!") 'time 'note))
4497 (and log2 (if (equal log2 "!") 'time 'note)))))))
4499 (defun org-remove-keyword-keys (list)
4500 "Remove a pair of parenthesis at the end of each string in LIST."
4501 (mapcar (lambda (x)
4502 (if (string-match "(.*)$" x)
4503 (substring x 0 (match-beginning 0))
4505 list))
4507 (defun org-assign-fast-keys (alist)
4508 "Assign fast keys to a keyword-key alist.
4509 Respect keys that are already there."
4510 (let (new e (alt ?0))
4511 (while (setq e (pop alist))
4512 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4513 (cdr e)) ;; Key already assigned.
4514 (push e new)
4515 (let ((clist (string-to-list (downcase (car e))))
4516 (used (append new alist)))
4517 (when (= (car clist) ?@)
4518 (pop clist))
4519 (while (and clist (rassoc (car clist) used))
4520 (pop clist))
4521 (unless clist
4522 (while (rassoc alt used)
4523 (incf alt)))
4524 (push (cons (car e) (or (car clist) alt)) new))))
4525 (nreverse new)))
4527 ;;; Some variables used in various places
4529 (defvar org-window-configuration nil
4530 "Used in various places to store a window configuration.")
4531 (defvar org-selected-window nil
4532 "Used in various places to store a window configuration.")
4533 (defvar org-finish-function nil
4534 "Function to be called when `C-c C-c' is used.
4535 This is for getting out of special buffers like remember.")
4538 ;; FIXME: Occasionally check by commenting these, to make sure
4539 ;; no other functions uses these, forgetting to let-bind them.
4540 (defvar entry)
4541 (defvar last-state)
4542 (defvar date)
4544 ;; Defined somewhere in this file, but used before definition.
4545 (defvar org-entities) ;; defined in org-entities.el
4546 (defvar org-struct-menu)
4547 (defvar org-org-menu)
4548 (defvar org-tbl-menu)
4550 ;;;; Define the Org-mode
4552 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4553 (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"))
4556 ;; We use a before-change function to check if a table might need
4557 ;; an update.
4558 (defvar org-table-may-need-update t
4559 "Indicates that a table might need an update.
4560 This variable is set by `org-before-change-function'.
4561 `org-table-align' sets it back to nil.")
4562 (defun org-before-change-function (beg end)
4563 "Every change indicates that a table might need an update."
4564 (setq org-table-may-need-update t))
4565 (defvar org-mode-map)
4566 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4567 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4568 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4569 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4570 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4571 (defvar org-table-buffer-is-an nil)
4572 (defconst org-outline-regexp "\\*+ ")
4574 ;;;###autoload
4575 (define-derived-mode org-mode outline-mode "Org"
4576 "Outline-based notes management and organizer, alias
4577 \"Carsten's outline-mode for keeping track of everything.\"
4579 Org-mode develops organizational tasks around a NOTES file which
4580 contains information about projects as plain text. Org-mode is
4581 implemented on top of outline-mode, which is ideal to keep the content
4582 of large files well structured. It supports ToDo items, deadlines and
4583 time stamps, which magically appear in the diary listing of the Emacs
4584 calendar. Tables are easily created with a built-in table editor.
4585 Plain text URL-like links connect to websites, emails (VM), Usenet
4586 messages (Gnus), BBDB entries, and any files related to the project.
4587 For printing and sharing of notes, an Org-mode file (or a part of it)
4588 can be exported as a structured ASCII or HTML file.
4590 The following commands are available:
4592 \\{org-mode-map}"
4594 ;; Get rid of Outline menus, they are not needed
4595 ;; Need to do this here because define-derived-mode sets up
4596 ;; the keymap so late. Still, it is a waste to call this each time
4597 ;; we switch another buffer into org-mode.
4598 (if (featurep 'xemacs)
4599 (when (boundp 'outline-mode-menu-heading)
4600 ;; Assume this is Greg's port, it uses easymenu
4601 (easy-menu-remove outline-mode-menu-heading)
4602 (easy-menu-remove outline-mode-menu-show)
4603 (easy-menu-remove outline-mode-menu-hide))
4604 (define-key org-mode-map [menu-bar headings] 'undefined)
4605 (define-key org-mode-map [menu-bar hide] 'undefined)
4606 (define-key org-mode-map [menu-bar show] 'undefined))
4608 (org-load-modules-maybe)
4609 (easy-menu-add org-org-menu)
4610 (easy-menu-add org-tbl-menu)
4611 (org-install-agenda-files-menu)
4612 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4613 (add-to-invisibility-spec '(org-cwidth))
4614 (add-to-invisibility-spec '(org-hide-block . t))
4615 (when (featurep 'xemacs)
4616 (org-set-local 'line-move-ignore-invisible t))
4617 (org-set-local 'outline-regexp org-outline-regexp)
4618 (org-set-local 'outline-level 'org-outline-level)
4619 (when (and org-ellipsis
4620 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4621 (fboundp 'make-glyph-code))
4622 (unless org-display-table
4623 (setq org-display-table (make-display-table)))
4624 (set-display-table-slot
4625 org-display-table 4
4626 (vconcat (mapcar
4627 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4628 org-ellipsis)))
4629 (if (stringp org-ellipsis) org-ellipsis "..."))))
4630 (setq buffer-display-table org-display-table))
4631 (org-set-regexps-and-options)
4632 (when (and org-tag-faces (not org-tags-special-faces-re))
4633 ;; tag faces set outside customize.... force initialization.
4634 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4635 ;; Calc embedded
4636 (org-set-local 'calc-embedded-open-mode "# ")
4637 (modify-syntax-entry ?@ "w")
4638 (if org-startup-truncated (setq truncate-lines t))
4639 (org-set-local 'font-lock-unfontify-region-function
4640 'org-unfontify-region)
4641 ;; Activate before-change-function
4642 (org-set-local 'org-table-may-need-update t)
4643 (org-add-hook 'before-change-functions 'org-before-change-function nil
4644 'local)
4645 ;; Check for running clock before killing a buffer
4646 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4647 ;; Paragraphs and auto-filling
4648 (org-set-autofill-regexps)
4649 (setq indent-line-function 'org-indent-line-function)
4650 (org-update-radio-target-regexp)
4651 ;; Beginning/end of defun
4652 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
4653 (org-set-local 'end-of-defun-function 'org-end-of-defun)
4654 ;; Make sure dependence stuff works reliably, even for users who set it
4655 ;; too late :-(
4656 (if org-enforce-todo-dependencies
4657 (add-hook 'org-blocker-hook
4658 'org-block-todo-from-children-or-siblings-or-parent)
4659 (remove-hook 'org-blocker-hook
4660 'org-block-todo-from-children-or-siblings-or-parent))
4661 (if org-enforce-todo-checkbox-dependencies
4662 (add-hook 'org-blocker-hook
4663 'org-block-todo-from-checkboxes)
4664 (remove-hook 'org-blocker-hook
4665 'org-block-todo-from-checkboxes))
4667 ;; Comment characters
4668 (org-set-local 'comment-start "#")
4669 (org-set-local 'comment-padding " ")
4671 ;; Align options lines
4672 (org-set-local
4673 'align-mode-rules-list
4674 '((org-in-buffer-settings
4675 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4676 (modes . '(org-mode)))))
4678 ;; Imenu
4679 (org-set-local 'imenu-create-index-function
4680 'org-imenu-get-tree)
4682 ;; Make isearch reveal context
4683 (if (or (featurep 'xemacs)
4684 (not (boundp 'outline-isearch-open-invisible-function)))
4685 ;; Emacs 21 and XEmacs make use of the hook
4686 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4687 ;; Emacs 22 deals with this through a special variable
4688 (org-set-local 'outline-isearch-open-invisible-function
4689 (lambda (&rest ignore) (org-show-context 'isearch))))
4691 ;; Turn on org-beamer-mode?
4692 (and org-startup-with-beamer-mode (org-beamer-mode 1))
4694 ;; If empty file that did not turn on org-mode automatically, make it to.
4695 (if (and org-insert-mode-line-in-empty-file
4696 (interactive-p)
4697 (= (point-min) (point-max)))
4698 (insert "# -*- mode: org -*-\n\n"))
4699 (unless org-inhibit-startup
4700 (when org-startup-align-all-tables
4701 (let ((bmp (buffer-modified-p)))
4702 (org-table-map-tables 'org-table-align 'quietly)
4703 (set-buffer-modified-p bmp)))
4704 (when org-startup-indented
4705 (require 'org-indent)
4706 (org-indent-mode 1))
4707 (unless org-inhibit-startup-visibility-stuff
4708 (org-set-startup-visibility))))
4710 (when (fboundp 'abbrev-table-put)
4711 (abbrev-table-put org-mode-abbrev-table
4712 :parents (list text-mode-abbrev-table)))
4714 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4716 (defun org-current-time ()
4717 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4718 (if (> (car org-time-stamp-rounding-minutes) 1)
4719 (let ((r (car org-time-stamp-rounding-minutes))
4720 (time (decode-time)))
4721 (apply 'encode-time
4722 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4723 (nthcdr 2 time))))
4724 (current-time)))
4726 ;;;; Font-Lock stuff, including the activators
4728 (defvar org-mouse-map (make-sparse-keymap))
4729 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
4730 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
4731 (when org-mouse-1-follows-link
4732 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4733 (when org-tab-follows-link
4734 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4735 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4737 (require 'font-lock)
4739 (defconst org-non-link-chars "]\t\n\r<>")
4740 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4741 "shell" "elisp" "doi"))
4742 (defvar org-link-types-re nil
4743 "Matches a link that has a url-like prefix like \"http:\"")
4744 (defvar org-link-re-with-space nil
4745 "Matches a link with spaces, optional angular brackets around it.")
4746 (defvar org-link-re-with-space2 nil
4747 "Matches a link with spaces, optional angular brackets around it.")
4748 (defvar org-link-re-with-space3 nil
4749 "Matches a link with spaces, only for internal part in bracket links.")
4750 (defvar org-angle-link-re nil
4751 "Matches link with angular brackets, spaces are allowed.")
4752 (defvar org-plain-link-re nil
4753 "Matches plain link, without spaces.")
4754 (defvar org-bracket-link-regexp nil
4755 "Matches a link in double brackets.")
4756 (defvar org-bracket-link-analytic-regexp nil
4757 "Regular expression used to analyze links.
4758 Here is what the match groups contain after a match:
4759 1: http:
4760 2: http
4761 3: path
4762 4: [desc]
4763 5: desc")
4764 (defvar org-bracket-link-analytic-regexp++ nil
4765 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
4766 (defvar org-any-link-re nil
4767 "Regular expression matching any link.")
4769 (defcustom org-match-sexp-depth 3
4770 "Number of stacked braces for sub/superscript matching.
4771 This has to be set before loading org.el to be effective."
4772 :group 'org-export-translation ; ??????????????????????????/
4773 :type 'integer)
4775 (defun org-create-multibrace-regexp (left right n)
4776 "Create a regular expression which will match a balanced sexp.
4777 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
4778 as single character strings.
4779 The regexp returned will match the entire expression including the
4780 delimiters. It will also define a single group which contains the
4781 match except for the outermost delimiters. The maximum depth of
4782 stacked delimiters is N. Escaping delimiters is not possible."
4783 (let* ((nothing (concat "[^" left right "]*?"))
4784 (or "\\|")
4785 (re nothing)
4786 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
4787 (while (> n 1)
4788 (setq n (1- n)
4789 re (concat re or next)
4790 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
4791 (concat left "\\(" re "\\)" right)))
4793 (defvar org-match-substring-regexp
4794 (concat
4795 "\\([^\\]\\)\\([_^]\\)\\("
4796 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
4797 "\\|"
4798 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
4799 "\\|"
4800 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
4801 "The regular expression matching a sub- or superscript.")
4803 (defvar org-match-substring-with-braces-regexp
4804 (concat
4805 "\\([^\\]\\)\\([_^]\\)\\("
4806 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
4807 "\\)")
4808 "The regular expression matching a sub- or superscript, forcing braces.")
4810 (defun org-make-link-regexps ()
4811 "Update the link regular expressions.
4812 This should be called after the variable `org-link-types' has changed."
4813 (setq org-link-types-re
4814 (concat
4815 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
4816 org-link-re-with-space
4817 (concat
4818 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4819 "\\([^" org-non-link-chars " ]"
4820 "[^" org-non-link-chars "]*"
4821 "[^" org-non-link-chars " ]\\)>?")
4822 org-link-re-with-space2
4823 (concat
4824 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4825 "\\([^" org-non-link-chars " ]"
4826 "[^\t\n\r]*"
4827 "[^" org-non-link-chars " ]\\)>?")
4828 org-link-re-with-space3
4829 (concat
4830 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4831 "\\([^" org-non-link-chars " ]"
4832 "[^\t\n\r]*\\)")
4833 org-angle-link-re
4834 (concat
4835 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4836 "\\([^" org-non-link-chars " ]"
4837 "[^" org-non-link-chars "]*"
4838 "\\)>")
4839 org-plain-link-re
4840 (concat
4841 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4842 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
4843 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4844 org-bracket-link-regexp
4845 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4846 org-bracket-link-analytic-regexp
4847 (concat
4848 "\\[\\["
4849 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
4850 "\\([^]]+\\)"
4851 "\\]"
4852 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4853 "\\]")
4854 org-bracket-link-analytic-regexp++
4855 (concat
4856 "\\[\\["
4857 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4858 "\\([^]]+\\)"
4859 "\\]"
4860 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4861 "\\]")
4862 org-any-link-re
4863 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4864 org-angle-link-re "\\)\\|\\("
4865 org-plain-link-re "\\)")))
4867 (org-make-link-regexps)
4869 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4870 "Regular expression for fast time stamp matching.")
4871 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4872 "Regular expression for fast time stamp matching.")
4873 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4874 "Regular expression matching time strings for analysis.
4875 This one does not require the space after the date, so it can be used
4876 on a string that terminates immediately after the date.")
4877 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4878 "Regular expression matching time strings for analysis.")
4879 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4880 "Regular expression matching time stamps, with groups.")
4881 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4882 "Regular expression matching time stamps (also [..]), with groups.")
4883 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4884 "Regular expression matching a time stamp range.")
4885 (defconst org-tr-regexp-both
4886 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4887 "Regular expression matching a time stamp range.")
4888 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4889 org-ts-regexp "\\)?")
4890 "Regular expression matching a time stamp or time stamp range.")
4891 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4892 org-ts-regexp-both "\\)?")
4893 "Regular expression matching a time stamp or time stamp range.
4894 The time stamps may be either active or inactive.")
4896 (defvar org-emph-face nil)
4898 (defun org-do-emphasis-faces (limit)
4899 "Run through the buffer and add overlays to links."
4900 (let (rtn a)
4901 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4902 (if (not (= (char-after (match-beginning 3))
4903 (char-after (match-beginning 4))))
4904 (progn
4905 (setq rtn t)
4906 (setq a (assoc (match-string 3) org-emphasis-alist))
4907 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4908 'face
4909 (nth 1 a))
4910 (and (nth 4 a)
4911 (org-remove-flyspell-overlays-in
4912 (match-beginning 0) (match-end 0)))
4913 (add-text-properties (match-beginning 2) (match-end 2)
4914 '(font-lock-multiline t org-emphasis t))
4915 (when org-hide-emphasis-markers
4916 (add-text-properties (match-end 4) (match-beginning 5)
4917 '(invisible org-link))
4918 (add-text-properties (match-beginning 3) (match-end 3)
4919 '(invisible org-link)))))
4920 (backward-char 1))
4921 rtn))
4923 (defun org-emphasize (&optional char)
4924 "Insert or change an emphasis, i.e. a font like bold or italic.
4925 If there is an active region, change that region to a new emphasis.
4926 If there is no region, just insert the marker characters and position
4927 the cursor between them.
4928 CHAR should be either the marker character, or the first character of the
4929 HTML tag associated with that emphasis. If CHAR is a space, the means
4930 to remove the emphasis of the selected region.
4931 If char is not given (for example in an interactive call) it
4932 will be prompted for."
4933 (interactive)
4934 (let ((eal org-emphasis-alist) e det
4935 (erc org-emphasis-regexp-components)
4936 (prompt "")
4937 (string "") beg end move tag c s)
4938 (if (org-region-active-p)
4939 (setq beg (region-beginning) end (region-end)
4940 string (buffer-substring beg end))
4941 (setq move t))
4943 (while (setq e (pop eal))
4944 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4945 c (aref tag 0))
4946 (push (cons c (string-to-char (car e))) det)
4947 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4948 (substring tag 1)))))
4949 (setq det (nreverse det))
4950 (unless char
4951 (message "%s" (concat "Emphasis marker or tag:" prompt))
4952 (setq char (read-char-exclusive)))
4953 (setq char (or (cdr (assoc char det)) char))
4954 (if (equal char ?\ )
4955 (setq s "" move nil)
4956 (unless (assoc (char-to-string char) org-emphasis-alist)
4957 (error "No such emphasis marker: \"%c\"" char))
4958 (setq s (char-to-string char)))
4959 (while (and (> (length string) 1)
4960 (equal (substring string 0 1) (substring string -1))
4961 (assoc (substring string 0 1) org-emphasis-alist))
4962 (setq string (substring string 1 -1)))
4963 (setq string (concat s string s))
4964 (if beg (delete-region beg end))
4965 (unless (or (bolp)
4966 (string-match (concat "[" (nth 0 erc) "\n]")
4967 (char-to-string (char-before (point)))))
4968 (insert " "))
4969 (unless (or (eobp)
4970 (string-match (concat "[" (nth 1 erc) "\n]")
4971 (char-to-string (char-after (point)))))
4972 (insert " ") (backward-char 1))
4973 (insert string)
4974 (and move (backward-char 1))))
4976 (defconst org-nonsticky-props
4977 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4979 (defsubst org-rear-nonsticky-at (pos)
4980 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4982 (defun org-activate-plain-links (limit)
4983 "Run through the buffer and add overlays to links."
4984 (catch 'exit
4985 (let (f)
4986 (if (re-search-forward org-plain-link-re limit t)
4987 (progn
4988 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4989 (setq f (get-text-property (match-beginning 0) 'face))
4990 (if (or (eq f 'org-tag)
4991 (and (listp f) (memq 'org-tag f)))
4993 (add-text-properties (match-beginning 0) (match-end 0)
4994 (list 'mouse-face 'highlight
4995 'face 'org-link
4996 'keymap org-mouse-map))
4997 (org-rear-nonsticky-at (match-end 0)))
4998 t)))))
5000 (defun org-activate-code (limit)
5001 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
5002 (progn
5003 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5004 (remove-text-properties (match-beginning 0) (match-end 0)
5005 '(display t invisible t intangible t))
5006 t)))
5008 (defun org-fontify-meta-lines-and-blocks (limit)
5009 "Fontify #+ lines and blocks, in the correct ways."
5010 (let ((case-fold-search t))
5011 (if (re-search-forward
5012 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
5013 limit t)
5014 (let ((beg (match-beginning 0))
5015 (beg1 (line-beginning-position 2))
5016 (dc1 (downcase (match-string 2)))
5017 (dc3 (downcase (match-string 3)))
5018 end end1 quoting block-type)
5019 (cond
5020 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
5021 ;; a single line of backend-specific content
5022 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5023 (remove-text-properties (match-beginning 0) (match-end 0)
5024 '(display t invisible t intangible t))
5025 (add-text-properties (match-beginning 1) (match-end 3)
5026 '(font-lock-fontified t face org-meta-line))
5027 (add-text-properties (match-beginning 6) (match-end 6)
5028 '(font-lock-fontified t face org-block))
5030 ((and (match-end 4) (equal dc3 "begin"))
5031 ;; Truly a block
5032 (setq block-type (downcase (match-string 5))
5033 quoting (member block-type org-protecting-blocks))
5034 (when (re-search-forward
5035 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5036 nil t) ;; on purpose, we look further than LIMIT
5037 (setq end (match-end 0) end1 (1- (match-beginning 0)))
5038 (when quoting
5039 (remove-text-properties beg end
5040 '(display t invisible t intangible t)))
5041 (add-text-properties
5042 beg end
5043 '(font-lock-fontified t font-lock-multiline t))
5044 (add-text-properties beg beg1 '(face org-meta-line))
5045 (add-text-properties end1 end '(face org-meta-line))
5046 (cond
5047 (quoting
5048 (add-text-properties beg1 end1 '(face org-block)))
5049 ((not org-fontify-quote-and-verse-blocks))
5050 ((string= block-type "quote")
5051 (add-text-properties beg1 end1 '(face org-quote)))
5052 ((string= block-type "verse")
5053 (add-text-properties beg1 end1 '(face org-verse))))
5055 ((member dc1 '("title:" "author:" "email:" "date:"))
5056 (add-text-properties
5057 beg (match-end 3)
5058 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5059 '(font-lock-fontified t invisible t)
5060 '(font-lock-fontified t face org-document-info-keyword)))
5061 (add-text-properties
5062 (match-beginning 6) (match-end 6)
5063 (if (string-equal dc1 "title:")
5064 '(font-lock-fontified t face org-document-title)
5065 '(font-lock-fontified t face org-document-info))))
5066 ((not (member (char-after beg) '(?\ ?\t)))
5067 ;; just any other in-buffer setting, but not indented
5068 (add-text-properties
5069 beg (match-end 0)
5070 '(font-lock-fontified t face org-meta-line))
5072 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
5073 "orgtbl:" "tblfm:" "tblname:" "result:"
5074 "results:" "source:" "srcname:" "call:"))
5075 (and (match-end 4) (equal dc3 "attr")))
5076 (add-text-properties
5077 beg (match-end 0)
5078 '(font-lock-fontified t face org-meta-line))
5080 ((member dc3 '(" " ""))
5081 (add-text-properties
5082 beg (match-end 0)
5083 '(font-lock-fontified t face font-lock-comment-face)))
5084 (t nil))))))
5086 (defun org-activate-angle-links (limit)
5087 "Run through the buffer and add overlays to links."
5088 (if (re-search-forward org-angle-link-re limit t)
5089 (progn
5090 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5091 (add-text-properties (match-beginning 0) (match-end 0)
5092 (list 'mouse-face 'highlight
5093 'keymap org-mouse-map))
5094 (org-rear-nonsticky-at (match-end 0))
5095 t)))
5097 (defun org-activate-footnote-links (limit)
5098 "Run through the buffer and add overlays to links."
5099 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
5100 limit t)
5101 (progn
5102 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5103 (add-text-properties (match-beginning 2) (match-end 2)
5104 (list 'mouse-face 'highlight
5105 'keymap org-mouse-map
5106 'help-echo
5107 (if (= (point-at-bol) (match-beginning 2))
5108 "Footnote definition"
5109 "Footnote reference")
5111 (org-rear-nonsticky-at (match-end 2))
5112 t)))
5114 (defun org-activate-bracket-links (limit)
5115 "Run through the buffer and add overlays to bracketed links."
5116 (if (re-search-forward org-bracket-link-regexp limit t)
5117 (let* ((help (concat "LINK: "
5118 (org-match-string-no-properties 1)))
5119 ;; FIXME: above we should remove the escapes.
5120 ;; but that requires another match, protecting match data,
5121 ;; a lot of overhead for font-lock.
5122 (ip (org-maybe-intangible
5123 (list 'invisible 'org-link
5124 'keymap org-mouse-map 'mouse-face 'highlight
5125 'font-lock-multiline t 'help-echo help)))
5126 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5127 'font-lock-multiline t 'help-echo help)))
5128 ;; We need to remove the invisible property here. Table narrowing
5129 ;; may have made some of this invisible.
5130 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5131 (remove-text-properties (match-beginning 0) (match-end 0)
5132 '(invisible nil))
5133 (if (match-end 3)
5134 (progn
5135 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5136 (org-rear-nonsticky-at (match-beginning 3))
5137 (add-text-properties (match-beginning 3) (match-end 3) vp)
5138 (org-rear-nonsticky-at (match-end 3))
5139 (add-text-properties (match-end 3) (match-end 0) ip)
5140 (org-rear-nonsticky-at (match-end 0)))
5141 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5142 (org-rear-nonsticky-at (match-beginning 1))
5143 (add-text-properties (match-beginning 1) (match-end 1) vp)
5144 (org-rear-nonsticky-at (match-end 1))
5145 (add-text-properties (match-end 1) (match-end 0) ip)
5146 (org-rear-nonsticky-at (match-end 0)))
5147 t)))
5149 (defun org-activate-dates (limit)
5150 "Run through the buffer and add overlays to dates."
5151 (if (re-search-forward org-tsr-regexp-both limit t)
5152 (progn
5153 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5154 (add-text-properties (match-beginning 0) (match-end 0)
5155 (list 'mouse-face 'highlight
5156 'keymap org-mouse-map))
5157 (org-rear-nonsticky-at (match-end 0))
5158 (when org-display-custom-times
5159 (if (match-end 3)
5160 (org-display-custom-time (match-beginning 3) (match-end 3)))
5161 (org-display-custom-time (match-beginning 1) (match-end 1)))
5162 t)))
5164 (defvar org-target-link-regexp nil
5165 "Regular expression matching radio targets in plain text.")
5166 (make-variable-buffer-local 'org-target-link-regexp)
5167 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5168 "Regular expression matching a link target.")
5169 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5170 "Regular expression matching a radio target.")
5171 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5172 "Regular expression matching any target.")
5174 (defun org-activate-target-links (limit)
5175 "Run through the buffer and add overlays to target matches."
5176 (when org-target-link-regexp
5177 (let ((case-fold-search t))
5178 (if (re-search-forward org-target-link-regexp limit t)
5179 (progn
5180 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5181 (add-text-properties (match-beginning 0) (match-end 0)
5182 (list 'mouse-face 'highlight
5183 'keymap org-mouse-map
5184 'help-echo "Radio target link"
5185 'org-linked-text t))
5186 (org-rear-nonsticky-at (match-end 0))
5187 t)))))
5189 (defun org-update-radio-target-regexp ()
5190 "Find all radio targets in this file and update the regular expression."
5191 (interactive)
5192 (when (memq 'radio org-activate-links)
5193 (setq org-target-link-regexp
5194 (org-make-target-link-regexp (org-all-targets 'radio)))
5195 (org-restart-font-lock)))
5197 (defun org-hide-wide-columns (limit)
5198 (let (s e)
5199 (setq s (text-property-any (point) (or limit (point-max))
5200 'org-cwidth t))
5201 (when s
5202 (setq e (next-single-property-change s 'org-cwidth))
5203 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5204 (goto-char e)
5205 t)))
5207 (defvar org-latex-and-specials-regexp nil
5208 "Regular expression for highlighting export special stuff.")
5209 (defvar org-match-substring-regexp)
5210 (defvar org-match-substring-with-braces-regexp)
5212 ;; This should be with the exporter code, but we also use if for font-locking
5213 (defconst org-export-html-special-string-regexps
5214 '(("\\\\-" . "&shy;")
5215 ("---\\([^-]\\)" . "&mdash;\\1")
5216 ("--\\([^-]\\)" . "&ndash;\\1")
5217 ("\\.\\.\\." . "&hellip;"))
5218 "Regular expressions for special string conversion.")
5221 (defun org-compute-latex-and-specials-regexp ()
5222 "Compute regular expression for stuff treated specially by exporters."
5223 (if (not org-highlight-latex-fragments-and-specials)
5224 (org-set-local 'org-latex-and-specials-regexp nil)
5225 (require 'org-exp)
5226 (let*
5227 ((matchers (plist-get org-format-latex-options :matchers))
5228 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5229 org-latex-regexps)))
5230 (org-export-allow-BIND nil)
5231 (options (org-combine-plists (org-default-export-plist)
5232 (org-infile-export-plist)))
5233 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5234 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5235 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5236 (org-export-html-expand (plist-get options :expand-quoted-html))
5237 (org-export-with-special-strings (plist-get options :special-strings))
5238 (re-sub
5239 (cond
5240 ((equal org-export-with-sub-superscripts '{})
5241 (list org-match-substring-with-braces-regexp))
5242 (org-export-with-sub-superscripts
5243 (list org-match-substring-regexp))
5244 (t nil)))
5245 (re-latex
5246 (if org-export-with-LaTeX-fragments
5247 (mapcar (lambda (x) (nth 1 x)) latexs)))
5248 (re-macros
5249 (if org-export-with-TeX-macros
5250 (list (concat "\\\\"
5251 (regexp-opt
5252 (append
5254 (delq nil
5255 (mapcar 'car-safe
5256 (append org-entities-user
5257 org-entities)))
5258 (if (boundp 'org-latex-entities)
5259 (mapcar (lambda (x)
5260 (or (car-safe x) x))
5261 org-latex-entities)
5262 nil))
5263 'words))) ; FIXME
5265 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5266 (re-special (if org-export-with-special-strings
5267 (mapcar (lambda (x) (car x))
5268 org-export-html-special-string-regexps)))
5269 (re-rest
5270 (delq nil
5271 (list
5272 (if org-export-html-expand "@<[^>\n]+>")
5273 ))))
5274 (org-set-local
5275 'org-latex-and-specials-regexp
5276 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5277 re-rest) "\\|")))))
5279 (defun org-do-latex-and-special-faces (limit)
5280 "Run through the buffer and add overlays to links."
5281 (when org-latex-and-specials-regexp
5282 (let (rtn d)
5283 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5284 limit t))
5285 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5286 'face))
5287 '(org-code org-verbatim underline)))
5288 (progn
5289 (setq rtn t
5290 d (cond ((member (char-after (1+ (match-beginning 0)))
5291 '(?_ ?^)) 1)
5292 (t 0)))
5293 (font-lock-prepend-text-property
5294 (+ d (match-beginning 0)) (match-end 0)
5295 'face 'org-latex-and-export-specials)
5296 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5297 '(font-lock-multiline t)))))
5298 rtn)))
5300 (defun org-restart-font-lock ()
5301 "Restart `font-lock-mode', to force refontification."
5302 (when (and (boundp 'font-lock-mode) font-lock-mode)
5303 (font-lock-mode -1)
5304 (font-lock-mode 1)))
5306 (defun org-all-targets (&optional radio)
5307 "Return a list of all targets in this file.
5308 With optional argument RADIO, only find radio targets."
5309 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5310 rtn)
5311 (save-excursion
5312 (goto-char (point-min))
5313 (while (re-search-forward re nil t)
5314 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5315 rtn)))
5317 (defun org-make-target-link-regexp (targets)
5318 "Make regular expression matching all strings in TARGETS.
5319 The regular expression finds the targets also if there is a line break
5320 between words."
5321 (and targets
5322 (concat
5323 "\\<\\("
5324 (mapconcat
5325 (lambda (x)
5326 (while (string-match " +" x)
5327 (setq x (replace-match "\\s-+" t t x)))
5329 targets
5330 "\\|")
5331 "\\)\\>")))
5333 (defun org-activate-tags (limit)
5334 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
5335 (progn
5336 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5337 (add-text-properties (match-beginning 1) (match-end 1)
5338 (list 'mouse-face 'highlight
5339 'keymap org-mouse-map))
5340 (org-rear-nonsticky-at (match-end 1))
5341 t)))
5343 (defun org-outline-level ()
5344 "Compute the outline level of the heading at point.
5345 This function assumes that the cursor is at the beginning of a line matched
5346 by `outline-regexp'. Otherwise it returns garbage.
5347 If this is called at a normal headline, the level is the number of stars.
5348 Use `org-reduced-level' to remove the effect of `org-odd-levels'.
5349 For plain list items, if they are matched by `outline-regexp', this returns
5350 1000 plus the line indentation."
5351 (save-excursion
5352 (looking-at outline-regexp)
5353 (if (match-beginning 1)
5354 (+ (org-get-string-indentation (match-string 1)) 1000)
5355 (1- (- (match-end 0) (match-beginning 0))))))
5357 (defvar org-font-lock-keywords nil)
5359 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5360 "Regular expression matching a property line.")
5362 (defvar org-font-lock-hook nil
5363 "Functions to be called for special font lock stuff.")
5365 (defun org-font-lock-hook (limit)
5366 (run-hook-with-args 'org-font-lock-hook limit))
5368 (defun org-set-font-lock-defaults ()
5369 (let* ((em org-fontify-emphasized-text)
5370 (lk org-activate-links)
5371 (org-font-lock-extra-keywords
5372 (list
5373 ;; Call the hook
5374 '(org-font-lock-hook)
5375 ;; Headlines
5376 `(,(if org-fontify-whole-heading-line
5377 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5378 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5379 (1 (org-get-level-face 1))
5380 (2 (org-get-level-face 2))
5381 (3 (org-get-level-face 3)))
5382 ;; Table lines
5383 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5384 (1 'org-table t))
5385 ;; Table internals
5386 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5387 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5388 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5389 '("| *\\(<[lr]?[0-9]*>\\)" (1 'org-formula t))
5390 ;; Drawers
5391 (list org-drawer-regexp '(0 'org-special-keyword t))
5392 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5393 ;; Properties
5394 (list org-property-re
5395 '(1 'org-special-keyword t)
5396 '(3 'org-property-value t))
5397 ;; Links
5398 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5399 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5400 (if (memq 'plain lk) '(org-activate-plain-links))
5401 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5402 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5403 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5404 (if (memq 'footnote lk) '(org-activate-footnote-links
5405 (2 'org-footnote t)))
5406 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5407 '(org-hide-wide-columns (0 nil append))
5408 ;; TODO lines
5409 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
5410 '(1 (org-get-todo-face 1) t))
5411 ;; DONE
5412 (if org-fontify-done-headline
5413 (list (concat "^[*]+ +\\<\\("
5414 (mapconcat 'regexp-quote org-done-keywords "\\|")
5415 "\\)\\(.*\\)")
5416 '(2 'org-headline-done t))
5417 nil)
5418 ;; Priorities
5419 '(org-font-lock-add-priority-faces)
5420 ;; Tags
5421 '(org-font-lock-add-tag-faces)
5422 ;; Special keywords
5423 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5424 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5425 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5426 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5427 ;; Emphasis
5428 (if em
5429 (if (featurep 'xemacs)
5430 '(org-do-emphasis-faces (0 nil append))
5431 '(org-do-emphasis-faces)))
5432 ;; Checkboxes
5433 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5434 2 'org-checkbox prepend)
5435 (if org-provide-checkbox-statistics
5436 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5437 (0 (org-get-checkbox-statistics-face) t)))
5438 ;; Description list items
5439 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
5440 2 'bold prepend)
5441 ;; ARCHIVEd headings
5442 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5443 '(1 'org-archived prepend))
5444 ;; Specials
5445 '(org-do-latex-and-special-faces)
5446 '(org-fontify-entities)
5447 '(org-raise-scripts)
5448 ;; Code
5449 '(org-activate-code (1 'org-code t))
5450 ;; COMMENT
5451 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5452 "\\|" org-quote-string "\\)\\>")
5453 '(1 'org-special-keyword t))
5454 '("^#.*" (0 'font-lock-comment-face t))
5455 ;; Blocks and meta lines
5456 '(org-fontify-meta-lines-and-blocks)
5458 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5459 ;; Now set the full font-lock-keywords
5460 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5461 (org-set-local 'font-lock-defaults
5462 '(org-font-lock-keywords t nil nil backward-paragraph))
5463 (kill-local-variable 'font-lock-keywords) nil))
5465 (defun org-toggle-pretty-entities ()
5466 "Toggle the composition display of entities as UTF8 characters."
5467 (interactive)
5468 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5469 (org-restart-font-lock)
5470 (if org-pretty-entities
5471 (message "Entities are displayed as UTF8 characers")
5472 (save-restriction
5473 (widen)
5474 (decompose-region (point-min) (point-max))
5475 (message "Entities are displayed plain"))))
5477 (defun org-fontify-entities (limit)
5478 "Find an entity to fontify."
5479 (let (ee)
5480 (when org-pretty-entities
5481 (catch 'match
5482 (while (re-search-forward
5483 "\\\\\\([a-zA-Z][a-zA-Z0-9]*\\)\\($\\|[^[:alnum:]\n]\\)"
5484 limit t)
5485 (if (and (not (org-in-indented-comment-line))
5486 (setq ee (org-entity-get (match-string 1)))
5487 (= (length (nth 6 ee)) 1))
5488 (progn
5489 (add-text-properties
5490 (match-beginning 0) (match-end 1)
5491 (list 'font-lock-fontified t))
5492 (compose-region (match-beginning 0) (match-end 1)
5493 (nth 6 ee) nil)
5494 (backward-char 1)
5495 (throw 'match t))))
5496 nil))))
5498 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5499 "Fontify string S like in Org-mode."
5500 (with-temp-buffer
5501 (insert s)
5502 (let ((org-odd-levels-only odd-levels))
5503 (org-mode)
5504 (font-lock-fontify-buffer)
5505 (buffer-string))))
5507 (defvar org-m nil)
5508 (defvar org-l nil)
5509 (defvar org-f nil)
5510 (defun org-get-level-face (n)
5511 "Get the right face for match N in font-lock matching of headlines."
5512 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5513 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5514 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5515 (cond
5516 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5517 ((eq n 2) org-f)
5518 (t (if org-level-color-stars-only nil org-f))))
5520 (defun org-get-todo-face (kwd)
5521 "Get the right face for a TODO keyword KWD.
5522 If KWD is a number, get the corresponding match group."
5523 (if (numberp kwd) (setq kwd (match-string kwd)))
5524 (or (org-face-from-face-or-color
5525 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5526 (and (member kwd org-done-keywords) 'org-done)
5527 'org-todo))
5529 (defun org-face-from-face-or-color (context inherit face-or-color)
5530 "Create a face list that inherits INHERIT, but sets the foreground color.
5531 When FACE-OR-COLOR is not a string, just return it."
5532 (if (stringp face-or-color)
5533 (list :inherit inherit
5534 (cdr (assoc context org-faces-easy-properties))
5535 face-or-color)
5536 face-or-color))
5538 (defun org-font-lock-add-tag-faces (limit)
5539 "Add the special tag faces."
5540 (when (and org-tag-faces org-tags-special-faces-re)
5541 (while (re-search-forward org-tags-special-faces-re limit t)
5542 (add-text-properties (match-beginning 1) (match-end 1)
5543 (list 'face (org-get-tag-face 1)
5544 'font-lock-fontified t))
5545 (backward-char 1))))
5547 (defun org-font-lock-add-priority-faces (limit)
5548 "Add the special priority faces."
5549 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5550 (add-text-properties
5551 (match-beginning 0) (match-end 0)
5552 (list 'face (or (org-face-from-face-or-color
5553 'priority 'org-special-keyword
5554 (cdr (assoc (char-after (match-beginning 1))
5555 org-priority-faces)))
5556 'org-special-keyword)
5557 'font-lock-fontified t))))
5559 (defun org-get-tag-face (kwd)
5560 "Get the right face for a TODO keyword KWD.
5561 If KWD is a number, get the corresponding match group."
5562 (if (numberp kwd) (setq kwd (match-string kwd)))
5563 (or (org-face-from-face-or-color
5564 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5565 'org-tag))
5567 (defun org-unfontify-region (beg end &optional maybe_loudly)
5568 "Remove fontification and activation overlays from links."
5569 (font-lock-default-unfontify-region beg end)
5570 (let* ((buffer-undo-list t)
5571 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5572 (inhibit-modification-hooks t)
5573 deactivate-mark buffer-file-name buffer-file-truename)
5574 (decompose-region beg end)
5575 (remove-text-properties
5576 beg end
5577 (if org-indent-mode
5578 ;; also remove line-prefix and wrap-prefix properties
5579 '(mouse-face t keymap t org-linked-text t
5580 invisible t intangible t
5581 line-prefix t wrap-prefix t
5582 org-no-flyspell t org-emphasis t)
5583 '(mouse-face t keymap t org-linked-text t
5584 invisible t intangible t
5585 org-no-flyspell t org-emphasis t)))
5586 (org-remove-font-lock-display-properties beg end)))
5588 (defconst org-script-display '(((raise -0.3) (height 0.7))
5589 ((raise 0.3) (height 0.7))
5590 ((raise -0.5))
5591 ((raise 0.5)))
5592 "Display properties for showing superscripts and subscripts.")
5594 (defun org-remove-font-lock-display-properties (beg end)
5595 "Remove specific display properties that have been added by font lock.
5596 The will remove the raise properties that are used to show superscripts
5597 and subscripts."
5598 (let (next prop)
5599 (while (< beg end)
5600 (setq next (next-single-property-change beg 'display nil end)
5601 prop (get-text-property beg 'display))
5602 (if (member prop org-script-display)
5603 (put-text-property beg next 'display nil))
5604 (setq beg next))))
5606 (defun org-raise-scripts (limit)
5607 "Add raise properties to sub/superscripts."
5608 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
5609 (if (re-search-forward
5610 (if (eq org-use-sub-superscripts t)
5611 org-match-substring-regexp
5612 org-match-substring-with-braces-regexp)
5613 limit t)
5614 (let* ((pos (point)) table-p comment-p
5615 (mpos (match-beginning 3))
5616 (emph-p (get-text-property mpos 'org-emphasis))
5617 (link-p (get-text-property mpos 'mouse-face))
5618 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
5619 (goto-char (point-at-bol))
5620 (setq table-p (org-looking-at-p org-table-dataline-regexp)
5621 comment-p (org-looking-at-p "[ \t]*#"))
5622 (goto-char pos)
5623 ;; FIXME: Should we go back one character here, for a_b^c
5624 ;; (goto-char (1- pos)) ;????????????????????
5625 (if (or comment-p emph-p link-p keyw-p)
5627 (put-text-property (match-beginning 3) (match-end 0)
5628 'display
5629 (if (equal (char-after (match-beginning 2)) ?^)
5630 (nth (if table-p 3 1) org-script-display)
5631 (nth (if table-p 2 0) org-script-display)))
5632 (add-text-properties (match-beginning 2) (match-end 2)
5633 (list 'invisible t
5634 'org-dwidth t 'org-dwidth-n 1))
5635 (if (and (eq (char-after (match-beginning 3)) ?{)
5636 (eq (char-before (match-end 3)) ?}))
5637 (progn
5638 (add-text-properties
5639 (match-beginning 3) (1+ (match-beginning 3))
5640 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
5641 (add-text-properties
5642 (1- (match-end 3)) (match-end 3)
5643 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
5644 t)))))
5646 ;;;; Visibility cycling, including org-goto and indirect buffer
5648 ;;; Cycling
5650 (defvar org-cycle-global-status nil)
5651 (make-variable-buffer-local 'org-cycle-global-status)
5652 (defvar org-cycle-subtree-status nil)
5653 (make-variable-buffer-local 'org-cycle-subtree-status)
5655 ;;;###autoload
5657 (defvar org-inlinetask-min-level)
5659 (defun org-cycle (&optional arg)
5660 "TAB-action and visibility cycling for Org-mode.
5662 This is the command invoked in Org-mode by the TAB key. Its main purpose
5663 is outline visibility cycling, but it also invokes other actions
5664 in special contexts.
5666 - When this function is called with a prefix argument, rotate the entire
5667 buffer through 3 states (global cycling)
5668 1. OVERVIEW: Show only top-level headlines.
5669 2. CONTENTS: Show all headlines of all levels, but no body text.
5670 3. SHOW ALL: Show everything.
5671 When called with two `C-u C-u' prefixes, switch to the startup visibility,
5672 determined by the variable `org-startup-folded', and by any VISIBILITY
5673 properties in the buffer.
5674 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
5675 including any drawers.
5677 - When inside a table, re-align the table and move to the next field.
5679 - When point is at the beginning of a headline, rotate the subtree started
5680 by this line through 3 different states (local cycling)
5681 1. FOLDED: Only the main headline is shown.
5682 2. CHILDREN: The main headline and the direct children are shown.
5683 From this state, you can move to one of the children
5684 and zoom in further.
5685 3. SUBTREE: Show the entire subtree, including body text.
5686 If there is no subtree, switch directly from CHILDREN to FOLDED.
5688 - When point is at the beginning of an empty headline and the variable
5689 `org-cycle-level-after-item/entry-creation' is set, cycle the level
5690 of the headline by demoting and promoting it to likely levels. This
5691 speeds up creation document structure by pressing TAB once or several
5692 times right after creating a new headline.
5694 - When there is a numeric prefix, go up to a heading with level ARG, do
5695 a `show-subtree' and return to the previous cursor position. If ARG
5696 is negative, go up that many levels.
5698 - When point is not at the beginning of a headline, execute the global
5699 binding for TAB, which is re-indenting the line. See the option
5700 `org-cycle-emulate-tab' for details.
5702 - Special case: if point is at the beginning of the buffer and there is
5703 no headline in line 1, this function will act as if called with prefix arg.
5704 But only if also the variable `org-cycle-global-at-bob' is t."
5705 (interactive "P")
5706 (org-load-modules-maybe)
5707 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
5708 (and org-cycle-level-after-item/entry-creation
5709 (or (org-cycle-level)
5710 (org-cycle-item-indentation))))
5711 (let* ((limit-level
5712 (or org-cycle-max-level
5713 (and (boundp 'org-inlinetask-min-level)
5714 org-inlinetask-min-level
5715 (1- org-inlinetask-min-level))))
5716 (nstars (and limit-level
5717 (if org-odd-levels-only
5718 (and limit-level (1- (* limit-level 2)))
5719 limit-level)))
5720 (outline-regexp
5721 (cond
5722 ((not (org-mode-p)) outline-regexp)
5723 ((or (eq org-cycle-include-plain-lists 'integrate)
5724 (and org-cycle-include-plain-lists (org-at-item-p)))
5725 (concat "\\(?:\\*"
5726 (if nstars (format "\\{1,%d\\}" nstars) "+")
5727 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
5728 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
5729 (bob-special (and org-cycle-global-at-bob (bobp)
5730 (not (looking-at outline-regexp))))
5731 (org-cycle-hook
5732 (if bob-special
5733 (delq 'org-optimize-window-after-visibility-change
5734 (copy-sequence org-cycle-hook))
5735 org-cycle-hook))
5736 (pos (point)))
5738 (if (or bob-special (equal arg '(4)))
5739 ;; special case: use global cycling
5740 (setq arg t))
5742 (cond
5744 ((equal arg '(16))
5745 (org-set-startup-visibility)
5746 (message "Startup visibility, plus VISIBILITY properties"))
5748 ((equal arg '(64))
5749 (show-all)
5750 (message "Entire buffer visible, including drawers"))
5752 ((org-at-table-p 'any)
5753 ;; Enter the table or move to the next field in the table
5754 (if (org-at-table.el-p)
5755 (message "Use C-c ' to edit table.el tables")
5756 (if arg (org-table-edit-field t)
5757 (org-table-justify-field-maybe)
5758 (call-interactively 'org-table-next-field))))
5760 ((run-hook-with-args-until-success
5761 'org-tab-after-check-for-table-hook))
5763 ((eq arg t) ;; Global cycling
5764 (org-cycle-internal-global))
5766 ((and org-drawers org-drawer-regexp
5767 (save-excursion
5768 (beginning-of-line 1)
5769 (looking-at org-drawer-regexp)))
5770 ;; Toggle block visibility
5771 (org-flag-drawer
5772 (not (get-char-property (match-end 0) 'invisible))))
5774 ((integerp arg)
5775 ;; Show-subtree, ARG levels up from here.
5776 (save-excursion
5777 (org-back-to-heading)
5778 (outline-up-heading (if (< arg 0) (- arg)
5779 (- (funcall outline-level) arg)))
5780 (org-show-subtree)))
5782 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5783 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5785 (org-cycle-internal-local))
5787 ;; TAB emulation and template completion
5788 (buffer-read-only (org-back-to-heading))
5790 ((run-hook-with-args-until-success
5791 'org-tab-after-check-for-cycling-hook))
5793 ((org-try-structure-completion))
5795 ((org-try-cdlatex-tab))
5797 ((run-hook-with-args-until-success
5798 'org-tab-before-tab-emulation-hook))
5800 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5801 (or (not (bolp))
5802 (not (looking-at outline-regexp))))
5803 (call-interactively (global-key-binding "\t")))
5805 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5806 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5807 (or (and (eq org-cycle-emulate-tab 'white)
5808 (= (match-end 0) (point-at-eol)))
5809 (and (eq org-cycle-emulate-tab 'whitestart)
5810 (>= (match-end 0) pos))))
5812 (eq org-cycle-emulate-tab t))
5813 (call-interactively (global-key-binding "\t")))
5815 (t (save-excursion
5816 (org-back-to-heading)
5817 (org-cycle)))))))
5819 (defun org-cycle-internal-global ()
5820 "Do the global cycling action."
5821 (cond
5822 ((and (eq last-command this-command)
5823 (eq org-cycle-global-status 'overview))
5824 ;; We just created the overview - now do table of contents
5825 ;; This can be slow in very large buffers, so indicate action
5826 (run-hook-with-args 'org-pre-cycle-hook 'contents)
5827 (message "CONTENTS...")
5828 (org-content)
5829 (message "CONTENTS...done")
5830 (setq org-cycle-global-status 'contents)
5831 (run-hook-with-args 'org-cycle-hook 'contents))
5833 ((and (eq last-command this-command)
5834 (eq org-cycle-global-status 'contents))
5835 ;; We just showed the table of contents - now show everything
5836 (run-hook-with-args 'org-pre-cycle-hook 'all)
5837 (show-all)
5838 (message "SHOW ALL")
5839 (setq org-cycle-global-status 'all)
5840 (run-hook-with-args 'org-cycle-hook 'all))
5843 ;; Default action: go to overview
5844 (run-hook-with-args 'org-pre-cycle-hook 'overview)
5845 (org-overview)
5846 (message "OVERVIEW")
5847 (setq org-cycle-global-status 'overview)
5848 (run-hook-with-args 'org-cycle-hook 'overview))))
5850 (defun org-cycle-internal-local ()
5851 "Do the local cycling action."
5852 (org-back-to-heading)
5853 (let ((goal-column 0) eoh eol eos level has-children children-skipped)
5854 ;; First, some boundaries
5855 (save-excursion
5856 (org-back-to-heading)
5857 (setq level (funcall outline-level))
5858 (save-excursion
5859 (beginning-of-line 2)
5860 (if (or (featurep 'xemacs) (<= emacs-major-version 21))
5861 ; XEmacs does not have `next-single-char-property-change'
5862 ; I'm not sure about Emacs 21.
5863 (while (and (not (eobp)) ;; this is like `next-line'
5864 (get-char-property (1- (point)) 'invisible))
5865 (beginning-of-line 2))
5866 (while (and (not (eobp)) ;; this is like `next-line'
5867 (get-char-property (1- (point)) 'invisible))
5868 (goto-char (next-single-char-property-change (point) 'invisible))
5869 (and (eolp) (beginning-of-line 2))))
5870 (setq eol (point)))
5871 (outline-end-of-heading) (setq eoh (point))
5872 (save-excursion
5873 (outline-next-heading)
5874 (setq has-children (and (org-at-heading-p t)
5875 (> (funcall outline-level) level))))
5876 (org-end-of-subtree t)
5877 (unless (eobp)
5878 (skip-chars-forward " \t\n")
5879 (beginning-of-line 1) ; in case this is an item
5881 (setq eos (if (eobp) (point) (1- (point)))))
5882 ;; Find out what to do next and set `this-command'
5883 (cond
5884 ((= eos eoh)
5885 ;; Nothing is hidden behind this heading
5886 (run-hook-with-args 'org-pre-cycle-hook 'empty)
5887 (message "EMPTY ENTRY")
5888 (setq org-cycle-subtree-status nil)
5889 (save-excursion
5890 (goto-char eos)
5891 (outline-next-heading)
5892 (if (org-invisible-p) (org-flag-heading nil))))
5893 ((and (or (>= eol eos)
5894 (not (string-match "\\S-" (buffer-substring eol eos))))
5895 (or has-children
5896 (not (setq children-skipped
5897 org-cycle-skip-children-state-if-no-children))))
5898 ;; Entire subtree is hidden in one line: children view
5899 (run-hook-with-args 'org-pre-cycle-hook 'children)
5900 (org-show-entry)
5901 (show-children)
5902 (message "CHILDREN")
5903 (save-excursion
5904 (goto-char eos)
5905 (outline-next-heading)
5906 (if (org-invisible-p) (org-flag-heading nil)))
5907 (setq org-cycle-subtree-status 'children)
5908 (run-hook-with-args 'org-cycle-hook 'children))
5909 ((or children-skipped
5910 (and (eq last-command this-command)
5911 (eq org-cycle-subtree-status 'children)))
5912 ;; We just showed the children, or no children are there,
5913 ;; now show everything.
5914 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
5915 (org-show-subtree)
5916 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
5917 (setq org-cycle-subtree-status 'subtree)
5918 (run-hook-with-args 'org-cycle-hook 'subtree))
5920 ;; Default action: hide the subtree.
5921 (run-hook-with-args 'org-pre-cycle-hook 'folded)
5922 (hide-subtree)
5923 (message "FOLDED")
5924 (setq org-cycle-subtree-status 'folded)
5925 (run-hook-with-args 'org-cycle-hook 'folded)))))
5927 ;;;###autoload
5928 (defun org-global-cycle (&optional arg)
5929 "Cycle the global visibility. For details see `org-cycle'.
5930 With \\[universal-argument] prefix arg, switch to startup visibility.
5931 With a numeric prefix, show all headlines up to that level."
5932 (interactive "P")
5933 (let ((org-cycle-include-plain-lists
5934 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5935 (cond
5936 ((integerp arg)
5937 (show-all)
5938 (hide-sublevels arg)
5939 (setq org-cycle-global-status 'contents))
5940 ((equal arg '(4))
5941 (org-set-startup-visibility)
5942 (message "Startup visibility, plus VISIBILITY properties."))
5944 (org-cycle '(4))))))
5946 (defun org-set-startup-visibility ()
5947 "Set the visibility required by startup options and properties."
5948 (cond
5949 ((eq org-startup-folded t)
5950 (org-cycle '(4)))
5951 ((eq org-startup-folded 'content)
5952 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5953 (org-cycle '(4)) (org-cycle '(4)))))
5954 (unless (eq org-startup-folded 'showeverything)
5955 (if org-hide-block-startup (org-hide-block-all))
5956 (org-set-visibility-according-to-property 'no-cleanup)
5957 (org-cycle-hide-archived-subtrees 'all)
5958 (org-cycle-hide-drawers 'all)
5959 (org-cycle-show-empty-lines t)))
5961 (defun org-set-visibility-according-to-property (&optional no-cleanup)
5962 "Switch subtree visibilities according to :VISIBILITY: property."
5963 (interactive)
5964 (let (org-show-entry-below state)
5965 (save-excursion
5966 (goto-char (point-min))
5967 (while (re-search-forward
5968 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
5969 nil t)
5970 (setq state (match-string 1))
5971 (save-excursion
5972 (org-back-to-heading t)
5973 (hide-subtree)
5974 (org-reveal)
5975 (cond
5976 ((equal state '("fold" "folded"))
5977 (hide-subtree))
5978 ((equal state "children")
5979 (org-show-hidden-entry)
5980 (show-children))
5981 ((equal state "content")
5982 (save-excursion
5983 (save-restriction
5984 (org-narrow-to-subtree)
5985 (org-content))))
5986 ((member state '("all" "showall"))
5987 (show-subtree)))))
5988 (unless no-cleanup
5989 (org-cycle-hide-archived-subtrees 'all)
5990 (org-cycle-hide-drawers 'all)
5991 (org-cycle-show-empty-lines 'all)))))
5993 (defun org-overview ()
5994 "Switch to overview mode, showing only top-level headlines.
5995 Really, this shows all headlines with level equal or greater than the level
5996 of the first headline in the buffer. This is important, because if the
5997 first headline is not level one, then (hide-sublevels 1) gives confusing
5998 results."
5999 (interactive)
6000 (let ((level (save-excursion
6001 (goto-char (point-min))
6002 (if (re-search-forward (concat "^" outline-regexp) nil t)
6003 (progn
6004 (goto-char (match-beginning 0))
6005 (funcall outline-level))))))
6006 (and level (hide-sublevels level))))
6008 (defun org-content (&optional arg)
6009 "Show all headlines in the buffer, like a table of contents.
6010 With numerical argument N, show content up to level N."
6011 (interactive "P")
6012 (save-excursion
6013 ;; Visit all headings and show their offspring
6014 (and (integerp arg) (org-overview))
6015 (goto-char (point-max))
6016 (catch 'exit
6017 (while (and (progn (condition-case nil
6018 (outline-previous-visible-heading 1)
6019 (error (goto-char (point-min))))
6021 (looking-at outline-regexp))
6022 (if (integerp arg)
6023 (show-children (1- arg))
6024 (show-branches))
6025 (if (bobp) (throw 'exit nil))))))
6028 (defun org-optimize-window-after-visibility-change (state)
6029 "Adjust the window after a change in outline visibility.
6030 This function is the default value of the hook `org-cycle-hook'."
6031 (when (get-buffer-window (current-buffer))
6032 (cond
6033 ((eq state 'content) nil)
6034 ((eq state 'all) nil)
6035 ((eq state 'folded) nil)
6036 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6037 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6039 (defun org-remove-empty-overlays-at (pos)
6040 "Remove outline overlays that do not contain non-white stuff."
6041 (mapc
6042 (lambda (o)
6043 (and (eq 'outline (overlay-get o 'invisible))
6044 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6045 (overlay-end o))))
6046 (delete-overlay o)))
6047 (overlays-at pos)))
6049 (defun org-clean-visibility-after-subtree-move ()
6050 "Fix visibility issues after moving a subtree."
6051 ;; First, find a reasonable region to look at:
6052 ;; Start two siblings above, end three below
6053 (let* ((beg (save-excursion
6054 (and (org-get-last-sibling)
6055 (org-get-last-sibling))
6056 (point)))
6057 (end (save-excursion
6058 (and (org-get-next-sibling)
6059 (org-get-next-sibling)
6060 (org-get-next-sibling))
6061 (if (org-at-heading-p)
6062 (point-at-eol)
6063 (point))))
6064 (level (looking-at "\\*+"))
6065 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6066 (save-excursion
6067 (save-restriction
6068 (narrow-to-region beg end)
6069 (when re
6070 ;; Properly fold already folded siblings
6071 (goto-char (point-min))
6072 (while (re-search-forward re nil t)
6073 (if (and (not (org-invisible-p))
6074 (save-excursion
6075 (goto-char (point-at-eol)) (org-invisible-p)))
6076 (hide-entry))))
6077 (org-cycle-show-empty-lines 'overview)
6078 (org-cycle-hide-drawers 'overview)))))
6080 (defun org-cycle-show-empty-lines (state)
6081 "Show empty lines above all visible headlines.
6082 The region to be covered depends on STATE when called through
6083 `org-cycle-hook'. Lisp program can use t for STATE to get the
6084 entire buffer covered. Note that an empty line is only shown if there
6085 are at least `org-cycle-separator-lines' empty lines before the headline."
6086 (when (not (= org-cycle-separator-lines 0))
6087 (save-excursion
6088 (let* ((n (abs org-cycle-separator-lines))
6089 (re (cond
6090 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6091 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6092 (t (let ((ns (number-to-string (- n 2))))
6093 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6094 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6095 beg end b e)
6096 (cond
6097 ((memq state '(overview contents t))
6098 (setq beg (point-min) end (point-max)))
6099 ((memq state '(children folded))
6100 (setq beg (point) end (progn (org-end-of-subtree t t)
6101 (beginning-of-line 2)
6102 (point)))))
6103 (when beg
6104 (goto-char beg)
6105 (while (re-search-forward re end t)
6106 (unless (get-char-property (match-end 1) 'invisible)
6107 (setq e (match-end 1))
6108 (if (< org-cycle-separator-lines 0)
6109 (setq b (save-excursion
6110 (goto-char (match-beginning 0))
6111 (org-back-over-empty-lines)
6112 (if (save-excursion
6113 (goto-char (max (point-min) (1- (point))))
6114 (org-on-heading-p))
6115 (1- (point))
6116 (point))))
6117 (setq b (match-beginning 1)))
6118 (outline-flag-region b e nil)))))))
6119 ;; Never hide empty lines at the end of the file.
6120 (save-excursion
6121 (goto-char (point-max))
6122 (outline-previous-heading)
6123 (outline-end-of-heading)
6124 (if (and (looking-at "[ \t\n]+")
6125 (= (match-end 0) (point-max)))
6126 (outline-flag-region (point) (match-end 0) nil))))
6128 (defun org-show-empty-lines-in-parent ()
6129 "Move to the parent and re-show empty lines before visible headlines."
6130 (save-excursion
6131 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6132 (org-cycle-show-empty-lines context))))
6134 (defun org-files-list ()
6135 "Return `org-agenda-files' list, plus all open org-mode files.
6136 This is useful for operations that need to scan all of a user's
6137 open and agenda-wise Org files."
6138 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6139 (dolist (buf (buffer-list))
6140 (with-current-buffer buf
6141 (if (and (eq major-mode 'org-mode) (buffer-file-name))
6142 (let ((file (expand-file-name (buffer-file-name))))
6143 (unless (member file files)
6144 (push file files))))))
6145 files))
6147 (defsubst org-entry-beginning-position ()
6148 "Return the beginning position of the current entry."
6149 (save-excursion (outline-back-to-heading t) (point)))
6151 (defsubst org-entry-end-position ()
6152 "Return the end position of the current entry."
6153 (save-excursion (outline-next-heading) (point)))
6155 (defun org-cycle-hide-drawers (state)
6156 "Re-hide all drawers after a visibility state change."
6157 (when (and (org-mode-p)
6158 (not (memq state '(overview folded contents))))
6159 (save-excursion
6160 (let* ((globalp (memq state '(contents all)))
6161 (beg (if globalp (point-min) (point)))
6162 (end (if globalp (point-max)
6163 (if (eq state 'children)
6164 (save-excursion (outline-next-heading) (point))
6165 (org-end-of-subtree t)))))
6166 (goto-char beg)
6167 (while (re-search-forward org-drawer-regexp end t)
6168 (org-flag-drawer t))))))
6170 (defun org-flag-drawer (flag)
6171 (save-excursion
6172 (beginning-of-line 1)
6173 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6174 (let ((b (match-end 0))
6175 (outline-regexp org-outline-regexp))
6176 (if (re-search-forward
6177 "^[ \t]*:END:"
6178 (save-excursion (outline-next-heading) (point)) t)
6179 (outline-flag-region b (point-at-eol) flag)
6180 (error ":END: line missing at position %s" b))))))
6182 (defun org-subtree-end-visible-p ()
6183 "Is the end of the current subtree visible?"
6184 (pos-visible-in-window-p
6185 (save-excursion (org-end-of-subtree t) (point))))
6187 (defun org-first-headline-recenter (&optional N)
6188 "Move cursor to the first headline and recenter the headline.
6189 Optional argument N means put the headline into the Nth line of the window."
6190 (goto-char (point-min))
6191 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
6192 (beginning-of-line)
6193 (recenter (prefix-numeric-value N))))
6195 ;;; Saving and restoring visibility
6197 (defun org-outline-overlay-data (&optional use-markers)
6198 "Return a list of the locations of all outline overlays.
6199 The are overlays with the `invisible' property value `outline'.
6200 The return values is a list of cons cells, with start and stop
6201 positions for each overlay.
6202 If USE-MARKERS is set, return the positions as markers."
6203 (let (beg end)
6204 (save-excursion
6205 (save-restriction
6206 (widen)
6207 (delq nil
6208 (mapcar (lambda (o)
6209 (when (eq (overlay-get o 'invisible) 'outline)
6210 (setq beg (overlay-start o)
6211 end (overlay-end o))
6212 (and beg end (> end beg)
6213 (if use-markers
6214 (cons (move-marker (make-marker) beg)
6215 (move-marker (make-marker) end))
6216 (cons beg end)))))
6217 (overlays-in (point-min) (point-max))))))))
6219 (defun org-set-outline-overlay-data (data)
6220 "Create visibility overlays for all positions in DATA.
6221 DATA should have been made by `org-outline-overlay-data'."
6222 (let (o)
6223 (save-excursion
6224 (save-restriction
6225 (widen)
6226 (show-all)
6227 (mapc (lambda (c)
6228 (setq o (make-overlay (car c) (cdr c)))
6229 (overlay-put o 'invisible 'outline))
6230 data)))))
6232 (defmacro org-save-outline-visibility (use-markers &rest body)
6233 "Save and restore outline visibility around BODY.
6234 If USE-MARKERS is non-nil, use markers for the positions.
6235 This means that the buffer may change while running BODY,
6236 but it also means that the buffer should stay alive
6237 during the operation, because otherwise all these markers will
6238 point nowhere."
6239 (declare (indent 1))
6240 `(let ((data (org-outline-overlay-data ,use-markers)))
6241 (unwind-protect
6242 (progn
6243 ,@body
6244 (org-set-outline-overlay-data data))
6245 (when ,use-markers
6246 (mapc (lambda (c)
6247 (and (markerp (car c)) (move-marker (car c) nil))
6248 (and (markerp (cdr c)) (move-marker (cdr c) nil)))
6249 data)))))
6252 ;;; Folding of blocks
6254 (defconst org-block-regexp
6256 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
6257 "Regular expression for hiding blocks.")
6259 (defvar org-hide-block-overlays nil
6260 "Overlays hiding blocks.")
6261 (make-variable-buffer-local 'org-hide-block-overlays)
6263 (defun org-block-map (function &optional start end)
6264 "Call FUNCTION at the head of all source blocks in the current buffer.
6265 Optional arguments START and END can be used to limit the range."
6266 (let ((start (or start (point-min)))
6267 (end (or end (point-max))))
6268 (save-excursion
6269 (goto-char start)
6270 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6271 (save-excursion
6272 (save-match-data
6273 (goto-char (match-beginning 0))
6274 (funcall function)))))))
6276 (defun org-hide-block-toggle-all ()
6277 "Toggle the visibility of all blocks in the current buffer."
6278 (org-block-map #'org-hide-block-toggle))
6280 (defun org-hide-block-all ()
6281 "Fold all blocks in the current buffer."
6282 (interactive)
6283 (org-show-block-all)
6284 (org-block-map #'org-hide-block-toggle-maybe))
6286 (defun org-show-block-all ()
6287 "Unfold all blocks in the current buffer."
6288 (interactive)
6289 (mapc 'delete-overlay org-hide-block-overlays)
6290 (setq org-hide-block-overlays nil))
6292 (defun org-hide-block-toggle-maybe ()
6293 "Toggle visibility of block at point."
6294 (interactive)
6295 (let ((case-fold-search t))
6296 (if (save-excursion
6297 (beginning-of-line 1)
6298 (looking-at org-block-regexp))
6299 (progn (org-hide-block-toggle)
6300 t) ;; to signal that we took action
6301 nil))) ;; to signal that we did not
6303 (defun org-hide-block-toggle (&optional force)
6304 "Toggle the visibility of the current block."
6305 (interactive)
6306 (save-excursion
6307 (beginning-of-line)
6308 (if (re-search-forward org-block-regexp nil t)
6309 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6310 (end (match-end 0)) ;; end of entire body
6312 (if (memq t (mapcar (lambda (overlay)
6313 (eq (overlay-get overlay 'invisible)
6314 'org-hide-block))
6315 (overlays-at start)))
6316 (if (or (not force) (eq force 'off))
6317 (mapc (lambda (ov)
6318 (when (member ov org-hide-block-overlays)
6319 (setq org-hide-block-overlays
6320 (delq ov org-hide-block-overlays)))
6321 (when (eq (overlay-get ov 'invisible)
6322 'org-hide-block)
6323 (delete-overlay ov)))
6324 (overlays-at start)))
6325 (setq ov (make-overlay start end))
6326 (overlay-put ov 'invisible 'org-hide-block)
6327 ;; make the block accessible to isearch
6328 (overlay-put
6329 ov 'isearch-open-invisible
6330 (lambda (ov)
6331 (when (member ov org-hide-block-overlays)
6332 (setq org-hide-block-overlays
6333 (delq ov org-hide-block-overlays)))
6334 (when (eq (overlay-get ov 'invisible)
6335 'org-hide-block)
6336 (delete-overlay ov))))
6337 (push ov org-hide-block-overlays)))
6338 (error "Not looking at a source block"))))
6340 ;; org-tab-after-check-for-cycling-hook
6341 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6342 ;; Remove overlays when changing major mode
6343 (add-hook 'org-mode-hook
6344 (lambda () (org-add-hook 'change-major-mode-hook
6345 'org-show-block-all 'append 'local)))
6347 ;;; Org-goto
6349 (defvar org-goto-window-configuration nil)
6350 (defvar org-goto-marker nil)
6351 (defvar org-goto-map
6352 (let ((map (make-sparse-keymap)))
6353 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6354 (while (setq cmd (pop cmds))
6355 (substitute-key-definition cmd cmd map global-map)))
6356 (suppress-keymap map)
6357 (org-defkey map "\C-m" 'org-goto-ret)
6358 (org-defkey map [(return)] 'org-goto-ret)
6359 (org-defkey map [(left)] 'org-goto-left)
6360 (org-defkey map [(right)] 'org-goto-right)
6361 (org-defkey map [(control ?g)] 'org-goto-quit)
6362 (org-defkey map "\C-i" 'org-cycle)
6363 (org-defkey map [(tab)] 'org-cycle)
6364 (org-defkey map [(down)] 'outline-next-visible-heading)
6365 (org-defkey map [(up)] 'outline-previous-visible-heading)
6366 (if org-goto-auto-isearch
6367 (if (fboundp 'define-key-after)
6368 (define-key-after map [t] 'org-goto-local-auto-isearch)
6369 nil)
6370 (org-defkey map "q" 'org-goto-quit)
6371 (org-defkey map "n" 'outline-next-visible-heading)
6372 (org-defkey map "p" 'outline-previous-visible-heading)
6373 (org-defkey map "f" 'outline-forward-same-level)
6374 (org-defkey map "b" 'outline-backward-same-level)
6375 (org-defkey map "u" 'outline-up-heading))
6376 (org-defkey map "/" 'org-occur)
6377 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6378 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6379 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6380 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6381 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6382 map))
6384 (defconst org-goto-help
6385 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6386 RET=jump to location [Q]uit and return to previous location
6387 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6389 (defvar org-goto-start-pos) ; dynamically scoped parameter
6391 ;; FIXME: Docstring does not mention both interfaces
6392 (defun org-goto (&optional alternative-interface)
6393 "Look up a different location in the current file, keeping current visibility.
6395 When you want look-up or go to a different location in a document, the
6396 fastest way is often to fold the entire buffer and then dive into the tree.
6397 This method has the disadvantage, that the previous location will be folded,
6398 which may not be what you want.
6400 This command works around this by showing a copy of the current buffer
6401 in an indirect buffer, in overview mode. You can dive into the tree in
6402 that copy, use org-occur and incremental search to find a location.
6403 When pressing RET or `Q', the command returns to the original buffer in
6404 which the visibility is still unchanged. After RET is will also jump to
6405 the location selected in the indirect buffer and expose the
6406 the headline hierarchy above."
6407 (interactive "P")
6408 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6409 (org-refile-use-outline-path t)
6410 (org-refile-target-verify-function nil)
6411 (interface
6412 (if (not alternative-interface)
6413 org-goto-interface
6414 (if (eq org-goto-interface 'outline)
6415 'outline-path-completion
6416 'outline)))
6417 (org-goto-start-pos (point))
6418 (selected-point
6419 (if (eq interface 'outline)
6420 (car (org-get-location (current-buffer) org-goto-help))
6421 (nth 3 (org-refile-get-location "Goto: ")))))
6422 (if selected-point
6423 (progn
6424 (org-mark-ring-push org-goto-start-pos)
6425 (goto-char selected-point)
6426 (if (or (org-invisible-p) (org-invisible-p2))
6427 (org-show-context 'org-goto)))
6428 (message "Quit"))))
6430 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6431 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6432 (defvar org-goto-local-auto-isearch-map) ; defined below
6434 (defun org-get-location (buf help)
6435 "Let the user select a location in the Org-mode buffer BUF.
6436 This function uses a recursive edit. It returns the selected position
6437 or nil."
6438 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6439 (isearch-hide-immediately nil)
6440 (isearch-search-fun-function
6441 (lambda () 'org-goto-local-search-headings))
6442 (org-goto-selected-point org-goto-exit-command)
6443 (pop-up-frames nil)
6444 (special-display-buffer-names nil)
6445 (special-display-regexps nil)
6446 (special-display-function nil))
6447 (save-excursion
6448 (save-window-excursion
6449 (delete-other-windows)
6450 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6451 (switch-to-buffer
6452 (condition-case nil
6453 (make-indirect-buffer (current-buffer) "*org-goto*")
6454 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6455 (with-output-to-temp-buffer "*Help*"
6456 (princ help))
6457 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6458 (setq buffer-read-only nil)
6459 (let ((org-startup-truncated t)
6460 (org-startup-folded nil)
6461 (org-startup-align-all-tables nil))
6462 (org-mode)
6463 (org-overview))
6464 (setq buffer-read-only t)
6465 (if (and (boundp 'org-goto-start-pos)
6466 (integer-or-marker-p org-goto-start-pos))
6467 (let ((org-show-hierarchy-above t)
6468 (org-show-siblings t)
6469 (org-show-following-heading t))
6470 (goto-char org-goto-start-pos)
6471 (and (org-invisible-p) (org-show-context)))
6472 (goto-char (point-min)))
6473 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6474 (message "Select location and press RET")
6475 (use-local-map org-goto-map)
6476 (recursive-edit)
6478 (kill-buffer "*org-goto*")
6479 (cons org-goto-selected-point org-goto-exit-command)))
6481 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6482 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6483 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6484 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6486 (defun org-goto-local-search-headings (string bound noerror)
6487 "Search and make sure that any matches are in headlines."
6488 (catch 'return
6489 (while (if isearch-forward
6490 (search-forward string bound noerror)
6491 (search-backward string bound noerror))
6492 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6493 (and (member :headline context)
6494 (not (member :tags context))))
6495 (throw 'return (point))))))
6497 (defun org-goto-local-auto-isearch ()
6498 "Start isearch."
6499 (interactive)
6500 (goto-char (point-min))
6501 (let ((keys (this-command-keys)))
6502 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6503 (isearch-mode t)
6504 (isearch-process-search-char (string-to-char keys)))))
6506 (defun org-goto-ret (&optional arg)
6507 "Finish `org-goto' by going to the new location."
6508 (interactive "P")
6509 (setq org-goto-selected-point (point)
6510 org-goto-exit-command 'return)
6511 (throw 'exit nil))
6513 (defun org-goto-left ()
6514 "Finish `org-goto' by going to the new location."
6515 (interactive)
6516 (if (org-on-heading-p)
6517 (progn
6518 (beginning-of-line 1)
6519 (setq org-goto-selected-point (point)
6520 org-goto-exit-command 'left)
6521 (throw 'exit nil))
6522 (error "Not on a heading")))
6524 (defun org-goto-right ()
6525 "Finish `org-goto' by going to the new location."
6526 (interactive)
6527 (if (org-on-heading-p)
6528 (progn
6529 (setq org-goto-selected-point (point)
6530 org-goto-exit-command 'right)
6531 (throw 'exit nil))
6532 (error "Not on a heading")))
6534 (defun org-goto-quit ()
6535 "Finish `org-goto' without cursor motion."
6536 (interactive)
6537 (setq org-goto-selected-point nil)
6538 (setq org-goto-exit-command 'quit)
6539 (throw 'exit nil))
6541 ;;; Indirect buffer display of subtrees
6543 (defvar org-indirect-dedicated-frame nil
6544 "This is the frame being used for indirect tree display.")
6545 (defvar org-last-indirect-buffer nil)
6547 (defun org-tree-to-indirect-buffer (&optional arg)
6548 "Create indirect buffer and narrow it to current subtree.
6549 With numerical prefix ARG, go up to this level and then take that tree.
6550 If ARG is negative, go up that many levels.
6551 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6552 indirect buffer previously made with this command, to avoid proliferation of
6553 indirect buffers. However, when you call the command with a \
6554 \\[universal-argument] prefix, or
6555 when `org-indirect-buffer-display' is `new-frame', the last buffer
6556 is kept so that you can work with several indirect buffers at the same time.
6557 If `org-indirect-buffer-display' is `dedicated-frame', the \
6558 \\[universal-argument] prefix also
6559 requests that a new frame be made for the new buffer, so that the dedicated
6560 frame is not changed."
6561 (interactive "P")
6562 (let ((cbuf (current-buffer))
6563 (cwin (selected-window))
6564 (pos (point))
6565 beg end level heading ibuf)
6566 (save-excursion
6567 (org-back-to-heading t)
6568 (when (numberp arg)
6569 (setq level (org-outline-level))
6570 (if (< arg 0) (setq arg (+ level arg)))
6571 (while (> (setq level (org-outline-level)) arg)
6572 (outline-up-heading 1 t)))
6573 (setq beg (point)
6574 heading (org-get-heading))
6575 (org-end-of-subtree t t)
6576 (if (org-on-heading-p) (backward-char 1))
6577 (setq end (point)))
6578 (if (and (buffer-live-p org-last-indirect-buffer)
6579 (not (eq org-indirect-buffer-display 'new-frame))
6580 (not arg))
6581 (kill-buffer org-last-indirect-buffer))
6582 (setq ibuf (org-get-indirect-buffer cbuf)
6583 org-last-indirect-buffer ibuf)
6584 (cond
6585 ((or (eq org-indirect-buffer-display 'new-frame)
6586 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6587 (select-frame (make-frame))
6588 (delete-other-windows)
6589 (switch-to-buffer ibuf)
6590 (org-set-frame-title heading))
6591 ((eq org-indirect-buffer-display 'dedicated-frame)
6592 (raise-frame
6593 (select-frame (or (and org-indirect-dedicated-frame
6594 (frame-live-p org-indirect-dedicated-frame)
6595 org-indirect-dedicated-frame)
6596 (setq org-indirect-dedicated-frame (make-frame)))))
6597 (delete-other-windows)
6598 (switch-to-buffer ibuf)
6599 (org-set-frame-title (concat "Indirect: " heading)))
6600 ((eq org-indirect-buffer-display 'current-window)
6601 (switch-to-buffer ibuf))
6602 ((eq org-indirect-buffer-display 'other-window)
6603 (pop-to-buffer ibuf))
6604 (t (error "Invalid value")))
6605 (if (featurep 'xemacs)
6606 (save-excursion (org-mode) (turn-on-font-lock)))
6607 (narrow-to-region beg end)
6608 (show-all)
6609 (goto-char pos)
6610 (and (window-live-p cwin) (select-window cwin))))
6612 (defun org-get-indirect-buffer (&optional buffer)
6613 (setq buffer (or buffer (current-buffer)))
6614 (let ((n 1) (base (buffer-name buffer)) bname)
6615 (while (buffer-live-p
6616 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6617 (setq n (1+ n)))
6618 (condition-case nil
6619 (make-indirect-buffer buffer bname 'clone)
6620 (error (make-indirect-buffer buffer bname)))))
6622 (defun org-set-frame-title (title)
6623 "Set the title of the current frame to the string TITLE."
6624 ;; FIXME: how to name a single frame in XEmacs???
6625 (unless (featurep 'xemacs)
6626 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6628 ;;;; Structure editing
6630 ;;; Inserting headlines
6632 (defun org-previous-line-empty-p ()
6633 (save-excursion
6634 (and (not (bobp))
6635 (or (beginning-of-line 0) t)
6636 (save-match-data
6637 (looking-at "[ \t]*$")))))
6639 (defun org-insert-heading (&optional force-heading invisible-ok)
6640 "Insert a new heading or item with same depth at point.
6641 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6642 If point is at the beginning of a headline, insert a sibling before the
6643 current headline. If point is not at the beginning, do not split the line,
6644 but create the new headline after the current line.
6645 When INVISIBLE-OK is set, stop at invisible headlines when going back.
6646 This is important for non-interactive uses of the command."
6647 (interactive "P")
6648 (if (or (= (buffer-size) 0)
6649 (and (not (save-excursion (and (ignore-errors (org-back-to-heading invisible-ok))
6650 (org-on-heading-p))))
6651 (not (org-in-item-p))))
6652 (insert "\n* ")
6653 (when (or force-heading (not (org-insert-item)))
6654 (let* ((empty-line-p nil)
6655 (head (save-excursion
6656 (condition-case nil
6657 (progn
6658 (org-back-to-heading invisible-ok)
6659 (setq empty-line-p (org-previous-line-empty-p))
6660 (match-string 0))
6661 (error "*"))))
6662 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
6663 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
6664 pos hide-previous previous-pos)
6665 (cond
6666 ((and (org-on-heading-p) (bolp)
6667 (or (bobp)
6668 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6669 ;; insert before the current line
6670 (open-line (if blank 2 1)))
6671 ((and (bolp)
6672 (not org-insert-heading-respect-content)
6673 (or (bobp)
6674 (save-excursion
6675 (backward-char 1) (not (org-invisible-p)))))
6676 ;; insert right here
6677 nil)
6679 ;; somewhere in the line
6680 (save-excursion
6681 (setq previous-pos (point-at-bol))
6682 (end-of-line)
6683 (setq hide-previous (org-invisible-p)))
6684 (and org-insert-heading-respect-content (org-show-subtree))
6685 (let ((split
6686 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
6687 (save-excursion
6688 (let ((p (point)))
6689 (goto-char (point-at-bol))
6690 (and (looking-at org-complex-heading-regexp)
6691 (> p (match-beginning 4)))))))
6692 tags pos)
6693 (cond
6694 (org-insert-heading-respect-content
6695 (org-end-of-subtree nil t)
6696 (or (bolp) (newline))
6697 (or (org-previous-line-empty-p)
6698 (and blank (newline)))
6699 (open-line 1))
6700 ((org-on-heading-p)
6701 (when hide-previous
6702 (show-children)
6703 (org-show-entry))
6704 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6705 (setq tags (and (match-end 2) (match-string 2)))
6706 (and (match-end 1)
6707 (delete-region (match-beginning 1) (match-end 1)))
6708 (setq pos (point-at-bol))
6709 (or split (end-of-line 1))
6710 (delete-horizontal-space)
6711 (if (string-match "\\`\\*+\\'"
6712 (buffer-substring (point-at-bol) (point)))
6713 (insert " "))
6714 (newline (if blank 2 1))
6715 (when tags
6716 (save-excursion
6717 (goto-char pos)
6718 (end-of-line 1)
6719 (insert " " tags)
6720 (org-set-tags nil 'align))))
6722 (or split (end-of-line 1))
6723 (newline (if blank 2 1)))))))
6724 (insert head) (just-one-space)
6725 (setq pos (point))
6726 (end-of-line 1)
6727 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6728 (when (and org-insert-heading-respect-content hide-previous)
6729 (save-excursion
6730 (goto-char previous-pos)
6731 (hide-subtree)))
6732 (run-hooks 'org-insert-heading-hook)))))
6734 (defun org-get-heading (&optional no-tags)
6735 "Return the heading of the current entry, without the stars."
6736 (save-excursion
6737 (org-back-to-heading t)
6738 (if (looking-at
6739 (if no-tags
6740 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
6741 "\\*+[ \t]+\\([^\r\n]*\\)"))
6742 (match-string 1) "")))
6744 (defun org-heading-components ()
6745 "Return the components of the current heading.
6746 This is a list with the following elements:
6747 - the level as an integer
6748 - the reduced level, different if `org-odd-levels-only' is set.
6749 - the TODO keyword, or nil
6750 - the priority character, like ?A, or nil if no priority is given
6751 - the headline text itself, or the tags string if no headline text
6752 - the tags string, or nil."
6753 (save-excursion
6754 (org-back-to-heading t)
6755 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
6756 (list (length (match-string 1))
6757 (org-reduced-level (length (match-string 1)))
6758 (org-match-string-no-properties 2)
6759 (and (match-end 3) (aref (match-string 3) 2))
6760 (org-match-string-no-properties 4)
6761 (org-match-string-no-properties 5)))))
6763 (defun org-get-entry ()
6764 "Get the entry text, after heading, entire subtree."
6765 (save-excursion
6766 (org-back-to-heading t)
6767 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
6769 (defun org-insert-heading-after-current ()
6770 "Insert a new heading with same level as current, after current subtree."
6771 (interactive)
6772 (org-back-to-heading)
6773 (org-insert-heading)
6774 (org-move-subtree-down)
6775 (end-of-line 1))
6777 (defun org-insert-heading-respect-content ()
6778 (interactive)
6779 (let ((org-insert-heading-respect-content t))
6780 (org-insert-heading t)))
6782 (defun org-insert-todo-heading-respect-content (&optional force-state)
6783 (interactive "P")
6784 (let ((org-insert-heading-respect-content t))
6785 (org-insert-todo-heading force-state t)))
6787 (defun org-insert-todo-heading (arg &optional force-heading)
6788 "Insert a new heading with the same level and TODO state as current heading.
6789 If the heading has no TODO state, or if the state is DONE, use the first
6790 state (TODO by default). Also with prefix arg, force first state."
6791 (interactive "P")
6792 (when (or force-heading (not (org-insert-item 'checkbox)))
6793 (org-insert-heading force-heading)
6794 (save-excursion
6795 (org-back-to-heading)
6796 (outline-previous-heading)
6797 (looking-at org-todo-line-regexp))
6798 (let*
6799 ((new-mark-x
6800 (if (or arg
6801 (not (match-beginning 2))
6802 (member (match-string 2) org-done-keywords))
6803 (car org-todo-keywords-1)
6804 (match-string 2)))
6805 (new-mark
6807 (run-hook-with-args-until-success
6808 'org-todo-get-default-hook new-mark-x nil)
6809 new-mark-x)))
6810 (beginning-of-line 1)
6811 (and (looking-at "\\*+ ") (goto-char (match-end 0))
6812 (if org-treat-insert-todo-heading-as-state-change
6813 (org-todo new-mark)
6814 (insert new-mark " "))))
6815 (when org-provide-todo-statistics
6816 (org-update-parent-todo-statistics))))
6818 (defun org-insert-subheading (arg)
6819 "Insert a new subheading and demote it.
6820 Works for outline headings and for plain lists alike."
6821 (interactive "P")
6822 (org-insert-heading arg)
6823 (cond
6824 ((org-on-heading-p) (org-do-demote))
6825 ((org-at-item-p) (org-indent-item 1))))
6827 (defun org-insert-todo-subheading (arg)
6828 "Insert a new subheading with TODO keyword or checkbox and demote it.
6829 Works for outline headings and for plain lists alike."
6830 (interactive "P")
6831 (org-insert-todo-heading arg)
6832 (cond
6833 ((org-on-heading-p) (org-do-demote))
6834 ((org-at-item-p) (org-indent-item 1))))
6836 ;;; Promotion and Demotion
6838 (defvar org-after-demote-entry-hook nil
6839 "Hook run after an entry has been demoted.
6840 The cursor will be at the beginning of the entry.
6841 When a subtree is being demoted, the hook will be called for each node.")
6843 (defvar org-after-promote-entry-hook nil
6844 "Hook run after an entry has been promoted.
6845 The cursor will be at the beginning of the entry.
6846 When a subtree is being promoted, the hook will be called for each node.")
6848 (defun org-promote-subtree ()
6849 "Promote the entire subtree.
6850 See also `org-promote'."
6851 (interactive)
6852 (save-excursion
6853 (org-map-tree 'org-promote))
6854 (org-fix-position-after-promote))
6856 (defun org-demote-subtree ()
6857 "Demote the entire subtree. See `org-demote'.
6858 See also `org-promote'."
6859 (interactive)
6860 (save-excursion
6861 (org-map-tree 'org-demote))
6862 (org-fix-position-after-promote))
6865 (defun org-do-promote ()
6866 "Promote the current heading higher up the tree.
6867 If the region is active in `transient-mark-mode', promote all headings
6868 in the region."
6869 (interactive)
6870 (save-excursion
6871 (if (org-region-active-p)
6872 (org-map-region 'org-promote (region-beginning) (region-end))
6873 (org-promote)))
6874 (org-fix-position-after-promote))
6876 (defun org-do-demote ()
6877 "Demote the current heading lower down the tree.
6878 If the region is active in `transient-mark-mode', demote all headings
6879 in the region."
6880 (interactive)
6881 (save-excursion
6882 (if (org-region-active-p)
6883 (org-map-region 'org-demote (region-beginning) (region-end))
6884 (org-demote)))
6885 (org-fix-position-after-promote))
6887 (defun org-fix-position-after-promote ()
6888 "Make sure that after pro/demotion cursor position is right."
6889 (let ((pos (point)))
6890 (when (save-excursion
6891 (beginning-of-line 1)
6892 (looking-at org-todo-line-regexp)
6893 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6894 (cond ((eobp) (insert " "))
6895 ((eolp) (insert " "))
6896 ((equal (char-after) ?\ ) (forward-char 1))))))
6898 (defun org-current-level ()
6899 "Return the level of the current entry, or nil if before the first headline.
6900 The level is the number of stars at the beginning of the headline."
6901 (save-excursion
6902 (condition-case nil
6903 (progn
6904 (org-back-to-heading t)
6905 (funcall outline-level))
6906 (error nil))))
6908 (defun org-get-previous-line-level ()
6909 "Return the outline depth of the last headline before the current line.
6910 Returns 0 for the first headline in the buffer, and nil if before the
6911 first headline."
6912 (let ((current-level (org-current-level))
6913 (prev-level (when (> (line-number-at-pos) 1)
6914 (save-excursion
6915 (beginning-of-line 0)
6916 (org-current-level)))))
6917 (cond ((null current-level) nil) ; Before first headline
6918 ((null prev-level) 0) ; At first headline
6919 (prev-level))))
6921 (defun org-reduced-level (l)
6922 "Compute the effective level of a heading.
6923 This takes into account the setting of `org-odd-levels-only'."
6924 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6926 (defun org-level-increment ()
6927 "Return the number of stars that will be added or removed at a
6928 time to headlines when structure editing, based on the value of
6929 `org-odd-levels-only'."
6930 (if org-odd-levels-only 2 1))
6932 (defun org-get-valid-level (level &optional change)
6933 "Rectify a level change under the influence of `org-odd-levels-only'
6934 LEVEL is a current level, CHANGE is by how much the level should be
6935 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6936 even level numbers will become the next higher odd number."
6937 (if org-odd-levels-only
6938 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6939 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6940 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6941 (max 1 (+ level (or change 0)))))
6943 (if (boundp 'define-obsolete-function-alias)
6944 (if (or (featurep 'xemacs) (< emacs-major-version 23))
6945 (define-obsolete-function-alias 'org-get-legal-level
6946 'org-get-valid-level)
6947 (define-obsolete-function-alias 'org-get-legal-level
6948 'org-get-valid-level "23.1")))
6950 (defun org-promote ()
6951 "Promote the current heading higher up the tree.
6952 If the region is active in `transient-mark-mode', promote all headings
6953 in the region."
6954 (org-back-to-heading t)
6955 (let* ((level (save-match-data (funcall outline-level)))
6956 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6957 (diff (abs (- level (length up-head) -1))))
6958 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6959 (replace-match up-head nil t)
6960 ;; Fixup tag positioning
6961 (and org-auto-align-tags (org-set-tags nil t))
6962 (if org-adapt-indentation (org-fixup-indentation (- diff)))
6963 (run-hooks 'org-after-promote-entry-hook)))
6965 (defun org-demote ()
6966 "Demote the current heading lower down the tree.
6967 If the region is active in `transient-mark-mode', demote all headings
6968 in the region."
6969 (org-back-to-heading t)
6970 (let* ((level (save-match-data (funcall outline-level)))
6971 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6972 (diff (abs (- level (length down-head) -1))))
6973 (replace-match down-head nil t)
6974 ;; Fixup tag positioning
6975 (and org-auto-align-tags (org-set-tags nil t))
6976 (if org-adapt-indentation (org-fixup-indentation diff))
6977 (run-hooks 'org-after-demote-entry-hook)))
6979 (defun org-cycle-level ()
6980 "Cycle the level of an empty headline through possible states.
6981 This goes first to child, then to parent, level, then up the hierarchy.
6982 After top level, it switches back to sibling level."
6983 (interactive)
6984 (let ((org-adapt-indentation nil))
6985 (when (org-point-at-end-of-empty-headline)
6986 (setq this-command 'org-cycle-level) ; Only needed for caching
6987 (let ((cur-level (org-current-level))
6988 (prev-level (org-get-previous-line-level)))
6989 (cond
6990 ;; If first headline in file, promote to top-level.
6991 ((= prev-level 0)
6992 (loop repeat (/ (- cur-level 1) (org-level-increment))
6993 do (org-do-promote)))
6994 ;; If same level as prev, demote one.
6995 ((= prev-level cur-level)
6996 (org-do-demote))
6997 ;; If parent is top-level, promote to top level if not already.
6998 ((= prev-level 1)
6999 (loop repeat (/ (- cur-level 1) (org-level-increment))
7000 do (org-do-promote)))
7001 ;; If top-level, return to prev-level.
7002 ((= cur-level 1)
7003 (loop repeat (/ (- prev-level 1) (org-level-increment))
7004 do (org-do-demote)))
7005 ;; If less than prev-level, promote one.
7006 ((< cur-level prev-level)
7007 (org-do-promote))
7008 ;; If deeper than prev-level, promote until higher than
7009 ;; prev-level.
7010 ((> cur-level prev-level)
7011 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7012 do (org-do-promote))))
7013 t))))
7015 (defun org-map-tree (fun)
7016 "Call FUN for every heading underneath the current one."
7017 (org-back-to-heading)
7018 (let ((level (funcall outline-level)))
7019 (save-excursion
7020 (funcall fun)
7021 (while (and (progn
7022 (outline-next-heading)
7023 (> (funcall outline-level) level))
7024 (not (eobp)))
7025 (funcall fun)))))
7027 (defun org-map-region (fun beg end)
7028 "Call FUN for every heading between BEG and END."
7029 (let ((org-ignore-region t))
7030 (save-excursion
7031 (setq end (copy-marker end))
7032 (goto-char beg)
7033 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
7034 (< (point) end))
7035 (funcall fun))
7036 (while (and (progn
7037 (outline-next-heading)
7038 (< (point) end))
7039 (not (eobp)))
7040 (funcall fun)))))
7042 (defun org-fixup-indentation (diff)
7043 "Change the indentation in the current entry by DIFF.
7044 However, if any line in the current entry has no indentation, or if it
7045 would end up with no indentation after the change, nothing at all is done."
7046 (save-excursion
7047 (let ((end (save-excursion (outline-next-heading)
7048 (point-marker)))
7049 (prohibit (if (> diff 0)
7050 "^\\S-"
7051 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7052 col)
7053 (unless (save-excursion (end-of-line 1)
7054 (re-search-forward prohibit end t))
7055 (while (and (< (point) end)
7056 (re-search-forward "^[ \t]+" end t))
7057 (goto-char (match-end 0))
7058 (setq col (current-column))
7059 (if (< diff 0) (replace-match ""))
7060 (org-indent-to-column (+ diff col))))
7061 (move-marker end nil))))
7063 (defun org-convert-to-odd-levels ()
7064 "Convert an org-mode file with all levels allowed to one with odd levels.
7065 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7066 level 5 etc."
7067 (interactive)
7068 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7069 (let ((outline-regexp org-outline-regexp)
7070 (outline-level 'org-outline-level)
7071 (org-odd-levels-only nil) n)
7072 (save-excursion
7073 (goto-char (point-min))
7074 (while (re-search-forward "^\\*\\*+ " nil t)
7075 (setq n (- (length (match-string 0)) 2))
7076 (while (>= (setq n (1- n)) 0)
7077 (org-demote))
7078 (end-of-line 1))))))
7080 (defun org-convert-to-oddeven-levels ()
7081 "Convert an org-mode file with only odd levels to one with odd/even levels.
7082 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7083 file contains a section with an even level, conversion would
7084 destroy the structure of the file. An error is signaled in this
7085 case."
7086 (interactive)
7087 (goto-char (point-min))
7088 ;; First check if there are no even levels
7089 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7090 (org-show-context t)
7091 (error "Not all levels are odd in this file. Conversion not possible"))
7092 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7093 (let ((outline-regexp org-outline-regexp)
7094 (outline-level 'org-outline-level)
7095 (org-odd-levels-only nil) n)
7096 (save-excursion
7097 (goto-char (point-min))
7098 (while (re-search-forward "^\\*\\*+ " nil t)
7099 (setq n (/ (1- (length (match-string 0))) 2))
7100 (while (>= (setq n (1- n)) 0)
7101 (org-promote))
7102 (end-of-line 1))))))
7104 (defun org-tr-level (n)
7105 "Make N odd if required."
7106 (if org-odd-levels-only (1+ (/ n 2)) n))
7108 ;;; Vertical tree motion, cutting and pasting of subtrees
7110 (defun org-move-subtree-up (&optional arg)
7111 "Move the current subtree up past ARG headlines of the same level."
7112 (interactive "p")
7113 (org-move-subtree-down (- (prefix-numeric-value arg))))
7115 (defun org-move-subtree-down (&optional arg)
7116 "Move the current subtree down past ARG headlines of the same level."
7117 (interactive "p")
7118 (setq arg (prefix-numeric-value arg))
7119 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7120 'org-get-last-sibling))
7121 (ins-point (make-marker))
7122 (cnt (abs arg))
7123 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7124 ;; Select the tree
7125 (org-back-to-heading)
7126 (setq beg0 (point))
7127 (save-excursion
7128 (setq ne-beg (org-back-over-empty-lines))
7129 (setq beg (point)))
7130 (save-match-data
7131 (save-excursion (outline-end-of-heading)
7132 (setq folded (org-invisible-p)))
7133 (outline-end-of-subtree))
7134 (outline-next-heading)
7135 (setq ne-end (org-back-over-empty-lines))
7136 (setq end (point))
7137 (goto-char beg0)
7138 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7139 ;; include less whitespace
7140 (save-excursion
7141 (goto-char beg)
7142 (forward-line (- ne-beg ne-end))
7143 (setq beg (point))))
7144 ;; Find insertion point, with error handling
7145 (while (> cnt 0)
7146 (or (and (funcall movfunc) (looking-at outline-regexp))
7147 (progn (goto-char beg0)
7148 (error "Cannot move past superior level or buffer limit")))
7149 (setq cnt (1- cnt)))
7150 (if (> arg 0)
7151 ;; Moving forward - still need to move over subtree
7152 (progn (org-end-of-subtree t t)
7153 (save-excursion
7154 (org-back-over-empty-lines)
7155 (or (bolp) (newline)))))
7156 (setq ne-ins (org-back-over-empty-lines))
7157 (move-marker ins-point (point))
7158 (setq txt (buffer-substring beg end))
7159 (org-save-markers-in-region beg end)
7160 (delete-region beg end)
7161 (org-remove-empty-overlays-at beg)
7162 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7163 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7164 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7165 (let ((bbb (point)))
7166 (insert-before-markers txt)
7167 (org-reinstall-markers-in-region bbb)
7168 (move-marker ins-point bbb))
7169 (or (bolp) (insert "\n"))
7170 (setq ins-end (point))
7171 (goto-char ins-point)
7172 (org-skip-whitespace)
7173 (when (and (< arg 0)
7174 (org-first-sibling-p)
7175 (> ne-ins ne-beg))
7176 ;; Move whitespace back to beginning
7177 (save-excursion
7178 (goto-char ins-end)
7179 (let ((kill-whole-line t))
7180 (kill-line (- ne-ins ne-beg)) (point)))
7181 (insert (make-string (- ne-ins ne-beg) ?\n)))
7182 (move-marker ins-point nil)
7183 (if folded
7184 (hide-subtree)
7185 (org-show-entry)
7186 (show-children)
7187 (org-cycle-hide-drawers 'children))
7188 (org-clean-visibility-after-subtree-move)))
7190 (defvar org-subtree-clip ""
7191 "Clipboard for cut and paste of subtrees.
7192 This is actually only a copy of the kill, because we use the normal kill
7193 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7195 (defvar org-subtree-clip-folded nil
7196 "Was the last copied subtree folded?
7197 This is used to fold the tree back after pasting.")
7199 (defun org-cut-subtree (&optional n)
7200 "Cut the current subtree into the clipboard.
7201 With prefix arg N, cut this many sequential subtrees.
7202 This is a short-hand for marking the subtree and then cutting it."
7203 (interactive "p")
7204 (org-copy-subtree n 'cut))
7206 (defun org-copy-subtree (&optional n cut force-store-markers)
7207 "Cut the current subtree into the clipboard.
7208 With prefix arg N, cut this many sequential subtrees.
7209 This is a short-hand for marking the subtree and then copying it.
7210 If CUT is non-nil, actually cut the subtree.
7211 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7212 of some markers in the region, even if CUT is non-nil. This is
7213 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7214 (interactive "p")
7215 (let (beg end folded (beg0 (point)))
7216 (if (interactive-p)
7217 (org-back-to-heading nil) ; take what looks like a subtree
7218 (org-back-to-heading t)) ; take what is really there
7219 (org-back-over-empty-lines)
7220 (setq beg (point))
7221 (skip-chars-forward " \t\r\n")
7222 (save-match-data
7223 (save-excursion (outline-end-of-heading)
7224 (setq folded (org-invisible-p)))
7225 (condition-case nil
7226 (org-forward-same-level (1- n) t)
7227 (error nil))
7228 (org-end-of-subtree t t))
7229 (org-back-over-empty-lines)
7230 (setq end (point))
7231 (goto-char beg0)
7232 (when (> end beg)
7233 (setq org-subtree-clip-folded folded)
7234 (when (or cut force-store-markers)
7235 (org-save-markers-in-region beg end))
7236 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7237 (setq org-subtree-clip (current-kill 0))
7238 (message "%s: Subtree(s) with %d characters"
7239 (if cut "Cut" "Copied")
7240 (length org-subtree-clip)))))
7242 (defun org-paste-subtree (&optional level tree for-yank)
7243 "Paste the clipboard as a subtree, with modification of headline level.
7244 The entire subtree is promoted or demoted in order to match a new headline
7245 level.
7247 If the cursor is at the beginning of a headline, the same level as
7248 that headline is used to paste the tree
7250 If not, the new level is derived from the *visible* headings
7251 before and after the insertion point, and taken to be the inferior headline
7252 level of the two. So if the previous visible heading is level 3 and the
7253 next is level 4 (or vice versa), level 4 will be used for insertion.
7254 This makes sure that the subtree remains an independent subtree and does
7255 not swallow low level entries.
7257 You can also force a different level, either by using a numeric prefix
7258 argument, or by inserting the heading marker by hand. For example, if the
7259 cursor is after \"*****\", then the tree will be shifted to level 5.
7261 If optional TREE is given, use this text instead of the kill ring.
7263 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7264 move back over whitespace before inserting, and move point to the end of
7265 the inserted text when done."
7266 (interactive "P")
7267 (setq tree (or tree (and kill-ring (current-kill 0))))
7268 (unless (org-kill-is-subtree-p tree)
7269 (error "%s"
7270 (substitute-command-keys
7271 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7272 (let* ((visp (not (org-invisible-p)))
7273 (txt tree)
7274 (^re (concat "^\\(" outline-regexp "\\)"))
7275 (re (concat "\\(" outline-regexp "\\)"))
7276 (^re_ (concat "\\(\\*+\\)[ \t]*"))
7278 (old-level (if (string-match ^re txt)
7279 (- (match-end 0) (match-beginning 0) 1)
7280 -1))
7281 (force-level (cond (level (prefix-numeric-value level))
7282 ((and (looking-at "[ \t]*$")
7283 (string-match
7284 ^re_ (buffer-substring
7285 (point-at-bol) (point))))
7286 (- (match-end 1) (match-beginning 1)))
7287 ((and (bolp)
7288 (looking-at org-outline-regexp))
7289 (- (match-end 0) (point) 1))
7290 (t nil)))
7291 (previous-level (save-excursion
7292 (condition-case nil
7293 (progn
7294 (outline-previous-visible-heading 1)
7295 (if (looking-at re)
7296 (- (match-end 0) (match-beginning 0) 1)
7298 (error 1))))
7299 (next-level (save-excursion
7300 (condition-case nil
7301 (progn
7302 (or (looking-at outline-regexp)
7303 (outline-next-visible-heading 1))
7304 (if (looking-at re)
7305 (- (match-end 0) (match-beginning 0) 1)
7307 (error 1))))
7308 (new-level (or force-level (max previous-level next-level)))
7309 (shift (if (or (= old-level -1)
7310 (= new-level -1)
7311 (= old-level new-level))
7313 (- new-level old-level)))
7314 (delta (if (> shift 0) -1 1))
7315 (func (if (> shift 0) 'org-demote 'org-promote))
7316 (org-odd-levels-only nil)
7317 beg end newend)
7318 ;; Remove the forced level indicator
7319 (if force-level
7320 (delete-region (point-at-bol) (point)))
7321 ;; Paste
7322 (beginning-of-line 1)
7323 (unless for-yank (org-back-over-empty-lines))
7324 (setq beg (point))
7325 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7326 (insert-before-markers txt)
7327 (unless (string-match "\n\\'" txt) (insert "\n"))
7328 (setq newend (point))
7329 (org-reinstall-markers-in-region beg)
7330 (setq end (point))
7331 (goto-char beg)
7332 (skip-chars-forward " \t\n\r")
7333 (setq beg (point))
7334 (if (and (org-invisible-p) visp)
7335 (save-excursion (outline-show-heading)))
7336 ;; Shift if necessary
7337 (unless (= shift 0)
7338 (save-restriction
7339 (narrow-to-region beg end)
7340 (while (not (= shift 0))
7341 (org-map-region func (point-min) (point-max))
7342 (setq shift (+ delta shift)))
7343 (goto-char (point-min))
7344 (setq newend (point-max))))
7345 (when (or (interactive-p) for-yank)
7346 (message "Clipboard pasted as level %d subtree" new-level))
7347 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7348 kill-ring
7349 (eq org-subtree-clip (current-kill 0))
7350 org-subtree-clip-folded)
7351 ;; The tree was folded before it was killed/copied
7352 (hide-subtree))
7353 (and for-yank (goto-char newend))))
7355 (defun org-kill-is-subtree-p (&optional txt)
7356 "Check if the current kill is an outline subtree, or a set of trees.
7357 Returns nil if kill does not start with a headline, or if the first
7358 headline level is not the largest headline level in the tree.
7359 So this will actually accept several entries of equal levels as well,
7360 which is OK for `org-paste-subtree'.
7361 If optional TXT is given, check this string instead of the current kill."
7362 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7363 (start-level (and kill
7364 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
7365 org-outline-regexp "\\)")
7366 kill)
7367 (- (match-end 2) (match-beginning 2) 1)))
7368 (re (concat "^" org-outline-regexp))
7369 (start (1+ (or (match-beginning 2) -1))))
7370 (if (not start-level)
7371 (progn
7372 nil) ;; does not even start with a heading
7373 (catch 'exit
7374 (while (setq start (string-match re kill (1+ start)))
7375 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7376 (throw 'exit nil)))
7377 t))))
7379 (defvar org-markers-to-move nil
7380 "Markers that should be moved with a cut-and-paste operation.
7381 Those markers are stored together with their positions relative to
7382 the start of the region.")
7384 (defun org-save-markers-in-region (beg end)
7385 "Check markers in region.
7386 If these markers are between BEG and END, record their position relative
7387 to BEG, so that after moving the block of text, we can put the markers back
7388 into place.
7389 This function gets called just before an entry or tree gets cut from the
7390 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7391 called immediately, to move the markers with the entries."
7392 (setq org-markers-to-move nil)
7393 (when (featurep 'org-clock)
7394 (org-clock-save-markers-for-cut-and-paste beg end))
7395 (when (featurep 'org-agenda)
7396 (org-agenda-save-markers-for-cut-and-paste beg end)))
7398 (defun org-check-and-save-marker (marker beg end)
7399 "Check if MARKER is between BEG and END.
7400 If yes, remember the marker and the distance to BEG."
7401 (when (and (marker-buffer marker)
7402 (equal (marker-buffer marker) (current-buffer)))
7403 (if (and (>= marker beg) (< marker end))
7404 (push (cons marker (- marker beg)) org-markers-to-move))))
7406 (defun org-reinstall-markers-in-region (beg)
7407 "Move all remembered markers to their position relative to BEG."
7408 (mapc (lambda (x)
7409 (move-marker (car x) (+ beg (cdr x))))
7410 org-markers-to-move)
7411 (setq org-markers-to-move nil))
7413 (defun org-narrow-to-subtree ()
7414 "Narrow buffer to the current subtree."
7415 (interactive)
7416 (save-excursion
7417 (save-match-data
7418 (narrow-to-region
7419 (progn (org-back-to-heading t) (point))
7420 (progn (org-end-of-subtree t t)
7421 (if (org-on-heading-p) (backward-char 1))
7422 (point))))))
7424 (eval-when-compile
7425 (defvar org-property-drawer-re))
7427 (defun org-clone-subtree-with-time-shift (n &optional shift)
7428 "Clone the task (subtree) at point N times.
7429 The clones will be inserted as siblings.
7431 In interactive use, the user will be prompted for the number of
7432 clones to be produced, and for a time SHIFT, which may be a
7433 repeater as used in time stamps, for example `+3d'.
7435 When a valid repeater is given and the entry contains any time
7436 stamps, the clones will become a sequence in time, with time
7437 stamps in the subtree shifted for each clone produced. If SHIFT
7438 is nil or the empty string, time stamps will be left alone. The
7439 ID property of the original subtree is removed.
7441 If the original subtree did contain time stamps with a repeater,
7442 the following will happen:
7443 - the repeater will be removed in each clone
7444 - an additional clone will be produced, with the current, unshifted
7445 date(s) in the entry.
7446 - the original entry will be placed *after* all the clones, with
7447 repeater intact.
7448 - the start days in the repeater in the original entry will be shifted
7449 to past the last clone.
7450 I this way you can spell out a number of instances of a repeating task,
7451 and still retain the repeater to cover future instances of the task."
7452 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7453 (let (beg end template task idprop
7454 shift-n shift-what doshift nmin nmax (n-no-remove -1))
7455 (if (not (and (integerp n) (> n 0)))
7456 (error "Invalid number of replications %s" n))
7457 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7458 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
7459 shift)))
7460 (error "Invalid shift specification %s" shift))
7461 (when doshift
7462 (setq shift-n (string-to-number (match-string 1 shift))
7463 shift-what (cdr (assoc (match-string 2 shift)
7464 '(("d" . day) ("w" . week)
7465 ("m" . month) ("y" . year))))))
7466 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7467 (setq nmin 1 nmax n)
7468 (org-back-to-heading t)
7469 (setq beg (point))
7470 (setq idprop (org-entry-get nil "ID"))
7471 (org-end-of-subtree t t)
7472 (or (bolp) (insert "\n"))
7473 (setq end (point))
7474 (setq template (buffer-substring beg end))
7475 (when (and doshift
7476 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
7477 (delete-region beg end)
7478 (setq end beg)
7479 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7480 (goto-char end)
7481 (loop for n from nmin to nmax do
7482 ;; prepare clone
7483 (with-temp-buffer
7484 (insert template)
7485 (org-mode)
7486 (goto-char (point-min))
7487 (and idprop (if org-clone-delete-id
7488 (org-entry-delete nil "ID")
7489 (org-id-get-create t)))
7490 (while (re-search-forward org-property-drawer-re nil t)
7491 (org-remove-empty-drawer-at "PROPERTIES" (point)))
7492 (goto-char (point-min))
7493 (when doshift
7494 (while (re-search-forward org-ts-regexp-both nil t)
7495 (org-timestamp-change (* n shift-n) shift-what))
7496 (unless (= n n-no-remove)
7497 (goto-char (point-min))
7498 (while (re-search-forward org-ts-regexp nil t)
7499 (save-excursion
7500 (goto-char (match-beginning 0))
7501 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
7502 (delete-region (match-beginning 1) (match-end 1)))))))
7503 (setq task (buffer-string)))
7504 (insert task))
7505 (goto-char beg)))
7507 ;;; Outline Sorting
7509 (defun org-sort (with-case)
7510 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
7511 Optional argument WITH-CASE means sort case-sensitively.
7512 With a double prefix argument, also remove duplicate entries."
7513 (interactive "P")
7514 (if (org-at-table-p)
7515 (org-call-with-arg 'org-table-sort-lines with-case)
7516 (org-call-with-arg 'org-sort-entries-or-items with-case)))
7518 (defun org-sort-remove-invisible (s)
7519 (remove-text-properties 0 (length s) org-rm-props s)
7520 (while (string-match org-bracket-link-regexp s)
7521 (setq s (replace-match (if (match-end 2)
7522 (match-string 3 s)
7523 (match-string 1 s)) t t s)))
7526 (defvar org-priority-regexp) ; defined later in the file
7528 (defvar org-after-sorting-entries-or-items-hook nil
7529 "Hook that is run after a bunch of entries or items have been sorted.
7530 When children are sorted, the cursor is in the parent line when this
7531 hook gets called. When a region or a plain list is sorted, the cursor
7532 will be in the first entry of the sorted region/list.")
7534 (defun org-sort-entries-or-items
7535 (&optional with-case sorting-type getkey-func compare-func property)
7536 "Sort entries on a certain level of an outline tree, or plain list items.
7537 If there is an active region, the entries in the region are sorted.
7538 Else, if the cursor is before the first entry, sort the top-level items.
7539 Else, the children of the entry at point are sorted.
7540 If the cursor is at the first item in a plain list, the list items will be
7541 sorted.
7543 Sorting can be alphabetically, numerically, by date/time as given by
7544 a time stamp, by a property or by priority.
7546 The command prompts for the sorting type unless it has been given to the
7547 function through the SORTING-TYPE argument, which needs to be a character,
7548 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
7549 precise meaning of each character:
7551 n Numerically, by converting the beginning of the entry/item to a number.
7552 a Alphabetically, ignoring the TODO keyword and the priority, if any.
7553 t By date/time, either the first active time stamp in the entry, or, if
7554 none exist, by the first inactive one.
7555 In items, only the first line will be checked.
7556 s By the scheduled date/time.
7557 d By deadline date/time.
7558 c By creation time, which is assumed to be the first inactive time stamp
7559 at the beginning of a line.
7560 p By priority according to the cookie.
7561 r By the value of a property.
7563 Capital letters will reverse the sort order.
7565 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
7566 called with point at the beginning of the record. It must return either
7567 a string or a number that should serve as the sorting key for that record.
7569 Comparing entries ignores case by default. However, with an optional argument
7570 WITH-CASE, the sorting considers case as well."
7571 (interactive "P")
7572 (let ((case-func (if with-case 'identity 'downcase))
7573 start beg end stars re re2
7574 txt what tmp plain-list-p)
7575 ;; Find beginning and end of region to sort
7576 (cond
7577 ((org-region-active-p)
7578 ;; we will sort the region
7579 (setq end (region-end)
7580 what "region")
7581 (goto-char (region-beginning))
7582 (if (not (org-on-heading-p)) (outline-next-heading))
7583 (setq start (point)))
7584 ((org-at-item-p)
7585 ;; we will sort this plain list
7586 (org-beginning-of-item-list) (setq start (point))
7587 (org-end-of-item-list)
7588 (or (bolp) (insert "\n"))
7589 (setq end (point))
7590 (goto-char start)
7591 (setq plain-list-p t
7592 what "plain list"))
7593 ((or (org-on-heading-p)
7594 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
7595 ;; we will sort the children of the current headline
7596 (org-back-to-heading)
7597 (setq start (point)
7598 end (progn (org-end-of-subtree t t)
7599 (or (bolp) (insert "\n"))
7600 (org-back-over-empty-lines)
7601 (point))
7602 what "children")
7603 (goto-char start)
7604 (show-subtree)
7605 (outline-next-heading))
7607 ;; we will sort the top-level entries in this file
7608 (goto-char (point-min))
7609 (or (org-on-heading-p) (outline-next-heading))
7610 (setq start (point))
7611 (goto-char (point-max))
7612 (beginning-of-line 1)
7613 (when (looking-at ".*?\\S-")
7614 ;; File ends in a non-white line
7615 (end-of-line 1)
7616 (insert "\n"))
7617 (setq end (point-max))
7618 (setq what "top-level")
7619 (goto-char start)
7620 (show-all)))
7622 (setq beg (point))
7623 (if (>= beg end) (error "Nothing to sort"))
7625 (unless plain-list-p
7626 (looking-at "\\(\\*+\\)")
7627 (setq stars (match-string 1)
7628 re (concat "^" (regexp-quote stars) " +")
7629 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
7630 txt (buffer-substring beg end))
7631 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
7632 (if (and (not (equal stars "*")) (string-match re2 txt))
7633 (error "Region to sort contains a level above the first entry")))
7635 (unless sorting-type
7636 (message
7637 (if plain-list-p
7638 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
7639 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
7640 [t]ime [s]cheduled [d]eadline [c]reated
7641 A/N/T/S/D/C/P/O/F means reversed:")
7642 what)
7643 (setq sorting-type (read-char-exclusive))
7645 (and (= (downcase sorting-type) ?f)
7646 (setq getkey-func
7647 (org-icompleting-read "Sort using function: "
7648 obarray 'fboundp t nil nil))
7649 (setq getkey-func (intern getkey-func)))
7651 (and (= (downcase sorting-type) ?r)
7652 (setq property
7653 (org-icompleting-read "Property: "
7654 (mapcar 'list (org-buffer-property-keys t))
7655 nil t))))
7657 (message "Sorting entries...")
7659 (save-restriction
7660 (narrow-to-region start end)
7662 (let ((dcst (downcase sorting-type))
7663 (case-fold-search nil)
7664 (now (current-time)))
7665 (sort-subr
7666 (/= dcst sorting-type)
7667 ;; This function moves to the beginning character of the "record" to
7668 ;; be sorted.
7669 (if plain-list-p
7670 (lambda nil
7671 (if (org-at-item-p) t (goto-char (point-max))))
7672 (lambda nil
7673 (if (re-search-forward re nil t)
7674 (goto-char (match-beginning 0))
7675 (goto-char (point-max)))))
7676 ;; This function moves to the last character of the "record" being
7677 ;; sorted.
7678 (if plain-list-p
7679 'org-end-of-item
7680 (lambda nil
7681 (save-match-data
7682 (condition-case nil
7683 (outline-forward-same-level 1)
7684 (error
7685 (goto-char (point-max)))))))
7687 ;; This function returns the value that gets sorted against.
7688 (if plain-list-p
7689 (lambda nil
7690 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
7691 (cond
7692 ((= dcst ?n)
7693 (string-to-number (buffer-substring (match-end 0)
7694 (point-at-eol))))
7695 ((= dcst ?a)
7696 (buffer-substring (match-end 0) (point-at-eol)))
7697 ((= dcst ?t)
7698 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
7699 (re-search-forward org-ts-regexp-both
7700 (point-at-eol) t))
7701 (org-time-string-to-seconds (match-string 0))
7702 (org-float-time now)))
7703 ((= dcst ?f)
7704 (if getkey-func
7705 (progn
7706 (setq tmp (funcall getkey-func))
7707 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7708 tmp)
7709 (error "Invalid key function `%s'" getkey-func)))
7710 (t (error "Invalid sorting type `%c'" sorting-type)))))
7711 (lambda nil
7712 (cond
7713 ((= dcst ?n)
7714 (if (looking-at org-complex-heading-regexp)
7715 (string-to-number (match-string 4))
7716 nil))
7717 ((= dcst ?a)
7718 (if (looking-at org-complex-heading-regexp)
7719 (funcall case-func (match-string 4))
7720 nil))
7721 ((= dcst ?t)
7722 (let ((end (save-excursion (outline-next-heading) (point))))
7723 (if (or (re-search-forward org-ts-regexp end t)
7724 (re-search-forward org-ts-regexp-both end t))
7725 (org-time-string-to-seconds (match-string 0))
7726 (org-float-time now))))
7727 ((= dcst ?c)
7728 (let ((end (save-excursion (outline-next-heading) (point))))
7729 (if (re-search-forward
7730 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
7731 end t)
7732 (org-time-string-to-seconds (match-string 0))
7733 (org-float-time now))))
7734 ((= dcst ?s)
7735 (let ((end (save-excursion (outline-next-heading) (point))))
7736 (if (re-search-forward org-scheduled-time-regexp end t)
7737 (org-time-string-to-seconds (match-string 1))
7738 (org-float-time now))))
7739 ((= dcst ?d)
7740 (let ((end (save-excursion (outline-next-heading) (point))))
7741 (if (re-search-forward org-deadline-time-regexp end t)
7742 (org-time-string-to-seconds (match-string 1))
7743 (org-float-time now))))
7744 ((= dcst ?p)
7745 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7746 (string-to-char (match-string 2))
7747 org-default-priority))
7748 ((= dcst ?r)
7749 (or (org-entry-get nil property) ""))
7750 ((= dcst ?o)
7751 (if (looking-at org-complex-heading-regexp)
7752 (- 9999 (length (member (match-string 2)
7753 org-todo-keywords-1)))))
7754 ((= dcst ?f)
7755 (if getkey-func
7756 (progn
7757 (setq tmp (funcall getkey-func))
7758 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7759 tmp)
7760 (error "Invalid key function `%s'" getkey-func)))
7761 (t (error "Invalid sorting type `%c'" sorting-type)))))
7763 (cond
7764 ((= dcst ?a) 'string<)
7765 ((= dcst ?f) compare-func)
7766 ((member dcst '(?p ?t ?s ?d ?c)) '<)
7767 (t nil)))))
7768 (run-hooks 'org-after-sorting-entries-or-items-hook)
7769 (message "Sorting entries...done")))
7771 (defun org-do-sort (table what &optional with-case sorting-type)
7772 "Sort TABLE of WHAT according to SORTING-TYPE.
7773 The user will be prompted for the SORTING-TYPE if the call to this
7774 function does not specify it. WHAT is only for the prompt, to indicate
7775 what is being sorted. The sorting key will be extracted from
7776 the car of the elements of the table.
7777 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7778 (unless sorting-type
7779 (message
7780 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7781 what)
7782 (setq sorting-type (read-char-exclusive)))
7783 (let ((dcst (downcase sorting-type))
7784 extractfun comparefun)
7785 ;; Define the appropriate functions
7786 (cond
7787 ((= dcst ?n)
7788 (setq extractfun 'string-to-number
7789 comparefun (if (= dcst sorting-type) '< '>)))
7790 ((= dcst ?a)
7791 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7792 (lambda(x) (downcase (org-sort-remove-invisible x))))
7793 comparefun (if (= dcst sorting-type)
7794 'string<
7795 (lambda (a b) (and (not (string< a b))
7796 (not (string= a b)))))))
7797 ((= dcst ?t)
7798 (setq extractfun
7799 (lambda (x)
7800 (if (or (string-match org-ts-regexp x)
7801 (string-match org-ts-regexp-both x))
7802 (org-float-time
7803 (org-time-string-to-time (match-string 0 x)))
7805 comparefun (if (= dcst sorting-type) '< '>)))
7806 (t (error "Invalid sorting type `%c'" sorting-type)))
7808 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7809 table)
7810 (lambda (a b) (funcall comparefun (car a) (car b))))))
7813 ;;; The orgstruct minor mode
7815 ;; Define a minor mode which can be used in other modes in order to
7816 ;; integrate the org-mode structure editing commands.
7818 ;; This is really a hack, because the org-mode structure commands use
7819 ;; keys which normally belong to the major mode. Here is how it
7820 ;; works: The minor mode defines all the keys necessary to operate the
7821 ;; structure commands, but wraps the commands into a function which
7822 ;; tests if the cursor is currently at a headline or a plain list
7823 ;; item. If that is the case, the structure command is used,
7824 ;; temporarily setting many Org-mode variables like regular
7825 ;; expressions for filling etc. However, when any of those keys is
7826 ;; used at a different location, function uses `key-binding' to look
7827 ;; up if the key has an associated command in another currently active
7828 ;; keymap (minor modes, major mode, global), and executes that
7829 ;; command. There might be problems if any of the keys is otherwise
7830 ;; used as a prefix key.
7832 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7833 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7834 ;; addresses this by checking explicitly for both bindings.
7836 (defvar orgstruct-mode-map (make-sparse-keymap)
7837 "Keymap for the minor `orgstruct-mode'.")
7839 (defvar org-local-vars nil
7840 "List of local variables, for use by `orgstruct-mode'.")
7842 ;;;###autoload
7843 (define-minor-mode orgstruct-mode
7844 "Toggle the minor mode `orgstruct-mode'.
7845 This mode is for using Org-mode structure commands in other
7846 modes. The following keys behave as if Org-mode were active, if
7847 the cursor is on a headline, or on a plain list item (both as
7848 defined by Org-mode).
7850 M-up Move entry/item up
7851 M-down Move entry/item down
7852 M-left Promote
7853 M-right Demote
7854 M-S-up Move entry/item up
7855 M-S-down Move entry/item down
7856 M-S-left Promote subtree
7857 M-S-right Demote subtree
7858 M-q Fill paragraph and items like in Org-mode
7859 C-c ^ Sort entries
7860 C-c - Cycle list bullet
7861 TAB Cycle item visibility
7862 M-RET Insert new heading/item
7863 S-M-RET Insert new TODO heading / Checkbox item
7864 C-c C-c Set tags / toggle checkbox"
7865 nil " OrgStruct" nil
7866 (org-load-modules-maybe)
7867 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7869 ;;;###autoload
7870 (defun turn-on-orgstruct ()
7871 "Unconditionally turn on `orgstruct-mode'."
7872 (orgstruct-mode 1))
7874 (defun orgstruct++-mode (&optional arg)
7875 "Toggle `orgstruct-mode', the enhanced version of it.
7876 In addition to setting orgstruct-mode, this also exports all indentation
7877 and autofilling variables from org-mode into the buffer. It will also
7878 recognize item context in multiline items.
7879 Note that turning off orgstruct-mode will *not* remove the
7880 indentation/paragraph settings. This can only be done by refreshing the
7881 major mode, for example with \\[normal-mode]."
7882 (interactive "P")
7883 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
7884 (if (< arg 1)
7885 (orgstruct-mode -1)
7886 (orgstruct-mode 1)
7887 (let (var val)
7888 (mapc
7889 (lambda (x)
7890 (when (string-match
7891 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7892 (symbol-name (car x)))
7893 (setq var (car x) val (nth 1 x))
7894 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7895 org-local-vars)
7896 (org-set-local 'orgstruct-is-++ t))))
7898 (defvar orgstruct-is-++ nil
7899 "Is `orgstruct-mode' in ++ version in the current-buffer?")
7900 (make-variable-buffer-local 'orgstruct-is-++)
7902 ;;;###autoload
7903 (defun turn-on-orgstruct++ ()
7904 "Unconditionally turn on `orgstruct++-mode'."
7905 (orgstruct++-mode 1))
7907 (defun orgstruct-error ()
7908 "Error when there is no default binding for a structure key."
7909 (interactive)
7910 (error "This key has no function outside structure elements"))
7912 (defun orgstruct-setup ()
7913 "Setup orgstruct keymaps."
7914 (let ((nfunc 0)
7915 (bindings
7916 (list
7917 '([(meta up)] org-metaup)
7918 '([(meta down)] org-metadown)
7919 '([(meta left)] org-metaleft)
7920 '([(meta right)] org-metaright)
7921 '([(meta shift up)] org-shiftmetaup)
7922 '([(meta shift down)] org-shiftmetadown)
7923 '([(meta shift left)] org-shiftmetaleft)
7924 '([(meta shift right)] org-shiftmetaright)
7925 '([?\e (up)] org-metaup)
7926 '([?\e (down)] org-metadown)
7927 '([?\e (left)] org-metaleft)
7928 '([?\e (right)] org-metaright)
7929 '([?\e (shift up)] org-shiftmetaup)
7930 '([?\e (shift down)] org-shiftmetadown)
7931 '([?\e (shift left)] org-shiftmetaleft)
7932 '([?\e (shift right)] org-shiftmetaright)
7933 '([(shift up)] org-shiftup)
7934 '([(shift down)] org-shiftdown)
7935 '([(shift left)] org-shiftleft)
7936 '([(shift right)] org-shiftright)
7937 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7938 '("\M-q" fill-paragraph)
7939 '("\C-c^" org-sort)
7940 '("\C-c-" org-cycle-list-bullet)))
7941 elt key fun cmd)
7942 (while (setq elt (pop bindings))
7943 (setq nfunc (1+ nfunc))
7944 (setq key (org-key (car elt))
7945 fun (nth 1 elt)
7946 cmd (orgstruct-make-binding fun nfunc key))
7947 (org-defkey orgstruct-mode-map key cmd))
7949 ;; Special treatment needed for TAB and RET
7950 (org-defkey orgstruct-mode-map [(tab)]
7951 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7952 (org-defkey orgstruct-mode-map "\C-i"
7953 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7955 (org-defkey orgstruct-mode-map "\M-\C-m"
7956 (orgstruct-make-binding 'org-insert-heading 105
7957 "\M-\C-m" [(meta return)]))
7958 (org-defkey orgstruct-mode-map [(meta return)]
7959 (orgstruct-make-binding 'org-insert-heading 106
7960 [(meta return)] "\M-\C-m"))
7962 (org-defkey orgstruct-mode-map [(shift meta return)]
7963 (orgstruct-make-binding 'org-insert-todo-heading 107
7964 [(meta return)] "\M-\C-m"))
7966 (org-defkey orgstruct-mode-map "\e\C-m"
7967 (orgstruct-make-binding 'org-insert-heading 108
7968 "\e\C-m" [?\e (return)]))
7969 (org-defkey orgstruct-mode-map [?\e (return)]
7970 (orgstruct-make-binding 'org-insert-heading 109
7971 [?\e (return)] "\e\C-m"))
7972 (org-defkey orgstruct-mode-map [?\e (shift return)]
7973 (orgstruct-make-binding 'org-insert-todo-heading 110
7974 [?\e (return)] "\e\C-m"))
7976 (unless org-local-vars
7977 (setq org-local-vars (org-get-local-variables)))
7981 (defun orgstruct-make-binding (fun n &rest keys)
7982 "Create a function for binding in the structure minor mode.
7983 FUN is the command to call inside a table. N is used to create a unique
7984 command name. KEYS are keys that should be checked in for a command
7985 to execute outside of tables."
7986 (eval
7987 (list 'defun
7988 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7989 '(arg)
7990 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7991 "Outside of structure, run the binding of `"
7992 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7993 "'.")
7994 '(interactive "p")
7995 (list 'if
7996 `(org-context-p 'headline 'item
7997 (and orgstruct-is-++
7998 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
7999 'item-body))
8000 (list 'org-run-like-in-org-mode (list 'quote fun))
8001 (list 'let '(orgstruct-mode)
8002 (list 'call-interactively
8003 (append '(or)
8004 (mapcar (lambda (k)
8005 (list 'key-binding k))
8006 keys)
8007 '('orgstruct-error))))))))
8009 (defun org-context-p (&rest contexts)
8010 "Check if local context is any of CONTEXTS.
8011 Possible values in the list of contexts are `table', `headline', and `item'."
8012 (let ((pos (point)))
8013 (goto-char (point-at-bol))
8014 (prog1 (or (and (memq 'table contexts)
8015 (looking-at "[ \t]*|"))
8016 (and (memq 'headline contexts)
8017 ;;????????? (looking-at "\\*+"))
8018 (looking-at outline-regexp))
8019 (and (memq 'item contexts)
8020 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8021 (and (memq 'item-body contexts)
8022 (org-in-item-p)))
8023 (goto-char pos))))
8025 (defun org-get-local-variables ()
8026 "Return a list of all local variables in an org-mode buffer."
8027 (let (varlist)
8028 (with-current-buffer (get-buffer-create "*Org tmp*")
8029 (erase-buffer)
8030 (org-mode)
8031 (setq varlist (buffer-local-variables)))
8032 (kill-buffer "*Org tmp*")
8033 (delq nil
8034 (mapcar
8035 (lambda (x)
8036 (setq x
8037 (if (symbolp x)
8038 (list x)
8039 (list (car x) (list 'quote (cdr x)))))
8040 (if (string-match
8041 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8042 (symbol-name (car x)))
8043 x nil))
8044 varlist))))
8046 ;;;###autoload
8047 (defun org-run-like-in-org-mode (cmd)
8048 "Run a command, pretending that the current buffer is in Org-mode.
8049 This will temporarily bind local variables that are typically bound in
8050 Org-mode to the values they have in Org-mode, and then interactively
8051 call CMD."
8052 (org-load-modules-maybe)
8053 (unless org-local-vars
8054 (setq org-local-vars (org-get-local-variables)))
8055 (eval (list 'let org-local-vars
8056 (list 'call-interactively (list 'quote cmd)))))
8058 ;;;; Archiving
8060 (defun org-get-category (&optional pos)
8061 "Get the category applying to position POS."
8062 (get-text-property (or pos (point)) 'org-category))
8064 (defun org-refresh-category-properties ()
8065 "Refresh category text properties in the buffer."
8066 (let ((def-cat (cond
8067 ((null org-category)
8068 (if buffer-file-name
8069 (file-name-sans-extension
8070 (file-name-nondirectory buffer-file-name))
8071 "???"))
8072 ((symbolp org-category) (symbol-name org-category))
8073 (t org-category)))
8074 beg end cat pos optionp)
8075 (org-unmodified
8076 (save-excursion
8077 (save-restriction
8078 (widen)
8079 (goto-char (point-min))
8080 (put-text-property (point) (point-max) 'org-category def-cat)
8081 (while (re-search-forward
8082 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8083 (setq pos (match-end 0)
8084 optionp (equal (char-after (match-beginning 0)) ?#)
8085 cat (org-trim (match-string 2)))
8086 (if optionp
8087 (setq beg (point-at-bol) end (point-max))
8088 (org-back-to-heading t)
8089 (setq beg (point) end (org-end-of-subtree t t)))
8090 (put-text-property beg end 'org-category cat)
8091 (goto-char pos)))))))
8094 ;;;; Link Stuff
8096 ;;; Link abbreviations
8098 (defun org-link-expand-abbrev (link)
8099 "Apply replacements as defined in `org-link-abbrev-alist."
8100 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
8101 (let* ((key (match-string 1 link))
8102 (as (or (assoc key org-link-abbrev-alist-local)
8103 (assoc key org-link-abbrev-alist)))
8104 (tag (and (match-end 2) (match-string 3 link)))
8105 rpl)
8106 (if (not as)
8107 link
8108 (setq rpl (cdr as))
8109 (cond
8110 ((symbolp rpl) (funcall rpl tag))
8111 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8112 ((string-match "%h" rpl)
8113 (replace-match (url-hexify-string (or tag "")) t t rpl))
8114 (t (concat rpl tag)))))
8115 link))
8117 ;;; Storing and inserting links
8119 (defvar org-insert-link-history nil
8120 "Minibuffer history for links inserted with `org-insert-link'.")
8122 (defvar org-stored-links nil
8123 "Contains the links stored with `org-store-link'.")
8125 (defvar org-store-link-plist nil
8126 "Plist with info about the most recently link created with `org-store-link'.")
8128 (defvar org-link-protocols nil
8129 "Link protocols added to Org-mode using `org-add-link-type'.")
8131 (defvar org-store-link-functions nil
8132 "List of functions that are called to create and store a link.
8133 Each function will be called in turn until one returns a non-nil
8134 value. Each function should check if it is responsible for creating
8135 this link (for example by looking at the major mode).
8136 If not, it must exit and return nil.
8137 If yes, it should return a non-nil value after a calling
8138 `org-store-link-props' with a list of properties and values.
8139 Special properties are:
8141 :type The link prefix, like \"http\". This must be given.
8142 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8143 This is obligatory as well.
8144 :description Optional default description for the second pair
8145 of brackets in an Org-mode link. The user can still change
8146 this when inserting this link into an Org-mode buffer.
8148 In addition to these, any additional properties can be specified
8149 and then used in remember templates.")
8151 (defun org-add-link-type (type &optional follow export)
8152 "Add TYPE to the list of `org-link-types'.
8153 Re-compute all regular expressions depending on `org-link-types'
8155 FOLLOW and EXPORT are two functions.
8157 FOLLOW should take the link path as the single argument and do whatever
8158 is necessary to follow the link, for example find a file or display
8159 a mail message.
8161 EXPORT should format the link path for export to one of the export formats.
8162 It should be a function accepting three arguments:
8164 path the path of the link, the text after the prefix (like \"http:\")
8165 desc the description of the link, if any, nil if there was no description
8166 format the export format, a symbol like `html' or `latex'.
8168 The function may use the FORMAT information to return different values
8169 depending on the format. The return value will be put literally into
8170 the exported file.
8171 Org-mode has a built-in default for exporting links. If you are happy with
8172 this default, there is no need to define an export function for the link
8173 type. For a simple example of an export function, see `org-bbdb.el'."
8174 (add-to-list 'org-link-types type t)
8175 (org-make-link-regexps)
8176 (if (assoc type org-link-protocols)
8177 (setcdr (assoc type org-link-protocols) (list follow export))
8178 (push (list type follow export) org-link-protocols)))
8180 (defvar org-agenda-buffer-name)
8182 ;;;###autoload
8183 (defun org-store-link (arg)
8184 "\\<org-mode-map>Store an org-link to the current location.
8185 This link is added to `org-stored-links' and can later be inserted
8186 into an org-buffer with \\[org-insert-link].
8188 For some link types, a prefix arg is interpreted:
8189 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8190 For file links, arg negates `org-context-in-file-links'."
8191 (interactive "P")
8192 (org-load-modules-maybe)
8193 (setq org-store-link-plist nil) ; reset
8194 (let ((outline-regexp (org-get-limited-outline-regexp))
8195 link cpltxt desc description search txt custom-id)
8196 (cond
8198 ((run-hook-with-args-until-success 'org-store-link-functions)
8199 (setq link (plist-get org-store-link-plist :link)
8200 desc (or (plist-get org-store-link-plist :description) link)))
8202 ((equal (buffer-name) "*Org Edit Src Example*")
8203 (let (label gc)
8204 (while (or (not label)
8205 (save-excursion
8206 (save-restriction
8207 (widen)
8208 (goto-char (point-min))
8209 (re-search-forward
8210 (regexp-quote (format org-coderef-label-format label))
8211 nil t))))
8212 (when label (message "Label exists already") (sit-for 2))
8213 (setq label (read-string "Code line label: " label)))
8214 (end-of-line 1)
8215 (setq link (format org-coderef-label-format label))
8216 (setq gc (- 79 (length link)))
8217 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8218 (insert link)
8219 (setq link (concat "(" label ")") desc nil)))
8221 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8222 ;; We are in the agenda, link to referenced location
8223 (let ((m (or (get-text-property (point) 'org-hd-marker)
8224 (get-text-property (point) 'org-marker))))
8225 (when m
8226 (org-with-point-at m
8227 (if (interactive-p)
8228 (call-interactively 'org-store-link)
8229 (org-store-link nil))))))
8231 ((eq major-mode 'calendar-mode)
8232 (let ((cd (calendar-cursor-to-date)))
8233 (setq link
8234 (format-time-string
8235 (car org-time-stamp-formats)
8236 (apply 'encode-time
8237 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8238 nil nil nil))))
8239 (org-store-link-props :type "calendar" :date cd)))
8241 ((eq major-mode 'w3-mode)
8242 (setq cpltxt (if (and (buffer-name)
8243 (not (string-match "Untitled" (buffer-name))))
8244 (buffer-name)
8245 (url-view-url t))
8246 link (org-make-link (url-view-url t)))
8247 (org-store-link-props :type "w3" :url (url-view-url t)))
8249 ((eq major-mode 'w3m-mode)
8250 (setq cpltxt (or w3m-current-title w3m-current-url)
8251 link (org-make-link w3m-current-url))
8252 (org-store-link-props :type "w3m" :url (url-view-url t)))
8254 ((setq search (run-hook-with-args-until-success
8255 'org-create-file-search-functions))
8256 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8257 "::" search))
8258 (setq cpltxt (or description link)))
8260 ((eq major-mode 'image-mode)
8261 (setq cpltxt (concat "file:"
8262 (abbreviate-file-name buffer-file-name))
8263 link (org-make-link cpltxt))
8264 (org-store-link-props :type "image" :file buffer-file-name))
8266 ((eq major-mode 'dired-mode)
8267 ;; link to the file in the current line
8268 (let ((file (dired-get-filename nil t)))
8269 (setq file (if file
8270 (abbreviate-file-name
8271 (expand-file-name (dired-get-filename nil t)))
8272 ;; otherwise, no file so use current directory.
8273 default-directory))
8274 (setq cpltxt (concat "file:" file)
8275 link (org-make-link cpltxt))))
8277 ((and buffer-file-name (org-mode-p))
8278 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
8279 (cond
8280 ((org-in-regexp "<<\\(.*?\\)>>")
8281 (setq cpltxt
8282 (concat "file:"
8283 (abbreviate-file-name buffer-file-name)
8284 "::" (match-string 1))
8285 link (org-make-link cpltxt)))
8286 ((and (featurep 'org-id)
8287 (or (eq org-link-to-org-use-id t)
8288 (and (eq org-link-to-org-use-id 'create-if-interactive)
8289 (interactive-p))
8290 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
8291 (interactive-p)
8292 (not custom-id))
8293 (and org-link-to-org-use-id
8294 (condition-case nil
8295 (org-entry-get nil "ID")
8296 (error nil)))))
8297 ;; We can make a link using the ID.
8298 (setq link (condition-case nil
8299 (prog1 (org-id-store-link)
8300 (setq desc (plist-get org-store-link-plist
8301 :description)))
8302 (error
8303 ;; probably before first headline, link to file only
8304 (concat "file:"
8305 (abbreviate-file-name buffer-file-name))))))
8307 ;; Just link to current headline
8308 (setq cpltxt (concat "file:"
8309 (abbreviate-file-name buffer-file-name)))
8310 ;; Add a context search string
8311 (when (org-xor org-context-in-file-links arg)
8312 (setq txt (cond
8313 ((org-on-heading-p) nil)
8314 ((org-region-active-p)
8315 (buffer-substring (region-beginning) (region-end)))
8316 (t nil)))
8317 (when (or (null txt) (string-match "\\S-" txt))
8318 (setq cpltxt
8319 (concat cpltxt "::"
8320 (condition-case nil
8321 (org-make-org-heading-search-string txt)
8322 (error "")))
8323 desc (or (nth 4 (ignore-errors
8324 (org-heading-components))) "NONE"))))
8325 (if (string-match "::\\'" cpltxt)
8326 (setq cpltxt (substring cpltxt 0 -2)))
8327 (setq link (org-make-link cpltxt)))))
8329 ((buffer-file-name (buffer-base-buffer))
8330 ;; Just link to this file here.
8331 (setq cpltxt (concat "file:"
8332 (abbreviate-file-name
8333 (buffer-file-name (buffer-base-buffer)))))
8334 ;; Add a context string
8335 (when (org-xor org-context-in-file-links arg)
8336 (setq txt (if (org-region-active-p)
8337 (buffer-substring (region-beginning) (region-end))
8338 (buffer-substring (point-at-bol) (point-at-eol))))
8339 ;; Only use search option if there is some text.
8340 (when (string-match "\\S-" txt)
8341 (setq cpltxt
8342 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8343 desc "NONE")))
8344 (setq link (org-make-link cpltxt)))
8346 ((interactive-p)
8347 (error "Cannot link to a buffer which is not visiting a file"))
8349 (t (setq link nil)))
8351 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8352 (setq link (or link cpltxt)
8353 desc (or desc cpltxt))
8354 (if (equal desc "NONE") (setq desc nil))
8356 (if (and (or (interactive-p) executing-kbd-macro) link)
8357 (progn
8358 (setq org-stored-links
8359 (cons (list link desc) org-stored-links))
8360 (message "Stored: %s" (or desc link))
8361 (when custom-id
8362 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8363 "::#" custom-id))
8364 (setq org-stored-links
8365 (cons (list link desc) org-stored-links))))
8366 (and link (org-make-link-string link desc)))))
8368 (defun org-store-link-props (&rest plist)
8369 "Store link properties, extract names and addresses."
8370 (let (x adr)
8371 (when (setq x (plist-get plist :from))
8372 (setq adr (mail-extract-address-components x))
8373 (setq plist (plist-put plist :fromname (car adr)))
8374 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8375 (when (setq x (plist-get plist :to))
8376 (setq adr (mail-extract-address-components x))
8377 (setq plist (plist-put plist :toname (car adr)))
8378 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8379 (let ((from (plist-get plist :from))
8380 (to (plist-get plist :to)))
8381 (when (and from to org-from-is-user-regexp)
8382 (setq plist
8383 (plist-put plist :fromto
8384 (if (string-match org-from-is-user-regexp from)
8385 (concat "to %t")
8386 (concat "from %f"))))))
8387 (setq org-store-link-plist plist))
8389 (defun org-add-link-props (&rest plist)
8390 "Add these properties to the link property list."
8391 (let (key value)
8392 (while plist
8393 (setq key (pop plist) value (pop plist))
8394 (setq org-store-link-plist
8395 (plist-put org-store-link-plist key value)))))
8397 (defun org-email-link-description (&optional fmt)
8398 "Return the description part of an email link.
8399 This takes information from `org-store-link-plist' and formats it
8400 according to FMT (default from `org-email-link-description-format')."
8401 (setq fmt (or fmt org-email-link-description-format))
8402 (let* ((p org-store-link-plist)
8403 (to (plist-get p :toaddress))
8404 (from (plist-get p :fromaddress))
8405 (table
8406 (list
8407 (cons "%c" (plist-get p :fromto))
8408 (cons "%F" (plist-get p :from))
8409 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8410 (cons "%T" (plist-get p :to))
8411 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8412 (cons "%s" (plist-get p :subject))
8413 (cons "%m" (plist-get p :message-id)))))
8414 (when (string-match "%c" fmt)
8415 ;; Check if the user wrote this message
8416 (if (and org-from-is-user-regexp from to
8417 (save-match-data (string-match org-from-is-user-regexp from)))
8418 (setq fmt (replace-match "to %t" t t fmt))
8419 (setq fmt (replace-match "from %f" t t fmt))))
8420 (org-replace-escapes fmt table)))
8422 (defun org-make-org-heading-search-string (&optional string heading)
8423 "Make search string for STRING or current headline."
8424 (interactive)
8425 (let ((s (or string (org-get-heading))))
8426 (unless (and string (not heading))
8427 ;; We are using a headline, clean up garbage in there.
8428 (if (string-match org-todo-regexp s)
8429 (setq s (replace-match "" t t s)))
8430 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
8431 (setq s (replace-match "" t t s)))
8432 (setq s (org-trim s))
8433 (if (string-match (concat "^\\(" org-quote-string "\\|"
8434 org-comment-string "\\)") s)
8435 (setq s (replace-match "" t t s)))
8436 (while (string-match org-ts-regexp s)
8437 (setq s (replace-match "" t t s))))
8438 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
8439 (setq s (replace-match " " t t s)))
8440 (or string (setq s (concat "*" s))) ; Add * for headlines
8441 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8443 (defun org-make-link (&rest strings)
8444 "Concatenate STRINGS."
8445 (apply 'concat strings))
8447 (defun org-make-link-string (link &optional description)
8448 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8449 (unless (string-match "\\S-" link)
8450 (error "Empty link"))
8451 (when (and description
8452 (stringp description)
8453 (not (string-match "\\S-" description)))
8454 (setq description nil))
8455 (when (stringp description)
8456 ;; Remove brackets from the description, they are fatal.
8457 (while (string-match "\\[" description)
8458 (setq description (replace-match "{" t t description)))
8459 (while (string-match "\\]" description)
8460 (setq description (replace-match "}" t t description))))
8461 (when (equal (org-link-escape link) description)
8462 ;; No description needed, it is identical
8463 (setq description nil))
8464 (when (and (not description)
8465 (not (equal link (org-link-escape link))))
8466 (setq description (org-extract-attributes link)))
8467 (concat "[[" (org-link-escape link) "]"
8468 (if description (concat "[" description "]") "")
8469 "]"))
8471 (defconst org-link-escape-chars
8472 '((?\ . "%20")
8473 (?\[ . "%5B")
8474 (?\] . "%5D")
8475 (?\340 . "%E0") ; `a
8476 (?\342 . "%E2") ; ^a
8477 (?\347 . "%E7") ; ,c
8478 (?\350 . "%E8") ; `e
8479 (?\351 . "%E9") ; 'e
8480 (?\352 . "%EA") ; ^e
8481 (?\356 . "%EE") ; ^i
8482 (?\364 . "%F4") ; ^o
8483 (?\371 . "%F9") ; `u
8484 (?\373 . "%FB") ; ^u
8485 (?\; . "%3B")
8486 ;; (?? . "%3F")
8487 (?= . "%3D")
8488 (?+ . "%2B")
8490 "Association list of escapes for some characters problematic in links.
8491 This is the list that is used for internal purposes.")
8493 (defvar org-url-encoding-use-url-hexify nil)
8495 (defconst org-link-escape-chars-browser
8496 '((?\ . "%20")) ; 32 for the SPC char
8497 "Association list of escapes for some characters problematic in links.
8498 This is the list that is used before handing over to the browser.")
8500 (defun org-link-escape (text &optional table)
8501 "Escape characters in TEXT that are problematic for links."
8502 (if (and org-url-encoding-use-url-hexify (not table))
8503 (url-hexify-string text)
8504 (setq table (or table org-link-escape-chars))
8505 (when text
8506 (let ((re (mapconcat (lambda (x) (regexp-quote
8507 (char-to-string (car x))))
8508 table "\\|")))
8509 (while (string-match re text)
8510 (setq text
8511 (replace-match
8512 (cdr (assoc (string-to-char (match-string 0 text))
8513 table))
8514 t t text)))
8515 text))))
8517 (defun org-link-unescape (text &optional table)
8518 "Reverse the action of `org-link-escape'."
8519 (if (and org-url-encoding-use-url-hexify (not table))
8520 (url-unhex-string text)
8521 (setq table (or table org-link-escape-chars))
8522 (when text
8523 (let ((case-fold-search t)
8524 (re (mapconcat (lambda (x) (regexp-quote (downcase (cdr x))))
8525 table "\\|")))
8526 (while (string-match re text)
8527 (setq text
8528 (replace-match
8529 (char-to-string (car (rassoc (upcase (match-string 0 text))
8530 table)))
8531 t t text)))
8532 text))))
8534 (defun org-xor (a b)
8535 "Exclusive or."
8536 (if a (not b) b))
8538 (defun org-fixup-message-id-for-http (s)
8539 "Replace special characters in a message id, so it can be used in an http query."
8540 (when (string-match "%" s)
8541 (setq s (mapconcat (lambda (c)
8542 (if (eq c ?%)
8543 "%25"
8544 (char-to-string c)))
8545 s "")))
8546 (while (string-match "<" s)
8547 (setq s (replace-match "%3C" t t s)))
8548 (while (string-match ">" s)
8549 (setq s (replace-match "%3E" t t s)))
8550 (while (string-match "@" s)
8551 (setq s (replace-match "%40" t t s)))
8554 ;;;###autoload
8555 (defun org-insert-link-global ()
8556 "Insert a link like Org-mode does.
8557 This command can be called in any mode to insert a link in Org-mode syntax."
8558 (interactive)
8559 (org-load-modules-maybe)
8560 (org-run-like-in-org-mode 'org-insert-link))
8562 (defun org-insert-link (&optional complete-file link-location)
8563 "Insert a link. At the prompt, enter the link.
8565 Completion can be used to insert any of the link protocol prefixes like
8566 http or ftp in use.
8568 The history can be used to select a link previously stored with
8569 `org-store-link'. When the empty string is entered (i.e. if you just
8570 press RET at the prompt), the link defaults to the most recently
8571 stored link. As SPC triggers completion in the minibuffer, you need to
8572 use M-SPC or C-q SPC to force the insertion of a space character.
8574 You will also be prompted for a description, and if one is given, it will
8575 be displayed in the buffer instead of the link.
8577 If there is already a link at point, this command will allow you to edit link
8578 and description parts.
8580 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
8581 be selected using completion. The path to the file will be relative to the
8582 current directory if the file is in the current directory or a subdirectory.
8583 Otherwise, the link will be the absolute path as completed in the minibuffer
8584 \(i.e. normally ~/path/to/file). You can configure this behavior using the
8585 option `org-link-file-path-type'.
8587 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
8588 the current directory or below.
8590 With three \\[universal-argument] prefixes, negate the meaning of
8591 `org-keep-stored-link-after-insertion'.
8593 If `org-make-link-description-function' is non-nil, this function will be
8594 called with the link target, and the result will be the default
8595 link description.
8597 If the LINK-LOCATION parameter is non-nil, this value will be
8598 used as the link location instead of reading one interactively."
8599 (interactive "P")
8600 (let* ((wcf (current-window-configuration))
8601 (region (if (org-region-active-p)
8602 (buffer-substring (region-beginning) (region-end))))
8603 (remove (and region (list (region-beginning) (region-end))))
8604 (desc region)
8605 tmphist ; byte-compile incorrectly complains about this
8606 (link link-location)
8607 entry file all-prefixes)
8608 (cond
8609 (link-location) ; specified by arg, just use it.
8610 ((org-in-regexp org-bracket-link-regexp 1)
8611 ;; We do have a link at point, and we are going to edit it.
8612 (setq remove (list (match-beginning 0) (match-end 0)))
8613 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
8614 (setq link (read-string "Link: "
8615 (org-link-unescape
8616 (org-match-string-no-properties 1)))))
8617 ((or (org-in-regexp org-angle-link-re)
8618 (org-in-regexp org-plain-link-re))
8619 ;; Convert to bracket link
8620 (setq remove (list (match-beginning 0) (match-end 0))
8621 link (read-string "Link: "
8622 (org-remove-angle-brackets (match-string 0)))))
8623 ((member complete-file '((4) (16)))
8624 ;; Completing read for file names.
8625 (setq link (org-file-complete-link complete-file)))
8627 ;; Read link, with completion for stored links.
8628 (with-output-to-temp-buffer "*Org Links*"
8629 (princ "Insert a link.
8630 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
8631 (when org-stored-links
8632 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
8633 (princ (mapconcat
8634 (lambda (x)
8635 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
8636 (reverse org-stored-links) "\n"))))
8637 (let ((cw (selected-window)))
8638 (select-window (get-buffer-window "*Org Links*" 'visible))
8639 (setq truncate-lines t)
8640 (unless (pos-visible-in-window-p (point-max))
8641 (org-fit-window-to-buffer))
8642 (and (window-live-p cw) (select-window cw)))
8643 ;; Fake a link history, containing the stored links.
8644 (setq tmphist (append (mapcar 'car org-stored-links)
8645 org-insert-link-history))
8646 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
8647 (mapcar 'car org-link-abbrev-alist)
8648 org-link-types))
8649 (unwind-protect
8650 (progn
8651 (setq link
8652 (let ((org-completion-use-ido nil)
8653 (org-completion-use-iswitchb nil))
8654 (org-completing-read
8655 "Link: "
8656 (append
8657 (mapcar (lambda (x) (list (concat x ":")))
8658 all-prefixes)
8659 (mapcar 'car org-stored-links))
8660 nil nil nil
8661 'tmphist
8662 (car (car org-stored-links)))))
8663 (if (not (string-match "\\S-" link))
8664 (error "No link selected"))
8665 (if (or (member link all-prefixes)
8666 (and (equal ":" (substring link -1))
8667 (member (substring link 0 -1) all-prefixes)
8668 (setq link (substring link 0 -1))))
8669 (setq link (org-link-try-special-completion link))))
8670 (set-window-configuration wcf)
8671 (kill-buffer "*Org Links*"))
8672 (setq entry (assoc link org-stored-links))
8673 (or entry (push link org-insert-link-history))
8674 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
8675 (not org-keep-stored-link-after-insertion))
8676 (setq org-stored-links (delq (assoc link org-stored-links)
8677 org-stored-links)))
8678 (setq desc (or desc (nth 1 entry)))))
8680 (if (string-match org-plain-link-re link)
8681 ;; URL-like link, normalize the use of angular brackets.
8682 (setq link (org-make-link (org-remove-angle-brackets link))))
8684 ;; Check if we are linking to the current file with a search option
8685 ;; If yes, simplify the link by using only the search option.
8686 (when (and buffer-file-name
8687 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
8688 (let* ((path (match-string 1 link))
8689 (case-fold-search nil)
8690 (search (match-string 2 link)))
8691 (save-match-data
8692 (if (equal (file-truename buffer-file-name) (file-truename path))
8693 ;; We are linking to this same file, with a search option
8694 (setq link search)))))
8696 ;; Check if we can/should use a relative path. If yes, simplify the link
8697 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
8698 (let* ((type (match-string 1 link))
8699 (path (match-string 2 link))
8700 (origpath path)
8701 (case-fold-search nil))
8702 (cond
8703 ((or (eq org-link-file-path-type 'absolute)
8704 (equal complete-file '(16)))
8705 (setq path (abbreviate-file-name (expand-file-name path))))
8706 ((eq org-link-file-path-type 'noabbrev)
8707 (setq path (expand-file-name path)))
8708 ((eq org-link-file-path-type 'relative)
8709 (setq path (file-relative-name path)))
8711 (save-match-data
8712 (if (string-match (concat "^" (regexp-quote
8713 (expand-file-name
8714 (file-name-as-directory
8715 default-directory))))
8716 (expand-file-name path))
8717 ;; We are linking a file with relative path name.
8718 (setq path (substring (expand-file-name path)
8719 (match-end 0)))
8720 (setq path (abbreviate-file-name (expand-file-name path)))))))
8721 (setq link (concat type path))
8722 (if (equal desc origpath)
8723 (setq desc path))))
8725 (if org-make-link-description-function
8726 (setq desc (funcall org-make-link-description-function link desc)))
8728 (setq desc (read-string "Description: " desc))
8729 (unless (string-match "\\S-" desc) (setq desc nil))
8730 (if remove (apply 'delete-region remove))
8731 (insert (org-make-link-string link desc))))
8733 (defun org-link-try-special-completion (type)
8734 "If there is completion support for link type TYPE, offer it."
8735 (let ((fun (intern (concat "org-" type "-complete-link"))))
8736 (if (functionp fun)
8737 (funcall fun)
8738 (read-string "Link (no completion support): " (concat type ":")))))
8740 (defun org-file-complete-link (&optional arg)
8741 "Create a file link using completion."
8742 (let (file link)
8743 (setq file (read-file-name "File: "))
8744 (let ((pwd (file-name-as-directory (expand-file-name ".")))
8745 (pwd1 (file-name-as-directory (abbreviate-file-name
8746 (expand-file-name ".")))))
8747 (cond
8748 ((equal arg '(16))
8749 (setq link (org-make-link
8750 "file:"
8751 (abbreviate-file-name (expand-file-name file)))))
8752 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
8753 (setq link (org-make-link "file:" (match-string 1 file))))
8754 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
8755 (expand-file-name file))
8756 (setq link (org-make-link
8757 "file:" (match-string 1 (expand-file-name file)))))
8758 (t (setq link (org-make-link "file:" file)))))
8759 link))
8761 (defun org-completing-read (&rest args)
8762 "Completing-read with SPACE being a normal character."
8763 (let ((minibuffer-local-completion-map
8764 (copy-keymap minibuffer-local-completion-map)))
8765 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
8766 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
8767 (apply 'org-icompleting-read args)))
8769 (defun org-completing-read-no-i (&rest args)
8770 (let (org-completion-use-ido org-completion-use-iswitchb)
8771 (apply 'org-completing-read args)))
8773 (defun org-iswitchb-completing-read (prompt choices &rest args)
8774 "Use iswitch as a completing-read replacement to choose from choices.
8775 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
8776 from."
8777 (let* ((iswitchb-use-virtual-buffers nil)
8778 (iswitchb-make-buflist-hook
8779 (lambda ()
8780 (setq iswitchb-temp-buflist choices))))
8781 (iswitchb-read-buffer prompt)))
8783 (defun org-icompleting-read (&rest args)
8784 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
8785 (org-without-partial-completion
8786 (if (and org-completion-use-ido
8787 (fboundp 'ido-completing-read)
8788 (boundp 'ido-mode) ido-mode
8789 (listp (second args)))
8790 (let ((ido-enter-matching-directory nil))
8791 (apply 'ido-completing-read (concat (car args))
8792 (if (consp (car (nth 1 args)))
8793 (mapcar (lambda (x) (car x)) (nth 1 args))
8794 (nth 1 args))
8795 (cddr args)))
8796 (if (and org-completion-use-iswitchb
8797 (boundp 'iswitchb-mode) iswitchb-mode
8798 (listp (second args)))
8799 (apply 'org-iswitchb-completing-read (concat (car args))
8800 (if (consp (car (nth 1 args)))
8801 (mapcar (lambda (x) (car x)) (nth 1 args))
8802 (nth 1 args))
8803 (cddr args))
8804 (apply 'completing-read args)))))
8806 (defun org-extract-attributes (s)
8807 "Extract the attributes cookie from a string and set as text property."
8808 (let (a attr (start 0) key value)
8809 (save-match-data
8810 (when (string-match "{{\\([^}]+\\)}}$" s)
8811 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
8812 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
8813 (setq key (match-string 1 a) value (match-string 2 a)
8814 start (match-end 0)
8815 attr (plist-put attr (intern key) value))))
8816 (org-add-props s nil 'org-attr attr))
8819 (defun org-extract-attributes-from-string (tag)
8820 (let (key value attr)
8821 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
8822 (setq key (match-string 1 tag) value (match-string 2 tag)
8823 tag (replace-match "" t t tag)
8824 attr (plist-put attr (intern key) value)))
8825 (cons tag attr)))
8827 (defun org-attributes-to-string (plist)
8828 "Format a property list into an HTML attribute list."
8829 (let ((s "") key value)
8830 (while plist
8831 (setq key (pop plist) value (pop plist))
8832 (and value
8833 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
8836 ;;; Opening/following a link
8838 (defvar org-link-search-failed nil)
8840 (defvar org-open-link-functions nil
8841 "Hook for functions finding a plain text link.
8842 These functions must take a single argument, the link content.
8843 They will be called for links that look like [[link text][description]]
8844 when LINK TEXT does not have a protocol like \"http:\" and does not look
8845 like a filename (e.g. \"./blue.png\").
8847 These functions will be called *before* Org attempts to resolve the
8848 link by doing text searches in the current buffer - so if you want a
8849 link \"[[target]]\" to still find \"<<target>>\", your function should
8850 handle this as a special case.
8852 When the function does handle the link, it must return a non-nil value.
8853 If it decides that it is not responsible for this link, it must return
8854 nil to indicate that that Org-mode can continue with other options
8855 like exact and fuzzy text search.")
8857 (defun org-next-link ()
8858 "Move forward to the next link.
8859 If the link is in hidden text, expose it."
8860 (interactive)
8861 (when (and org-link-search-failed (eq this-command last-command))
8862 (goto-char (point-min))
8863 (message "Link search wrapped back to beginning of buffer"))
8864 (setq org-link-search-failed nil)
8865 (let* ((pos (point))
8866 (ct (org-context))
8867 (a (assoc :link ct)))
8868 (if a (goto-char (nth 2 a)))
8869 (if (re-search-forward org-any-link-re nil t)
8870 (progn
8871 (goto-char (match-beginning 0))
8872 (if (org-invisible-p) (org-show-context)))
8873 (goto-char pos)
8874 (setq org-link-search-failed t)
8875 (error "No further link found"))))
8877 (defun org-previous-link ()
8878 "Move backward to the previous link.
8879 If the link is in hidden text, expose it."
8880 (interactive)
8881 (when (and org-link-search-failed (eq this-command last-command))
8882 (goto-char (point-max))
8883 (message "Link search wrapped back to end of buffer"))
8884 (setq org-link-search-failed nil)
8885 (let* ((pos (point))
8886 (ct (org-context))
8887 (a (assoc :link ct)))
8888 (if a (goto-char (nth 1 a)))
8889 (if (re-search-backward org-any-link-re nil t)
8890 (progn
8891 (goto-char (match-beginning 0))
8892 (if (org-invisible-p) (org-show-context)))
8893 (goto-char pos)
8894 (setq org-link-search-failed t)
8895 (error "No further link found"))))
8897 (defun org-translate-link (s)
8898 "Translate a link string if a translation function has been defined."
8899 (if (and org-link-translation-function
8900 (fboundp org-link-translation-function)
8901 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
8902 (progn
8903 (setq s (funcall org-link-translation-function
8904 (match-string 1) (match-string 2)))
8905 (concat (car s) ":" (cdr s)))
8908 (defun org-translate-link-from-planner (type path)
8909 "Translate a link from Emacs Planner syntax so that Org can follow it.
8910 This is still an experimental function, your mileage may vary."
8911 (cond
8912 ((member type '("http" "https" "news" "ftp"))
8913 ;; standard Internet links are the same.
8914 nil)
8915 ((and (equal type "irc") (string-match "^//" path))
8916 ;; Planner has two / at the beginning of an irc link, we have 1.
8917 ;; We should have zero, actually....
8918 (setq path (substring path 1)))
8919 ((and (equal type "lisp") (string-match "^/" path))
8920 ;; Planner has a slash, we do not.
8921 (setq type "elisp" path (substring path 1)))
8922 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
8923 ;; A typical message link. Planner has the id after the final slash,
8924 ;; we separate it with a hash mark
8925 (setq path (concat (match-string 1 path) "#"
8926 (org-remove-angle-brackets (match-string 2 path)))))
8928 (cons type path))
8930 (defun org-find-file-at-mouse (ev)
8931 "Open file link or URL at mouse."
8932 (interactive "e")
8933 (mouse-set-point ev)
8934 (org-open-at-point 'in-emacs))
8936 (defun org-open-at-mouse (ev)
8937 "Open file link or URL at mouse."
8938 (interactive "e")
8939 (mouse-set-point ev)
8940 (if (eq major-mode 'org-agenda-mode)
8941 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
8942 (org-open-at-point))
8944 (defvar org-window-config-before-follow-link nil
8945 "The window configuration before following a link.
8946 This is saved in case the need arises to restore it.")
8948 (defvar org-open-link-marker (make-marker)
8949 "Marker pointing to the location where `org-open-at-point; was called.")
8951 ;;;###autoload
8952 (defun org-open-at-point-global ()
8953 "Follow a link like Org-mode does.
8954 This command can be called in any mode to follow a link that has
8955 Org-mode syntax."
8956 (interactive)
8957 (org-run-like-in-org-mode 'org-open-at-point))
8959 ;;;###autoload
8960 (defun org-open-link-from-string (s &optional arg reference-buffer)
8961 "Open a link in the string S, as if it was in Org-mode."
8962 (interactive "sLink: \nP")
8963 (let ((reference-buffer (or reference-buffer (current-buffer))))
8964 (with-temp-buffer
8965 (let ((org-inhibit-startup t))
8966 (org-mode)
8967 (insert s)
8968 (goto-char (point-min))
8969 (when reference-buffer
8970 (setq org-link-abbrev-alist-local
8971 (with-current-buffer reference-buffer
8972 org-link-abbrev-alist-local)))
8973 (org-open-at-point arg reference-buffer)))))
8975 (defun org-open-at-point (&optional in-emacs reference-buffer)
8976 "Open link at or after point.
8977 If there is no link at point, this function will search forward up to
8978 the end of the current line.
8979 Normally, files will be opened by an appropriate application. If the
8980 optional argument IN-EMACS is non-nil, Emacs will visit the file.
8981 With a double prefix argument, try to open outside of Emacs, in the
8982 application the system uses for this file type."
8983 (interactive "P")
8984 ;; if in a code block, then open the block's results
8985 (unless (call-interactively #'org-babel-open-src-block-result)
8986 (org-load-modules-maybe)
8987 (move-marker org-open-link-marker (point))
8988 (setq org-window-config-before-follow-link (current-window-configuration))
8989 (org-remove-occur-highlights nil nil t)
8990 (cond
8991 ((and (org-on-heading-p)
8992 (not (org-in-regexp
8993 (concat org-plain-link-re "\\|"
8994 org-bracket-link-regexp "\\|"
8995 org-angle-link-re "\\|"
8996 "[ \t]:[^ \t\n]+:[ \t]*$")))
8997 (not (get-text-property (point) 'org-linked-text)))
8998 (or (org-offer-links-in-entry in-emacs)
8999 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9000 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9001 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9002 (org-footnote-action))
9004 (let (type path link line search (pos (point)))
9005 (catch 'match
9006 (save-excursion
9007 (skip-chars-forward "^]\n\r")
9008 (when (org-in-regexp org-bracket-link-regexp 1)
9009 (setq link (org-extract-attributes
9010 (org-link-unescape (org-match-string-no-properties 1))))
9011 (while (string-match " *\n *" link)
9012 (setq link (replace-match " " t t link)))
9013 (setq link (org-link-expand-abbrev link))
9014 (cond
9015 ((or (file-name-absolute-p link)
9016 (string-match "^\\.\\.?/" link))
9017 (setq type "file" path link))
9018 ((string-match org-link-re-with-space3 link)
9019 (setq type (match-string 1 link) path (match-string 2 link)))
9020 (t (setq type "thisfile" path link)))
9021 (throw 'match t)))
9023 (when (get-text-property (point) 'org-linked-text)
9024 (setq type "thisfile"
9025 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9026 (1+ (point)) (point))
9027 path (buffer-substring
9028 (previous-single-property-change pos 'org-linked-text)
9029 (next-single-property-change pos 'org-linked-text)))
9030 (throw 'match t))
9032 (save-excursion
9033 (when (or (org-in-regexp org-angle-link-re)
9034 (org-in-regexp org-plain-link-re))
9035 (setq type (match-string 1) path (match-string 2))
9036 (throw 'match t)))
9037 (save-excursion
9038 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
9039 (setq type "tags"
9040 path (match-string 1))
9041 (while (string-match ":" path)
9042 (setq path (replace-match "+" t t path)))
9043 (throw 'match t)))
9044 (when (org-in-regexp "<\\([^><\n]+\\)>")
9045 (setq type "tree-match"
9046 path (match-string 1))
9047 (throw 'match t)))
9048 (unless path
9049 (error "No link found"))
9051 ;; switch back to reference buffer
9052 ;; needed when if called in a temporary buffer through
9053 ;; org-open-link-from-string
9054 (with-current-buffer (or reference-buffer (current-buffer))
9056 ;; Remove any trailing spaces in path
9057 (if (string-match " +\\'" path)
9058 (setq path (replace-match "" t t path)))
9059 (if (and org-link-translation-function
9060 (fboundp org-link-translation-function))
9061 ;; Check if we need to translate the link
9062 (let ((tmp (funcall org-link-translation-function type path)))
9063 (setq type (car tmp) path (cdr tmp))))
9065 (cond
9067 ((assoc type org-link-protocols)
9068 (funcall (nth 1 (assoc type org-link-protocols)) path))
9070 ((equal type "mailto")
9071 (let ((cmd (car org-link-mailto-program))
9072 (args (cdr org-link-mailto-program)) args1
9073 (address path) (subject "") a)
9074 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9075 (setq address (match-string 1 path)
9076 subject (org-link-escape (match-string 2 path))))
9077 (while args
9078 (cond
9079 ((not (stringp (car args))) (push (pop args) args1))
9080 (t (setq a (pop args))
9081 (if (string-match "%a" a)
9082 (setq a (replace-match address t t a)))
9083 (if (string-match "%s" a)
9084 (setq a (replace-match subject t t a)))
9085 (push a args1))))
9086 (apply cmd (nreverse args1))))
9088 ((member type '("http" "https" "ftp" "news"))
9089 (browse-url (concat type ":" (org-link-escape
9090 path org-link-escape-chars-browser))))
9092 ((string= type "doi")
9093 (browse-url (concat "http://dx.doi.org/"
9094 (org-link-escape
9095 path org-link-escape-chars-browser))))
9097 ((member type '("message"))
9098 (browse-url (concat type ":" path)))
9100 ((string= type "tags")
9101 (org-tags-view in-emacs path))
9103 ((string= type "tree-match")
9104 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9106 ((string= type "file")
9107 (if (string-match "::\\([0-9]+\\)\\'" path)
9108 (setq line (string-to-number (match-string 1 path))
9109 path (substring path 0 (match-beginning 0)))
9110 (if (string-match "::\\(.+\\)\\'" path)
9111 (setq search (match-string 1 path)
9112 path (substring path 0 (match-beginning 0)))))
9113 (if (string-match "[*?{]" (file-name-nondirectory path))
9114 (dired path)
9115 (org-open-file path in-emacs line search)))
9117 ((string= type "news")
9118 (require 'org-gnus)
9119 (org-gnus-follow-link path))
9121 ((string= type "shell")
9122 (let ((cmd path))
9123 (if (or (not org-confirm-shell-link-function)
9124 (funcall org-confirm-shell-link-function
9125 (format "Execute \"%s\" in shell? "
9126 (org-add-props cmd nil
9127 'face 'org-warning))))
9128 (progn
9129 (message "Executing %s" cmd)
9130 (shell-command cmd))
9131 (error "Abort"))))
9133 ((string= type "elisp")
9134 (let ((cmd path))
9135 (if (or (not org-confirm-elisp-link-function)
9136 (funcall org-confirm-elisp-link-function
9137 (format "Execute \"%s\" as elisp? "
9138 (org-add-props cmd nil
9139 'face 'org-warning))))
9140 (message "%s => %s" cmd
9141 (if (equal (string-to-char cmd) ?\()
9142 (eval (read cmd))
9143 (call-interactively (read cmd))))
9144 (error "Abort"))))
9146 ((and (string= type "thisfile")
9147 (run-hook-with-args-until-success
9148 'org-open-link-functions path)))
9150 ((string= type "thisfile")
9151 (if in-emacs
9152 (switch-to-buffer-other-window
9153 (org-get-buffer-for-internal-link (current-buffer)))
9154 (org-mark-ring-push))
9155 (let ((cmd `(org-link-search
9156 ,path
9157 ,(cond ((equal in-emacs '(4)) 'occur)
9158 ((equal in-emacs '(16)) 'org-occur)
9159 (t nil))
9160 ,pos)))
9161 (condition-case nil (eval cmd)
9162 (error (progn (widen) (eval cmd))))))
9165 (browse-url-at-point)))))))
9166 (move-marker org-open-link-marker nil)
9167 (run-hook-with-args 'org-follow-link-hook)))
9169 (defun org-offer-links-in-entry (&optional nth zero)
9170 "Offer links in the current entry and follow the selected link.
9171 If there is only one link, follow it immediately as well.
9172 If NTH is an integer, immediately pick the NTH link found.
9173 If ZERO is a string, check also this string for a link, and if
9174 there is one, offer it as link number zero."
9175 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9176 "\\(" org-angle-link-re "\\)\\|"
9177 "\\(" org-plain-link-re "\\)"))
9178 (cnt ?0)
9179 (in-emacs (if (integerp nth) nil nth))
9180 have-zero end links link c)
9181 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9182 (push (match-string 0 zero) links)
9183 (setq cnt (1- cnt) have-zero t))
9184 (save-excursion
9185 (org-back-to-heading t)
9186 (setq end (save-excursion (outline-next-heading) (point)))
9187 (while (re-search-forward re end t)
9188 (push (match-string 0) links))
9189 (setq links (org-uniquify (reverse links))))
9191 (cond
9192 ((null links)
9193 (message "No links"))
9194 ((equal (length links) 1)
9195 (setq link (list (car links))))
9196 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9197 (setq link (nth (if have-zero nth (1- nth)) links)))
9198 (t ; we have to select a link
9199 (save-excursion
9200 (save-window-excursion
9201 (delete-other-windows)
9202 (with-output-to-temp-buffer "*Select Link*"
9203 (mapc (lambda (l)
9204 (if (not (string-match org-bracket-link-regexp l))
9205 (princ (format "[%c] %s\n" (incf cnt)
9206 (org-remove-angle-brackets l)))
9207 (if (match-end 3)
9208 (princ (format "[%c] %s (%s)\n" (incf cnt)
9209 (match-string 3 l) (match-string 1 l)))
9210 (princ (format "[%c] %s\n" (incf cnt)
9211 (match-string 1 l))))))
9212 links))
9213 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9214 (message "Select link to open, RET to open all:")
9215 (setq c (read-char-exclusive))
9216 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9217 (when (equal c ?q) (error "Abort"))
9218 (if (equal c ?\C-m)
9219 (setq link links)
9220 (setq nth (- c ?0))
9221 (if have-zero (setq nth (1+ nth)))
9222 (unless (and (integerp nth) (>= (length links) nth))
9223 (error "Invalid link selection"))
9224 (setq link (list (nth (1- nth) links))))))
9225 (if link
9226 (let ((buf (current-buffer)))
9227 (dolist (l link)
9228 (org-open-link-from-string l in-emacs buf))
9230 nil)))
9232 ;; Add special file links that specify the way of opening
9234 (org-add-link-type "file+sys" 'org-open-file-with-system)
9235 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9236 (defun org-open-file-with-system (path)
9237 "Open file at PATH using the system way of opening it."
9238 (org-open-file path 'system))
9239 (defun org-open-file-with-emacs (path)
9240 "Open file at PATH in Emacs."
9241 (org-open-file path 'emacs))
9242 (defun org-remove-file-link-modifiers ()
9243 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9244 (goto-char (point-min))
9245 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9246 (org-if-unprotected
9247 (replace-match "file:" t t))))
9248 (eval-after-load "org-exp"
9249 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9250 'org-remove-file-link-modifiers))
9252 ;;;; Time estimates
9254 (defun org-get-effort (&optional pom)
9255 "Get the effort estimate for the current entry."
9256 (org-entry-get pom org-effort-property))
9258 ;;; File search
9260 (defvar org-create-file-search-functions nil
9261 "List of functions to construct the right search string for a file link.
9262 These functions are called in turn with point at the location to
9263 which the link should point.
9265 A function in the hook should first test if it would like to
9266 handle this file type, for example by checking the `major-mode'
9267 or the file extension. If it decides not to handle this file, it
9268 should just return nil to give other functions a chance. If it
9269 does handle the file, it must return the search string to be used
9270 when following the link. The search string will be part of the
9271 file link, given after a double colon, and `org-open-at-point'
9272 will automatically search for it. If special measures must be
9273 taken to make the search successful, another function should be
9274 added to the companion hook `org-execute-file-search-functions',
9275 which see.
9277 A function in this hook may also use `setq' to set the variable
9278 `description' to provide a suggestion for the descriptive text to
9279 be used for this link when it gets inserted into an Org-mode
9280 buffer with \\[org-insert-link].")
9282 (defvar org-execute-file-search-functions nil
9283 "List of functions to execute a file search triggered by a link.
9285 Functions added to this hook must accept a single argument, the
9286 search string that was part of the file link, the part after the
9287 double colon. The function must first check if it would like to
9288 handle this search, for example by checking the `major-mode' or
9289 the file extension. If it decides not to handle this search, it
9290 should just return nil to give other functions a chance. If it
9291 does handle the search, it must return a non-nil value to keep
9292 other functions from trying.
9294 Each function can access the current prefix argument through the
9295 variable `current-prefix-argument'. Note that a single prefix is
9296 used to force opening a link in Emacs, so it may be good to only
9297 use a numeric or double prefix to guide the search function.
9299 In case this is needed, a function in this hook can also restore
9300 the window configuration before `org-open-at-point' was called using:
9302 (set-window-configuration org-window-config-before-follow-link)")
9304 (defun org-link-search (s &optional type avoid-pos)
9305 "Search for a link search option.
9306 If S is surrounded by forward slashes, it is interpreted as a
9307 regular expression. In org-mode files, this will create an `org-occur'
9308 sparse tree. In ordinary files, `occur' will be used to list matches.
9309 If the current buffer is in `dired-mode', grep will be used to search
9310 in all files. If AVOID-POS is given, ignore matches near that position."
9311 (let ((case-fold-search t)
9312 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9313 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9314 (append '(("") (" ") ("\t") ("\n"))
9315 org-emphasis-alist)
9316 "\\|") "\\)"))
9317 (pos (point))
9318 (pre nil) (post nil)
9319 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9320 (cond
9321 ;; First check if there are any special
9322 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9323 ;; Now try the builtin stuff
9324 ((and (equal (string-to-char s0) ?#)
9325 (> (length s0) 1)
9326 (save-excursion
9327 (goto-char (point-min))
9328 (and
9329 (re-search-forward
9330 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9331 (setq type 'dedicated
9332 pos (match-beginning 0))))
9333 ;; There is an exact target for this
9334 (goto-char pos)
9335 (org-back-to-heading t)))
9336 ((save-excursion
9337 (goto-char (point-min))
9338 (and
9339 (re-search-forward
9340 (concat "<<" (regexp-quote s0) ">>") nil t)
9341 (setq type 'dedicated
9342 pos (match-beginning 0))))
9343 ;; There is an exact target for this
9344 (goto-char pos))
9345 ((and (string-match "^(\\(.*\\))$" s0)
9346 (save-excursion
9347 (goto-char (point-min))
9348 (and
9349 (re-search-forward
9350 (concat "[^[]" (regexp-quote
9351 (format org-coderef-label-format
9352 (match-string 1 s0))))
9353 nil t)
9354 (setq type 'dedicated
9355 pos (1+ (match-beginning 0))))))
9356 ;; There is a coderef target for this
9357 (goto-char pos))
9358 ((string-match "^/\\(.*\\)/$" s)
9359 ;; A regular expression
9360 (cond
9361 ((org-mode-p)
9362 (org-occur (match-string 1 s)))
9363 ;;((eq major-mode 'dired-mode)
9364 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9365 (t (org-do-occur (match-string 1 s)))))
9367 ;; A normal search strings
9368 (when (equal (string-to-char s) ?*)
9369 ;; Anchor on headlines, post may include tags.
9370 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
9371 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
9372 s (substring s 1)))
9373 (remove-text-properties
9374 0 (length s)
9375 '(face nil mouse-face nil keymap nil fontified nil) s)
9376 ;; Make a series of regular expressions to find a match
9377 (setq words (org-split-string s "[ \n\r\t]+")
9379 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9380 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
9381 "\\)" markers)
9382 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9383 re2a (concat "[ \t\r\n]" re2a_)
9384 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9385 re4 (concat "[^a-zA-Z_]" re4_)
9387 re1 (concat pre re2 post)
9388 re3 (concat pre (if pre re4_ re4) post)
9389 re5 (concat pre ".*" re4)
9390 re2 (concat pre re2)
9391 re2a (concat pre (if pre re2a_ re2a))
9392 re4 (concat pre (if pre re4_ re4))
9393 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9394 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9395 re5 "\\)"
9397 (cond
9398 ((eq type 'org-occur) (org-occur reall))
9399 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9400 (t (goto-char (point-min))
9401 (setq type 'fuzzy)
9402 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
9403 (org-search-not-self 1 re1 nil t)
9404 (org-search-not-self 1 re2 nil t)
9405 (org-search-not-self 1 re2a nil t)
9406 (org-search-not-self 1 re3 nil t)
9407 (org-search-not-self 1 re4 nil t)
9408 (org-search-not-self 1 re5 nil t)
9410 (goto-char (match-beginning 1))
9411 (goto-char pos)
9412 (error "No match")))))
9414 ;; Normal string-search
9415 (goto-char (point-min))
9416 (if (search-forward s nil t)
9417 (goto-char (match-beginning 0))
9418 (error "No match"))))
9419 (and (org-mode-p) (org-show-context 'link-search))
9420 type))
9422 (defun org-search-not-self (group &rest args)
9423 "Execute `re-search-forward', but only accept matches that do not
9424 enclose the position of `org-open-link-marker'."
9425 (let ((m org-open-link-marker))
9426 (catch 'exit
9427 (while (apply 're-search-forward args)
9428 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
9429 (goto-char (match-end group))
9430 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
9431 (> (match-beginning 0) (marker-position m))
9432 (< (match-end 0) (marker-position m)))
9433 (save-match-data
9434 (or (not (org-in-regexp
9435 org-bracket-link-analytic-regexp 1))
9436 (not (match-end 4)) ; no description
9437 (and (<= (match-beginning 4) (point))
9438 (>= (match-end 4) (point))))))
9439 (throw 'exit (point))))))))
9441 (defun org-get-buffer-for-internal-link (buffer)
9442 "Return a buffer to be used for displaying the link target of internal links."
9443 (cond
9444 ((not org-display-internal-link-with-indirect-buffer)
9445 buffer)
9446 ((string-match "(Clone)$" (buffer-name buffer))
9447 (message "Buffer is already a clone, not making another one")
9448 ;; we also do not modify visibility in this case
9449 buffer)
9450 (t ; make a new indirect buffer for displaying the link
9451 (let* ((bn (buffer-name buffer))
9452 (ibn (concat bn "(Clone)"))
9453 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
9454 (with-current-buffer ib (org-overview))
9455 ib))))
9457 (defun org-do-occur (regexp &optional cleanup)
9458 "Call the Emacs command `occur'.
9459 If CLEANUP is non-nil, remove the printout of the regular expression
9460 in the *Occur* buffer. This is useful if the regex is long and not useful
9461 to read."
9462 (occur regexp)
9463 (when cleanup
9464 (let ((cwin (selected-window)) win beg end)
9465 (when (setq win (get-buffer-window "*Occur*"))
9466 (select-window win))
9467 (goto-char (point-min))
9468 (when (re-search-forward "match[a-z]+" nil t)
9469 (setq beg (match-end 0))
9470 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9471 (setq end (1- (match-beginning 0)))))
9472 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
9473 (goto-char (point-min))
9474 (select-window cwin))))
9476 ;;; The mark ring for links jumps
9478 (defvar org-mark-ring nil
9479 "Mark ring for positions before jumps in Org-mode.")
9480 (defvar org-mark-ring-last-goto nil
9481 "Last position in the mark ring used to go back.")
9482 ;; Fill and close the ring
9483 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9484 (loop for i from 1 to org-mark-ring-length do
9485 (push (make-marker) org-mark-ring))
9486 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
9487 org-mark-ring)
9489 (defun org-mark-ring-push (&optional pos buffer)
9490 "Put the current position or POS into the mark ring and rotate it."
9491 (interactive)
9492 (setq pos (or pos (point)))
9493 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
9494 (move-marker (car org-mark-ring)
9495 (or pos (point))
9496 (or buffer (current-buffer)))
9497 (message "%s"
9498 (substitute-command-keys
9499 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
9501 (defun org-mark-ring-goto (&optional n)
9502 "Jump to the previous position in the mark ring.
9503 With prefix arg N, jump back that many stored positions. When
9504 called several times in succession, walk through the entire ring.
9505 Org-mode commands jumping to a different position in the current file,
9506 or to another Org-mode file, automatically push the old position
9507 onto the ring."
9508 (interactive "p")
9509 (let (p m)
9510 (if (eq last-command this-command)
9511 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
9512 (setq p org-mark-ring))
9513 (setq org-mark-ring-last-goto p)
9514 (setq m (car p))
9515 (switch-to-buffer (marker-buffer m))
9516 (goto-char m)
9517 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
9519 (defun org-remove-angle-brackets (s)
9520 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
9521 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
9523 (defun org-add-angle-brackets (s)
9524 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
9525 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
9527 (defun org-remove-double-quotes (s)
9528 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
9529 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
9532 ;;; Following specific links
9534 (defun org-follow-timestamp-link ()
9535 (cond
9536 ((org-at-date-range-p t)
9537 (let ((org-agenda-start-on-weekday)
9538 (t1 (match-string 1))
9539 (t2 (match-string 2)))
9540 (setq t1 (time-to-days (org-time-string-to-time t1))
9541 t2 (time-to-days (org-time-string-to-time t2)))
9542 (org-agenda-list nil t1 (1+ (- t2 t1)))))
9543 ((org-at-timestamp-p t)
9544 (org-agenda-list nil (time-to-days (org-time-string-to-time
9545 (substring (match-string 1) 0 10)))
9547 (t (error "This should not happen"))))
9550 ;;; Following file links
9551 (defvar org-wait nil)
9552 (defun org-open-file (path &optional in-emacs line search)
9553 "Open the file at PATH.
9554 First, this expands any special file name abbreviations. Then the
9555 configuration variable `org-file-apps' is checked if it contains an
9556 entry for this file type, and if yes, the corresponding command is launched.
9558 If no application is found, Emacs simply visits the file.
9560 With optional prefix argument IN-EMACS, Emacs will visit the file.
9561 With a double \\[universal-argument] \\[universal-argument] \
9562 prefix arg, Org tries to avoid opening in Emacs
9563 and to use an external application to visit the file.
9565 Optional LINE specifies a line to go to, optional SEARCH a string
9566 to search for. If LINE or SEARCH is given, the file will be
9567 opened in Emacs, unless an entry from org-file-apps that makes
9568 use of groups in a regexp matches.
9569 If the file does not exist, an error is thrown."
9570 (let* ((file (if (equal path "")
9571 buffer-file-name
9572 (substitute-in-file-name (expand-file-name path))))
9573 (file-apps (append org-file-apps (org-default-apps)))
9574 (apps (org-remove-if
9575 'org-file-apps-entry-match-against-dlink-p file-apps))
9576 (apps-dlink (org-remove-if-not
9577 'org-file-apps-entry-match-against-dlink-p file-apps))
9578 (remp (and (assq 'remote apps) (org-file-remote-p file)))
9579 (dirp (if remp nil (file-directory-p file)))
9580 (file (if (and dirp org-open-directory-means-index-dot-org)
9581 (concat (file-name-as-directory file) "index.org")
9582 file))
9583 (a-m-a-p (assq 'auto-mode apps))
9584 (dfile (downcase file))
9585 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
9586 (link (cond ((and (eq line nil)
9587 (eq search nil))
9588 file)
9589 (line
9590 (concat file "::" (number-to-string line)))
9591 (search
9592 (concat file "::" search))))
9593 (dlink (downcase link))
9594 (old-buffer (current-buffer))
9595 (old-pos (point))
9596 (old-mode major-mode)
9597 ext cmd link-match-data)
9598 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
9599 (setq ext (match-string 1 dfile))
9600 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
9601 (setq ext (match-string 1 dfile))))
9602 (cond
9603 ((member in-emacs '((16) system))
9604 (setq cmd (cdr (assoc 'system apps))))
9605 (in-emacs (setq cmd 'emacs))
9607 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
9608 (and dirp (cdr (assoc 'directory apps)))
9609 ; first, try matching against apps-dlink
9610 ; if we get a match here, store the match data for later
9611 (let ((match (assoc-default dlink apps-dlink
9612 'string-match)))
9613 (if match
9614 (progn (setq link-match-data (match-data))
9615 match)
9616 (progn (setq in-emacs (or in-emacs line search))
9617 nil))) ; if we have no match in apps-dlink,
9618 ; always open the file in emacs if line or search
9619 ; is given (for backwards compatibility)
9620 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
9621 'string-match)
9622 (cdr (assoc ext apps))
9623 (cdr (assoc t apps))))))
9624 (when (eq cmd 'system)
9625 (setq cmd (cdr (assoc 'system apps))))
9626 (when (eq cmd 'default)
9627 (setq cmd (cdr (assoc t apps))))
9628 (when (eq cmd 'mailcap)
9629 (require 'mailcap)
9630 (mailcap-parse-mailcaps)
9631 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
9632 (command (mailcap-mime-info mime-type)))
9633 (if (stringp command)
9634 (setq cmd command)
9635 (setq cmd 'emacs))))
9636 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
9637 (not (file-exists-p file))
9638 (not org-open-non-existing-files))
9639 (error "No such file: %s" file))
9640 (cond
9641 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
9642 ;; Remove quotes around the file name - we'll use shell-quote-argument.
9643 (while (string-match "['\"]%s['\"]" cmd)
9644 (setq cmd (replace-match "%s" t t cmd)))
9645 (while (string-match "%s" cmd)
9646 (setq cmd (replace-match
9647 (save-match-data
9648 (shell-quote-argument
9649 (convert-standard-filename file)))
9650 t t cmd)))
9652 ;; Replace "%1", "%2" etc. in command with group matches from regex
9653 (save-match-data
9654 (let ((match-index 1)
9655 (number-of-groups (- (/ (length link-match-data) 2) 1)))
9656 (set-match-data link-match-data)
9657 (while (<= match-index number-of-groups)
9658 (let ((regex (concat "%" (number-to-string match-index)))
9659 (replace-with (match-string match-index dlink)))
9660 (while (string-match regex cmd)
9661 (setq cmd (replace-match replace-with t t cmd))))
9662 (setq match-index (+ match-index 1)))))
9664 (save-window-excursion
9665 (start-process-shell-command cmd nil cmd)
9666 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
9668 ((or (stringp cmd)
9669 (eq cmd 'emacs))
9670 (funcall (cdr (assq 'file org-link-frame-setup)) file)
9671 (widen)
9672 (if line (org-goto-line line)
9673 (if search (org-link-search search))))
9674 ((consp cmd)
9675 (let ((file (convert-standard-filename file)))
9676 (save-match-data
9677 (set-match-data link-match-data)
9678 (eval cmd))))
9679 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
9680 (and (org-mode-p) (eq old-mode 'org-mode)
9681 (or (not (equal old-buffer (current-buffer)))
9682 (not (equal old-pos (point))))
9683 (org-mark-ring-push old-pos old-buffer))))
9685 (defun org-file-apps-entry-match-against-dlink-p (entry)
9686 "This function returns non-nil if `entry' uses a regular
9687 expression which should be matched against the whole link by
9688 org-open-file.
9690 It assumes that is the case when the entry uses a regular
9691 expression which has at least one grouping construct and the
9692 action is either a lisp form or a command string containing
9693 '%1', i.e. using at least one subexpression match as a
9694 parameter."
9695 (let ((selector (car entry))
9696 (action (cdr entry)))
9697 (if (stringp selector)
9698 (and (> (regexp-opt-depth selector) 0)
9699 (or (and (stringp action)
9700 (string-match "%[0-9]" action))
9701 (consp action)))
9702 nil)))
9704 (defun org-default-apps ()
9705 "Return the default applications for this operating system."
9706 (cond
9707 ((eq system-type 'darwin)
9708 org-file-apps-defaults-macosx)
9709 ((eq system-type 'windows-nt)
9710 org-file-apps-defaults-windowsnt)
9711 (t org-file-apps-defaults-gnu)))
9713 (defun org-apps-regexp-alist (list &optional add-auto-mode)
9714 "Convert extensions to regular expressions in the cars of LIST.
9715 Also, weed out any non-string entries, because the return value is used
9716 only for regexp matching.
9717 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
9718 point to the symbol `emacs', indicating that the file should
9719 be opened in Emacs."
9720 (append
9721 (delq nil
9722 (mapcar (lambda (x)
9723 (if (not (stringp (car x)))
9725 (if (string-match "\\W" (car x))
9727 (cons (concat "\\." (car x) "\\'") (cdr x)))))
9728 list))
9729 (if add-auto-mode
9730 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
9732 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
9733 (defun org-file-remote-p (file)
9734 "Test whether FILE specifies a location on a remote system.
9735 Return non-nil if the location is indeed remote.
9737 For example, the filename \"/user@host:/foo\" specifies a location
9738 on the system \"/user@host:\"."
9739 (cond ((fboundp 'file-remote-p)
9740 (file-remote-p file))
9741 ((fboundp 'tramp-handle-file-remote-p)
9742 (tramp-handle-file-remote-p file))
9743 ((and (boundp 'ange-ftp-name-format)
9744 (string-match (car ange-ftp-name-format) file))
9746 (t nil)))
9749 ;;;; Refiling
9751 (defun org-get-org-file ()
9752 "Read a filename, with default directory `org-directory'."
9753 (let ((default (or org-default-notes-file remember-data-file)))
9754 (read-file-name (format "File name [%s]: " default)
9755 (file-name-as-directory org-directory)
9756 default)))
9758 (defun org-notes-order-reversed-p ()
9759 "Check if the current file should receive notes in reversed order."
9760 (cond
9761 ((not org-reverse-note-order) nil)
9762 ((eq t org-reverse-note-order) t)
9763 ((not (listp org-reverse-note-order)) nil)
9764 (t (catch 'exit
9765 (let ((all org-reverse-note-order)
9766 entry)
9767 (while (setq entry (pop all))
9768 (if (string-match (car entry) buffer-file-name)
9769 (throw 'exit (cdr entry))))
9770 nil)))))
9772 (defvar org-refile-target-table nil
9773 "The list of refile targets, created by `org-refile'.")
9775 (defvar org-agenda-new-buffers nil
9776 "Buffers created to visit agenda files.")
9778 (defvar org-refile-cache nil
9779 "Cache for refile targets.")
9782 (defvar org-refile-markers nil
9783 "All the markers used for caching refile locations.")
9785 (defun org-refile-marker (pos)
9786 "Get a new refile marker, but only if caching is in use."
9787 (if (not org-refile-use-cache)
9789 (let ((m (make-marker)))
9790 (move-marker m pos)
9791 (push m org-refile-markers)
9792 m)))
9794 (defun org-refile-cache-clear ()
9795 "Clear the refile cache and disable all the markers."
9796 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
9797 (setq org-refile-markers nil)
9798 (setq org-refile-cache nil)
9799 (message "Refile cache has been cleared"))
9801 (defun org-refile-cache-check-set (set)
9802 "Check if all the markers in the cache still have live buffers."
9803 (let (marker)
9804 (catch 'exit
9805 (while (and set (setq marker (nth 3 (pop set))))
9806 ;; if org-refile-use-outline-path is 'file, marker may be nil
9807 (when (and marker (null (marker-buffer marker)))
9808 (message "not found") (sit-for 3)
9809 (throw 'exit nil)))
9810 t)))
9812 (defun org-refile-cache-put (set &rest identifiers)
9813 "Push the refile targets SET into the cache, under IDENTIFIERS."
9814 (let* ((key (sha1 (prin1-to-string identifiers)))
9815 (entry (assoc key org-refile-cache)))
9816 (if entry
9817 (setcdr entry set)
9818 (push (cons key set) org-refile-cache))))
9820 (defun org-refile-cache-get (&rest identifiers)
9821 "Retrieve the cached value for refile targets given by IDENTIFIERS."
9822 (cond
9823 ((not org-refile-cache) nil)
9824 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
9826 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
9827 org-refile-cache))))
9828 (and set (org-refile-cache-check-set set) set)))))
9830 (defun org-get-refile-targets (&optional default-buffer)
9831 "Produce a table with refile targets."
9832 (let ((case-fold-search nil)
9833 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
9834 (entries (or org-refile-targets '((nil . (:level . 1)))))
9835 targets tgs txt re files f desc descre fast-path-p level pos0)
9836 (message "Getting targets...")
9837 (with-current-buffer (or default-buffer (current-buffer))
9838 (while (setq entry (pop entries))
9839 (setq files (car entry) desc (cdr entry))
9840 (setq fast-path-p nil)
9841 (cond
9842 ((null files) (setq files (list (current-buffer))))
9843 ((eq files 'org-agenda-files)
9844 (setq files (org-agenda-files 'unrestricted)))
9845 ((and (symbolp files) (fboundp files))
9846 (setq files (funcall files)))
9847 ((and (symbolp files) (boundp files))
9848 (setq files (symbol-value files))))
9849 (if (stringp files) (setq files (list files)))
9850 (cond
9851 ((eq (car desc) :tag)
9852 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
9853 ((eq (car desc) :todo)
9854 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
9855 ((eq (car desc) :regexp)
9856 (setq descre (cdr desc)))
9857 ((eq (car desc) :level)
9858 (setq descre (concat "^\\*\\{" (number-to-string
9859 (if org-odd-levels-only
9860 (1- (* 2 (cdr desc)))
9861 (cdr desc)))
9862 "\\}[ \t]")))
9863 ((eq (car desc) :maxlevel)
9864 (setq fast-path-p t)
9865 (setq descre (concat "^\\*\\{1," (number-to-string
9866 (if org-odd-levels-only
9867 (1- (* 2 (cdr desc)))
9868 (cdr desc)))
9869 "\\}[ \t]")))
9870 (t (error "Bad refiling target description %s" desc)))
9871 (while (setq f (pop files))
9872 (with-current-buffer
9873 (if (bufferp f) f (org-get-agenda-file-buffer f))
9875 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
9876 (progn
9877 (if (bufferp f) (setq f (buffer-file-name
9878 (buffer-base-buffer f))))
9879 (setq f (and f (expand-file-name f)))
9880 (if (eq org-refile-use-outline-path 'file)
9881 (push (list (file-name-nondirectory f) f nil nil) tgs))
9882 (save-excursion
9883 (save-restriction
9884 (widen)
9885 (goto-char (point-min))
9886 (while (re-search-forward descre nil t)
9887 (goto-char (setq pos0 (point-at-bol)))
9888 (catch 'next
9889 (when org-refile-target-verify-function
9890 (save-match-data
9891 (or (funcall org-refile-target-verify-function)
9892 (throw 'next t))))
9893 (when (looking-at org-complex-heading-regexp)
9894 (setq level (org-reduced-level
9895 (- (match-end 1) (match-beginning 1)))
9896 txt (org-link-display-format (match-string 4))
9897 re (concat "^" (regexp-quote
9898 (buffer-substring
9899 (match-beginning 1)
9900 (match-end 4)))))
9901 (if (match-end 5) (setq re (concat
9902 re "[ \t]+"
9903 (regexp-quote
9904 (match-string 5)))))
9905 (setq re (concat re "[ \t]*$"))
9906 (when org-refile-use-outline-path
9907 (setq txt (mapconcat
9908 'org-protect-slash
9909 (append
9910 (if (eq org-refile-use-outline-path
9911 'file)
9912 (list (file-name-nondirectory
9913 (buffer-file-name
9914 (buffer-base-buffer))))
9915 (if (eq org-refile-use-outline-path
9916 'full-file-path)
9917 (list (buffer-file-name
9918 (buffer-base-buffer)))))
9919 (org-get-outline-path fast-path-p
9920 level txt)
9921 (list txt))
9922 "/")))
9923 (push (list txt f re (org-refile-marker (point)))
9924 tgs)))
9925 (when (= (point) pos0)
9926 ;; verification function has not moved point
9927 (goto-char (point-at-eol))))))))
9928 (when org-refile-use-cache
9929 (org-refile-cache-put tgs (buffer-file-name) descre))
9930 (setq targets (append tgs targets))
9931 ))))
9932 (message "Getting targets...done")
9933 (nreverse targets)))
9935 (defun org-protect-slash (s)
9936 (while (string-match "/" s)
9937 (setq s (replace-match "\\" t t s)))
9940 (defvar org-olpa (make-vector 20 nil))
9942 (defun org-get-outline-path (&optional fastp level heading)
9943 "Return the outline path to the current entry, as a list.
9945 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
9946 routine which makes outline path derivations for an entire file,
9947 avoiding backtracing. Refile target collection makes use of that."
9948 (if fastp
9949 (progn
9950 (if (> level 19)
9951 (error "Outline path failure, more than 19 levels"))
9952 (loop for i from level upto 19 do
9953 (aset org-olpa i nil))
9954 (prog1
9955 (delq nil (append org-olpa nil))
9956 (aset org-olpa level heading)))
9957 (let (rtn case-fold-search)
9958 (save-excursion
9959 (save-restriction
9960 (widen)
9961 (while (org-up-heading-safe)
9962 (when (looking-at org-complex-heading-regexp)
9963 (push (org-match-string-no-properties 4) rtn)))
9964 rtn)))))
9966 (defun org-format-outline-path (path &optional width prefix)
9967 "Format the outline path PATH for display.
9968 Width is the maximum number of characters that is available.
9969 Prefix is a prefix to be included in the returned string,
9970 such as the file name."
9971 (setq width (or width 79))
9972 (if prefix (setq width (- width (length prefix))))
9973 (if (not path)
9974 (or prefix "")
9975 (let* ((nsteps (length path))
9976 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
9977 (maxwidth (if (<= total-width width)
9978 10000 ;; everything fits
9979 ;; we need to shorten the level headings
9980 (/ (- width nsteps) nsteps)))
9981 (org-odd-levels-only nil)
9982 (n 0)
9983 (total (1+ (length prefix))))
9984 (setq maxwidth (max maxwidth 10))
9985 (concat prefix
9986 (mapconcat
9987 (lambda (h)
9988 (setq n (1+ n))
9989 (if (and (= n nsteps) (< maxwidth 10000))
9990 (setq maxwidth (- total-width total)))
9991 (if (< (length h) maxwidth)
9992 (progn (setq total (+ total (length h) 1)) h)
9993 (setq h (substring h 0 (- maxwidth 2))
9994 total (+ total maxwidth 1))
9995 (if (string-match "[ \t]+\\'" h)
9996 (setq h (substring h 0 (match-beginning 0))))
9997 (setq h (concat h "..")))
9998 (org-add-props h nil 'face
9999 (nth (% (1- n) org-n-level-faces)
10000 org-level-faces))
10002 path "/")))))
10004 (defun org-display-outline-path (&optional file current)
10005 "Display the current outline path in the echo area."
10006 (interactive "P")
10007 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10008 (case-fold-search nil)
10009 (path (and (org-mode-p) (org-get-outline-path))))
10010 (if current (setq path (append path
10011 (save-excursion
10012 (org-back-to-heading t)
10013 (if (looking-at org-complex-heading-regexp)
10014 (list (match-string 4)))))))
10015 (message "%s"
10016 (org-format-outline-path
10017 path
10018 (1- (frame-width))
10019 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10021 (defvar org-refile-history nil
10022 "History for refiling operations.")
10024 (defvar org-after-refile-insert-hook nil
10025 "Hook run after `org-refile' has inserted its stuff at the new location.
10026 Note that this is still *before* the stuff will be removed from
10027 the *old* location.")
10029 (defvar org-capture-last-stored-marker)
10030 (defun org-refile (&optional goto default-buffer rfloc)
10031 "Move the entry at point to another heading.
10032 The list of target headings is compiled using the information in
10033 `org-refile-targets', which see. This list is created before each use
10034 and will therefore always be up-to-date.
10036 At the target location, the entry is filed as a subitem of the target heading.
10037 Depending on `org-reverse-note-order', the new subitem will either be the
10038 first or the last subitem.
10040 If there is an active region, all entries in that region will be moved.
10041 However, the region must fulfill the requirement that the first heading
10042 is the first one sets the top-level of the moved text - at most siblings
10043 below it are allowed.
10045 With prefix arg GOTO, the command will only visit the target location,
10046 not actually move anything.
10047 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10048 go to the location where the last refiling
10049 operation has put the subtree.
10050 With a prefix argument of `2', refile to the running clock.
10052 RFLOC can be a refile location obtained in a different way.
10054 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10056 If you are using target caching (see `org-refile-use-cache'),
10057 You have to clear the target cache in order to find new targets.
10058 This can be done with a 0 prefix: `C-0 C-c C-w'"
10059 (interactive "P")
10060 (if (member goto '(0 (64)))
10061 (org-refile-cache-clear)
10062 (let* ((cbuf (current-buffer))
10063 (regionp (org-region-active-p))
10064 (region-start (and regionp (region-beginning)))
10065 (region-end (and regionp (region-end)))
10066 (region-length (and regionp (- region-end region-start)))
10067 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10068 pos it nbuf file re level reversed)
10069 (setq last-command nil)
10070 (when regionp
10071 (goto-char region-start)
10072 (or (bolp) (goto-char (point-at-bol)))
10073 (setq region-start (point))
10074 (unless (org-kill-is-subtree-p
10075 (buffer-substring region-start region-end))
10076 (error "The region is not a (sequence of) subtree(s)")))
10077 (if (equal goto '(16))
10078 (org-refile-goto-last-stored)
10079 (when (or
10080 (and (equal goto 2)
10081 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10082 (prog1
10083 (setq it (list (or org-clock-heading "running clock")
10084 (buffer-file-name
10085 (marker-buffer org-clock-hd-marker))
10087 (marker-position org-clock-hd-marker)))
10088 (setq goto nil)))
10089 (setq it (or rfloc
10090 (save-excursion
10091 (org-refile-get-location
10092 (if goto "Goto: " "Refile to: ") default-buffer
10093 org-refile-allow-creating-parent-nodes)))))
10094 (setq file (nth 1 it)
10095 re (nth 2 it)
10096 pos (nth 3 it))
10097 (if (and (not goto)
10099 (equal (buffer-file-name) file)
10100 (if regionp
10101 (and (>= pos region-start)
10102 (<= pos region-end))
10103 (and (>= pos (point))
10104 (< pos (save-excursion
10105 (org-end-of-subtree t t))))))
10106 (error "Cannot refile to position inside the tree or region"))
10108 (setq nbuf (or (find-buffer-visiting file)
10109 (find-file-noselect file)))
10110 (if goto
10111 (progn
10112 (switch-to-buffer nbuf)
10113 (goto-char pos)
10114 (org-show-context 'org-goto))
10115 (if regionp
10116 (progn
10117 (org-kill-new (buffer-substring region-start region-end))
10118 (org-save-markers-in-region region-start region-end))
10119 (org-copy-subtree 1 nil t))
10120 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10121 (find-file-noselect file)))
10122 (setq reversed (org-notes-order-reversed-p))
10123 (save-excursion
10124 (save-restriction
10125 (widen)
10126 (if pos
10127 (progn
10128 (goto-char pos)
10129 (looking-at outline-regexp)
10130 (setq level (org-get-valid-level (funcall outline-level) 1))
10131 (goto-char
10132 (if reversed
10133 (or (outline-next-heading) (point-max))
10134 (or (save-excursion (org-get-next-sibling))
10135 (org-end-of-subtree t t)
10136 (point-max)))))
10137 (setq level 1)
10138 (if (not reversed)
10139 (goto-char (point-max))
10140 (goto-char (point-min))
10141 (or (outline-next-heading) (goto-char (point-max)))))
10142 (if (not (bolp)) (newline))
10143 (org-paste-subtree level)
10144 (when org-log-refile
10145 (org-add-log-setup 'refile nil nil 'findpos
10146 org-log-refile)
10147 (unless (eq org-log-refile 'note)
10148 (save-excursion (org-add-log-note))))
10149 (and org-auto-align-tags (org-set-tags nil t))
10150 (bookmark-set "org-refile-last-stored")
10151 ;; If we are refiling for capture, make sure that the
10152 ;; last-capture pointers point here
10153 (when (org-bound-and-true-p org-refile-for-capture)
10154 (bookmark-set "org-capture-last-stored-marker")
10155 (move-marker org-capture-last-stored-marker (point)))
10156 (if (fboundp 'deactivate-mark) (deactivate-mark))
10157 (run-hooks 'org-after-refile-insert-hook))))
10158 (if regionp
10159 (delete-region (point) (+ (point) region-length))
10160 (org-cut-subtree))
10161 (when (featurep 'org-inlinetask)
10162 (org-inlinetask-remove-END-maybe))
10163 (setq org-markers-to-move nil)
10164 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10166 (defun org-refile-goto-last-stored ()
10167 "Go to the location where the last refile was stored."
10168 (interactive)
10169 (bookmark-jump "org-refile-last-stored")
10170 (message "This is the location of the last refile"))
10172 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
10173 "Prompt the user for a refile location, using PROMPT."
10174 (let ((org-refile-targets org-refile-targets)
10175 (org-refile-use-outline-path org-refile-use-outline-path))
10176 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
10177 (unless org-refile-target-table
10178 (error "No refile targets"))
10179 (let* ((cbuf (current-buffer))
10180 (partial-completion-mode nil)
10181 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10182 (cfunc (if (and org-refile-use-outline-path
10183 org-outline-path-complete-in-steps)
10184 'org-olpath-completing-read
10185 'org-icompleting-read))
10186 (extra (if org-refile-use-outline-path "/" ""))
10187 (filename (and cfn (expand-file-name cfn)))
10188 (tbl (mapcar
10189 (lambda (x)
10190 (if (and (not (member org-refile-use-outline-path
10191 '(file full-file-path)))
10192 (not (equal filename (nth 1 x))))
10193 (cons (concat (car x) extra " ("
10194 (file-name-nondirectory (nth 1 x)) ")")
10195 (cdr x))
10196 (cons (concat (car x) extra) (cdr x))))
10197 org-refile-target-table))
10198 (completion-ignore-case t)
10199 pa answ parent-target child parent old-hist)
10200 (setq old-hist org-refile-history)
10201 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10202 nil 'org-refile-history))
10203 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10204 (if pa
10205 (progn
10206 (when (or (not org-refile-history)
10207 (not (eq old-hist org-refile-history))
10208 (not (equal (car pa) (car org-refile-history))))
10209 (setq org-refile-history
10210 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10211 org-refile-history
10212 (cdr org-refile-history))))
10213 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10214 (pop org-refile-history)))
10216 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10217 (progn
10218 (setq parent (match-string 1 answ)
10219 child (match-string 2 answ))
10220 (setq parent-target (or (assoc parent tbl)
10221 (assoc (concat parent "/") tbl)))
10222 (when (and parent-target
10223 (or (eq new-nodes t)
10224 (and (eq new-nodes 'confirm)
10225 (y-or-n-p (format "Create new node \"%s\"? "
10226 child)))))
10227 (org-refile-new-child parent-target child)))
10228 (error "Invalid target location")))))
10230 (defun org-refile-new-child (parent-target child)
10231 "Use refile target PARENT-TARGET to add new CHILD below it."
10232 (unless parent-target
10233 (error "Cannot find parent for new node"))
10234 (let ((file (nth 1 parent-target))
10235 (pos (nth 3 parent-target))
10236 level)
10237 (with-current-buffer (or (find-buffer-visiting file)
10238 (find-file-noselect file))
10239 (save-excursion
10240 (save-restriction
10241 (widen)
10242 (if pos
10243 (goto-char pos)
10244 (goto-char (point-max))
10245 (if (not (bolp)) (newline)))
10246 (when (looking-at outline-regexp)
10247 (setq level (funcall outline-level))
10248 (org-end-of-subtree t t))
10249 (org-back-over-empty-lines)
10250 (insert "\n" (make-string
10251 (if pos (org-get-valid-level level 1) 1) ?*)
10252 " " child "\n")
10253 (beginning-of-line 0)
10254 (list (concat (car parent-target) "/" child) file "" (point)))))))
10256 (defun org-olpath-completing-read (prompt collection &rest args)
10257 "Read an outline path like a file name."
10258 (let ((thetable collection)
10259 (org-completion-use-ido nil) ; does not work with ido.
10260 (org-completion-use-iswitchb nil)) ; or iswitchb
10261 (apply
10262 'org-icompleting-read prompt
10263 (lambda (string predicate &optional flag)
10264 (let (rtn r f (l (length string)))
10265 (cond
10266 ((eq flag nil)
10267 ;; try completion
10268 (try-completion string thetable))
10269 ((eq flag t)
10270 ;; all-completions
10271 (setq rtn (all-completions string thetable predicate))
10272 (mapcar
10273 (lambda (x)
10274 (setq r (substring x l))
10275 (if (string-match " ([^)]*)$" x)
10276 (setq f (match-string 0 x))
10277 (setq f ""))
10278 (if (string-match "/" r)
10279 (concat string (substring r 0 (match-end 0)) f)
10281 rtn))
10282 ((eq flag 'lambda)
10283 ;; exact match?
10284 (assoc string thetable)))
10286 args)))
10288 ;;;; Dynamic blocks
10290 (defun org-find-dblock (name)
10291 "Find the first dynamic block with name NAME in the buffer.
10292 If not found, stay at current position and return nil."
10293 (let (pos)
10294 (save-excursion
10295 (goto-char (point-min))
10296 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
10297 nil t)
10298 (match-beginning 0))))
10299 (if pos (goto-char pos))
10300 pos))
10302 (defconst org-dblock-start-re
10303 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10304 "Matches the start line of a dynamic block, with parameters.")
10306 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
10307 "Matches the end of a dynamic block.")
10309 (defun org-create-dblock (plist)
10310 "Create a dynamic block section, with parameters taken from PLIST.
10311 PLIST must contain a :name entry which is used as name of the block."
10312 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
10313 (end-of-line 1)
10314 (newline))
10315 (let ((col (current-column))
10316 (name (plist-get plist :name)))
10317 (insert "#+BEGIN: " name)
10318 (while plist
10319 (if (eq (car plist) :name)
10320 (setq plist (cddr plist))
10321 (insert " " (prin1-to-string (pop plist)))))
10322 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
10323 (beginning-of-line -2)))
10325 (defun org-prepare-dblock ()
10326 "Prepare dynamic block for refresh.
10327 This empties the block, puts the cursor at the insert position and returns
10328 the property list including an extra property :name with the block name."
10329 (unless (looking-at org-dblock-start-re)
10330 (error "Not at a dynamic block"))
10331 (let* ((begdel (1+ (match-end 0)))
10332 (name (org-no-properties (match-string 1)))
10333 (params (append (list :name name)
10334 (read (concat "(" (match-string 3) ")")))))
10335 (save-excursion
10336 (beginning-of-line 1)
10337 (skip-chars-forward " \t")
10338 (setq params (plist-put params :indentation-column (current-column))))
10339 (unless (re-search-forward org-dblock-end-re nil t)
10340 (error "Dynamic block not terminated"))
10341 (setq params
10342 (append params
10343 (list :content (buffer-substring
10344 begdel (match-beginning 0)))))
10345 (delete-region begdel (match-beginning 0))
10346 (goto-char begdel)
10347 (open-line 1)
10348 params))
10350 (defun org-map-dblocks (&optional command)
10351 "Apply COMMAND to all dynamic blocks in the current buffer.
10352 If COMMAND is not given, use `org-update-dblock'."
10353 (let ((cmd (or command 'org-update-dblock)))
10354 (save-excursion
10355 (goto-char (point-min))
10356 (while (re-search-forward org-dblock-start-re nil t)
10357 (goto-char (match-beginning 0))
10358 (save-excursion
10359 (condition-case nil
10360 (funcall cmd)
10361 (error (message "Error during update of dynamic block"))))
10362 (unless (re-search-forward org-dblock-end-re nil t)
10363 (error "Dynamic block not terminated"))))))
10365 (defun org-dblock-update (&optional arg)
10366 "User command for updating dynamic blocks.
10367 Update the dynamic block at point. With prefix ARG, update all dynamic
10368 blocks in the buffer."
10369 (interactive "P")
10370 (if arg
10371 (org-update-all-dblocks)
10372 (or (looking-at org-dblock-start-re)
10373 (org-beginning-of-dblock))
10374 (org-update-dblock)))
10376 (defun org-update-dblock ()
10377 "Update the dynamic block at point.
10378 This means to empty the block, parse for parameters and then call
10379 the correct writing function."
10380 (save-window-excursion
10381 (let* ((pos (point))
10382 (line (org-current-line))
10383 (params (org-prepare-dblock))
10384 (name (plist-get params :name))
10385 (indent (plist-get params :indentation-column))
10386 (cmd (intern (concat "org-dblock-write:" name))))
10387 (message "Updating dynamic block `%s' at line %d..." name line)
10388 (funcall cmd params)
10389 (message "Updating dynamic block `%s' at line %d...done" name line)
10390 (goto-char pos)
10391 (when (and indent (> indent 0))
10392 (setq indent (make-string indent ?\ ))
10393 (save-excursion
10394 (org-beginning-of-dblock)
10395 (forward-line 1)
10396 (while (not (looking-at org-dblock-end-re))
10397 (insert indent)
10398 (beginning-of-line 2))
10399 (when (looking-at org-dblock-end-re)
10400 (and (looking-at "[ \t]+")
10401 (replace-match ""))
10402 (insert indent)))))))
10404 (defun org-beginning-of-dblock ()
10405 "Find the beginning of the dynamic block at point.
10406 Error if there is no such block at point."
10407 (let ((pos (point))
10408 beg)
10409 (end-of-line 1)
10410 (if (and (re-search-backward org-dblock-start-re nil t)
10411 (setq beg (match-beginning 0))
10412 (re-search-forward org-dblock-end-re nil t)
10413 (> (match-end 0) pos))
10414 (goto-char beg)
10415 (goto-char pos)
10416 (error "Not in a dynamic block"))))
10418 (defun org-update-all-dblocks ()
10419 "Update all dynamic blocks in the buffer.
10420 This function can be used in a hook."
10421 (when (org-mode-p)
10422 (org-map-dblocks 'org-update-dblock)))
10425 ;;;; Completion
10427 (defconst org-additional-option-like-keywords
10428 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
10429 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
10430 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
10431 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX"
10432 "BEGIN:" "END:"
10433 "ORGTBL" "TBLFM:" "TBLNAME:"
10434 "BEGIN_EXAMPLE" "END_EXAMPLE"
10435 "BEGIN_QUOTE" "END_QUOTE"
10436 "BEGIN_VERSE" "END_VERSE"
10437 "BEGIN_CENTER" "END_CENTER"
10438 "BEGIN_SRC" "END_SRC"
10439 "CATEGORY" "COLUMNS"
10440 "CAPTION" "LABEL"
10441 "SETUPFILE"
10442 "BIND"
10443 "MACRO"))
10445 (defcustom org-structure-template-alist
10447 ("s" "#+begin_src ?\n\n#+end_src"
10448 "<src lang=\"?\">\n\n</src>")
10449 ("e" "#+begin_example\n?\n#+end_example"
10450 "<example>\n?\n</example>")
10451 ("q" "#+begin_quote\n?\n#+end_quote"
10452 "<quote>\n?\n</quote>")
10453 ("v" "#+begin_verse\n?\n#+end_verse"
10454 "<verse>\n?\n/verse>")
10455 ("c" "#+begin_center\n?\n#+end_center"
10456 "<center>\n?\n/center>")
10457 ("l" "#+begin_latex\n?\n#+end_latex"
10458 "<literal style=\"latex\">\n?\n</literal>")
10459 ("L" "#+latex: "
10460 "<literal style=\"latex\">?</literal>")
10461 ("h" "#+begin_html\n?\n#+end_html"
10462 "<literal style=\"html\">\n?\n</literal>")
10463 ("H" "#+html: "
10464 "<literal style=\"html\">?</literal>")
10465 ("a" "#+begin_ascii\n?\n#+end_ascii")
10466 ("A" "#+ascii: ")
10467 ("i" "#+include %file ?"
10468 "<include file=%file markup=\"?\">")
10470 "Structure completion elements.
10471 This is a list of abbreviation keys and values. The value gets inserted
10472 if you type `<' followed by the key and then press the completion key,
10473 usually `M-TAB'. %file will be replaced by a file name after prompting
10474 for the file using completion.
10475 There are two templates for each key, the first uses the original Org syntax,
10476 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
10477 the default when the /org-mtags.el/ module has been loaded. See also the
10478 variable `org-mtags-prefer-muse-templates'.
10479 This is an experimental feature, it is undecided if it is going to stay in."
10480 :group 'org-completion
10481 :type '(repeat
10482 (string :tag "Key")
10483 (string :tag "Template")
10484 (string :tag "Muse Template")))
10486 (defun org-try-structure-completion ()
10487 "Try to complete a structure template before point.
10488 This looks for strings like \"<e\" on an otherwise empty line and
10489 expands them."
10490 (let ((l (buffer-substring (point-at-bol) (point)))
10492 (when (and (looking-at "[ \t]*$")
10493 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
10494 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
10495 (org-complete-expand-structure-template (+ -1 (point-at-bol)
10496 (match-beginning 1)) a)
10497 t)))
10499 (defun org-complete-expand-structure-template (start cell)
10500 "Expand a structure template."
10501 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
10502 (rpl (nth (if musep 2 1) cell))
10503 (ind ""))
10504 (delete-region start (point))
10505 (when (string-match "\\`#\\+" rpl)
10506 (cond
10507 ((bolp))
10508 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
10509 (setq ind (buffer-substring (point-at-bol) (point))))
10510 (t (newline))))
10511 (setq start (point))
10512 (if (string-match "%file" rpl)
10513 (setq rpl (replace-match
10514 (concat
10515 "\""
10516 (save-match-data
10517 (abbreviate-file-name (read-file-name "Include file: ")))
10518 "\"")
10519 t t rpl)))
10520 (setq rpl (mapconcat 'identity (split-string rpl "\n")
10521 (concat "\n" ind)))
10522 (insert rpl)
10523 (if (re-search-backward "\\?" start t) (delete-char 1))))
10526 (defun org-complete (&optional arg)
10527 "Perform completion on word at point.
10528 At the beginning of a headline, this completes TODO keywords as given in
10529 `org-todo-keywords'.
10530 If the current word is preceded by a backslash, completes the TeX symbols
10531 that are supported for HTML support.
10532 If the current word is preceded by \"#+\", completes special words for
10533 setting file options.
10534 In the line after \"#+STARTUP:, complete valid keywords.\"
10535 At all other locations, this simply calls the value of
10536 `org-completion-fallback-command'."
10537 (interactive "P")
10538 (org-without-partial-completion
10539 (catch 'exit
10540 (let* ((a nil)
10541 (end (point))
10542 (beg1 (save-excursion
10543 (skip-chars-backward (org-re "[:alnum:]_@"))
10544 (point)))
10545 (beg (save-excursion
10546 (skip-chars-backward "a-zA-Z0-9_:$")
10547 (point)))
10548 (confirm (lambda (x) (stringp (car x))))
10549 (searchhead (equal (char-before beg) ?*))
10550 (struct
10551 (when (and (member (char-before beg1) '(?. ?<))
10552 (setq a (assoc (buffer-substring beg1 (point))
10553 org-structure-template-alist)))
10554 (org-complete-expand-structure-template (1- beg1) a)
10555 (throw 'exit t)))
10556 (tag (and (equal (char-before beg1) ?:)
10557 (equal (char-after (point-at-bol)) ?*)))
10558 (prop (and (equal (char-before beg1) ?:)
10559 (not (equal (char-after (point-at-bol)) ?*))))
10560 (texp (equal (char-before beg) ?\\))
10561 (link (equal (char-before beg) ?\[))
10562 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
10563 beg)
10564 "#+"))
10565 (startup (string-match "^#\\+STARTUP:.*"
10566 (buffer-substring (point-at-bol) (point))))
10567 (completion-ignore-case opt)
10568 (type nil)
10569 (tbl nil)
10570 (table (cond
10571 (opt
10572 (setq type :opt)
10573 (require 'org-exp)
10574 (append
10575 (delq nil
10576 (mapcar
10577 (lambda (x)
10578 (if (string-match
10579 "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
10580 (cons (match-string 2 x)
10581 (match-string 1 x))))
10582 (org-split-string (org-get-current-options) "\n")))
10583 (mapcar 'list org-additional-option-like-keywords)))
10584 (startup
10585 (setq type :startup)
10586 org-startup-options)
10587 (link (append org-link-abbrev-alist-local
10588 org-link-abbrev-alist))
10589 (texp
10590 (setq type :tex)
10591 (append org-entities-user org-entities))
10592 ((string-match "\\`\\*+[ \t]+\\'"
10593 (buffer-substring (point-at-bol) beg))
10594 (setq type :todo)
10595 (mapcar 'list org-todo-keywords-1))
10596 (searchhead
10597 (setq type :searchhead)
10598 (save-excursion
10599 (goto-char (point-min))
10600 (while (re-search-forward org-todo-line-regexp nil t)
10601 (push (list
10602 (org-make-org-heading-search-string
10603 (match-string 3) t))
10604 tbl)))
10605 tbl)
10606 (tag (setq type :tag beg beg1)
10607 (or org-tag-alist (org-get-buffer-tags)))
10608 (prop (setq type :prop beg beg1)
10609 (mapcar 'list (org-buffer-property-keys nil t t)))
10610 (t (progn
10611 (call-interactively org-completion-fallback-command)
10612 (throw 'exit nil)))))
10613 (pattern (buffer-substring-no-properties beg end))
10614 (completion (try-completion pattern table confirm)))
10615 (cond ((eq completion t)
10616 (if (not (assoc (upcase pattern) table))
10617 (message "Already complete")
10618 (if (and (equal type :opt)
10619 (not (member (car (assoc (upcase pattern) table))
10620 org-additional-option-like-keywords)))
10621 (insert (substring (cdr (assoc (upcase pattern) table))
10622 (length pattern)))
10623 (if (memq type '(:tag :prop)) (insert ":")))))
10624 ((null completion)
10625 (message "Can't find completion for \"%s\"" pattern)
10626 (ding))
10627 ((not (string= pattern completion))
10628 (delete-region beg end)
10629 (if (string-match " +$" completion)
10630 (setq completion (replace-match "" t t completion)))
10631 (insert completion)
10632 (if (get-buffer-window "*Completions*")
10633 (delete-window (get-buffer-window "*Completions*")))
10634 (if (assoc completion table)
10635 (if (eq type :todo) (insert " ")
10636 (if (memq type '(:tag :prop)) (insert ":"))))
10637 (if (and (equal type :opt) (assoc completion table))
10638 (message "%s" (substitute-command-keys
10639 "Press \\[org-complete] again to insert example settings"))))
10641 (message "Making completion list...")
10642 (let ((list (sort (all-completions pattern table confirm)
10643 'string<)))
10644 (with-output-to-temp-buffer "*Completions*"
10645 (condition-case nil
10646 ;; Protection needed for XEmacs and emacs 21
10647 (display-completion-list list pattern)
10648 (error (display-completion-list list)))))
10649 (message "Making completion list...%s" "done")))))))
10651 ;;;; TODO, DEADLINE, Comments
10653 (defun org-toggle-comment ()
10654 "Change the COMMENT state of an entry."
10655 (interactive)
10656 (save-excursion
10657 (org-back-to-heading)
10658 (let (case-fold-search)
10659 (if (looking-at (concat outline-regexp
10660 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
10661 (replace-match "" t t nil 1)
10662 (if (looking-at outline-regexp)
10663 (progn
10664 (goto-char (match-end 0))
10665 (insert org-comment-string " ")))))))
10667 (defvar org-last-todo-state-is-todo nil
10668 "This is non-nil when the last TODO state change led to a TODO state.
10669 If the last change removed the TODO tag or switched to DONE, then
10670 this is nil.")
10672 (defvar org-setting-tags nil) ; dynamically skipped
10674 (defun org-parse-local-options (string var)
10675 "Parse STRING for startup setting relevant for variable VAR."
10676 (let ((rtn (symbol-value var))
10677 e opts)
10678 (save-match-data
10679 (if (or (not string) (not (string-match "\\S-" string)))
10681 (setq opts (delq nil (mapcar (lambda (x)
10682 (setq e (assoc x org-startup-options))
10683 (if (eq (nth 1 e) var) e nil))
10684 (org-split-string string "[ \t]+"))))
10685 (if (not opts)
10687 (setq rtn nil)
10688 (while (setq e (pop opts))
10689 (if (not (nth 3 e))
10690 (setq rtn (nth 2 e))
10691 (if (not (listp rtn)) (setq rtn nil))
10692 (push (nth 2 e) rtn)))
10693 rtn)))))
10695 (defvar org-todo-setup-filter-hook nil
10696 "Hook for functions that pre-filter todo specs.
10697 Each function takes a todo spec and returns either nil or the spec
10698 transformed into canonical form." )
10700 (defvar org-todo-get-default-hook nil
10701 "Hook for functions that get a default item for todo.
10702 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
10703 nil or a string to be used for the todo mark." )
10705 (defvar org-agenda-headline-snapshot-before-repeat)
10707 (defun org-todo (&optional arg)
10708 "Change the TODO state of an item.
10709 The state of an item is given by a keyword at the start of the heading,
10710 like
10711 *** TODO Write paper
10712 *** DONE Call mom
10714 The different keywords are specified in the variable `org-todo-keywords'.
10715 By default the available states are \"TODO\" and \"DONE\".
10716 So for this example: when the item starts with TODO, it is changed to DONE.
10717 When it starts with DONE, the DONE is removed. And when neither TODO nor
10718 DONE are present, add TODO at the beginning of the heading.
10720 With \\[universal-argument] prefix arg, use completion to determine the new \
10721 state.
10722 With numeric prefix arg, switch to that state.
10723 With a double \\[universal-argument] prefix, switch to the next set of TODO \
10724 keywords (nextset).
10725 With a triple \\[universal-argument] prefix, circumvent any state blocking.
10727 For calling through lisp, arg is also interpreted in the following way:
10728 'none -> empty state
10729 \"\"(empty string) -> switch to empty state
10730 'done -> switch to DONE
10731 'nextset -> switch to the next set of keywords
10732 'previousset -> switch to the previous set of keywords
10733 \"WAITING\" -> switch to the specified keyword, but only if it
10734 really is a member of `org-todo-keywords'."
10735 (interactive "P")
10736 (if (equal arg '(16)) (setq arg 'nextset))
10737 (let ((org-blocker-hook org-blocker-hook)
10738 (case-fold-search nil))
10739 (when (equal arg '(64))
10740 (setq arg nil org-blocker-hook nil))
10741 (when (and org-blocker-hook
10742 (or org-inhibit-blocking
10743 (org-entry-get nil "NOBLOCKING")))
10744 (setq org-blocker-hook nil))
10745 (save-excursion
10746 (catch 'exit
10747 (org-back-to-heading t)
10748 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
10749 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
10750 (looking-at " *"))
10751 (let* ((match-data (match-data))
10752 (startpos (point-at-bol))
10753 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
10754 (org-log-done org-log-done)
10755 (org-log-repeat org-log-repeat)
10756 (org-todo-log-states org-todo-log-states)
10757 (this (match-string 1))
10758 (hl-pos (match-beginning 0))
10759 (head (org-get-todo-sequence-head this))
10760 (ass (assoc head org-todo-kwd-alist))
10761 (interpret (nth 1 ass))
10762 (done-word (nth 3 ass))
10763 (final-done-word (nth 4 ass))
10764 (last-state (or this ""))
10765 (completion-ignore-case t)
10766 (member (member this org-todo-keywords-1))
10767 (tail (cdr member))
10768 (state (cond
10769 ((and org-todo-key-trigger
10770 (or (and (equal arg '(4))
10771 (eq org-use-fast-todo-selection 'prefix))
10772 (and (not arg) org-use-fast-todo-selection
10773 (not (eq org-use-fast-todo-selection
10774 'prefix)))))
10775 ;; Use fast selection
10776 (org-fast-todo-selection))
10777 ((and (equal arg '(4))
10778 (or (not org-use-fast-todo-selection)
10779 (not org-todo-key-trigger)))
10780 ;; Read a state with completion
10781 (org-icompleting-read
10782 "State: " (mapcar (lambda(x) (list x))
10783 org-todo-keywords-1)
10784 nil t))
10785 ((eq arg 'right)
10786 (if this
10787 (if tail (car tail) nil)
10788 (car org-todo-keywords-1)))
10789 ((eq arg 'left)
10790 (if (equal member org-todo-keywords-1)
10792 (if this
10793 (nth (- (length org-todo-keywords-1)
10794 (length tail) 2)
10795 org-todo-keywords-1)
10796 (org-last org-todo-keywords-1))))
10797 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
10798 (setq arg nil))) ; hack to fall back to cycling
10799 (arg
10800 ;; user or caller requests a specific state
10801 (cond
10802 ((equal arg "") nil)
10803 ((eq arg 'none) nil)
10804 ((eq arg 'done) (or done-word (car org-done-keywords)))
10805 ((eq arg 'nextset)
10806 (or (car (cdr (member head org-todo-heads)))
10807 (car org-todo-heads)))
10808 ((eq arg 'previousset)
10809 (let ((org-todo-heads (reverse org-todo-heads)))
10810 (or (car (cdr (member head org-todo-heads)))
10811 (car org-todo-heads))))
10812 ((car (member arg org-todo-keywords-1)))
10813 ((stringp arg)
10814 (error "State `%s' not valid in this file" arg))
10815 ((nth (1- (prefix-numeric-value arg))
10816 org-todo-keywords-1))))
10817 ((null member) (or head (car org-todo-keywords-1)))
10818 ((equal this final-done-word) nil) ;; -> make empty
10819 ((null tail) nil) ;; -> first entry
10820 ((memq interpret '(type priority))
10821 (if (eq this-command last-command)
10822 (car tail)
10823 (if (> (length tail) 0)
10824 (or done-word (car org-done-keywords))
10825 nil)))
10827 (car tail))))
10828 (state (or
10829 (run-hook-with-args-until-success
10830 'org-todo-get-default-hook state last-state)
10831 state))
10832 (next (if state (concat " " state " ") " "))
10833 (change-plist (list :type 'todo-state-change :from this :to state
10834 :position startpos))
10835 dolog now-done-p)
10836 (when org-blocker-hook
10837 (setq org-last-todo-state-is-todo
10838 (not (member this org-done-keywords)))
10839 (unless (save-excursion
10840 (save-match-data
10841 (run-hook-with-args-until-failure
10842 'org-blocker-hook change-plist)))
10843 (if (interactive-p)
10844 (error "TODO state change from %s to %s blocked" this state)
10845 ;; fail silently
10846 (message "TODO state change from %s to %s blocked" this state)
10847 (throw 'exit nil))))
10848 (store-match-data match-data)
10849 (replace-match next t t)
10850 (unless (pos-visible-in-window-p hl-pos)
10851 (message "TODO state changed to %s" (org-trim next)))
10852 (unless head
10853 (setq head (org-get-todo-sequence-head state)
10854 ass (assoc head org-todo-kwd-alist)
10855 interpret (nth 1 ass)
10856 done-word (nth 3 ass)
10857 final-done-word (nth 4 ass)))
10858 (when (memq arg '(nextset previousset))
10859 (message "Keyword-Set %d/%d: %s"
10860 (- (length org-todo-sets) -1
10861 (length (memq (assoc state org-todo-sets) org-todo-sets)))
10862 (length org-todo-sets)
10863 (mapconcat 'identity (assoc state org-todo-sets) " ")))
10864 (setq org-last-todo-state-is-todo
10865 (not (member state org-done-keywords)))
10866 (setq now-done-p (and (member state org-done-keywords)
10867 (not (member this org-done-keywords))))
10868 (and logging (org-local-logging logging))
10869 (when (and (or org-todo-log-states org-log-done)
10870 (not (eq org-inhibit-logging t))
10871 (not (memq arg '(nextset previousset))))
10872 ;; we need to look at recording a time and note
10873 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
10874 (nth 2 (assoc this org-todo-log-states))))
10875 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
10876 (setq dolog 'time))
10877 (when (and state
10878 (member state org-not-done-keywords)
10879 (not (member this org-not-done-keywords)))
10880 ;; This is now a todo state and was not one before
10881 ;; If there was a CLOSED time stamp, get rid of it.
10882 (org-add-planning-info nil nil 'closed))
10883 (when (and now-done-p org-log-done)
10884 ;; It is now done, and it was not done before
10885 (org-add-planning-info 'closed (org-current-time))
10886 (if (and (not dolog) (eq 'note org-log-done))
10887 (org-add-log-setup 'done state this 'findpos 'note)))
10888 (when (and state dolog)
10889 ;; This is a non-nil state, and we need to log it
10890 (org-add-log-setup 'state state this 'findpos dolog)))
10891 ;; Fixup tag positioning
10892 (org-todo-trigger-tag-changes state)
10893 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
10894 (when org-provide-todo-statistics
10895 (org-update-parent-todo-statistics))
10896 (run-hooks 'org-after-todo-state-change-hook)
10897 (if (and arg (not (member state org-done-keywords)))
10898 (setq head (org-get-todo-sequence-head state)))
10899 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
10900 ;; Do we need to trigger a repeat?
10901 (when now-done-p
10902 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
10903 ;; This is for the agenda, take a snapshot of the headline.
10904 (save-match-data
10905 (setq org-agenda-headline-snapshot-before-repeat
10906 (org-get-heading))))
10907 (org-auto-repeat-maybe state))
10908 ;; Fixup cursor location if close to the keyword
10909 (if (and (outline-on-heading-p)
10910 (not (bolp))
10911 (save-excursion (beginning-of-line 1)
10912 (looking-at org-todo-line-regexp))
10913 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
10914 (progn
10915 (goto-char (or (match-end 2) (match-end 1)))
10916 (and (looking-at " ") (just-one-space))))
10917 (when org-trigger-hook
10918 (save-excursion
10919 (run-hook-with-args 'org-trigger-hook change-plist))))))))
10921 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
10922 "Block turning an entry into a TODO, using the hierarchy.
10923 This checks whether the current task should be blocked from state
10924 changes. Such blocking occurs when:
10926 1. The task has children which are not all in a completed state.
10928 2. A task has a parent with the property :ORDERED:, and there
10929 are siblings prior to the current task with incomplete
10930 status.
10932 3. The parent of the task is blocked because it has siblings that should
10933 be done first, or is child of a block grandparent TODO entry."
10935 (if (not org-enforce-todo-dependencies)
10936 t ; if locally turned off don't block
10937 (catch 'dont-block
10938 ;; If this is not a todo state change, or if this entry is already DONE,
10939 ;; do not block
10940 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10941 (member (plist-get change-plist :from)
10942 (cons 'done org-done-keywords))
10943 (member (plist-get change-plist :to)
10944 (cons 'todo org-not-done-keywords))
10945 (not (plist-get change-plist :to)))
10946 (throw 'dont-block t))
10947 ;; If this task has children, and any are undone, it's blocked
10948 (save-excursion
10949 (org-back-to-heading t)
10950 (let ((this-level (funcall outline-level)))
10951 (outline-next-heading)
10952 (let ((child-level (funcall outline-level)))
10953 (while (and (not (eobp))
10954 (> child-level this-level))
10955 ;; this todo has children, check whether they are all
10956 ;; completed
10957 (if (and (not (org-entry-is-done-p))
10958 (org-entry-is-todo-p))
10959 (throw 'dont-block nil))
10960 (outline-next-heading)
10961 (setq child-level (funcall outline-level))))))
10962 ;; Otherwise, if the task's parent has the :ORDERED: property, and
10963 ;; any previous siblings are undone, it's blocked
10964 (save-excursion
10965 (org-back-to-heading t)
10966 (let* ((pos (point))
10967 (parent-pos (and (org-up-heading-safe) (point))))
10968 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10969 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
10970 (forward-line 1)
10971 (re-search-forward org-not-done-heading-regexp pos t))
10972 (throw 'dont-block nil)) ; block, there is an older sibling not done.
10973 ;; Search further up the hierarchy, to see if an anchestor is blocked
10974 (while t
10975 (goto-char parent-pos)
10976 (if (not (looking-at org-not-done-heading-regexp))
10977 (throw 'dont-block t)) ; do not block, parent is not a TODO
10978 (setq pos (point))
10979 (setq parent-pos (and (org-up-heading-safe) (point)))
10980 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10981 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
10982 (forward-line 1)
10983 (re-search-forward org-not-done-heading-regexp pos t))
10984 (throw 'dont-block nil)))))))) ; block, older sibling not done.
10986 (defcustom org-track-ordered-property-with-tag nil
10987 "Should the ORDERED property also be shown as a tag?
10988 The ORDERED property decides if an entry should require subtasks to be
10989 completed in sequence. Since a property is not very visible, setting
10990 this option means that toggling the ORDERED property with the command
10991 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
10992 not relevant for the behavior, but it makes things more visible.
10994 Note that toggling the tag with tags commands will not change the property
10995 and therefore not influence behavior!
10997 This can be t, meaning the tag ORDERED should be used, It can also be a
10998 string to select a different tag for this task."
10999 :group 'org-todo
11000 :type '(choice
11001 (const :tag "No tracking" nil)
11002 (const :tag "Track with ORDERED tag" t)
11003 (string :tag "Use other tag")))
11005 (defun org-toggle-ordered-property ()
11006 "Toggle the ORDERED property of the current entry.
11007 For better visibility, you can track the value of this property with a tag.
11008 See variable `org-track-ordered-property-with-tag'."
11009 (interactive)
11010 (let* ((t1 org-track-ordered-property-with-tag)
11011 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11012 (save-excursion
11013 (org-back-to-heading)
11014 (if (org-entry-get nil "ORDERED")
11015 (progn
11016 (org-delete-property "ORDERED")
11017 (and tag (org-toggle-tag tag 'off))
11018 (message "Subtasks can be completed in arbitrary order"))
11019 (org-entry-put nil "ORDERED" "t")
11020 (and tag (org-toggle-tag tag 'on))
11021 (message "Subtasks must be completed in sequence")))))
11023 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11024 (defun org-block-todo-from-checkboxes (change-plist)
11025 "Block turning an entry into a TODO, using checkboxes.
11026 This checks whether the current task should be blocked from state
11027 changes because there are unchecked boxes in this entry."
11028 (if (not org-enforce-todo-checkbox-dependencies)
11029 t ; if locally turned off don't block
11030 (catch 'dont-block
11031 ;; If this is not a todo state change, or if this entry is already DONE,
11032 ;; do not block
11033 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11034 (member (plist-get change-plist :from)
11035 (cons 'done org-done-keywords))
11036 (member (plist-get change-plist :to)
11037 (cons 'todo org-not-done-keywords))
11038 (not (plist-get change-plist :to)))
11039 (throw 'dont-block t))
11040 ;; If this task has checkboxes that are not checked, it's blocked
11041 (save-excursion
11042 (org-back-to-heading t)
11043 (let ((beg (point)) end)
11044 (outline-next-heading)
11045 (setq end (point))
11046 (goto-char beg)
11047 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
11048 end t)
11049 (progn
11050 (if (boundp 'org-blocked-by-checkboxes)
11051 (setq org-blocked-by-checkboxes t))
11052 (throw 'dont-block nil)))))
11053 t))) ; do not block
11055 (defun org-entry-blocked-p ()
11056 "Is the current entry blocked?"
11057 (if (org-entry-get nil "NOBLOCKING")
11058 nil ;; Never block this entry
11059 (not
11060 (run-hook-with-args-until-failure
11061 'org-blocker-hook
11062 (list :type 'todo-state-change
11063 :position (point)
11064 :from 'todo
11065 :to 'done)))))
11067 (defun org-update-statistics-cookies (all)
11068 "Update the statistics cookie, either from TODO or from checkboxes.
11069 This should be called with the cursor in a line with a statistics cookie."
11070 (interactive "P")
11071 (if all
11072 (progn
11073 (org-update-checkbox-count 'all)
11074 (org-map-entries 'org-update-parent-todo-statistics))
11075 (if (not (org-on-heading-p))
11076 (org-update-checkbox-count)
11077 (let ((pos (move-marker (make-marker) (point)))
11078 end l1 l2)
11079 (ignore-errors (org-back-to-heading t))
11080 (if (not (org-on-heading-p))
11081 (org-update-checkbox-count)
11082 (setq l1 (org-outline-level))
11083 (setq end (save-excursion
11084 (outline-next-heading)
11085 (if (org-on-heading-p) (setq l2 (org-outline-level)))
11086 (point)))
11087 (if (and (save-excursion
11088 (re-search-forward
11089 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11090 (not (save-excursion (re-search-forward
11091 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11092 (org-update-checkbox-count)
11093 (if (and l2 (> l2 l1))
11094 (progn
11095 (goto-char end)
11096 (org-update-parent-todo-statistics))
11097 (goto-char pos)
11098 (beginning-of-line 1)
11099 (while (re-search-forward
11100 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11101 (point-at-eol) t)
11102 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11103 (goto-char pos)
11104 (move-marker pos nil)))))
11106 (defvar org-entry-property-inherited-from) ;; defined below
11107 (defun org-update-parent-todo-statistics ()
11108 "Update any statistics cookie in the parent of the current headline.
11109 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11110 the entire subtree and this will travel up the hierarchy and update
11111 statistics everywhere."
11112 (interactive)
11113 (let* ((lim 0) prop
11114 (recursive (or (not org-hierarchical-todo-statistics)
11115 (string-match
11116 "\\<recursive\\>"
11117 (or (setq prop (org-entry-get
11118 nil "COOKIE_DATA" 'inherit)) ""))))
11119 (lim (or (and prop (marker-position
11120 org-entry-property-inherited-from))
11121 lim))
11122 (first t)
11123 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11124 level ltoggle l1 new ndel
11125 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
11126 (catch 'exit
11127 (save-excursion
11128 (beginning-of-line 1)
11129 (if (org-at-heading-p)
11130 (setq ltoggle (funcall outline-level))
11131 (error "This should not happen"))
11132 (while (and (setq level (org-up-heading-safe))
11133 (or recursive first)
11134 (>= (point) lim))
11135 (setq first nil cookie-present nil)
11136 (unless (and level
11137 (not (string-match
11138 "\\<checkbox\\>"
11139 (downcase
11140 (or (org-entry-get
11141 nil "COOKIE_DATA")
11142 "")))))
11143 (throw 'exit nil))
11144 (while (re-search-forward box-re (point-at-eol) t)
11145 (setq cnt-all 0 cnt-done 0 cookie-present t)
11146 (setq is-percent (match-end 2))
11147 (save-match-data
11148 (unless (outline-next-heading) (throw 'exit nil))
11149 (while (and (looking-at org-complex-heading-regexp)
11150 (> (setq l1 (length (match-string 1))) level))
11151 (setq kwd (and (or recursive (= l1 ltoggle))
11152 (match-string 2)))
11153 (if (or (eq org-provide-todo-statistics 'all-headlines)
11154 (and (listp org-provide-todo-statistics)
11155 (or (member kwd org-provide-todo-statistics)
11156 (member kwd org-done-keywords))))
11157 (setq cnt-all (1+ cnt-all))
11158 (if (eq org-provide-todo-statistics t)
11159 (and kwd (setq cnt-all (1+ cnt-all)))))
11160 (and (member kwd org-done-keywords)
11161 (setq cnt-done (1+ cnt-done)))
11162 (outline-next-heading)))
11163 (setq new
11164 (if is-percent
11165 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11166 (format "[%d/%d]" cnt-done cnt-all))
11167 ndel (- (match-end 0) (match-beginning 0)))
11168 (goto-char (match-beginning 0))
11169 (insert new)
11170 (delete-region (point) (+ (point) ndel)))
11171 (when cookie-present
11172 (run-hook-with-args 'org-after-todo-statistics-hook
11173 cnt-done (- cnt-all cnt-done))))))
11174 (run-hooks 'org-todo-statistics-hook)))
11176 (defvar org-after-todo-statistics-hook nil
11177 "Hook that is called after a TODO statistics cookie has been updated.
11178 Each function is called with two arguments: the number of not-done entries
11179 and the number of done entries.
11181 For example, the following function, when added to this hook, will switch
11182 an entry to DONE when all children are done, and back to TODO when new
11183 entries are set to a TODO status. Note that this hook is only called
11184 when there is a statistics cookie in the headline!
11186 (defun org-summary-todo (n-done n-not-done)
11187 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11188 (let (org-log-done org-log-states) ; turn off logging
11189 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11192 (defvar org-todo-statistics-hook nil
11193 "Hook that is run whenever Org thinks TODO statistics should be updated.
11194 This hook runs even if there is no statistics cookie present, in which case
11195 `org-after-todo-statistics-hook' would not run.")
11197 (defun org-todo-trigger-tag-changes (state)
11198 "Apply the changes defined in `org-todo-state-tags-triggers'."
11199 (let ((l org-todo-state-tags-triggers)
11200 changes)
11201 (when (or (not state) (equal state ""))
11202 (setq changes (append changes (cdr (assoc "" l)))))
11203 (when (and (stringp state) (> (length state) 0))
11204 (setq changes (append changes (cdr (assoc state l)))))
11205 (when (member state org-not-done-keywords)
11206 (setq changes (append changes (cdr (assoc 'todo l)))))
11207 (when (member state org-done-keywords)
11208 (setq changes (append changes (cdr (assoc 'done l)))))
11209 (dolist (c changes)
11210 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11212 (defun org-local-logging (value)
11213 "Get logging settings from a property VALUE."
11214 (let* (words w a)
11215 ;; directly set the variables, they are already local.
11216 (setq org-log-done nil
11217 org-log-repeat nil
11218 org-todo-log-states nil)
11219 (setq words (org-split-string value))
11220 (while (setq w (pop words))
11221 (cond
11222 ((setq a (assoc w org-startup-options))
11223 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11224 (set (nth 1 a) (nth 2 a))))
11225 ((setq a (org-extract-log-state-settings w))
11226 (and (member (car a) org-todo-keywords-1)
11227 (push a org-todo-log-states)))))))
11229 (defun org-get-todo-sequence-head (kwd)
11230 "Return the head of the TODO sequence to which KWD belongs.
11231 If KWD is not set, check if there is a text property remembering the
11232 right sequence."
11233 (let (p)
11234 (cond
11235 ((not kwd)
11236 (or (get-text-property (point-at-bol) 'org-todo-head)
11237 (progn
11238 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11239 nil (point-at-eol)))
11240 (get-text-property p 'org-todo-head))))
11241 ((not (member kwd org-todo-keywords-1))
11242 (car org-todo-keywords-1))
11243 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11245 (defun org-fast-todo-selection ()
11246 "Fast TODO keyword selection with single keys.
11247 Returns the new TODO keyword, or nil if no state change should occur."
11248 (let* ((fulltable org-todo-key-alist)
11249 (done-keywords org-done-keywords) ;; needed for the faces.
11250 (maxlen (apply 'max (mapcar
11251 (lambda (x)
11252 (if (stringp (car x)) (string-width (car x)) 0))
11253 fulltable)))
11254 (expert nil)
11255 (fwidth (+ maxlen 3 1 3))
11256 (ncol (/ (- (window-width) 4) fwidth))
11257 tg cnt e c tbl
11258 groups ingroup)
11259 (save-excursion
11260 (save-window-excursion
11261 (if expert
11262 (set-buffer (get-buffer-create " *Org todo*"))
11263 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11264 (erase-buffer)
11265 (org-set-local 'org-done-keywords done-keywords)
11266 (setq tbl fulltable cnt 0)
11267 (while (setq e (pop tbl))
11268 (cond
11269 ((equal e '(:startgroup))
11270 (push '() groups) (setq ingroup t)
11271 (when (not (= cnt 0))
11272 (setq cnt 0)
11273 (insert "\n"))
11274 (insert "{ "))
11275 ((equal e '(:endgroup))
11276 (setq ingroup nil cnt 0)
11277 (insert "}\n"))
11278 ((equal e '(:newline))
11279 (when (not (= cnt 0))
11280 (setq cnt 0)
11281 (insert "\n")
11282 (setq e (car tbl))
11283 (while (equal (car tbl) '(:newline))
11284 (insert "\n")
11285 (setq tbl (cdr tbl)))))
11287 (setq tg (car e) c (cdr e))
11288 (if ingroup (push tg (car groups)))
11289 (setq tg (org-add-props tg nil 'face
11290 (org-get-todo-face tg)))
11291 (if (and (= cnt 0) (not ingroup)) (insert " "))
11292 (insert "[" c "] " tg (make-string
11293 (- fwidth 4 (length tg)) ?\ ))
11294 (when (= (setq cnt (1+ cnt)) ncol)
11295 (insert "\n")
11296 (if ingroup (insert " "))
11297 (setq cnt 0)))))
11298 (insert "\n")
11299 (goto-char (point-min))
11300 (if (not expert) (org-fit-window-to-buffer))
11301 (message "[a-z..]:Set [SPC]:clear")
11302 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11303 (cond
11304 ((or (= c ?\C-g)
11305 (and (= c ?q) (not (rassoc c fulltable))))
11306 (setq quit-flag t))
11307 ((= c ?\ ) nil)
11308 ((setq e (rassoc c fulltable) tg (car e))
11310 (t (setq quit-flag t)))))))
11312 (defun org-entry-is-todo-p ()
11313 (member (org-get-todo-state) org-not-done-keywords))
11315 (defun org-entry-is-done-p ()
11316 (member (org-get-todo-state) org-done-keywords))
11318 (defun org-get-todo-state ()
11319 (save-excursion
11320 (org-back-to-heading t)
11321 (and (looking-at org-todo-line-regexp)
11322 (match-end 2)
11323 (match-string 2))))
11325 (defun org-at-date-range-p (&optional inactive-ok)
11326 "Is the cursor inside a date range?"
11327 (interactive)
11328 (save-excursion
11329 (catch 'exit
11330 (let ((pos (point)))
11331 (skip-chars-backward "^[<\r\n")
11332 (skip-chars-backward "<[")
11333 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11334 (>= (match-end 0) pos)
11335 (throw 'exit t))
11336 (skip-chars-backward "^<[\r\n")
11337 (skip-chars-backward "<[")
11338 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11339 (>= (match-end 0) pos)
11340 (throw 'exit t)))
11341 nil)))
11343 (defun org-get-repeat (&optional tagline)
11344 "Check if there is a deadline/schedule with repeater in this entry."
11345 (save-match-data
11346 (save-excursion
11347 (org-back-to-heading t)
11348 (and (re-search-forward (if tagline
11349 (concat tagline "\\s-*" org-repeat-re)
11350 org-repeat-re)
11351 (org-entry-end-position) t)
11352 (match-string-no-properties 1)))))
11354 (defvar org-last-changed-timestamp)
11355 (defvar org-last-inserted-timestamp)
11356 (defvar org-log-post-message)
11357 (defvar org-log-note-purpose)
11358 (defvar org-log-note-how)
11359 (defvar org-log-note-extra)
11360 (defun org-auto-repeat-maybe (done-word)
11361 "Check if the current headline contains a repeated deadline/schedule.
11362 If yes, set TODO state back to what it was and change the base date
11363 of repeating deadline/scheduled time stamps to new date.
11364 This function is run automatically after each state change to a DONE state."
11365 ;; last-state is dynamically scoped into this function
11366 (let* ((repeat (org-get-repeat))
11367 (aa (assoc last-state org-todo-kwd-alist))
11368 (interpret (nth 1 aa))
11369 (head (nth 2 aa))
11370 (whata '(("d" . day) ("m" . month) ("y" . year)))
11371 (msg "Entry repeats: ")
11372 (org-log-done nil)
11373 (org-todo-log-states nil)
11374 (nshiftmax 10) (nshift 0)
11375 re type n what ts time to-state)
11376 (when repeat
11377 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11378 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11379 org-todo-repeat-to-state))
11380 (unless (and to-state (member to-state org-todo-keywords-1))
11381 (setq to-state (if (eq interpret 'type) last-state head)))
11382 (org-todo to-state)
11383 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11384 (org-entry-put nil "LAST_REPEAT" (format-time-string
11385 (org-time-stamp-format t t))))
11386 (when org-log-repeat
11387 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11388 (memq 'org-add-log-note post-command-hook))
11389 ;; OK, we are already setup for some record
11390 (if (eq org-log-repeat 'note)
11391 ;; make sure we take a note, not only a time stamp
11392 (setq org-log-note-how 'note))
11393 ;; Set up for taking a record
11394 (org-add-log-setup 'state (or done-word (car org-done-keywords))
11395 last-state
11396 'findpos org-log-repeat)))
11397 (org-back-to-heading t)
11398 (org-add-planning-info nil nil 'closed)
11399 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11400 org-deadline-time-regexp "\\)\\|\\("
11401 org-ts-regexp "\\)"))
11402 (while (re-search-forward
11403 re (save-excursion (outline-next-heading) (point)) t)
11404 (setq type (if (match-end 1) org-scheduled-string
11405 (if (match-end 3) org-deadline-string "Plain:"))
11406 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
11407 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
11408 (setq n (string-to-number (match-string 2 ts))
11409 what (match-string 3 ts))
11410 (if (equal what "w") (setq n (* n 7) what "d"))
11411 ;; Preparation, see if we need to modify the start date for the change
11412 (when (match-end 1)
11413 (setq time (save-match-data (org-time-string-to-time ts)))
11414 (cond
11415 ((equal (match-string 1 ts) ".")
11416 ;; Shift starting date to today
11417 (org-timestamp-change
11418 (- (time-to-days (current-time)) (time-to-days time))
11419 'day))
11420 ((equal (match-string 1 ts) "+")
11421 (while (or (= nshift 0)
11422 (<= (time-to-days time) (time-to-days (current-time))))
11423 (when (= (incf nshift) nshiftmax)
11424 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
11425 (error "Abort")))
11426 (org-timestamp-change n (cdr (assoc what whata)))
11427 (org-at-timestamp-p t)
11428 (setq ts (match-string 1))
11429 (setq time (save-match-data (org-time-string-to-time ts))))
11430 (org-timestamp-change (- n) (cdr (assoc what whata)))
11431 ;; rematch, so that we have everything in place for the real shift
11432 (org-at-timestamp-p t)
11433 (setq ts (match-string 1))
11434 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
11435 (org-timestamp-change n (cdr (assoc what whata)))
11436 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
11437 (setq org-log-post-message msg)
11438 (message "%s" msg))))
11440 (defun org-show-todo-tree (arg)
11441 "Make a compact tree which shows all headlines marked with TODO.
11442 The tree will show the lines where the regexp matches, and all higher
11443 headlines above the match.
11444 With a \\[universal-argument] prefix, prompt for a regexp to match.
11445 With a numeric prefix N, construct a sparse tree for the Nth element
11446 of `org-todo-keywords-1'."
11447 (interactive "P")
11448 (let ((case-fold-search nil)
11449 (kwd-re
11450 (cond ((null arg) org-not-done-regexp)
11451 ((equal arg '(4))
11452 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
11453 (mapcar 'list org-todo-keywords-1))))
11454 (concat "\\("
11455 (mapconcat 'identity (org-split-string kwd "|") "\\|")
11456 "\\)\\>")))
11457 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
11458 (regexp-quote (nth (1- (prefix-numeric-value arg))
11459 org-todo-keywords-1)))
11460 (t (error "Invalid prefix argument: %s" arg)))))
11461 (message "%d TODO entries found"
11462 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
11464 (defun org-deadline (&optional remove time)
11465 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
11466 With argument REMOVE, remove any deadline from the item.
11467 When TIME is set, it should be an internal time specification, and the
11468 scheduling will use the corresponding date."
11469 (interactive "P")
11470 (let* ((old-date (org-entry-get nil "DEADLINE"))
11471 (repeater (and old-date
11472 (string-match "\\([.+]+[0-9]+[dwmy]\\) ?" old-date)
11473 (match-string 1 old-date))))
11474 (if remove
11475 (progn
11476 (when (and old-date org-log-redeadline)
11477 (org-add-log-setup 'deldeadline nil old-date 'findpos
11478 org-log-redeadline))
11479 (org-remove-timestamp-with-keyword org-deadline-string)
11480 (message "Item no longer has a deadline."))
11481 (org-add-planning-info 'deadline time 'closed)
11482 (when (and old-date org-log-redeadline
11483 (not (equal old-date
11484 (substring org-last-inserted-timestamp 1 -1))))
11485 (org-add-log-setup 'redeadline nil old-date 'findpos
11486 org-log-redeadline))
11487 (when repeater
11488 (save-excursion
11489 (org-back-to-heading t)
11490 (when (re-search-forward (concat org-deadline-string " "
11491 org-last-inserted-timestamp)
11492 (save-excursion
11493 (outline-next-heading) (point)) t)
11494 (goto-char (1- (match-end 0)))
11495 (insert " " repeater)
11496 (setq org-last-inserted-timestamp
11497 (concat (substring org-last-inserted-timestamp 0 -1)
11498 " " repeater
11499 (substring org-last-inserted-timestamp -1))))))
11500 (message "Deadline on %s" org-last-inserted-timestamp))))
11502 (defun org-schedule (&optional remove time)
11503 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
11504 With argument REMOVE, remove any scheduling date from the item.
11505 When TIME is set, it should be an internal time specification, and the
11506 scheduling will use the corresponding date."
11507 (interactive "P")
11508 (let* ((old-date (org-entry-get nil "SCHEDULED"))
11509 (repeater (and old-date
11510 (string-match "\\([.+]+[0-9]+[dwmy]\\) ?" old-date)
11511 (match-string 1 old-date))))
11512 (if remove
11513 (progn
11514 (when (and old-date org-log-reschedule)
11515 (org-add-log-setup 'delschedule nil old-date 'findpos
11516 org-log-reschedule))
11517 (org-remove-timestamp-with-keyword org-scheduled-string)
11518 (message "Item is no longer scheduled."))
11519 (org-add-planning-info 'scheduled time 'closed)
11520 (when (and old-date org-log-reschedule
11521 (not (equal old-date
11522 (substring org-last-inserted-timestamp 1 -1))))
11523 (org-add-log-setup 'reschedule nil old-date 'findpos
11524 org-log-reschedule))
11525 (when repeater
11526 (save-excursion
11527 (org-back-to-heading t)
11528 (when (re-search-forward (concat org-scheduled-string " "
11529 org-last-inserted-timestamp)
11530 (save-excursion
11531 (outline-next-heading) (point)) t)
11532 (goto-char (1- (match-end 0)))
11533 (insert " " repeater)
11534 (setq org-last-inserted-timestamp
11535 (concat (substring org-last-inserted-timestamp 0 -1)
11536 " " repeater
11537 (substring org-last-inserted-timestamp -1))))))
11538 (message "Scheduled to %s" org-last-inserted-timestamp))))
11540 (defun org-get-scheduled-time (pom &optional inherit)
11541 "Get the scheduled time as a time tuple, of a format suitable
11542 for calling org-schedule with, or if there is no scheduling,
11543 returns nil."
11544 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
11545 (when time
11546 (apply 'encode-time (org-parse-time-string time)))))
11548 (defun org-get-deadline-time (pom &optional inherit)
11549 "Get the deadline as a time tuple, of a format suitable for
11550 calling org-deadline with, or if there is no scheduling, returns
11551 nil."
11552 (let ((time (org-entry-get pom "DEADLINE" inherit)))
11553 (when time
11554 (apply 'encode-time (org-parse-time-string time)))))
11556 (defun org-remove-timestamp-with-keyword (keyword)
11557 "Remove all time stamps with KEYWORD in the current entry."
11558 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
11559 beg)
11560 (save-excursion
11561 (org-back-to-heading t)
11562 (setq beg (point))
11563 (outline-next-heading)
11564 (while (re-search-backward re beg t)
11565 (replace-match "")
11566 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
11567 (equal (char-before) ?\ ))
11568 (backward-delete-char 1)
11569 (if (string-match "^[ \t]*$" (buffer-substring
11570 (point-at-bol) (point-at-eol)))
11571 (delete-region (point-at-bol)
11572 (min (point-max) (1+ (point-at-eol))))))))))
11574 (defun org-add-planning-info (what &optional time &rest remove)
11575 "Insert new timestamp with keyword in the line directly after the headline.
11576 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
11577 If non is given, the user is prompted for a date.
11578 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
11579 be removed."
11580 (interactive)
11581 (let (org-time-was-given org-end-time-was-given ts
11582 end default-time default-input)
11584 (catch 'exit
11585 (when (and (not time) (memq what '(scheduled deadline)))
11586 ;; Try to get a default date/time from existing timestamp
11587 (save-excursion
11588 (org-back-to-heading t)
11589 (setq end (save-excursion (outline-next-heading) (point)))
11590 (when (re-search-forward (if (eq what 'scheduled)
11591 org-scheduled-time-regexp
11592 org-deadline-time-regexp)
11593 end t)
11594 (setq ts (match-string 1)
11595 default-time
11596 (apply 'encode-time (org-parse-time-string ts))
11597 default-input (and ts (org-get-compact-tod ts))))))
11598 (when what
11599 ;; If necessary, get the time from the user
11600 (setq time (or time (org-read-date nil 'to-time nil nil
11601 default-time default-input))))
11603 (when (and org-insert-labeled-timestamps-at-point
11604 (member what '(scheduled deadline)))
11605 (insert
11606 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
11607 (org-insert-time-stamp time org-time-was-given
11608 nil nil nil (list org-end-time-was-given))
11609 (setq what nil))
11610 (save-excursion
11611 (save-restriction
11612 (let (col list elt ts buffer-invisibility-spec)
11613 (org-back-to-heading t)
11614 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
11615 (goto-char (match-end 1))
11616 (setq col (current-column))
11617 (goto-char (match-end 0))
11618 (if (eobp) (insert "\n") (forward-char 1))
11619 (when (and (not what)
11620 (not (looking-at
11621 (concat "[ \t]*"
11622 org-keyword-time-not-clock-regexp))))
11623 ;; Nothing to add, nothing to remove...... :-)
11624 (throw 'exit nil))
11625 (if (and (not (looking-at outline-regexp))
11626 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
11627 "[^\r\n]*"))
11628 (not (equal (match-string 1) org-clock-string)))
11629 (narrow-to-region (match-beginning 0) (match-end 0))
11630 (insert-before-markers "\n")
11631 (backward-char 1)
11632 (narrow-to-region (point) (point))
11633 (and org-adapt-indentation (org-indent-to-column col)))
11634 ;; Check if we have to remove something.
11635 (setq list (cons what remove))
11636 (while list
11637 (setq elt (pop list))
11638 (goto-char (point-min))
11639 (when (or (and (eq elt 'scheduled)
11640 (re-search-forward org-scheduled-time-regexp nil t))
11641 (and (eq elt 'deadline)
11642 (re-search-forward org-deadline-time-regexp nil t))
11643 (and (eq elt 'closed)
11644 (re-search-forward org-closed-time-regexp nil t)))
11645 (replace-match "")
11646 (if (looking-at "--+<[^>]+>") (replace-match ""))
11647 (skip-chars-backward " ")
11648 (if (looking-at " +") (replace-match ""))))
11649 (goto-char (point-max))
11650 (and org-adapt-indentation (bolp) (org-indent-to-column col))
11651 (when what
11652 (insert
11653 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
11654 (cond ((eq what 'scheduled) org-scheduled-string)
11655 ((eq what 'deadline) org-deadline-string)
11656 ((eq what 'closed) org-closed-string))
11657 " ")
11658 (setq ts (org-insert-time-stamp
11659 time
11660 (or org-time-was-given
11661 (and (eq what 'closed) org-log-done-with-time))
11662 (eq what 'closed)
11663 nil nil (list org-end-time-was-given)))
11664 (end-of-line 1))
11665 (goto-char (point-min))
11666 (widen)
11667 (if (and (looking-at "[ \t]*\n")
11668 (equal (char-before) ?\n))
11669 (delete-region (1- (point)) (point-at-eol)))
11670 ts))))))
11672 (defvar org-log-note-marker (make-marker))
11673 (defvar org-log-note-purpose nil)
11674 (defvar org-log-note-state nil)
11675 (defvar org-log-note-previous-state nil)
11676 (defvar org-log-note-how nil)
11677 (defvar org-log-note-extra nil)
11678 (defvar org-log-note-window-configuration nil)
11679 (defvar org-log-note-return-to (make-marker))
11680 (defvar org-log-post-message nil
11681 "Message to be displayed after a log note has been stored.
11682 The auto-repeater uses this.")
11684 (defun org-add-note ()
11685 "Add a note to the current entry.
11686 This is done in the same way as adding a state change note."
11687 (interactive)
11688 (org-add-log-setup 'note nil nil 'findpos nil))
11690 (defvar org-property-end-re)
11691 (defun org-add-log-setup (&optional purpose state prev-state
11692 findpos how &optional extra)
11693 "Set up the post command hook to take a note.
11694 If this is about to TODO state change, the new state is expected in STATE.
11695 When FINDPOS is non-nil, find the correct position for the note in
11696 the current entry. If not, assume that it can be inserted at point.
11697 HOW is an indicator what kind of note should be created.
11698 EXTRA is additional text that will be inserted into the notes buffer."
11699 (let* ((org-log-into-drawer (org-log-into-drawer))
11700 (drawer (cond ((stringp org-log-into-drawer)
11701 org-log-into-drawer)
11702 (org-log-into-drawer "LOGBOOK")
11703 (t nil))))
11704 (save-restriction
11705 (save-excursion
11706 (when findpos
11707 (org-back-to-heading t)
11708 (narrow-to-region (point) (save-excursion
11709 (outline-next-heading) (point)))
11710 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
11711 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
11712 "[^\r\n]*\\)?"))
11713 (goto-char (match-end 0))
11714 (cond
11715 (drawer
11716 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
11717 nil t)
11718 (progn
11719 (goto-char (match-end 0))
11720 (or org-log-states-order-reversed
11721 (and (re-search-forward org-property-end-re nil t)
11722 (goto-char (1- (match-beginning 0))))))
11723 (insert "\n:" drawer ":\n:END:")
11724 (beginning-of-line 0)
11725 (org-indent-line-function)
11726 (beginning-of-line 2)
11727 (org-indent-line-function)
11728 (end-of-line 0)))
11729 ((and org-log-state-notes-insert-after-drawers
11730 (save-excursion
11731 (forward-line) (looking-at org-drawer-regexp)))
11732 (forward-line)
11733 (while (looking-at org-drawer-regexp)
11734 (goto-char (match-end 0))
11735 (re-search-forward org-property-end-re (point-max) t)
11736 (forward-line))
11737 (forward-line -1)))
11738 (unless org-log-states-order-reversed
11739 (and (= (char-after) ?\n) (forward-char 1))
11740 (org-skip-over-state-notes)
11741 (skip-chars-backward " \t\n\r")))
11742 (move-marker org-log-note-marker (point))
11743 (setq org-log-note-purpose purpose
11744 org-log-note-state state
11745 org-log-note-previous-state prev-state
11746 org-log-note-how how
11747 org-log-note-extra extra)
11748 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
11750 (defun org-skip-over-state-notes ()
11751 "Skip past the list of State notes in an entry."
11752 (if (looking-at "\n[ \t]*- State") (forward-char 1))
11753 (while (looking-at "[ \t]*- State")
11754 (condition-case nil
11755 (org-next-item)
11756 (error (org-end-of-item)))))
11758 (defun org-add-log-note (&optional purpose)
11759 "Pop up a window for taking a note, and add this note later at point."
11760 (remove-hook 'post-command-hook 'org-add-log-note)
11761 (setq org-log-note-window-configuration (current-window-configuration))
11762 (delete-other-windows)
11763 (move-marker org-log-note-return-to (point))
11764 (switch-to-buffer (marker-buffer org-log-note-marker))
11765 (goto-char org-log-note-marker)
11766 (org-switch-to-buffer-other-window "*Org Note*")
11767 (erase-buffer)
11768 (if (memq org-log-note-how '(time state))
11769 (let (current-prefix-arg) (org-store-log-note))
11770 (let ((org-inhibit-startup t)) (org-mode))
11771 (insert (format "# Insert note for %s.
11772 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
11773 (cond
11774 ((eq org-log-note-purpose 'clock-out) "stopped clock")
11775 ((eq org-log-note-purpose 'done) "closed todo item")
11776 ((eq org-log-note-purpose 'state)
11777 (format "state change from \"%s\" to \"%s\""
11778 (or org-log-note-previous-state "")
11779 (or org-log-note-state "")))
11780 ((eq org-log-note-purpose 'reschedule)
11781 "rescheduling")
11782 ((eq org-log-note-purpose 'delschedule)
11783 "no longer scheduled")
11784 ((eq org-log-note-purpose 'redeadline)
11785 "changing deadline")
11786 ((eq org-log-note-purpose 'deldeadline)
11787 "removing deadline")
11788 ((eq org-log-note-purpose 'refile)
11789 "refiling")
11790 ((eq org-log-note-purpose 'note)
11791 "this entry")
11792 (t (error "This should not happen")))))
11793 (if org-log-note-extra (insert org-log-note-extra))
11794 (org-set-local 'org-finish-function 'org-store-log-note)))
11796 (defvar org-note-abort nil) ; dynamically scoped
11797 (defun org-store-log-note ()
11798 "Finish taking a log note, and insert it to where it belongs."
11799 (let ((txt (buffer-string))
11800 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
11801 lines ind)
11802 (kill-buffer (current-buffer))
11803 (while (string-match "\\`#.*\n[ \t\n]*" txt)
11804 (setq txt (replace-match "" t t txt)))
11805 (if (string-match "\\s-+\\'" txt)
11806 (setq txt (replace-match "" t t txt)))
11807 (setq lines (org-split-string txt "\n"))
11808 (when (and note (string-match "\\S-" note))
11809 (setq note
11810 (org-replace-escapes
11811 note
11812 (list (cons "%u" (user-login-name))
11813 (cons "%U" user-full-name)
11814 (cons "%t" (format-time-string
11815 (org-time-stamp-format 'long 'inactive)
11816 (current-time)))
11817 (cons "%T" (format-time-string
11818 (org-time-stamp-format 'long nil)
11819 (current-time)))
11820 (cons "%s" (if org-log-note-state
11821 (concat "\"" org-log-note-state "\"")
11822 ""))
11823 (cons "%S" (if org-log-note-previous-state
11824 (concat "\"" org-log-note-previous-state "\"")
11825 "\"\"")))))
11826 (if lines (setq note (concat note " \\\\")))
11827 (push note lines))
11828 (when (or current-prefix-arg org-note-abort)
11829 (when org-log-into-drawer
11830 (org-remove-empty-drawer-at
11831 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
11832 org-log-note-marker))
11833 (setq lines nil))
11834 (when lines
11835 (with-current-buffer (marker-buffer org-log-note-marker)
11836 (save-excursion
11837 (goto-char org-log-note-marker)
11838 (move-marker org-log-note-marker nil)
11839 (end-of-line 1)
11840 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
11841 (insert "- " (pop lines))
11842 (org-indent-line-function)
11843 (beginning-of-line 1)
11844 (looking-at "[ \t]*")
11845 (setq ind (concat (match-string 0) " "))
11846 (end-of-line 1)
11847 (while lines (insert "\n" ind (pop lines)))
11848 (message "Note stored")
11849 (org-back-to-heading t)
11850 (org-cycle-hide-drawers 'children)))))
11851 (set-window-configuration org-log-note-window-configuration)
11852 (with-current-buffer (marker-buffer org-log-note-return-to)
11853 (goto-char org-log-note-return-to))
11854 (move-marker org-log-note-return-to nil)
11855 (and org-log-post-message (message "%s" org-log-post-message)))
11857 (defun org-remove-empty-drawer-at (drawer pos)
11858 "Remove an empty drawer DRAWER at position POS.
11859 POS may also be a marker."
11860 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
11861 (save-excursion
11862 (save-restriction
11863 (widen)
11864 (goto-char pos)
11865 (if (org-in-regexp
11866 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
11867 (replace-match ""))))))
11869 (defun org-sparse-tree (&optional arg)
11870 "Create a sparse tree, prompt for the details.
11871 This command can create sparse trees. You first need to select the type
11872 of match used to create the tree:
11874 t Show all TODO entries.
11875 T Show entries with a specific TODO keyword.
11876 m Show entries selected by a tags/property match.
11877 p Enter a property name and its value (both with completion on existing
11878 names/values) and show entries with that property.
11879 / Show entries matching a regular expression (`r' can be used as well)
11880 d Show deadlines due within `org-deadline-warning-days'.
11881 b Show deadlines and scheduled items before a date.
11882 a Show deadlines and scheduled items after a date."
11883 (interactive "P")
11884 (let (ans kwd value)
11885 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty [d]eadlines\n [b]efore-date [a]fter-date")
11886 (setq ans (read-char-exclusive))
11887 (cond
11888 ((equal ans ?d)
11889 (call-interactively 'org-check-deadlines))
11890 ((equal ans ?b)
11891 (call-interactively 'org-check-before-date))
11892 ((equal ans ?a)
11893 (call-interactively 'org-check-after-date))
11894 ((equal ans ?t)
11895 (org-show-todo-tree nil))
11896 ((equal ans ?T)
11897 (org-show-todo-tree '(4)))
11898 ((member ans '(?T ?m))
11899 (call-interactively 'org-match-sparse-tree))
11900 ((member ans '(?p ?P))
11901 (setq kwd (org-icompleting-read "Property: "
11902 (mapcar 'list (org-buffer-property-keys))))
11903 (setq value (org-icompleting-read "Value: "
11904 (mapcar 'list (org-property-values kwd))))
11905 (unless (string-match "\\`{.*}\\'" value)
11906 (setq value (concat "\"" value "\"")))
11907 (org-match-sparse-tree arg (concat kwd "=" value)))
11908 ((member ans '(?r ?R ?/))
11909 (call-interactively 'org-occur))
11910 (t (error "No such sparse tree command \"%c\"" ans)))))
11912 (defvar org-occur-highlights nil
11913 "List of overlays used for occur matches.")
11914 (make-variable-buffer-local 'org-occur-highlights)
11915 (defvar org-occur-parameters nil
11916 "Parameters of the active org-occur calls.
11917 This is a list, each call to org-occur pushes as cons cell,
11918 containing the regular expression and the callback, onto the list.
11919 The list can contain several entries if `org-occur' has been called
11920 several time with the KEEP-PREVIOUS argument. Otherwise, this list
11921 will only contain one set of parameters. When the highlights are
11922 removed (for example with `C-c C-c', or with the next edit (depending
11923 on `org-remove-highlights-with-change'), this variable is emptied
11924 as well.")
11925 (make-variable-buffer-local 'org-occur-parameters)
11927 (defun org-occur (regexp &optional keep-previous callback)
11928 "Make a compact tree which shows all matches of REGEXP.
11929 The tree will show the lines where the regexp matches, and all higher
11930 headlines above the match. It will also show the heading after the match,
11931 to make sure editing the matching entry is easy.
11932 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
11933 call to `org-occur' will be kept, to allow stacking of calls to this
11934 command.
11935 If CALLBACK is non-nil, it is a function which is called to confirm
11936 that the match should indeed be shown."
11937 (interactive "sRegexp: \nP")
11938 (when (equal regexp "")
11939 (error "Regexp cannot be empty"))
11940 (unless keep-previous
11941 (org-remove-occur-highlights nil nil t))
11942 (push (cons regexp callback) org-occur-parameters)
11943 (let ((cnt 0))
11944 (save-excursion
11945 (goto-char (point-min))
11946 (if (or (not keep-previous) ; do not want to keep
11947 (not org-occur-highlights)) ; no previous matches
11948 ;; hide everything
11949 (org-overview))
11950 (while (re-search-forward regexp nil t)
11951 (when (or (not callback)
11952 (save-match-data (funcall callback)))
11953 (setq cnt (1+ cnt))
11954 (when org-highlight-sparse-tree-matches
11955 (org-highlight-new-match (match-beginning 0) (match-end 0)))
11956 (org-show-context 'occur-tree))))
11957 (when org-remove-highlights-with-change
11958 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
11959 nil 'local))
11960 (unless org-sparse-tree-open-archived-trees
11961 (org-hide-archived-subtrees (point-min) (point-max)))
11962 (run-hooks 'org-occur-hook)
11963 (if (interactive-p)
11964 (message "%d match(es) for regexp %s" cnt regexp))
11965 cnt))
11967 (defun org-show-context (&optional key)
11968 "Make sure point and context are visible.
11969 How much context is shown depends upon the variables
11970 `org-show-hierarchy-above', `org-show-following-heading'. and
11971 `org-show-siblings'."
11972 (let ((heading-p (org-on-heading-p t))
11973 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
11974 (following-p (org-get-alist-option org-show-following-heading key))
11975 (entry-p (org-get-alist-option org-show-entry-below key))
11976 (siblings-p (org-get-alist-option org-show-siblings key)))
11977 (catch 'exit
11978 ;; Show heading or entry text
11979 (if (and heading-p (not entry-p))
11980 (org-flag-heading nil) ; only show the heading
11981 (and (or entry-p (org-invisible-p) (org-invisible-p2))
11982 (org-show-hidden-entry))) ; show entire entry
11983 (when following-p
11984 ;; Show next sibling, or heading below text
11985 (save-excursion
11986 (and (if heading-p (org-goto-sibling) (outline-next-heading))
11987 (org-flag-heading nil))))
11988 (when siblings-p (org-show-siblings))
11989 (when hierarchy-p
11990 ;; show all higher headings, possibly with siblings
11991 (save-excursion
11992 (while (and (condition-case nil
11993 (progn (org-up-heading-all 1) t)
11994 (error nil))
11995 (not (bobp)))
11996 (org-flag-heading nil)
11997 (when siblings-p (org-show-siblings))))))))
11999 (defvar org-reveal-start-hook nil
12000 "Hook run before revealing a location.")
12002 (defun org-reveal (&optional siblings)
12003 "Show current entry, hierarchy above it, and the following headline.
12004 This can be used to show a consistent set of context around locations
12005 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12006 not t for the search context.
12008 With optional argument SIBLINGS, on each level of the hierarchy all
12009 siblings are shown. This repairs the tree structure to what it would
12010 look like when opened with hierarchical calls to `org-cycle'.
12011 With double optional argument \\[universal-argument] \\[universal-argument], \
12012 go to the parent and show the
12013 entire tree."
12014 (interactive "P")
12015 (run-hooks 'org-reveal-start-hook)
12016 (let ((org-show-hierarchy-above t)
12017 (org-show-following-heading t)
12018 (org-show-siblings (if siblings t org-show-siblings)))
12019 (org-show-context nil))
12020 (when (equal siblings '(16))
12021 (save-excursion
12022 (when (org-up-heading-safe)
12023 (org-show-subtree)
12024 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12026 (defun org-highlight-new-match (beg end)
12027 "Highlight from BEG to END and mark the highlight is an occur headline."
12028 (let ((ov (make-overlay beg end)))
12029 (overlay-put ov 'face 'secondary-selection)
12030 (push ov org-occur-highlights)))
12032 (defun org-remove-occur-highlights (&optional beg end noremove)
12033 "Remove the occur highlights from the buffer.
12034 BEG and END are ignored. If NOREMOVE is nil, remove this function
12035 from the `before-change-functions' in the current buffer."
12036 (interactive)
12037 (unless org-inhibit-highlight-removal
12038 (mapc 'delete-overlay org-occur-highlights)
12039 (setq org-occur-highlights nil)
12040 (setq org-occur-parameters nil)
12041 (unless noremove
12042 (remove-hook 'before-change-functions
12043 'org-remove-occur-highlights 'local))))
12045 ;;;; Priorities
12047 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12048 "Regular expression matching the priority indicator.")
12050 (defvar org-remove-priority-next-time nil)
12052 (defun org-priority-up ()
12053 "Increase the priority of the current item."
12054 (interactive)
12055 (org-priority 'up))
12057 (defun org-priority-down ()
12058 "Decrease the priority of the current item."
12059 (interactive)
12060 (org-priority 'down))
12062 (defun org-priority (&optional action)
12063 "Change the priority of an item by ARG.
12064 ACTION can be `set', `up', `down', or a character."
12065 (interactive)
12066 (unless org-enable-priority-commands
12067 (error "Priority commands are disabled"))
12068 (setq action (or action 'set))
12069 (let (current new news have remove)
12070 (save-excursion
12071 (org-back-to-heading t)
12072 (if (looking-at org-priority-regexp)
12073 (setq current (string-to-char (match-string 2))
12074 have t)
12075 (setq current org-default-priority))
12076 (cond
12077 ((eq action 'remove)
12078 (setq remove t new ?\ ))
12079 ((or (eq action 'set)
12080 (if (featurep 'xemacs) (characterp action) (integerp action)))
12081 (if (not (eq action 'set))
12082 (setq new action)
12083 (message "Priority %c-%c, SPC to remove: "
12084 org-highest-priority org-lowest-priority)
12085 (setq new (read-char-exclusive)))
12086 (if (and (= (upcase org-highest-priority) org-highest-priority)
12087 (= (upcase org-lowest-priority) org-lowest-priority))
12088 (setq new (upcase new)))
12089 (cond ((equal new ?\ ) (setq remove t))
12090 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12091 (error "Priority must be between `%c' and `%c'"
12092 org-highest-priority org-lowest-priority))))
12093 ((eq action 'up)
12094 (if (and (not have) (eq last-command this-command))
12095 (setq new org-lowest-priority)
12096 (setq new (if (and org-priority-start-cycle-with-default (not have))
12097 org-default-priority (1- current)))))
12098 ((eq action 'down)
12099 (if (and (not have) (eq last-command this-command))
12100 (setq new org-highest-priority)
12101 (setq new (if (and org-priority-start-cycle-with-default (not have))
12102 org-default-priority (1+ current)))))
12103 (t (error "Invalid action")))
12104 (if (or (< (upcase new) org-highest-priority)
12105 (> (upcase new) org-lowest-priority))
12106 (setq remove t))
12107 (setq news (format "%c" new))
12108 (if have
12109 (if remove
12110 (replace-match "" t t nil 1)
12111 (replace-match news t t nil 2))
12112 (if remove
12113 (error "No priority cookie found in line")
12114 (let ((case-fold-search nil))
12115 (looking-at org-todo-line-regexp))
12116 (if (match-end 2)
12117 (progn
12118 (goto-char (match-end 2))
12119 (insert " [#" news "]"))
12120 (goto-char (match-beginning 3))
12121 (insert "[#" news "] "))))
12122 (org-preserve-lc (org-set-tags nil 'align)))
12123 (if remove
12124 (message "Priority removed")
12125 (message "Priority of current item set to %s" news))))
12127 (defun org-get-priority (s)
12128 "Find priority cookie and return priority."
12129 (save-match-data
12130 (if (not (string-match org-priority-regexp s))
12131 (* 1000 (- org-lowest-priority org-default-priority))
12132 (* 1000 (- org-lowest-priority
12133 (string-to-char (match-string 2 s)))))))
12135 ;;;; Tags
12137 (defvar org-agenda-archives-mode)
12138 (defvar org-map-continue-from nil
12139 "Position from where mapping should continue.
12140 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
12142 (defvar org-scanner-tags nil
12143 "The current tag list while the tags scanner is running.")
12144 (defvar org-trust-scanner-tags nil
12145 "Should `org-get-tags-at' use the tags fro the scanner.
12146 This is for internal dynamical scoping only.
12147 When this is non-nil, the function `org-get-tags-at' will return the value
12148 of `org-scanner-tags' instead of building the list by itself. This
12149 can lead to large speed-ups when the tags scanner is used in a file with
12150 many entries, and when the list of tags is retrieved, for example to
12151 obtain a list of properties. Building the tags list for each entry in such
12152 a file becomes an N^2 operation - but with this variable set, it scales
12153 as N.")
12155 (defun org-scan-tags (action matcher &optional todo-only)
12156 "Scan headline tags with inheritance and produce output ACTION.
12158 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12159 or `agenda' to produce an entry list for an agenda view. It can also be
12160 a Lisp form or a function that should be called at each matched headline, in
12161 this case the return value is a list of all return values from these calls.
12163 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12164 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12165 only lines with a TODO keyword are included in the output."
12166 (require 'org-agenda)
12167 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
12168 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12169 (org-re
12170 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
12171 (props (list 'face 'default
12172 'done-face 'org-agenda-done
12173 'undone-face 'default
12174 'mouse-face 'highlight
12175 'org-not-done-regexp org-not-done-regexp
12176 'org-todo-regexp org-todo-regexp
12177 'help-echo
12178 (format "mouse-2 or RET jump to org file %s"
12179 (abbreviate-file-name
12180 (or (buffer-file-name (buffer-base-buffer))
12181 (buffer-name (buffer-base-buffer)))))))
12182 (case-fold-search nil)
12183 (org-map-continue-from nil)
12184 lspos tags tags-list
12185 (tags-alist (list (cons 0 org-file-tags)))
12186 (llast 0) rtn rtn1 level category i txt
12187 todo marker entry priority)
12188 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12189 (setq action (list 'lambda nil action)))
12190 (save-excursion
12191 (goto-char (point-min))
12192 (when (eq action 'sparse-tree)
12193 (org-overview)
12194 (org-remove-occur-highlights))
12195 (while (re-search-forward re nil t)
12196 (catch :skip
12197 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12198 tags (if (match-end 4) (org-match-string-no-properties 4)))
12199 (goto-char (setq lspos (match-beginning 0)))
12200 (setq level (org-reduced-level (funcall outline-level))
12201 category (org-get-category))
12202 (setq i llast llast level)
12203 ;; remove tag lists from same and sublevels
12204 (while (>= i level)
12205 (when (setq entry (assoc i tags-alist))
12206 (setq tags-alist (delete entry tags-alist)))
12207 (setq i (1- i)))
12208 ;; add the next tags
12209 (when tags
12210 (setq tags (org-split-string tags ":")
12211 tags-alist
12212 (cons (cons level tags) tags-alist)))
12213 ;; compile tags for current headline
12214 (setq tags-list
12215 (if org-use-tag-inheritance
12216 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12217 tags)
12218 org-scanner-tags tags-list)
12219 (when org-use-tag-inheritance
12220 (setcdr (car tags-alist)
12221 (mapcar (lambda (x)
12222 (setq x (copy-sequence x))
12223 (org-add-prop-inherited x))
12224 (cdar tags-alist))))
12225 (when (and tags org-use-tag-inheritance
12226 (or (not (eq t org-use-tag-inheritance))
12227 org-tags-exclude-from-inheritance))
12228 ;; selective inheritance, remove uninherited ones
12229 (setcdr (car tags-alist)
12230 (org-remove-uniherited-tags (cdar tags-alist))))
12231 (when (and (or (not todo-only)
12232 (and (member todo org-not-done-keywords)
12233 (or (not org-agenda-tags-todo-honor-ignore-options)
12234 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
12235 (let ((case-fold-search t)) (eval matcher))
12237 (not (member org-archive-tag tags-list))
12238 ;; we have an archive tag, should we use this anyway?
12239 (or (not org-agenda-skip-archived-trees)
12240 (and (eq action 'agenda) org-agenda-archives-mode))))
12241 (unless (eq action 'sparse-tree) (org-agenda-skip))
12243 ;; select this headline
12245 (cond
12246 ((eq action 'sparse-tree)
12247 (and org-highlight-sparse-tree-matches
12248 (org-get-heading) (match-end 0)
12249 (org-highlight-new-match
12250 (match-beginning 0) (match-beginning 1)))
12251 (org-show-context 'tags-tree))
12252 ((eq action 'agenda)
12253 (setq txt (org-format-agenda-item
12255 (concat
12256 (if (eq org-tags-match-list-sublevels 'indented)
12257 (make-string (1- level) ?.) "")
12258 (org-get-heading))
12259 category
12260 tags-list
12262 priority (org-get-priority txt))
12263 (goto-char lspos)
12264 (setq marker (org-agenda-new-marker))
12265 (org-add-props txt props
12266 'org-marker marker 'org-hd-marker marker 'org-category category
12267 'todo-state todo
12268 'priority priority 'type "tagsmatch")
12269 (push txt rtn))
12270 ((functionp action)
12271 (setq org-map-continue-from nil)
12272 (save-excursion
12273 (setq rtn1 (funcall action))
12274 (push rtn1 rtn)))
12275 (t (error "Invalid action")))
12277 ;; if we are to skip sublevels, jump to end of subtree
12278 (unless org-tags-match-list-sublevels
12279 (org-end-of-subtree t)
12280 (backward-char 1))))
12281 ;; Get the correct position from where to continue
12282 (if org-map-continue-from
12283 (goto-char org-map-continue-from)
12284 (and (= (point) lspos) (end-of-line 1)))))
12285 (when (and (eq action 'sparse-tree)
12286 (not org-sparse-tree-open-archived-trees))
12287 (org-hide-archived-subtrees (point-min) (point-max)))
12288 (nreverse rtn)))
12290 (defun org-remove-uniherited-tags (tags)
12291 "Remove all tags that are not inherited from the list TAGS."
12292 (cond
12293 ((eq org-use-tag-inheritance t)
12294 (if org-tags-exclude-from-inheritance
12295 (org-delete-all org-tags-exclude-from-inheritance tags)
12296 tags))
12297 ((not org-use-tag-inheritance) nil)
12298 ((stringp org-use-tag-inheritance)
12299 (delq nil (mapcar
12300 (lambda (x)
12301 (if (and (string-match org-use-tag-inheritance x)
12302 (not (member x org-tags-exclude-from-inheritance)))
12303 x nil))
12304 tags)))
12305 ((listp org-use-tag-inheritance)
12306 (delq nil (mapcar
12307 (lambda (x)
12308 (if (member x org-use-tag-inheritance) x nil))
12309 tags)))))
12311 (defvar todo-only) ;; dynamically scoped
12313 (defun org-match-sparse-tree (&optional todo-only match)
12314 "Create a sparse tree according to tags string MATCH.
12315 MATCH can contain positive and negative selection of tags, like
12316 \"+WORK+URGENT-WITHBOSS\".
12317 If optional argument TODO-ONLY is non-nil, only select lines that are
12318 also TODO lines."
12319 (interactive "P")
12320 (org-prepare-agenda-buffers (list (current-buffer)))
12321 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
12323 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
12325 (defvar org-cached-props nil)
12326 (defun org-cached-entry-get (pom property)
12327 (if (or (eq t org-use-property-inheritance)
12328 (and (stringp org-use-property-inheritance)
12329 (string-match org-use-property-inheritance property))
12330 (and (listp org-use-property-inheritance)
12331 (member property org-use-property-inheritance)))
12332 ;; Caching is not possible, check it directly
12333 (org-entry-get pom property 'inherit)
12334 ;; Get all properties, so that we can do complicated checks easily
12335 (cdr (assoc property (or org-cached-props
12336 (setq org-cached-props
12337 (org-entry-properties pom)))))))
12339 (defun org-global-tags-completion-table (&optional files)
12340 "Return the list of all tags in all agenda buffer/files."
12341 (save-excursion
12342 (org-uniquify
12343 (delq nil
12344 (apply 'append
12345 (mapcar
12346 (lambda (file)
12347 (set-buffer (find-file-noselect file))
12348 (append (org-get-buffer-tags)
12349 (mapcar (lambda (x) (if (stringp (car-safe x))
12350 (list (car-safe x)) nil))
12351 org-tag-alist)))
12352 (if (and files (car files))
12353 files
12354 (org-agenda-files))))))))
12356 (defun org-make-tags-matcher (match)
12357 "Create the TAGS//TODO matcher form for the selection string MATCH."
12358 ;; todo-only is scoped dynamically into this function, and the function
12359 ;; may change it if the matcher asks for it.
12360 (unless match
12361 ;; Get a new match request, with completion
12362 (let ((org-last-tags-completion-table
12363 (org-global-tags-completion-table)))
12364 (setq match (org-completing-read-no-i
12365 "Match: " 'org-tags-completion-function nil nil nil
12366 'org-tags-history))))
12368 ;; Parse the string and create a lisp form
12369 (let ((match0 match)
12370 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
12371 minus tag mm
12372 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
12373 orterms term orlist re-p str-p level-p level-op time-p
12374 prop-p pn pv po cat-p gv rest)
12375 (if (string-match "/+" match)
12376 ;; match contains also a todo-matching request
12377 (progn
12378 (setq tagsmatch (substring match 0 (match-beginning 0))
12379 todomatch (substring match (match-end 0)))
12380 (if (string-match "^!" todomatch)
12381 (setq todo-only t todomatch (substring todomatch 1)))
12382 (if (string-match "^\\s-*$" todomatch)
12383 (setq todomatch nil)))
12384 ;; only matching tags
12385 (setq tagsmatch match todomatch nil))
12387 ;; Make the tags matcher
12388 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
12389 (setq tagsmatcher t)
12390 (setq orterms (org-split-string tagsmatch "|") orlist nil)
12391 (while (setq term (pop orterms))
12392 (while (and (equal (substring term -1) "\\") orterms)
12393 (setq term (concat term "|" (pop orterms)))) ; repair bad split
12394 (while (string-match re term)
12395 (setq rest (substring term (match-end 0))
12396 minus (and (match-end 1)
12397 (equal (match-string 1 term) "-"))
12398 tag (match-string 2 term)
12399 re-p (equal (string-to-char tag) ?{)
12400 level-p (match-end 4)
12401 prop-p (match-end 5)
12402 mm (cond
12403 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
12404 (level-p
12405 (setq level-op (org-op-to-function (match-string 3 term)))
12406 `(,level-op level ,(string-to-number
12407 (match-string 4 term))))
12408 (prop-p
12409 (setq pn (match-string 5 term)
12410 po (match-string 6 term)
12411 pv (match-string 7 term)
12412 cat-p (equal pn "CATEGORY")
12413 re-p (equal (string-to-char pv) ?{)
12414 str-p (equal (string-to-char pv) ?\")
12415 time-p (save-match-data
12416 (string-match "^\"[[<].*[]>]\"$" pv))
12417 pv (if (or re-p str-p) (substring pv 1 -1) pv))
12418 (if time-p (setq pv (org-matcher-time pv)))
12419 (setq po (org-op-to-function po (if time-p 'time str-p)))
12420 (cond
12421 ((equal pn "CATEGORY")
12422 (setq gv '(get-text-property (point) 'org-category)))
12423 ((equal pn "TODO")
12424 (setq gv 'todo))
12426 (setq gv `(org-cached-entry-get nil ,pn))))
12427 (if re-p
12428 (if (eq po 'org<>)
12429 `(not (string-match ,pv (or ,gv "")))
12430 `(string-match ,pv (or ,gv "")))
12431 (if str-p
12432 `(,po (or ,gv "") ,pv)
12433 `(,po (string-to-number (or ,gv ""))
12434 ,(string-to-number pv) ))))
12435 (t `(member ,tag tags-list)))
12436 mm (if minus (list 'not mm) mm)
12437 term rest)
12438 (push mm tagsmatcher))
12439 (push (if (> (length tagsmatcher) 1)
12440 (cons 'and tagsmatcher)
12441 (car tagsmatcher))
12442 orlist)
12443 (setq tagsmatcher nil))
12444 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
12445 (setq tagsmatcher
12446 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
12447 ;; Make the todo matcher
12448 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
12449 (setq todomatcher t)
12450 (setq orterms (org-split-string todomatch "|") orlist nil)
12451 (while (setq term (pop orterms))
12452 (while (string-match re term)
12453 (setq minus (and (match-end 1)
12454 (equal (match-string 1 term) "-"))
12455 kwd (match-string 2 term)
12456 re-p (equal (string-to-char kwd) ?{)
12457 term (substring term (match-end 0))
12458 mm (if re-p
12459 `(string-match ,(substring kwd 1 -1) todo)
12460 (list 'equal 'todo kwd))
12461 mm (if minus (list 'not mm) mm))
12462 (push mm todomatcher))
12463 (push (if (> (length todomatcher) 1)
12464 (cons 'and todomatcher)
12465 (car todomatcher))
12466 orlist)
12467 (setq todomatcher nil))
12468 (setq todomatcher (if (> (length orlist) 1)
12469 (cons 'or orlist) (car orlist))))
12471 ;; Return the string and lisp forms of the matcher
12472 (setq matcher (if todomatcher
12473 (list 'and tagsmatcher todomatcher)
12474 tagsmatcher))
12475 (cons match0 matcher)))
12477 (defun org-op-to-function (op &optional stringp)
12478 "Turn an operator into the appropriate function."
12479 (setq op
12480 (cond
12481 ((equal op "<" ) '(< string< org-time<))
12482 ((equal op ">" ) '(> org-string> org-time>))
12483 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
12484 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
12485 ((member op '("=" "==")) '(= string= org-time=))
12486 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
12487 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
12489 (defun org<> (a b) (not (= a b)))
12490 (defun org-string<= (a b) (or (string= a b) (string< a b)))
12491 (defun org-string>= (a b) (not (string< a b)))
12492 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
12493 (defun org-string<> (a b) (not (string= 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) (> a b)))
12498 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
12499 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
12500 (defun org-2ft (s)
12501 "Convert S to a floating point time.
12502 If S is already a number, just return it. If it is a string, parse
12503 it as a time string and apply `float-time' to it. If S is nil, just return 0."
12504 (cond
12505 ((numberp s) s)
12506 ((stringp s)
12507 (condition-case nil
12508 (float-time (apply 'encode-time (org-parse-time-string s)))
12509 (error 0.)))
12510 (t 0.)))
12512 (defun org-time-today ()
12513 "Time in seconds today at 0:00.
12514 Returns the float number of seconds since the beginning of the
12515 epoch to the beginning of today (00:00)."
12516 (float-time (apply 'encode-time
12517 (append '(0 0 0) (nthcdr 3 (decode-time))))))
12519 (defun org-matcher-time (s)
12520 "Interpret a time comparison value."
12521 (save-match-data
12522 (cond
12523 ((string= s "<now>") (float-time))
12524 ((string= s "<today>") (org-time-today))
12525 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
12526 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
12527 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
12528 (+ (org-time-today)
12529 (* (string-to-number (match-string 1 s))
12530 (cdr (assoc (match-string 2 s)
12531 '(("d" . 86400.0) ("w" . 604800.0)
12532 ("m" . 2678400.0) ("y" . 31557600.0)))))))
12533 (t (org-2ft s)))))
12535 (defun org-match-any-p (re list)
12536 "Does re match any element of list?"
12537 (setq list (mapcar (lambda (x) (string-match re x)) list))
12538 (delq nil list))
12540 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
12541 (defvar org-tags-overlay (make-overlay 1 1))
12542 (org-detach-overlay org-tags-overlay)
12544 (defun org-get-local-tags-at (&optional pos)
12545 "Get a list of tags defined in the current headline."
12546 (org-get-tags-at pos 'local))
12548 (defun org-get-local-tags ()
12549 "Get a list of tags defined in the current headline."
12550 (org-get-tags-at nil 'local))
12552 (defun org-get-tags-at (&optional pos local)
12553 "Get a list of all headline tags applicable at POS.
12554 POS defaults to point. If tags are inherited, the list contains
12555 the targets in the same sequence as the headlines appear, i.e.
12556 the tags of the current headline come last.
12557 When LOCAL is non-nil, only return tags from the current headline,
12558 ignore inherited ones."
12559 (interactive)
12560 (if (and org-trust-scanner-tags
12561 (or (not pos) (equal pos (point)))
12562 (not local))
12563 org-scanner-tags
12564 (let (tags ltags lastpos parent)
12565 (save-excursion
12566 (save-restriction
12567 (widen)
12568 (goto-char (or pos (point)))
12569 (save-match-data
12570 (catch 'done
12571 (condition-case nil
12572 (progn
12573 (org-back-to-heading t)
12574 (while (not (equal lastpos (point)))
12575 (setq lastpos (point))
12576 (when (looking-at
12577 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
12578 (setq ltags (org-split-string
12579 (org-match-string-no-properties 1) ":"))
12580 (when parent
12581 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
12582 (setq tags (append
12583 (if parent
12584 (org-remove-uniherited-tags ltags)
12585 ltags)
12586 tags)))
12587 (or org-use-tag-inheritance (throw 'done t))
12588 (if local (throw 'done t))
12589 (or (org-up-heading-safe) (error nil))
12590 (setq parent t)))
12591 (error nil)))))
12592 (append (org-remove-uniherited-tags org-file-tags) tags)))))
12594 (defun org-add-prop-inherited (s)
12595 (add-text-properties 0 (length s) '(inherited t) s)
12598 (defun org-toggle-tag (tag &optional onoff)
12599 "Toggle the tag TAG for the current line.
12600 If ONOFF is `on' or `off', don't toggle but set to this state."
12601 (let (res current)
12602 (save-excursion
12603 (org-back-to-heading t)
12604 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
12605 (point-at-eol) t)
12606 (progn
12607 (setq current (match-string 1))
12608 (replace-match ""))
12609 (setq current ""))
12610 (setq current (nreverse (org-split-string current ":")))
12611 (cond
12612 ((eq onoff 'on)
12613 (setq res t)
12614 (or (member tag current) (push tag current)))
12615 ((eq onoff 'off)
12616 (or (not (member tag current)) (setq current (delete tag current))))
12617 (t (if (member tag current)
12618 (setq current (delete tag current))
12619 (setq res t)
12620 (push tag current))))
12621 (end-of-line 1)
12622 (if current
12623 (progn
12624 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
12625 (org-set-tags nil t))
12626 (delete-horizontal-space))
12627 (run-hooks 'org-after-tags-change-hook))
12628 res))
12630 (defun org-align-tags-here (to-col)
12631 ;; Assumes that this is a headline
12632 (let ((pos (point)) (col (current-column)) ncol tags-l p)
12633 (beginning-of-line 1)
12634 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12635 (< pos (match-beginning 2)))
12636 (progn
12637 (setq tags-l (- (match-end 2) (match-beginning 2)))
12638 (goto-char (match-beginning 1))
12639 (insert " ")
12640 (delete-region (point) (1+ (match-beginning 2)))
12641 (setq ncol (max (1+ (current-column))
12642 (1+ col)
12643 (if (> to-col 0)
12644 to-col
12645 (- (abs to-col) tags-l))))
12646 (setq p (point))
12647 (insert (make-string (- ncol (current-column)) ?\ ))
12648 (setq ncol (current-column))
12649 (when indent-tabs-mode (tabify p (point-at-eol)))
12650 (org-move-to-column (min ncol col) t))
12651 (goto-char pos))))
12653 (defun org-set-tags-command (&optional arg just-align)
12654 "Call the set-tags command for the current entry."
12655 (interactive "P")
12656 (if (org-on-heading-p)
12657 (org-set-tags arg just-align)
12658 (save-excursion
12659 (org-back-to-heading t)
12660 (org-set-tags arg just-align))))
12662 (defun org-set-tags-to (data)
12663 "Set the tags of the current entry to DATA, replacing the current tags.
12664 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
12665 If DATA is nil or the empty string, any tags will be removed."
12666 (interactive "sTags: ")
12667 (setq data
12668 (cond
12669 ((eq data nil) "")
12670 ((equal data "") "")
12671 ((stringp data)
12672 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
12673 ":"))
12674 ((listp data)
12675 (concat ":" (mapconcat 'identity data ":") ":"))
12676 (t nil)))
12677 (when data
12678 (save-excursion
12679 (org-back-to-heading t)
12680 (when (looking-at org-complex-heading-regexp)
12681 (if (match-end 5)
12682 (progn
12683 (goto-char (match-beginning 5))
12684 (insert data)
12685 (delete-region (point) (point-at-eol))
12686 (org-set-tags nil 'align))
12687 (goto-char (point-at-eol))
12688 (insert " " data)
12689 (org-set-tags nil 'align)))
12690 (beginning-of-line 1)
12691 (if (looking-at ".*?\\([ \t]+\\)$")
12692 (delete-region (match-beginning 1) (match-end 1))))))
12694 (defun org-align-all-tags ()
12695 "Align the tags i all headings."
12696 (interactive)
12697 (save-excursion
12698 (or (ignore-errors (org-back-to-heading t))
12699 (outline-next-heading))
12700 (if (org-on-heading-p)
12701 (org-set-tags t)
12702 (message "No headings"))))
12704 (defun org-set-tags (&optional arg just-align)
12705 "Set the tags for the current headline.
12706 With prefix ARG, realign all tags in headings in the current buffer."
12707 (interactive "P")
12708 (let* ((re (concat "^" outline-regexp))
12709 (current (org-get-tags-string))
12710 (col (current-column))
12711 (org-setting-tags t)
12712 table current-tags inherited-tags ; computed below when needed
12713 tags p0 c0 c1 rpl)
12714 (if arg
12715 (save-excursion
12716 (goto-char (point-min))
12717 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
12718 (while (re-search-forward re nil t)
12719 (org-set-tags nil t)
12720 (end-of-line 1)))
12721 (message "All tags realigned to column %d" org-tags-column))
12722 (if just-align
12723 (setq tags current)
12724 ;; Get a new set of tags from the user
12725 (save-excursion
12726 (setq table (append org-tag-persistent-alist
12727 (or org-tag-alist (org-get-buffer-tags))
12728 (and org-complete-tags-always-offer-all-agenda-tags
12729 (org-global-tags-completion-table (org-agenda-files))))
12730 org-last-tags-completion-table table
12731 current-tags (org-split-string current ":")
12732 inherited-tags (nreverse
12733 (nthcdr (length current-tags)
12734 (nreverse (org-get-tags-at))))
12735 tags
12736 (if (or (eq t org-use-fast-tag-selection)
12737 (and org-use-fast-tag-selection
12738 (delq nil (mapcar 'cdr table))))
12739 (org-fast-tag-selection
12740 current-tags inherited-tags table
12741 (if org-fast-tag-selection-include-todo org-todo-key-alist))
12742 (let ((org-add-colon-after-tag-completion t))
12743 (org-trim
12744 (org-without-partial-completion
12745 (org-icompleting-read "Tags: " 'org-tags-completion-function
12746 nil nil current 'org-tags-history)))))))
12747 (while (string-match "[-+&]+" tags)
12748 ;; No boolean logic, just a list
12749 (setq tags (replace-match ":" t t tags))))
12751 (if org-tags-sort-function
12752 (setq tags (mapconcat 'identity
12753 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
12754 org-tags-sort-function) ":")))
12756 (if (string-match "\\`[\t ]*\\'" tags)
12757 (setq tags "")
12758 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
12759 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
12761 ;; Insert new tags at the correct column
12762 (beginning-of-line 1)
12763 (cond
12764 ((and (equal current "") (equal tags "")))
12765 ((re-search-forward
12766 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
12767 (point-at-eol) t)
12768 (if (equal tags "")
12769 (setq rpl "")
12770 (goto-char (match-beginning 0))
12771 (setq c0 (current-column) p0 (if (equal (char-before) ?*)
12772 (1+ (point)) (point))
12773 c1 (max (1+ c0) (if (> org-tags-column 0)
12774 org-tags-column
12775 (- (- org-tags-column) (length tags))))
12776 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
12777 (replace-match rpl t t)
12778 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
12779 tags)
12780 (t (error "Tags alignment failed")))
12781 (org-move-to-column col)
12782 (unless just-align
12783 (run-hooks 'org-after-tags-change-hook)))))
12785 (defun org-change-tag-in-region (beg end tag off)
12786 "Add or remove TAG for each entry in the region.
12787 This works in the agenda, and also in an org-mode buffer."
12788 (interactive
12789 (list (region-beginning) (region-end)
12790 (let ((org-last-tags-completion-table
12791 (if (org-mode-p)
12792 (org-get-buffer-tags)
12793 (org-global-tags-completion-table))))
12794 (org-icompleting-read
12795 "Tag: " 'org-tags-completion-function nil nil nil
12796 'org-tags-history))
12797 (progn
12798 (message "[s]et or [r]emove? ")
12799 (equal (read-char-exclusive) ?r))))
12800 (if (fboundp 'deactivate-mark) (deactivate-mark))
12801 (let ((agendap (equal major-mode 'org-agenda-mode))
12802 l1 l2 m buf pos newhead (cnt 0))
12803 (goto-char end)
12804 (setq l2 (1- (org-current-line)))
12805 (goto-char beg)
12806 (setq l1 (org-current-line))
12807 (loop for l from l1 to l2 do
12808 (org-goto-line l)
12809 (setq m (get-text-property (point) 'org-hd-marker))
12810 (when (or (and (org-mode-p) (org-on-heading-p))
12811 (and agendap m))
12812 (setq buf (if agendap (marker-buffer m) (current-buffer))
12813 pos (if agendap m (point)))
12814 (with-current-buffer buf
12815 (save-excursion
12816 (save-restriction
12817 (goto-char pos)
12818 (setq cnt (1+ cnt))
12819 (org-toggle-tag tag (if off 'off 'on))
12820 (setq newhead (org-get-heading)))))
12821 (and agendap (org-agenda-change-all-lines newhead m))))
12822 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
12824 (defun org-tags-completion-function (string predicate &optional flag)
12825 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
12826 (confirm (lambda (x) (stringp (car x)))))
12827 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
12828 (setq s1 (match-string 1 string)
12829 s2 (match-string 2 string))
12830 (setq s1 "" s2 string))
12831 (cond
12832 ((eq flag nil)
12833 ;; try completion
12834 (setq rtn (try-completion s2 ctable confirm))
12835 (if (stringp rtn)
12836 (setq rtn
12837 (concat s1 s2 (substring rtn (length s2))
12838 (if (and org-add-colon-after-tag-completion
12839 (assoc rtn ctable))
12840 ":" ""))))
12841 rtn)
12842 ((eq flag t)
12843 ;; all-completions
12844 (all-completions s2 ctable confirm)
12846 ((eq flag 'lambda)
12847 ;; exact match?
12848 (assoc s2 ctable)))
12851 (defun org-fast-tag-insert (kwd tags face &optional end)
12852 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
12853 (insert (format "%-12s" (concat kwd ":"))
12854 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
12855 (or end "")))
12857 (defun org-fast-tag-show-exit (flag)
12858 (save-excursion
12859 (org-goto-line 3)
12860 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
12861 (replace-match ""))
12862 (when flag
12863 (end-of-line 1)
12864 (org-move-to-column (- (window-width) 19) t)
12865 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
12867 (defun org-set-current-tags-overlay (current prefix)
12868 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
12869 (if (featurep 'xemacs)
12870 (org-overlay-display org-tags-overlay (concat prefix s)
12871 'secondary-selection)
12872 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
12873 (org-overlay-display org-tags-overlay (concat prefix s)))))
12875 (defvar org-last-tag-selection-key nil)
12876 (defun org-fast-tag-selection (current inherited table &optional todo-table)
12877 "Fast tag selection with single keys.
12878 CURRENT is the current list of tags in the headline, INHERITED is the
12879 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
12880 possibly with grouping information. TODO-TABLE is a similar table with
12881 TODO keywords, should these have keys assigned to them.
12882 If the keys are nil, a-z are automatically assigned.
12883 Returns the new tags string, or nil to not change the current settings."
12884 (let* ((fulltable (append table todo-table))
12885 (maxlen (apply 'max (mapcar
12886 (lambda (x)
12887 (if (stringp (car x)) (string-width (car x)) 0))
12888 fulltable)))
12889 (buf (current-buffer))
12890 (expert (eq org-fast-tag-selection-single-key 'expert))
12891 (buffer-tags nil)
12892 (fwidth (+ maxlen 3 1 3))
12893 (ncol (/ (- (window-width) 4) fwidth))
12894 (i-face 'org-done)
12895 (c-face 'org-todo)
12896 tg cnt e c char c1 c2 ntable tbl rtn
12897 ov-start ov-end ov-prefix
12898 (exit-after-next org-fast-tag-selection-single-key)
12899 (done-keywords org-done-keywords)
12900 groups ingroup)
12901 (save-excursion
12902 (beginning-of-line 1)
12903 (if (looking-at
12904 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12905 (setq ov-start (match-beginning 1)
12906 ov-end (match-end 1)
12907 ov-prefix "")
12908 (setq ov-start (1- (point-at-eol))
12909 ov-end (1+ ov-start))
12910 (skip-chars-forward "^\n\r")
12911 (setq ov-prefix
12912 (concat
12913 (buffer-substring (1- (point)) (point))
12914 (if (> (current-column) org-tags-column)
12916 (make-string (- org-tags-column (current-column)) ?\ ))))))
12917 (move-overlay org-tags-overlay ov-start ov-end)
12918 (save-window-excursion
12919 (if expert
12920 (set-buffer (get-buffer-create " *Org tags*"))
12921 (delete-other-windows)
12922 (split-window-vertically)
12923 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
12924 (erase-buffer)
12925 (org-set-local 'org-done-keywords done-keywords)
12926 (org-fast-tag-insert "Inherited" inherited i-face "\n")
12927 (org-fast-tag-insert "Current" current c-face "\n\n")
12928 (org-fast-tag-show-exit exit-after-next)
12929 (org-set-current-tags-overlay current ov-prefix)
12930 (setq tbl fulltable char ?a cnt 0)
12931 (while (setq e (pop tbl))
12932 (cond
12933 ((equal (car e) :startgroup)
12934 (push '() groups) (setq ingroup t)
12935 (when (not (= cnt 0))
12936 (setq cnt 0)
12937 (insert "\n"))
12938 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
12939 ((equal (car e) :endgroup)
12940 (setq ingroup nil cnt 0)
12941 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
12942 ((equal e '(:newline))
12943 (when (not (= cnt 0))
12944 (setq cnt 0)
12945 (insert "\n")
12946 (setq e (car tbl))
12947 (while (equal (car tbl) '(:newline))
12948 (insert "\n")
12949 (setq tbl (cdr tbl)))))
12951 (setq tg (copy-sequence (car e)) c2 nil)
12952 (if (cdr e)
12953 (setq c (cdr e))
12954 ;; automatically assign a character.
12955 (setq c1 (string-to-char
12956 (downcase (substring
12957 tg (if (= (string-to-char tg) ?@) 1 0)))))
12958 (if (or (rassoc c1 ntable) (rassoc c1 table))
12959 (while (or (rassoc char ntable) (rassoc char table))
12960 (setq char (1+ char)))
12961 (setq c2 c1))
12962 (setq c (or c2 char)))
12963 (if ingroup (push tg (car groups)))
12964 (setq tg (org-add-props tg nil 'face
12965 (cond
12966 ((not (assoc tg table))
12967 (org-get-todo-face tg))
12968 ((member tg current) c-face)
12969 ((member tg inherited) i-face)
12970 (t nil))))
12971 (if (and (= cnt 0) (not ingroup)) (insert " "))
12972 (insert "[" c "] " tg (make-string
12973 (- fwidth 4 (length tg)) ?\ ))
12974 (push (cons tg c) ntable)
12975 (when (= (setq cnt (1+ cnt)) ncol)
12976 (insert "\n")
12977 (if ingroup (insert " "))
12978 (setq cnt 0)))))
12979 (setq ntable (nreverse ntable))
12980 (insert "\n")
12981 (goto-char (point-min))
12982 (if (not expert) (org-fit-window-to-buffer))
12983 (setq rtn
12984 (catch 'exit
12985 (while t
12986 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
12987 (if (not groups) "no " "")
12988 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
12989 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12990 (setq org-last-tag-selection-key c)
12991 (cond
12992 ((= c ?\r) (throw 'exit t))
12993 ((= c ?!)
12994 (setq groups (not groups))
12995 (goto-char (point-min))
12996 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
12997 ((= c ?\C-c)
12998 (if (not expert)
12999 (org-fast-tag-show-exit
13000 (setq exit-after-next (not exit-after-next)))
13001 (setq expert nil)
13002 (delete-other-windows)
13003 (split-window-vertically)
13004 (org-switch-to-buffer-other-window " *Org tags*")
13005 (org-fit-window-to-buffer)))
13006 ((or (= c ?\C-g)
13007 (and (= c ?q) (not (rassoc c ntable))))
13008 (org-detach-overlay org-tags-overlay)
13009 (setq quit-flag t))
13010 ((= c ?\ )
13011 (setq current nil)
13012 (if exit-after-next (setq exit-after-next 'now)))
13013 ((= c ?\t)
13014 (condition-case nil
13015 (setq tg (org-icompleting-read
13016 "Tag: "
13017 (or buffer-tags
13018 (with-current-buffer buf
13019 (org-get-buffer-tags)))))
13020 (quit (setq tg "")))
13021 (when (string-match "\\S-" tg)
13022 (add-to-list 'buffer-tags (list tg))
13023 (if (member tg current)
13024 (setq current (delete tg current))
13025 (push tg current)))
13026 (if exit-after-next (setq exit-after-next 'now)))
13027 ((setq e (rassoc c todo-table) tg (car e))
13028 (with-current-buffer buf
13029 (save-excursion (org-todo tg)))
13030 (if exit-after-next (setq exit-after-next 'now)))
13031 ((setq e (rassoc c ntable) tg (car e))
13032 (if (member tg current)
13033 (setq current (delete tg current))
13034 (loop for g in groups do
13035 (if (member tg g)
13036 (mapc (lambda (x)
13037 (setq current (delete x current)))
13038 g)))
13039 (push tg current))
13040 (if exit-after-next (setq exit-after-next 'now))))
13042 ;; Create a sorted list
13043 (setq current
13044 (sort current
13045 (lambda (a b)
13046 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13047 (if (eq exit-after-next 'now) (throw 'exit t))
13048 (goto-char (point-min))
13049 (beginning-of-line 2)
13050 (delete-region (point) (point-at-eol))
13051 (org-fast-tag-insert "Current" current c-face)
13052 (org-set-current-tags-overlay current ov-prefix)
13053 (while (re-search-forward
13054 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
13055 (setq tg (match-string 1))
13056 (add-text-properties
13057 (match-beginning 1) (match-end 1)
13058 (list 'face
13059 (cond
13060 ((member tg current) c-face)
13061 ((member tg inherited) i-face)
13062 (t (get-text-property (match-beginning 1) 'face))))))
13063 (goto-char (point-min)))))
13064 (org-detach-overlay org-tags-overlay)
13065 (if rtn
13066 (mapconcat 'identity current ":")
13067 nil))))
13069 (defun org-get-tags-string ()
13070 "Get the TAGS string in the current headline."
13071 (unless (org-on-heading-p t)
13072 (error "Not on a heading"))
13073 (save-excursion
13074 (beginning-of-line 1)
13075 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13076 (org-match-string-no-properties 1)
13077 "")))
13079 (defun org-get-tags ()
13080 "Get the list of tags specified in the current headline."
13081 (org-split-string (org-get-tags-string) ":"))
13083 (defun org-get-buffer-tags ()
13084 "Get a table of all tags used in the buffer, for completion."
13085 (let (tags)
13086 (save-excursion
13087 (goto-char (point-min))
13088 (while (re-search-forward
13089 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
13090 (when (equal (char-after (point-at-bol 0)) ?*)
13091 (mapc (lambda (x) (add-to-list 'tags x))
13092 (org-split-string (org-match-string-no-properties 1) ":")))))
13093 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13094 (mapcar 'list tags)))
13096 ;;;; The mapping API
13098 ;;;###autoload
13099 (defun org-map-entries (func &optional match scope &rest skip)
13100 "Call FUNC at each headline selected by MATCH in SCOPE.
13102 FUNC is a function or a lisp form. The function will be called without
13103 arguments, with the cursor positioned at the beginning of the headline.
13104 The return values of all calls to the function will be collected and
13105 returned as a list.
13107 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13108 does not need to preserve point. After evaluation, the cursor will be
13109 moved to the end of the line (presumably of the headline of the
13110 processed entry) and search continues from there. Under some
13111 circumstances, this may not produce the wanted results. For example,
13112 if you have removed (e.g. archived) the current (sub)tree it could
13113 mean that the next entry will be skipped entirely. In such cases, you
13114 can specify the position from where search should continue by making
13115 FUNC set the variable `org-map-continue-from' to the desired buffer
13116 position.
13118 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13119 Only headlines that are matched by this query will be considered during
13120 the iteration. When MATCH is nil or t, all headlines will be
13121 visited by the iteration.
13123 SCOPE determines the scope of this command. It can be any of:
13125 nil The current buffer, respecting the restriction if any
13126 tree The subtree started with the entry at point
13127 file The current buffer, without restriction
13128 file-with-archives
13129 The current buffer, and any archives associated with it
13130 agenda All agenda files
13131 agenda-with-archives
13132 All agenda files with any archive files associated with them
13133 \(file1 file2 ...)
13134 If this is a list, all files in the list will be scanned
13136 The remaining args are treated as settings for the skipping facilities of
13137 the scanner. The following items can be given here:
13139 archive skip trees with the archive tag.
13140 comment skip trees with the COMMENT keyword
13141 function or Emacs Lisp form:
13142 will be used as value for `org-agenda-skip-function', so whenever
13143 the function returns t, FUNC will not be called for that
13144 entry and search will continue from the point where the
13145 function leaves it.
13147 If your function needs to retrieve the tags including inherited tags
13148 at the *current* entry, you can use the value of the variable
13149 `org-scanner-tags' which will be much faster than getting the value
13150 with `org-get-tags-at'. If your function gets properties with
13151 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13152 to t around the call to `org-entry-properties' to get the same speedup.
13153 Note that if your function moves around to retrieve tags and properties at
13154 a *different* entry, you cannot use these techniques."
13155 (let* ((org-agenda-archives-mode nil) ; just to make sure
13156 (org-agenda-skip-archived-trees (memq 'archive skip))
13157 (org-agenda-skip-comment-trees (memq 'comment skip))
13158 (org-agenda-skip-function
13159 (car (org-delete-all '(comment archive) skip)))
13160 (org-tags-match-list-sublevels t)
13161 matcher file res
13162 org-todo-keywords-for-agenda
13163 org-done-keywords-for-agenda
13164 org-todo-keyword-alist-for-agenda
13165 org-drawers-for-agenda
13166 org-tag-alist-for-agenda)
13168 (cond
13169 ((eq match t) (setq matcher t))
13170 ((eq match nil) (setq matcher t))
13171 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13173 (save-excursion
13174 (save-restriction
13175 (when (eq scope 'tree)
13176 (org-back-to-heading t)
13177 (org-narrow-to-subtree)
13178 (setq scope nil))
13180 (if (not scope)
13181 (progn
13182 (org-prepare-agenda-buffers
13183 (list (buffer-file-name (current-buffer))))
13184 (setq res (org-scan-tags func matcher)))
13185 ;; Get the right scope
13186 (cond
13187 ((and scope (listp scope) (symbolp (car scope)))
13188 (setq scope (eval scope)))
13189 ((eq scope 'agenda)
13190 (setq scope (org-agenda-files t)))
13191 ((eq scope 'agenda-with-archives)
13192 (setq scope (org-agenda-files t))
13193 (setq scope (org-add-archive-files scope)))
13194 ((eq scope 'file)
13195 (setq scope (list (buffer-file-name))))
13196 ((eq scope 'file-with-archives)
13197 (setq scope (org-add-archive-files (list (buffer-file-name))))))
13198 (org-prepare-agenda-buffers scope)
13199 (while (setq file (pop scope))
13200 (with-current-buffer (org-find-base-buffer-visiting file)
13201 (save-excursion
13202 (save-restriction
13203 (widen)
13204 (goto-char (point-min))
13205 (setq res (append res (org-scan-tags func matcher))))))))))
13206 res))
13208 ;;;; Properties
13210 ;;; Setting and retrieving properties
13212 (defconst org-special-properties
13213 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
13214 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED")
13215 "The special properties valid in Org-mode.
13217 These are properties that are not defined in the property drawer,
13218 but in some other way.")
13220 (defconst org-default-properties
13221 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
13222 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
13223 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
13224 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
13225 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
13226 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
13227 "Some properties that are used by Org-mode for various purposes.
13228 Being in this list makes sure that they are offered for completion.")
13230 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
13231 "Regular expression matching the first line of a property drawer.")
13233 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
13234 "Regular expression matching the last line of a property drawer.")
13236 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
13237 "Regular expression matching the first line of a property drawer.")
13239 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
13240 "Regular expression matching the first line of a property drawer.")
13242 (defconst org-property-drawer-re
13243 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
13244 org-property-end-re "\\)\n?")
13245 "Matches an entire property drawer.")
13247 (defconst org-clock-drawer-re
13248 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
13249 org-property-end-re "\\)\n?")
13250 "Matches an entire clock drawer.")
13252 (defun org-property-action ()
13253 "Do an action on properties."
13254 (interactive)
13255 (let (c)
13256 (org-at-property-p)
13257 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
13258 (setq c (read-char-exclusive))
13259 (cond
13260 ((equal c ?s)
13261 (call-interactively 'org-set-property))
13262 ((equal c ?d)
13263 (call-interactively 'org-delete-property))
13264 ((equal c ?D)
13265 (call-interactively 'org-delete-property-globally))
13266 ((equal c ?c)
13267 (call-interactively 'org-compute-property-at-point))
13268 (t (error "No such property action %c" c)))))
13270 (defun org-set-effort (&optional value)
13271 "Set the effort property of the current entry.
13272 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
13273 allowed value."
13274 (interactive "P")
13275 (if (equal value 0) (setq value 10))
13276 (let* ((completion-ignore-case t)
13277 (prop org-effort-property)
13278 (cur (org-entry-get nil prop))
13279 (allowed (org-property-get-allowed-values nil prop 'table))
13280 (existing (mapcar 'list (org-property-values prop)))
13282 (val (cond
13283 ((stringp value) value)
13284 ((and allowed (integerp value))
13285 (or (car (nth (1- value) allowed))
13286 (car (org-last allowed))))
13287 (allowed
13288 (message "Select 1-9,0, [RET%s]: %s"
13289 (if cur (concat "=" cur) "")
13290 (mapconcat 'car allowed " "))
13291 (setq rpl (read-char-exclusive))
13292 (if (equal rpl ?\r)
13294 (setq rpl (- rpl ?0))
13295 (if (equal rpl 0) (setq rpl 10))
13296 (if (and (> rpl 0) (<= rpl (length allowed)))
13297 (car (nth (1- rpl) allowed))
13298 (org-completing-read "Effort: " allowed nil))))
13300 (let (org-completion-use-ido org-completion-use-iswitchb)
13301 (org-completing-read
13302 (concat "Effort " (if (and cur (string-match "\\S-" cur))
13303 (concat "[" cur "]") "")
13304 ": ")
13305 existing nil nil "" nil cur))))))
13306 (unless (equal (org-entry-get nil prop) val)
13307 (org-entry-put nil prop val))
13308 (message "%s is now %s" prop val)))
13310 (defun org-at-property-p ()
13311 "Is cursor inside a property drawer?"
13312 (save-excursion
13313 (beginning-of-line 1)
13314 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
13315 (save-match-data ;; Used by calling procedures
13316 (let ((p (point))
13317 (range (unless (org-before-first-heading-p)
13318 (org-get-property-block))))
13319 (and range (<= (car range) p) (< p (cdr range))))))))
13321 (defun org-get-property-block (&optional beg end force)
13322 "Return the (beg . end) range of the body of the property drawer.
13323 BEG and END can be beginning and end of subtree, if not given
13324 they will be found.
13325 If the drawer does not exist and FORCE is non-nil, create the drawer."
13326 (catch 'exit
13327 (save-excursion
13328 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
13329 (end (or end (progn (outline-next-heading) (point)))))
13330 (goto-char beg)
13331 (if (re-search-forward org-property-start-re end t)
13332 (setq beg (1+ (match-end 0)))
13333 (if force
13334 (save-excursion
13335 (org-insert-property-drawer)
13336 (setq end (progn (outline-next-heading) (point))))
13337 (throw 'exit nil))
13338 (goto-char beg)
13339 (if (re-search-forward org-property-start-re end t)
13340 (setq beg (1+ (match-end 0)))))
13341 (if (re-search-forward org-property-end-re end t)
13342 (setq end (match-beginning 0))
13343 (or force (throw 'exit nil))
13344 (goto-char beg)
13345 (setq end beg)
13346 (org-indent-line-function)
13347 (insert ":END:\n"))
13348 (cons beg end)))))
13350 (defun org-entry-properties (&optional pom which specific)
13351 "Get all properties of the entry at point-or-marker POM.
13352 This includes the TODO keyword, the tags, time strings for deadline,
13353 scheduled, and clocking, and any additional properties defined in the
13354 entry. The return value is an alist, keys may occur multiple times
13355 if the property key was used several times.
13356 POM may also be nil, in which case the current entry is used.
13357 If WHICH is nil or `all', get all properties. If WHICH is
13358 `special' or `standard', only get that subclass. If WHICH
13359 is a string only get exactly this property. Specific can be a string, the
13360 specific property we are interested in. Specifying it can speed
13361 things up because then unnecessary parsing is avoided."
13362 (setq which (or which 'all))
13363 (org-with-point-at pom
13364 (let ((clockstr (substring org-clock-string 0 -1))
13365 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
13366 (case-fold-search nil)
13367 beg end range props sum-props key key1 value string clocksum)
13368 (save-excursion
13369 (when (condition-case nil
13370 (and (org-mode-p) (org-back-to-heading t))
13371 (error nil))
13372 (setq beg (point))
13373 (setq sum-props (get-text-property (point) 'org-summaries))
13374 (setq clocksum (get-text-property (point) :org-clock-minutes))
13375 (outline-next-heading)
13376 (setq end (point))
13377 (when (memq which '(all special))
13378 ;; Get the special properties, like TODO and tags
13379 (goto-char beg)
13380 (when (and (or (not specific) (string= specific "TODO"))
13381 (looking-at org-todo-line-regexp) (match-end 2))
13382 (push (cons "TODO" (org-match-string-no-properties 2)) props))
13383 (when (and (or (not specific) (string= specific "PRIORITY"))
13384 (looking-at org-priority-regexp))
13385 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
13386 (when (and (or (not specific) (string= specific "TAGS"))
13387 (setq value (org-get-tags-string))
13388 (string-match "\\S-" value))
13389 (push (cons "TAGS" value) props))
13390 (when (and (or (not specific) (string= specific "ALLTAGS"))
13391 (setq value (org-get-tags-at)))
13392 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
13393 ":"))
13394 props))
13395 (when (or (not specific) (string= specific "BLOCKED"))
13396 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
13397 (when (or (not specific)
13398 (member specific
13399 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
13400 "TIMESTAMP" "TIMESTAMP_IA")))
13401 (while (re-search-forward org-maybe-keyword-time-regexp end t)
13402 (setq key (if (match-end 1)
13403 (substring (org-match-string-no-properties 1)
13404 0 -1))
13405 string (if (equal key clockstr)
13406 (org-no-properties
13407 (org-trim
13408 (buffer-substring
13409 (match-beginning 3) (goto-char
13410 (point-at-eol)))))
13411 (substring (org-match-string-no-properties 3)
13412 1 -1)))
13413 ;; Get the correct property name from the key. This is
13414 ;; necessary if the user has configured time keywords.
13415 (setq key1 (concat key ":"))
13416 (cond
13417 ((not key)
13418 (setq key
13419 (if (= (char-after (match-beginning 3)) ?\[)
13420 "TIMESTAMP_IA" "TIMESTAMP")))
13421 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
13422 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
13423 ((equal key1 org-closed-string) (setq key "CLOSED"))
13424 ((equal key1 org-clock-string) (setq key "CLOCK")))
13425 (when (or (equal key "CLOCK") (not (assoc key props)))
13426 (push (cons key string) props))))
13429 (when (memq which '(all standard))
13430 ;; Get the standard properties, like :PROP: ...
13431 (setq range (org-get-property-block beg end))
13432 (when range
13433 (goto-char (car range))
13434 (while (re-search-forward
13435 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
13436 (cdr range) t)
13437 (setq key (org-match-string-no-properties 1)
13438 value (org-trim (or (org-match-string-no-properties 2) "")))
13439 (unless (member key excluded)
13440 (push (cons key (or value "")) props)))))
13441 (if clocksum
13442 (push (cons "CLOCKSUM"
13443 (org-columns-number-to-string (/ (float clocksum) 60.)
13444 'add_times))
13445 props))
13446 (unless (assoc "CATEGORY" props)
13447 (setq value (or (org-get-category)
13448 (progn (org-refresh-category-properties)
13449 (org-get-category))))
13450 (push (cons "CATEGORY" value) props))
13451 (append sum-props (nreverse props)))))))
13453 (defun org-entry-get (pom property &optional inherit literal-nil)
13454 "Get value of PROPERTY for entry at point-or-marker POM.
13455 If INHERIT is non-nil and the entry does not have the property,
13456 then also check higher levels of the hierarchy.
13457 If INHERIT is the symbol `selective', use inheritance only if the setting
13458 in `org-use-property-inheritance' selects PROPERTY for inheritance.
13459 If the property is present but empty, the return value is the empty string.
13460 If the property is not present at all, nil is returned.
13462 If LITERAL-NIL is set, return the string value \"nil\" as a string,
13463 do not interpret it as the list atom nil. This is used for inheritance
13464 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
13465 (org-with-point-at pom
13466 (if (and inherit (if (eq inherit 'selective)
13467 (org-property-inherit-p property)
13469 (org-entry-get-with-inheritance property literal-nil)
13470 (if (member property org-special-properties)
13471 ;; We need a special property. Use `org-entry-properties' to
13472 ;; retrieve it, but specify the wanted property
13473 (cdr (assoc property (org-entry-properties nil 'special property)))
13474 (let ((range (org-get-property-block)))
13475 (if (and range
13476 (goto-char (car range))
13477 (re-search-forward
13478 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
13479 (cdr range) t))
13480 ;; Found the property, return it.
13481 (if (match-end 1)
13482 (if literal-nil
13483 (org-match-string-no-properties 1)
13484 (org-not-nil (org-match-string-no-properties 1)))
13485 "")))))))
13487 (defun org-property-or-variable-value (var &optional inherit)
13488 "Check if there is a property fixing the value of VAR.
13489 If yes, return this value. If not, return the current value of the variable."
13490 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
13491 (if (and prop (stringp prop) (string-match "\\S-" prop))
13492 (read prop)
13493 (symbol-value var))))
13495 (defun org-entry-delete (pom property)
13496 "Delete the property PROPERTY from entry at point-or-marker POM."
13497 (org-with-point-at pom
13498 (if (member property org-special-properties)
13499 nil ; cannot delete these properties.
13500 (let ((range (org-get-property-block)))
13501 (if (and range
13502 (goto-char (car range))
13503 (re-search-forward
13504 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
13505 (cdr range) t))
13506 (progn
13507 (delete-region (match-beginning 0) (1+ (point-at-eol)))
13509 nil)))))
13511 ;; Multi-values properties are properties that contain multiple values
13512 ;; These values are assumed to be single words, separated by whitespace.
13513 (defun org-entry-add-to-multivalued-property (pom property value)
13514 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
13515 (let* ((old (org-entry-get pom property))
13516 (values (and old (org-split-string old "[ \t]"))))
13517 (setq value (org-entry-protect-space value))
13518 (unless (member value values)
13519 (setq values (cons value values))
13520 (org-entry-put pom property
13521 (mapconcat 'identity values " ")))))
13523 (defun org-entry-remove-from-multivalued-property (pom property value)
13524 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
13525 (let* ((old (org-entry-get pom property))
13526 (values (and old (org-split-string old "[ \t]"))))
13527 (setq value (org-entry-protect-space value))
13528 (when (member value values)
13529 (setq values (delete value values))
13530 (org-entry-put pom property
13531 (mapconcat 'identity values " ")))))
13533 (defun org-entry-member-in-multivalued-property (pom property value)
13534 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
13535 (let* ((old (org-entry-get pom property))
13536 (values (and old (org-split-string old "[ \t]"))))
13537 (setq value (org-entry-protect-space value))
13538 (member value values)))
13540 (defun org-entry-get-multivalued-property (pom property)
13541 "Return a list of values in a multivalued property."
13542 (let* ((value (org-entry-get pom property))
13543 (values (and value (org-split-string value "[ \t]"))))
13544 (mapcar 'org-entry-restore-space values)))
13546 (defun org-entry-put-multivalued-property (pom property &rest values)
13547 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
13548 VALUES should be a list of strings. Spaces will be protected."
13549 (org-entry-put pom property
13550 (mapconcat 'org-entry-protect-space values " "))
13551 (let* ((value (org-entry-get pom property))
13552 (values (and value (org-split-string value "[ \t]"))))
13553 (mapcar 'org-entry-restore-space values)))
13555 (defun org-entry-protect-space (s)
13556 "Protect spaces and newline in string S."
13557 (while (string-match " " s)
13558 (setq s (replace-match "%20" t t s)))
13559 (while (string-match "\n" s)
13560 (setq s (replace-match "%0A" t t s)))
13563 (defun org-entry-restore-space (s)
13564 "Restore spaces and newline in string S."
13565 (while (string-match "%20" s)
13566 (setq s (replace-match " " t t s)))
13567 (while (string-match "%0A" s)
13568 (setq s (replace-match "\n" t t s)))
13571 (defvar org-entry-property-inherited-from (make-marker)
13572 "Marker pointing to the entry from where a property was inherited.
13573 Each call to `org-entry-get-with-inheritance' will set this marker to the
13574 location of the entry where the inheritance search matched. If there was
13575 no match, the marker will point nowhere.
13576 Note that also `org-entry-get' calls this function, if the INHERIT flag
13577 is set.")
13579 (defun org-entry-get-with-inheritance (property &optional literal-nil)
13580 "Get entry property, and search higher levels if not present.
13581 The search will stop at the first ancestor which has the property defined.
13582 If the value found is \"nil\", return nil to show that the property
13583 should be considered as undefined (this is the meaning of nil here).
13584 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
13585 (move-marker org-entry-property-inherited-from nil)
13586 (let (tmp)
13587 (save-excursion
13588 (save-restriction
13589 (widen)
13590 (catch 'ex
13591 (while t
13592 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
13593 (org-back-to-heading t)
13594 (move-marker org-entry-property-inherited-from (point))
13595 (throw 'ex tmp))
13596 (or (org-up-heading-safe) (throw 'ex nil)))))
13597 (setq tmp (or tmp
13598 (cdr (assoc property org-file-properties))
13599 (cdr (assoc property org-global-properties))
13600 (cdr (assoc property org-global-properties-fixed))))
13601 (if literal-nil tmp (org-not-nil tmp)))))
13603 (defvar org-property-changed-functions nil
13604 "Hook called when the value of a property has changed.
13605 Each hook function should accept two arguments, the name of the property
13606 and the new value.")
13608 (defun org-entry-put (pom property value)
13609 "Set PROPERTY to VALUE for entry at point-or-marker POM."
13610 (org-with-point-at pom
13611 (org-back-to-heading t)
13612 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
13613 range)
13614 (cond
13615 ((equal property "TODO")
13616 (when (and (stringp value) (string-match "\\S-" value)
13617 (not (member value org-todo-keywords-1)))
13618 (error "\"%s\" is not a valid TODO state" value))
13619 (if (or (not value)
13620 (not (string-match "\\S-" value)))
13621 (setq value 'none))
13622 (org-todo value)
13623 (org-set-tags nil 'align))
13624 ((equal property "PRIORITY")
13625 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
13626 (string-to-char value) ?\ ))
13627 (org-set-tags nil 'align))
13628 ((equal property "SCHEDULED")
13629 (if (re-search-forward org-scheduled-time-regexp end t)
13630 (cond
13631 ((eq value 'earlier) (org-timestamp-change -1 'day))
13632 ((eq value 'later) (org-timestamp-change 1 'day))
13633 (t (call-interactively 'org-schedule)))
13634 (call-interactively 'org-schedule)))
13635 ((equal property "DEADLINE")
13636 (if (re-search-forward org-deadline-time-regexp end t)
13637 (cond
13638 ((eq value 'earlier) (org-timestamp-change -1 'day))
13639 ((eq value 'later) (org-timestamp-change 1 'day))
13640 (t (call-interactively 'org-deadline)))
13641 (call-interactively 'org-deadline)))
13642 ((member property org-special-properties)
13643 (error "The %s property can not yet be set with `org-entry-put'"
13644 property))
13645 (t ; a non-special property
13646 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
13647 (setq range (org-get-property-block beg end 'force))
13648 (goto-char (car range))
13649 (if (re-search-forward
13650 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
13651 (progn
13652 (delete-region (match-beginning 1) (match-end 1))
13653 (goto-char (match-beginning 1)))
13654 (goto-char (cdr range))
13655 (insert "\n")
13656 (backward-char 1)
13657 (org-indent-line-function)
13658 (insert ":" property ":"))
13659 (and value (insert " " value))
13660 (org-indent-line-function)))))
13661 (run-hook-with-args 'org-property-changed-functions property value)))
13663 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
13664 "Get all property keys in the current buffer.
13665 With INCLUDE-SPECIALS, also list the special properties that reflect things
13666 like tags and TODO state.
13667 With INCLUDE-DEFAULTS, also include properties that has special meaning
13668 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
13669 With INCLUDE-COLUMNS, also include property names given in COLUMN
13670 formats in the current buffer."
13671 (let (rtn range cfmt s p)
13672 (save-excursion
13673 (save-restriction
13674 (widen)
13675 (goto-char (point-min))
13676 (while (re-search-forward org-property-start-re nil t)
13677 (setq range (org-get-property-block))
13678 (goto-char (car range))
13679 (while (re-search-forward
13680 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
13681 (cdr range) t)
13682 (add-to-list 'rtn (org-match-string-no-properties 1)))
13683 (outline-next-heading))))
13685 (when include-specials
13686 (setq rtn (append org-special-properties rtn)))
13688 (when include-defaults
13689 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
13690 (add-to-list 'rtn org-effort-property))
13692 (when include-columns
13693 (save-excursion
13694 (save-restriction
13695 (widen)
13696 (goto-char (point-min))
13697 (while (re-search-forward
13698 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
13699 nil t)
13700 (setq cfmt (match-string 2) s 0)
13701 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
13702 cfmt s)
13703 (setq s (match-end 0)
13704 p (match-string 1 cfmt))
13705 (unless (or (equal p "ITEM")
13706 (member p org-special-properties))
13707 (add-to-list 'rtn (match-string 1 cfmt))))))))
13709 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
13711 (defun org-property-values (key)
13712 "Return a list of all values of property KEY."
13713 (save-excursion
13714 (save-restriction
13715 (widen)
13716 (goto-char (point-min))
13717 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
13718 values)
13719 (while (re-search-forward re nil t)
13720 (add-to-list 'values (org-trim (match-string 1))))
13721 (delete "" values)))))
13723 (defun org-insert-property-drawer ()
13724 "Insert a property drawer into the current entry."
13725 (interactive)
13726 (org-back-to-heading t)
13727 (looking-at outline-regexp)
13728 (let ((indent (if org-adapt-indentation
13729 (- (match-end 0)(match-beginning 0))
13731 (beg (point))
13732 (re (concat "^[ \t]*" org-keyword-time-regexp))
13733 end hiddenp)
13734 (outline-next-heading)
13735 (setq end (point))
13736 (goto-char beg)
13737 (while (re-search-forward re end t))
13738 (setq hiddenp (org-invisible-p))
13739 (end-of-line 1)
13740 (and (equal (char-after) ?\n) (forward-char 1))
13741 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
13742 (if (member (match-string 1) '("CLOCK:" ":END:"))
13743 ;; just skip this line
13744 (beginning-of-line 2)
13745 ;; Drawer start, find the end
13746 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
13747 (beginning-of-line 1)))
13748 (org-skip-over-state-notes)
13749 (skip-chars-backward " \t\n\r")
13750 (if (eq (char-before) ?*) (forward-char 1))
13751 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
13752 (beginning-of-line 0)
13753 (org-indent-to-column indent)
13754 (beginning-of-line 2)
13755 (org-indent-to-column indent)
13756 (beginning-of-line 0)
13757 (if hiddenp
13758 (save-excursion
13759 (org-back-to-heading t)
13760 (hide-entry))
13761 (org-flag-drawer t))))
13763 (defun org-set-property (property value)
13764 "In the current entry, set PROPERTY to VALUE.
13765 When called interactively, this will prompt for a property name, offering
13766 completion on existing and default properties. And then it will prompt
13767 for a value, offering completion either on allowed values (via an inherited
13768 xxx_ALL property) or on existing values in other instances of this property
13769 in the current file."
13770 (interactive
13771 (let* ((completion-ignore-case t)
13772 (keys (org-buffer-property-keys nil t t))
13773 (prop0 (org-icompleting-read "Property: " (mapcar 'list keys)))
13774 (prop (if (member prop0 keys)
13775 prop0
13776 (or (cdr (assoc (downcase prop0)
13777 (mapcar (lambda (x) (cons (downcase x) x))
13778 keys)))
13779 prop0)))
13780 (cur (org-entry-get nil prop))
13781 (prompt (concat prop " value"
13782 (if (and cur (string-match "\\S-" cur))
13783 (concat " [" cur "]") "") ": "))
13784 (allowed (org-property-get-allowed-values nil prop 'table))
13785 (existing (mapcar 'list (org-property-values prop)))
13786 (val (if allowed
13787 (org-completing-read prompt allowed nil
13788 (not (get-text-property 0 'org-unrestricted
13789 (caar allowed))))
13790 (let (org-completion-use-ido org-completion-use-iswitchb)
13791 (org-completing-read prompt existing nil nil "" nil cur)))))
13792 (list prop (if (equal val "") cur val))))
13793 (unless (equal (org-entry-get nil property) value)
13794 (org-entry-put nil property value)))
13796 (defun org-delete-property (property)
13797 "In the current entry, delete PROPERTY."
13798 (interactive
13799 (let* ((completion-ignore-case t)
13800 (prop (org-icompleting-read "Property: "
13801 (org-entry-properties nil 'standard))))
13802 (list prop)))
13803 (message "Property %s %s" property
13804 (if (org-entry-delete nil property)
13805 "deleted"
13806 "was not present in the entry")))
13808 (defun org-delete-property-globally (property)
13809 "Remove PROPERTY globally, from all entries."
13810 (interactive
13811 (let* ((completion-ignore-case t)
13812 (prop (org-icompleting-read
13813 "Globally remove property: "
13814 (mapcar 'list (org-buffer-property-keys)))))
13815 (list prop)))
13816 (save-excursion
13817 (save-restriction
13818 (widen)
13819 (goto-char (point-min))
13820 (let ((cnt 0))
13821 (while (re-search-forward
13822 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
13823 nil t)
13824 (setq cnt (1+ cnt))
13825 (replace-match ""))
13826 (message "Property \"%s\" removed from %d entries" property cnt)))))
13828 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
13830 (defun org-compute-property-at-point ()
13831 "Compute the property at point.
13832 This looks for an enclosing column format, extracts the operator and
13833 then applies it to the property in the column format's scope."
13834 (interactive)
13835 (unless (org-at-property-p)
13836 (error "Not at a property"))
13837 (let ((prop (org-match-string-no-properties 2)))
13838 (org-columns-get-format-and-top-level)
13839 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
13840 (error "No operator defined for property %s" prop))
13841 (org-columns-compute prop)))
13843 (defvar org-property-allowed-value-functions nil
13844 "Hook for functions supplying allowed values for a specific property.
13845 The functions must take a single argument, the name of the property, and
13846 return a flat list of allowed values. If \":ETC\" is one of
13847 the values, this means that these values are intended as defaults for
13848 completion, but that other values should be allowed too.
13849 The functions must return nil if they are not responsible for this
13850 property.")
13852 (defun org-property-get-allowed-values (pom property &optional table)
13853 "Get allowed values for the property PROPERTY.
13854 When TABLE is non-nil, return an alist that can directly be used for
13855 completion."
13856 (let (vals)
13857 (cond
13858 ((equal property "TODO")
13859 (setq vals (org-with-point-at pom
13860 (append org-todo-keywords-1 '("")))))
13861 ((equal property "PRIORITY")
13862 (let ((n org-lowest-priority))
13863 (while (>= n org-highest-priority)
13864 (push (char-to-string n) vals)
13865 (setq n (1- n)))))
13866 ((member property org-special-properties))
13867 ((setq vals (run-hook-with-args-until-success
13868 'org-property-allowed-value-functions property)))
13870 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
13871 (when (and vals (string-match "\\S-" vals))
13872 (setq vals (car (read-from-string (concat "(" vals ")"))))
13873 (setq vals (mapcar (lambda (x)
13874 (cond ((stringp x) x)
13875 ((numberp x) (number-to-string x))
13876 ((symbolp x) (symbol-name x))
13877 (t "???")))
13878 vals)))))
13879 (when (member ":ETC" vals)
13880 (setq vals (remove ":ETC" vals))
13881 (org-add-props (car vals) '(org-unrestricted t)))
13882 (if table (mapcar 'list vals) vals)))
13884 (defun org-property-previous-allowed-value (&optional previous)
13885 "Switch to the next allowed value for this property."
13886 (interactive)
13887 (org-property-next-allowed-value t))
13889 (defun org-property-next-allowed-value (&optional previous)
13890 "Switch to the next allowed value for this property."
13891 (interactive)
13892 (unless (org-at-property-p)
13893 (error "Not at a property"))
13894 (let* ((key (match-string 2))
13895 (value (match-string 3))
13896 (allowed (or (org-property-get-allowed-values (point) key)
13897 (and (member value '("[ ]" "[-]" "[X]"))
13898 '("[ ]" "[X]"))))
13899 nval)
13900 (unless allowed
13901 (error "Allowed values for this property have not been defined"))
13902 (if previous (setq allowed (reverse allowed)))
13903 (if (member value allowed)
13904 (setq nval (car (cdr (member value allowed)))))
13905 (setq nval (or nval (car allowed)))
13906 (if (equal nval value)
13907 (error "Only one allowed value for this property"))
13908 (org-at-property-p)
13909 (replace-match (concat " :" key ": " nval) t t)
13910 (org-indent-line-function)
13911 (beginning-of-line 1)
13912 (skip-chars-forward " \t")
13913 (run-hook-with-args 'org-property-changed-functions key nval)))
13915 (defun org-find-olp (path &optional this-buffer)
13916 "Return a marker pointing to the entry at outline path OLP.
13917 If anything goes wrong, throw an error.
13918 You can wrap this call to catch the error like this:
13920 (condition-case msg
13921 (org-mobile-locate-entry (match-string 4))
13922 (error (nth 1 msg)))
13924 The return value will then be either a string with the error message,
13925 or a marker if everything is OK.
13927 If THIS-BUFFER is set, the outline path does not contain a file,
13928 only headings."
13929 (let* ((file (if this-buffer buffer-file-name (pop path)))
13930 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
13931 (level 1)
13932 (lmin 1)
13933 (lmax 1)
13934 limit re end found pos heading cnt)
13935 (unless buffer (error "File not found :%s" file))
13936 (with-current-buffer buffer
13937 (save-excursion
13938 (save-restriction
13939 (widen)
13940 (setq limit (point-max))
13941 (goto-char (point-min))
13942 (while (setq heading (pop path))
13943 (setq re (format org-complex-heading-regexp-format
13944 (regexp-quote heading)))
13945 (setq cnt 0 pos (point))
13946 (while (re-search-forward re end t)
13947 (setq level (- (match-end 1) (match-beginning 1)))
13948 (if (and (>= level lmin) (<= level lmax))
13949 (setq found (match-beginning 0) cnt (1+ cnt))))
13950 (when (= cnt 0) (error "Heading not found on level %d: %s"
13951 lmax heading))
13952 (when (> cnt 1) (error "Heading not unique on level %d: %s"
13953 lmax heading))
13954 (goto-char found)
13955 (setq lmin (1+ level) lmax (+ lmin (if org-odd-levels-only 1 0)))
13956 (setq end (save-excursion (org-end-of-subtree t t))))
13957 (when (org-on-heading-p)
13958 (move-marker (make-marker) (point))))))))
13960 (defun org-find-entry-with-id (ident)
13961 "Locate the entry that contains the ID property with exact value IDENT.
13962 IDENT can be a string, a symbol or a number, this function will search for
13963 the string representation of it.
13964 Return the position where this entry starts, or nil if there is no such entry."
13965 (interactive "sID: ")
13966 (let ((id (cond
13967 ((stringp ident) ident)
13968 ((symbol-name ident) (symbol-name ident))
13969 ((numberp ident) (number-to-string ident))
13970 (t (error "IDENT %s must be a string, symbol or number" ident))))
13971 (case-fold-search nil))
13972 (save-excursion
13973 (save-restriction
13974 (widen)
13975 (goto-char (point-min))
13976 (when (re-search-forward
13977 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
13978 nil t)
13979 (org-back-to-heading t)
13980 (point))))))
13982 ;;;; Timestamps
13984 (defvar org-last-changed-timestamp nil)
13985 (defvar org-last-inserted-timestamp nil
13986 "The last time stamp inserted with `org-insert-time-stamp'.")
13987 (defvar org-time-was-given) ; dynamically scoped parameter
13988 (defvar org-end-time-was-given) ; dynamically scoped parameter
13989 (defvar org-ts-what) ; dynamically scoped parameter
13991 (defun org-time-stamp (arg &optional inactive)
13992 "Prompt for a date/time and insert a time stamp.
13993 If the user specifies a time like HH:MM, or if this command is called
13994 with a prefix argument, the time stamp will contain date and time.
13995 Otherwise, only the date will be included. All parts of a date not
13996 specified by the user will be filled in from the current date/time.
13997 So if you press just return without typing anything, the time stamp
13998 will represent the current date/time. If there is already a timestamp
13999 at the cursor, it will be modified."
14000 (interactive "P")
14001 (let* ((ts nil)
14002 (default-time
14003 ;; Default time is either today, or, when entering a range,
14004 ;; the range start.
14005 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
14006 (save-excursion
14007 (re-search-backward
14008 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
14009 (- (point) 20) t)))
14010 (apply 'encode-time (org-parse-time-string (match-string 1)))
14011 (current-time)))
14012 (default-input (and ts (org-get-compact-tod ts)))
14013 org-time-was-given org-end-time-was-given time)
14014 (cond
14015 ((and (org-at-timestamp-p t)
14016 (memq last-command '(org-time-stamp org-time-stamp-inactive))
14017 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
14018 (insert "--")
14019 (setq time (let ((this-command this-command))
14020 (org-read-date arg 'totime nil nil
14021 default-time default-input)))
14022 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
14023 ((org-at-timestamp-p t)
14024 (setq time (let ((this-command this-command))
14025 (org-read-date arg 'totime nil nil default-time default-input)))
14026 (when (org-at-timestamp-p t) ; just to get the match data
14027 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
14028 (replace-match "")
14029 (setq org-last-changed-timestamp
14030 (org-insert-time-stamp
14031 time (or org-time-was-given arg)
14032 inactive nil nil (list org-end-time-was-given))))
14033 (message "Timestamp updated"))
14035 (setq time (let ((this-command this-command))
14036 (org-read-date arg 'totime nil nil default-time default-input)))
14037 (org-insert-time-stamp time (or org-time-was-given arg) inactive
14038 nil nil (list org-end-time-was-given))))))
14040 ;; FIXME: can we use this for something else, like computing time differences?
14041 (defun org-get-compact-tod (s)
14042 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
14043 (let* ((t1 (match-string 1 s))
14044 (h1 (string-to-number (match-string 2 s)))
14045 (m1 (string-to-number (match-string 3 s)))
14046 (t2 (and (match-end 4) (match-string 5 s)))
14047 (h2 (and t2 (string-to-number (match-string 6 s))))
14048 (m2 (and t2 (string-to-number (match-string 7 s))))
14049 dh dm)
14050 (if (not t2)
14052 (setq dh (- h2 h1) dm (- m2 m1))
14053 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
14054 (concat t1 "+" (number-to-string dh)
14055 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
14057 (defun org-time-stamp-inactive (&optional arg)
14058 "Insert an inactive time stamp.
14059 An inactive time stamp is enclosed in square brackets instead of angle
14060 brackets. It is inactive in the sense that it does not trigger agenda entries,
14061 does not link to the calendar and cannot be changed with the S-cursor keys.
14062 So these are more for recording a certain time/date."
14063 (interactive "P")
14064 (org-time-stamp arg 'inactive))
14066 (defvar org-date-ovl (make-overlay 1 1))
14067 (overlay-put org-date-ovl 'face 'org-warning)
14068 (org-detach-overlay org-date-ovl)
14070 (defvar org-ans1) ; dynamically scoped parameter
14071 (defvar org-ans2) ; dynamically scoped parameter
14073 (defvar org-plain-time-of-day-regexp) ; defined below
14075 (defvar org-overriding-default-time nil) ; dynamically scoped
14076 (defvar org-read-date-overlay nil)
14077 (defvar org-dcst nil) ; dynamically scoped
14078 (defvar org-read-date-history nil)
14079 (defvar org-read-date-final-answer nil)
14081 (defun org-read-date (&optional with-time to-time from-string prompt
14082 default-time default-input)
14083 "Read a date, possibly a time, and make things smooth for the user.
14084 The prompt will suggest to enter an ISO date, but you can also enter anything
14085 which will at least partially be understood by `parse-time-string'.
14086 Unrecognized parts of the date will default to the current day, month, year,
14087 hour and minute. If this command is called to replace a timestamp at point,
14088 of to enter the second timestamp of a range, the default time is taken
14089 from the existing stamp. Furthermore, the command prefers the future,
14090 so if you are giving a date where the year is not given, and the day-month
14091 combination is already past in the current year, it will assume you
14092 mean next year. For details, see the manual. A few examples:
14094 3-2-5 --> 2003-02-05
14095 feb 15 --> currentyear-02-15
14096 2/15 --> currentyear-02-15
14097 sep 12 9 --> 2009-09-12
14098 12:45 --> today 12:45
14099 22 sept 0:34 --> currentyear-09-22 0:34
14100 12 --> currentyear-currentmonth-12
14101 Fri --> nearest Friday (today or later)
14102 etc.
14104 Furthermore you can specify a relative date by giving, as the *first* thing
14105 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
14106 change in days weeks, months, years.
14107 With a single plus or minus, the date is relative to today. With a double
14108 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
14109 +4d --> four days from today
14110 +4 --> same as above
14111 +2w --> two weeks from today
14112 ++5 --> five days from default date
14114 The function understands only English month and weekday abbreviations,
14115 but this can be configured with the variables `parse-time-months' and
14116 `parse-time-weekdays'.
14118 While prompting, a calendar is popped up - you can also select the
14119 date with the mouse (button 1). The calendar shows a period of three
14120 months. To scroll it to other months, use the keys `>' and `<'.
14121 If you don't like the calendar, turn it off with
14122 \(setq org-read-date-popup-calendar nil)
14124 With optional argument TO-TIME, the date will immediately be converted
14125 to an internal time.
14126 With an optional argument WITH-TIME, the prompt will suggest to also
14127 insert a time. Note that when WITH-TIME is not set, you can still
14128 enter a time, and this function will inform the calling routine about
14129 this change. The calling routine may then choose to change the format
14130 used to insert the time stamp into the buffer to include the time.
14131 With optional argument FROM-STRING, read from this string instead from
14132 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
14133 the time/date that is used for everything that is not specified by the
14134 user."
14135 (require 'parse-time)
14136 (let* ((org-time-stamp-rounding-minutes
14137 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
14138 (org-dcst org-display-custom-times)
14139 (ct (org-current-time))
14140 (def (or org-overriding-default-time default-time ct))
14141 (defdecode (decode-time def))
14142 (dummy (progn
14143 (when (< (nth 2 defdecode) org-extend-today-until)
14144 (setcar (nthcdr 2 defdecode) -1)
14145 (setcar (nthcdr 1 defdecode) 59)
14146 (setq def (apply 'encode-time defdecode)
14147 defdecode (decode-time def)))))
14148 (calendar-frame-setup nil)
14149 (calendar-setup nil)
14150 (calendar-move-hook nil)
14151 (calendar-view-diary-initially-flag nil)
14152 (calendar-view-holidays-initially-flag nil)
14153 (timestr (format-time-string
14154 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
14155 (prompt (concat (if prompt (concat prompt " ") "")
14156 (format "Date+time [%s]: " timestr)))
14157 ans (org-ans0 "") org-ans1 org-ans2 final)
14159 (cond
14160 (from-string (setq ans from-string))
14161 (org-read-date-popup-calendar
14162 (save-excursion
14163 (save-window-excursion
14164 (calendar)
14165 (calendar-forward-day (- (time-to-days def)
14166 (calendar-absolute-from-gregorian
14167 (calendar-current-date))))
14168 (org-eval-in-calendar nil t)
14169 (let* ((old-map (current-local-map))
14170 (map (copy-keymap calendar-mode-map))
14171 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
14172 (org-defkey map (kbd "RET") 'org-calendar-select)
14173 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
14174 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
14175 (org-defkey minibuffer-local-map [(meta shift left)]
14176 (lambda () (interactive)
14177 (org-eval-in-calendar '(calendar-backward-month 1))))
14178 (org-defkey minibuffer-local-map [(meta shift right)]
14179 (lambda () (interactive)
14180 (org-eval-in-calendar '(calendar-forward-month 1))))
14181 (org-defkey minibuffer-local-map [(meta shift up)]
14182 (lambda () (interactive)
14183 (org-eval-in-calendar '(calendar-backward-year 1))))
14184 (org-defkey minibuffer-local-map [(meta shift down)]
14185 (lambda () (interactive)
14186 (org-eval-in-calendar '(calendar-forward-year 1))))
14187 (org-defkey minibuffer-local-map [?\e (shift left)]
14188 (lambda () (interactive)
14189 (org-eval-in-calendar '(calendar-backward-month 1))))
14190 (org-defkey minibuffer-local-map [?\e (shift right)]
14191 (lambda () (interactive)
14192 (org-eval-in-calendar '(calendar-forward-month 1))))
14193 (org-defkey minibuffer-local-map [?\e (shift up)]
14194 (lambda () (interactive)
14195 (org-eval-in-calendar '(calendar-backward-year 1))))
14196 (org-defkey minibuffer-local-map [?\e (shift down)]
14197 (lambda () (interactive)
14198 (org-eval-in-calendar '(calendar-forward-year 1))))
14199 (org-defkey minibuffer-local-map [(shift up)]
14200 (lambda () (interactive)
14201 (org-eval-in-calendar '(calendar-backward-week 1))))
14202 (org-defkey minibuffer-local-map [(shift down)]
14203 (lambda () (interactive)
14204 (org-eval-in-calendar '(calendar-forward-week 1))))
14205 (org-defkey minibuffer-local-map [(shift left)]
14206 (lambda () (interactive)
14207 (org-eval-in-calendar '(calendar-backward-day 1))))
14208 (org-defkey minibuffer-local-map [(shift right)]
14209 (lambda () (interactive)
14210 (org-eval-in-calendar '(calendar-forward-day 1))))
14211 (org-defkey minibuffer-local-map ">"
14212 (lambda () (interactive)
14213 (org-eval-in-calendar '(scroll-calendar-left 1))))
14214 (org-defkey minibuffer-local-map "<"
14215 (lambda () (interactive)
14216 (org-eval-in-calendar '(scroll-calendar-right 1))))
14217 (org-defkey minibuffer-local-map "\C-v"
14218 (lambda () (interactive)
14219 (org-eval-in-calendar
14220 '(calendar-scroll-left-three-months 1))))
14221 (org-defkey minibuffer-local-map "\M-v"
14222 (lambda () (interactive)
14223 (org-eval-in-calendar
14224 '(calendar-scroll-right-three-months 1))))
14225 (run-hooks 'org-read-date-minibuffer-setup-hook)
14226 (unwind-protect
14227 (progn
14228 (use-local-map map)
14229 (add-hook 'post-command-hook 'org-read-date-display)
14230 (setq org-ans0 (read-string prompt default-input
14231 'org-read-date-history nil))
14232 ;; org-ans0: from prompt
14233 ;; org-ans1: from mouse click
14234 ;; org-ans2: from calendar motion
14235 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
14236 (remove-hook 'post-command-hook 'org-read-date-display)
14237 (use-local-map old-map)
14238 (when org-read-date-overlay
14239 (delete-overlay org-read-date-overlay)
14240 (setq org-read-date-overlay nil)))))))
14242 (t ; Naked prompt only
14243 (unwind-protect
14244 (setq ans (read-string prompt default-input
14245 'org-read-date-history timestr))
14246 (when org-read-date-overlay
14247 (delete-overlay org-read-date-overlay)
14248 (setq org-read-date-overlay nil)))))
14250 (setq final (org-read-date-analyze ans def defdecode))
14251 (setq org-read-date-final-answer ans)
14253 (if to-time
14254 (apply 'encode-time final)
14255 (if (and (boundp 'org-time-was-given) org-time-was-given)
14256 (format "%04d-%02d-%02d %02d:%02d"
14257 (nth 5 final) (nth 4 final) (nth 3 final)
14258 (nth 2 final) (nth 1 final))
14259 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
14261 (defvar def)
14262 (defvar defdecode)
14263 (defvar with-time)
14264 (defvar org-read-date-analyze-futurep nil)
14265 (defun org-read-date-display ()
14266 "Display the current date prompt interpretation in the minibuffer."
14267 (when org-read-date-display-live
14268 (when org-read-date-overlay
14269 (delete-overlay org-read-date-overlay))
14270 (let ((p (point)))
14271 (end-of-line 1)
14272 (while (not (equal (buffer-substring
14273 (max (point-min) (- (point) 4)) (point))
14274 " "))
14275 (insert " "))
14276 (goto-char p))
14277 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
14278 " " (or org-ans1 org-ans2)))
14279 (org-end-time-was-given nil)
14280 (f (org-read-date-analyze ans def defdecode))
14281 (fmts (if org-dcst
14282 org-time-stamp-custom-formats
14283 org-time-stamp-formats))
14284 (fmt (if (or with-time
14285 (and (boundp 'org-time-was-given) org-time-was-given))
14286 (cdr fmts)
14287 (car fmts)))
14288 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
14289 (when (and org-end-time-was-given
14290 (string-match org-plain-time-of-day-regexp txt))
14291 (setq txt (concat (substring txt 0 (match-end 0)) "-"
14292 org-end-time-was-given
14293 (substring txt (match-end 0)))))
14294 (when org-read-date-analyze-futurep
14295 (setq txt (concat txt " (=>F)")))
14296 (setq org-read-date-overlay
14297 (make-overlay (1- (point-at-eol)) (point-at-eol)))
14298 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
14300 (defun org-read-date-analyze (ans def defdecode)
14301 "Analyze the combined answer of the date prompt."
14302 ;; FIXME: cleanup and comment
14303 (let ((nowdecode (decode-time (current-time)))
14304 delta deltan deltaw deltadef year month day
14305 hour minute second wday pm h2 m2 tl wday1
14306 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
14307 (setq org-read-date-analyze-futurep nil)
14308 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
14309 (setq ans "+0"))
14311 (when (setq delta (org-read-date-get-relative ans (current-time) def))
14312 (setq ans (replace-match "" t t ans)
14313 deltan (car delta)
14314 deltaw (nth 1 delta)
14315 deltadef (nth 2 delta)))
14317 ;; Check if there is an iso week date in there
14318 ;; If yes, store the info and postpone interpreting it until the rest
14319 ;; of the parsing is done
14320 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
14321 (setq iso-year (if (match-end 1)
14322 (org-small-year-to-year
14323 (string-to-number (match-string 1 ans))))
14324 iso-weekday (if (match-end 3)
14325 (string-to-number (match-string 3 ans)))
14326 iso-week (string-to-number (match-string 2 ans)))
14327 (setq ans (replace-match "" t t ans)))
14329 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
14330 (when (string-match
14331 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
14332 (setq year (if (match-end 2)
14333 (string-to-number (match-string 2 ans))
14334 (progn (setq kill-year t)
14335 (string-to-number (format-time-string "%Y"))))
14336 month (string-to-number (match-string 3 ans))
14337 day (string-to-number (match-string 4 ans)))
14338 (if (< year 100) (setq year (+ 2000 year)))
14339 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14340 t nil ans)))
14341 ;; Help matching american dates, like 5/30 or 5/30/7
14342 (when (string-match
14343 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
14344 (setq year (if (match-end 4)
14345 (string-to-number (match-string 4 ans))
14346 (progn (setq kill-year t)
14347 (string-to-number (format-time-string "%Y"))))
14348 month (string-to-number (match-string 1 ans))
14349 day (string-to-number (match-string 2 ans)))
14350 (if (< year 100) (setq year (+ 2000 year)))
14351 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14352 t nil ans)))
14353 ;; Help matching am/pm times, because `parse-time-string' does not do that.
14354 ;; If there is a time with am/pm, and *no* time without it, we convert
14355 ;; so that matching will be successful.
14356 (loop for i from 1 to 2 do ; twice, for end time as well
14357 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
14358 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
14359 (setq hour (string-to-number (match-string 1 ans))
14360 minute (if (match-end 3)
14361 (string-to-number (match-string 3 ans))
14363 pm (equal ?p
14364 (string-to-char (downcase (match-string 4 ans)))))
14365 (if (and (= hour 12) (not pm))
14366 (setq hour 0)
14367 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
14368 (setq ans (replace-match (format "%02d:%02d" hour minute)
14369 t t ans))))
14371 ;; Check if a time range is given as a duration
14372 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
14373 (setq hour (string-to-number (match-string 1 ans))
14374 h2 (+ hour (string-to-number (match-string 3 ans)))
14375 minute (string-to-number (match-string 2 ans))
14376 m2 (+ minute (if (match-end 5) (string-to-number
14377 (match-string 5 ans))0)))
14378 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
14379 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
14380 t t ans)))
14382 ;; Check if there is a time range
14383 (when (boundp 'org-end-time-was-given)
14384 (setq org-time-was-given nil)
14385 (when (and (string-match org-plain-time-of-day-regexp ans)
14386 (match-end 8))
14387 (setq org-end-time-was-given (match-string 8 ans))
14388 (setq ans (concat (substring ans 0 (match-beginning 7))
14389 (substring ans (match-end 7))))))
14391 (setq tl (parse-time-string ans)
14392 day (or (nth 3 tl) (nth 3 defdecode))
14393 month (or (nth 4 tl)
14394 (if (and org-read-date-prefer-future
14395 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
14396 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
14397 (nth 4 defdecode)))
14398 year (or (and (not kill-year) (nth 5 tl))
14399 (if (and org-read-date-prefer-future
14400 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
14401 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
14402 (nth 5 defdecode)))
14403 hour (or (nth 2 tl) (nth 2 defdecode))
14404 minute (or (nth 1 tl) (nth 1 defdecode))
14405 second (or (nth 0 tl) 0)
14406 wday (nth 6 tl))
14408 (when (and (eq org-read-date-prefer-future 'time)
14409 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
14410 (equal day (nth 3 nowdecode))
14411 (equal month (nth 4 nowdecode))
14412 (equal year (nth 5 nowdecode))
14413 (nth 2 tl)
14414 (or (< (nth 2 tl) (nth 2 nowdecode))
14415 (and (= (nth 2 tl) (nth 2 nowdecode))
14416 (nth 1 tl)
14417 (< (nth 1 tl) (nth 1 nowdecode)))))
14418 (setq day (1+ day)
14419 futurep t))
14421 ;; Special date definitions below
14422 (cond
14423 (iso-week
14424 ;; There was an iso week
14425 (require 'cal-iso)
14426 (setq futurep nil)
14427 (setq year (or iso-year year)
14428 day (or iso-weekday wday 1)
14429 wday nil ; to make sure that the trigger below does not match
14430 iso-date (calendar-gregorian-from-absolute
14431 (calendar-absolute-from-iso
14432 (list iso-week day year))))
14433 ; FIXME: Should we also push ISO weeks into the future?
14434 ; (when (and org-read-date-prefer-future
14435 ; (not iso-year)
14436 ; (< (calendar-absolute-from-gregorian iso-date)
14437 ; (time-to-days (current-time))))
14438 ; (setq year (1+ year)
14439 ; iso-date (calendar-gregorian-from-absolute
14440 ; (calendar-absolute-from-iso
14441 ; (list iso-week day year)))))
14442 (setq month (car iso-date)
14443 year (nth 2 iso-date)
14444 day (nth 1 iso-date)))
14445 (deltan
14446 (setq futurep nil)
14447 (unless deltadef
14448 (let ((now (decode-time (current-time))))
14449 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
14450 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
14451 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
14452 ((equal deltaw "m") (setq month (+ month deltan)))
14453 ((equal deltaw "y") (setq year (+ year deltan)))))
14454 ((and wday (not (nth 3 tl)))
14455 (setq futurep nil)
14456 ;; Weekday was given, but no day, so pick that day in the week
14457 ;; on or after the derived date.
14458 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
14459 (unless (equal wday wday1)
14460 (setq day (+ day (% (- wday wday1 -7) 7))))))
14461 (if (and (boundp 'org-time-was-given)
14462 (nth 2 tl))
14463 (setq org-time-was-given t))
14464 (if (< year 100) (setq year (+ 2000 year)))
14465 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
14466 (setq org-read-date-analyze-futurep futurep)
14467 (list second minute hour day month year)))
14469 (defvar parse-time-weekdays)
14471 (defun org-read-date-get-relative (s today default)
14472 "Check string S for special relative date string.
14473 TODAY and DEFAULT are internal times, for today and for a default.
14474 Return shift list (N what def-flag)
14475 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
14476 N is the number of WHATs to shift.
14477 DEF-FLAG is t when a double ++ or -- indicates shift relative to
14478 the DEFAULT date rather than TODAY."
14479 (when (and
14480 (string-match
14481 (concat
14482 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
14483 "\\([0-9]+\\)?"
14484 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
14485 "\\([ \t]\\|$\\)") s)
14486 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
14487 (let* ((dir (if (> (match-end 1) (match-beginning 1))
14488 (string-to-char (substring (match-string 1 s) -1))
14489 ?+))
14490 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
14491 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
14492 (what (if (match-end 3) (match-string 3 s) "d"))
14493 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
14494 (date (if rel default today))
14495 (wday (nth 6 (decode-time date)))
14496 delta)
14497 (if wday1
14498 (progn
14499 (setq delta (mod (+ 7 (- wday1 wday)) 7))
14500 (if (= dir ?-) (setq delta (- delta 7)))
14501 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
14502 (list delta "d" rel))
14503 (list (* n (if (= dir ?-) -1 1)) what rel)))))
14505 (defun org-order-calendar-date-args (arg1 arg2 arg3)
14506 "Turn a user-specified date into the internal representation.
14507 The internal representation needed by the calendar is (month day year).
14508 This is a wrapper to handle the brain-dead convention in calendar that
14509 user function argument order change dependent on argument order."
14510 (if (boundp 'calendar-date-style)
14511 (cond
14512 ((eq calendar-date-style 'american)
14513 (list arg1 arg2 arg3))
14514 ((eq calendar-date-style 'european)
14515 (list arg2 arg1 arg3))
14516 ((eq calendar-date-style 'iso)
14517 (list arg2 arg3 arg1)))
14518 (if (org-bound-and-true-p european-calendar-style)
14519 (list arg2 arg1 arg3)
14520 (list arg1 arg2 arg3))))
14522 (defun org-eval-in-calendar (form &optional keepdate)
14523 "Eval FORM in the calendar window and return to current window.
14524 Also, store the cursor date in variable org-ans2."
14525 (let ((sf (selected-frame))
14526 (sw (selected-window)))
14527 (select-window (get-buffer-window "*Calendar*" t))
14528 (eval form)
14529 (when (and (not keepdate) (calendar-cursor-to-date))
14530 (let* ((date (calendar-cursor-to-date))
14531 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14532 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
14533 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
14534 (select-window sw)
14535 (org-select-frame-set-input-focus sf)))
14537 (defun org-calendar-select ()
14538 "Return to `org-read-date' with the date currently selected.
14539 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
14540 (interactive)
14541 (when (calendar-cursor-to-date)
14542 (let* ((date (calendar-cursor-to-date))
14543 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14544 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
14545 (if (active-minibuffer-window) (exit-minibuffer))))
14547 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
14548 "Insert a date stamp for the date given by the internal TIME.
14549 WITH-HM means use the stamp format that includes the time of the day.
14550 INACTIVE means use square brackets instead of angular ones, so that the
14551 stamp will not contribute to the agenda.
14552 PRE and POST are optional strings to be inserted before and after the
14553 stamp.
14554 The command returns the inserted time stamp."
14555 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
14556 stamp)
14557 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
14558 (insert-before-markers (or pre ""))
14559 (when (listp extra)
14560 (setq extra (car extra))
14561 (if (and (stringp extra)
14562 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
14563 (setq extra (format "-%02d:%02d"
14564 (string-to-number (match-string 1 extra))
14565 (string-to-number (match-string 2 extra))))
14566 (setq extra nil)))
14567 (when extra
14568 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
14569 (insert-before-markers (setq stamp (format-time-string fmt time)))
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