Improve documentation and error handling with priorities
[org-mode.git] / lisp / org.el
blobdeae30c9a7f1b7facd2c27537dcbee2cb321d965
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, 2011
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.5
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)
79 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
80 (when (fboundp 'defvaralias)
81 (unless (boundp 'calendar-view-holidays-initially-flag)
82 (defvaralias 'calendar-view-holidays-initially-flag
83 'view-calendar-holidays-initially))
84 (unless (boundp 'calendar-view-diary-initially-flag)
85 (defvaralias 'calendar-view-diary-initially-flag
86 'view-diary-entries-initially))
87 (unless (boundp 'diary-fancy-buffer)
88 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
90 (require 'outline) (require 'noutline)
91 ;; Other stuff we need.
92 (require 'time-date)
93 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
94 (require 'easymenu)
95 (require 'overlay)
97 (require 'org-macs)
98 (require 'org-entities)
99 (require 'org-compat)
100 (require 'org-faces)
101 (require 'org-list)
102 (require 'org-pcomplete)
103 (require 'org-src)
104 (require 'org-footnote)
106 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
107 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
108 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
110 ;; babel
111 (require 'ob)
112 (require 'ob-table)
113 (require 'ob-lob)
114 (require 'ob-ref)
115 (require 'ob-tangle)
116 (require 'ob-comint)
117 (require 'ob-keys)
119 ;; load languages based on value of `org-babel-load-languages'
120 (defvar org-babel-load-languages)
121 ;;;###autoload
122 (defun org-babel-do-load-languages (sym value)
123 "Load the languages defined in `org-babel-load-languages'."
124 (set-default sym value)
125 (mapc (lambda (pair)
126 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
127 (if active
128 (progn
129 (require (intern (concat "ob-" lang))))
130 (progn
131 (funcall 'fmakunbound
132 (intern (concat "org-babel-execute:" lang)))
133 (funcall 'fmakunbound
134 (intern (concat "org-babel-expand-body:" lang)))))))
135 org-babel-load-languages))
137 (defcustom org-babel-load-languages '((emacs-lisp . t))
138 "Languages which can be evaluated in Org-mode buffers.
139 This list can be used to load support for any of the languages
140 below, note that each language will depend on a different set of
141 system executables and/or Emacs modes. When a language is
142 \"loaded\", then code blocks in that language can be evaluated
143 with `org-babel-execute-src-block' bound by default to C-c
144 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
145 be set to remove code block evaluation from the C-c C-c
146 keybinding. By default only Emacs Lisp (which has no
147 requirements) is loaded."
148 :group 'org-babel
149 :set 'org-babel-do-load-languages
150 :type '(alist :tag "Babel Languages"
151 :key-type
152 (choice
153 (const :tag "Awk" awk)
154 (const :tag "C" C)
155 (const :tag "R" R)
156 (const :tag "Asymptote" asymptote)
157 (const :tag "Calc" calc)
158 (const :tag "Clojure" clojure)
159 (const :tag "CSS" css)
160 (const :tag "Ditaa" ditaa)
161 (const :tag "Dot" dot)
162 (const :tag "Emacs Lisp" emacs-lisp)
163 (const :tag "Gnuplot" gnuplot)
164 (const :tag "Haskell" haskell)
165 (const :tag "Javascript" js)
166 (const :tag "Latex" latex)
167 (const :tag "Ledger" ledger)
168 (const :tag "Maxima" maxima)
169 (const :tag "Matlab" matlab)
170 (const :tag "Mscgen" mscgen)
171 (const :tag "Ocaml" ocaml)
172 (const :tag "Octave" octave)
173 (const :tag "Org" org)
174 (const :tag "Perl" perl)
175 (const :tag "PlantUML" plantuml)
176 (const :tag "Python" python)
177 (const :tag "Ruby" ruby)
178 (const :tag "Sass" sass)
179 (const :tag "Scheme" scheme)
180 (const :tag "Screen" screen)
181 (const :tag "Shell Script" sh)
182 (const :tag "Sql" sql)
183 (const :tag "Sqlite" sqlite))
184 :value-type (boolean :tag "Activate" :value t)))
186 ;;;; Customization variables
187 (defcustom org-clone-delete-id nil
188 "Remove ID property of clones of a subtree.
189 When non-nil, clones of a subtree don't inherit the ID property.
190 Otherwise they inherit the ID property with a new unique
191 identifier."
192 :type 'boolean
193 :group 'org-id)
195 ;;; Version
197 (defconst org-version "7.5"
198 "The version number of the file org.el.")
200 (defun org-version (&optional here)
201 "Show the org-mode version in the echo area.
202 With prefix arg HERE, insert it at point."
203 (interactive "P")
204 (let* ((origin default-directory)
205 (version org-version)
206 (git-version)
207 (dir (concat (file-name-directory (locate-library "org")) "../" )))
208 (when (and (file-exists-p (expand-file-name ".git" dir))
209 (executable-find "git"))
210 (unwind-protect
211 (progn
212 (cd dir)
213 (when (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
214 (with-current-buffer "*Shell Command Output*"
215 (goto-char (point-min))
216 (setq git-version (buffer-substring (point) (point-at-eol))))
217 (subst-char-in-string ?- ?. git-version t)
218 (when (string-match "\\S-"
219 (shell-command-to-string
220 "git diff-index --name-only HEAD --"))
221 (setq git-version (concat git-version ".dirty")))
222 (setq version (concat version " (" git-version ")"))))
223 (cd origin)))
224 (setq version (format "Org-mode version %s" version))
225 (if here (insert version))
226 (message version)))
228 ;;; Compatibility constants
230 ;;; The custom variables
232 (defgroup org nil
233 "Outline-based notes management and organizer."
234 :tag "Org"
235 :group 'outlines
236 :group 'calendar)
238 (defcustom org-mode-hook nil
239 "Mode hook for Org-mode, run after the mode was turned on."
240 :group 'org
241 :type 'hook)
243 (defcustom org-load-hook nil
244 "Hook that is run after org.el has been loaded."
245 :group 'org
246 :type 'hook)
248 (defvar org-modules) ; defined below
249 (defvar org-modules-loaded nil
250 "Have the modules been loaded already?")
252 (defun org-load-modules-maybe (&optional force)
253 "Load all extensions listed in `org-modules'."
254 (when (or force (not org-modules-loaded))
255 (mapc (lambda (ext)
256 (condition-case nil (require ext)
257 (error (message "Problems while trying to load feature `%s'" ext))))
258 org-modules)
259 (setq org-modules-loaded t)))
261 (defun org-set-modules (var value)
262 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
263 (set var value)
264 (when (featurep 'org)
265 (org-load-modules-maybe 'force)))
267 (when (org-bound-and-true-p org-modules)
268 (let ((a (member 'org-infojs org-modules)))
269 (and a (setcar a 'org-jsinfo))))
271 (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)
272 "Modules that should always be loaded together with org.el.
273 If a description starts with <C>, the file is not part of Emacs
274 and loading it will require that you have downloaded and properly installed
275 the org-mode distribution.
277 You can also use this system to load external packages (i.e. neither Org
278 core modules, nor modules from the CONTRIB directory). Just add symbols
279 to the end of the list. If the package is called org-xyz.el, then you need
280 to add the symbol `xyz', and the package must have a call to
282 (provide 'org-xyz)"
283 :group 'org
284 :set 'org-set-modules
285 :type
286 '(set :greedy t
287 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
288 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
289 (const :tag " crypt: Encryption of subtrees" org-crypt)
290 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
291 (const :tag " docview: Links to doc-view buffers" org-docview)
292 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
293 (const :tag " id: Global IDs for identifying entries" org-id)
294 (const :tag " info: Links to Info nodes" org-info)
295 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
296 (const :tag " habit: Track your consistency with habits" org-habit)
297 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
298 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
299 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
300 (const :tag " mew Links to Mew folders/messages" org-mew)
301 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
302 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
303 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
304 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
305 (const :tag " vm: Links to VM folders/messages" org-vm)
306 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
307 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
308 (const :tag " mouse: Additional mouse support" org-mouse)
309 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
311 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
312 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
313 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
314 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
315 (const :tag "C collector: Collect properties into tables" org-collector)
316 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
317 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
318 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
319 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
320 (const :tag "C eval: Include command output as text" org-eval)
321 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
322 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
323 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
324 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
325 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
327 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
329 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
330 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
331 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
332 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
333 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
334 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
335 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
336 (const :tag "C mtags: Support for muse-like tags" org-mtags)
337 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
338 (const :tag "C registry: A registry for Org-mode links" org-registry)
339 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
340 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
341 (const :tag "C secretary: Team management with org-mode" org-secretary)
342 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
343 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
344 (const :tag "C track: Keep up with Org-mode development" org-track)
345 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
346 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
347 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
349 (defcustom org-support-shift-select nil
350 "Non-nil means make shift-cursor commands select text when possible.
352 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
353 selecting a region, or enlarge regions started in this way.
354 In Org-mode, in special contexts, these same keys are used for other
355 purposes, important enough to compete with shift selection. Org tries
356 to balance these needs by supporting `shift-select-mode' outside these
357 special contexts, under control of this variable.
359 The default of this variable is nil, to avoid confusing behavior. Shifted
360 cursor keys will then execute Org commands in the following contexts:
361 - on a headline, changing TODO state (left/right) and priority (up/down)
362 - on a time stamp, changing the time
363 - in a plain list item, changing the bullet type
364 - in a property definition line, switching between allowed values
365 - in the BEGIN line of a clock table (changing the time block).
366 Outside these contexts, the commands will throw an error.
368 When this variable is t and the cursor is not in a special context,
369 Org-mode will support shift-selection for making and enlarging regions.
370 To make this more effective, the bullet cycling will no longer happen
371 anywhere in an item line, but only if the cursor is exactly on the bullet.
373 If you set this variable to the symbol `always', then the keys
374 will not be special in headlines, property lines, and item lines, to make
375 shift selection work there as well. If this is what you want, you can
376 use the following alternative commands: `C-c C-t' and `C-c ,' to
377 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
378 TODO sets, `C-c -' to cycle item bullet types, and properties can be
379 edited by hand or in column view.
381 However, when the cursor is on a timestamp, shift-cursor commands
382 will still edit the time stamp - this is just too good to give up.
384 XEmacs user should have this variable set to nil, because shift-select-mode
385 is Emacs 23 only."
386 :group 'org
387 :type '(choice
388 (const :tag "Never" nil)
389 (const :tag "When outside special context" t)
390 (const :tag "Everywhere except timestamps" always)))
392 (defgroup org-startup nil
393 "Options concerning startup of Org-mode."
394 :tag "Org Startup"
395 :group 'org)
397 (defcustom org-startup-folded t
398 "Non-nil means entering Org-mode will switch to OVERVIEW.
399 This can also be configured on a per-file basis by adding one of
400 the following lines anywhere in the buffer:
402 #+STARTUP: fold (or `overview', this is equivalent)
403 #+STARTUP: nofold (or `showall', this is equivalent)
404 #+STARTUP: content
405 #+STARTUP: showeverything"
406 :group 'org-startup
407 :type '(choice
408 (const :tag "nofold: show all" nil)
409 (const :tag "fold: overview" t)
410 (const :tag "content: all headlines" content)
411 (const :tag "show everything, even drawers" showeverything)))
413 (defcustom org-startup-truncated t
414 "Non-nil means entering Org-mode will set `truncate-lines'.
415 This is useful since some lines containing links can be very long and
416 uninteresting. Also tables look terrible when wrapped."
417 :group 'org-startup
418 :type 'boolean)
420 (defcustom org-startup-indented nil
421 "Non-nil means turn on `org-indent-mode' on startup.
422 This can also be configured on a per-file basis by adding one of
423 the following lines anywhere in the buffer:
425 #+STARTUP: indent
426 #+STARTUP: noindent"
427 :group 'org-structure
428 :type '(choice
429 (const :tag "Not" nil)
430 (const :tag "Globally (slow on startup in large files)" t)))
432 (defcustom org-use-sub-superscripts t
433 "Non-nil means interpret \"_\" and \"^\" for export.
434 When this option is turned on, you can use TeX-like syntax for sub- and
435 superscripts. Several characters after \"_\" or \"^\" will be
436 considered as a single item - so grouping with {} is normally not
437 needed. For example, the following things will be parsed as single
438 sub- or superscripts.
440 10^24 or 10^tau several digits will be considered 1 item.
441 10^-12 or 10^-tau a leading sign with digits or a word
442 x^2-y^3 will be read as x^2 - y^3, because items are
443 terminated by almost any nonword/nondigit char.
444 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
446 Still, ambiguity is possible - so when in doubt use {} to enclose the
447 sub/superscript. If you set this variable to the symbol `{}',
448 the braces are *required* in order to trigger interpretations as
449 sub/superscript. This can be helpful in documents that need \"_\"
450 frequently in plain text.
452 Not all export backends support this, but HTML does.
454 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
455 :group 'org-startup
456 :group 'org-export-translation
457 :type '(choice
458 (const :tag "Always interpret" t)
459 (const :tag "Only with braces" {})
460 (const :tag "Never interpret" nil)))
462 (if (fboundp 'defvaralias)
463 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
466 (defcustom org-startup-with-beamer-mode nil
467 "Non-nil means turn on `org-beamer-mode' on startup.
468 This can also be configured on a per-file basis by adding one of
469 the following lines anywhere in the buffer:
471 #+STARTUP: beamer"
472 :group 'org-startup
473 :type 'boolean)
475 (defcustom org-startup-align-all-tables nil
476 "Non-nil means align all tables when visiting a file.
477 This is useful when the column width in tables is forced with <N> cookies
478 in table fields. Such tables will look correct only after the first re-align.
479 This can also be configured on a per-file basis by adding one of
480 the following lines anywhere in the buffer:
481 #+STARTUP: align
482 #+STARTUP: noalign"
483 :group 'org-startup
484 :type 'boolean)
486 (defcustom org-startup-with-inline-images nil
487 "Non-nil means show inline images when loading a new Org file.
488 This can also be configured on a per-file basis by adding one of
489 the following lines anywhere in the buffer:
490 #+STARTUP: inlineimages
491 #+STARTUP: noinlineimages"
492 :group 'org-startup
493 :type 'boolean)
495 (defcustom org-insert-mode-line-in-empty-file nil
496 "Non-nil means insert the first line setting Org-mode in empty files.
497 When the function `org-mode' is called interactively in an empty file, this
498 normally means that the file name does not automatically trigger Org-mode.
499 To ensure that the file will always be in Org-mode in the future, a
500 line enforcing Org-mode will be inserted into the buffer, if this option
501 has been set."
502 :group 'org-startup
503 :type 'boolean)
505 (defcustom org-replace-disputed-keys nil
506 "Non-nil means use alternative key bindings for some keys.
507 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
508 These keys are also used by other packages like shift-selection-mode'
509 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
510 If you want to use Org-mode together with one of these other modes,
511 or more generally if you would like to move some Org-mode commands to
512 other keys, set this variable and configure the keys with the variable
513 `org-disputed-keys'.
515 This option is only relevant at load-time of Org-mode, and must be set
516 *before* org.el is loaded. Changing it requires a restart of Emacs to
517 become effective."
518 :group 'org-startup
519 :type 'boolean)
521 (defcustom org-use-extra-keys nil
522 "Non-nil means use extra key sequence definitions for certain commands.
523 This happens automatically if you run XEmacs or if `window-system'
524 is nil. This variable lets you do the same manually. You must
525 set it before loading org.
527 Example: on Carbon Emacs 22 running graphically, with an external
528 keyboard on a Powerbook, the default way of setting M-left might
529 not work for either Alt or ESC. Setting this variable will make
530 it work for ESC."
531 :group 'org-startup
532 :type 'boolean)
534 (if (fboundp 'defvaralias)
535 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
537 (defcustom org-disputed-keys
538 '(([(shift up)] . [(meta p)])
539 ([(shift down)] . [(meta n)])
540 ([(shift left)] . [(meta -)])
541 ([(shift right)] . [(meta +)])
542 ([(control shift right)] . [(meta shift +)])
543 ([(control shift left)] . [(meta shift -)]))
544 "Keys for which Org-mode and other modes compete.
545 This is an alist, cars are the default keys, second element specifies
546 the alternative to use when `org-replace-disputed-keys' is t.
548 Keys can be specified in any syntax supported by `define-key'.
549 The value of this option takes effect only at Org-mode's startup,
550 therefore you'll have to restart Emacs to apply it after changing."
551 :group 'org-startup
552 :type 'alist)
554 (defun org-key (key)
555 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
556 Or return the original if not disputed.
557 Also apply the translations defined in `org-xemacs-key-equivalents'."
558 (when org-replace-disputed-keys
559 (let* ((nkey (key-description key))
560 (x (org-find-if (lambda (x)
561 (equal (key-description (car x)) nkey))
562 org-disputed-keys)))
563 (setq key (if x (cdr x) key))))
564 (when (featurep 'xemacs)
565 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
566 key)
568 (defun org-find-if (predicate seq)
569 (catch 'exit
570 (while seq
571 (if (funcall predicate (car seq))
572 (throw 'exit (car seq))
573 (pop seq)))))
575 (defun org-defkey (keymap key def)
576 "Define a key, possibly translated, as returned by `org-key'."
577 (define-key keymap (org-key key) def))
579 (defcustom org-ellipsis nil
580 "The ellipsis to use in the Org-mode outline.
581 When nil, just use the standard three dots. When a string, use that instead,
582 When a face, use the standard 3 dots, but with the specified face.
583 The change affects only Org-mode (which will then use its own display table).
584 Changing this requires executing `M-x org-mode' in a buffer to become
585 effective."
586 :group 'org-startup
587 :type '(choice (const :tag "Default" nil)
588 (face :tag "Face" :value org-warning)
589 (string :tag "String" :value "...#")))
591 (defvar org-display-table nil
592 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
594 (defgroup org-keywords nil
595 "Keywords in Org-mode."
596 :tag "Org Keywords"
597 :group 'org)
599 (defcustom org-deadline-string "DEADLINE:"
600 "String to mark deadline entries.
601 A deadline is this string, followed by a time stamp. Should be a word,
602 terminated by a colon. You can insert a schedule keyword and
603 a timestamp with \\[org-deadline].
604 Changes become only effective after restarting Emacs."
605 :group 'org-keywords
606 :type 'string)
608 (defcustom org-scheduled-string "SCHEDULED:"
609 "String to mark scheduled TODO entries.
610 A schedule is this string, followed by a time stamp. Should be a word,
611 terminated by a colon. You can insert a schedule keyword and
612 a timestamp with \\[org-schedule].
613 Changes become only effective after restarting Emacs."
614 :group 'org-keywords
615 :type 'string)
617 (defcustom org-closed-string "CLOSED:"
618 "String used as the prefix for timestamps logging closing a TODO entry."
619 :group 'org-keywords
620 :type 'string)
622 (defcustom org-clock-string "CLOCK:"
623 "String used as prefix for timestamps clocking work hours on an item."
624 :group 'org-keywords
625 :type 'string)
627 (defcustom org-comment-string "COMMENT"
628 "Entries starting with this keyword will never be exported.
629 An entry can be toggled between COMMENT and normal with
630 \\[org-toggle-comment].
631 Changes become only effective after restarting Emacs."
632 :group 'org-keywords
633 :type 'string)
635 (defcustom org-quote-string "QUOTE"
636 "Entries starting with this keyword will be exported in fixed-width font.
637 Quoting applies only to the text in the entry following the headline, and does
638 not extend beyond the next headline, even if that is lower level.
639 An entry can be toggled between QUOTE and normal with
640 \\[org-toggle-fixed-width-section]."
641 :group 'org-keywords
642 :type 'string)
644 (defconst org-repeat-re
645 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
646 "Regular expression for specifying repeated events.
647 After a match, group 1 contains the repeat expression.")
649 (defgroup org-structure nil
650 "Options concerning the general structure of Org-mode files."
651 :tag "Org Structure"
652 :group 'org)
654 (defgroup org-reveal-location nil
655 "Options about how to make context of a location visible."
656 :tag "Org Reveal Location"
657 :group 'org-structure)
659 (defconst org-context-choice
660 '(choice
661 (const :tag "Always" t)
662 (const :tag "Never" nil)
663 (repeat :greedy t :tag "Individual contexts"
664 (cons
665 (choice :tag "Context"
666 (const agenda)
667 (const org-goto)
668 (const occur-tree)
669 (const tags-tree)
670 (const link-search)
671 (const mark-goto)
672 (const bookmark-jump)
673 (const isearch)
674 (const default))
675 (boolean))))
676 "Contexts for the reveal options.")
678 (defcustom org-show-hierarchy-above '((default . t))
679 "Non-nil means show full hierarchy when revealing a location.
680 Org-mode often shows locations in an org-mode file which might have
681 been invisible before. When this is set, the hierarchy of headings
682 above the exposed location is shown.
683 Turning this off for example for sparse trees makes them very compact.
684 Instead of t, this can also be an alist specifying this option for different
685 contexts. Valid contexts are
686 agenda when exposing an entry from the agenda
687 org-goto when using the command `org-goto' on key C-c C-j
688 occur-tree when using the command `org-occur' on key C-c /
689 tags-tree when constructing a sparse tree based on tags matches
690 link-search when exposing search matches associated with a link
691 mark-goto when exposing the jump goal of a mark
692 bookmark-jump when exposing a bookmark location
693 isearch when exiting from an incremental search
694 default default for all contexts not set explicitly"
695 :group 'org-reveal-location
696 :type org-context-choice)
698 (defcustom org-show-following-heading '((default . nil))
699 "Non-nil means show following heading when revealing a location.
700 Org-mode often shows locations in an org-mode file which might have
701 been invisible before. When this is set, the heading following the
702 match is shown.
703 Turning this off for example for sparse trees makes them very compact,
704 but makes it harder to edit the location of the match. In such a case,
705 use the command \\[org-reveal] to show more context.
706 Instead of t, this can also be an alist specifying this option for different
707 contexts. See `org-show-hierarchy-above' for valid contexts."
708 :group 'org-reveal-location
709 :type org-context-choice)
711 (defcustom org-show-siblings '((default . nil) (isearch t))
712 "Non-nil means show all sibling heading when revealing a location.
713 Org-mode often shows locations in an org-mode file which might have
714 been invisible before. When this is set, the sibling of the current entry
715 heading are all made visible. If `org-show-hierarchy-above' is t,
716 the same happens on each level of the hierarchy above the current entry.
718 By default this is on for the isearch context, off for all other contexts.
719 Turning this off for example for sparse trees makes them very compact,
720 but makes it harder to edit the location of the match. In such a case,
721 use the command \\[org-reveal] to show more context.
722 Instead of t, this can also be an alist specifying this option for different
723 contexts. See `org-show-hierarchy-above' for valid contexts."
724 :group 'org-reveal-location
725 :type org-context-choice)
727 (defcustom org-show-entry-below '((default . nil))
728 "Non-nil means show the entry below a headline when revealing a location.
729 Org-mode often shows locations in an org-mode file which might have
730 been invisible before. When this is set, the text below the headline that is
731 exposed is also shown.
733 By default this is off for all contexts.
734 Instead of t, this can also be an alist specifying this option for different
735 contexts. See `org-show-hierarchy-above' for valid contexts."
736 :group 'org-reveal-location
737 :type org-context-choice)
739 (defcustom org-indirect-buffer-display 'other-window
740 "How should indirect tree buffers be displayed?
741 This applies to indirect buffers created with the commands
742 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
743 Valid values are:
744 current-window Display in the current window
745 other-window Just display in another window.
746 dedicated-frame Create one new frame, and re-use it each time.
747 new-frame Make a new frame each time. Note that in this case
748 previously-made indirect buffers are kept, and you need to
749 kill these buffers yourself."
750 :group 'org-structure
751 :group 'org-agenda-windows
752 :type '(choice
753 (const :tag "In current window" current-window)
754 (const :tag "In current frame, other window" other-window)
755 (const :tag "Each time a new frame" new-frame)
756 (const :tag "One dedicated frame" dedicated-frame)))
758 (defcustom org-use-speed-commands nil
759 "Non-nil means activate single letter commands at beginning of a headline.
760 This may also be a function to test for appropriate locations where speed
761 commands should be active."
762 :group 'org-structure
763 :type '(choice
764 (const :tag "Never" nil)
765 (const :tag "At beginning of headline stars" t)
766 (function)))
768 (defcustom org-speed-commands-user nil
769 "Alist of additional speed commands.
770 This list will be checked before `org-speed-commands-default'
771 when the variable `org-use-speed-commands' is non-nil
772 and when the cursor is at the beginning of a headline.
773 The car if each entry is a string with a single letter, which must
774 be assigned to `self-insert-command' in the global map.
775 The cdr is either a command to be called interactively, a function
776 to be called, or a form to be evaluated.
777 An entry that is just a list with a single string will be interpreted
778 as a descriptive headline that will be added when listing the speed
779 commands in the Help buffer using the `?' speed command."
780 :group 'org-structure
781 :type '(repeat :value ("k" . ignore)
782 (choice :value ("k" . ignore)
783 (list :tag "Descriptive Headline" (string :tag "Headline"))
784 (cons :tag "Letter and Command"
785 (string :tag "Command letter")
786 (choice
787 (function)
788 (sexp))))))
790 (defgroup org-cycle nil
791 "Options concerning visibility cycling in Org-mode."
792 :tag "Org Cycle"
793 :group 'org-structure)
795 (defcustom org-cycle-skip-children-state-if-no-children t
796 "Non-nil means skip CHILDREN state in entries that don't have any."
797 :group 'org-cycle
798 :type 'boolean)
800 (defcustom org-cycle-max-level nil
801 "Maximum level which should still be subject to visibility cycling.
802 Levels higher than this will, for cycling, be treated as text, not a headline.
803 When `org-odd-levels-only' is set, a value of N in this variable actually
804 means 2N-1 stars as the limiting headline.
805 When nil, cycle all levels.
806 Note that the limiting level of cycling is also influenced by
807 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
808 `org-inlinetask-min-level' is, cycling will be limited to levels one less
809 than its value."
810 :group 'org-cycle
811 :type '(choice
812 (const :tag "No limit" nil)
813 (integer :tag "Maximum level")))
815 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
816 "Names of drawers. Drawers are not opened by cycling on the headline above.
817 Drawers only open with a TAB on the drawer line itself. A drawer looks like
818 this:
819 :DRAWERNAME:
820 .....
821 :END:
822 The drawer \"PROPERTIES\" is special for capturing properties through
823 the property API.
825 Drawers can be defined on the per-file basis with a line like:
827 #+DRAWERS: HIDDEN STATE PROPERTIES"
828 :group 'org-structure
829 :group 'org-cycle
830 :type '(repeat (string :tag "Drawer Name")))
832 (defcustom org-hide-block-startup nil
833 "Non-nil means entering Org-mode will fold all blocks.
834 This can also be set in on a per-file basis with
836 #+STARTUP: hideblocks
837 #+STARTUP: showblocks"
838 :group 'org-startup
839 :group 'org-cycle
840 :type 'boolean)
842 (defcustom org-cycle-global-at-bob nil
843 "Cycle globally if cursor is at beginning of buffer and not at a headline.
844 This makes it possible to do global cycling without having to use S-TAB or
845 \\[universal-argument] TAB. For this special case to work, the first line \
846 of the buffer
847 must not be a headline - it may be empty or some other text. When used in
848 this way, `org-cycle-hook' is disables temporarily, to make sure the
849 cursor stays at the beginning of the buffer.
850 When this option is nil, don't do anything special at the beginning
851 of the buffer."
852 :group 'org-cycle
853 :type 'boolean)
855 (defcustom org-cycle-level-after-item/entry-creation t
856 "Non-nil means cycle entry level or item indentation in new empty entries.
858 When the cursor is at the end of an empty headline, i.e with only stars
859 and maybe a TODO keyword, TAB will then switch the entry to become a child,
860 and then all possible ancestor states, before returning to the original state.
861 This makes data entry extremely fast: M-RET to create a new headline,
862 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
864 When the cursor is at the end of an empty plain list item, one TAB will
865 make it a subitem, two or more tabs will back up to make this an item
866 higher up in the item hierarchy."
867 :group 'org-cycle
868 :type 'boolean)
870 (defcustom org-cycle-emulate-tab t
871 "Where should `org-cycle' emulate TAB.
872 nil Never
873 white Only in completely white lines
874 whitestart Only at the beginning of lines, before the first non-white char
875 t Everywhere except in headlines
876 exc-hl-bol Everywhere except at the start of a headline
877 If TAB is used in a place where it does not emulate TAB, the current subtree
878 visibility is cycled."
879 :group 'org-cycle
880 :type '(choice (const :tag "Never" nil)
881 (const :tag "Only in completely white lines" white)
882 (const :tag "Before first char in a line" whitestart)
883 (const :tag "Everywhere except in headlines" t)
884 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
887 (defcustom org-cycle-separator-lines 2
888 "Number of empty lines needed to keep an empty line between collapsed trees.
889 If you leave an empty line between the end of a subtree and the following
890 headline, this empty line is hidden when the subtree is folded.
891 Org-mode will leave (exactly) one empty line visible if the number of
892 empty lines is equal or larger to the number given in this variable.
893 So the default 2 means at least 2 empty lines after the end of a subtree
894 are needed to produce free space between a collapsed subtree and the
895 following headline.
897 If the number is negative, and the number of empty lines is at least -N,
898 all empty lines are shown.
900 Special case: when 0, never leave empty lines in collapsed view."
901 :group 'org-cycle
902 :type 'integer)
903 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
905 (defcustom org-pre-cycle-hook nil
906 "Hook that is run before visibility cycling is happening.
907 The function(s) in this hook must accept a single argument which indicates
908 the new state that will be set right after running this hook. The
909 argument is a symbol. Before a global state change, it can have the values
910 `overview', `content', or `all'. Before a local state change, it can have
911 the values `folded', `children', or `subtree'."
912 :group 'org-cycle
913 :type 'hook)
915 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
916 org-cycle-hide-drawers
917 org-cycle-show-empty-lines
918 org-optimize-window-after-visibility-change)
919 "Hook that is run after `org-cycle' has changed the buffer visibility.
920 The function(s) in this hook must accept a single argument which indicates
921 the new state that was set by the most recent `org-cycle' command. The
922 argument is a symbol. After a global state change, it can have the values
923 `overview', `content', or `all'. After a local state change, it can have
924 the values `folded', `children', or `subtree'."
925 :group 'org-cycle
926 :type 'hook)
928 (defgroup org-edit-structure nil
929 "Options concerning structure editing in Org-mode."
930 :tag "Org Edit Structure"
931 :group 'org-structure)
933 (defcustom org-odd-levels-only nil
934 "Non-nil means skip even levels and only use odd levels for the outline.
935 This has the effect that two stars are being added/taken away in
936 promotion/demotion commands. It also influences how levels are
937 handled by the exporters.
938 Changing it requires restart of `font-lock-mode' to become effective
939 for fontification also in regions already fontified.
940 You may also set this on a per-file basis by adding one of the following
941 lines to the buffer:
943 #+STARTUP: odd
944 #+STARTUP: oddeven"
945 :group 'org-edit-structure
946 :group 'org-appearance
947 :type 'boolean)
949 (defcustom org-adapt-indentation t
950 "Non-nil means adapt indentation to outline node level.
952 When this variable is set, Org assumes that you write outlines by
953 indenting text in each node to align with the headline (after the stars).
954 The following issues are influenced by this variable:
956 - When this is set and the *entire* text in an entry is indented, the
957 indentation is increased by one space in a demotion command, and
958 decreased by one in a promotion command. If any line in the entry
959 body starts with text at column 0, indentation is not changed at all.
961 - Property drawers and planning information is inserted indented when
962 this variable s set. When nil, they will not be indented.
964 - TAB indents a line relative to context. The lines below a headline
965 will be indented when this variable is set.
967 Note that this is all about true indentation, by adding and removing
968 space characters. See also `org-indent.el' which does level-dependent
969 indentation in a virtual way, i.e. at display time in Emacs."
970 :group 'org-edit-structure
971 :type 'boolean)
973 (defcustom org-special-ctrl-a/e nil
974 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
976 When t, `C-a' will bring back the cursor to the beginning of the
977 headline text, i.e. after the stars and after a possible TODO keyword.
978 In an item, this will be the position after the bullet.
979 When the cursor is already at that position, another `C-a' will bring
980 it to the beginning of the line.
982 `C-e' will jump to the end of the headline, ignoring the presence of tags
983 in the headline. A second `C-e' will then jump to the true end of the
984 line, after any tags. This also means that, when this variable is
985 non-nil, `C-e' also will never jump beyond the end of the heading of a
986 folded section, i.e. not after the ellipses.
988 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
989 going to the true line boundary first. Only a directly following, identical
990 keypress will bring the cursor to the special positions.
992 This may also be a cons cell where the behavior for `C-a' and `C-e' is
993 set separately."
994 :group 'org-edit-structure
995 :type '(choice
996 (const :tag "off" nil)
997 (const :tag "on: after stars/bullet and before tags first" t)
998 (const :tag "reversed: true line boundary first" reversed)
999 (cons :tag "Set C-a and C-e separately"
1000 (choice :tag "Special C-a"
1001 (const :tag "off" nil)
1002 (const :tag "on: after stars/bullet first" t)
1003 (const :tag "reversed: before stars/bullet first" reversed))
1004 (choice :tag "Special C-e"
1005 (const :tag "off" nil)
1006 (const :tag "on: before tags first" t)
1007 (const :tag "reversed: after tags first" reversed)))))
1008 (if (fboundp 'defvaralias)
1009 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1011 (defcustom org-special-ctrl-k nil
1012 "Non-nil means `C-k' will behave specially in headlines.
1013 When nil, `C-k' will call the default `kill-line' command.
1014 When t, the following will happen while the cursor is in the headline:
1016 - When the cursor is at the beginning of a headline, kill the entire
1017 line and possible the folded subtree below the line.
1018 - When in the middle of the headline text, kill the headline up to the tags.
1019 - When after the headline text, kill the tags."
1020 :group 'org-edit-structure
1021 :type 'boolean)
1023 (defcustom org-ctrl-k-protect-subtree nil
1024 "Non-nil means, do not delete a hidden subtree with C-k.
1025 When set to the symbol `error', simply throw an error when C-k is
1026 used to kill (part-of) a headline that has hidden text behind it.
1027 Any other non-nil value will result in a query to the user, if it is
1028 OK to kill that hidden subtree. When nil, kill without remorse."
1029 :group 'org-edit-structure
1030 :type '(choice
1031 (const :tag "Do not protect hidden subtrees" nil)
1032 (const :tag "Protect hidden subtrees with a security query" t)
1033 (const :tag "Never kill a hidden subtree with C-k" error)))
1035 (defcustom org-yank-folded-subtrees t
1036 "Non-nil means when yanking subtrees, fold them.
1037 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1038 it starts with a heading and all other headings in it are either children
1039 or siblings, then fold all the subtrees. However, do this only if no
1040 text after the yank would be swallowed into a folded tree by this action."
1041 :group 'org-edit-structure
1042 :type 'boolean)
1044 (defcustom org-yank-adjusted-subtrees nil
1045 "Non-nil means when yanking subtrees, adjust the level.
1046 With this setting, `org-paste-subtree' is used to insert the subtree, see
1047 this function for details."
1048 :group 'org-edit-structure
1049 :type 'boolean)
1051 (defcustom org-M-RET-may-split-line '((default . t))
1052 "Non-nil means M-RET will split the line at the cursor position.
1053 When nil, it will go to the end of the line before making a
1054 new line.
1055 You may also set this option in a different way for different
1056 contexts. Valid contexts are:
1058 headline when creating a new headline
1059 item when creating a new item
1060 table in a table field
1061 default the value to be used for all contexts not explicitly
1062 customized"
1063 :group 'org-structure
1064 :group 'org-table
1065 :type '(choice
1066 (const :tag "Always" t)
1067 (const :tag "Never" nil)
1068 (repeat :greedy t :tag "Individual contexts"
1069 (cons
1070 (choice :tag "Context"
1071 (const headline)
1072 (const item)
1073 (const table)
1074 (const default))
1075 (boolean)))))
1078 (defcustom org-insert-heading-respect-content nil
1079 "Non-nil means insert new headings after the current subtree.
1080 When nil, the new heading is created directly after the current line.
1081 The commands \\[org-insert-heading-respect-content] and
1082 \\[org-insert-todo-heading-respect-content] turn this variable on
1083 for the duration of the command."
1084 :group 'org-structure
1085 :type 'boolean)
1087 (defcustom org-blank-before-new-entry '((heading . auto)
1088 (plain-list-item . auto))
1089 "Should `org-insert-heading' leave a blank line before new heading/item?
1090 The value is an alist, with `heading' and `plain-list-item' as car,
1091 and a boolean flag as cdr. The cdr may also be the symbol `auto', and then
1092 Org will look at the surrounding headings/items and try to make an
1093 intelligent decision whether to insert a blank line or not.
1095 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1096 set, the setting here is ignored and no empty line is inserted, to avoid
1097 breaking the list structure."
1098 :group 'org-edit-structure
1099 :type '(list
1100 (cons (const heading)
1101 (choice (const :tag "Never" nil)
1102 (const :tag "Always" t)
1103 (const :tag "Auto" auto)))
1104 (cons (const plain-list-item)
1105 (choice (const :tag "Never" nil)
1106 (const :tag "Always" t)
1107 (const :tag "Auto" auto)))))
1109 (defcustom org-insert-heading-hook nil
1110 "Hook being run after inserting a new heading."
1111 :group 'org-edit-structure
1112 :type 'hook)
1114 (defcustom org-enable-fixed-width-editor t
1115 "Non-nil means lines starting with \":\" are treated as fixed-width.
1116 This currently only means they are never auto-wrapped.
1117 When nil, such lines will be treated like ordinary lines.
1118 See also the QUOTE keyword."
1119 :group 'org-edit-structure
1120 :type 'boolean)
1122 (defcustom org-goto-auto-isearch t
1123 "Non-nil means typing characters in `org-goto' starts incremental search."
1124 :group 'org-edit-structure
1125 :type 'boolean)
1127 (defgroup org-sparse-trees nil
1128 "Options concerning sparse trees in Org-mode."
1129 :tag "Org Sparse Trees"
1130 :group 'org-structure)
1132 (defcustom org-highlight-sparse-tree-matches t
1133 "Non-nil means highlight all matches that define a sparse tree.
1134 The highlights will automatically disappear the next time the buffer is
1135 changed by an edit command."
1136 :group 'org-sparse-trees
1137 :type 'boolean)
1139 (defcustom org-remove-highlights-with-change t
1140 "Non-nil means any change to the buffer will remove temporary highlights.
1141 Such highlights are created by `org-occur' and `org-clock-display'.
1142 When nil, `C-c C-c needs to be used to get rid of the highlights.
1143 The highlights created by `org-preview-latex-fragment' always need
1144 `C-c C-c' to be removed."
1145 :group 'org-sparse-trees
1146 :group 'org-time
1147 :type 'boolean)
1150 (defcustom org-occur-hook '(org-first-headline-recenter)
1151 "Hook that is run after `org-occur' has constructed a sparse tree.
1152 This can be used to recenter the window to show as much of the structure
1153 as possible."
1154 :group 'org-sparse-trees
1155 :type 'hook)
1157 (defgroup org-imenu-and-speedbar nil
1158 "Options concerning imenu and speedbar in Org-mode."
1159 :tag "Org Imenu and Speedbar"
1160 :group 'org-structure)
1162 (defcustom org-imenu-depth 2
1163 "The maximum level for Imenu access to Org-mode headlines.
1164 This also applied for speedbar access."
1165 :group 'org-imenu-and-speedbar
1166 :type 'integer)
1168 (defgroup org-table nil
1169 "Options concerning tables in Org-mode."
1170 :tag "Org Table"
1171 :group 'org)
1173 (defcustom org-enable-table-editor 'optimized
1174 "Non-nil means lines starting with \"|\" are handled by the table editor.
1175 When nil, such lines will be treated like ordinary lines.
1177 When equal to the symbol `optimized', the table editor will be optimized to
1178 do the following:
1179 - Automatic overwrite mode in front of whitespace in table fields.
1180 This makes the structure of the table stay in tact as long as the edited
1181 field does not exceed the column width.
1182 - Minimize the number of realigns. Normally, the table is aligned each time
1183 TAB or RET are pressed to move to another field. With optimization this
1184 happens only if changes to a field might have changed the column width.
1185 Optimization requires replacing the functions `self-insert-command',
1186 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1187 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1188 very good at guessing when a re-align will be necessary, but you can always
1189 force one with \\[org-ctrl-c-ctrl-c].
1191 If you would like to use the optimized version in Org-mode, but the
1192 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1194 This variable can be used to turn on and off the table editor during a session,
1195 but in order to toggle optimization, a restart is required.
1197 See also the variable `org-table-auto-blank-field'."
1198 :group 'org-table
1199 :type '(choice
1200 (const :tag "off" nil)
1201 (const :tag "on" t)
1202 (const :tag "on, optimized" optimized)))
1204 (defcustom org-self-insert-cluster-for-undo t
1205 "Non-nil means cluster self-insert commands for undo when possible.
1206 If this is set, then, like in the Emacs command loop, 20 consecutive
1207 characters will be undone together.
1208 This is configurable, because there is some impact on typing performance."
1209 :group 'org-table
1210 :type 'boolean)
1212 (defcustom org-table-tab-recognizes-table.el t
1213 "Non-nil means TAB will automatically notice a table.el table.
1214 When it sees such a table, it moves point into it and - if necessary -
1215 calls `table-recognize-table'."
1216 :group 'org-table-editing
1217 :type 'boolean)
1219 (defgroup org-link nil
1220 "Options concerning links in Org-mode."
1221 :tag "Org Link"
1222 :group 'org)
1224 (defvar org-link-abbrev-alist-local nil
1225 "Buffer-local version of `org-link-abbrev-alist', which see.
1226 The value of this is taken from the #+LINK lines.")
1227 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1229 (defcustom org-link-abbrev-alist nil
1230 "Alist of link abbreviations.
1231 The car of each element is a string, to be replaced at the start of a link.
1232 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1233 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1235 [[linkkey:tag][description]]
1237 The 'linkkey' must be a word word, starting with a letter, followed
1238 by letters, numbers, '-' or '_'.
1240 If REPLACE is a string, the tag will simply be appended to create the link.
1241 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1242 the placeholder \"%h\" will cause a url-encoded version of the tag to
1243 be inserted at that point (see the function `url-hexify-string').
1245 REPLACE may also be a function that will be called with the tag as the
1246 only argument to create the link, which should be returned as a string.
1248 See the manual for examples."
1249 :group 'org-link
1250 :type '(repeat
1251 (cons
1252 (string :tag "Protocol")
1253 (choice
1254 (string :tag "Format")
1255 (function)))))
1257 (defcustom org-descriptive-links t
1258 "Non-nil means hide link part and only show description of bracket links.
1259 Bracket links are like [[link][description]]. This variable sets the initial
1260 state in new org-mode buffers. The setting can then be toggled on a
1261 per-buffer basis from the Org->Hyperlinks menu."
1262 :group 'org-link
1263 :type 'boolean)
1265 (defcustom org-link-file-path-type 'adaptive
1266 "How the path name in file links should be stored.
1267 Valid values are:
1269 relative Relative to the current directory, i.e. the directory of the file
1270 into which the link is being inserted.
1271 absolute Absolute path, if possible with ~ for home directory.
1272 noabbrev Absolute path, no abbreviation of home directory.
1273 adaptive Use relative path for files in the current directory and sub-
1274 directories of it. For other files, use an absolute path."
1275 :group 'org-link
1276 :type '(choice
1277 (const relative)
1278 (const absolute)
1279 (const noabbrev)
1280 (const adaptive)))
1282 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1283 "Types of links that should be activated in Org-mode files.
1284 This is a list of symbols, each leading to the activation of a certain link
1285 type. In principle, it does not hurt to turn on most link types - there may
1286 be a small gain when turning off unused link types. The types are:
1288 bracket The recommended [[link][description]] or [[link]] links with hiding.
1289 angle Links in angular brackets that may contain whitespace like
1290 <bbdb:Carsten Dominik>.
1291 plain Plain links in normal text, no whitespace, like http://google.com.
1292 radio Text that is matched by a radio target, see manual for details.
1293 tag Tag settings in a headline (link to tag search).
1294 date Time stamps (link to calendar).
1295 footnote Footnote labels.
1297 Changing this variable requires a restart of Emacs to become effective."
1298 :group 'org-link
1299 :type '(set :greedy t
1300 (const :tag "Double bracket links" bracket)
1301 (const :tag "Angular bracket links" angle)
1302 (const :tag "Plain text links" plain)
1303 (const :tag "Radio target matches" radio)
1304 (const :tag "Tags" tag)
1305 (const :tag "Timestamps" date)
1306 (const :tag "Footnotes" footnote)))
1308 (defcustom org-make-link-description-function nil
1309 "Function to use to generate link descriptions from links.
1310 If nil the link location will be used. This function must take
1311 two parameters; the first is the link and the second the
1312 description `org-insert-link' has generated, and should return the
1313 description to use."
1314 :group 'org-link
1315 :type 'function)
1317 (defgroup org-link-store nil
1318 "Options concerning storing links in Org-mode."
1319 :tag "Org Store Link"
1320 :group 'org-link)
1322 (defcustom org-email-link-description-format "Email %c: %.30s"
1323 "Format of the description part of a link to an email or usenet message.
1324 The following %-escapes will be replaced by corresponding information:
1326 %F full \"From\" field
1327 %f name, taken from \"From\" field, address if no name
1328 %T full \"To\" field
1329 %t first name in \"To\" field, address if no name
1330 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1331 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1332 %s subject
1333 %d date
1334 %m message-id.
1336 You may use normal field width specification between the % and the letter.
1337 This is for example useful to limit the length of the subject.
1339 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1340 :group 'org-link-store
1341 :type 'string)
1343 (defcustom org-from-is-user-regexp
1344 (let (r1 r2)
1345 (when (and user-mail-address (not (string= user-mail-address "")))
1346 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1347 (when (and user-full-name (not (string= user-full-name "")))
1348 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1349 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1350 "Regexp matched against the \"From:\" header of an email or usenet message.
1351 It should match if the message is from the user him/herself."
1352 :group 'org-link-store
1353 :type 'regexp)
1355 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1356 "Non-nil means storing a link to an Org file will use entry IDs.
1358 Note that before this variable is even considered, org-id must be loaded,
1359 so please customize `org-modules' and turn it on.
1361 The variable can have the following values:
1363 t Create an ID if needed to make a link to the current entry.
1365 create-if-interactive
1366 If `org-store-link' is called directly (interactively, as a user
1367 command), do create an ID to support the link. But when doing the
1368 job for remember, only use the ID if it already exists. The
1369 purpose of this setting is to avoid proliferation of unwanted
1370 IDs, just because you happen to be in an Org file when you
1371 call `org-remember' that automatically and preemptively
1372 creates a link. If you do want to get an ID link in a remember
1373 template to an entry not having an ID, create it first by
1374 explicitly creating a link to it, using `C-c C-l' first.
1376 create-if-interactive-and-no-custom-id
1377 Like create-if-interactive, but do not create an ID if there is
1378 a CUSTOM_ID property defined in the entry. This is the default.
1380 use-existing
1381 Use existing ID, do not create one.
1383 nil Never use an ID to make a link, instead link using a text search for
1384 the headline text."
1385 :group 'org-link-store
1386 :type '(choice
1387 (const :tag "Create ID to make link" t)
1388 (const :tag "Create if storing link interactively"
1389 create-if-interactive)
1390 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1391 create-if-interactive-and-no-custom-id)
1392 (const :tag "Only use existing" use-existing)
1393 (const :tag "Do not use ID to create link" nil)))
1395 (defcustom org-context-in-file-links t
1396 "Non-nil means file links from `org-store-link' contain context.
1397 A search string will be added to the file name with :: as separator and
1398 used to find the context when the link is activated by the command
1399 `org-open-at-point'. When this option is t, the entire active region
1400 will be placed in the search string of the file link. If set to a
1401 positive integer, only the first n lines of context will be stored.
1403 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1404 negates this setting for the duration of the command."
1405 :group 'org-link-store
1406 :type '(choice boolean integer))
1408 (defcustom org-keep-stored-link-after-insertion nil
1409 "Non-nil means keep link in list for entire session.
1411 The command `org-store-link' adds a link pointing to the current
1412 location to an internal list. These links accumulate during a session.
1413 The command `org-insert-link' can be used to insert links into any
1414 Org-mode file (offering completion for all stored links). When this
1415 option is nil, every link which has been inserted once using \\[org-insert-link]
1416 will be removed from the list, to make completing the unused links
1417 more efficient."
1418 :group 'org-link-store
1419 :type 'boolean)
1421 (defgroup org-link-follow nil
1422 "Options concerning following links in Org-mode."
1423 :tag "Org Follow Link"
1424 :group 'org-link)
1426 (defcustom org-link-translation-function nil
1427 "Function to translate links with different syntax to Org syntax.
1428 This can be used to translate links created for example by the Planner
1429 or emacs-wiki packages to Org syntax.
1430 The function must accept two parameters, a TYPE containing the link
1431 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1432 which is everything after the link protocol. It should return a cons
1433 with possibly modified values of type and path.
1434 Org contains a function for this, so if you set this variable to
1435 `org-translate-link-from-planner', you should be able follow many
1436 links created by planner."
1437 :group 'org-link-follow
1438 :type 'function)
1440 (defcustom org-follow-link-hook nil
1441 "Hook that is run after a link has been followed."
1442 :group 'org-link-follow
1443 :type 'hook)
1445 (defcustom org-tab-follows-link nil
1446 "Non-nil means on links TAB will follow the link.
1447 Needs to be set before org.el is loaded.
1448 This really should not be used, it does not make sense, and the
1449 implementation is bad."
1450 :group 'org-link-follow
1451 :type 'boolean)
1453 (defcustom org-return-follows-link nil
1454 "Non-nil means on links RET will follow the link."
1455 :group 'org-link-follow
1456 :type 'boolean)
1458 (defcustom org-mouse-1-follows-link
1459 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1460 "Non-nil means mouse-1 on a link will follow the link.
1461 A longer mouse click will still set point. Does not work on XEmacs.
1462 Needs to be set before org.el is loaded."
1463 :group 'org-link-follow
1464 :type 'boolean)
1466 (defcustom org-mark-ring-length 4
1467 "Number of different positions to be recorded in the ring.
1468 Changing this requires a restart of Emacs to work correctly."
1469 :group 'org-link-follow
1470 :type 'integer)
1472 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1473 "Non-nil means internal links in Org files must exactly match a headline.
1474 When nil, the link search tries to match a phrase with all words
1475 in the search text."
1476 :group 'org-link-follow
1477 :type '(choice
1478 (const :tag "Use fuzy text search" nil)
1479 (const :tag "Match only exact headline" t)
1480 (const :tag "Match extact headline or query to create it"
1481 query-to-create)))
1483 (defcustom org-link-frame-setup
1484 '((vm . vm-visit-folder-other-frame)
1485 (gnus . org-gnus-no-new-news)
1486 (file . find-file-other-window)
1487 (wl . wl-other-frame))
1488 "Setup the frame configuration for following links.
1489 When following a link with Emacs, it may often be useful to display
1490 this link in another window or frame. This variable can be used to
1491 set this up for the different types of links.
1492 For VM, use any of
1493 `vm-visit-folder'
1494 `vm-visit-folder-other-window'
1495 `vm-visit-folder-other-frame'
1496 For Gnus, use any of
1497 `gnus'
1498 `gnus-other-frame'
1499 `org-gnus-no-new-news'
1500 For FILE, use any of
1501 `find-file'
1502 `find-file-other-window'
1503 `find-file-other-frame'
1504 For Wanderlust use any of
1505 `wl'
1506 `wl-other-frame'
1507 For the calendar, use the variable `calendar-setup'.
1508 For BBDB, it is currently only possible to display the matches in
1509 another window."
1510 :group 'org-link-follow
1511 :type '(list
1512 (cons (const vm)
1513 (choice
1514 (const vm-visit-folder)
1515 (const vm-visit-folder-other-window)
1516 (const vm-visit-folder-other-frame)))
1517 (cons (const gnus)
1518 (choice
1519 (const gnus)
1520 (const gnus-other-frame)
1521 (const org-gnus-no-new-news)))
1522 (cons (const file)
1523 (choice
1524 (const find-file)
1525 (const find-file-other-window)
1526 (const find-file-other-frame)))
1527 (cons (const wl)
1528 (choice
1529 (const wl)
1530 (const wl-other-frame)))))
1532 (defcustom org-display-internal-link-with-indirect-buffer nil
1533 "Non-nil means use indirect buffer to display infile links.
1534 Activating internal links (from one location in a file to another location
1535 in the same file) normally just jumps to the location. When the link is
1536 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1537 is displayed in
1538 another window. When this option is set, the other window actually displays
1539 an indirect buffer clone of the current buffer, to avoid any visibility
1540 changes to the current buffer."
1541 :group 'org-link-follow
1542 :type 'boolean)
1544 (defcustom org-open-non-existing-files nil
1545 "Non-nil means `org-open-file' will open non-existing files.
1546 When nil, an error will be generated.
1547 This variable applies only to external applications because they
1548 might choke on non-existing files. If the link is to a file that
1549 will be opened in Emacs, the variable is ignored."
1550 :group 'org-link-follow
1551 :type 'boolean)
1553 (defcustom org-open-directory-means-index-dot-org nil
1554 "Non-nil means a link to a directory really means to index.org.
1555 When nil, following a directory link will run dired or open a finder/explorer
1556 window on that directory."
1557 :group 'org-link-follow
1558 :type 'boolean)
1560 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1561 "Function and arguments to call for following mailto links.
1562 This is a list with the first element being a Lisp function, and the
1563 remaining elements being arguments to the function. In string arguments,
1564 %a will be replaced by the address, and %s will be replaced by the subject
1565 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1566 :group 'org-link-follow
1567 :type '(choice
1568 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1569 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1570 (const :tag "message-mail" (message-mail "%a" "%s"))
1571 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1573 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1574 "Non-nil means ask for confirmation before executing shell links.
1575 Shell links can be dangerous: just think about a link
1577 [[shell:rm -rf ~/*][Google Search]]
1579 This link would show up in your Org-mode document as \"Google Search\",
1580 but really it would remove your entire home directory.
1581 Therefore we advise against setting this variable to nil.
1582 Just change it to `y-or-n-p' if you want to confirm with a
1583 single keystroke rather than having to type \"yes\"."
1584 :group 'org-link-follow
1585 :type '(choice
1586 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1587 (const :tag "with y-or-n (faster)" y-or-n-p)
1588 (const :tag "no confirmation (dangerous)" nil)))
1589 (put 'org-confirm-shell-link-function
1590 'safe-local-variable
1591 '(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1593 (defcustom org-confirm-shell-link-not-regexp ""
1594 "A regexp to skip confirmation for shell links."
1595 :group 'org-link-follow
1596 :type 'regexp)
1598 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1599 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1600 Elisp links can be dangerous: just think about a link
1602 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1604 This link would show up in your Org-mode document as \"Google Search\",
1605 but really it would remove your entire home directory.
1606 Therefore we advise against setting this variable to nil.
1607 Just change it to `y-or-n-p' if you want to confirm with a
1608 single keystroke rather than having to type \"yes\"."
1609 :group 'org-link-follow
1610 :type '(choice
1611 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1612 (const :tag "with y-or-n (faster)" y-or-n-p)
1613 (const :tag "no confirmation (dangerous)" nil)))
1614 (put 'org-confirm-shell-link-function
1615 'safe-local-variable
1616 '(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1618 (defcustom org-confirm-elisp-link-not-regexp ""
1619 "A regexp to skip confirmation for Elisp links."
1620 :group 'org-link-follow
1621 :type 'regexp)
1623 (defconst org-file-apps-defaults-gnu
1624 '((remote . emacs)
1625 (system . mailcap)
1626 (t . mailcap))
1627 "Default file applications on a UNIX or GNU/Linux system.
1628 See `org-file-apps'.")
1630 (defconst org-file-apps-defaults-macosx
1631 '((remote . emacs)
1632 (t . "open %s")
1633 (system . "open %s")
1634 ("ps.gz" . "gv %s")
1635 ("eps.gz" . "gv %s")
1636 ("dvi" . "xdvi %s")
1637 ("fig" . "xfig %s"))
1638 "Default file applications on a MacOS X system.
1639 The system \"open\" is known as a default, but we use X11 applications
1640 for some files for which the OS does not have a good default.
1641 See `org-file-apps'.")
1643 (defconst org-file-apps-defaults-windowsnt
1644 (list
1645 '(remote . emacs)
1646 (cons t
1647 (list (if (featurep 'xemacs)
1648 'mswindows-shell-execute
1649 'w32-shell-execute)
1650 "open" 'file))
1651 (cons 'system
1652 (list (if (featurep 'xemacs)
1653 'mswindows-shell-execute
1654 'w32-shell-execute)
1655 "open" 'file)))
1656 "Default file applications on a Windows NT system.
1657 The system \"open\" is used for most files.
1658 See `org-file-apps'.")
1660 (defcustom org-file-apps
1662 (auto-mode . emacs)
1663 ("\\.mm\\'" . default)
1664 ("\\.x?html?\\'" . default)
1665 ("\\.pdf\\'" . default)
1667 "External applications for opening `file:path' items in a document.
1668 Org-mode uses system defaults for different file types, but
1669 you can use this variable to set the application for a given file
1670 extension. The entries in this list are cons cells where the car identifies
1671 files and the cdr the corresponding command. Possible values for the
1672 file identifier are
1673 \"string\" A string as a file identifier can be interpreted in different
1674 ways, depending on its contents:
1676 - Alphanumeric characters only:
1677 Match links with this file extension.
1678 Example: (\"pdf\" . \"evince %s\")
1679 to open PDFs with evince.
1681 - Regular expression: Match links where the
1682 filename matches the regexp. If you want to
1683 use groups here, use shy groups.
1685 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1686 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1687 to open *.html and *.xhtml with firefox.
1689 - Regular expression which contains (non-shy) groups:
1690 Match links where the whole link, including \"::\", and
1691 anything after that, matches the regexp.
1692 In a custom command string, %1, %2, etc. are replaced with
1693 the parts of the link that were matched by the groups.
1694 For backwards compatibility, if a command string is given
1695 that does not use any of the group matches, this case is
1696 handled identically to the second one (i.e. match against
1697 file name only).
1698 In a custom lisp form, you can access the group matches with
1699 (match-string n link).
1701 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1702 to open [[file:document.pdf::5]] with evince at page 5.
1704 `directory' Matches a directory
1705 `remote' Matches a remote file, accessible through tramp or efs.
1706 Remote files most likely should be visited through Emacs
1707 because external applications cannot handle such paths.
1708 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1709 so all files Emacs knows how to handle. Using this with
1710 command `emacs' will open most files in Emacs. Beware that this
1711 will also open html files inside Emacs, unless you add
1712 (\"html\" . default) to the list as well.
1713 t Default for files not matched by any of the other options.
1714 `system' The system command to open files, like `open' on Windows
1715 and Mac OS X, and mailcap under GNU/Linux. This is the command
1716 that will be selected if you call `C-c C-o' with a double
1717 \\[universal-argument] \\[universal-argument] prefix.
1719 Possible values for the command are:
1720 `emacs' The file will be visited by the current Emacs process.
1721 `default' Use the default application for this file type, which is the
1722 association for t in the list, most likely in the system-specific
1723 part.
1724 This can be used to overrule an unwanted setting in the
1725 system-specific variable.
1726 `system' Use the system command for opening files, like \"open\".
1727 This command is specified by the entry whose car is `system'.
1728 Most likely, the system-specific version of this variable
1729 does define this command, but you can overrule/replace it
1730 here.
1731 string A command to be executed by a shell; %s will be replaced
1732 by the path to the file.
1733 sexp A Lisp form which will be evaluated. The file path will
1734 be available in the Lisp variable `file'.
1735 For more examples, see the system specific constants
1736 `org-file-apps-defaults-macosx'
1737 `org-file-apps-defaults-windowsnt'
1738 `org-file-apps-defaults-gnu'."
1739 :group 'org-link-follow
1740 :type '(repeat
1741 (cons (choice :value ""
1742 (string :tag "Extension")
1743 (const :tag "System command to open files" system)
1744 (const :tag "Default for unrecognized files" t)
1745 (const :tag "Remote file" remote)
1746 (const :tag "Links to a directory" directory)
1747 (const :tag "Any files that have Emacs modes"
1748 auto-mode))
1749 (choice :value ""
1750 (const :tag "Visit with Emacs" emacs)
1751 (const :tag "Use default" default)
1752 (const :tag "Use the system command" system)
1753 (string :tag "Command")
1754 (sexp :tag "Lisp form")))))
1758 (defgroup org-refile nil
1759 "Options concerning refiling entries in Org-mode."
1760 :tag "Org Refile"
1761 :group 'org)
1763 (defcustom org-directory "~/org"
1764 "Directory with org files.
1765 This is just a default location to look for Org files. There is no need
1766 at all to put your files into this directory. It is only used in the
1767 following situations:
1769 1. When a remember template specifies a target file that is not an
1770 absolute path. The path will then be interpreted relative to
1771 `org-directory'
1772 2. When a remember note is filed away in an interactive way (when exiting the
1773 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1774 with `org-directory' as the default path."
1775 :group 'org-refile
1776 :group 'org-remember
1777 :type 'directory)
1779 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1780 "Default target for storing notes.
1781 Used as a fall back file for org-remember.el and org-capture.el, for
1782 templates that do not specify a target file."
1783 :group 'org-refile
1784 :group 'org-remember
1785 :type '(choice
1786 (const :tag "Default from remember-data-file" nil)
1787 file))
1789 (defcustom org-goto-interface 'outline
1790 "The default interface to be used for `org-goto'.
1791 Allowed values are:
1792 outline The interface shows an outline of the relevant file
1793 and the correct heading is found by moving through
1794 the outline or by searching with incremental search.
1795 outline-path-completion Headlines in the current buffer are offered via
1796 completion. This is the interface also used by
1797 the refile command."
1798 :group 'org-refile
1799 :type '(choice
1800 (const :tag "Outline" outline)
1801 (const :tag "Outline-path-completion" outline-path-completion)))
1803 (defcustom org-goto-max-level 5
1804 "Maximum target level when running `org-goto' with refile interface."
1805 :group 'org-refile
1806 :type 'integer)
1808 (defcustom org-reverse-note-order nil
1809 "Non-nil means store new notes at the beginning of a file or entry.
1810 When nil, new notes will be filed to the end of a file or entry.
1811 This can also be a list with cons cells of regular expressions that
1812 are matched against file names, and values."
1813 :group 'org-remember
1814 :group 'org-refile
1815 :type '(choice
1816 (const :tag "Reverse always" t)
1817 (const :tag "Reverse never" nil)
1818 (repeat :tag "By file name regexp"
1819 (cons regexp boolean))))
1821 (defcustom org-log-refile nil
1822 "Information to record when a task is refiled.
1824 Possible values are:
1826 nil Don't add anything
1827 time Add a time stamp to the task
1828 note Prompt for a note and add it with template `org-log-note-headings'
1830 This option can also be set with on a per-file-basis with
1832 #+STARTUP: nologrefile
1833 #+STARTUP: logrefile
1834 #+STARTUP: lognoterefile
1836 You can have local logging settings for a subtree by setting the LOGGING
1837 property to one or more of these keywords.
1839 When bulk-refiling from the agenda, the value `note' is forbidden and
1840 will temporarily be changed to `time'."
1841 :group 'org-refile
1842 :group 'org-progress
1843 :type '(choice
1844 (const :tag "No logging" nil)
1845 (const :tag "Record timestamp" time)
1846 (const :tag "Record timestamp with note." note)))
1848 (defcustom org-refile-targets nil
1849 "Targets for refiling entries with \\[org-refile].
1850 This is list of cons cells. Each cell contains:
1851 - a specification of the files to be considered, either a list of files,
1852 or a symbol whose function or variable value will be used to retrieve
1853 a file name or a list of file names. If you use `org-agenda-files' for
1854 that, all agenda files will be scanned for targets. Nil means consider
1855 headings in the current buffer.
1856 - A specification of how to find candidate refile targets. This may be
1857 any of:
1858 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1859 This tag has to be present in all target headlines, inheritance will
1860 not be considered.
1861 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1862 todo keyword.
1863 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1864 headlines that are refiling targets.
1865 - a cons cell (:level . N). Any headline of level N is considered a target.
1866 Note that, when `org-odd-levels-only' is set, level corresponds to
1867 order in hierarchy, not to the number of stars.
1868 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1869 Note that, when `org-odd-levels-only' is set, level corresponds to
1870 order in hierarchy, not to the number of stars.
1872 You can set the variable `org-refile-target-verify-function' to a function
1873 to verify each headline found by the simple criteria above.
1875 When this variable is nil, all top-level headlines in the current buffer
1876 are used, equivalent to the value `((nil . (:level . 1))'."
1877 :group 'org-refile
1878 :type '(repeat
1879 (cons
1880 (choice :value org-agenda-files
1881 (const :tag "All agenda files" org-agenda-files)
1882 (const :tag "Current buffer" nil)
1883 (function) (variable) (file))
1884 (choice :tag "Identify target headline by"
1885 (cons :tag "Specific tag" (const :value :tag) (string))
1886 (cons :tag "TODO keyword" (const :value :todo) (string))
1887 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1888 (cons :tag "Level number" (const :value :level) (integer))
1889 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1891 (defcustom org-refile-target-verify-function nil
1892 "Function to verify if the headline at point should be a refile target.
1893 The function will be called without arguments, with point at the
1894 beginning of the headline. It should return t and leave point
1895 where it is if the headline is a valid target for refiling.
1897 If the target should not be selected, the function must return nil.
1898 In addition to this, it may move point to a place from where the search
1899 should be continued. For example, the function may decide that the entire
1900 subtree of the current entry should be excluded and move point to the end
1901 of the subtree."
1902 :group 'org-refile
1903 :type 'function)
1905 (defcustom org-refile-use-cache nil
1906 "Non-nil means cache refile targets to speed up the process.
1907 The cache for a particular file will be updated automatically when
1908 the buffer has been killed, or when any of the marker used for flagging
1909 refile targets no longer points at a live buffer.
1910 If you have added new entries to a buffer that might themselves be targets,
1911 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
1912 find that easier, `C-u C-u C-u C-c C-w'."
1913 :group 'org-refile
1914 :type 'boolean)
1916 (defcustom org-refile-use-outline-path nil
1917 "Non-nil means provide refile targets as paths.
1918 So a level 3 headline will be available as level1/level2/level3.
1920 When the value is `file', also include the file name (without directory)
1921 into the path. In this case, you can also stop the completion after
1922 the file name, to get entries inserted as top level in the file.
1924 When `full-file-path', include the full file path."
1925 :group 'org-refile
1926 :type '(choice
1927 (const :tag "Not" nil)
1928 (const :tag "Yes" t)
1929 (const :tag "Start with file name" file)
1930 (const :tag "Start with full file path" full-file-path)))
1932 (defcustom org-outline-path-complete-in-steps t
1933 "Non-nil means complete the outline path in hierarchical steps.
1934 When Org-mode uses the refile interface to select an outline path
1935 \(see variable `org-refile-use-outline-path'), the completion of
1936 the path can be done is a single go, or if can be done in steps down
1937 the headline hierarchy. Going in steps is probably the best if you
1938 do not use a special completion package like `ido' or `icicles'.
1939 However, when using these packages, going in one step can be very
1940 fast, while still showing the whole path to the entry."
1941 :group 'org-refile
1942 :type 'boolean)
1944 (defcustom org-refile-allow-creating-parent-nodes nil
1945 "Non-nil means allow to create new nodes as refile targets.
1946 New nodes are then created by adding \"/new node name\" to the completion
1947 of an existing node. When the value of this variable is `confirm',
1948 new node creation must be confirmed by the user (recommended)
1949 When nil, the completion must match an existing entry.
1951 Note that, if the new heading is not seen by the criteria
1952 listed in `org-refile-targets', multiple instances of the same
1953 heading would be created by trying again to file under the new
1954 heading."
1955 :group 'org-refile
1956 :type '(choice
1957 (const :tag "Never" nil)
1958 (const :tag "Always" t)
1959 (const :tag "Prompt for confirmation" confirm)))
1961 (defgroup org-todo nil
1962 "Options concerning TODO items in Org-mode."
1963 :tag "Org TODO"
1964 :group 'org)
1966 (defgroup org-progress nil
1967 "Options concerning Progress logging in Org-mode."
1968 :tag "Org Progress"
1969 :group 'org-time)
1971 (defvar org-todo-interpretation-widgets
1973 (:tag "Sequence (cycling hits every state)" sequence)
1974 (:tag "Type (cycling directly to DONE)" type))
1975 "The available interpretation symbols for customizing `org-todo-keywords'.
1976 Interested libraries should add to this list.")
1978 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1979 "List of TODO entry keyword sequences and their interpretation.
1980 \\<org-mode-map>This is a list of sequences.
1982 Each sequence starts with a symbol, either `sequence' or `type',
1983 indicating if the keywords should be interpreted as a sequence of
1984 action steps, or as different types of TODO items. The first
1985 keywords are states requiring action - these states will select a headline
1986 for inclusion into the global TODO list Org-mode produces. If one of
1987 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
1988 signify that no further action is necessary. If \"|\" is not found,
1989 the last keyword is treated as the only DONE state of the sequence.
1991 The command \\[org-todo] cycles an entry through these states, and one
1992 additional state where no keyword is present. For details about this
1993 cycling, see the manual.
1995 TODO keywords and interpretation can also be set on a per-file basis with
1996 the special #+SEQ_TODO and #+TYP_TODO lines.
1998 Each keyword can optionally specify a character for fast state selection
1999 \(in combination with the variable `org-use-fast-todo-selection')
2000 and specifiers for state change logging, using the same syntax
2001 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
2002 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2003 indicates to record a time stamp each time this state is selected.
2005 Each keyword may also specify if a timestamp or a note should be
2006 recorded when entering or leaving the state, by adding additional
2007 characters in the parenthesis after the keyword. This looks like this:
2008 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2009 record only the time of the state change. With X and Y being either
2010 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2011 Y when leaving the state if and only if the *target* state does not
2012 define X. You may omit any of the fast-selection key or X or /Y,
2013 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2015 For backward compatibility, this variable may also be just a list
2016 of keywords - in this case the interpretation (sequence or type) will be
2017 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2018 :group 'org-todo
2019 :group 'org-keywords
2020 :type '(choice
2021 (repeat :tag "Old syntax, just keywords"
2022 (string :tag "Keyword"))
2023 (repeat :tag "New syntax"
2024 (cons
2025 (choice
2026 :tag "Interpretation"
2027 ;;Quick and dirty way to see
2028 ;;`org-todo-interpretations'. This takes the
2029 ;;place of item arguments
2030 :convert-widget
2031 (lambda (widget)
2032 (widget-put widget
2033 :args (mapcar
2034 #'(lambda (x)
2035 (widget-convert
2036 (cons 'const x)))
2037 org-todo-interpretation-widgets))
2038 widget))
2039 (repeat
2040 (string :tag "Keyword"))))))
2042 (defvar org-todo-keywords-1 nil
2043 "All TODO and DONE keywords active in a buffer.")
2044 (make-variable-buffer-local 'org-todo-keywords-1)
2045 (defvar org-todo-keywords-for-agenda nil)
2046 (defvar org-done-keywords-for-agenda nil)
2047 (defvar org-drawers-for-agenda nil)
2048 (defvar org-todo-keyword-alist-for-agenda nil)
2049 (defvar org-tag-alist-for-agenda nil)
2050 (defvar org-agenda-contributing-files nil)
2051 (defvar org-not-done-keywords nil)
2052 (make-variable-buffer-local 'org-not-done-keywords)
2053 (defvar org-done-keywords nil)
2054 (make-variable-buffer-local 'org-done-keywords)
2055 (defvar org-todo-heads nil)
2056 (make-variable-buffer-local 'org-todo-heads)
2057 (defvar org-todo-sets nil)
2058 (make-variable-buffer-local 'org-todo-sets)
2059 (defvar org-todo-log-states nil)
2060 (make-variable-buffer-local 'org-todo-log-states)
2061 (defvar org-todo-kwd-alist nil)
2062 (make-variable-buffer-local 'org-todo-kwd-alist)
2063 (defvar org-todo-key-alist nil)
2064 (make-variable-buffer-local 'org-todo-key-alist)
2065 (defvar org-todo-key-trigger nil)
2066 (make-variable-buffer-local 'org-todo-key-trigger)
2068 (defcustom org-todo-interpretation 'sequence
2069 "Controls how TODO keywords are interpreted.
2070 This variable is in principle obsolete and is only used for
2071 backward compatibility, if the interpretation of todo keywords is
2072 not given already in `org-todo-keywords'. See that variable for
2073 more information."
2074 :group 'org-todo
2075 :group 'org-keywords
2076 :type '(choice (const sequence)
2077 (const type)))
2079 (defcustom org-use-fast-todo-selection t
2080 "Non-nil means use the fast todo selection scheme with C-c C-t.
2081 This variable describes if and under what circumstances the cycling
2082 mechanism for TODO keywords will be replaced by a single-key, direct
2083 selection scheme.
2085 When nil, fast selection is never used.
2087 When the symbol `prefix', it will be used when `org-todo' is called with
2088 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
2089 in an agenda buffer.
2091 When t, fast selection is used by default. In this case, the prefix
2092 argument forces cycling instead.
2094 In all cases, the special interface is only used if access keys have actually
2095 been assigned by the user, i.e. if keywords in the configuration are followed
2096 by a letter in parenthesis, like TODO(t)."
2097 :group 'org-todo
2098 :type '(choice
2099 (const :tag "Never" nil)
2100 (const :tag "By default" t)
2101 (const :tag "Only with C-u C-c C-t" prefix)))
2103 (defcustom org-provide-todo-statistics t
2104 "Non-nil means update todo statistics after insert and toggle.
2105 ALL-HEADLINES means update todo statistics by including headlines
2106 with no TODO keyword as well, counting them as not done.
2107 A list of TODO keywords means the same, but skip keywords that are
2108 not in this list.
2110 When this is set, todo statistics is updated in the parent of the
2111 current entry each time a todo state is changed."
2112 :group 'org-todo
2113 :type '(choice
2114 (const :tag "Yes, only for TODO entries" t)
2115 (const :tag "Yes, including all entries" 'all-headlines)
2116 (repeat :tag "Yes, for TODOs in this list"
2117 (string :tag "TODO keyword"))
2118 (other :tag "No TODO statistics" nil)))
2120 (defcustom org-hierarchical-todo-statistics t
2121 "Non-nil means TODO statistics covers just direct children.
2122 When nil, all entries in the subtree are considered.
2123 This has only an effect if `org-provide-todo-statistics' is set.
2124 To set this to nil for only a single subtree, use a COOKIE_DATA
2125 property and include the word \"recursive\" into the value."
2126 :group 'org-todo
2127 :type 'boolean)
2129 (defcustom org-after-todo-state-change-hook nil
2130 "Hook which is run after the state of a TODO item was changed.
2131 The new state (a string with a TODO keyword, or nil) is available in the
2132 Lisp variable `state'."
2133 :group 'org-todo
2134 :type 'hook)
2136 (defvar org-blocker-hook nil
2137 "Hook for functions that are allowed to block a state change.
2139 Each function gets as its single argument a property list, see
2140 `org-trigger-hook' for more information about this list.
2142 If any of the functions in this hook returns nil, the state change
2143 is blocked.")
2145 (defvar org-trigger-hook nil
2146 "Hook for functions that are triggered by a state change.
2148 Each function gets as its single argument a property list with at least
2149 the following elements:
2151 (:type type-of-change :position pos-at-entry-start
2152 :from old-state :to new-state)
2154 Depending on the type, more properties may be present.
2156 This mechanism is currently implemented for:
2158 TODO state changes
2159 ------------------
2160 :type todo-state-change
2161 :from previous state (keyword as a string), or nil, or a symbol
2162 'todo' or 'done', to indicate the general type of state.
2163 :to new state, like in :from")
2165 (defcustom org-enforce-todo-dependencies nil
2166 "Non-nil means undone TODO entries will block switching the parent to DONE.
2167 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2168 be blocked if any prior sibling is not yet done.
2169 Finally, if the parent is blocked because of ordered siblings of its own,
2170 the child will also be blocked.
2171 This variable needs to be set before org.el is loaded, and you need to
2172 restart Emacs after a change to make the change effective. The only way
2173 to change is while Emacs is running is through the customize interface."
2174 :set (lambda (var val)
2175 (set var val)
2176 (if val
2177 (add-hook 'org-blocker-hook
2178 'org-block-todo-from-children-or-siblings-or-parent)
2179 (remove-hook 'org-blocker-hook
2180 'org-block-todo-from-children-or-siblings-or-parent)))
2181 :group 'org-todo
2182 :type 'boolean)
2184 (defcustom org-enforce-todo-checkbox-dependencies nil
2185 "Non-nil means unchecked boxes will block switching the parent to DONE.
2186 When this is nil, checkboxes have no influence on switching TODO states.
2187 When non-nil, you first need to check off all check boxes before the TODO
2188 entry can be switched to DONE.
2189 This variable needs to be set before org.el is loaded, and you need to
2190 restart Emacs after a change to make the change effective. The only way
2191 to change is while Emacs is running is through the customize interface."
2192 :set (lambda (var val)
2193 (set var val)
2194 (if val
2195 (add-hook 'org-blocker-hook
2196 'org-block-todo-from-checkboxes)
2197 (remove-hook 'org-blocker-hook
2198 'org-block-todo-from-checkboxes)))
2199 :group 'org-todo
2200 :type 'boolean)
2202 (defcustom org-treat-insert-todo-heading-as-state-change nil
2203 "Non-nil means inserting a TODO heading is treated as state change.
2204 So when the command \\[org-insert-todo-heading] is used, state change
2205 logging will apply if appropriate. When nil, the new TODO item will
2206 be inserted directly, and no logging will take place."
2207 :group 'org-todo
2208 :type 'boolean)
2210 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2211 "Non-nil means switching TODO states with S-cursor counts as state change.
2212 This is the default behavior. However, setting this to nil allows a
2213 convenient way to select a TODO state and bypass any logging associated
2214 with that."
2215 :group 'org-todo
2216 :type 'boolean)
2218 (defcustom org-todo-state-tags-triggers nil
2219 "Tag changes that should be triggered by TODO state changes.
2220 This is a list. Each entry is
2222 (state-change (tag . flag) .......)
2224 State-change can be a string with a state, and empty string to indicate the
2225 state that has no TODO keyword, or it can be one of the symbols `todo'
2226 or `done', meaning any not-done or done state, respectively."
2227 :group 'org-todo
2228 :group 'org-tags
2229 :type '(repeat
2230 (cons (choice :tag "When changing to"
2231 (const :tag "Not-done state" todo)
2232 (const :tag "Done state" done)
2233 (string :tag "State"))
2234 (repeat
2235 (cons :tag "Tag action"
2236 (string :tag "Tag")
2237 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2239 (defcustom org-log-done nil
2240 "Information to record when a task moves to the DONE state.
2242 Possible values are:
2244 nil Don't add anything, just change the keyword
2245 time Add a time stamp to the task
2246 note Prompt for a note and add it with template `org-log-note-headings'
2248 This option can also be set with on a per-file-basis with
2250 #+STARTUP: nologdone
2251 #+STARTUP: logdone
2252 #+STARTUP: lognotedone
2254 You can have local logging settings for a subtree by setting the LOGGING
2255 property to one or more of these keywords."
2256 :group 'org-todo
2257 :group 'org-progress
2258 :type '(choice
2259 (const :tag "No logging" nil)
2260 (const :tag "Record CLOSED timestamp" time)
2261 (const :tag "Record CLOSED timestamp with note." note)))
2263 ;; Normalize old uses of org-log-done.
2264 (cond
2265 ((eq org-log-done t) (setq org-log-done 'time))
2266 ((and (listp org-log-done) (memq 'done org-log-done))
2267 (setq org-log-done 'note)))
2269 (defcustom org-log-reschedule nil
2270 "Information to record when the scheduling date of a tasks is modified.
2272 Possible values are:
2274 nil Don't add anything, just change the date
2275 time Add a time stamp to the task
2276 note Prompt for a note and add it with template `org-log-note-headings'
2278 This option can also be set with on a per-file-basis with
2280 #+STARTUP: nologreschedule
2281 #+STARTUP: logreschedule
2282 #+STARTUP: lognotereschedule"
2283 :group 'org-todo
2284 :group 'org-progress
2285 :type '(choice
2286 (const :tag "No logging" nil)
2287 (const :tag "Record timestamp" time)
2288 (const :tag "Record timestamp with note." note)))
2290 (defcustom org-log-redeadline nil
2291 "Information to record when the deadline date of a tasks is modified.
2293 Possible values are:
2295 nil Don't add anything, just change the date
2296 time Add a time stamp to the task
2297 note Prompt for a note and add it with template `org-log-note-headings'
2299 This option can also be set with on a per-file-basis with
2301 #+STARTUP: nologredeadline
2302 #+STARTUP: logredeadline
2303 #+STARTUP: lognoteredeadline
2305 You can have local logging settings for a subtree by setting the LOGGING
2306 property to one or more of these keywords."
2307 :group 'org-todo
2308 :group 'org-progress
2309 :type '(choice
2310 (const :tag "No logging" nil)
2311 (const :tag "Record timestamp" time)
2312 (const :tag "Record timestamp with note." note)))
2314 (defcustom org-log-note-clock-out nil
2315 "Non-nil means record a note when clocking out of an item.
2316 This can also be configured on a per-file basis by adding one of
2317 the following lines anywhere in the buffer:
2319 #+STARTUP: lognoteclock-out
2320 #+STARTUP: nolognoteclock-out"
2321 :group 'org-todo
2322 :group 'org-progress
2323 :type 'boolean)
2325 (defcustom org-log-done-with-time t
2326 "Non-nil means the CLOSED time stamp will contain date and time.
2327 When nil, only the date will be recorded."
2328 :group 'org-progress
2329 :type 'boolean)
2331 (defcustom org-log-note-headings
2332 '((done . "CLOSING NOTE %t")
2333 (state . "State %-12s from %-12S %t")
2334 (note . "Note taken on %t")
2335 (reschedule . "Rescheduled from %S on %t")
2336 (delschedule . "Not scheduled, was %S on %t")
2337 (redeadline . "New deadline from %S on %t")
2338 (deldeadline . "Removed deadline, was %S on %t")
2339 (refile . "Refiled on %t")
2340 (clock-out . ""))
2341 "Headings for notes added to entries.
2342 The value is an alist, with the car being a symbol indicating the note
2343 context, and the cdr is the heading to be used. The heading may also be the
2344 empty string.
2345 %t in the heading will be replaced by a time stamp.
2346 %T will be an active time stamp instead the default inactive one
2347 %s will be replaced by the new TODO state, in double quotes.
2348 %S will be replaced by the old TODO state, in double quotes.
2349 %u will be replaced by the user name.
2350 %U will be replaced by the full user name.
2352 In fact, it is not a good idea to change the `state' entry, because
2353 agenda log mode depends on the format of these entries."
2354 :group 'org-todo
2355 :group 'org-progress
2356 :type '(list :greedy t
2357 (cons (const :tag "Heading when closing an item" done) string)
2358 (cons (const :tag
2359 "Heading when changing todo state (todo sequence only)"
2360 state) string)
2361 (cons (const :tag "Heading when just taking a note" note) string)
2362 (cons (const :tag "Heading when clocking out" clock-out) string)
2363 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2364 (cons (const :tag "Heading when rescheduling" reschedule) string)
2365 (cons (const :tag "Heading when changing deadline" redeadline) string)
2366 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2367 (cons (const :tag "Heading when refiling" refile) string)))
2369 (unless (assq 'note org-log-note-headings)
2370 (push '(note . "%t") org-log-note-headings))
2372 (defcustom org-log-into-drawer nil
2373 "Non-nil means insert state change notes and time stamps into a drawer.
2374 When nil, state changes notes will be inserted after the headline and
2375 any scheduling and clock lines, but not inside a drawer.
2377 The value of this variable should be the name of the drawer to use.
2378 LOGBOOK is proposed at the default drawer for this purpose, you can
2379 also set this to a string to define the drawer of your choice.
2381 A value of t is also allowed, representing \"LOGBOOK\".
2383 If this variable is set, `org-log-state-notes-insert-after-drawers'
2384 will be ignored.
2386 You can set the property LOG_INTO_DRAWER to overrule this setting for
2387 a subtree."
2388 :group 'org-todo
2389 :group 'org-progress
2390 :type '(choice
2391 (const :tag "Not into a drawer" nil)
2392 (const :tag "LOGBOOK" t)
2393 (string :tag "Other")))
2395 (if (fboundp 'defvaralias)
2396 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2398 (defun org-log-into-drawer ()
2399 "Return the value of `org-log-into-drawer', but let properties overrule.
2400 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2401 used instead of the default value."
2402 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2403 (cond
2404 ((or (not p) (equal p "nil")) org-log-into-drawer)
2405 ((equal p "t") "LOGBOOK")
2406 (t p))))
2408 (defcustom org-log-state-notes-insert-after-drawers nil
2409 "Non-nil means insert state change notes after any drawers in entry.
2410 Only the drawers that *immediately* follow the headline and the
2411 deadline/scheduled line are skipped.
2412 When nil, insert notes right after the heading and perhaps the line
2413 with deadline/scheduling if present.
2415 This variable will have no effect if `org-log-into-drawer' is
2416 set."
2417 :group 'org-todo
2418 :group 'org-progress
2419 :type 'boolean)
2421 (defcustom org-log-states-order-reversed t
2422 "Non-nil means the latest state note will be directly after heading.
2423 When nil, the state change notes will be ordered according to time."
2424 :group 'org-todo
2425 :group 'org-progress
2426 :type 'boolean)
2428 (defcustom org-todo-repeat-to-state nil
2429 "The TODO state to which a repeater should return the repeating task.
2430 By default this is the first task in a TODO sequence, or the previous state
2431 in a TODO_TYP set. But you can specify another task here.
2432 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2433 :group 'org-todo
2434 :type '(choice (const :tag "Head of sequence" nil)
2435 (string :tag "Specific state")))
2437 (defcustom org-log-repeat 'time
2438 "Non-nil means record moving through the DONE state when triggering repeat.
2439 An auto-repeating task is immediately switched back to TODO when
2440 marked DONE. If you are not logging state changes (by adding \"@\"
2441 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2442 record a closing note, there will be no record of the task moving
2443 through DONE. This variable forces taking a note anyway.
2445 nil Don't force a record
2446 time Record a time stamp
2447 note Record a note
2449 This option can also be set with on a per-file-basis with
2451 #+STARTUP: logrepeat
2452 #+STARTUP: lognoterepeat
2453 #+STARTUP: nologrepeat
2455 You can have local logging settings for a subtree by setting the LOGGING
2456 property to one or more of these keywords."
2457 :group 'org-todo
2458 :group 'org-progress
2459 :type '(choice
2460 (const :tag "Don't force a record" nil)
2461 (const :tag "Force recording the DONE state" time)
2462 (const :tag "Force recording a note with the DONE state" note)))
2465 (defgroup org-priorities nil
2466 "Priorities in Org-mode."
2467 :tag "Org Priorities"
2468 :group 'org-todo)
2470 (defcustom org-enable-priority-commands t
2471 "Non-nil means priority commands are active.
2472 When nil, these commands will be disabled, so that you never accidentally
2473 set a priority."
2474 :group 'org-priorities
2475 :type 'boolean)
2477 (defcustom org-highest-priority ?A
2478 "The highest priority of TODO items. A character like ?A, ?B etc.
2479 Must have a smaller ASCII number than `org-lowest-priority'."
2480 :group 'org-priorities
2481 :type 'character)
2483 (defcustom org-lowest-priority ?C
2484 "The lowest priority of TODO items. A character like ?A, ?B etc.
2485 Must have a larger ASCII number than `org-highest-priority'."
2486 :group 'org-priorities
2487 :type 'character)
2489 (defcustom org-default-priority ?B
2490 "The default priority of TODO items.
2491 This is the priority an item gets if no explicit priority is given.
2492 When starting to cycle on an empty priority the first step in the cycle
2493 depends on `org-priority-start-cycle-with-default'. The resulting first
2494 step priority must not exceed the range from `org-highest-priority' to
2495 `org-lowest-priority' which means that `org-default-priority' has to be
2496 in this range exclusive or inclusive the range boundaries."
2497 :group 'org-priorities
2498 :type 'character)
2500 (defcustom org-priority-start-cycle-with-default t
2501 "Non-nil means start with default priority when starting to cycle.
2502 When this is nil, the first step in the cycle will be (depending on the
2503 command used) one higher or lower than the default priority.
2504 See also `org-default-priority'."
2505 :group 'org-priorities
2506 :type 'boolean)
2508 (defcustom org-get-priority-function nil
2509 "Function to extract the priority from a string.
2510 The string is normally the headline. If this is nil Org computes the
2511 priority from the priority cookie like [#A] in the headline. It returns
2512 an integer, increasing by 1000 for each priority level.
2513 The user can set a different function here, which should take a string
2514 as an argument and return the numeric priority."
2515 :group 'org-priorities
2516 :type 'function)
2518 (defgroup org-time nil
2519 "Options concerning time stamps and deadlines in Org-mode."
2520 :tag "Org Time"
2521 :group 'org)
2523 (defcustom org-insert-labeled-timestamps-at-point nil
2524 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2525 When nil, these labeled time stamps are forces into the second line of an
2526 entry, just after the headline. When scheduling from the global TODO list,
2527 the time stamp will always be forced into the second line."
2528 :group 'org-time
2529 :type 'boolean)
2531 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2532 "Formats for `format-time-string' which are used for time stamps.
2533 It is not recommended to change this constant.")
2535 (defcustom org-time-stamp-rounding-minutes '(0 5)
2536 "Number of minutes to round time stamps to.
2537 These are two values, the first applies when first creating a time stamp.
2538 The second applies when changing it with the commands `S-up' and `S-down'.
2539 When changing the time stamp, this means that it will change in steps
2540 of N minutes, as given by the second value.
2542 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2543 numbers should be factors of 60, so for example 5, 10, 15.
2545 When this is larger than 1, you can still force an exact time stamp by using
2546 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2547 and by using a prefix arg to `S-up/down' to specify the exact number
2548 of minutes to shift."
2549 :group 'org-time
2550 :get '(lambda (var) ; Make sure both elements are there
2551 (if (integerp (default-value var))
2552 (list (default-value var) 5)
2553 (default-value var)))
2554 :type '(list
2555 (integer :tag "when inserting times")
2556 (integer :tag "when modifying times")))
2558 ;; Normalize old customizations of this variable.
2559 (when (integerp org-time-stamp-rounding-minutes)
2560 (setq org-time-stamp-rounding-minutes
2561 (list org-time-stamp-rounding-minutes
2562 org-time-stamp-rounding-minutes)))
2564 (defcustom org-display-custom-times nil
2565 "Non-nil means overlay custom formats over all time stamps.
2566 The formats are defined through the variable `org-time-stamp-custom-formats'.
2567 To turn this on on a per-file basis, insert anywhere in the file:
2568 #+STARTUP: customtime"
2569 :group 'org-time
2570 :set 'set-default
2571 :type 'sexp)
2572 (make-variable-buffer-local 'org-display-custom-times)
2574 (defcustom org-time-stamp-custom-formats
2575 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2576 "Custom formats for time stamps. See `format-time-string' for the syntax.
2577 These are overlayed over the default ISO format if the variable
2578 `org-display-custom-times' is set. Time like %H:%M should be at the
2579 end of the second format. The custom formats are also honored by export
2580 commands, if custom time display is turned on at the time of export."
2581 :group 'org-time
2582 :type 'sexp)
2584 (defun org-time-stamp-format (&optional long inactive)
2585 "Get the right format for a time string."
2586 (let ((f (if long (cdr org-time-stamp-formats)
2587 (car org-time-stamp-formats))))
2588 (if inactive
2589 (concat "[" (substring f 1 -1) "]")
2590 f)))
2592 (defcustom org-time-clocksum-format "%d:%02d"
2593 "The format string used when creating CLOCKSUM lines.
2594 This is also used when org-mode generates a time duration."
2595 :group 'org-time
2596 :type 'string)
2598 (defcustom org-time-clocksum-use-fractional nil
2599 "If non-nil, \\[org-clock-display] uses fractional times.
2600 org-mode generates a time duration."
2601 :group 'org-time
2602 :type 'boolean)
2604 (defcustom org-time-clocksum-fractional-format "%.2f"
2605 "The format string used when creating CLOCKSUM lines, or when
2606 org-mode generates a time duration."
2607 :group 'org-time
2608 :type 'string)
2610 (defcustom org-deadline-warning-days 14
2611 "No. of days before expiration during which a deadline becomes active.
2612 This variable governs the display in sparse trees and in the agenda.
2613 When 0 or negative, it means use this number (the absolute value of it)
2614 even if a deadline has a different individual lead time specified.
2616 Custom commands can set this variable in the options section."
2617 :group 'org-time
2618 :group 'org-agenda-daily/weekly
2619 :type 'integer)
2621 (defcustom org-read-date-prefer-future t
2622 "Non-nil means assume future for incomplete date input from user.
2623 This affects the following situations:
2624 1. The user gives a month but not a year.
2625 For example, if it is April and you enter \"feb 2\", this will be read
2626 as Feb 2, *next* year. \"May 5\", however, will be this year.
2627 2. The user gives a day, but no month.
2628 For example, if today is the 15th, and you enter \"3\", Org-mode will
2629 read this as the third of *next* month. However, if you enter \"17\",
2630 it will be considered as *this* month.
2632 If you set this variable to the symbol `time', then also the following
2633 will work:
2635 3. If the user gives a time, but no day. If the time is before now,
2636 to will be interpreted as tomorrow.
2638 Currently none of this works for ISO week specifications.
2640 When this option is nil, the current day, month and year will always be
2641 used as defaults.
2643 See also `org-agenda-jump-prefer-future'."
2644 :group 'org-time
2645 :type '(choice
2646 (const :tag "Never" nil)
2647 (const :tag "Check month and day" t)
2648 (const :tag "Check month, day, and time" time)))
2650 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2651 "Should the agenda jump command prefer the future for incomplete dates?
2652 The default is to do the same as configured in `org-read-date-prefer-future'.
2653 But you can also set a deviating value here.
2654 This may t or nil, or the symbol `org-read-date-prefer-future'."
2655 :group 'org-agenda
2656 :group 'org-time
2657 :type '(choice
2658 (const :tag "Use org-read-date-prefer-future"
2659 org-read-date-prefer-future)
2660 (const :tag "Never" nil)
2661 (const :tag "Always" t)))
2663 (defcustom org-read-date-force-compatible-dates t
2664 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2666 Depending on the system Emacs is running on, certain dates cannot
2667 be represented with the type used internally to represent time.
2668 Dates between 1970-1-1 and 2038-1-1 can always be represented
2669 correctly. Some systems allow for earlier dates, some for later,
2670 some for both. One way to find out it to insert any date into an
2671 Org buffer, putting the cursor on the year and hitting S-up and
2672 S-down to test the range.
2674 When this variable is set to t, the date/time prompt will not let
2675 you specify dates outside the 1970-2037 range, so it is certain that
2676 these dates will work in whatever version of Emacs you are
2677 running, and also that you can move a file from one Emacs implementation
2678 to another. WHenever Org is forcing the year for you, it will display
2679 a message and beep.
2681 When this variable is nil, Org will check if the date is
2682 representable in the specific Emacs implementation you are using.
2683 If not, it will force a year, usually the current year, and beep
2684 to remind you. Currently this setting is not recommended because
2685 the likelihood that you will open your Org files in an Emacs that
2686 has limited date range is not negligible.
2688 A workaround for this problem is to use diary sexp dates for time
2689 stamps outside of this range."
2690 :group 'org-time
2691 :type 'boolean)
2693 (defcustom org-read-date-display-live t
2694 "Non-nil means display current interpretation of date prompt live.
2695 This display will be in an overlay, in the minibuffer."
2696 :group 'org-time
2697 :type 'boolean)
2699 (defcustom org-read-date-popup-calendar t
2700 "Non-nil means pop up a calendar when prompting for a date.
2701 In the calendar, the date can be selected with mouse-1. However, the
2702 minibuffer will also be active, and you can simply enter the date as well.
2703 When nil, only the minibuffer will be available."
2704 :group 'org-time
2705 :type 'boolean)
2706 (if (fboundp 'defvaralias)
2707 (defvaralias 'org-popup-calendar-for-date-prompt
2708 'org-read-date-popup-calendar))
2710 (defcustom org-read-date-minibuffer-setup-hook nil
2711 "Hook to be used to set up keys for the date/time interface.
2712 Add key definitions to `minibuffer-local-map', which will be a temporary
2713 copy."
2714 :group 'org-time
2715 :type 'hook)
2717 (defcustom org-extend-today-until 0
2718 "The hour when your day really ends. Must be an integer.
2719 This has influence for the following applications:
2720 - When switching the agenda to \"today\". It it is still earlier than
2721 the time given here, the day recognized as TODAY is actually yesterday.
2722 - When a date is read from the user and it is still before the time given
2723 here, the current date and time will be assumed to be yesterday, 23:59.
2724 Also, timestamps inserted in remember templates follow this rule.
2726 IMPORTANT: This is a feature whose implementation is and likely will
2727 remain incomplete. Really, it is only here because past midnight seems to
2728 be the favorite working time of John Wiegley :-)"
2729 :group 'org-time
2730 :type 'integer)
2732 (defcustom org-edit-timestamp-down-means-later nil
2733 "Non-nil means S-down will increase the time in a time stamp.
2734 When nil, S-up will increase."
2735 :group 'org-time
2736 :type 'boolean)
2738 (defcustom org-calendar-follow-timestamp-change t
2739 "Non-nil means make the calendar window follow timestamp changes.
2740 When a timestamp is modified and the calendar window is visible, it will be
2741 moved to the new date."
2742 :group 'org-time
2743 :type 'boolean)
2745 (defgroup org-tags nil
2746 "Options concerning tags in Org-mode."
2747 :tag "Org Tags"
2748 :group 'org)
2750 (defcustom org-tag-alist nil
2751 "List of tags allowed in Org-mode files.
2752 When this list is nil, Org-mode will base TAG input on what is already in the
2753 buffer.
2754 The value of this variable is an alist, the car of each entry must be a
2755 keyword as a string, the cdr may be a character that is used to select
2756 that tag through the fast-tag-selection interface.
2757 See the manual for details."
2758 :group 'org-tags
2759 :type '(repeat
2760 (choice
2761 (cons (string :tag "Tag name")
2762 (character :tag "Access char"))
2763 (list :tag "Start radio group"
2764 (const :startgroup)
2765 (option (string :tag "Group description")))
2766 (list :tag "End radio group"
2767 (const :endgroup)
2768 (option (string :tag "Group description")))
2769 (const :tag "New line" (:newline)))))
2771 (defcustom org-tag-persistent-alist nil
2772 "List of tags that will always appear in all Org-mode files.
2773 This is in addition to any in buffer settings or customizations
2774 of `org-tag-alist'.
2775 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2776 The value of this variable is an alist, the car of each entry must be a
2777 keyword as a string, the cdr may be a character that is used to select
2778 that tag through the fast-tag-selection interface.
2779 See the manual for details.
2780 To disable these tags on a per-file basis, insert anywhere in the file:
2781 #+STARTUP: noptag"
2782 :group 'org-tags
2783 :type '(repeat
2784 (choice
2785 (cons (string :tag "Tag name")
2786 (character :tag "Access char"))
2787 (const :tag "Start radio group" (:startgroup))
2788 (const :tag "End radio group" (:endgroup))
2789 (const :tag "New line" (:newline)))))
2791 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2792 "If non-nil, always offer completion for all tags of all agenda files.
2793 Instead of customizing this variable directly, you might want to
2794 set it locally for capture buffers, because there no list of
2795 tags in that file can be created dynamically (there are none).
2797 (add-hook 'org-capture-mode-hook
2798 (lambda ()
2799 (set (make-local-variable
2800 'org-complete-tags-always-offer-all-agenda-tags)
2801 t)))"
2802 :group 'org-tags
2803 :type 'boolean)
2805 (defvar org-file-tags nil
2806 "List of tags that can be inherited by all entries in the file.
2807 The tags will be inherited if the variable `org-use-tag-inheritance'
2808 says they should be.
2809 This variable is populated from #+FILETAGS lines.")
2811 (defcustom org-use-fast-tag-selection 'auto
2812 "Non-nil means use fast tag selection scheme.
2813 This is a special interface to select and deselect tags with single keys.
2814 When nil, fast selection is never used.
2815 When the symbol `auto', fast selection is used if and only if selection
2816 characters for tags have been configured, either through the variable
2817 `org-tag-alist' or through a #+TAGS line in the buffer.
2818 When t, fast selection is always used and selection keys are assigned
2819 automatically if necessary."
2820 :group 'org-tags
2821 :type '(choice
2822 (const :tag "Always" t)
2823 (const :tag "Never" nil)
2824 (const :tag "When selection characters are configured" 'auto)))
2826 (defcustom org-fast-tag-selection-single-key nil
2827 "Non-nil means fast tag selection exits after first change.
2828 When nil, you have to press RET to exit it.
2829 During fast tag selection, you can toggle this flag with `C-c'.
2830 This variable can also have the value `expert'. In this case, the window
2831 displaying the tags menu is not even shown, until you press C-c again."
2832 :group 'org-tags
2833 :type '(choice
2834 (const :tag "No" nil)
2835 (const :tag "Yes" t)
2836 (const :tag "Expert" expert)))
2838 (defvar org-fast-tag-selection-include-todo nil
2839 "Non-nil means fast tags selection interface will also offer TODO states.
2840 This is an undocumented feature, you should not rely on it.")
2842 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2843 "The column to which tags should be indented in a headline.
2844 If this number is positive, it specifies the column. If it is negative,
2845 it means that the tags should be flushright to that column. For example,
2846 -80 works well for a normal 80 character screen."
2847 :group 'org-tags
2848 :type 'integer)
2850 (defcustom org-auto-align-tags t
2851 "Non-nil means realign tags after pro/demotion of TODO state change.
2852 These operations change the length of a headline and therefore shift
2853 the tags around. With this options turned on, after each such operation
2854 the tags are again aligned to `org-tags-column'."
2855 :group 'org-tags
2856 :type 'boolean)
2858 (defcustom org-use-tag-inheritance t
2859 "Non-nil means tags in levels apply also for sublevels.
2860 When nil, only the tags directly given in a specific line apply there.
2861 This may also be a list of tags that should be inherited, or a regexp that
2862 matches tags that should be inherited. Additional control is possible
2863 with the variable `org-tags-exclude-from-inheritance' which gives an
2864 explicit list of tags to be excluded from inheritance., even if the value of
2865 `org-use-tag-inheritance' would select it for inheritance.
2867 If this option is t, a match early-on in a tree can lead to a large
2868 number of matches in the subtree when constructing the agenda or creating
2869 a sparse tree. If you only want to see the first match in a tree during
2870 a search, check out the variable `org-tags-match-list-sublevels'."
2871 :group 'org-tags
2872 :type '(choice
2873 (const :tag "Not" nil)
2874 (const :tag "Always" t)
2875 (repeat :tag "Specific tags" (string :tag "Tag"))
2876 (regexp :tag "Tags matched by regexp")))
2878 (defcustom org-tags-exclude-from-inheritance nil
2879 "List of tags that should never be inherited.
2880 This is a way to exclude a few tags from inheritance. For way to do
2881 the opposite, to actively allow inheritance for selected tags,
2882 see the variable `org-use-tag-inheritance'."
2883 :group 'org-tags
2884 :type '(repeat (string :tag "Tag")))
2886 (defun org-tag-inherit-p (tag)
2887 "Check if TAG is one that should be inherited."
2888 (cond
2889 ((member tag org-tags-exclude-from-inheritance) nil)
2890 ((eq org-use-tag-inheritance t) t)
2891 ((not org-use-tag-inheritance) nil)
2892 ((stringp org-use-tag-inheritance)
2893 (string-match org-use-tag-inheritance tag))
2894 ((listp org-use-tag-inheritance)
2895 (member tag org-use-tag-inheritance))
2896 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2898 (defcustom org-tags-match-list-sublevels t
2899 "Non-nil means list also sublevels of headlines matching a search.
2900 This variable applies to tags/property searches, and also to stuck
2901 projects because this search is based on a tags match as well.
2903 When set to the symbol `indented', sublevels are indented with
2904 leading dots.
2906 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2907 the sublevels of a headline matching a tag search often also match
2908 the same search. Listing all of them can create very long lists.
2909 Setting this variable to nil causes subtrees of a match to be skipped.
2911 This variable is semi-obsolete and probably should always be true. It
2912 is better to limit inheritance to certain tags using the variables
2913 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2914 :group 'org-tags
2915 :type '(choice
2916 (const :tag "No, don't list them" nil)
2917 (const :tag "Yes, do list them" t)
2918 (const :tag "List them, indented with leading dots" indented)))
2920 (defcustom org-tags-sort-function nil
2921 "When set, tags are sorted using this function as a comparator."
2922 :group 'org-tags
2923 :type '(choice
2924 (const :tag "No sorting" nil)
2925 (const :tag "Alphabetical" string<)
2926 (const :tag "Reverse alphabetical" string>)
2927 (function :tag "Custom function" nil)))
2929 (defvar org-tags-history nil
2930 "History of minibuffer reads for tags.")
2931 (defvar org-last-tags-completion-table nil
2932 "The last used completion table for tags.")
2933 (defvar org-after-tags-change-hook nil
2934 "Hook that is run after the tags in a line have changed.")
2936 (defgroup org-properties nil
2937 "Options concerning properties in Org-mode."
2938 :tag "Org Properties"
2939 :group 'org)
2941 (defcustom org-property-format "%-10s %s"
2942 "How property key/value pairs should be formatted by `indent-line'.
2943 When `indent-line' hits a property definition, it will format the line
2944 according to this format, mainly to make sure that the values are
2945 lined-up with respect to each other."
2946 :group 'org-properties
2947 :type 'string)
2949 (defcustom org-use-property-inheritance nil
2950 "Non-nil means properties apply also for sublevels.
2952 This setting is chiefly used during property searches. Turning it on can
2953 cause significant overhead when doing a search, which is why it is not
2954 on by default.
2956 When nil, only the properties directly given in the current entry count.
2957 When t, every property is inherited. The value may also be a list of
2958 properties that should have inheritance, or a regular expression matching
2959 properties that should be inherited.
2961 However, note that some special properties use inheritance under special
2962 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2963 and the properties ending in \"_ALL\" when they are used as descriptor
2964 for valid values of a property.
2966 Note for programmers:
2967 When querying an entry with `org-entry-get', you can control if inheritance
2968 should be used. By default, `org-entry-get' looks only at the local
2969 properties. You can request inheritance by setting the inherit argument
2970 to t (to force inheritance) or to `selective' (to respect the setting
2971 in this variable)."
2972 :group 'org-properties
2973 :type '(choice
2974 (const :tag "Not" nil)
2975 (const :tag "Always" t)
2976 (repeat :tag "Specific properties" (string :tag "Property"))
2977 (regexp :tag "Properties matched by regexp")))
2979 (defun org-property-inherit-p (property)
2980 "Check if PROPERTY is one that should be inherited."
2981 (cond
2982 ((eq org-use-property-inheritance t) t)
2983 ((not org-use-property-inheritance) nil)
2984 ((stringp org-use-property-inheritance)
2985 (string-match org-use-property-inheritance property))
2986 ((listp org-use-property-inheritance)
2987 (member property org-use-property-inheritance))
2988 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2990 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2991 "The default column format, if no other format has been defined.
2992 This variable can be set on the per-file basis by inserting a line
2994 #+COLUMNS: %25ITEM ....."
2995 :group 'org-properties
2996 :type 'string)
2998 (defcustom org-columns-ellipses ".."
2999 "The ellipses to be used when a field in column view is truncated.
3000 When this is the empty string, as many characters as possible are shown,
3001 but then there will be no visual indication that the field has been truncated.
3002 When this is a string of length N, the last N characters of a truncated
3003 field are replaced by this string. If the column is narrower than the
3004 ellipses string, only part of the ellipses string will be shown."
3005 :group 'org-properties
3006 :type 'string)
3008 (defcustom org-columns-modify-value-for-display-function nil
3009 "Function that modifies values for display in column view.
3010 For example, it can be used to cut out a certain part from a time stamp.
3011 The function must take 2 arguments:
3013 column-title The title of the column (*not* the property name)
3014 value The value that should be modified.
3016 The function should return the value that should be displayed,
3017 or nil if the normal value should be used."
3018 :group 'org-properties
3019 :type 'function)
3021 (defcustom org-effort-property "Effort"
3022 "The property that is being used to keep track of effort estimates.
3023 Effort estimates given in this property need to have the format H:MM."
3024 :group 'org-properties
3025 :group 'org-progress
3026 :type '(string :tag "Property"))
3028 (defconst org-global-properties-fixed
3029 '(("VISIBILITY_ALL" . "folded children content all")
3030 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3031 "List of property/value pairs that can be inherited by any entry.
3033 These are fixed values, for the preset properties. The user variable
3034 that can be used to add to this list is `org-global-properties'.
3036 The entries in this list are cons cells where the car is a property
3037 name and cdr is a string with the value. If the value represents
3038 multiple items like an \"_ALL\" property, separate the items by
3039 spaces.")
3041 (defcustom org-global-properties nil
3042 "List of property/value pairs that can be inherited by any entry.
3044 This list will be combined with the constant `org-global-properties-fixed'.
3046 The entries in this list are cons cells where the car is a property
3047 name and cdr is a string with the value.
3049 You can set buffer-local values for the same purpose in the variable
3050 `org-file-properties' this by adding lines like
3052 #+PROPERTY: NAME VALUE"
3053 :group 'org-properties
3054 :type '(repeat
3055 (cons (string :tag "Property")
3056 (string :tag "Value"))))
3058 (defvar org-file-properties nil
3059 "List of property/value pairs that can be inherited by any entry.
3060 Valid for the current buffer.
3061 This variable is populated from #+PROPERTY lines.")
3062 (make-variable-buffer-local 'org-file-properties)
3064 (defgroup org-agenda nil
3065 "Options concerning agenda views in Org-mode."
3066 :tag "Org Agenda"
3067 :group 'org)
3069 (defvar org-category nil
3070 "Variable used by org files to set a category for agenda display.
3071 Such files should use a file variable to set it, for example
3073 # -*- mode: org; org-category: \"ELisp\"
3075 or contain a special line
3077 #+CATEGORY: ELisp
3079 If the file does not specify a category, then file's base name
3080 is used instead.")
3081 (make-variable-buffer-local 'org-category)
3082 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
3084 (defcustom org-agenda-files nil
3085 "The files to be used for agenda display.
3086 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3087 \\[org-remove-file]. You can also use customize to edit the list.
3089 If an entry is a directory, all files in that directory that are matched by
3090 `org-agenda-file-regexp' will be part of the file list.
3092 If the value of the variable is not a list but a single file name, then
3093 the list of agenda files is actually stored and maintained in that file, one
3094 agenda file per line. In this file paths can be given relative to
3095 `org-directory'. Tilde expansion and environment variable substitution
3096 are also made."
3097 :group 'org-agenda
3098 :type '(choice
3099 (repeat :tag "List of files and directories" file)
3100 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3102 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3103 "Regular expression to match files for `org-agenda-files'.
3104 If any element in the list in that variable contains a directory instead
3105 of a normal file, all files in that directory that are matched by this
3106 regular expression will be included."
3107 :group 'org-agenda
3108 :type 'regexp)
3110 (defcustom org-agenda-text-search-extra-files nil
3111 "List of extra files to be searched by text search commands.
3112 These files will be search in addition to the agenda files by the
3113 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3114 Note that these files will only be searched for text search commands,
3115 not for the other agenda views like todo lists, tag searches or the weekly
3116 agenda. This variable is intended to list notes and possibly archive files
3117 that should also be searched by these two commands.
3118 In fact, if the first element in the list is the symbol `agenda-archives',
3119 than all archive files of all agenda files will be added to the search
3120 scope."
3121 :group 'org-agenda
3122 :type '(set :greedy t
3123 (const :tag "Agenda Archives" agenda-archives)
3124 (repeat :inline t (file))))
3126 (if (fboundp 'defvaralias)
3127 (defvaralias 'org-agenda-multi-occur-extra-files
3128 'org-agenda-text-search-extra-files))
3130 (defcustom org-agenda-skip-unavailable-files nil
3131 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3132 A nil value means to remove them, after a query, from the list."
3133 :group 'org-agenda
3134 :type 'boolean)
3136 (defcustom org-calendar-to-agenda-key [?c]
3137 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3138 The command `org-calendar-goto-agenda' will be bound to this key. The
3139 default is the character `c' because then `c' can be used to switch back and
3140 forth between agenda and calendar."
3141 :group 'org-agenda
3142 :type 'sexp)
3144 (defcustom org-calendar-agenda-action-key [?k]
3145 "The key to be installed in `calendar-mode-map' for agenda-action.
3146 The command `org-agenda-action' will be bound to this key. The
3147 default is the character `k' because we use the same key in the agenda."
3148 :group 'org-agenda
3149 :type 'sexp)
3151 (defcustom org-calendar-insert-diary-entry-key [?i]
3152 "The key to be installed in `calendar-mode-map' for adding diary entries.
3153 This option is irrelevant until `org-agenda-diary-file' has been configured
3154 to point to an Org-mode file. When that is the case, the command
3155 `org-agenda-diary-entry' will be bound to the key given here, by default
3156 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3157 if you want to continue doing this, you need to change this to a different
3158 key."
3159 :group 'org-agenda
3160 :type 'sexp)
3162 (defcustom org-agenda-diary-file 'diary-file
3163 "File to which to add new entries with the `i' key in agenda and calendar.
3164 When this is the symbol `diary-file', the functionality in the Emacs
3165 calendar will be used to add entries to the `diary-file'. But when this
3166 points to a file, `org-agenda-diary-entry' will be used instead."
3167 :group 'org-agenda
3168 :type '(choice
3169 (const :tag "The standard Emacs diary file" diary-file)
3170 (file :tag "Special Org file diary entries")))
3172 (eval-after-load "calendar"
3173 '(progn
3174 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3175 'org-calendar-goto-agenda)
3176 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3177 'org-agenda-action)
3178 (add-hook 'calendar-mode-hook
3179 (lambda ()
3180 (unless (eq org-agenda-diary-file 'diary-file)
3181 (define-key calendar-mode-map
3182 org-calendar-insert-diary-entry-key
3183 'org-agenda-diary-entry))))))
3185 (defgroup org-latex nil
3186 "Options for embedding LaTeX code into Org-mode."
3187 :tag "Org LaTeX"
3188 :group 'org)
3190 (defcustom org-format-latex-options
3191 '(:foreground default :background default :scale 1.0
3192 :html-foreground "Black" :html-background "Transparent"
3193 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3194 "Options for creating images from LaTeX fragments.
3195 This is a property list with the following properties:
3196 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3197 `default' means use the foreground of the default face.
3198 :background the background color, or \"Transparent\".
3199 `default' means use the background of the default face.
3200 :scale a scaling factor for the size of the images, to get more pixels
3201 :html-foreground, :html-background, :html-scale
3202 the same numbers for HTML export.
3203 :matchers a list indicating which matchers should be used to
3204 find LaTeX fragments. Valid members of this list are:
3205 \"begin\" find environments
3206 \"$1\" find single characters surrounded by $.$
3207 \"$\" find math expressions surrounded by $...$
3208 \"$$\" find math expressions surrounded by $$....$$
3209 \"\\(\" find math expressions surrounded by \\(...\\)
3210 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3211 :group 'org-latex
3212 :type 'plist)
3214 (defcustom org-format-latex-signal-error t
3215 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3216 When nil, just push out a message."
3217 :group 'org-latex
3218 :type 'boolean)
3220 (defcustom org-format-latex-header "\\documentclass{article}
3221 \\usepackage[usenames]{color}
3222 \\usepackage{amsmath}
3223 \\usepackage[mathscr]{eucal}
3224 \\pagestyle{empty} % do not remove
3225 \[PACKAGES]
3226 \[DEFAULT-PACKAGES]
3227 % The settings below are copied from fullpage.sty
3228 \\setlength{\\textwidth}{\\paperwidth}
3229 \\addtolength{\\textwidth}{-3cm}
3230 \\setlength{\\oddsidemargin}{1.5cm}
3231 \\addtolength{\\oddsidemargin}{-2.54cm}
3232 \\setlength{\\evensidemargin}{\\oddsidemargin}
3233 \\setlength{\\textheight}{\\paperheight}
3234 \\addtolength{\\textheight}{-\\headheight}
3235 \\addtolength{\\textheight}{-\\headsep}
3236 \\addtolength{\\textheight}{-\\footskip}
3237 \\addtolength{\\textheight}{-3cm}
3238 \\setlength{\\topmargin}{1.5cm}
3239 \\addtolength{\\topmargin}{-2.54cm}"
3240 "The document header used for processing LaTeX fragments.
3241 It is imperative that this header make sure that no page number
3242 appears on the page. The package defined in the variables
3243 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3244 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3245 will be appended."
3246 :group 'org-latex
3247 :type 'string)
3249 (defvar org-format-latex-header-extra nil)
3251 (defun org-set-packages-alist (var val)
3252 "Set the packages alist and make sure it has 3 elements per entry."
3253 (set var (mapcar (lambda (x)
3254 (if (and (consp x) (= (length x) 2))
3255 (list (car x) (nth 1 x) t)
3257 val)))
3259 (defun org-get-packages-alist (var)
3261 "Get the packages alist and make sure it has 3 elements per entry."
3262 (mapcar (lambda (x)
3263 (if (and (consp x) (= (length x) 2))
3264 (list (car x) (nth 1 x) t)
3266 (default-value var)))
3268 ;; The following variables are defined here because is it also used
3269 ;; when formatting latex fragments. Originally it was part of the
3270 ;; LaTeX exporter, which is why the name includes "export".
3271 (defcustom org-export-latex-default-packages-alist
3272 '(("AUTO" "inputenc" t)
3273 ("T1" "fontenc" t)
3274 ("" "fixltx2e" nil)
3275 ("" "graphicx" t)
3276 ("" "longtable" nil)
3277 ("" "float" nil)
3278 ("" "wrapfig" nil)
3279 ("" "soul" t)
3280 ("" "textcomp" t)
3281 ("" "marvosym" t)
3282 ("" "wasysym" t)
3283 ("" "latexsym" t)
3284 ("" "amssymb" t)
3285 ("" "hyperref" nil)
3286 "\\tolerance=1000"
3288 "Alist of default packages to be inserted in the header.
3289 Change this only if one of the packages here causes an incompatibility
3290 with another package you are using.
3291 The packages in this list are needed by one part or another of Org-mode
3292 to function properly.
3294 - inputenc, fontenc: for basic font and character selection
3295 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3296 for interpreting the entities in `org-entities'. You can skip some of these
3297 packages if you don't use any of the symbols in it.
3298 - graphicx: for including images
3299 - float, wrapfig: for figure placement
3300 - longtable: for long tables
3301 - hyperref: for cross references
3303 Therefore you should not modify this variable unless you know what you
3304 are doing. The one reason to change it anyway is that you might be loading
3305 some other package that conflicts with one of the default packages.
3306 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3307 If SNIPPET-FLAG is t, the package also needs to be included when
3308 compiling LaTeX snippets into images for inclusion into HTML."
3309 :group 'org-export-latex
3310 :set 'org-set-packages-alist
3311 :get 'org-get-packages-alist
3312 :type '(repeat
3313 (choice
3314 (list :tag "options/package pair"
3315 (string :tag "options")
3316 (string :tag "package")
3317 (boolean :tag "Snippet"))
3318 (string :tag "A line of LaTeX"))))
3320 (defcustom org-export-latex-packages-alist nil
3321 "Alist of packages to be inserted in every LaTeX header.
3322 These will be inserted after `org-export-latex-default-packages-alist'.
3323 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3324 SNIPPET-FLAG, when t, indicates that this package is also needed when
3325 turning LaTeX snippets into images for inclusion into HTML.
3326 Make sure that you only list packages here which:
3327 - you want in every file
3328 - do not conflict with the default packages in
3329 `org-export-latex-default-packages-alist'
3330 - do not conflict with the setup in `org-format-latex-header'."
3331 :group 'org-export-latex
3332 :set 'org-set-packages-alist
3333 :get 'org-get-packages-alist
3334 :type '(repeat
3335 (choice
3336 (list :tag "options/package pair"
3337 (string :tag "options")
3338 (string :tag "package")
3339 (boolean :tag "Snippet"))
3340 (string :tag "A line of LaTeX"))))
3343 (defgroup org-appearance nil
3344 "Settings for Org-mode appearance."
3345 :tag "Org Appearance"
3346 :group 'org)
3348 (defcustom org-level-color-stars-only nil
3349 "Non-nil means fontify only the stars in each headline.
3350 When nil, the entire headline is fontified.
3351 Changing it requires restart of `font-lock-mode' to become effective
3352 also in regions already fontified."
3353 :group 'org-appearance
3354 :type 'boolean)
3356 (defcustom org-hide-leading-stars nil
3357 "Non-nil means hide the first N-1 stars in a headline.
3358 This works by using the face `org-hide' for these stars. This
3359 face is white for a light background, and black for a dark
3360 background. You may have to customize the face `org-hide' to
3361 make this work.
3362 Changing it requires restart of `font-lock-mode' to become effective
3363 also in regions already fontified.
3364 You may also set this on a per-file basis by adding one of the following
3365 lines to the buffer:
3367 #+STARTUP: hidestars
3368 #+STARTUP: showstars"
3369 :group 'org-appearance
3370 :type 'boolean)
3372 (defcustom org-hidden-keywords nil
3373 "List of symbols corresponding to keywords to be hidden the org buffer.
3374 For example, a value '(title) for this list will make the document's title
3375 appear in the buffer without the initial #+TITLE: keyword."
3376 :group 'org-appearance
3377 :type '(set (const :tag "#+AUTHOR" author)
3378 (const :tag "#+DATE" date)
3379 (const :tag "#+EMAIL" email)
3380 (const :tag "#+TITLE" title)))
3382 (defcustom org-fontify-done-headline nil
3383 "Non-nil means change the face of a headline if it is marked DONE.
3384 Normally, only the TODO/DONE keyword indicates the state of a headline.
3385 When this is non-nil, the headline after the keyword is set to the
3386 `org-headline-done' as an additional indication."
3387 :group 'org-appearance
3388 :type 'boolean)
3390 (defcustom org-fontify-emphasized-text t
3391 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3392 Changing this variable requires a restart of Emacs to take effect."
3393 :group 'org-appearance
3394 :type 'boolean)
3396 (defcustom org-fontify-whole-heading-line nil
3397 "Non-nil means fontify the whole line for headings.
3398 This is useful when setting a background color for the
3399 org-level-* faces."
3400 :group 'org-appearance
3401 :type 'boolean)
3403 (defcustom org-highlight-latex-fragments-and-specials nil
3404 "Non-nil means fontify what is treated specially by the exporters."
3405 :group 'org-appearance
3406 :type 'boolean)
3408 (defcustom org-hide-emphasis-markers nil
3409 "Non-nil mean font-lock should hide the emphasis marker characters."
3410 :group 'org-appearance
3411 :type 'boolean)
3413 (defcustom org-pretty-entities nil
3414 "Non-nil means show entities as UTF8 characters.
3415 When nil, the \\name form remains in the buffer."
3416 :group 'org-appearance
3417 :type 'boolean)
3419 (defcustom org-pretty-entities-include-sub-superscripts t
3420 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3421 :group 'org-appearance
3422 :type 'boolean)
3424 (defvar org-emph-re nil
3425 "Regular expression for matching emphasis.
3426 After a match, the match groups contain these elements:
3427 0 The match of the full regular expression, including the characters
3428 before and after the proper match
3429 1 The character before the proper match, or empty at beginning of line
3430 2 The proper match, including the leading and trailing markers
3431 3 The leading marker like * or /, indicating the type of highlighting
3432 4 The text between the emphasis markers, not including the markers
3433 5 The character after the match, empty at the end of a line")
3434 (defvar org-verbatim-re nil
3435 "Regular expression for matching verbatim text.")
3436 (defvar org-emphasis-regexp-components) ; defined just below
3437 (defvar org-emphasis-alist) ; defined just below
3438 (defun org-set-emph-re (var val)
3439 "Set variable and compute the emphasis regular expression."
3440 (set var val)
3441 (when (and (boundp 'org-emphasis-alist)
3442 (boundp 'org-emphasis-regexp-components)
3443 org-emphasis-alist org-emphasis-regexp-components)
3444 (let* ((e org-emphasis-regexp-components)
3445 (pre (car e))
3446 (post (nth 1 e))
3447 (border (nth 2 e))
3448 (body (nth 3 e))
3449 (nl (nth 4 e))
3450 (body1 (concat body "*?"))
3451 (markers (mapconcat 'car org-emphasis-alist ""))
3452 (vmarkers (mapconcat
3453 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3454 org-emphasis-alist "")))
3455 ;; make sure special characters appear at the right position in the class
3456 (if (string-match "\\^" markers)
3457 (setq markers (concat (replace-match "" t t markers) "^")))
3458 (if (string-match "-" markers)
3459 (setq markers (concat (replace-match "" t t markers) "-")))
3460 (if (string-match "\\^" vmarkers)
3461 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3462 (if (string-match "-" vmarkers)
3463 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3464 (if (> nl 0)
3465 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3466 (int-to-string nl) "\\}")))
3467 ;; Make the regexp
3468 (setq org-emph-re
3469 (concat "\\([" pre "]\\|^\\)"
3470 "\\("
3471 "\\([" markers "]\\)"
3472 "\\("
3473 "[^" border "]\\|"
3474 "[^" border "]"
3475 body1
3476 "[^" border "]"
3477 "\\)"
3478 "\\3\\)"
3479 "\\([" post "]\\|$\\)"))
3480 (setq org-verbatim-re
3481 (concat "\\([" pre "]\\|^\\)"
3482 "\\("
3483 "\\([" vmarkers "]\\)"
3484 "\\("
3485 "[^" border "]\\|"
3486 "[^" border "]"
3487 body1
3488 "[^" border "]"
3489 "\\)"
3490 "\\3\\)"
3491 "\\([" post "]\\|$\\)")))))
3493 (defcustom org-emphasis-regexp-components
3494 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3495 "Components used to build the regular expression for emphasis.
3496 This is a list with five entries. Terminology: In an emphasis string
3497 like \" *strong word* \", we call the initial space PREMATCH, the final
3498 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3499 and \"trong wor\" is the body. The different components in this variable
3500 specify what is allowed/forbidden in each part:
3502 pre Chars allowed as prematch. Beginning of line will be allowed too.
3503 post Chars allowed as postmatch. End of line will be allowed too.
3504 border The chars *forbidden* as border characters.
3505 body-regexp A regexp like \".\" to match a body character. Don't use
3506 non-shy groups here, and don't allow newline here.
3507 newline The maximum number of newlines allowed in an emphasis exp.
3509 Use customize to modify this, or restart Emacs after changing it."
3510 :group 'org-appearance
3511 :set 'org-set-emph-re
3512 :type '(list
3513 (sexp :tag "Allowed chars in pre ")
3514 (sexp :tag "Allowed chars in post ")
3515 (sexp :tag "Forbidden chars in border ")
3516 (sexp :tag "Regexp for body ")
3517 (integer :tag "number of newlines allowed")
3518 (option (boolean :tag "Please ignore this button"))))
3520 (defcustom org-emphasis-alist
3521 `(("*" bold "<b>" "</b>")
3522 ("/" italic "<i>" "</i>")
3523 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3524 ("=" org-code "<code>" "</code>" verbatim)
3525 ("~" org-verbatim "<code>" "</code>" verbatim)
3526 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3527 "<del>" "</del>")
3529 "Special syntax for emphasized text.
3530 Text starting and ending with a special character will be emphasized, for
3531 example *bold*, _underlined_ and /italic/. This variable sets the marker
3532 characters, the face to be used by font-lock for highlighting in Org-mode
3533 Emacs buffers, and the HTML tags to be used for this.
3534 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3535 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3536 Use customize to modify this, or restart Emacs after changing it."
3537 :group 'org-appearance
3538 :set 'org-set-emph-re
3539 :type '(repeat
3540 (list
3541 (string :tag "Marker character")
3542 (choice
3543 (face :tag "Font-lock-face")
3544 (plist :tag "Face property list"))
3545 (string :tag "HTML start tag")
3546 (string :tag "HTML end tag")
3547 (option (const verbatim)))))
3549 (defvar org-protecting-blocks
3550 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3551 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3552 This is needed for font-lock setup.")
3554 ;;; Miscellaneous options
3556 (defgroup org-completion nil
3557 "Completion in Org-mode."
3558 :tag "Org Completion"
3559 :group 'org)
3561 (defcustom org-completion-use-ido nil
3562 "Non-nil means use ido completion wherever possible.
3563 Note that `ido-mode' must be active for this variable to be relevant.
3564 If you decide to turn this variable on, you might well want to turn off
3565 `org-outline-path-complete-in-steps'.
3566 See also `org-completion-use-iswitchb'."
3567 :group 'org-completion
3568 :type 'boolean)
3570 (defcustom org-completion-use-iswitchb nil
3571 "Non-nil means use iswitchb completion wherever possible.
3572 Note that `iswitchb-mode' must be active for this variable to be relevant.
3573 If you decide to turn this variable on, you might well want to turn off
3574 `org-outline-path-complete-in-steps'.
3575 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3576 :group 'org-completion
3577 :type 'boolean)
3579 (defcustom org-completion-fallback-command 'hippie-expand
3580 "The expansion command called by \\[pcomplete] in normal context.
3581 Normal means, no org-mode-specific context."
3582 :group 'org-completion
3583 :type 'function)
3585 ;;; Functions and variables from their packages
3586 ;; Declared here to avoid compiler warnings
3588 ;; XEmacs only
3589 (defvar outline-mode-menu-heading)
3590 (defvar outline-mode-menu-show)
3591 (defvar outline-mode-menu-hide)
3592 (defvar zmacs-regions) ; XEmacs regions
3594 ;; Emacs only
3595 (defvar mark-active)
3597 ;; Various packages
3598 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3599 (declare-function calendar-forward-day "cal-move" (arg))
3600 (declare-function calendar-goto-date "cal-move" (date))
3601 (declare-function calendar-goto-today "cal-move" ())
3602 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3603 (defvar calc-embedded-close-formula)
3604 (defvar calc-embedded-open-formula)
3605 (declare-function cdlatex-tab "ext:cdlatex" ())
3606 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3607 (defvar font-lock-unfontify-region-function)
3608 (declare-function iswitchb-read-buffer "iswitchb"
3609 (prompt &optional default require-match start matches-set))
3610 (defvar iswitchb-temp-buflist)
3611 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3612 (defvar org-agenda-tags-todo-honor-ignore-options)
3613 (declare-function org-agenda-skip "org-agenda" ())
3614 (declare-function
3615 org-format-agenda-item "org-agenda"
3616 (extra txt &optional category tags dotime noprefix remove-re habitp))
3617 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3618 (declare-function org-agenda-change-all-lines "org-agenda"
3619 (newhead hdmarker &optional fixface just-this))
3620 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3621 (declare-function org-agenda-maybe-redo "org-agenda" ())
3622 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3623 (beg end))
3624 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3625 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3626 "org-agenda" (&optional end))
3627 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3628 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3629 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3630 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3631 (declare-function org-indent-mode "org-indent" (&optional arg))
3632 (declare-function parse-time-string "parse-time" (string))
3633 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3634 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3635 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3636 (defvar remember-data-file)
3637 (defvar texmathp-why)
3638 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3639 (declare-function table--at-cell-p "table" (position &optional object at-column))
3641 (defvar w3m-current-url)
3642 (defvar w3m-current-title)
3644 (defvar org-latex-regexps)
3646 ;;; Autoload and prepare some org modules
3648 ;; Some table stuff that needs to be defined here, because it is used
3649 ;; by the functions setting up org-mode or checking for table context.
3651 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3652 "Detect an org-type or table-type table.")
3653 (defconst org-table-line-regexp "^[ \t]*|"
3654 "Detect an org-type table line.")
3655 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3656 "Detect an org-type table line.")
3657 (defconst org-table-hline-regexp "^[ \t]*|-"
3658 "Detect an org-type table hline.")
3659 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3660 "Detect a table-type table hline.")
3661 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3662 "Detect the first line outside a table when searching from within it.
3663 This works for both table types.")
3665 ;; Autoload the functions in org-table.el that are needed by functions here.
3667 (eval-and-compile
3668 (org-autoload "org-table"
3669 '(org-table-align org-table-begin org-table-blank-field
3670 org-table-convert org-table-convert-region org-table-copy-down
3671 org-table-copy-region org-table-create
3672 org-table-create-or-convert-from-region
3673 org-table-create-with-table.el org-table-current-dline
3674 org-table-cut-region org-table-delete-column org-table-edit-field
3675 org-table-edit-formulas org-table-end org-table-eval-formula
3676 org-table-export org-table-field-info
3677 org-table-get-stored-formulas org-table-goto-column
3678 org-table-hline-and-move org-table-import org-table-insert-column
3679 org-table-insert-hline org-table-insert-row org-table-iterate
3680 org-table-justify-field-maybe org-table-kill-row
3681 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3682 org-table-move-column org-table-move-column-left
3683 org-table-move-column-right org-table-move-row
3684 org-table-move-row-down org-table-move-row-up
3685 org-table-next-field org-table-next-row org-table-paste-rectangle
3686 org-table-previous-field org-table-recalculate
3687 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3688 org-table-toggle-coordinate-overlays
3689 org-table-toggle-formula-debugger org-table-wrap-region
3690 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3691 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3692 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3694 (defun org-at-table-p (&optional table-type)
3695 "Return t if the cursor is inside an org-type table.
3696 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3697 (if org-enable-table-editor
3698 (save-excursion
3699 (beginning-of-line 1)
3700 (looking-at (if table-type org-table-any-line-regexp
3701 org-table-line-regexp)))
3702 nil))
3703 (defsubst org-table-p () (org-at-table-p))
3705 (defun org-at-table.el-p ()
3706 "Return t if and only if we are at a table.el table."
3707 (and (org-at-table-p 'any)
3708 (save-excursion
3709 (goto-char (org-table-begin 'any))
3710 (looking-at org-table1-hline-regexp))))
3711 (defun org-table-recognize-table.el ()
3712 "If there is a table.el table nearby, recognize it and move into it."
3713 (if org-table-tab-recognizes-table.el
3714 (if (org-at-table.el-p)
3715 (progn
3716 (beginning-of-line 1)
3717 (if (looking-at org-table-dataline-regexp)
3719 (if (looking-at org-table1-hline-regexp)
3720 (progn
3721 (beginning-of-line 2)
3722 (if (looking-at org-table-any-border-regexp)
3723 (beginning-of-line -1)))))
3724 (if (re-search-forward "|" (org-table-end t) t)
3725 (progn
3726 (require 'table)
3727 (if (table--at-cell-p (point))
3729 (message "recognizing table.el table...")
3730 (table-recognize-table)
3731 (message "recognizing table.el table...done")))
3732 (error "This should not happen"))
3734 nil)
3735 nil))
3737 (defun org-at-table-hline-p ()
3738 "Return t if the cursor is inside a hline in a table."
3739 (if org-enable-table-editor
3740 (save-excursion
3741 (beginning-of-line 1)
3742 (looking-at org-table-hline-regexp))
3743 nil))
3745 (defvar org-table-clean-did-remove-column nil)
3747 (defun org-table-map-tables (function &optional quietly)
3748 "Apply FUNCTION to the start of all tables in the buffer."
3749 (save-excursion
3750 (save-restriction
3751 (widen)
3752 (goto-char (point-min))
3753 (while (re-search-forward org-table-any-line-regexp nil t)
3754 (unless quietly
3755 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3756 (beginning-of-line 1)
3757 (when (looking-at org-table-line-regexp)
3758 (save-excursion (funcall function))
3759 (or (looking-at org-table-line-regexp)
3760 (forward-char 1)))
3761 (re-search-forward org-table-any-border-regexp nil 1))))
3762 (unless quietly (message "Mapping tables: done")))
3764 ;; Declare and autoload functions from org-exp.el & Co
3766 (declare-function org-default-export-plist "org-exp")
3767 (declare-function org-infile-export-plist "org-exp")
3768 (declare-function org-get-current-options "org-exp")
3769 (eval-and-compile
3770 (org-autoload "org-exp"
3771 '(org-export org-export-visible
3772 org-insert-export-options-template
3773 org-table-clean-before-export))
3774 (org-autoload "org-ascii"
3775 '(org-export-as-ascii org-export-ascii-preprocess
3776 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3777 org-export-region-as-ascii))
3778 (org-autoload "org-latex"
3779 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3780 org-replace-region-by-latex org-export-region-as-latex
3781 org-export-as-latex org-export-as-pdf
3782 org-export-as-pdf-and-open))
3783 (org-autoload "org-html"
3784 '(org-export-as-html-and-open
3785 org-export-as-html-batch org-export-as-html-to-buffer
3786 org-replace-region-by-html org-export-region-as-html
3787 org-export-as-html))
3788 (org-autoload "org-docbook"
3789 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3790 org-replace-region-by-docbook org-export-region-as-docbook
3791 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3792 org-export-as-docbook))
3793 (org-autoload "org-icalendar"
3794 '(org-export-icalendar-this-file
3795 org-export-icalendar-all-agenda-files
3796 org-export-icalendar-combine-agenda-files))
3797 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3798 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3800 ;; Declare and autoload functions from org-agenda.el
3802 (eval-and-compile
3803 (org-autoload "org-agenda"
3804 '(org-agenda org-agenda-list org-search-view
3805 org-todo-list org-tags-view org-agenda-list-stuck-projects
3806 org-diary org-agenda-to-appt
3807 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3809 ;; Autoload org-remember
3811 (eval-and-compile
3812 (org-autoload "org-remember"
3813 '(org-remember-insinuate org-remember-annotation
3814 org-remember-apply-template org-remember org-remember-handler)))
3816 (eval-and-compile
3817 (org-autoload "org-capture"
3818 '(org-capture org-capture-insert-template-here
3819 org-capture-import-remember-templates)))
3821 ;; Autoload org-clock.el
3823 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3824 (beg end))
3825 (declare-function org-clock-update-mode-line "org-clock" ())
3826 (declare-function org-resolve-clocks "org-clock"
3827 (&optional also-non-dangling-p prompt last-valid))
3828 (defvar org-clock-start-time)
3829 (defvar org-clock-marker (make-marker)
3830 "Marker recording the last clock-in.")
3831 (defvar org-clock-hd-marker (make-marker)
3832 "Marker recording the last clock-in, but the headline position.")
3833 (defvar org-clock-heading ""
3834 "The heading of the current clock entry.")
3835 (defun org-clock-is-active ()
3836 "Return non-nil if clock is currently running.
3837 The return value is actually the clock marker."
3838 (marker-buffer org-clock-marker))
3840 (eval-and-compile
3841 (org-autoload
3842 "org-clock"
3843 '(org-clock-in org-clock-out org-clock-cancel
3844 org-clock-goto org-clock-sum org-clock-display
3845 org-clock-remove-overlays org-clock-report
3846 org-clocktable-shift org-dblock-write:clocktable
3847 org-get-clocktable org-resolve-clocks)))
3849 (defun org-clock-update-time-maybe ()
3850 "If this is a CLOCK line, update it and return t.
3851 Otherwise, return nil."
3852 (interactive)
3853 (save-excursion
3854 (beginning-of-line 1)
3855 (skip-chars-forward " \t")
3856 (when (looking-at org-clock-string)
3857 (let ((re (concat "[ \t]*" org-clock-string
3858 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3859 "\\([ \t]*=>.*\\)?\\)?"))
3860 ts te h m s neg)
3861 (cond
3862 ((not (looking-at re))
3863 nil)
3864 ((not (match-end 2))
3865 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3866 (> org-clock-marker (point))
3867 (<= org-clock-marker (point-at-eol)))
3868 ;; The clock is running here
3869 (setq org-clock-start-time
3870 (apply 'encode-time
3871 (org-parse-time-string (match-string 1))))
3872 (org-clock-update-mode-line)))
3874 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3875 (end-of-line 1)
3876 (setq ts (match-string 1)
3877 te (match-string 3))
3878 (setq s (- (org-float-time
3879 (apply 'encode-time (org-parse-time-string te)))
3880 (org-float-time
3881 (apply 'encode-time (org-parse-time-string ts))))
3882 neg (< s 0)
3883 s (abs s)
3884 h (floor (/ s 3600))
3885 s (- s (* 3600 h))
3886 m (floor (/ s 60))
3887 s (- s (* 60 s)))
3888 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3889 t))))))
3891 (defun org-check-running-clock ()
3892 "Check if the current buffer contains the running clock.
3893 If yes, offer to stop it and to save the buffer with the changes."
3894 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3895 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3896 (buffer-name))))
3897 (org-clock-out)
3898 (when (y-or-n-p "Save changed buffer?")
3899 (save-buffer))))
3901 (defun org-clocktable-try-shift (dir n)
3902 "Check if this line starts a clock table, if yes, shift the time block."
3903 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3904 (org-clocktable-shift dir n)))
3906 ;; Autoload org-timer.el
3908 (eval-and-compile
3909 (org-autoload
3910 "org-timer"
3911 '(org-timer-start org-timer org-timer-item
3912 org-timer-change-times-in-region
3913 org-timer-set-timer
3914 org-timer-reset-timers
3915 org-timer-show-remaining-time)))
3917 ;; Autoload org-feed.el
3919 (eval-and-compile
3920 (org-autoload
3921 "org-feed"
3922 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3925 ;; Autoload org-indent.el
3927 ;; Define the variable already here, to make sure we have it.
3928 (defvar org-indent-mode nil
3929 "Non-nil if Org-Indent mode is enabled.
3930 Use the command `org-indent-mode' to change this variable.")
3932 (eval-and-compile
3933 (org-autoload
3934 "org-indent"
3935 '(org-indent-mode)))
3937 ;; Autoload org-mobile.el
3939 (eval-and-compile
3940 (org-autoload
3941 "org-mobile"
3942 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
3944 ;; Autoload archiving code
3945 ;; The stuff that is needed for cycling and tags has to be defined here.
3947 (defgroup org-archive nil
3948 "Options concerning archiving in Org-mode."
3949 :tag "Org Archive"
3950 :group 'org-structure)
3952 (defcustom org-archive-location "%s_archive::"
3953 "The location where subtrees should be archived.
3955 The value of this variable is a string, consisting of two parts,
3956 separated by a double-colon. The first part is a filename and
3957 the second part is a headline.
3959 When the filename is omitted, archiving happens in the same file.
3960 %s in the filename will be replaced by the current file
3961 name (without the directory part). Archiving to a different file
3962 is useful to keep archived entries from contributing to the
3963 Org-mode Agenda.
3965 The archived entries will be filed as subtrees of the specified
3966 headline. When the headline is omitted, the subtrees are simply
3967 filed away at the end of the file, as top-level entries. Also in
3968 the heading you can use %s to represent the file name, this can be
3969 useful when using the same archive for a number of different files.
3971 Here are a few examples:
3972 \"%s_archive::\"
3973 If the current file is Projects.org, archive in file
3974 Projects.org_archive, as top-level trees. This is the default.
3976 \"::* Archived Tasks\"
3977 Archive in the current file, under the top-level headline
3978 \"* Archived Tasks\".
3980 \"~/org/archive.org::\"
3981 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3983 \"~/org/archive.org::From %s\"
3984 Archive in file ~/org/archive.org (absolute path), under headlines
3985 \"From FILENAME\" where file name is the current file name.
3987 \"basement::** Finished Tasks\"
3988 Archive in file ./basement (relative path), as level 3 trees
3989 below the level 2 heading \"** Finished Tasks\".
3991 You may set this option on a per-file basis by adding to the buffer a
3992 line like
3994 #+ARCHIVE: basement::** Finished Tasks
3996 You may also define it locally for a subtree by setting an ARCHIVE property
3997 in the entry. If such a property is found in an entry, or anywhere up
3998 the hierarchy, it will be used."
3999 :group 'org-archive
4000 :type 'string)
4002 (defcustom org-archive-tag "ARCHIVE"
4003 "The tag that marks a subtree as archived.
4004 An archived subtree does not open during visibility cycling, and does
4005 not contribute to the agenda listings.
4006 After changing this, font-lock must be restarted in the relevant buffers to
4007 get the proper fontification."
4008 :group 'org-archive
4009 :group 'org-keywords
4010 :type 'string)
4012 (defcustom org-agenda-skip-archived-trees t
4013 "Non-nil means the agenda will skip any items located in archived trees.
4014 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4015 variable is no longer recommended, you should leave it at the value t.
4016 Instead, use the key `v' to cycle the archives-mode in the agenda."
4017 :group 'org-archive
4018 :group 'org-agenda-skip
4019 :type 'boolean)
4021 (defcustom org-columns-skip-archived-trees t
4022 "Non-nil means ignore archived trees when creating column view."
4023 :group 'org-archive
4024 :group 'org-properties
4025 :type 'boolean)
4027 (defcustom org-cycle-open-archived-trees nil
4028 "Non-nil means `org-cycle' will open archived trees.
4029 An archived tree is a tree marked with the tag ARCHIVE.
4030 When nil, archived trees will stay folded. You can still open them with
4031 normal outline commands like `show-all', but not with the cycling commands."
4032 :group 'org-archive
4033 :group 'org-cycle
4034 :type 'boolean)
4036 (defcustom org-sparse-tree-open-archived-trees nil
4037 "Non-nil means sparse tree construction shows matches in archived trees.
4038 When nil, matches in these trees are highlighted, but the trees are kept in
4039 collapsed state."
4040 :group 'org-archive
4041 :group 'org-sparse-trees
4042 :type 'boolean)
4044 (defun org-cycle-hide-archived-subtrees (state)
4045 "Re-hide all archived subtrees after a visibility state change."
4046 (when (and (not org-cycle-open-archived-trees)
4047 (not (memq state '(overview folded))))
4048 (save-excursion
4049 (let* ((globalp (memq state '(contents all)))
4050 (beg (if globalp (point-min) (point)))
4051 (end (if globalp (point-max) (org-end-of-subtree t))))
4052 (org-hide-archived-subtrees beg end)
4053 (goto-char beg)
4054 (if (looking-at (concat ".*:" org-archive-tag ":"))
4055 (message "%s" (substitute-command-keys
4056 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4058 (defun org-force-cycle-archived ()
4059 "Cycle subtree even if it is archived."
4060 (interactive)
4061 (setq this-command 'org-cycle)
4062 (let ((org-cycle-open-archived-trees t))
4063 (call-interactively 'org-cycle)))
4065 (defun org-hide-archived-subtrees (beg end)
4066 "Re-hide all archived subtrees after a visibility state change."
4067 (save-excursion
4068 (let* ((re (concat ":" org-archive-tag ":")))
4069 (goto-char beg)
4070 (while (re-search-forward re end t)
4071 (when (org-on-heading-p)
4072 (org-flag-subtree t)
4073 (org-end-of-subtree t))))))
4075 (defun org-flag-subtree (flag)
4076 (save-excursion
4077 (org-back-to-heading t)
4078 (outline-end-of-heading)
4079 (outline-flag-region (point)
4080 (progn (org-end-of-subtree t) (point))
4081 flag)))
4083 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4085 (eval-and-compile
4086 (org-autoload "org-archive"
4087 '(org-add-archive-files org-archive-subtree
4088 org-archive-to-archive-sibling org-toggle-archive-tag
4089 org-archive-subtree-default
4090 org-archive-subtree-default-with-confirmation)))
4092 ;; Autoload Column View Code
4094 (declare-function org-columns-number-to-string "org-colview")
4095 (declare-function org-columns-get-format-and-top-level "org-colview")
4096 (declare-function org-columns-compute "org-colview")
4098 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4099 '(org-columns-number-to-string org-columns-get-format-and-top-level
4100 org-columns-compute org-agenda-columns org-columns-remove-overlays
4101 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4103 ;; Autoload ID code
4105 (declare-function org-id-store-link "org-id")
4106 (declare-function org-id-locations-load "org-id")
4107 (declare-function org-id-locations-save "org-id")
4108 (defvar org-id-track-globally)
4109 (org-autoload "org-id"
4110 '(org-id-get-create org-id-new org-id-copy org-id-get
4111 org-id-get-with-outline-path-completion
4112 org-id-get-with-outline-drilling org-id-store-link
4113 org-id-goto org-id-find org-id-store-link))
4115 ;; Autoload Plotting Code
4117 (org-autoload "org-plot"
4118 '(org-plot/gnuplot))
4120 ;;; Variables for pre-computed regular expressions, all buffer local
4122 (defvar org-drawer-regexp nil
4123 "Matches first line of a hidden block.")
4124 (make-variable-buffer-local 'org-drawer-regexp)
4125 (defvar org-todo-regexp nil
4126 "Matches any of the TODO state keywords.")
4127 (make-variable-buffer-local 'org-todo-regexp)
4128 (defvar org-not-done-regexp nil
4129 "Matches any of the TODO state keywords except the last one.")
4130 (make-variable-buffer-local 'org-not-done-regexp)
4131 (defvar org-not-done-heading-regexp nil
4132 "Matches a TODO headline that is not done.")
4133 (make-variable-buffer-local 'org-not-done-regexp)
4134 (defvar org-todo-line-regexp nil
4135 "Matches a headline and puts TODO state into group 2 if present.")
4136 (make-variable-buffer-local 'org-todo-line-regexp)
4137 (defvar org-complex-heading-regexp nil
4138 "Matches a headline and puts everything into groups:
4139 group 1: the stars
4140 group 2: The todo keyword, maybe
4141 group 3: Priority cookie
4142 group 4: True headline
4143 group 5: Tags")
4144 (make-variable-buffer-local 'org-complex-heading-regexp)
4145 (defvar org-complex-heading-regexp-format nil
4146 "Printf format to make regexp to match an exact headline.
4147 This regexp will match the headline of any node which hase the exact
4148 headline text that is put into the format, but may have any TODO state,
4149 priority and tags.")
4150 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4151 (defvar org-todo-line-tags-regexp nil
4152 "Matches a headline and puts TODO state into group 2 if present.
4153 Also put tags into group 4 if tags are present.")
4154 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4155 (defvar org-nl-done-regexp nil
4156 "Matches newline followed by a headline with the DONE keyword.")
4157 (make-variable-buffer-local 'org-nl-done-regexp)
4158 (defvar org-looking-at-done-regexp nil
4159 "Matches the DONE keyword a point.")
4160 (make-variable-buffer-local 'org-looking-at-done-regexp)
4161 (defvar org-ds-keyword-length 12
4162 "Maximum length of the Deadline and SCHEDULED keywords.")
4163 (make-variable-buffer-local 'org-ds-keyword-length)
4164 (defvar org-deadline-regexp nil
4165 "Matches the DEADLINE keyword.")
4166 (make-variable-buffer-local 'org-deadline-regexp)
4167 (defvar org-deadline-time-regexp nil
4168 "Matches the DEADLINE keyword together with a time stamp.")
4169 (make-variable-buffer-local 'org-deadline-time-regexp)
4170 (defvar org-deadline-line-regexp nil
4171 "Matches the DEADLINE keyword and the rest of the line.")
4172 (make-variable-buffer-local 'org-deadline-line-regexp)
4173 (defvar org-scheduled-regexp nil
4174 "Matches the SCHEDULED keyword.")
4175 (make-variable-buffer-local 'org-scheduled-regexp)
4176 (defvar org-scheduled-time-regexp nil
4177 "Matches the SCHEDULED keyword together with a time stamp.")
4178 (make-variable-buffer-local 'org-scheduled-time-regexp)
4179 (defvar org-closed-time-regexp nil
4180 "Matches the CLOSED keyword together with a time stamp.")
4181 (make-variable-buffer-local 'org-closed-time-regexp)
4183 (defvar org-keyword-time-regexp nil
4184 "Matches any of the 4 keywords, together with the time stamp.")
4185 (make-variable-buffer-local 'org-keyword-time-regexp)
4186 (defvar org-keyword-time-not-clock-regexp nil
4187 "Matches any of the 3 keywords, together with the time stamp.")
4188 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4189 (defvar org-maybe-keyword-time-regexp nil
4190 "Matches a timestamp, possibly preceded by a keyword.")
4191 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4192 (defvar org-planning-or-clock-line-re nil
4193 "Matches a line with planning or clock info.")
4194 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4195 (defvar org-all-time-keywords nil
4196 "List of time keywords.")
4197 (make-variable-buffer-local 'org-all-time-keywords)
4199 (defconst org-plain-time-of-day-regexp
4200 (concat
4201 "\\(\\<[012]?[0-9]"
4202 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4203 "\\(--?"
4204 "\\(\\<[012]?[0-9]"
4205 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4206 "\\)?")
4207 "Regular expression to match a plain time or time range.
4208 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4209 groups carry important information:
4210 0 the full match
4211 1 the first time, range or not
4212 8 the second time, if it is a range.")
4214 (defconst org-plain-time-extension-regexp
4215 (concat
4216 "\\(\\<[012]?[0-9]"
4217 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4218 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4219 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4220 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4221 groups carry important information:
4222 0 the full match
4223 7 hours of duration
4224 9 minutes of duration")
4226 (defconst org-stamp-time-of-day-regexp
4227 (concat
4228 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4229 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4230 "\\(--?"
4231 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4232 "Regular expression to match a timestamp time or time range.
4233 After a match, the following groups carry important information:
4234 0 the full match
4235 1 date plus weekday, for back referencing to make sure both times are on the same day
4236 2 the first time, range or not
4237 4 the second time, if it is a range.")
4239 (defconst org-startup-options
4240 '(("fold" org-startup-folded t)
4241 ("overview" org-startup-folded t)
4242 ("nofold" org-startup-folded nil)
4243 ("showall" org-startup-folded nil)
4244 ("showeverything" org-startup-folded showeverything)
4245 ("content" org-startup-folded content)
4246 ("indent" org-startup-indented t)
4247 ("noindent" org-startup-indented nil)
4248 ("hidestars" org-hide-leading-stars t)
4249 ("showstars" org-hide-leading-stars nil)
4250 ("odd" org-odd-levels-only t)
4251 ("oddeven" org-odd-levels-only nil)
4252 ("align" org-startup-align-all-tables t)
4253 ("noalign" org-startup-align-all-tables nil)
4254 ("inlineimages" org-startup-with-inline-images t)
4255 ("noinlineimages" org-startup-with-inline-images nil)
4256 ("customtime" org-display-custom-times t)
4257 ("logdone" org-log-done time)
4258 ("lognotedone" org-log-done note)
4259 ("nologdone" org-log-done nil)
4260 ("lognoteclock-out" org-log-note-clock-out t)
4261 ("nolognoteclock-out" org-log-note-clock-out nil)
4262 ("logrepeat" org-log-repeat state)
4263 ("lognoterepeat" org-log-repeat note)
4264 ("nologrepeat" org-log-repeat nil)
4265 ("logreschedule" org-log-reschedule time)
4266 ("lognotereschedule" org-log-reschedule note)
4267 ("nologreschedule" org-log-reschedule nil)
4268 ("logredeadline" org-log-redeadline time)
4269 ("lognoteredeadline" org-log-redeadline note)
4270 ("nologredeadline" org-log-redeadline nil)
4271 ("logrefile" org-log-refile time)
4272 ("lognoterefile" org-log-refile note)
4273 ("nologrefile" org-log-refile nil)
4274 ("fninline" org-footnote-define-inline t)
4275 ("nofninline" org-footnote-define-inline nil)
4276 ("fnlocal" org-footnote-section nil)
4277 ("fnauto" org-footnote-auto-label t)
4278 ("fnprompt" org-footnote-auto-label nil)
4279 ("fnconfirm" org-footnote-auto-label confirm)
4280 ("fnplain" org-footnote-auto-label plain)
4281 ("fnadjust" org-footnote-auto-adjust t)
4282 ("nofnadjust" org-footnote-auto-adjust nil)
4283 ("constcgs" constants-unit-system cgs)
4284 ("constSI" constants-unit-system SI)
4285 ("noptag" org-tag-persistent-alist nil)
4286 ("hideblocks" org-hide-block-startup t)
4287 ("nohideblocks" org-hide-block-startup nil)
4288 ("beamer" org-startup-with-beamer-mode t)
4289 ("entitiespretty" org-pretty-entities t)
4290 ("entitiesplain" org-pretty-entities nil))
4291 "Variable associated with STARTUP options for org-mode.
4292 Each element is a list of three items: The startup options as written
4293 in the #+STARTUP line, the corresponding variable, and the value to
4294 set this variable to if the option is found. An optional forth element PUSH
4295 means to push this value onto the list in the variable.")
4297 (defun org-set-regexps-and-options ()
4298 "Precompute regular expressions for current buffer."
4299 (when (org-mode-p)
4300 (org-set-local 'org-todo-kwd-alist nil)
4301 (org-set-local 'org-todo-key-alist nil)
4302 (org-set-local 'org-todo-key-trigger nil)
4303 (org-set-local 'org-todo-keywords-1 nil)
4304 (org-set-local 'org-done-keywords nil)
4305 (org-set-local 'org-todo-heads nil)
4306 (org-set-local 'org-todo-sets nil)
4307 (org-set-local 'org-todo-log-states nil)
4308 (org-set-local 'org-file-properties nil)
4309 (org-set-local 'org-file-tags nil)
4310 (let ((re (org-make-options-regexp
4311 '("CATEGORY" "TODO" "COLUMNS"
4312 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4313 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4314 "OPTIONS")
4315 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4316 (splitre "[ \t]+")
4317 (scripts org-use-sub-superscripts)
4318 kwds kws0 kwsa key log value cat arch tags const links hw dws
4319 tail sep kws1 prio props ftags drawers beamer-p
4320 ext-setup-or-nil setup-contents (start 0))
4321 (save-excursion
4322 (save-restriction
4323 (widen)
4324 (goto-char (point-min))
4325 (while (or (and ext-setup-or-nil
4326 (string-match re ext-setup-or-nil start)
4327 (setq start (match-end 0)))
4328 (and (setq ext-setup-or-nil nil start 0)
4329 (re-search-forward re nil t)))
4330 (setq key (upcase (match-string 1 ext-setup-or-nil))
4331 value (org-match-string-no-properties 2 ext-setup-or-nil))
4332 (if (stringp value) (setq value (org-trim value)))
4333 (cond
4334 ((equal key "CATEGORY")
4335 (setq cat value))
4336 ((member key '("SEQ_TODO" "TODO"))
4337 (push (cons 'sequence (org-split-string value splitre)) kwds))
4338 ((equal key "TYP_TODO")
4339 (push (cons 'type (org-split-string value splitre)) kwds))
4340 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4341 ;; general TODO-like setup
4342 (push (cons (intern (downcase (match-string 1 key)))
4343 (org-split-string value splitre)) kwds))
4344 ((equal key "TAGS")
4345 (setq tags (append tags (if tags '("\\n") nil)
4346 (org-split-string value splitre))))
4347 ((equal key "COLUMNS")
4348 (org-set-local 'org-columns-default-format value))
4349 ((equal key "LINK")
4350 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4351 (push (cons (match-string 1 value)
4352 (org-trim (match-string 2 value)))
4353 links)))
4354 ((equal key "PRIORITIES")
4355 (setq prio (org-split-string value " +")))
4356 ((equal key "PROPERTY")
4357 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4358 (push (cons (match-string 1 value) (match-string 2 value))
4359 props)))
4360 ((equal key "FILETAGS")
4361 (when (string-match "\\S-" value)
4362 (setq ftags
4363 (append
4364 ftags
4365 (apply 'append
4366 (mapcar (lambda (x) (org-split-string x ":"))
4367 (org-split-string value)))))))
4368 ((equal key "DRAWERS")
4369 (setq drawers (org-split-string value splitre)))
4370 ((equal key "CONSTANTS")
4371 (setq const (append const (org-split-string value splitre))))
4372 ((equal key "STARTUP")
4373 (let ((opts (org-split-string value splitre))
4374 l var val)
4375 (while (setq l (pop opts))
4376 (when (setq l (assoc l org-startup-options))
4377 (setq var (nth 1 l) val (nth 2 l))
4378 (if (not (nth 3 l))
4379 (set (make-local-variable var) val)
4380 (if (not (listp (symbol-value var)))
4381 (set (make-local-variable var) nil))
4382 (set (make-local-variable var) (symbol-value var))
4383 (add-to-list var val))))))
4384 ((equal key "ARCHIVE")
4385 (setq arch value)
4386 (remove-text-properties 0 (length arch)
4387 '(face t fontified t) arch))
4388 ((equal key "LATEX_CLASS")
4389 (setq beamer-p (equal value "beamer")))
4390 ((equal key "OPTIONS")
4391 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4392 (setq scripts (read (match-string 2 value)))))
4393 ((equal key "SETUPFILE")
4394 (setq setup-contents (org-file-contents
4395 (expand-file-name
4396 (org-remove-double-quotes value))
4397 'noerror))
4398 (if (not ext-setup-or-nil)
4399 (setq ext-setup-or-nil setup-contents start 0)
4400 (setq ext-setup-or-nil
4401 (concat (substring ext-setup-or-nil 0 start)
4402 "\n" setup-contents "\n"
4403 (substring ext-setup-or-nil start)))))
4404 ))))
4405 (org-set-local 'org-use-sub-superscripts scripts)
4406 (when cat
4407 (org-set-local 'org-category (intern cat))
4408 (push (cons "CATEGORY" cat) props))
4409 (when prio
4410 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4411 (setq prio (mapcar 'string-to-char prio))
4412 (org-set-local 'org-highest-priority (nth 0 prio))
4413 (org-set-local 'org-lowest-priority (nth 1 prio))
4414 (org-set-local 'org-default-priority (nth 2 prio)))
4415 (and props (org-set-local 'org-file-properties (nreverse props)))
4416 (and ftags (org-set-local 'org-file-tags
4417 (mapcar 'org-add-prop-inherited ftags)))
4418 (and drawers (org-set-local 'org-drawers drawers))
4419 (and arch (org-set-local 'org-archive-location arch))
4420 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4421 ;; Process the TODO keywords
4422 (unless kwds
4423 ;; Use the global values as if they had been given locally.
4424 (setq kwds (default-value 'org-todo-keywords))
4425 (if (stringp (car kwds))
4426 (setq kwds (list (cons org-todo-interpretation
4427 (default-value 'org-todo-keywords)))))
4428 (setq kwds (reverse kwds)))
4429 (setq kwds (nreverse kwds))
4430 (let (inter kws kw)
4431 (while (setq kws (pop kwds))
4432 (let ((kws (or
4433 (run-hook-with-args-until-success
4434 'org-todo-setup-filter-hook kws)
4435 kws)))
4436 (setq inter (pop kws) sep (member "|" kws)
4437 kws0 (delete "|" (copy-sequence kws))
4438 kwsa nil
4439 kws1 (mapcar
4440 (lambda (x)
4441 ;; 1 2
4442 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4443 (progn
4444 (setq kw (match-string 1 x)
4445 key (and (match-end 2) (match-string 2 x))
4446 log (org-extract-log-state-settings x))
4447 (push (cons kw (and key (string-to-char key))) kwsa)
4448 (and log (push log org-todo-log-states))
4450 (error "Invalid TODO keyword %s" x)))
4451 kws0)
4452 kwsa (if kwsa (append '((:startgroup))
4453 (nreverse kwsa)
4454 '((:endgroup))))
4455 hw (car kws1)
4456 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4457 tail (list inter hw (car dws) (org-last dws))))
4458 (add-to-list 'org-todo-heads hw 'append)
4459 (push kws1 org-todo-sets)
4460 (setq org-done-keywords (append org-done-keywords dws nil))
4461 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4462 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4463 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4464 (setq org-todo-sets (nreverse org-todo-sets)
4465 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4466 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4467 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4468 ;; Process the constants
4469 (when const
4470 (let (e cst)
4471 (while (setq e (pop const))
4472 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4473 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4474 (setq org-table-formula-constants-local cst)))
4476 ;; Process the tags.
4477 (when tags
4478 (let (e tgs)
4479 (while (setq e (pop tags))
4480 (cond
4481 ((equal e "{") (push '(:startgroup) tgs))
4482 ((equal e "}") (push '(:endgroup) tgs))
4483 ((equal e "\\n") (push '(:newline) tgs))
4484 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4485 (push (cons (match-string 1 e)
4486 (string-to-char (match-string 2 e)))
4487 tgs))
4488 (t (push (list e) tgs))))
4489 (org-set-local 'org-tag-alist nil)
4490 (while (setq e (pop tgs))
4491 (or (and (stringp (car e))
4492 (assoc (car e) org-tag-alist))
4493 (push e org-tag-alist)))))
4495 ;; Compute the regular expressions and other local variables
4496 (if (not org-done-keywords)
4497 (setq org-done-keywords (and org-todo-keywords-1
4498 (list (org-last org-todo-keywords-1)))))
4499 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4500 (length org-scheduled-string)
4501 (length org-clock-string)
4502 (length org-closed-string)))
4503 org-drawer-regexp
4504 (concat "^[ \t]*:\\("
4505 (mapconcat 'regexp-quote org-drawers "\\|")
4506 "\\):[ \t]*$")
4507 org-not-done-keywords
4508 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4509 org-todo-regexp
4510 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4511 "\\|") "\\)\\>")
4512 org-not-done-regexp
4513 (concat "\\<\\("
4514 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4515 "\\)\\>")
4516 org-not-done-heading-regexp
4517 (concat "^\\(\\*+\\)[ \t]+\\("
4518 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4519 "\\)\\>")
4520 org-todo-line-regexp
4521 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4522 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4523 "\\)\\>\\)?[ \t]*\\(.*\\)")
4524 org-complex-heading-regexp
4525 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4526 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4527 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4528 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
4529 org-complex-heading-regexp-format
4530 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4531 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4532 "\\)\\>\\)?"
4533 "\\(?:[ \t]*\\(\\[#.\\]\\)\\)?"
4534 "\\(?:[ \t]*\\(?:\\[[0-9%%/]+\\]\\)\\)?" ;; stats cookie
4535 "[ \t]*\\(%s\\)"
4536 "\\(?:[ \t]*\\(?:\\[[0-9%%/]+\\]\\)\\)?" ;; stats cookie
4537 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?[ \t]*$")
4538 org-nl-done-regexp
4539 (concat "\n\\*+[ \t]+"
4540 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4541 "\\)" "\\>")
4542 org-todo-line-tags-regexp
4543 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4544 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4545 (org-re
4546 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@#%]+:[ \t]*\\)?$\\)"))
4547 org-looking-at-done-regexp
4548 (concat "^" "\\(?:"
4549 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4550 "\\>")
4551 org-deadline-regexp (concat "\\<" org-deadline-string)
4552 org-deadline-time-regexp
4553 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4554 org-deadline-line-regexp
4555 (concat "\\<\\(" org-deadline-string "\\).*")
4556 org-scheduled-regexp
4557 (concat "\\<" org-scheduled-string)
4558 org-scheduled-time-regexp
4559 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4560 org-closed-time-regexp
4561 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4562 org-keyword-time-regexp
4563 (concat "\\<\\(" org-scheduled-string
4564 "\\|" org-deadline-string
4565 "\\|" org-closed-string
4566 "\\|" org-clock-string "\\)"
4567 " *[[<]\\([^]>]+\\)[]>]")
4568 org-keyword-time-not-clock-regexp
4569 (concat "\\<\\(" org-scheduled-string
4570 "\\|" org-deadline-string
4571 "\\|" org-closed-string
4572 "\\)"
4573 " *[[<]\\([^]>]+\\)[]>]")
4574 org-maybe-keyword-time-regexp
4575 (concat "\\(\\<\\(" org-scheduled-string
4576 "\\|" org-deadline-string
4577 "\\|" org-closed-string
4578 "\\|" org-clock-string "\\)\\)?"
4579 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4580 org-planning-or-clock-line-re
4581 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4582 "\\|" org-deadline-string
4583 "\\|" org-closed-string "\\|" org-clock-string
4584 "\\)\\>\\)")
4585 org-all-time-keywords
4586 (mapcar (lambda (w) (substring w 0 -1))
4587 (list org-scheduled-string org-deadline-string
4588 org-clock-string org-closed-string))
4590 (org-compute-latex-and-specials-regexp)
4591 (org-set-font-lock-defaults))))
4593 (defun org-file-contents (file &optional noerror)
4594 "Return the contents of FILE, as a string."
4595 (if (or (not file)
4596 (not (file-readable-p file)))
4597 (if noerror
4598 (progn
4599 (message "Cannot read file \"%s\"" file)
4600 (ding) (sit-for 2)
4602 (error "Cannot read file \"%s\"" file))
4603 (with-temp-buffer
4604 (insert-file-contents file)
4605 (buffer-string))))
4607 (defun org-extract-log-state-settings (x)
4608 "Extract the log state setting from a TODO keyword string.
4609 This will extract info from a string like \"WAIT(w@/!)\"."
4610 (let (kw key log1 log2)
4611 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4612 (setq kw (match-string 1 x)
4613 key (and (match-end 2) (match-string 2 x))
4614 log1 (and (match-end 3) (match-string 3 x))
4615 log2 (and (match-end 4) (match-string 4 x)))
4616 (and (or log1 log2)
4617 (list kw
4618 (and log1 (if (equal log1 "!") 'time 'note))
4619 (and log2 (if (equal log2 "!") 'time 'note)))))))
4621 (defun org-remove-keyword-keys (list)
4622 "Remove a pair of parenthesis at the end of each string in LIST."
4623 (mapcar (lambda (x)
4624 (if (string-match "(.*)$" x)
4625 (substring x 0 (match-beginning 0))
4627 list))
4629 (defun org-assign-fast-keys (alist)
4630 "Assign fast keys to a keyword-key alist.
4631 Respect keys that are already there."
4632 (let (new e (alt ?0))
4633 (while (setq e (pop alist))
4634 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4635 (cdr e)) ;; Key already assigned.
4636 (push e new)
4637 (let ((clist (string-to-list (downcase (car e))))
4638 (used (append new alist)))
4639 (when (= (car clist) ?@)
4640 (pop clist))
4641 (while (and clist (rassoc (car clist) used))
4642 (pop clist))
4643 (unless clist
4644 (while (rassoc alt used)
4645 (incf alt)))
4646 (push (cons (car e) (or (car clist) alt)) new))))
4647 (nreverse new)))
4649 ;;; Some variables used in various places
4651 (defvar org-window-configuration nil
4652 "Used in various places to store a window configuration.")
4653 (defvar org-selected-window nil
4654 "Used in various places to store a window configuration.")
4655 (defvar org-finish-function nil
4656 "Function to be called when `C-c C-c' is used.
4657 This is for getting out of special buffers like remember.")
4660 ;; FIXME: Occasionally check by commenting these, to make sure
4661 ;; no other functions uses these, forgetting to let-bind them.
4662 (defvar entry)
4663 (defvar last-state)
4664 (defvar date)
4666 ;; Defined somewhere in this file, but used before definition.
4667 (defvar org-entities) ;; defined in org-entities.el
4668 (defvar org-struct-menu)
4669 (defvar org-org-menu)
4670 (defvar org-tbl-menu)
4672 ;;;; Define the Org-mode
4674 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4675 (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"))
4678 ;; We use a before-change function to check if a table might need
4679 ;; an update.
4680 (defvar org-table-may-need-update t
4681 "Indicates that a table might need an update.
4682 This variable is set by `org-before-change-function'.
4683 `org-table-align' sets it back to nil.")
4684 (defun org-before-change-function (beg end)
4685 "Every change indicates that a table might need an update."
4686 (setq org-table-may-need-update t))
4687 (defvar org-mode-map)
4688 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4689 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4690 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4691 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4692 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4693 (defvar org-table-buffer-is-an nil)
4694 (defconst org-outline-regexp "\\*+ ")
4696 ;;;###autoload
4697 (define-derived-mode org-mode outline-mode "Org"
4698 "Outline-based notes management and organizer, alias
4699 \"Carsten's outline-mode for keeping track of everything.\"
4701 Org-mode develops organizational tasks around a NOTES file which
4702 contains information about projects as plain text. Org-mode is
4703 implemented on top of outline-mode, which is ideal to keep the content
4704 of large files well structured. It supports ToDo items, deadlines and
4705 time stamps, which magically appear in the diary listing of the Emacs
4706 calendar. Tables are easily created with a built-in table editor.
4707 Plain text URL-like links connect to websites, emails (VM), Usenet
4708 messages (Gnus), BBDB entries, and any files related to the project.
4709 For printing and sharing of notes, an Org-mode file (or a part of it)
4710 can be exported as a structured ASCII or HTML file.
4712 The following commands are available:
4714 \\{org-mode-map}"
4716 ;; Get rid of Outline menus, they are not needed
4717 ;; Need to do this here because define-derived-mode sets up
4718 ;; the keymap so late. Still, it is a waste to call this each time
4719 ;; we switch another buffer into org-mode.
4720 (if (featurep 'xemacs)
4721 (when (boundp 'outline-mode-menu-heading)
4722 ;; Assume this is Greg's port, it uses easymenu
4723 (easy-menu-remove outline-mode-menu-heading)
4724 (easy-menu-remove outline-mode-menu-show)
4725 (easy-menu-remove outline-mode-menu-hide))
4726 (define-key org-mode-map [menu-bar headings] 'undefined)
4727 (define-key org-mode-map [menu-bar hide] 'undefined)
4728 (define-key org-mode-map [menu-bar show] 'undefined))
4730 (org-load-modules-maybe)
4731 (easy-menu-add org-org-menu)
4732 (easy-menu-add org-tbl-menu)
4733 (org-install-agenda-files-menu)
4734 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4735 (add-to-invisibility-spec '(org-cwidth))
4736 (add-to-invisibility-spec '(org-hide-block . t))
4737 (when (featurep 'xemacs)
4738 (org-set-local 'line-move-ignore-invisible t))
4739 (org-set-local 'outline-regexp org-outline-regexp)
4740 (org-set-local 'outline-level 'org-outline-level)
4741 (when (and org-ellipsis
4742 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4743 (fboundp 'make-glyph-code))
4744 (unless org-display-table
4745 (setq org-display-table (make-display-table)))
4746 (set-display-table-slot
4747 org-display-table 4
4748 (vconcat (mapcar
4749 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4750 org-ellipsis)))
4751 (if (stringp org-ellipsis) org-ellipsis "..."))))
4752 (setq buffer-display-table org-display-table))
4753 (org-set-regexps-and-options)
4754 (when (and org-tag-faces (not org-tags-special-faces-re))
4755 ;; tag faces set outside customize.... force initialization.
4756 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4757 ;; Calc embedded
4758 (org-set-local 'calc-embedded-open-mode "# ")
4759 (modify-syntax-entry ?@ "w")
4760 (if org-startup-truncated (setq truncate-lines t))
4761 (org-set-local 'font-lock-unfontify-region-function
4762 'org-unfontify-region)
4763 ;; Activate before-change-function
4764 (org-set-local 'org-table-may-need-update t)
4765 (org-add-hook 'before-change-functions 'org-before-change-function nil
4766 'local)
4767 ;; Check for running clock before killing a buffer
4768 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4769 ;; Paragraphs and auto-filling
4770 (org-set-autofill-regexps)
4771 (setq indent-line-function 'org-indent-line-function)
4772 (org-update-radio-target-regexp)
4773 ;; Beginning/end of defun
4774 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
4775 (org-set-local 'end-of-defun-function 'org-end-of-defun)
4776 ;; Next error for sparse trees
4777 (org-set-local 'next-error-function 'org-occur-next-match)
4778 ;; Make sure dependence stuff works reliably, even for users who set it
4779 ;; too late :-(
4780 (if org-enforce-todo-dependencies
4781 (add-hook 'org-blocker-hook
4782 'org-block-todo-from-children-or-siblings-or-parent)
4783 (remove-hook 'org-blocker-hook
4784 'org-block-todo-from-children-or-siblings-or-parent))
4785 (if org-enforce-todo-checkbox-dependencies
4786 (add-hook 'org-blocker-hook
4787 'org-block-todo-from-checkboxes)
4788 (remove-hook 'org-blocker-hook
4789 'org-block-todo-from-checkboxes))
4791 ;; Comment characters
4792 (org-set-local 'comment-start "#")
4793 (org-set-local 'comment-padding " ")
4795 ;; Align options lines
4796 (org-set-local
4797 'align-mode-rules-list
4798 '((org-in-buffer-settings
4799 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4800 (modes . '(org-mode)))))
4802 ;; Imenu
4803 (org-set-local 'imenu-create-index-function
4804 'org-imenu-get-tree)
4806 ;; Make isearch reveal context
4807 (if (or (featurep 'xemacs)
4808 (not (boundp 'outline-isearch-open-invisible-function)))
4809 ;; Emacs 21 and XEmacs make use of the hook
4810 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4811 ;; Emacs 22 deals with this through a special variable
4812 (org-set-local 'outline-isearch-open-invisible-function
4813 (lambda (&rest ignore) (org-show-context 'isearch))))
4815 ;; Turn on org-beamer-mode?
4816 (and org-startup-with-beamer-mode (org-beamer-mode 1))
4818 ;; Setup the pcomplete hooks
4819 (set (make-local-variable 'pcomplete-command-completion-function)
4820 'org-pcomplete-initial)
4821 (set (make-local-variable 'pcomplete-command-name-function)
4822 'org-command-at-point)
4823 (set (make-local-variable 'pcomplete-default-completion-function)
4824 'ignore)
4825 (set (make-local-variable 'pcomplete-parse-arguments-function)
4826 'org-parse-arguments)
4827 (set (make-local-variable 'pcomplete-termination-string) "")
4829 ;; If empty file that did not turn on org-mode automatically, make it to.
4830 (if (and org-insert-mode-line-in-empty-file
4831 (interactive-p)
4832 (= (point-min) (point-max)))
4833 (insert "# -*- mode: org -*-\n\n"))
4834 (unless org-inhibit-startup
4835 (when org-startup-align-all-tables
4836 (let ((bmp (buffer-modified-p)))
4837 (org-table-map-tables 'org-table-align 'quietly)
4838 (set-buffer-modified-p bmp)))
4839 (when org-startup-with-inline-images
4840 (org-display-inline-images))
4841 (when org-startup-indented
4842 (require 'org-indent)
4843 (org-indent-mode 1))
4844 (unless org-inhibit-startup-visibility-stuff
4845 (org-set-startup-visibility))))
4847 (when (fboundp 'abbrev-table-put)
4848 (abbrev-table-put org-mode-abbrev-table
4849 :parents (list text-mode-abbrev-table)))
4851 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4853 (defun org-current-time ()
4854 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4855 (if (> (car org-time-stamp-rounding-minutes) 1)
4856 (let ((r (car org-time-stamp-rounding-minutes))
4857 (time (decode-time)))
4858 (apply 'encode-time
4859 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4860 (nthcdr 2 time))))
4861 (current-time)))
4863 (defun org-today ()
4864 "Return today date, considering `org-extend-today-until'."
4865 (time-to-days
4866 (time-subtract (current-time)
4867 (list 0 (* 3600 org-extend-today-until) 0))))
4869 ;;;; Font-Lock stuff, including the activators
4871 (defvar org-mouse-map (make-sparse-keymap))
4872 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
4873 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
4874 (when org-mouse-1-follows-link
4875 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4876 (when org-tab-follows-link
4877 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4878 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4880 (require 'font-lock)
4882 (defconst org-non-link-chars "]\t\n\r<>")
4883 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4884 "shell" "elisp" "doi" "message"))
4885 (defvar org-link-types-re nil
4886 "Matches a link that has a url-like prefix like \"http:\"")
4887 (defvar org-link-re-with-space nil
4888 "Matches a link with spaces, optional angular brackets around it.")
4889 (defvar org-link-re-with-space2 nil
4890 "Matches a link with spaces, optional angular brackets around it.")
4891 (defvar org-link-re-with-space3 nil
4892 "Matches a link with spaces, only for internal part in bracket links.")
4893 (defvar org-angle-link-re nil
4894 "Matches link with angular brackets, spaces are allowed.")
4895 (defvar org-plain-link-re nil
4896 "Matches plain link, without spaces.")
4897 (defvar org-bracket-link-regexp nil
4898 "Matches a link in double brackets.")
4899 (defvar org-bracket-link-analytic-regexp nil
4900 "Regular expression used to analyze links.
4901 Here is what the match groups contain after a match:
4902 1: http:
4903 2: http
4904 3: path
4905 4: [desc]
4906 5: desc")
4907 (defvar org-bracket-link-analytic-regexp++ nil
4908 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
4909 (defvar org-any-link-re nil
4910 "Regular expression matching any link.")
4912 (defcustom org-match-sexp-depth 3
4913 "Number of stacked braces for sub/superscript matching.
4914 This has to be set before loading org.el to be effective."
4915 :group 'org-export-translation ; ??????????????????????????/
4916 :type 'integer)
4918 (defun org-create-multibrace-regexp (left right n)
4919 "Create a regular expression which will match a balanced sexp.
4920 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
4921 as single character strings.
4922 The regexp returned will match the entire expression including the
4923 delimiters. It will also define a single group which contains the
4924 match except for the outermost delimiters. The maximum depth of
4925 stacked delimiters is N. Escaping delimiters is not possible."
4926 (let* ((nothing (concat "[^" left right "]*?"))
4927 (or "\\|")
4928 (re nothing)
4929 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
4930 (while (> n 1)
4931 (setq n (1- n)
4932 re (concat re or next)
4933 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
4934 (concat left "\\(" re "\\)" right)))
4936 (defvar org-match-substring-regexp
4937 (concat
4938 "\\([^\\]\\)\\([_^]\\)\\("
4939 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
4940 "\\|"
4941 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
4942 "\\|"
4943 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
4944 "The regular expression matching a sub- or superscript.")
4946 (defvar org-match-substring-with-braces-regexp
4947 (concat
4948 "\\([^\\]\\)\\([_^]\\)\\("
4949 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
4950 "\\)")
4951 "The regular expression matching a sub- or superscript, forcing braces.")
4953 (defun org-make-link-regexps ()
4954 "Update the link regular expressions.
4955 This should be called after the variable `org-link-types' has changed."
4956 (setq org-link-types-re
4957 (concat
4958 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
4959 org-link-re-with-space
4960 (concat
4961 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4962 "\\([^" org-non-link-chars " ]"
4963 "[^" org-non-link-chars "]*"
4964 "[^" org-non-link-chars " ]\\)>?")
4965 org-link-re-with-space2
4966 (concat
4967 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4968 "\\([^" org-non-link-chars " ]"
4969 "[^\t\n\r]*"
4970 "[^" org-non-link-chars " ]\\)>?")
4971 org-link-re-with-space3
4972 (concat
4973 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4974 "\\([^" org-non-link-chars " ]"
4975 "[^\t\n\r]*\\)")
4976 org-angle-link-re
4977 (concat
4978 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4979 "\\([^" org-non-link-chars " ]"
4980 "[^" org-non-link-chars "]*"
4981 "\\)>")
4982 org-plain-link-re
4983 (concat
4984 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4985 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
4986 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4987 org-bracket-link-regexp
4988 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4989 org-bracket-link-analytic-regexp
4990 (concat
4991 "\\[\\["
4992 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
4993 "\\([^]]+\\)"
4994 "\\]"
4995 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4996 "\\]")
4997 org-bracket-link-analytic-regexp++
4998 (concat
4999 "\\[\\["
5000 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5001 "\\([^]]+\\)"
5002 "\\]"
5003 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5004 "\\]")
5005 org-any-link-re
5006 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5007 org-angle-link-re "\\)\\|\\("
5008 org-plain-link-re "\\)")))
5010 (org-make-link-regexps)
5012 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
5013 "Regular expression for fast time stamp matching.")
5014 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?\\)[]>]"
5015 "Regular expression for fast time stamp matching.")
5016 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5017 "Regular expression matching time strings for analysis.
5018 This one does not require the space after the date, so it can be used
5019 on a string that terminates immediately after the date.")
5020 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5021 "Regular expression matching time strings for analysis.")
5022 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5023 "Regular expression matching time stamps, with groups.")
5024 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5025 "Regular expression matching time stamps (also [..]), with groups.")
5026 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5027 "Regular expression matching a time stamp range.")
5028 (defconst org-tr-regexp-both
5029 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5030 "Regular expression matching a time stamp range.")
5031 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5032 org-ts-regexp "\\)?")
5033 "Regular expression matching a time stamp or time stamp range.")
5034 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5035 org-ts-regexp-both "\\)?")
5036 "Regular expression matching a time stamp or time stamp range.
5037 The time stamps may be either active or inactive.")
5039 (defvar org-emph-face nil)
5041 (defun org-do-emphasis-faces (limit)
5042 "Run through the buffer and add overlays to links."
5043 (let (rtn a)
5044 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5045 (if (not (= (char-after (match-beginning 3))
5046 (char-after (match-beginning 4))))
5047 (progn
5048 (setq rtn t)
5049 (setq a (assoc (match-string 3) org-emphasis-alist))
5050 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5051 'face
5052 (nth 1 a))
5053 (and (nth 4 a)
5054 (org-remove-flyspell-overlays-in
5055 (match-beginning 0) (match-end 0)))
5056 (add-text-properties (match-beginning 2) (match-end 2)
5057 '(font-lock-multiline t org-emphasis t))
5058 (when org-hide-emphasis-markers
5059 (add-text-properties (match-end 4) (match-beginning 5)
5060 '(invisible org-link))
5061 (add-text-properties (match-beginning 3) (match-end 3)
5062 '(invisible org-link)))))
5063 (backward-char 1))
5064 rtn))
5066 (defun org-emphasize (&optional char)
5067 "Insert or change an emphasis, i.e. a font like bold or italic.
5068 If there is an active region, change that region to a new emphasis.
5069 If there is no region, just insert the marker characters and position
5070 the cursor between them.
5071 CHAR should be either the marker character, or the first character of the
5072 HTML tag associated with that emphasis. If CHAR is a space, the means
5073 to remove the emphasis of the selected region.
5074 If char is not given (for example in an interactive call) it
5075 will be prompted for."
5076 (interactive)
5077 (let ((eal org-emphasis-alist) e det
5078 (erc org-emphasis-regexp-components)
5079 (prompt "")
5080 (string "") beg end move tag c s)
5081 (if (org-region-active-p)
5082 (setq beg (region-beginning) end (region-end)
5083 string (buffer-substring beg end))
5084 (setq move t))
5086 (while (setq e (pop eal))
5087 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5088 c (aref tag 0))
5089 (push (cons c (string-to-char (car e))) det)
5090 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5091 (substring tag 1)))))
5092 (setq det (nreverse det))
5093 (unless char
5094 (message "%s" (concat "Emphasis marker or tag:" prompt))
5095 (setq char (read-char-exclusive)))
5096 (setq char (or (cdr (assoc char det)) char))
5097 (if (equal char ?\ )
5098 (setq s "" move nil)
5099 (unless (assoc (char-to-string char) org-emphasis-alist)
5100 (error "No such emphasis marker: \"%c\"" char))
5101 (setq s (char-to-string char)))
5102 (while (and (> (length string) 1)
5103 (equal (substring string 0 1) (substring string -1))
5104 (assoc (substring string 0 1) org-emphasis-alist))
5105 (setq string (substring string 1 -1)))
5106 (setq string (concat s string s))
5107 (if beg (delete-region beg end))
5108 (unless (or (bolp)
5109 (string-match (concat "[" (nth 0 erc) "\n]")
5110 (char-to-string (char-before (point)))))
5111 (insert " "))
5112 (unless (or (eobp)
5113 (string-match (concat "[" (nth 1 erc) "\n]")
5114 (char-to-string (char-after (point)))))
5115 (insert " ") (backward-char 1))
5116 (insert string)
5117 (and move (backward-char 1))))
5119 (defconst org-nonsticky-props
5120 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5122 (defsubst org-rear-nonsticky-at (pos)
5123 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5125 (defun org-activate-plain-links (limit)
5126 "Run through the buffer and add overlays to links."
5127 (catch 'exit
5128 (let (f)
5129 (if (re-search-forward org-plain-link-re limit t)
5130 (progn
5131 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5132 (setq f (get-text-property (match-beginning 0) 'face))
5133 (if (or (eq f 'org-tag)
5134 (and (listp f) (memq 'org-tag f)))
5136 (add-text-properties (match-beginning 0) (match-end 0)
5137 (list 'mouse-face 'highlight
5138 'face 'org-link
5139 'keymap org-mouse-map))
5140 (org-rear-nonsticky-at (match-end 0)))
5141 t)))))
5143 (defun org-activate-code (limit)
5144 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
5145 (progn
5146 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5147 (remove-text-properties (match-beginning 0) (match-end 0)
5148 '(display t invisible t intangible t))
5149 t)))
5151 (defcustom org-src-fontify-natively nil
5152 "When non-nil, fontify code in code blocks."
5153 :type 'boolean
5154 :group 'org-appearance
5155 :group 'org-babel)
5157 (defun org-fontify-meta-lines-and-blocks (limit)
5158 "Fontify #+ lines and blocks, in the correct ways."
5159 (let ((case-fold-search t))
5160 (if (re-search-forward
5161 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5162 limit t)
5163 (let ((beg (match-beginning 0))
5164 (block-start (match-end 0))
5165 (block-end nil)
5166 (lang (match-string 7))
5167 (beg1 (line-beginning-position 2))
5168 (dc1 (downcase (match-string 2)))
5169 (dc3 (downcase (match-string 3)))
5170 end end1 quoting block-type ovl)
5171 (cond
5172 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
5173 ;; a single line of backend-specific content
5174 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5175 (remove-text-properties (match-beginning 0) (match-end 0)
5176 '(display t invisible t intangible t))
5177 (add-text-properties (match-beginning 1) (match-end 3)
5178 '(font-lock-fontified t face org-meta-line))
5179 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5180 '(font-lock-fontified t face org-block))
5181 ; for backend-specific code
5183 ((and (match-end 4) (equal dc3 "begin"))
5184 ;; Truly a block
5185 (setq block-type (downcase (match-string 5))
5186 quoting (member block-type org-protecting-blocks))
5187 (when (re-search-forward
5188 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5189 nil t) ;; on purpose, we look further than LIMIT
5190 (setq end (match-end 0) end1 (1- (match-beginning 0)))
5191 (setq block-end (match-beginning 0))
5192 (when quoting
5193 (remove-text-properties beg end
5194 '(display t invisible t intangible t)))
5195 (add-text-properties
5196 beg end
5197 '(font-lock-fontified t font-lock-multiline t))
5198 (add-text-properties beg beg1 '(face org-meta-line))
5199 (add-text-properties end1 (+ end 1) '(face org-meta-line))
5200 ; for end_src
5201 (cond
5202 ((and lang org-src-fontify-natively)
5203 (org-src-font-lock-fontify-block lang block-start block-end)
5204 ;; remove old background overlays
5205 (mapc (lambda (ov)
5206 (if (eq (overlay-get ov 'face) 'org-block-background)
5207 (delete-overlay ov)))
5208 (overlays-at (/ (+ beg1 block-end) 2)))
5209 ;; add a background overlay
5210 (setq ovl (make-overlay beg1 block-end))
5211 (overlay-put ovl 'face 'org-block-background)
5212 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5213 (quoting
5214 (add-text-properties beg1 (+ end1 1) '(face org-block)))
5215 ; end of source block
5216 ((not org-fontify-quote-and-verse-blocks))
5217 ((string= block-type "quote")
5218 (add-text-properties beg1 (1+ end1) '(face org-quote)))
5219 ((string= block-type "verse")
5220 (add-text-properties beg1 (1+ end1) '(face org-verse))))
5221 (add-text-properties beg beg1 '(face org-block-begin-line))
5222 (add-text-properties (1+ end) (1+ end1) '(face org-block-end-line))
5224 ((member dc1 '("title:" "author:" "email:" "date:"))
5225 (add-text-properties
5226 beg (match-end 3)
5227 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5228 '(font-lock-fontified t invisible t)
5229 '(font-lock-fontified t face org-document-info-keyword)))
5230 (add-text-properties
5231 (match-beginning 6) (match-end 6)
5232 (if (string-equal dc1 "title:")
5233 '(font-lock-fontified t face org-document-title)
5234 '(font-lock-fontified t face org-document-info))))
5235 ((not (member (char-after beg) '(?\ ?\t)))
5236 ;; just any other in-buffer setting, but not indented
5237 (add-text-properties
5238 beg (1+ (match-end 0))
5239 '(font-lock-fontified t face org-meta-line))
5241 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
5242 "orgtbl:" "tblfm:" "tblname:" "result:"
5243 "results:" "source:" "srcname:" "call:"))
5244 (and (match-end 4) (equal dc3 "attr")))
5245 (add-text-properties
5246 beg (match-end 0)
5247 '(font-lock-fontified t face org-meta-line))
5249 ((member dc3 '(" " ""))
5250 (add-text-properties
5251 beg (match-end 0)
5252 '(font-lock-fontified t face font-lock-comment-face)))
5253 (t nil))))))
5255 (defun org-activate-angle-links (limit)
5256 "Run through the buffer and add overlays to links."
5257 (if (re-search-forward org-angle-link-re limit t)
5258 (progn
5259 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5260 (add-text-properties (match-beginning 0) (match-end 0)
5261 (list 'mouse-face 'highlight
5262 'keymap org-mouse-map))
5263 (org-rear-nonsticky-at (match-end 0))
5264 t)))
5266 (defun org-activate-footnote-links (limit)
5267 "Run through the buffer and add overlays to links."
5268 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
5269 limit t)
5270 (progn
5271 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5272 (add-text-properties (match-beginning 2) (match-end 2)
5273 (list 'mouse-face 'highlight
5274 'keymap org-mouse-map
5275 'help-echo
5276 (if (= (point-at-bol) (match-beginning 2))
5277 "Footnote definition"
5278 "Footnote reference")
5280 (org-rear-nonsticky-at (match-end 2))
5281 t)))
5283 (defun org-activate-bracket-links (limit)
5284 "Run through the buffer and add overlays to bracketed links."
5285 (if (re-search-forward org-bracket-link-regexp limit t)
5286 (let* ((help (concat "LINK: "
5287 (org-match-string-no-properties 1)))
5288 ;; FIXME: above we should remove the escapes.
5289 ;; but that requires another match, protecting match data,
5290 ;; a lot of overhead for font-lock.
5291 (ip (org-maybe-intangible
5292 (list 'invisible 'org-link
5293 'keymap org-mouse-map 'mouse-face 'highlight
5294 'font-lock-multiline t 'help-echo help)))
5295 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5296 'font-lock-multiline t 'help-echo help)))
5297 ;; We need to remove the invisible property here. Table narrowing
5298 ;; may have made some of this invisible.
5299 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5300 (remove-text-properties (match-beginning 0) (match-end 0)
5301 '(invisible nil))
5302 (if (match-end 3)
5303 (progn
5304 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5305 (org-rear-nonsticky-at (match-beginning 3))
5306 (add-text-properties (match-beginning 3) (match-end 3) vp)
5307 (org-rear-nonsticky-at (match-end 3))
5308 (add-text-properties (match-end 3) (match-end 0) ip)
5309 (org-rear-nonsticky-at (match-end 0)))
5310 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5311 (org-rear-nonsticky-at (match-beginning 1))
5312 (add-text-properties (match-beginning 1) (match-end 1) vp)
5313 (org-rear-nonsticky-at (match-end 1))
5314 (add-text-properties (match-end 1) (match-end 0) ip)
5315 (org-rear-nonsticky-at (match-end 0)))
5316 t)))
5318 (defun org-activate-dates (limit)
5319 "Run through the buffer and add overlays to dates."
5320 (if (re-search-forward org-tsr-regexp-both limit t)
5321 (progn
5322 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5323 (add-text-properties (match-beginning 0) (match-end 0)
5324 (list 'mouse-face 'highlight
5325 'keymap org-mouse-map))
5326 (org-rear-nonsticky-at (match-end 0))
5327 (when org-display-custom-times
5328 (if (match-end 3)
5329 (org-display-custom-time (match-beginning 3) (match-end 3)))
5330 (org-display-custom-time (match-beginning 1) (match-end 1)))
5331 t)))
5333 (defvar org-target-link-regexp nil
5334 "Regular expression matching radio targets in plain text.")
5335 (make-variable-buffer-local 'org-target-link-regexp)
5336 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5337 "Regular expression matching a link target.")
5338 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5339 "Regular expression matching a radio target.")
5340 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5341 "Regular expression matching any target.")
5343 (defun org-activate-target-links (limit)
5344 "Run through the buffer and add overlays to target matches."
5345 (when org-target-link-regexp
5346 (let ((case-fold-search t))
5347 (if (re-search-forward org-target-link-regexp limit t)
5348 (progn
5349 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5350 (add-text-properties (match-beginning 0) (match-end 0)
5351 (list 'mouse-face 'highlight
5352 'keymap org-mouse-map
5353 'help-echo "Radio target link"
5354 'org-linked-text t))
5355 (org-rear-nonsticky-at (match-end 0))
5356 t)))))
5358 (defun org-update-radio-target-regexp ()
5359 "Find all radio targets in this file and update the regular expression."
5360 (interactive)
5361 (when (memq 'radio org-activate-links)
5362 (setq org-target-link-regexp
5363 (org-make-target-link-regexp (org-all-targets 'radio)))
5364 (org-restart-font-lock)))
5366 (defun org-hide-wide-columns (limit)
5367 (let (s e)
5368 (setq s (text-property-any (point) (or limit (point-max))
5369 'org-cwidth t))
5370 (when s
5371 (setq e (next-single-property-change s 'org-cwidth))
5372 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5373 (goto-char e)
5374 t)))
5376 (defvar org-latex-and-specials-regexp nil
5377 "Regular expression for highlighting export special stuff.")
5378 (defvar org-match-substring-regexp)
5379 (defvar org-match-substring-with-braces-regexp)
5381 ;; This should be with the exporter code, but we also use if for font-locking
5382 (defconst org-export-html-special-string-regexps
5383 '(("\\\\-" . "&shy;")
5384 ("---\\([^-]\\)" . "&mdash;\\1")
5385 ("--\\([^-]\\)" . "&ndash;\\1")
5386 ("\\.\\.\\." . "&hellip;"))
5387 "Regular expressions for special string conversion.")
5390 (defun org-compute-latex-and-specials-regexp ()
5391 "Compute regular expression for stuff treated specially by exporters."
5392 (if (not org-highlight-latex-fragments-and-specials)
5393 (org-set-local 'org-latex-and-specials-regexp nil)
5394 (require 'org-exp)
5395 (let*
5396 ((matchers (plist-get org-format-latex-options :matchers))
5397 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5398 org-latex-regexps)))
5399 (org-export-allow-BIND nil)
5400 (options (org-combine-plists (org-default-export-plist)
5401 (org-infile-export-plist)))
5402 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5403 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5404 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5405 (org-export-html-expand (plist-get options :expand-quoted-html))
5406 (org-export-with-special-strings (plist-get options :special-strings))
5407 (re-sub
5408 (cond
5409 ((equal org-export-with-sub-superscripts '{})
5410 (list org-match-substring-with-braces-regexp))
5411 (org-export-with-sub-superscripts
5412 (list org-match-substring-regexp))
5413 (t nil)))
5414 (re-latex
5415 (if org-export-with-LaTeX-fragments
5416 (mapcar (lambda (x) (nth 1 x)) latexs)))
5417 (re-macros
5418 (if org-export-with-TeX-macros
5419 (list (concat "\\\\"
5420 (regexp-opt
5421 (append
5423 (delq nil
5424 (mapcar 'car-safe
5425 (append org-entities-user
5426 org-entities)))
5427 (if (boundp 'org-latex-entities)
5428 (mapcar (lambda (x)
5429 (or (car-safe x) x))
5430 org-latex-entities)
5431 nil))
5432 'words))) ; FIXME
5434 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5435 (re-special (if org-export-with-special-strings
5436 (mapcar (lambda (x) (car x))
5437 org-export-html-special-string-regexps)))
5438 (re-rest
5439 (delq nil
5440 (list
5441 (if org-export-html-expand "@<[^>\n]+>")
5442 ))))
5443 (org-set-local
5444 'org-latex-and-specials-regexp
5445 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5446 re-rest) "\\|")))))
5448 (defun org-do-latex-and-special-faces (limit)
5449 "Run through the buffer and add overlays to links."
5450 (when org-latex-and-specials-regexp
5451 (let (rtn d)
5452 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5453 limit t))
5454 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5455 'face))
5456 '(org-code org-verbatim underline)))
5457 (progn
5458 (setq rtn t
5459 d (cond ((member (char-after (1+ (match-beginning 0)))
5460 '(?_ ?^)) 1)
5461 (t 0)))
5462 (font-lock-prepend-text-property
5463 (+ d (match-beginning 0)) (match-end 0)
5464 'face 'org-latex-and-export-specials)
5465 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5466 '(font-lock-multiline t)))))
5467 rtn)))
5469 (defun org-restart-font-lock ()
5470 "Restart `font-lock-mode', to force refontification."
5471 (when (and (boundp 'font-lock-mode) font-lock-mode)
5472 (font-lock-mode -1)
5473 (font-lock-mode 1)))
5475 (defun org-all-targets (&optional radio)
5476 "Return a list of all targets in this file.
5477 With optional argument RADIO, only find radio targets."
5478 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5479 rtn)
5480 (save-excursion
5481 (goto-char (point-min))
5482 (while (re-search-forward re nil t)
5483 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5484 rtn)))
5486 (defun org-make-target-link-regexp (targets)
5487 "Make regular expression matching all strings in TARGETS.
5488 The regular expression finds the targets also if there is a line break
5489 between words."
5490 (and targets
5491 (concat
5492 "\\<\\("
5493 (mapconcat
5494 (lambda (x)
5495 (setq x (regexp-quote x))
5496 (while (string-match " +" x)
5497 (setq x (replace-match "\\s-+" t t x)))
5499 targets
5500 "\\|")
5501 "\\)\\>")))
5503 (defun org-activate-tags (limit)
5504 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5505 (progn
5506 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5507 (add-text-properties (match-beginning 1) (match-end 1)
5508 (list 'mouse-face 'highlight
5509 'keymap org-mouse-map))
5510 (org-rear-nonsticky-at (match-end 1))
5511 t)))
5513 (defun org-outline-level ()
5514 "Compute the outline level of the heading at point.
5515 This function assumes that the cursor is at the beginning of a line matched
5516 by `outline-regexp'. Otherwise it returns garbage.
5517 If this is called at a normal headline, the level is the number of stars.
5518 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5519 (save-excursion
5520 (looking-at outline-regexp)
5521 (1- (- (match-end 0) (match-beginning 0)))))
5523 (defvar org-font-lock-keywords nil)
5525 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5526 "Regular expression matching a property line.")
5528 (defvar org-font-lock-hook nil
5529 "Functions to be called for special font lock stuff.")
5531 (defvar org-font-lock-set-keywords-hook nil
5532 "Functions that can manipulate `org-font-lock-extra-keywords'.
5533 This is calles after `org-font-lock-extra-keywords' is defined, but before
5534 it is installed to be used by font lock. This can be useful if something
5535 needs to be inserted at a specific position in the font-lock sequence.")
5537 (defun org-font-lock-hook (limit)
5538 (run-hook-with-args 'org-font-lock-hook limit))
5540 (defun org-set-font-lock-defaults ()
5541 (let* ((em org-fontify-emphasized-text)
5542 (lk org-activate-links)
5543 (org-font-lock-extra-keywords
5544 (list
5545 ;; Call the hook
5546 '(org-font-lock-hook)
5547 ;; Headlines
5548 `(,(if org-fontify-whole-heading-line
5549 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5550 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5551 (1 (org-get-level-face 1))
5552 (2 (org-get-level-face 2))
5553 (3 (org-get-level-face 3)))
5554 ;; Table lines
5555 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5556 (1 'org-table t))
5557 ;; Table internals
5558 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5559 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5560 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5561 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5562 ;; Drawers
5563 (list org-drawer-regexp '(0 'org-special-keyword t))
5564 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5565 ;; Properties
5566 (list org-property-re
5567 '(1 'org-special-keyword t)
5568 '(3 'org-property-value t))
5569 ;; Links
5570 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5571 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5572 (if (memq 'plain lk) '(org-activate-plain-links))
5573 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5574 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5575 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5576 (if (memq 'footnote lk) '(org-activate-footnote-links
5577 (2 'org-footnote t)))
5578 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5579 '(org-hide-wide-columns (0 nil append))
5580 ;; TODO lines
5581 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
5582 '(1 (org-get-todo-face 1) t))
5583 ;; DONE
5584 (if org-fontify-done-headline
5585 (list (concat "^[*]+ +\\<\\("
5586 (mapconcat 'regexp-quote org-done-keywords "\\|")
5587 "\\)\\(.*\\)")
5588 '(2 'org-headline-done t))
5589 nil)
5590 ;; Priorities
5591 '(org-font-lock-add-priority-faces)
5592 ;; Tags
5593 '(org-font-lock-add-tag-faces)
5594 ;; Special keywords
5595 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5596 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5597 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5598 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5599 ;; Emphasis
5600 (if em
5601 (if (featurep 'xemacs)
5602 '(org-do-emphasis-faces (0 nil append))
5603 '(org-do-emphasis-faces)))
5604 ;; Checkboxes
5605 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5606 1 'org-checkbox prepend)
5607 (if (cdr (assq 'checkbox org-list-automatic-rules))
5608 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5609 (0 (org-get-checkbox-statistics-face) t)))
5610 ;; Description list items
5611 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5612 1 'bold prepend)
5613 ;; ARCHIVEd headings
5614 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5615 '(1 'org-archived prepend))
5616 ;; Specials
5617 '(org-do-latex-and-special-faces)
5618 '(org-fontify-entities)
5619 '(org-raise-scripts)
5620 ;; Code
5621 '(org-activate-code (1 'org-code t))
5622 ;; COMMENT
5623 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5624 "\\|" org-quote-string "\\)\\>")
5625 '(1 'org-special-keyword t))
5626 '("^#.*" (0 'font-lock-comment-face t))
5627 ;; Blocks and meta lines
5628 '(org-fontify-meta-lines-and-blocks)
5630 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5631 (run-hooks 'org-font-lock-set-keywords-hook)
5632 ;; Now set the full font-lock-keywords
5633 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5634 (org-set-local 'font-lock-defaults
5635 '(org-font-lock-keywords t nil nil backward-paragraph))
5636 (kill-local-variable 'font-lock-keywords) nil))
5638 (defun org-toggle-pretty-entities ()
5639 "Toggle the composition display of entities as UTF8 characters."
5640 (interactive)
5641 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5642 (org-restart-font-lock)
5643 (if org-pretty-entities
5644 (message "Entities are displayed as UTF8 characers")
5645 (save-restriction
5646 (widen)
5647 (org-decompose-region (point-min) (point-max))
5648 (message "Entities are displayed plain"))))
5650 (defun org-fontify-entities (limit)
5651 "Find an entity to fontify."
5652 (let (ee)
5653 (when org-pretty-entities
5654 (catch 'match
5655 (while (re-search-forward
5656 "\\\\\\([a-zA-Z][a-zA-Z0-9]*\\)\\($\\|[^[:alnum:]\n]\\)"
5657 limit t)
5658 (if (and (not (org-in-indented-comment-line))
5659 (setq ee (org-entity-get (match-string 1)))
5660 (= (length (nth 6 ee)) 1))
5661 (progn
5662 (add-text-properties
5663 (match-beginning 0) (match-end 1)
5664 (list 'font-lock-fontified t))
5665 (compose-region (match-beginning 0) (match-end 1)
5666 (nth 6 ee) nil)
5667 (backward-char 1)
5668 (throw 'match t))))
5669 nil))))
5671 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5672 "Fontify string S like in Org-mode."
5673 (with-temp-buffer
5674 (insert s)
5675 (let ((org-odd-levels-only odd-levels))
5676 (org-mode)
5677 (font-lock-fontify-buffer)
5678 (buffer-string))))
5680 (defvar org-m nil)
5681 (defvar org-l nil)
5682 (defvar org-f nil)
5683 (defun org-get-level-face (n)
5684 "Get the right face for match N in font-lock matching of headlines."
5685 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5686 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5687 (if org-cycle-level-faces
5688 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5689 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5690 (cond
5691 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5692 ((eq n 2) org-f)
5693 (t (if org-level-color-stars-only nil org-f))))
5696 (defun org-get-todo-face (kwd)
5697 "Get the right face for a TODO keyword KWD.
5698 If KWD is a number, get the corresponding match group."
5699 (if (numberp kwd) (setq kwd (match-string kwd)))
5700 (or (org-face-from-face-or-color
5701 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5702 (and (member kwd org-done-keywords) 'org-done)
5703 'org-todo))
5705 (defun org-face-from-face-or-color (context inherit face-or-color)
5706 "Create a face list that inherits INHERIT, but sets the foreground color.
5707 When FACE-OR-COLOR is not a string, just return it."
5708 (if (stringp face-or-color)
5709 (list :inherit inherit
5710 (cdr (assoc context org-faces-easy-properties))
5711 face-or-color)
5712 face-or-color))
5714 (defun org-font-lock-add-tag-faces (limit)
5715 "Add the special tag faces."
5716 (when (and org-tag-faces org-tags-special-faces-re)
5717 (while (re-search-forward org-tags-special-faces-re limit t)
5718 (add-text-properties (match-beginning 1) (match-end 1)
5719 (list 'face (org-get-tag-face 1)
5720 'font-lock-fontified t))
5721 (backward-char 1))))
5723 (defun org-font-lock-add-priority-faces (limit)
5724 "Add the special priority faces."
5725 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5726 (add-text-properties
5727 (match-beginning 0) (match-end 0)
5728 (list 'face (or (org-face-from-face-or-color
5729 'priority 'org-special-keyword
5730 (cdr (assoc (char-after (match-beginning 1))
5731 org-priority-faces)))
5732 'org-special-keyword)
5733 'font-lock-fontified t))))
5735 (defun org-get-tag-face (kwd)
5736 "Get the right face for a TODO keyword KWD.
5737 If KWD is a number, get the corresponding match group."
5738 (if (numberp kwd) (setq kwd (match-string kwd)))
5739 (or (org-face-from-face-or-color
5740 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5741 'org-tag))
5743 (defun org-unfontify-region (beg end &optional maybe_loudly)
5744 "Remove fontification and activation overlays from links."
5745 (font-lock-default-unfontify-region beg end)
5746 (let* ((buffer-undo-list t)
5747 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5748 (inhibit-modification-hooks t)
5749 deactivate-mark buffer-file-name buffer-file-truename)
5750 (org-decompose-region beg end)
5751 (remove-text-properties
5752 beg end
5753 (if org-indent-mode
5754 ;; also remove line-prefix and wrap-prefix properties
5755 '(mouse-face t keymap t org-linked-text t
5756 invisible t intangible t
5757 line-prefix t wrap-prefix t
5758 org-no-flyspell t org-emphasis t)
5759 '(mouse-face t keymap t org-linked-text t
5760 invisible t intangible t
5761 org-no-flyspell t org-emphasis t)))
5762 (org-remove-font-lock-display-properties beg end)))
5764 (defconst org-script-display '(((raise -0.3) (height 0.7))
5765 ((raise 0.3) (height 0.7))
5766 ((raise -0.5))
5767 ((raise 0.5)))
5768 "Display properties for showing superscripts and subscripts.")
5770 (defun org-remove-font-lock-display-properties (beg end)
5771 "Remove specific display properties that have been added by font lock.
5772 The will remove the raise properties that are used to show superscripts
5773 and subscripts."
5774 (let (next prop)
5775 (while (< beg end)
5776 (setq next (next-single-property-change beg 'display nil end)
5777 prop (get-text-property beg 'display))
5778 (if (member prop org-script-display)
5779 (put-text-property beg next 'display nil))
5780 (setq beg next))))
5782 (defun org-raise-scripts (limit)
5783 "Add raise properties to sub/superscripts."
5784 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
5785 (if (re-search-forward
5786 (if (eq org-use-sub-superscripts t)
5787 org-match-substring-regexp
5788 org-match-substring-with-braces-regexp)
5789 limit t)
5790 (let* ((pos (point)) table-p comment-p
5791 (mpos (match-beginning 3))
5792 (emph-p (get-text-property mpos 'org-emphasis))
5793 (link-p (get-text-property mpos 'mouse-face))
5794 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
5795 (goto-char (point-at-bol))
5796 (setq table-p (org-looking-at-p org-table-dataline-regexp)
5797 comment-p (org-looking-at-p "[ \t]*#"))
5798 (goto-char pos)
5799 ;; FIXME: Should we go back one character here, for a_b^c
5800 ;; (goto-char (1- pos)) ;????????????????????
5801 (if (or comment-p emph-p link-p keyw-p)
5803 (put-text-property (match-beginning 3) (match-end 0)
5804 'display
5805 (if (equal (char-after (match-beginning 2)) ?^)
5806 (nth (if table-p 3 1) org-script-display)
5807 (nth (if table-p 2 0) org-script-display)))
5808 (add-text-properties (match-beginning 2) (match-end 2)
5809 (list 'invisible t
5810 'org-dwidth t 'org-dwidth-n 1))
5811 (if (and (eq (char-after (match-beginning 3)) ?{)
5812 (eq (char-before (match-end 3)) ?}))
5813 (progn
5814 (add-text-properties
5815 (match-beginning 3) (1+ (match-beginning 3))
5816 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
5817 (add-text-properties
5818 (1- (match-end 3)) (match-end 3)
5819 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
5820 t)))))
5822 ;;;; Visibility cycling, including org-goto and indirect buffer
5824 ;;; Cycling
5826 (defvar org-cycle-global-status nil)
5827 (make-variable-buffer-local 'org-cycle-global-status)
5828 (defvar org-cycle-subtree-status nil)
5829 (make-variable-buffer-local 'org-cycle-subtree-status)
5831 ;;;###autoload
5833 (defvar org-inlinetask-min-level)
5835 (defun org-cycle (&optional arg)
5836 "TAB-action and visibility cycling for Org-mode.
5838 This is the command invoked in Org-mode by the TAB key. Its main purpose
5839 is outline visibility cycling, but it also invokes other actions
5840 in special contexts.
5842 - When this function is called with a prefix argument, rotate the entire
5843 buffer through 3 states (global cycling)
5844 1. OVERVIEW: Show only top-level headlines.
5845 2. CONTENTS: Show all headlines of all levels, but no body text.
5846 3. SHOW ALL: Show everything.
5847 When called with two `C-u C-u' prefixes, switch to the startup visibility,
5848 determined by the variable `org-startup-folded', and by any VISIBILITY
5849 properties in the buffer.
5850 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
5851 including any drawers.
5853 - When inside a table, re-align the table and move to the next field.
5855 - When point is at the beginning of a headline, rotate the subtree started
5856 by this line through 3 different states (local cycling)
5857 1. FOLDED: Only the main headline is shown.
5858 2. CHILDREN: The main headline and the direct children are shown.
5859 From this state, you can move to one of the children
5860 and zoom in further.
5861 3. SUBTREE: Show the entire subtree, including body text.
5862 If there is no subtree, switch directly from CHILDREN to FOLDED.
5864 - When point is at the beginning of an empty headline and the variable
5865 `org-cycle-level-after-item/entry-creation' is set, cycle the level
5866 of the headline by demoting and promoting it to likely levels. This
5867 speeds up creation document structure by pressing TAB once or several
5868 times right after creating a new headline.
5870 - When there is a numeric prefix, go up to a heading with level ARG, do
5871 a `show-subtree' and return to the previous cursor position. If ARG
5872 is negative, go up that many levels.
5874 - When point is not at the beginning of a headline, execute the global
5875 binding for TAB, which is re-indenting the line. See the option
5876 `org-cycle-emulate-tab' for details.
5878 - Special case: if point is at the beginning of the buffer and there is
5879 no headline in line 1, this function will act as if called with prefix arg
5880 (C-u TAB, same as S-TAB) also when called without prefix arg.
5881 But only if also the variable `org-cycle-global-at-bob' is t."
5882 (interactive "P")
5883 (org-load-modules-maybe)
5884 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
5885 (and org-cycle-level-after-item/entry-creation
5886 (or (org-cycle-level)
5887 (org-cycle-item-indentation))))
5888 (let* ((limit-level
5889 (or org-cycle-max-level
5890 (and (boundp 'org-inlinetask-min-level)
5891 org-inlinetask-min-level
5892 (1- org-inlinetask-min-level))))
5893 (nstars (and limit-level
5894 (if org-odd-levels-only
5895 (and limit-level (1- (* limit-level 2)))
5896 limit-level)))
5897 (outline-regexp
5898 (if (not (org-mode-p))
5899 outline-regexp
5900 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
5901 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
5902 (not (looking-at outline-regexp))))
5903 (org-cycle-hook
5904 (if bob-special
5905 (delq 'org-optimize-window-after-visibility-change
5906 (copy-sequence org-cycle-hook))
5907 org-cycle-hook))
5908 (pos (point)))
5910 (if (or bob-special (equal arg '(4)))
5911 ;; special case: use global cycling
5912 (setq arg t))
5914 (cond
5916 ((equal arg '(16))
5917 (setq last-command 'dummy)
5918 (org-set-startup-visibility)
5919 (message "Startup visibility, plus VISIBILITY properties"))
5921 ((equal arg '(64))
5922 (show-all)
5923 (message "Entire buffer visible, including drawers"))
5925 ;; Table: enter it or move to the next field.
5926 ((org-at-table-p 'any)
5927 (if (org-at-table.el-p)
5928 (message "Use C-c ' to edit table.el tables")
5929 (if arg (org-table-edit-field t)
5930 (org-table-justify-field-maybe)
5931 (call-interactively 'org-table-next-field))))
5933 ((run-hook-with-args-until-success
5934 'org-tab-after-check-for-table-hook))
5936 ;; Global cycling: delegate to `org-cycle-internal-global'.
5937 ((eq arg t) (org-cycle-internal-global))
5939 ;; Drawers: delegate to `org-flag-drawer'.
5940 ((and org-drawers org-drawer-regexp
5941 (save-excursion
5942 (beginning-of-line 1)
5943 (looking-at org-drawer-regexp)))
5944 (org-flag-drawer ; toggle block visibility
5945 (not (get-char-property (match-end 0) 'invisible))))
5947 ;; Show-subtree, ARG levels up from here.
5948 ((integerp arg)
5949 (save-excursion
5950 (org-back-to-heading)
5951 (outline-up-heading (if (< arg 0) (- arg)
5952 (- (funcall outline-level) arg)))
5953 (org-show-subtree)))
5955 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
5956 ((and (featurep 'org-inlinetask)
5957 (org-inlinetask-at-task-p)
5958 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5959 (org-inlinetask-toggle-visibility))
5961 ;; At an item/headline: delegate to `org-cycle-internal-local'.
5962 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
5963 (save-excursion (beginning-of-line 1)
5964 (looking-at outline-regexp)))
5965 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5966 (org-cycle-internal-local))
5968 ;; From there: TAB emulation and template completion.
5969 (buffer-read-only (org-back-to-heading))
5971 ((run-hook-with-args-until-success
5972 'org-tab-after-check-for-cycling-hook))
5974 ((org-try-structure-completion))
5976 ((org-try-cdlatex-tab))
5978 ((run-hook-with-args-until-success
5979 'org-tab-before-tab-emulation-hook))
5981 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5982 (or (not (bolp))
5983 (not (looking-at outline-regexp))))
5984 (call-interactively (global-key-binding "\t")))
5986 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5987 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5988 (or (and (eq org-cycle-emulate-tab 'white)
5989 (= (match-end 0) (point-at-eol)))
5990 (and (eq org-cycle-emulate-tab 'whitestart)
5991 (>= (match-end 0) pos))))
5993 (eq org-cycle-emulate-tab t))
5994 (call-interactively (global-key-binding "\t")))
5996 (t (save-excursion
5997 (org-back-to-heading)
5998 (org-cycle)))))))
6000 (defun org-cycle-internal-global ()
6001 "Do the global cycling action."
6002 (cond
6003 ((and (eq last-command this-command)
6004 (eq org-cycle-global-status 'overview))
6005 ;; We just created the overview - now do table of contents
6006 ;; This can be slow in very large buffers, so indicate action
6007 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6008 (message "CONTENTS...")
6009 (org-content)
6010 (message "CONTENTS...done")
6011 (setq org-cycle-global-status 'contents)
6012 (run-hook-with-args 'org-cycle-hook 'contents))
6014 ((and (eq last-command this-command)
6015 (eq org-cycle-global-status 'contents))
6016 ;; We just showed the table of contents - now show everything
6017 (run-hook-with-args 'org-pre-cycle-hook 'all)
6018 (show-all)
6019 (message "SHOW ALL")
6020 (setq org-cycle-global-status 'all)
6021 (run-hook-with-args 'org-cycle-hook 'all))
6024 ;; Default action: go to overview
6025 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6026 (org-overview)
6027 (message "OVERVIEW")
6028 (setq org-cycle-global-status 'overview)
6029 (run-hook-with-args 'org-cycle-hook 'overview))))
6031 (defun org-cycle-internal-local ()
6032 "Do the local cycling action."
6033 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6034 ;; First, determine end of headline (EOH), end of subtree or item
6035 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6036 (save-excursion
6037 (if (org-at-item-p)
6038 (progn
6039 (beginning-of-line)
6040 (setq struct (org-list-struct))
6041 (setq eoh (point-at-eol))
6042 (setq eos (org-list-get-item-end-before-blank (point) struct))
6043 (setq has-children (org-list-has-child-p (point) struct)))
6044 (org-back-to-heading)
6045 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6046 (setq eos (save-excursion
6047 (org-end-of-subtree t)
6048 (unless (eobp)
6049 (skip-chars-forward " \t\n"))
6050 (if (eobp) (point) (1- (point)))))
6051 (setq has-children
6052 (or (save-excursion
6053 (let ((level (funcall outline-level)))
6054 (outline-next-heading)
6055 (and (org-at-heading-p t)
6056 (> (funcall outline-level) level))))
6057 (save-excursion
6058 (org-list-search-forward (org-item-beginning-re) eos t)))))
6059 ;; Determine end invisible part of buffer (EOL)
6060 (beginning-of-line 2)
6061 ;; XEmacs doesn't have `next-single-char-property-change'
6062 (if (featurep 'xemacs)
6063 (while (and (not (eobp)) ;; this is like `next-line'
6064 (get-char-property (1- (point)) 'invisible))
6065 (beginning-of-line 2))
6066 (while (and (not (eobp)) ;; this is like `next-line'
6067 (get-char-property (1- (point)) 'invisible))
6068 (goto-char (next-single-char-property-change (point) 'invisible))
6069 (and (eolp) (beginning-of-line 2))))
6070 (setq eol (point)))
6071 ;; Find out what to do next and set `this-command'
6072 (cond
6073 ((= eos eoh)
6074 ;; Nothing is hidden behind this heading
6075 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6076 (message "EMPTY ENTRY")
6077 (setq org-cycle-subtree-status nil)
6078 (save-excursion
6079 (goto-char eos)
6080 (outline-next-heading)
6081 (if (outline-invisible-p) (org-flag-heading nil))))
6082 ((and (or (>= eol eos)
6083 (not (string-match "\\S-" (buffer-substring eol eos))))
6084 (or has-children
6085 (not (setq children-skipped
6086 org-cycle-skip-children-state-if-no-children))))
6087 ;; Entire subtree is hidden in one line: children view
6088 (run-hook-with-args 'org-pre-cycle-hook 'children)
6089 (if (org-at-item-p)
6090 (org-list-set-item-visibility (point-at-bol) struct 'children)
6091 (org-show-entry)
6092 (show-children)
6093 ;; Fold every list in subtree to top-level items.
6094 (when (eq org-cycle-include-plain-lists 'integrate)
6095 (save-excursion
6096 (org-back-to-heading)
6097 (while (org-list-search-forward (org-item-beginning-re) eos t)
6098 (beginning-of-line 1)
6099 (let* ((struct (org-list-struct))
6100 (prevs (org-list-prevs-alist struct))
6101 (end (org-list-get-bottom-point struct)))
6102 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6103 (org-list-get-all-items (point) struct prevs))
6104 (goto-char end))))))
6105 (message "CHILDREN")
6106 (save-excursion
6107 (goto-char eos)
6108 (outline-next-heading)
6109 (if (outline-invisible-p) (org-flag-heading nil)))
6110 (setq org-cycle-subtree-status 'children)
6111 (run-hook-with-args 'org-cycle-hook 'children))
6112 ((or children-skipped
6113 (and (eq last-command this-command)
6114 (eq org-cycle-subtree-status 'children)))
6115 ;; We just showed the children, or no children are there,
6116 ;; now show everything.
6117 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6118 (outline-flag-region eoh eos nil)
6119 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6120 (setq org-cycle-subtree-status 'subtree)
6121 (run-hook-with-args 'org-cycle-hook 'subtree))
6123 ;; Default action: hide the subtree.
6124 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6125 (outline-flag-region eoh eos t)
6126 (message "FOLDED")
6127 (setq org-cycle-subtree-status 'folded)
6128 (run-hook-with-args 'org-cycle-hook 'folded)))))
6130 ;;;###autoload
6131 (defun org-global-cycle (&optional arg)
6132 "Cycle the global visibility. For details see `org-cycle'.
6133 With \\[universal-argument] prefix arg, switch to startup visibility.
6134 With a numeric prefix, show all headlines up to that level."
6135 (interactive "P")
6136 (let ((org-cycle-include-plain-lists
6137 (if (org-mode-p) org-cycle-include-plain-lists nil)))
6138 (cond
6139 ((integerp arg)
6140 (show-all)
6141 (hide-sublevels arg)
6142 (setq org-cycle-global-status 'contents))
6143 ((equal arg '(4))
6144 (org-set-startup-visibility)
6145 (message "Startup visibility, plus VISIBILITY properties."))
6147 (org-cycle '(4))))))
6149 (defun org-set-startup-visibility ()
6150 "Set the visibility required by startup options and properties."
6151 (cond
6152 ((eq org-startup-folded t)
6153 (org-cycle '(4)))
6154 ((eq org-startup-folded 'content)
6155 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6156 (org-cycle '(4)) (org-cycle '(4)))))
6157 (unless (eq org-startup-folded 'showeverything)
6158 (if org-hide-block-startup (org-hide-block-all))
6159 (org-set-visibility-according-to-property 'no-cleanup)
6160 (org-cycle-hide-archived-subtrees 'all)
6161 (org-cycle-hide-drawers 'all)
6162 (org-cycle-show-empty-lines t)))
6164 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6165 "Switch subtree visibilities according to :VISIBILITY: property."
6166 (interactive)
6167 (let (org-show-entry-below state)
6168 (save-excursion
6169 (goto-char (point-min))
6170 (while (re-search-forward
6171 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6172 nil t)
6173 (setq state (match-string 1))
6174 (save-excursion
6175 (org-back-to-heading t)
6176 (hide-subtree)
6177 (org-reveal)
6178 (cond
6179 ((equal state '("fold" "folded"))
6180 (hide-subtree))
6181 ((equal state "children")
6182 (org-show-hidden-entry)
6183 (show-children))
6184 ((equal state "content")
6185 (save-excursion
6186 (save-restriction
6187 (org-narrow-to-subtree)
6188 (org-content))))
6189 ((member state '("all" "showall"))
6190 (show-subtree)))))
6191 (unless no-cleanup
6192 (org-cycle-hide-archived-subtrees 'all)
6193 (org-cycle-hide-drawers 'all)
6194 (org-cycle-show-empty-lines 'all)))))
6196 (defun org-overview ()
6197 "Switch to overview mode, showing only top-level headlines.
6198 Really, this shows all headlines with level equal or greater than the level
6199 of the first headline in the buffer. This is important, because if the
6200 first headline is not level one, then (hide-sublevels 1) gives confusing
6201 results."
6202 (interactive)
6203 (let ((level (save-excursion
6204 (goto-char (point-min))
6205 (if (re-search-forward (concat "^" outline-regexp) nil t)
6206 (progn
6207 (goto-char (match-beginning 0))
6208 (funcall outline-level))))))
6209 (and level (hide-sublevels level))))
6211 (defun org-content (&optional arg)
6212 "Show all headlines in the buffer, like a table of contents.
6213 With numerical argument N, show content up to level N."
6214 (interactive "P")
6215 (save-excursion
6216 ;; Visit all headings and show their offspring
6217 (and (integerp arg) (org-overview))
6218 (goto-char (point-max))
6219 (catch 'exit
6220 (while (and (progn (condition-case nil
6221 (outline-previous-visible-heading 1)
6222 (error (goto-char (point-min))))
6224 (looking-at outline-regexp))
6225 (if (integerp arg)
6226 (show-children (1- arg))
6227 (show-branches))
6228 (if (bobp) (throw 'exit nil))))))
6231 (defun org-optimize-window-after-visibility-change (state)
6232 "Adjust the window after a change in outline visibility.
6233 This function is the default value of the hook `org-cycle-hook'."
6234 (when (get-buffer-window (current-buffer))
6235 (cond
6236 ((eq state 'content) nil)
6237 ((eq state 'all) nil)
6238 ((eq state 'folded) nil)
6239 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6240 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6242 (defun org-remove-empty-overlays-at (pos)
6243 "Remove outline overlays that do not contain non-white stuff."
6244 (mapc
6245 (lambda (o)
6246 (and (eq 'outline (overlay-get o 'invisible))
6247 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6248 (overlay-end o))))
6249 (delete-overlay o)))
6250 (overlays-at pos)))
6252 (defun org-clean-visibility-after-subtree-move ()
6253 "Fix visibility issues after moving a subtree."
6254 ;; First, find a reasonable region to look at:
6255 ;; Start two siblings above, end three below
6256 (let* ((beg (save-excursion
6257 (and (org-get-last-sibling)
6258 (org-get-last-sibling))
6259 (point)))
6260 (end (save-excursion
6261 (and (org-get-next-sibling)
6262 (org-get-next-sibling)
6263 (org-get-next-sibling))
6264 (if (org-at-heading-p)
6265 (point-at-eol)
6266 (point))))
6267 (level (looking-at "\\*+"))
6268 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6269 (save-excursion
6270 (save-restriction
6271 (narrow-to-region beg end)
6272 (when re
6273 ;; Properly fold already folded siblings
6274 (goto-char (point-min))
6275 (while (re-search-forward re nil t)
6276 (if (and (not (outline-invisible-p))
6277 (save-excursion
6278 (goto-char (point-at-eol)) (outline-invisible-p)))
6279 (hide-entry))))
6280 (org-cycle-show-empty-lines 'overview)
6281 (org-cycle-hide-drawers 'overview)))))
6283 (defun org-cycle-show-empty-lines (state)
6284 "Show empty lines above all visible headlines.
6285 The region to be covered depends on STATE when called through
6286 `org-cycle-hook'. Lisp program can use t for STATE to get the
6287 entire buffer covered. Note that an empty line is only shown if there
6288 are at least `org-cycle-separator-lines' empty lines before the headline."
6289 (when (not (= org-cycle-separator-lines 0))
6290 (save-excursion
6291 (let* ((n (abs org-cycle-separator-lines))
6292 (re (cond
6293 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6294 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6295 (t (let ((ns (number-to-string (- n 2))))
6296 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6297 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6298 beg end b e)
6299 (cond
6300 ((memq state '(overview contents t))
6301 (setq beg (point-min) end (point-max)))
6302 ((memq state '(children folded))
6303 (setq beg (point) end (progn (org-end-of-subtree t t)
6304 (beginning-of-line 2)
6305 (point)))))
6306 (when beg
6307 (goto-char beg)
6308 (while (re-search-forward re end t)
6309 (unless (get-char-property (match-end 1) 'invisible)
6310 (setq e (match-end 1))
6311 (if (< org-cycle-separator-lines 0)
6312 (setq b (save-excursion
6313 (goto-char (match-beginning 0))
6314 (org-back-over-empty-lines)
6315 (if (save-excursion
6316 (goto-char (max (point-min) (1- (point))))
6317 (org-on-heading-p))
6318 (1- (point))
6319 (point))))
6320 (setq b (match-beginning 1)))
6321 (outline-flag-region b e nil)))))))
6322 ;; Never hide empty lines at the end of the file.
6323 (save-excursion
6324 (goto-char (point-max))
6325 (outline-previous-heading)
6326 (outline-end-of-heading)
6327 (if (and (looking-at "[ \t\n]+")
6328 (= (match-end 0) (point-max)))
6329 (outline-flag-region (point) (match-end 0) nil))))
6331 (defun org-show-empty-lines-in-parent ()
6332 "Move to the parent and re-show empty lines before visible headlines."
6333 (save-excursion
6334 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6335 (org-cycle-show-empty-lines context))))
6337 (defun org-files-list ()
6338 "Return `org-agenda-files' list, plus all open org-mode files.
6339 This is useful for operations that need to scan all of a user's
6340 open and agenda-wise Org files."
6341 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6342 (dolist (buf (buffer-list))
6343 (with-current-buffer buf
6344 (if (and (org-mode-p) (buffer-file-name))
6345 (let ((file (expand-file-name (buffer-file-name))))
6346 (unless (member file files)
6347 (push file files))))))
6348 files))
6350 (defsubst org-entry-beginning-position ()
6351 "Return the beginning position of the current entry."
6352 (save-excursion (outline-back-to-heading t) (point)))
6354 (defsubst org-entry-end-position ()
6355 "Return the end position of the current entry."
6356 (save-excursion (outline-next-heading) (point)))
6358 (defun org-cycle-hide-drawers (state)
6359 "Re-hide all drawers after a visibility state change."
6360 (when (and (org-mode-p)
6361 (not (memq state '(overview folded contents))))
6362 (save-excursion
6363 (let* ((globalp (memq state '(contents all)))
6364 (beg (if globalp (point-min) (point)))
6365 (end (if globalp (point-max)
6366 (if (eq state 'children)
6367 (save-excursion (outline-next-heading) (point))
6368 (org-end-of-subtree t)))))
6369 (goto-char beg)
6370 (while (re-search-forward org-drawer-regexp end t)
6371 (org-flag-drawer t))))))
6373 (defun org-flag-drawer (flag)
6374 (save-excursion
6375 (beginning-of-line 1)
6376 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6377 (let ((b (match-end 0))
6378 (outline-regexp org-outline-regexp))
6379 (if (re-search-forward
6380 "^[ \t]*:END:"
6381 (save-excursion (outline-next-heading) (point)) t)
6382 (outline-flag-region b (point-at-eol) flag)
6383 (error ":END: line missing at position %s" b))))))
6385 (defun org-subtree-end-visible-p ()
6386 "Is the end of the current subtree visible?"
6387 (pos-visible-in-window-p
6388 (save-excursion (org-end-of-subtree t) (point))))
6390 (defun org-first-headline-recenter (&optional N)
6391 "Move cursor to the first headline and recenter the headline.
6392 Optional argument N means put the headline into the Nth line of the window."
6393 (goto-char (point-min))
6394 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
6395 (beginning-of-line)
6396 (recenter (prefix-numeric-value N))))
6398 ;;; Saving and restoring visibility
6400 (defun org-outline-overlay-data (&optional use-markers)
6401 "Return a list of the locations of all outline overlays.
6402 These are overlays with the `invisible' property value `outline'.
6403 The return value is a list of cons cells, with start and stop
6404 positions for each overlay.
6405 If USE-MARKERS is set, return the positions as markers."
6406 (let (beg end)
6407 (save-excursion
6408 (save-restriction
6409 (widen)
6410 (delq nil
6411 (mapcar (lambda (o)
6412 (when (eq (overlay-get o 'invisible) 'outline)
6413 (setq beg (overlay-start o)
6414 end (overlay-end o))
6415 (and beg end (> end beg)
6416 (if use-markers
6417 (cons (move-marker (make-marker) beg)
6418 (move-marker (make-marker) end))
6419 (cons beg end)))))
6420 (overlays-in (point-min) (point-max))))))))
6422 (defun org-set-outline-overlay-data (data)
6423 "Create visibility overlays for all positions in DATA.
6424 DATA should have been made by `org-outline-overlay-data'."
6425 (let (o)
6426 (save-excursion
6427 (save-restriction
6428 (widen)
6429 (show-all)
6430 (mapc (lambda (c)
6431 (setq o (make-overlay (car c) (cdr c)))
6432 (overlay-put o 'invisible 'outline))
6433 data)))))
6435 ;;; Folding of blocks
6437 (defconst org-block-regexp
6438 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
6439 "Regular expression for hiding blocks.")
6441 (defvar org-hide-block-overlays nil
6442 "Overlays hiding blocks.")
6443 (make-variable-buffer-local 'org-hide-block-overlays)
6445 (defun org-block-map (function &optional start end)
6446 "Call FUNCTION at the head of all source blocks in the current buffer.
6447 Optional arguments START and END can be used to limit the range."
6448 (let ((start (or start (point-min)))
6449 (end (or end (point-max))))
6450 (save-excursion
6451 (goto-char start)
6452 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6453 (save-excursion
6454 (save-match-data
6455 (goto-char (match-beginning 0))
6456 (funcall function)))))))
6458 (defun org-hide-block-toggle-all ()
6459 "Toggle the visibility of all blocks in the current buffer."
6460 (org-block-map #'org-hide-block-toggle))
6462 (defun org-hide-block-all ()
6463 "Fold all blocks in the current buffer."
6464 (interactive)
6465 (org-show-block-all)
6466 (org-block-map #'org-hide-block-toggle-maybe))
6468 (defun org-show-block-all ()
6469 "Unfold all blocks in the current buffer."
6470 (interactive)
6471 (mapc 'delete-overlay org-hide-block-overlays)
6472 (setq org-hide-block-overlays nil))
6474 (defun org-hide-block-toggle-maybe ()
6475 "Toggle visibility of block at point."
6476 (interactive)
6477 (let ((case-fold-search t))
6478 (if (save-excursion
6479 (beginning-of-line 1)
6480 (looking-at org-block-regexp))
6481 (progn (org-hide-block-toggle)
6482 t) ;; to signal that we took action
6483 nil))) ;; to signal that we did not
6485 (defun org-hide-block-toggle (&optional force)
6486 "Toggle the visibility of the current block."
6487 (interactive)
6488 (save-excursion
6489 (beginning-of-line)
6490 (if (re-search-forward org-block-regexp nil t)
6491 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6492 (end (match-end 0)) ;; end of entire body
6494 (if (memq t (mapcar (lambda (overlay)
6495 (eq (overlay-get overlay 'invisible)
6496 'org-hide-block))
6497 (overlays-at start)))
6498 (if (or (not force) (eq force 'off))
6499 (mapc (lambda (ov)
6500 (when (member ov org-hide-block-overlays)
6501 (setq org-hide-block-overlays
6502 (delq ov org-hide-block-overlays)))
6503 (when (eq (overlay-get ov 'invisible)
6504 'org-hide-block)
6505 (delete-overlay ov)))
6506 (overlays-at start)))
6507 (setq ov (make-overlay start end))
6508 (overlay-put ov 'invisible 'org-hide-block)
6509 ;; make the block accessible to isearch
6510 (overlay-put
6511 ov 'isearch-open-invisible
6512 (lambda (ov)
6513 (when (member ov org-hide-block-overlays)
6514 (setq org-hide-block-overlays
6515 (delq ov org-hide-block-overlays)))
6516 (when (eq (overlay-get ov 'invisible)
6517 'org-hide-block)
6518 (delete-overlay ov))))
6519 (push ov org-hide-block-overlays)))
6520 (error "Not looking at a source block"))))
6522 ;; org-tab-after-check-for-cycling-hook
6523 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6524 ;; Remove overlays when changing major mode
6525 (add-hook 'org-mode-hook
6526 (lambda () (org-add-hook 'change-major-mode-hook
6527 'org-show-block-all 'append 'local)))
6529 ;;; Org-goto
6531 (defvar org-goto-window-configuration nil)
6532 (defvar org-goto-marker nil)
6533 (defvar org-goto-map
6534 (let ((map (make-sparse-keymap)))
6535 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6536 (while (setq cmd (pop cmds))
6537 (substitute-key-definition cmd cmd map global-map)))
6538 (suppress-keymap map)
6539 (org-defkey map "\C-m" 'org-goto-ret)
6540 (org-defkey map [(return)] 'org-goto-ret)
6541 (org-defkey map [(left)] 'org-goto-left)
6542 (org-defkey map [(right)] 'org-goto-right)
6543 (org-defkey map [(control ?g)] 'org-goto-quit)
6544 (org-defkey map "\C-i" 'org-cycle)
6545 (org-defkey map [(tab)] 'org-cycle)
6546 (org-defkey map [(down)] 'outline-next-visible-heading)
6547 (org-defkey map [(up)] 'outline-previous-visible-heading)
6548 (if org-goto-auto-isearch
6549 (if (fboundp 'define-key-after)
6550 (define-key-after map [t] 'org-goto-local-auto-isearch)
6551 nil)
6552 (org-defkey map "q" 'org-goto-quit)
6553 (org-defkey map "n" 'outline-next-visible-heading)
6554 (org-defkey map "p" 'outline-previous-visible-heading)
6555 (org-defkey map "f" 'outline-forward-same-level)
6556 (org-defkey map "b" 'outline-backward-same-level)
6557 (org-defkey map "u" 'outline-up-heading))
6558 (org-defkey map "/" 'org-occur)
6559 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6560 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6561 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6562 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6563 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6564 map))
6566 (defconst org-goto-help
6567 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6568 RET=jump to location [Q]uit and return to previous location
6569 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6571 (defvar org-goto-start-pos) ; dynamically scoped parameter
6573 ;; FIXME: Docstring does not mention both interfaces
6574 (defun org-goto (&optional alternative-interface)
6575 "Look up a different location in the current file, keeping current visibility.
6577 When you want look-up or go to a different location in a document, the
6578 fastest way is often to fold the entire buffer and then dive into the tree.
6579 This method has the disadvantage, that the previous location will be folded,
6580 which may not be what you want.
6582 This command works around this by showing a copy of the current buffer
6583 in an indirect buffer, in overview mode. You can dive into the tree in
6584 that copy, use org-occur and incremental search to find a location.
6585 When pressing RET or `Q', the command returns to the original buffer in
6586 which the visibility is still unchanged. After RET is will also jump to
6587 the location selected in the indirect buffer and expose the
6588 the headline hierarchy above."
6589 (interactive "P")
6590 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6591 (org-refile-use-outline-path t)
6592 (org-refile-target-verify-function nil)
6593 (interface
6594 (if (not alternative-interface)
6595 org-goto-interface
6596 (if (eq org-goto-interface 'outline)
6597 'outline-path-completion
6598 'outline)))
6599 (org-goto-start-pos (point))
6600 (selected-point
6601 (if (eq interface 'outline)
6602 (car (org-get-location (current-buffer) org-goto-help))
6603 (let ((pa (org-refile-get-location "Goto")))
6604 (org-refile-check-position pa)
6605 (nth 3 pa)))))
6606 (if selected-point
6607 (progn
6608 (org-mark-ring-push org-goto-start-pos)
6609 (goto-char selected-point)
6610 (if (or (outline-invisible-p) (org-invisible-p2))
6611 (org-show-context 'org-goto)))
6612 (message "Quit"))))
6614 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6615 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6616 (defvar org-goto-local-auto-isearch-map) ; defined below
6618 (defun org-get-location (buf help)
6619 "Let the user select a location in the Org-mode buffer BUF.
6620 This function uses a recursive edit. It returns the selected position
6621 or nil."
6622 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6623 (isearch-hide-immediately nil)
6624 (isearch-search-fun-function
6625 (lambda () 'org-goto-local-search-headings))
6626 (org-goto-selected-point org-goto-exit-command)
6627 (pop-up-frames nil)
6628 (special-display-buffer-names nil)
6629 (special-display-regexps nil)
6630 (special-display-function nil))
6631 (save-excursion
6632 (save-window-excursion
6633 (delete-other-windows)
6634 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6635 (switch-to-buffer
6636 (condition-case nil
6637 (make-indirect-buffer (current-buffer) "*org-goto*")
6638 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6639 (with-output-to-temp-buffer "*Help*"
6640 (princ help))
6641 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6642 (setq buffer-read-only nil)
6643 (let ((org-startup-truncated t)
6644 (org-startup-folded nil)
6645 (org-startup-align-all-tables nil))
6646 (org-mode)
6647 (org-overview))
6648 (setq buffer-read-only t)
6649 (if (and (boundp 'org-goto-start-pos)
6650 (integer-or-marker-p org-goto-start-pos))
6651 (let ((org-show-hierarchy-above t)
6652 (org-show-siblings t)
6653 (org-show-following-heading t))
6654 (goto-char org-goto-start-pos)
6655 (and (outline-invisible-p) (org-show-context)))
6656 (goto-char (point-min)))
6657 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6658 (message "Select location and press RET")
6659 (use-local-map org-goto-map)
6660 (recursive-edit)
6662 (kill-buffer "*org-goto*")
6663 (cons org-goto-selected-point org-goto-exit-command)))
6665 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6666 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6667 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6668 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6670 (defun org-goto-local-search-headings (string bound noerror)
6671 "Search and make sure that any matches are in headlines."
6672 (catch 'return
6673 (while (if isearch-forward
6674 (search-forward string bound noerror)
6675 (search-backward string bound noerror))
6676 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6677 (and (member :headline context)
6678 (not (member :tags context))))
6679 (throw 'return (point))))))
6681 (defun org-goto-local-auto-isearch ()
6682 "Start isearch."
6683 (interactive)
6684 (goto-char (point-min))
6685 (let ((keys (this-command-keys)))
6686 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6687 (isearch-mode t)
6688 (isearch-process-search-char (string-to-char keys)))))
6690 (defun org-goto-ret (&optional arg)
6691 "Finish `org-goto' by going to the new location."
6692 (interactive "P")
6693 (setq org-goto-selected-point (point)
6694 org-goto-exit-command 'return)
6695 (throw 'exit nil))
6697 (defun org-goto-left ()
6698 "Finish `org-goto' by going to the new location."
6699 (interactive)
6700 (if (org-on-heading-p)
6701 (progn
6702 (beginning-of-line 1)
6703 (setq org-goto-selected-point (point)
6704 org-goto-exit-command 'left)
6705 (throw 'exit nil))
6706 (error "Not on a heading")))
6708 (defun org-goto-right ()
6709 "Finish `org-goto' by going to the new location."
6710 (interactive)
6711 (if (org-on-heading-p)
6712 (progn
6713 (setq org-goto-selected-point (point)
6714 org-goto-exit-command 'right)
6715 (throw 'exit nil))
6716 (error "Not on a heading")))
6718 (defun org-goto-quit ()
6719 "Finish `org-goto' without cursor motion."
6720 (interactive)
6721 (setq org-goto-selected-point nil)
6722 (setq org-goto-exit-command 'quit)
6723 (throw 'exit nil))
6725 ;;; Indirect buffer display of subtrees
6727 (defvar org-indirect-dedicated-frame nil
6728 "This is the frame being used for indirect tree display.")
6729 (defvar org-last-indirect-buffer nil)
6731 (defun org-tree-to-indirect-buffer (&optional arg)
6732 "Create indirect buffer and narrow it to current subtree.
6733 With numerical prefix ARG, go up to this level and then take that tree.
6734 If ARG is negative, go up that many levels.
6735 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6736 indirect buffer previously made with this command, to avoid proliferation of
6737 indirect buffers. However, when you call the command with a \
6738 \\[universal-argument] prefix, or
6739 when `org-indirect-buffer-display' is `new-frame', the last buffer
6740 is kept so that you can work with several indirect buffers at the same time.
6741 If `org-indirect-buffer-display' is `dedicated-frame', the \
6742 \\[universal-argument] prefix also
6743 requests that a new frame be made for the new buffer, so that the dedicated
6744 frame is not changed."
6745 (interactive "P")
6746 (let ((cbuf (current-buffer))
6747 (cwin (selected-window))
6748 (pos (point))
6749 beg end level heading ibuf)
6750 (save-excursion
6751 (org-back-to-heading t)
6752 (when (numberp arg)
6753 (setq level (org-outline-level))
6754 (if (< arg 0) (setq arg (+ level arg)))
6755 (while (> (setq level (org-outline-level)) arg)
6756 (outline-up-heading 1 t)))
6757 (setq beg (point)
6758 heading (org-get-heading))
6759 (org-end-of-subtree t t)
6760 (if (org-on-heading-p) (backward-char 1))
6761 (setq end (point)))
6762 (if (and (buffer-live-p org-last-indirect-buffer)
6763 (not (eq org-indirect-buffer-display 'new-frame))
6764 (not arg))
6765 (kill-buffer org-last-indirect-buffer))
6766 (setq ibuf (org-get-indirect-buffer cbuf)
6767 org-last-indirect-buffer ibuf)
6768 (cond
6769 ((or (eq org-indirect-buffer-display 'new-frame)
6770 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6771 (select-frame (make-frame))
6772 (delete-other-windows)
6773 (switch-to-buffer ibuf)
6774 (org-set-frame-title heading))
6775 ((eq org-indirect-buffer-display 'dedicated-frame)
6776 (raise-frame
6777 (select-frame (or (and org-indirect-dedicated-frame
6778 (frame-live-p org-indirect-dedicated-frame)
6779 org-indirect-dedicated-frame)
6780 (setq org-indirect-dedicated-frame (make-frame)))))
6781 (delete-other-windows)
6782 (switch-to-buffer ibuf)
6783 (org-set-frame-title (concat "Indirect: " heading)))
6784 ((eq org-indirect-buffer-display 'current-window)
6785 (switch-to-buffer ibuf))
6786 ((eq org-indirect-buffer-display 'other-window)
6787 (pop-to-buffer ibuf))
6788 (t (error "Invalid value")))
6789 (if (featurep 'xemacs)
6790 (save-excursion (org-mode) (turn-on-font-lock)))
6791 (narrow-to-region beg end)
6792 (show-all)
6793 (goto-char pos)
6794 (and (window-live-p cwin) (select-window cwin))))
6796 (defun org-get-indirect-buffer (&optional buffer)
6797 (setq buffer (or buffer (current-buffer)))
6798 (let ((n 1) (base (buffer-name buffer)) bname)
6799 (while (buffer-live-p
6800 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6801 (setq n (1+ n)))
6802 (condition-case nil
6803 (make-indirect-buffer buffer bname 'clone)
6804 (error (make-indirect-buffer buffer bname)))))
6806 (defun org-set-frame-title (title)
6807 "Set the title of the current frame to the string TITLE."
6808 ;; FIXME: how to name a single frame in XEmacs???
6809 (unless (featurep 'xemacs)
6810 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6812 ;;;; Structure editing
6814 ;;; Inserting headlines
6816 (defun org-previous-line-empty-p ()
6817 (save-excursion
6818 (and (not (bobp))
6819 (or (beginning-of-line 0) t)
6820 (save-match-data
6821 (looking-at "[ \t]*$")))))
6823 (defun org-insert-heading (&optional force-heading invisible-ok)
6824 "Insert a new heading or item with same depth at point.
6825 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6826 If point is at the beginning of a headline, insert a sibling before the
6827 current headline. If point is not at the beginning, split the line,
6828 create the new headline with the text in the current line after point
6829 \(but see also the variable `org-M-RET-may-split-line').
6831 When INVISIBLE-OK is set, stop at invisible headlines when going back.
6832 This is important for non-interactive uses of the command."
6833 (interactive "P")
6834 (if (or (= (buffer-size) 0)
6835 (and (not (save-excursion
6836 (and (ignore-errors (org-back-to-heading invisible-ok))
6837 (org-on-heading-p))))
6838 (not (org-in-item-p))))
6839 (progn
6840 (insert "\n* ")
6841 (run-hooks 'org-insert-heading-hook))
6842 (when (or force-heading (not (org-insert-item)))
6843 (let* ((empty-line-p nil)
6844 (level nil)
6845 (on-heading (org-on-heading-p))
6846 (head (save-excursion
6847 (condition-case nil
6848 (progn
6849 (org-back-to-heading invisible-ok)
6850 (when (and (not on-heading)
6851 (featurep 'org-inlinetask)
6852 (integerp org-inlinetask-min-level)
6853 (>= (length (match-string 0))
6854 org-inlinetask-min-level))
6855 ;; Find a heading level before the inline task
6856 (while (and (setq level (org-up-heading-safe))
6857 (>= level org-inlinetask-min-level)))
6858 (if (org-on-heading-p)
6859 (org-back-to-heading invisible-ok)
6860 (error "This should not happen")))
6861 (setq empty-line-p (org-previous-line-empty-p))
6862 (match-string 0))
6863 (error "*"))))
6864 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
6865 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
6866 pos hide-previous previous-pos)
6867 (cond
6868 ((and (org-on-heading-p) (bolp)
6869 (or (bobp)
6870 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
6871 ;; insert before the current line
6872 (open-line (if blank 2 1)))
6873 ((and (bolp)
6874 (not org-insert-heading-respect-content)
6875 (or (bobp)
6876 (save-excursion
6877 (backward-char 1) (not (outline-invisible-p)))))
6878 ;; insert right here
6879 nil)
6881 ;; somewhere in the line
6882 (save-excursion
6883 (setq previous-pos (point-at-bol))
6884 (end-of-line)
6885 (setq hide-previous (outline-invisible-p)))
6886 (and org-insert-heading-respect-content (org-show-subtree))
6887 (let ((split
6888 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
6889 (save-excursion
6890 (let ((p (point)))
6891 (goto-char (point-at-bol))
6892 (and (looking-at org-complex-heading-regexp)
6893 (> p (match-beginning 4)))))))
6894 tags pos)
6895 (cond
6896 (org-insert-heading-respect-content
6897 (org-end-of-subtree nil t)
6898 (when (featurep 'org-inlinetask)
6899 (while (and (not (eobp))
6900 (looking-at "\\(\\*+\\)[ \t]+")
6901 (>= (length (match-string 1))
6902 org-inlinetask-min-level))
6903 (org-end-of-subtree nil t)))
6904 (or (bolp) (newline))
6905 (or (org-previous-line-empty-p)
6906 (and blank (newline)))
6907 (open-line 1))
6908 ((org-on-heading-p)
6909 (when hide-previous
6910 (show-children)
6911 (org-show-entry))
6912 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
6913 (setq tags (and (match-end 2) (match-string 2)))
6914 (and (match-end 1)
6915 (delete-region (match-beginning 1) (match-end 1)))
6916 (setq pos (point-at-bol))
6917 (or split (end-of-line 1))
6918 (delete-horizontal-space)
6919 (if (string-match "\\`\\*+\\'"
6920 (buffer-substring (point-at-bol) (point)))
6921 (insert " "))
6922 (newline (if blank 2 1))
6923 (when tags
6924 (save-excursion
6925 (goto-char pos)
6926 (end-of-line 1)
6927 (insert " " tags)
6928 (org-set-tags nil 'align))))
6930 (or split (end-of-line 1))
6931 (newline (if blank 2 1)))))))
6932 (insert head) (just-one-space)
6933 (setq pos (point))
6934 (end-of-line 1)
6935 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6936 (when (and org-insert-heading-respect-content hide-previous)
6937 (save-excursion
6938 (goto-char previous-pos)
6939 (hide-subtree)))
6940 (run-hooks 'org-insert-heading-hook)))))
6942 (defun org-get-heading (&optional no-tags)
6943 "Return the heading of the current entry, without the stars."
6944 (save-excursion
6945 (org-back-to-heading t)
6946 (if (looking-at
6947 (if no-tags
6948 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@#%]+:[ \t]*\\)?$")
6949 "\\*+[ \t]+\\([^\r\n]*\\)"))
6950 (match-string 1) "")))
6952 (defun org-heading-components ()
6953 "Return the components of the current heading.
6954 This is a list with the following elements:
6955 - the level as an integer
6956 - the reduced level, different if `org-odd-levels-only' is set.
6957 - the TODO keyword, or nil
6958 - the priority character, like ?A, or nil if no priority is given
6959 - the headline text itself, or the tags string if no headline text
6960 - the tags string, or nil."
6961 (save-excursion
6962 (org-back-to-heading t)
6963 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
6964 (list (length (match-string 1))
6965 (org-reduced-level (length (match-string 1)))
6966 (org-match-string-no-properties 2)
6967 (and (match-end 3) (aref (match-string 3) 2))
6968 (org-match-string-no-properties 4)
6969 (org-match-string-no-properties 5)))))
6971 (defun org-get-entry ()
6972 "Get the entry text, after heading, entire subtree."
6973 (save-excursion
6974 (org-back-to-heading t)
6975 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
6977 (defun org-insert-heading-after-current ()
6978 "Insert a new heading with same level as current, after current subtree."
6979 (interactive)
6980 (org-back-to-heading)
6981 (org-insert-heading)
6982 (org-move-subtree-down)
6983 (end-of-line 1))
6985 (defun org-insert-heading-respect-content ()
6986 (interactive)
6987 (let ((org-insert-heading-respect-content t))
6988 (org-insert-heading t)))
6990 (defun org-insert-todo-heading-respect-content (&optional force-state)
6991 (interactive "P")
6992 (let ((org-insert-heading-respect-content t))
6993 (org-insert-todo-heading force-state t)))
6995 (defun org-insert-todo-heading (arg &optional force-heading)
6996 "Insert a new heading with the same level and TODO state as current heading.
6997 If the heading has no TODO state, or if the state is DONE, use the first
6998 state (TODO by default). Also with prefix arg, force first state."
6999 (interactive "P")
7000 (when (or force-heading (not (org-insert-item 'checkbox)))
7001 (org-insert-heading force-heading)
7002 (save-excursion
7003 (org-back-to-heading)
7004 (outline-previous-heading)
7005 (looking-at org-todo-line-regexp))
7006 (let*
7007 ((new-mark-x
7008 (if (or arg
7009 (not (match-beginning 2))
7010 (member (match-string 2) org-done-keywords))
7011 (car org-todo-keywords-1)
7012 (match-string 2)))
7013 (new-mark
7015 (run-hook-with-args-until-success
7016 'org-todo-get-default-hook new-mark-x nil)
7017 new-mark-x)))
7018 (beginning-of-line 1)
7019 (and (looking-at "\\*+ ") (goto-char (match-end 0))
7020 (if org-treat-insert-todo-heading-as-state-change
7021 (org-todo new-mark)
7022 (insert new-mark " "))))
7023 (when org-provide-todo-statistics
7024 (org-update-parent-todo-statistics))))
7026 (defun org-insert-subheading (arg)
7027 "Insert a new subheading and demote it.
7028 Works for outline headings and for plain lists alike."
7029 (interactive "P")
7030 (org-insert-heading arg)
7031 (cond
7032 ((org-on-heading-p) (org-do-demote))
7033 ((org-at-item-p) (org-indent-item))))
7035 (defun org-insert-todo-subheading (arg)
7036 "Insert a new subheading with TODO keyword or checkbox and demote it.
7037 Works for outline headings and for plain lists alike."
7038 (interactive "P")
7039 (org-insert-todo-heading arg)
7040 (cond
7041 ((org-on-heading-p) (org-do-demote))
7042 ((org-at-item-p) (org-indent-item))))
7044 ;;; Promotion and Demotion
7046 (defvar org-after-demote-entry-hook nil
7047 "Hook run after an entry has been demoted.
7048 The cursor will be at the beginning of the entry.
7049 When a subtree is being demoted, the hook will be called for each node.")
7051 (defvar org-after-promote-entry-hook nil
7052 "Hook run after an entry has been promoted.
7053 The cursor will be at the beginning of the entry.
7054 When a subtree is being promoted, the hook will be called for each node.")
7056 (defun org-promote-subtree ()
7057 "Promote the entire subtree.
7058 See also `org-promote'."
7059 (interactive)
7060 (save-excursion
7061 (org-with-limited-levels (org-map-tree 'org-promote)))
7062 (org-fix-position-after-promote))
7064 (defun org-demote-subtree ()
7065 "Demote the entire subtree. See `org-demote'.
7066 See also `org-promote'."
7067 (interactive)
7068 (save-excursion
7069 (org-with-limited-levels (org-map-tree 'org-demote)))
7070 (org-fix-position-after-promote))
7073 (defun org-do-promote ()
7074 "Promote the current heading higher up the tree.
7075 If the region is active in `transient-mark-mode', promote all headings
7076 in the region."
7077 (interactive)
7078 (save-excursion
7079 (if (org-region-active-p)
7080 (org-map-region 'org-promote (region-beginning) (region-end))
7081 (org-promote)))
7082 (org-fix-position-after-promote))
7084 (defun org-do-demote ()
7085 "Demote the current heading lower down the tree.
7086 If the region is active in `transient-mark-mode', demote all headings
7087 in the region."
7088 (interactive)
7089 (save-excursion
7090 (if (org-region-active-p)
7091 (org-map-region 'org-demote (region-beginning) (region-end))
7092 (org-demote)))
7093 (org-fix-position-after-promote))
7095 (defun org-fix-position-after-promote ()
7096 "Make sure that after pro/demotion cursor position is right."
7097 (let ((pos (point)))
7098 (when (save-excursion
7099 (beginning-of-line 1)
7100 (looking-at org-todo-line-regexp)
7101 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7102 (cond ((eobp) (insert " "))
7103 ((eolp) (insert " "))
7104 ((equal (char-after) ?\ ) (forward-char 1))))))
7106 (defun org-current-level ()
7107 "Return the level of the current entry, or nil if before the first headline.
7108 The level is the number of stars at the beginning of the headline."
7109 (save-excursion
7110 (org-with-limited-levels
7111 (ignore-errors
7112 (org-back-to-heading t)
7113 (funcall outline-level)))))
7115 (defun org-get-previous-line-level ()
7116 "Return the outline depth of the last headline before the current line.
7117 Returns 0 for the first headline in the buffer, and nil if before the
7118 first headline."
7119 (let ((current-level (org-current-level))
7120 (prev-level (when (> (line-number-at-pos) 1)
7121 (save-excursion
7122 (beginning-of-line 0)
7123 (org-current-level)))))
7124 (cond ((null current-level) nil) ; Before first headline
7125 ((null prev-level) 0) ; At first headline
7126 (prev-level))))
7128 (defun org-reduced-level (l)
7129 "Compute the effective level of a heading.
7130 This takes into account the setting of `org-odd-levels-only'."
7131 (cond
7132 ((zerop l) 0)
7133 (org-odd-levels-only (1+ (floor (/ l 2))))
7134 (t l)))
7136 (defun org-level-increment ()
7137 "Return the number of stars that will be added or removed at a
7138 time to headlines when structure editing, based on the value of
7139 `org-odd-levels-only'."
7140 (if org-odd-levels-only 2 1))
7142 (defun org-get-valid-level (level &optional change)
7143 "Rectify a level change under the influence of `org-odd-levels-only'
7144 LEVEL is a current level, CHANGE is by how much the level should be
7145 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7146 even level numbers will become the next higher odd number."
7147 (if org-odd-levels-only
7148 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7149 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7150 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7151 (max 1 (+ level (or change 0)))))
7153 (if (boundp 'define-obsolete-function-alias)
7154 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7155 (define-obsolete-function-alias 'org-get-legal-level
7156 'org-get-valid-level)
7157 (define-obsolete-function-alias 'org-get-legal-level
7158 'org-get-valid-level "23.1")))
7160 (defun org-promote ()
7161 "Promote the current heading higher up the tree.
7162 If the region is active in `transient-mark-mode', promote all headings
7163 in the region."
7164 (org-back-to-heading t)
7165 (let* ((level (save-match-data (funcall outline-level)))
7166 (after-change-functions (remove 'flyspell-after-change-function
7167 after-change-functions))
7168 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7169 (diff (abs (- level (length up-head) -1))))
7170 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
7171 (replace-match up-head nil t)
7172 ;; Fixup tag positioning
7173 (and org-auto-align-tags (org-set-tags nil t))
7174 (if org-adapt-indentation (org-fixup-indentation (- diff)))
7175 (run-hooks 'org-after-promote-entry-hook)))
7177 (defun org-demote ()
7178 "Demote the current heading lower down the tree.
7179 If the region is active in `transient-mark-mode', demote all headings
7180 in the region."
7181 (org-back-to-heading t)
7182 (let* ((level (save-match-data (funcall outline-level)))
7183 (after-change-functions (remove 'flyspell-after-change-function
7184 after-change-functions))
7185 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7186 (diff (abs (- level (length down-head) -1))))
7187 (replace-match down-head nil t)
7188 ;; Fixup tag positioning
7189 (and org-auto-align-tags (org-set-tags nil t))
7190 (if org-adapt-indentation (org-fixup-indentation diff))
7191 (run-hooks 'org-after-demote-entry-hook)))
7193 (defun org-cycle-level ()
7194 "Cycle the level of an empty headline through possible states.
7195 This goes first to child, then to parent, level, then up the hierarchy.
7196 After top level, it switches back to sibling level."
7197 (interactive)
7198 (let ((org-adapt-indentation nil))
7199 (when (org-point-at-end-of-empty-headline)
7200 (setq this-command 'org-cycle-level) ; Only needed for caching
7201 (let ((cur-level (org-current-level))
7202 (prev-level (org-get-previous-line-level)))
7203 (cond
7204 ;; If first headline in file, promote to top-level.
7205 ((= prev-level 0)
7206 (loop repeat (/ (- cur-level 1) (org-level-increment))
7207 do (org-do-promote)))
7208 ;; If same level as prev, demote one.
7209 ((= prev-level cur-level)
7210 (org-do-demote))
7211 ;; If parent is top-level, promote to top level if not already.
7212 ((= prev-level 1)
7213 (loop repeat (/ (- cur-level 1) (org-level-increment))
7214 do (org-do-promote)))
7215 ;; If top-level, return to prev-level.
7216 ((= cur-level 1)
7217 (loop repeat (/ (- prev-level 1) (org-level-increment))
7218 do (org-do-demote)))
7219 ;; If less than prev-level, promote one.
7220 ((< cur-level prev-level)
7221 (org-do-promote))
7222 ;; If deeper than prev-level, promote until higher than
7223 ;; prev-level.
7224 ((> cur-level prev-level)
7225 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7226 do (org-do-promote))))
7227 t))))
7229 (defun org-map-tree (fun)
7230 "Call FUN for every heading underneath the current one."
7231 (org-back-to-heading)
7232 (let ((level (funcall outline-level)))
7233 (save-excursion
7234 (funcall fun)
7235 (while (and (progn
7236 (outline-next-heading)
7237 (> (funcall outline-level) level))
7238 (not (eobp)))
7239 (funcall fun)))))
7241 (defun org-map-region (fun beg end)
7242 "Call FUN for every heading between BEG and END."
7243 (let ((org-ignore-region t))
7244 (save-excursion
7245 (setq end (copy-marker end))
7246 (goto-char beg)
7247 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
7248 (< (point) end))
7249 (funcall fun))
7250 (while (and (progn
7251 (outline-next-heading)
7252 (< (point) end))
7253 (not (eobp)))
7254 (funcall fun)))))
7256 (defun org-fixup-indentation (diff)
7257 "Change the indentation in the current entry by DIFF.
7258 However, if any line in the current entry has no indentation, or if it
7259 would end up with no indentation after the change, nothing at all is done."
7260 (save-excursion
7261 (let ((end (save-excursion (outline-next-heading)
7262 (point-marker)))
7263 (prohibit (if (> diff 0)
7264 "^\\S-"
7265 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7266 col)
7267 (unless (save-excursion (end-of-line 1)
7268 (re-search-forward prohibit end t))
7269 (while (and (< (point) end)
7270 (re-search-forward "^[ \t]+" end t))
7271 (goto-char (match-end 0))
7272 (setq col (current-column))
7273 (if (< diff 0) (replace-match ""))
7274 (org-indent-to-column (+ diff col))))
7275 (move-marker end nil))))
7277 (defun org-convert-to-odd-levels ()
7278 "Convert an org-mode file with all levels allowed to one with odd levels.
7279 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7280 level 5 etc."
7281 (interactive)
7282 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7283 (let ((outline-regexp org-outline-regexp)
7284 (outline-level 'org-outline-level)
7285 (org-odd-levels-only nil) n)
7286 (save-excursion
7287 (goto-char (point-min))
7288 (while (re-search-forward "^\\*\\*+ " nil t)
7289 (setq n (- (length (match-string 0)) 2))
7290 (while (>= (setq n (1- n)) 0)
7291 (org-demote))
7292 (end-of-line 1))))))
7294 (defun org-convert-to-oddeven-levels ()
7295 "Convert an org-mode file with only odd levels to one with odd/even levels.
7296 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7297 file contains a section with an even level, conversion would
7298 destroy the structure of the file. An error is signaled in this
7299 case."
7300 (interactive)
7301 (goto-char (point-min))
7302 ;; First check if there are no even levels
7303 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7304 (org-show-context t)
7305 (error "Not all levels are odd in this file. Conversion not possible"))
7306 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7307 (let ((outline-regexp org-outline-regexp)
7308 (outline-level 'org-outline-level)
7309 (org-odd-levels-only nil) n)
7310 (save-excursion
7311 (goto-char (point-min))
7312 (while (re-search-forward "^\\*\\*+ " nil t)
7313 (setq n (/ (1- (length (match-string 0))) 2))
7314 (while (>= (setq n (1- n)) 0)
7315 (org-promote))
7316 (end-of-line 1))))))
7318 (defun org-tr-level (n)
7319 "Make N odd if required."
7320 (if org-odd-levels-only (1+ (/ n 2)) n))
7322 ;;; Vertical tree motion, cutting and pasting of subtrees
7324 (defun org-move-subtree-up (&optional arg)
7325 "Move the current subtree up past ARG headlines of the same level."
7326 (interactive "p")
7327 (org-move-subtree-down (- (prefix-numeric-value arg))))
7329 (defun org-move-subtree-down (&optional arg)
7330 "Move the current subtree down past ARG headlines of the same level."
7331 (interactive "p")
7332 (setq arg (prefix-numeric-value arg))
7333 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7334 'org-get-last-sibling))
7335 (ins-point (make-marker))
7336 (cnt (abs arg))
7337 (col (current-column))
7338 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7339 ;; Select the tree
7340 (org-back-to-heading)
7341 (setq beg0 (point))
7342 (save-excursion
7343 (setq ne-beg (org-back-over-empty-lines))
7344 (setq beg (point)))
7345 (save-match-data
7346 (save-excursion (outline-end-of-heading)
7347 (setq folded (outline-invisible-p)))
7348 (outline-end-of-subtree))
7349 (outline-next-heading)
7350 (setq ne-end (org-back-over-empty-lines))
7351 (setq end (point))
7352 (goto-char beg0)
7353 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7354 ;; include less whitespace
7355 (save-excursion
7356 (goto-char beg)
7357 (forward-line (- ne-beg ne-end))
7358 (setq beg (point))))
7359 ;; Find insertion point, with error handling
7360 (while (> cnt 0)
7361 (or (and (funcall movfunc) (looking-at outline-regexp))
7362 (progn (goto-char beg0)
7363 (error "Cannot move past superior level or buffer limit")))
7364 (setq cnt (1- cnt)))
7365 (if (> arg 0)
7366 ;; Moving forward - still need to move over subtree
7367 (progn (org-end-of-subtree t t)
7368 (save-excursion
7369 (org-back-over-empty-lines)
7370 (or (bolp) (newline)))))
7371 (setq ne-ins (org-back-over-empty-lines))
7372 (move-marker ins-point (point))
7373 (setq txt (buffer-substring beg end))
7374 (org-save-markers-in-region beg end)
7375 (delete-region beg end)
7376 (org-remove-empty-overlays-at beg)
7377 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7378 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7379 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7380 (let ((bbb (point)))
7381 (insert-before-markers txt)
7382 (org-reinstall-markers-in-region bbb)
7383 (move-marker ins-point bbb))
7384 (or (bolp) (insert "\n"))
7385 (setq ins-end (point))
7386 (goto-char ins-point)
7387 (org-skip-whitespace)
7388 (when (and (< arg 0)
7389 (org-first-sibling-p)
7390 (> ne-ins ne-beg))
7391 ;; Move whitespace back to beginning
7392 (save-excursion
7393 (goto-char ins-end)
7394 (let ((kill-whole-line t))
7395 (kill-line (- ne-ins ne-beg)) (point)))
7396 (insert (make-string (- ne-ins ne-beg) ?\n)))
7397 (move-marker ins-point nil)
7398 (if folded
7399 (hide-subtree)
7400 (org-show-entry)
7401 (show-children)
7402 (org-cycle-hide-drawers 'children))
7403 (org-clean-visibility-after-subtree-move)
7404 ;; move back to the initial column we were at
7405 (move-to-column col)))
7407 (defvar org-subtree-clip ""
7408 "Clipboard for cut and paste of subtrees.
7409 This is actually only a copy of the kill, because we use the normal kill
7410 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7412 (defvar org-subtree-clip-folded nil
7413 "Was the last copied subtree folded?
7414 This is used to fold the tree back after pasting.")
7416 (defun org-cut-subtree (&optional n)
7417 "Cut the current subtree into the clipboard.
7418 With prefix arg N, cut this many sequential subtrees.
7419 This is a short-hand for marking the subtree and then cutting it."
7420 (interactive "p")
7421 (org-copy-subtree n 'cut))
7423 (defun org-copy-subtree (&optional n cut force-store-markers)
7424 "Cut the current subtree into the clipboard.
7425 With prefix arg N, cut this many sequential subtrees.
7426 This is a short-hand for marking the subtree and then copying it.
7427 If CUT is non-nil, actually cut the subtree.
7428 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7429 of some markers in the region, even if CUT is non-nil. This is
7430 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7431 (interactive "p")
7432 (let (beg end folded (beg0 (point)))
7433 (if (interactive-p)
7434 (org-back-to-heading nil) ; take what looks like a subtree
7435 (org-back-to-heading t)) ; take what is really there
7436 (org-back-over-empty-lines)
7437 (setq beg (point))
7438 (skip-chars-forward " \t\r\n")
7439 (save-match-data
7440 (save-excursion (outline-end-of-heading)
7441 (setq folded (outline-invisible-p)))
7442 (condition-case nil
7443 (org-forward-same-level (1- n) t)
7444 (error nil))
7445 (org-end-of-subtree t t))
7446 (org-back-over-empty-lines)
7447 (setq end (point))
7448 (goto-char beg0)
7449 (when (> end beg)
7450 (setq org-subtree-clip-folded folded)
7451 (when (or cut force-store-markers)
7452 (org-save-markers-in-region beg end))
7453 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7454 (setq org-subtree-clip (current-kill 0))
7455 (message "%s: Subtree(s) with %d characters"
7456 (if cut "Cut" "Copied")
7457 (length org-subtree-clip)))))
7459 (defun org-paste-subtree (&optional level tree for-yank)
7460 "Paste the clipboard as a subtree, with modification of headline level.
7461 The entire subtree is promoted or demoted in order to match a new headline
7462 level.
7464 If the cursor is at the beginning of a headline, the same level as
7465 that headline is used to paste the tree
7467 If not, the new level is derived from the *visible* headings
7468 before and after the insertion point, and taken to be the inferior headline
7469 level of the two. So if the previous visible heading is level 3 and the
7470 next is level 4 (or vice versa), level 4 will be used for insertion.
7471 This makes sure that the subtree remains an independent subtree and does
7472 not swallow low level entries.
7474 You can also force a different level, either by using a numeric prefix
7475 argument, or by inserting the heading marker by hand. For example, if the
7476 cursor is after \"*****\", then the tree will be shifted to level 5.
7478 If optional TREE is given, use this text instead of the kill ring.
7480 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7481 move back over whitespace before inserting, and move point to the end of
7482 the inserted text when done."
7483 (interactive "P")
7484 (setq tree (or tree (and kill-ring (current-kill 0))))
7485 (unless (org-kill-is-subtree-p tree)
7486 (error "%s"
7487 (substitute-command-keys
7488 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7489 (let* ((visp (not (outline-invisible-p)))
7490 (txt tree)
7491 (^re (concat "^\\(" outline-regexp "\\)"))
7492 (re (concat "\\(" outline-regexp "\\)"))
7493 (^re_ (concat "\\(\\*+\\)[ \t]*"))
7495 (old-level (if (string-match ^re txt)
7496 (- (match-end 0) (match-beginning 0) 1)
7497 -1))
7498 (force-level (cond (level (prefix-numeric-value level))
7499 ((and (looking-at "[ \t]*$")
7500 (string-match
7501 ^re_ (buffer-substring
7502 (point-at-bol) (point))))
7503 (- (match-end 1) (match-beginning 1)))
7504 ((and (bolp)
7505 (looking-at org-outline-regexp))
7506 (- (match-end 0) (point) 1))
7507 (t nil)))
7508 (previous-level (save-excursion
7509 (condition-case nil
7510 (progn
7511 (outline-previous-visible-heading 1)
7512 (if (looking-at re)
7513 (- (match-end 0) (match-beginning 0) 1)
7515 (error 1))))
7516 (next-level (save-excursion
7517 (condition-case nil
7518 (progn
7519 (or (looking-at outline-regexp)
7520 (outline-next-visible-heading 1))
7521 (if (looking-at re)
7522 (- (match-end 0) (match-beginning 0) 1)
7524 (error 1))))
7525 (new-level (or force-level (max previous-level next-level)))
7526 (shift (if (or (= old-level -1)
7527 (= new-level -1)
7528 (= old-level new-level))
7530 (- new-level old-level)))
7531 (delta (if (> shift 0) -1 1))
7532 (func (if (> shift 0) 'org-demote 'org-promote))
7533 (org-odd-levels-only nil)
7534 beg end newend)
7535 ;; Remove the forced level indicator
7536 (if force-level
7537 (delete-region (point-at-bol) (point)))
7538 ;; Paste
7539 (beginning-of-line 1)
7540 (unless for-yank (org-back-over-empty-lines))
7541 (setq beg (point))
7542 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7543 (insert-before-markers txt)
7544 (unless (string-match "\n\\'" txt) (insert "\n"))
7545 (setq newend (point))
7546 (org-reinstall-markers-in-region beg)
7547 (setq end (point))
7548 (goto-char beg)
7549 (skip-chars-forward " \t\n\r")
7550 (setq beg (point))
7551 (if (and (outline-invisible-p) visp)
7552 (save-excursion (outline-show-heading)))
7553 ;; Shift if necessary
7554 (unless (= shift 0)
7555 (save-restriction
7556 (narrow-to-region beg end)
7557 (while (not (= shift 0))
7558 (org-map-region func (point-min) (point-max))
7559 (setq shift (+ delta shift)))
7560 (goto-char (point-min))
7561 (setq newend (point-max))))
7562 (when (or (interactive-p) for-yank)
7563 (message "Clipboard pasted as level %d subtree" new-level))
7564 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7565 kill-ring
7566 (eq org-subtree-clip (current-kill 0))
7567 org-subtree-clip-folded)
7568 ;; The tree was folded before it was killed/copied
7569 (hide-subtree))
7570 (and for-yank (goto-char newend))))
7572 (defun org-kill-is-subtree-p (&optional txt)
7573 "Check if the current kill is an outline subtree, or a set of trees.
7574 Returns nil if kill does not start with a headline, or if the first
7575 headline level is not the largest headline level in the tree.
7576 So this will actually accept several entries of equal levels as well,
7577 which is OK for `org-paste-subtree'.
7578 If optional TXT is given, check this string instead of the current kill."
7579 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7580 (start-level (and kill
7581 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
7582 org-outline-regexp "\\)")
7583 kill)
7584 (- (match-end 2) (match-beginning 2) 1)))
7585 (re (concat "^" org-outline-regexp))
7586 (start (1+ (or (match-beginning 2) -1))))
7587 (if (not start-level)
7588 (progn
7589 nil) ;; does not even start with a heading
7590 (catch 'exit
7591 (while (setq start (string-match re kill (1+ start)))
7592 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7593 (throw 'exit nil)))
7594 t))))
7596 (defvar org-markers-to-move nil
7597 "Markers that should be moved with a cut-and-paste operation.
7598 Those markers are stored together with their positions relative to
7599 the start of the region.")
7601 (defun org-save-markers-in-region (beg end)
7602 "Check markers in region.
7603 If these markers are between BEG and END, record their position relative
7604 to BEG, so that after moving the block of text, we can put the markers back
7605 into place.
7606 This function gets called just before an entry or tree gets cut from the
7607 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7608 called immediately, to move the markers with the entries."
7609 (setq org-markers-to-move nil)
7610 (when (featurep 'org-clock)
7611 (org-clock-save-markers-for-cut-and-paste beg end))
7612 (when (featurep 'org-agenda)
7613 (org-agenda-save-markers-for-cut-and-paste beg end)))
7615 (defun org-check-and-save-marker (marker beg end)
7616 "Check if MARKER is between BEG and END.
7617 If yes, remember the marker and the distance to BEG."
7618 (when (and (marker-buffer marker)
7619 (equal (marker-buffer marker) (current-buffer)))
7620 (if (and (>= marker beg) (< marker end))
7621 (push (cons marker (- marker beg)) org-markers-to-move))))
7623 (defun org-reinstall-markers-in-region (beg)
7624 "Move all remembered markers to their position relative to BEG."
7625 (mapc (lambda (x)
7626 (move-marker (car x) (+ beg (cdr x))))
7627 org-markers-to-move)
7628 (setq org-markers-to-move nil))
7630 (defun org-narrow-to-subtree ()
7631 "Narrow buffer to the current subtree."
7632 (interactive)
7633 (save-excursion
7634 (save-match-data
7635 (org-with-limited-levels
7636 (narrow-to-region
7637 (progn (org-back-to-heading t) (point))
7638 (progn (org-end-of-subtree t t)
7639 (if (and (org-on-heading-p) (not (eobp))) (backward-char 1))
7640 (point)))))))
7642 (defun org-narrow-to-block ()
7643 "Narrow buffer to the current block."
7644 (interactive)
7645 (let ((bstart "^[ \t]*#\\+begin")
7646 (bend "[ \t]*#\\+end")
7647 (case-fold-search t) ;; allow #+BEGIN
7648 b_start b_end)
7649 (if (org-in-regexps-block-p bstart bend)
7650 (progn
7651 (save-excursion (re-search-backward bstart nil t)
7652 (setq b_start (match-beginning 0)))
7653 (save-excursion (re-search-forward bend nil t)
7654 (setq b_end (match-end 0)))
7655 (narrow-to-region b_start b_end))
7656 (error "Not in a block"))))
7658 (eval-when-compile
7659 (defvar org-property-drawer-re))
7661 (defvar org-property-start-re) ;; defined below
7662 (defun org-clone-subtree-with-time-shift (n &optional shift)
7663 "Clone the task (subtree) at point N times.
7664 The clones will be inserted as siblings.
7666 In interactive use, the user will be prompted for the number of
7667 clones to be produced, and for a time SHIFT, which may be a
7668 repeater as used in time stamps, for example `+3d'.
7670 When a valid repeater is given and the entry contains any time
7671 stamps, the clones will become a sequence in time, with time
7672 stamps in the subtree shifted for each clone produced. If SHIFT
7673 is nil or the empty string, time stamps will be left alone. The
7674 ID property of the original subtree is removed.
7676 If the original subtree did contain time stamps with a repeater,
7677 the following will happen:
7678 - the repeater will be removed in each clone
7679 - an additional clone will be produced, with the current, unshifted
7680 date(s) in the entry.
7681 - the original entry will be placed *after* all the clones, with
7682 repeater intact.
7683 - the start days in the repeater in the original entry will be shifted
7684 to past the last clone.
7685 I this way you can spell out a number of instances of a repeating task,
7686 and still retain the repeater to cover future instances of the task."
7687 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7688 (let (beg end template task idprop
7689 shift-n shift-what doshift nmin nmax (n-no-remove -1))
7690 (if (not (and (integerp n) (> n 0)))
7691 (error "Invalid number of replications %s" n))
7692 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7693 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
7694 shift)))
7695 (error "Invalid shift specification %s" shift))
7696 (when doshift
7697 (setq shift-n (string-to-number (match-string 1 shift))
7698 shift-what (cdr (assoc (match-string 2 shift)
7699 '(("d" . day) ("w" . week)
7700 ("m" . month) ("y" . year))))))
7701 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7702 (setq nmin 1 nmax n)
7703 (org-back-to-heading t)
7704 (setq beg (point))
7705 (setq idprop (org-entry-get nil "ID"))
7706 (org-end-of-subtree t t)
7707 (or (bolp) (insert "\n"))
7708 (setq end (point))
7709 (setq template (buffer-substring beg end))
7710 (when (and doshift
7711 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
7712 (delete-region beg end)
7713 (setq end beg)
7714 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7715 (goto-char end)
7716 (loop for n from nmin to nmax do
7717 ;; prepare clone
7718 (with-temp-buffer
7719 (insert template)
7720 (org-mode)
7721 (goto-char (point-min))
7722 (and idprop (if org-clone-delete-id
7723 (org-entry-delete nil "ID")
7724 (org-id-get-create t)))
7725 (while (re-search-forward org-property-start-re nil t)
7726 (org-remove-empty-drawer-at "PROPERTIES" (point)))
7727 (goto-char (point-min))
7728 (when doshift
7729 (while (re-search-forward org-ts-regexp-both nil t)
7730 (org-timestamp-change (* n shift-n) shift-what))
7731 (unless (= n n-no-remove)
7732 (goto-char (point-min))
7733 (while (re-search-forward org-ts-regexp nil t)
7734 (save-excursion
7735 (goto-char (match-beginning 0))
7736 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
7737 (delete-region (match-beginning 1) (match-end 1)))))))
7738 (setq task (buffer-string)))
7739 (insert task))
7740 (goto-char beg)))
7742 ;;; Outline Sorting
7744 (defun org-sort (with-case)
7745 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
7746 Optional argument WITH-CASE means sort case-sensitively.
7747 With a double prefix argument, also remove duplicate entries."
7748 (interactive "P")
7749 (cond
7750 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
7751 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
7753 (org-call-with-arg 'org-sort-entries with-case))))
7755 (defun org-sort-remove-invisible (s)
7756 (remove-text-properties 0 (length s) org-rm-props s)
7757 (while (string-match org-bracket-link-regexp s)
7758 (setq s (replace-match (if (match-end 2)
7759 (match-string 3 s)
7760 (match-string 1 s)) t t s)))
7763 (defvar org-priority-regexp) ; defined later in the file
7765 (defvar org-after-sorting-entries-or-items-hook nil
7766 "Hook that is run after a bunch of entries or items have been sorted.
7767 When children are sorted, the cursor is in the parent line when this
7768 hook gets called. When a region or a plain list is sorted, the cursor
7769 will be in the first entry of the sorted region/list.")
7771 (defun org-sort-entries
7772 (&optional with-case sorting-type getkey-func compare-func property)
7773 "Sort entries on a certain level of an outline tree.
7774 If there is an active region, the entries in the region are sorted.
7775 Else, if the cursor is before the first entry, sort the top-level items.
7776 Else, the children of the entry at point are sorted.
7778 Sorting can be alphabetically, numerically, by date/time as given by
7779 a time stamp, by a property or by priority.
7781 The command prompts for the sorting type unless it has been given to the
7782 function through the SORTING-TYPE argument, which needs to be a character,
7783 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
7784 precise meaning of each character:
7786 n Numerically, by converting the beginning of the entry/item to a number.
7787 a Alphabetically, ignoring the TODO keyword and the priority, if any.
7788 t By date/time, either the first active time stamp in the entry, or, if
7789 none exist, by the first inactive one.
7790 s By the scheduled date/time.
7791 d By deadline date/time.
7792 c By creation time, which is assumed to be the first inactive time stamp
7793 at the beginning of a line.
7794 p By priority according to the cookie.
7795 r By the value of a property.
7797 Capital letters will reverse the sort order.
7799 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
7800 called with point at the beginning of the record. It must return either
7801 a string or a number that should serve as the sorting key for that record.
7803 Comparing entries ignores case by default. However, with an optional argument
7804 WITH-CASE, the sorting considers case as well."
7805 (interactive "P")
7806 (let ((case-func (if with-case 'identity 'downcase))
7807 start beg end stars re re2
7808 txt what tmp)
7809 ;; Find beginning and end of region to sort
7810 (cond
7811 ((org-region-active-p)
7812 ;; we will sort the region
7813 (setq end (region-end)
7814 what "region")
7815 (goto-char (region-beginning))
7816 (if (not (org-on-heading-p)) (outline-next-heading))
7817 (setq start (point)))
7818 ((or (org-on-heading-p)
7819 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
7820 ;; we will sort the children of the current headline
7821 (org-back-to-heading)
7822 (setq start (point)
7823 end (progn (org-end-of-subtree t t)
7824 (or (bolp) (insert "\n"))
7825 (org-back-over-empty-lines)
7826 (point))
7827 what "children")
7828 (goto-char start)
7829 (show-subtree)
7830 (outline-next-heading))
7832 ;; we will sort the top-level entries in this file
7833 (goto-char (point-min))
7834 (or (org-on-heading-p) (outline-next-heading))
7835 (setq start (point))
7836 (goto-char (point-max))
7837 (beginning-of-line 1)
7838 (when (looking-at ".*?\\S-")
7839 ;; File ends in a non-white line
7840 (end-of-line 1)
7841 (insert "\n"))
7842 (setq end (point-max))
7843 (setq what "top-level")
7844 (goto-char start)
7845 (show-all)))
7847 (setq beg (point))
7848 (if (>= beg end) (error "Nothing to sort"))
7850 (looking-at "\\(\\*+\\)")
7851 (setq stars (match-string 1)
7852 re (concat "^" (regexp-quote stars) " +")
7853 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
7854 txt (buffer-substring beg end))
7855 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
7856 (if (and (not (equal stars "*")) (string-match re2 txt))
7857 (error "Region to sort contains a level above the first entry"))
7859 (unless sorting-type
7860 (message
7861 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
7862 [t]ime [s]cheduled [d]eadline [c]reated
7863 A/N/T/S/D/C/P/O/F means reversed:"
7864 what)
7865 (setq sorting-type (read-char-exclusive))
7867 (and (= (downcase sorting-type) ?f)
7868 (setq getkey-func
7869 (org-icompleting-read "Sort using function: "
7870 obarray 'fboundp t nil nil))
7871 (setq getkey-func (intern getkey-func)))
7873 (and (= (downcase sorting-type) ?r)
7874 (setq property
7875 (org-icompleting-read "Property: "
7876 (mapcar 'list (org-buffer-property-keys t))
7877 nil t))))
7879 (message "Sorting entries...")
7881 (save-restriction
7882 (narrow-to-region start end)
7883 (let ((dcst (downcase sorting-type))
7884 (case-fold-search nil)
7885 (now (current-time)))
7886 (sort-subr
7887 (/= dcst sorting-type)
7888 ;; This function moves to the beginning character of the "record" to
7889 ;; be sorted.
7890 (lambda nil
7891 (if (re-search-forward re nil t)
7892 (goto-char (match-beginning 0))
7893 (goto-char (point-max))))
7894 ;; This function moves to the last character of the "record" being
7895 ;; sorted.
7896 (lambda nil
7897 (save-match-data
7898 (condition-case nil
7899 (outline-forward-same-level 1)
7900 (error
7901 (goto-char (point-max))))))
7902 ;; This function returns the value that gets sorted against.
7903 (lambda nil
7904 (cond
7905 ((= dcst ?n)
7906 (if (looking-at org-complex-heading-regexp)
7907 (string-to-number (match-string 4))
7908 nil))
7909 ((= dcst ?a)
7910 (if (looking-at org-complex-heading-regexp)
7911 (funcall case-func (match-string 4))
7912 nil))
7913 ((= dcst ?t)
7914 (let ((end (save-excursion (outline-next-heading) (point))))
7915 (if (or (re-search-forward org-ts-regexp end t)
7916 (re-search-forward org-ts-regexp-both end t))
7917 (org-time-string-to-seconds (match-string 0))
7918 (org-float-time now))))
7919 ((= dcst ?c)
7920 (let ((end (save-excursion (outline-next-heading) (point))))
7921 (if (re-search-forward
7922 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
7923 end t)
7924 (org-time-string-to-seconds (match-string 0))
7925 (org-float-time now))))
7926 ((= dcst ?s)
7927 (let ((end (save-excursion (outline-next-heading) (point))))
7928 (if (re-search-forward org-scheduled-time-regexp end t)
7929 (org-time-string-to-seconds (match-string 1))
7930 (org-float-time now))))
7931 ((= dcst ?d)
7932 (let ((end (save-excursion (outline-next-heading) (point))))
7933 (if (re-search-forward org-deadline-time-regexp end t)
7934 (org-time-string-to-seconds (match-string 1))
7935 (org-float-time now))))
7936 ((= dcst ?p)
7937 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7938 (string-to-char (match-string 2))
7939 org-default-priority))
7940 ((= dcst ?r)
7941 (or (org-entry-get nil property) ""))
7942 ((= dcst ?o)
7943 (if (looking-at org-complex-heading-regexp)
7944 (- 9999 (length (member (match-string 2)
7945 org-todo-keywords-1)))))
7946 ((= dcst ?f)
7947 (if getkey-func
7948 (progn
7949 (setq tmp (funcall getkey-func))
7950 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7951 tmp)
7952 (error "Invalid key function `%s'" getkey-func)))
7953 (t (error "Invalid sorting type `%c'" sorting-type))))
7955 (cond
7956 ((= dcst ?a) 'string<)
7957 ((= dcst ?f) compare-func)
7958 ((member dcst '(?p ?t ?s ?d ?c)) '<)
7959 (t nil)))))
7960 (run-hooks 'org-after-sorting-entries-or-items-hook)
7961 (message "Sorting entries...done")))
7963 (defun org-do-sort (table what &optional with-case sorting-type)
7964 "Sort TABLE of WHAT according to SORTING-TYPE.
7965 The user will be prompted for the SORTING-TYPE if the call to this
7966 function does not specify it. WHAT is only for the prompt, to indicate
7967 what is being sorted. The sorting key will be extracted from
7968 the car of the elements of the table.
7969 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7970 (unless sorting-type
7971 (message
7972 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7973 what)
7974 (setq sorting-type (read-char-exclusive)))
7975 (let ((dcst (downcase sorting-type))
7976 extractfun comparefun)
7977 ;; Define the appropriate functions
7978 (cond
7979 ((= dcst ?n)
7980 (setq extractfun 'string-to-number
7981 comparefun (if (= dcst sorting-type) '< '>)))
7982 ((= dcst ?a)
7983 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7984 (lambda(x) (downcase (org-sort-remove-invisible x))))
7985 comparefun (if (= dcst sorting-type)
7986 'string<
7987 (lambda (a b) (and (not (string< a b))
7988 (not (string= a b)))))))
7989 ((= dcst ?t)
7990 (setq extractfun
7991 (lambda (x)
7992 (if (or (string-match org-ts-regexp x)
7993 (string-match org-ts-regexp-both x))
7994 (org-float-time
7995 (org-time-string-to-time (match-string 0 x)))
7997 comparefun (if (= dcst sorting-type) '< '>)))
7998 (t (error "Invalid sorting type `%c'" sorting-type)))
8000 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8001 table)
8002 (lambda (a b) (funcall comparefun (car a) (car b))))))
8005 ;;; The orgstruct minor mode
8007 ;; Define a minor mode which can be used in other modes in order to
8008 ;; integrate the org-mode structure editing commands.
8010 ;; This is really a hack, because the org-mode structure commands use
8011 ;; keys which normally belong to the major mode. Here is how it
8012 ;; works: The minor mode defines all the keys necessary to operate the
8013 ;; structure commands, but wraps the commands into a function which
8014 ;; tests if the cursor is currently at a headline or a plain list
8015 ;; item. If that is the case, the structure command is used,
8016 ;; temporarily setting many Org-mode variables like regular
8017 ;; expressions for filling etc. However, when any of those keys is
8018 ;; used at a different location, function uses `key-binding' to look
8019 ;; up if the key has an associated command in another currently active
8020 ;; keymap (minor modes, major mode, global), and executes that
8021 ;; command. There might be problems if any of the keys is otherwise
8022 ;; used as a prefix key.
8024 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8025 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8026 ;; addresses this by checking explicitly for both bindings.
8028 (defvar orgstruct-mode-map (make-sparse-keymap)
8029 "Keymap for the minor `orgstruct-mode'.")
8031 (defvar org-local-vars nil
8032 "List of local variables, for use by `orgstruct-mode'.")
8034 ;;;###autoload
8035 (define-minor-mode orgstruct-mode
8036 "Toggle the minor mode `orgstruct-mode'.
8037 This mode is for using Org-mode structure commands in other
8038 modes. The following keys behave as if Org-mode were active, if
8039 the cursor is on a headline, or on a plain list item (both as
8040 defined by Org-mode).
8042 M-up Move entry/item up
8043 M-down Move entry/item down
8044 M-left Promote
8045 M-right Demote
8046 M-S-up Move entry/item up
8047 M-S-down Move entry/item down
8048 M-S-left Promote subtree
8049 M-S-right Demote subtree
8050 M-q Fill paragraph and items like in Org-mode
8051 C-c ^ Sort entries
8052 C-c - Cycle list bullet
8053 TAB Cycle item visibility
8054 M-RET Insert new heading/item
8055 S-M-RET Insert new TODO heading / Checkbox item
8056 C-c C-c Set tags / toggle checkbox"
8057 nil " OrgStruct" nil
8058 (org-load-modules-maybe)
8059 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8061 ;;;###autoload
8062 (defun turn-on-orgstruct ()
8063 "Unconditionally turn on `orgstruct-mode'."
8064 (orgstruct-mode 1))
8066 (defun orgstruct++-mode (&optional arg)
8067 "Toggle `orgstruct-mode', the enhanced version of it.
8068 In addition to setting orgstruct-mode, this also exports all indentation
8069 and autofilling variables from org-mode into the buffer. It will also
8070 recognize item context in multiline items.
8071 Note that turning off orgstruct-mode will *not* remove the
8072 indentation/paragraph settings. This can only be done by refreshing the
8073 major mode, for example with \\[normal-mode]."
8074 (interactive "P")
8075 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8076 (if (< arg 1)
8077 (orgstruct-mode -1)
8078 (orgstruct-mode 1)
8079 (let (var val)
8080 (mapc
8081 (lambda (x)
8082 (when (string-match
8083 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8084 (symbol-name (car x)))
8085 (setq var (car x) val (nth 1 x))
8086 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8087 org-local-vars)
8088 (org-set-local 'orgstruct-is-++ t))))
8090 (defvar orgstruct-is-++ nil
8091 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8092 (make-variable-buffer-local 'orgstruct-is-++)
8094 ;;;###autoload
8095 (defun turn-on-orgstruct++ ()
8096 "Unconditionally turn on `orgstruct++-mode'."
8097 (orgstruct++-mode 1))
8099 (defun orgstruct-error ()
8100 "Error when there is no default binding for a structure key."
8101 (interactive)
8102 (error "This key has no function outside structure elements"))
8104 (defun orgstruct-setup ()
8105 "Setup orgstruct keymaps."
8106 (let ((nfunc 0)
8107 (bindings
8108 (list
8109 '([(meta up)] org-metaup)
8110 '([(meta down)] org-metadown)
8111 '([(meta left)] org-metaleft)
8112 '([(meta right)] org-metaright)
8113 '([(meta shift up)] org-shiftmetaup)
8114 '([(meta shift down)] org-shiftmetadown)
8115 '([(meta shift left)] org-shiftmetaleft)
8116 '([(meta shift right)] org-shiftmetaright)
8117 '([?\e (up)] org-metaup)
8118 '([?\e (down)] org-metadown)
8119 '([?\e (left)] org-metaleft)
8120 '([?\e (right)] org-metaright)
8121 '([?\e (shift up)] org-shiftmetaup)
8122 '([?\e (shift down)] org-shiftmetadown)
8123 '([?\e (shift left)] org-shiftmetaleft)
8124 '([?\e (shift right)] org-shiftmetaright)
8125 '([(shift up)] org-shiftup)
8126 '([(shift down)] org-shiftdown)
8127 '([(shift left)] org-shiftleft)
8128 '([(shift right)] org-shiftright)
8129 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8130 '("\M-q" fill-paragraph)
8131 '("\C-c^" org-sort)
8132 '("\C-c-" org-cycle-list-bullet)))
8133 elt key fun cmd)
8134 (while (setq elt (pop bindings))
8135 (setq nfunc (1+ nfunc))
8136 (setq key (org-key (car elt))
8137 fun (nth 1 elt)
8138 cmd (orgstruct-make-binding fun nfunc key))
8139 (org-defkey orgstruct-mode-map key cmd))
8141 ;; Special treatment needed for TAB and RET
8142 (org-defkey orgstruct-mode-map [(tab)]
8143 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8144 (org-defkey orgstruct-mode-map "\C-i"
8145 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8147 (org-defkey orgstruct-mode-map "\M-\C-m"
8148 (orgstruct-make-binding 'org-insert-heading 105
8149 "\M-\C-m" [(meta return)]))
8150 (org-defkey orgstruct-mode-map [(meta return)]
8151 (orgstruct-make-binding 'org-insert-heading 106
8152 [(meta return)] "\M-\C-m"))
8154 (org-defkey orgstruct-mode-map [(shift meta return)]
8155 (orgstruct-make-binding 'org-insert-todo-heading 107
8156 [(meta return)] "\M-\C-m"))
8158 (org-defkey orgstruct-mode-map "\e\C-m"
8159 (orgstruct-make-binding 'org-insert-heading 108
8160 "\e\C-m" [?\e (return)]))
8161 (org-defkey orgstruct-mode-map [?\e (return)]
8162 (orgstruct-make-binding 'org-insert-heading 109
8163 [?\e (return)] "\e\C-m"))
8164 (org-defkey orgstruct-mode-map [?\e (shift return)]
8165 (orgstruct-make-binding 'org-insert-todo-heading 110
8166 [?\e (return)] "\e\C-m"))
8168 (unless org-local-vars
8169 (setq org-local-vars (org-get-local-variables)))
8173 (defun orgstruct-make-binding (fun n &rest keys)
8174 "Create a function for binding in the structure minor mode.
8175 FUN is the command to call inside a table. N is used to create a unique
8176 command name. KEYS are keys that should be checked in for a command
8177 to execute outside of tables."
8178 (eval
8179 (list 'defun
8180 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8181 '(arg)
8182 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8183 "Outside of structure, run the binding of `"
8184 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8185 "'.")
8186 '(interactive "p")
8187 (list 'if
8188 `(org-context-p 'headline 'item
8189 (and orgstruct-is-++
8190 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8191 'item-body))
8192 (list 'org-run-like-in-org-mode (list 'quote fun))
8193 (list 'let '(orgstruct-mode)
8194 (list 'call-interactively
8195 (append '(or)
8196 (mapcar (lambda (k)
8197 (list 'key-binding k))
8198 keys)
8199 '('orgstruct-error))))))))
8201 (defun org-context-p (&rest contexts)
8202 "Check if local context is any of CONTEXTS.
8203 Possible values in the list of contexts are `table', `headline', and `item'."
8204 (let ((pos (point)))
8205 (goto-char (point-at-bol))
8206 (prog1 (or (and (memq 'table contexts)
8207 (looking-at "[ \t]*|"))
8208 (and (memq 'headline contexts)
8209 ;;????????? (looking-at "\\*+"))
8210 (looking-at outline-regexp))
8211 (and (memq 'item contexts)
8212 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8213 (and (memq 'item-body contexts)
8214 (org-in-item-p)))
8215 (goto-char pos))))
8217 (defun org-get-local-variables ()
8218 "Return a list of all local variables in an org-mode buffer."
8219 (let (varlist)
8220 (with-current-buffer (get-buffer-create "*Org tmp*")
8221 (erase-buffer)
8222 (org-mode)
8223 (setq varlist (buffer-local-variables)))
8224 (kill-buffer "*Org tmp*")
8225 (delq nil
8226 (mapcar
8227 (lambda (x)
8228 (setq x
8229 (if (symbolp x)
8230 (list x)
8231 (list (car x) (list 'quote (cdr x)))))
8232 (if (string-match
8233 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8234 (symbol-name (car x)))
8235 x nil))
8236 varlist))))
8238 (defun org-clone-local-variables (from-buffer &optional regexp)
8239 "Clone local variables from FROM-BUFFER.
8240 Optional argument REGEXP selects variables to clone."
8241 (mapc
8242 (lambda (pair)
8243 (and (symbolp (car pair))
8244 (or (null regexp)
8245 (string-match regexp (symbol-name (car pair))))
8246 (set (make-local-variable (car pair))
8247 (cdr pair))))
8248 (buffer-local-variables from-buffer)))
8250 ;;;###autoload
8251 (defun org-run-like-in-org-mode (cmd)
8252 "Run a command, pretending that the current buffer is in Org-mode.
8253 This will temporarily bind local variables that are typically bound in
8254 Org-mode to the values they have in Org-mode, and then interactively
8255 call CMD."
8256 (org-load-modules-maybe)
8257 (unless org-local-vars
8258 (setq org-local-vars (org-get-local-variables)))
8259 (eval (list 'let org-local-vars
8260 (list 'call-interactively (list 'quote cmd)))))
8262 ;;;; Archiving
8264 (defun org-get-category (&optional pos force-refresh)
8265 "Get the category applying to position POS."
8266 (if force-refresh (org-refresh-category-properties))
8267 (let ((pos (or pos (point))))
8268 (or (get-text-property pos 'org-category)
8269 (progn (org-refresh-category-properties)
8270 (get-text-property pos 'org-category)))))
8272 (defun org-refresh-category-properties ()
8273 "Refresh category text properties in the buffer."
8274 (let ((def-cat (cond
8275 ((null org-category)
8276 (if buffer-file-name
8277 (file-name-sans-extension
8278 (file-name-nondirectory buffer-file-name))
8279 "???"))
8280 ((symbolp org-category) (symbol-name org-category))
8281 (t org-category)))
8282 beg end cat pos optionp)
8283 (org-unmodified
8284 (save-excursion
8285 (save-restriction
8286 (widen)
8287 (goto-char (point-min))
8288 (put-text-property (point) (point-max) 'org-category def-cat)
8289 (while (re-search-forward
8290 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8291 (setq pos (match-end 0)
8292 optionp (equal (char-after (match-beginning 0)) ?#)
8293 cat (org-trim (match-string 2)))
8294 (if optionp
8295 (setq beg (point-at-bol) end (point-max))
8296 (org-back-to-heading t)
8297 (setq beg (point) end (org-end-of-subtree t t)))
8298 (put-text-property beg end 'org-category cat)
8299 (goto-char pos)))))))
8302 ;;;; Link Stuff
8304 ;;; Link abbreviations
8306 (defun org-link-expand-abbrev (link)
8307 "Apply replacements as defined in `org-link-abbrev-alist."
8308 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8309 (let* ((key (match-string 1 link))
8310 (as (or (assoc key org-link-abbrev-alist-local)
8311 (assoc key org-link-abbrev-alist)))
8312 (tag (and (match-end 2) (match-string 3 link)))
8313 rpl)
8314 (if (not as)
8315 link
8316 (setq rpl (cdr as))
8317 (cond
8318 ((symbolp rpl) (funcall rpl tag))
8319 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8320 ((string-match "%h" rpl)
8321 (replace-match (url-hexify-string (or tag "")) t t rpl))
8322 (t (concat rpl tag)))))
8323 link))
8325 ;;; Storing and inserting links
8327 (defvar org-insert-link-history nil
8328 "Minibuffer history for links inserted with `org-insert-link'.")
8330 (defvar org-stored-links nil
8331 "Contains the links stored with `org-store-link'.")
8333 (defvar org-store-link-plist nil
8334 "Plist with info about the most recently link created with `org-store-link'.")
8336 (defvar org-link-protocols nil
8337 "Link protocols added to Org-mode using `org-add-link-type'.")
8339 (defvar org-store-link-functions nil
8340 "List of functions that are called to create and store a link.
8341 Each function will be called in turn until one returns a non-nil
8342 value. Each function should check if it is responsible for creating
8343 this link (for example by looking at the major mode).
8344 If not, it must exit and return nil.
8345 If yes, it should return a non-nil value after a calling
8346 `org-store-link-props' with a list of properties and values.
8347 Special properties are:
8349 :type The link prefix, like \"http\". This must be given.
8350 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8351 This is obligatory as well.
8352 :description Optional default description for the second pair
8353 of brackets in an Org-mode link. The user can still change
8354 this when inserting this link into an Org-mode buffer.
8356 In addition to these, any additional properties can be specified
8357 and then used in remember templates.")
8359 (defun org-add-link-type (type &optional follow export)
8360 "Add TYPE to the list of `org-link-types'.
8361 Re-compute all regular expressions depending on `org-link-types'
8363 FOLLOW and EXPORT are two functions.
8365 FOLLOW should take the link path as the single argument and do whatever
8366 is necessary to follow the link, for example find a file or display
8367 a mail message.
8369 EXPORT should format the link path for export to one of the export formats.
8370 It should be a function accepting three arguments:
8372 path the path of the link, the text after the prefix (like \"http:\")
8373 desc the description of the link, if any, or a description added by
8374 org-export-normalize-links if there is none
8375 format the export format, a symbol like `html' or `latex' or `ascii'..
8377 The function may use the FORMAT information to return different values
8378 depending on the format. The return value will be put literally into
8379 the exported file. If the return value is nil, this means Org should
8380 do what it normally does with links which do not have EXPORT defined.
8382 Org-mode has a built-in default for exporting links. If you are happy with
8383 this default, there is no need to define an export function for the link
8384 type. For a simple example of an export function, see `org-bbdb.el'."
8385 (add-to-list 'org-link-types type t)
8386 (org-make-link-regexps)
8387 (if (assoc type org-link-protocols)
8388 (setcdr (assoc type org-link-protocols) (list follow export))
8389 (push (list type follow export) org-link-protocols)))
8391 (defvar org-agenda-buffer-name)
8393 ;;;###autoload
8394 (defun org-store-link (arg)
8395 "\\<org-mode-map>Store an org-link to the current location.
8396 This link is added to `org-stored-links' and can later be inserted
8397 into an org-buffer with \\[org-insert-link].
8399 For some link types, a prefix arg is interpreted:
8400 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8401 For file links, arg negates `org-context-in-file-links'."
8402 (interactive "P")
8403 (org-load-modules-maybe)
8404 (setq org-store-link-plist nil) ; reset
8405 (org-with-limited-levels
8406 (let (link cpltxt desc description search txt custom-id agenda-link)
8407 (cond
8409 ((run-hook-with-args-until-success 'org-store-link-functions)
8410 (setq link (plist-get org-store-link-plist :link)
8411 desc (or (plist-get org-store-link-plist :description) link)))
8413 ((equal (buffer-name) "*Org Edit Src Example*")
8414 (let (label gc)
8415 (while (or (not label)
8416 (save-excursion
8417 (save-restriction
8418 (widen)
8419 (goto-char (point-min))
8420 (re-search-forward
8421 (regexp-quote (format org-coderef-label-format label))
8422 nil t))))
8423 (when label (message "Label exists already") (sit-for 2))
8424 (setq label (read-string "Code line label: " label)))
8425 (end-of-line 1)
8426 (setq link (format org-coderef-label-format label))
8427 (setq gc (- 79 (length link)))
8428 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8429 (insert link)
8430 (setq link (concat "(" label ")") desc nil)))
8432 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8433 ;; We are in the agenda, link to referenced location
8434 (let ((m (or (get-text-property (point) 'org-hd-marker)
8435 (get-text-property (point) 'org-marker))))
8436 (when m
8437 (org-with-point-at m
8438 (setq agenda-link
8439 (if (interactive-p)
8440 (call-interactively 'org-store-link)
8441 (org-store-link nil)))))))
8443 ((eq major-mode 'calendar-mode)
8444 (let ((cd (calendar-cursor-to-date)))
8445 (setq link
8446 (format-time-string
8447 (car org-time-stamp-formats)
8448 (apply 'encode-time
8449 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8450 nil nil nil))))
8451 (org-store-link-props :type "calendar" :date cd)))
8453 ((eq major-mode 'w3-mode)
8454 (setq cpltxt (if (and (buffer-name)
8455 (not (string-match "Untitled" (buffer-name))))
8456 (buffer-name)
8457 (url-view-url t))
8458 link (org-make-link (url-view-url t)))
8459 (org-store-link-props :type "w3" :url (url-view-url t)))
8461 ((eq major-mode 'w3m-mode)
8462 (setq cpltxt (or w3m-current-title w3m-current-url)
8463 link (org-make-link w3m-current-url))
8464 (org-store-link-props :type "w3m" :url (url-view-url t)))
8466 ((setq search (run-hook-with-args-until-success
8467 'org-create-file-search-functions))
8468 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8469 "::" search))
8470 (setq cpltxt (or description link)))
8472 ((eq major-mode 'image-mode)
8473 (setq cpltxt (concat "file:"
8474 (abbreviate-file-name buffer-file-name))
8475 link (org-make-link cpltxt))
8476 (org-store-link-props :type "image" :file buffer-file-name))
8478 ((eq major-mode 'dired-mode)
8479 ;; link to the file in the current line
8480 (let ((file (dired-get-filename nil t)))
8481 (setq file (if file
8482 (abbreviate-file-name
8483 (expand-file-name (dired-get-filename nil t)))
8484 ;; otherwise, no file so use current directory.
8485 default-directory))
8486 (setq cpltxt (concat "file:" file)
8487 link (org-make-link cpltxt))))
8489 ((and (buffer-file-name (buffer-base-buffer)) (org-mode-p))
8490 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8491 (cond
8492 ((org-in-regexp "<<\\(.*?\\)>>")
8493 (setq cpltxt
8494 (concat "file:"
8495 (abbreviate-file-name
8496 (buffer-file-name (buffer-base-buffer)))
8497 "::" (match-string 1))
8498 link (org-make-link cpltxt)))
8499 ((and (featurep 'org-id)
8500 (or (eq org-link-to-org-use-id t)
8501 (and (eq org-link-to-org-use-id 'create-if-interactive)
8502 (interactive-p))
8503 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
8504 (interactive-p)
8505 (not custom-id))
8506 (and org-link-to-org-use-id
8507 (org-entry-get nil "ID"))))
8508 ;; We can make a link using the ID.
8509 (setq link (condition-case nil
8510 (prog1 (org-id-store-link)
8511 (setq desc (plist-get org-store-link-plist
8512 :description)))
8513 (error
8514 ;; probably before first headline, link to file only
8515 (concat "file:"
8516 (abbreviate-file-name
8517 (buffer-file-name (buffer-base-buffer))))))))
8519 ;; Just link to current headline
8520 (setq cpltxt (concat "file:"
8521 (abbreviate-file-name
8522 (buffer-file-name (buffer-base-buffer)))))
8523 ;; Add a context search string
8524 (when (org-xor org-context-in-file-links arg)
8525 (setq txt (cond
8526 ((org-on-heading-p) nil)
8527 ((org-region-active-p)
8528 (buffer-substring (region-beginning) (region-end)))
8529 (t nil)))
8530 (when (or (null txt) (string-match "\\S-" txt))
8531 (setq cpltxt
8532 (concat cpltxt "::"
8533 (condition-case nil
8534 (org-make-org-heading-search-string txt)
8535 (error "")))
8536 desc (or (nth 4 (ignore-errors
8537 (org-heading-components))) "NONE"))))
8538 (if (string-match "::\\'" cpltxt)
8539 (setq cpltxt (substring cpltxt 0 -2)))
8540 (setq link (org-make-link cpltxt)))))
8542 ((buffer-file-name (buffer-base-buffer))
8543 ;; Just link to this file here.
8544 (setq cpltxt (concat "file:"
8545 (abbreviate-file-name
8546 (buffer-file-name (buffer-base-buffer)))))
8547 ;; Add a context string
8548 (when (org-xor org-context-in-file-links arg)
8549 (setq txt (if (org-region-active-p)
8550 (buffer-substring (region-beginning) (region-end))
8551 (buffer-substring (point-at-bol) (point-at-eol))))
8552 ;; Only use search option if there is some text.
8553 (when (string-match "\\S-" txt)
8554 (setq cpltxt
8555 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8556 desc "NONE")))
8557 (setq link (org-make-link cpltxt)))
8559 ((interactive-p)
8560 (error "Cannot link to a buffer which is not visiting a file"))
8562 (t (setq link nil)))
8564 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8565 (setq link (or link cpltxt)
8566 desc (or desc cpltxt))
8567 (if (equal desc "NONE") (setq desc nil))
8569 (if (and (or (interactive-p) executing-kbd-macro) link)
8570 (progn
8571 (setq org-stored-links
8572 (cons (list link desc) org-stored-links))
8573 (message "Stored: %s" (or desc link))
8574 (when custom-id
8575 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8576 "::#" custom-id))
8577 (setq org-stored-links
8578 (cons (list link desc) org-stored-links))))
8579 (or agenda-link (and link (org-make-link-string link desc)))))))
8581 (defun org-store-link-props (&rest plist)
8582 "Store link properties, extract names and addresses."
8583 (let (x adr)
8584 (when (setq x (plist-get plist :from))
8585 (setq adr (mail-extract-address-components x))
8586 (setq plist (plist-put plist :fromname (car adr)))
8587 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8588 (when (setq x (plist-get plist :to))
8589 (setq adr (mail-extract-address-components x))
8590 (setq plist (plist-put plist :toname (car adr)))
8591 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8592 (let ((from (plist-get plist :from))
8593 (to (plist-get plist :to)))
8594 (when (and from to org-from-is-user-regexp)
8595 (setq plist
8596 (plist-put plist :fromto
8597 (if (string-match org-from-is-user-regexp from)
8598 (concat "to %t")
8599 (concat "from %f"))))))
8600 (setq org-store-link-plist plist))
8602 (defun org-add-link-props (&rest plist)
8603 "Add these properties to the link property list."
8604 (let (key value)
8605 (while plist
8606 (setq key (pop plist) value (pop plist))
8607 (setq org-store-link-plist
8608 (plist-put org-store-link-plist key value)))))
8610 (defun org-email-link-description (&optional fmt)
8611 "Return the description part of an email link.
8612 This takes information from `org-store-link-plist' and formats it
8613 according to FMT (default from `org-email-link-description-format')."
8614 (setq fmt (or fmt org-email-link-description-format))
8615 (let* ((p org-store-link-plist)
8616 (to (plist-get p :toaddress))
8617 (from (plist-get p :fromaddress))
8618 (table
8619 (list
8620 (cons "%c" (plist-get p :fromto))
8621 (cons "%F" (plist-get p :from))
8622 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8623 (cons "%T" (plist-get p :to))
8624 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8625 (cons "%s" (plist-get p :subject))
8626 (cons "%d" (plist-get p :date))
8627 (cons "%m" (plist-get p :message-id)))))
8628 (when (string-match "%c" fmt)
8629 ;; Check if the user wrote this message
8630 (if (and org-from-is-user-regexp from to
8631 (save-match-data (string-match org-from-is-user-regexp from)))
8632 (setq fmt (replace-match "to %t" t t fmt))
8633 (setq fmt (replace-match "from %f" t t fmt))))
8634 (org-replace-escapes fmt table)))
8636 (defun org-make-org-heading-search-string (&optional string heading)
8637 "Make search string for STRING or current headline."
8638 (interactive)
8639 (let ((s (or string (org-get-heading)))
8640 (lines org-context-in-file-links))
8641 (unless (and string (not heading))
8642 ;; We are using a headline, clean up garbage in there.
8643 (if (string-match org-todo-regexp s)
8644 (setq s (replace-match "" t t s)))
8645 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8646 (setq s (replace-match "" t t s)))
8647 (setq s (org-trim s))
8648 (if (string-match (concat "^\\(" org-quote-string "\\|"
8649 org-comment-string "\\)") s)
8650 (setq s (replace-match "" t t s)))
8651 (while (string-match org-ts-regexp s)
8652 (setq s (replace-match "" t t s))))
8653 (or string (setq s (concat "*" s))) ; Add * for headlines
8654 (when (and string (integerp lines) (> lines 0))
8655 (let ((slines (org-split-string s "\n")))
8656 (when (< lines (length slines))
8657 (setq s (mapconcat
8658 'identity
8659 (reverse (nthcdr (- (length slines) lines)
8660 (reverse slines))) "\n")))))
8661 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8663 (defun org-make-link (&rest strings)
8664 "Concatenate STRINGS."
8665 (apply 'concat strings))
8667 (defun org-make-link-string (link &optional description)
8668 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8669 (unless (string-match "\\S-" link)
8670 (error "Empty link"))
8671 (when (and description
8672 (stringp description)
8673 (not (string-match "\\S-" description)))
8674 (setq description nil))
8675 (when (stringp description)
8676 ;; Remove brackets from the description, they are fatal.
8677 (while (string-match "\\[" description)
8678 (setq description (replace-match "{" t t description)))
8679 (while (string-match "\\]" description)
8680 (setq description (replace-match "}" t t description))))
8681 (when (equal (org-link-escape link) description)
8682 ;; No description needed, it is identical
8683 (setq description nil))
8684 (when (and (not description)
8685 (not (equal link (org-link-escape link))))
8686 (setq description (org-extract-attributes link)))
8687 (setq link (if (string-match org-link-types-re link)
8688 (concat (match-string 1 link)
8689 (org-link-escape (substring link (match-end 1))))
8690 (org-link-escape link)))
8691 (concat "[[" link "]"
8692 (if description (concat "[" description "]") "")
8693 "]"))
8695 (defconst org-link-escape-chars
8696 '(?\ ?\[ ?\] ?\; ?\= ?\+)
8697 "List of characters that should be escaped in link.
8698 This is the list that is used for internal purposes.")
8700 (defvar org-url-encoding-use-url-hexify nil)
8702 (defconst org-link-escape-chars-browser
8703 '(?\ )
8704 "List of escapes for characters that are problematic in links.
8705 This is the list that is used before handing over to the browser.")
8707 (defun org-link-escape (text &optional table merge)
8708 "Return percent escaped representation of TEXT.
8709 TEXT is a string with the text to escape.
8710 Optional argument TABLE is a list with characters that should be
8711 escaped. When nil, `org-link-escape-chars' is used.
8712 If optional argument MERGE is set, merge TABLE into
8713 `org-link-escape-chars'."
8714 (if (and org-url-encoding-use-url-hexify (not table))
8715 (url-hexify-string text)
8716 (cond
8717 ((and table merge)
8718 (mapc (lambda (defchr)
8719 (unless (member defchr table)
8720 (setq table (cons defchr table)))) org-link-escape-chars))
8721 ((null table)
8722 (setq table org-link-escape-chars)))
8723 (mapconcat
8724 (lambda (char)
8725 (if (or (member char table)
8726 (< char 32) (= char 37) (> char 126))
8727 (mapconcat (lambda (sequence-element)
8728 (format "%%%.2X" sequence-element))
8729 (or (encode-coding-char char 'utf-8)
8730 (error "Unable to percent escape character: %s"
8731 (char-to-string char))) "")
8732 (char-to-string char))) text "")))
8734 (defun org-link-unescape (str)
8735 "Unhex hexified unicode strings as returned from the JavaScript function
8736 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
8737 (unless (and (null str) (string= "" str))
8738 (let ((pos 0) (case-fold-search t) unhexed)
8739 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
8740 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
8741 (setq str (replace-match unhexed t t str))
8742 (setq pos (+ pos (length unhexed))))))
8743 str)
8745 (defun org-link-unescape-compound (hex)
8746 "Unhexify unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
8747 Note: this function also decodes single byte encodings like
8748 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
8749 (save-match-data
8750 (let* ((bytes (cdr (split-string hex "%")))
8751 (ret "")
8752 (eat 0)
8753 (sum 0))
8754 (while bytes
8755 (let* ((val (string-to-number (pop bytes) 16))
8756 (shift-xor
8757 (if (= 0 eat)
8758 (cond
8759 ((>= val 252) (cons 6 252))
8760 ((>= val 248) (cons 5 248))
8761 ((>= val 240) (cons 4 240))
8762 ((>= val 224) (cons 3 224))
8763 ((>= val 192) (cons 2 192))
8764 (t (cons 0 0)))
8765 (cons 6 128))))
8766 (if (>= val 192) (setq eat (car shift-xor)))
8767 (setq val (logxor val (cdr shift-xor)))
8768 (setq sum (+ (lsh sum (car shift-xor)) val))
8769 (if (> eat 0) (setq eat (- eat 1)))
8770 (cond
8771 ((= 0 eat) ;multi byte
8772 (setq ret (concat ret (org-char-to-string sum)))
8773 (setq sum 0))
8774 ((not bytes) ; single byte(s)
8775 (setq ret (org-link-unescape-single-byte-sequence hex))))
8776 )) ;; end (while bytes
8777 ret )))
8779 (defun org-link-unescape-single-byte-sequence (hex)
8780 "Unhexify hex-encoded single byte character sequences."
8781 (mapconcat (lambda (byte)
8782 (char-to-string (string-to-number byte 16)))
8783 (cdr (split-string hex "%")) ""))
8785 (defun org-xor (a b)
8786 "Exclusive or."
8787 (if a (not b) b))
8789 (defun org-fixup-message-id-for-http (s)
8790 "Replace special characters in a message id, so it can be used in an http query."
8791 (when (string-match "%" s)
8792 (setq s (mapconcat (lambda (c)
8793 (if (eq c ?%)
8794 "%25"
8795 (char-to-string c)))
8796 s "")))
8797 (while (string-match "<" s)
8798 (setq s (replace-match "%3C" t t s)))
8799 (while (string-match ">" s)
8800 (setq s (replace-match "%3E" t t s)))
8801 (while (string-match "@" s)
8802 (setq s (replace-match "%40" t t s)))
8805 ;;;###autoload
8806 (defun org-insert-link-global ()
8807 "Insert a link like Org-mode does.
8808 This command can be called in any mode to insert a link in Org-mode syntax."
8809 (interactive)
8810 (org-load-modules-maybe)
8811 (org-run-like-in-org-mode 'org-insert-link))
8813 (defun org-insert-link (&optional complete-file link-location)
8814 "Insert a link. At the prompt, enter the link.
8816 Completion can be used to insert any of the link protocol prefixes like
8817 http or ftp in use.
8819 The history can be used to select a link previously stored with
8820 `org-store-link'. When the empty string is entered (i.e. if you just
8821 press RET at the prompt), the link defaults to the most recently
8822 stored link. As SPC triggers completion in the minibuffer, you need to
8823 use M-SPC or C-q SPC to force the insertion of a space character.
8825 You will also be prompted for a description, and if one is given, it will
8826 be displayed in the buffer instead of the link.
8828 If there is already a link at point, this command will allow you to edit link
8829 and description parts.
8831 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
8832 be selected using completion. The path to the file will be relative to the
8833 current directory if the file is in the current directory or a subdirectory.
8834 Otherwise, the link will be the absolute path as completed in the minibuffer
8835 \(i.e. normally ~/path/to/file). You can configure this behavior using the
8836 option `org-link-file-path-type'.
8838 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
8839 the current directory or below.
8841 With three \\[universal-argument] prefixes, negate the meaning of
8842 `org-keep-stored-link-after-insertion'.
8844 If `org-make-link-description-function' is non-nil, this function will be
8845 called with the link target, and the result will be the default
8846 link description.
8848 If the LINK-LOCATION parameter is non-nil, this value will be
8849 used as the link location instead of reading one interactively."
8850 (interactive "P")
8851 (let* ((wcf (current-window-configuration))
8852 (region (if (org-region-active-p)
8853 (buffer-substring (region-beginning) (region-end))))
8854 (remove (and region (list (region-beginning) (region-end))))
8855 (desc region)
8856 tmphist ; byte-compile incorrectly complains about this
8857 (link link-location)
8858 entry file all-prefixes)
8859 (cond
8860 (link-location) ; specified by arg, just use it.
8861 ((org-in-regexp org-bracket-link-regexp 1)
8862 ;; We do have a link at point, and we are going to edit it.
8863 (setq remove (list (match-beginning 0) (match-end 0)))
8864 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
8865 (setq link (read-string "Link: "
8866 (org-link-unescape
8867 (org-match-string-no-properties 1)))))
8868 ((or (org-in-regexp org-angle-link-re)
8869 (org-in-regexp org-plain-link-re))
8870 ;; Convert to bracket link
8871 (setq remove (list (match-beginning 0) (match-end 0))
8872 link (read-string "Link: "
8873 (org-remove-angle-brackets (match-string 0)))))
8874 ((member complete-file '((4) (16)))
8875 ;; Completing read for file names.
8876 (setq link (org-file-complete-link complete-file)))
8878 ;; Read link, with completion for stored links.
8879 (with-output-to-temp-buffer "*Org Links*"
8880 (princ "Insert a link.
8881 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
8882 (when org-stored-links
8883 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
8884 (princ (mapconcat
8885 (lambda (x)
8886 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
8887 (reverse org-stored-links) "\n"))))
8888 (let ((cw (selected-window)))
8889 (select-window (get-buffer-window "*Org Links*" 'visible))
8890 (setq truncate-lines t)
8891 (unless (pos-visible-in-window-p (point-max))
8892 (org-fit-window-to-buffer))
8893 (and (window-live-p cw) (select-window cw)))
8894 ;; Fake a link history, containing the stored links.
8895 (setq tmphist (append (mapcar 'car org-stored-links)
8896 org-insert-link-history))
8897 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
8898 (mapcar 'car org-link-abbrev-alist)
8899 org-link-types))
8900 (unwind-protect
8901 (progn
8902 (setq link
8903 (let ((org-completion-use-ido nil)
8904 (org-completion-use-iswitchb nil))
8905 (org-completing-read
8906 "Link: "
8907 (append
8908 (mapcar (lambda (x) (list (concat x ":")))
8909 all-prefixes)
8910 (mapcar 'car org-stored-links))
8911 nil nil nil
8912 'tmphist
8913 (car (car org-stored-links)))))
8914 (if (not (string-match "\\S-" link))
8915 (error "No link selected"))
8916 (if (or (member link all-prefixes)
8917 (and (equal ":" (substring link -1))
8918 (member (substring link 0 -1) all-prefixes)
8919 (setq link (substring link 0 -1))))
8920 (setq link (org-link-try-special-completion link))))
8921 (set-window-configuration wcf)
8922 (kill-buffer "*Org Links*"))
8923 (setq entry (assoc link org-stored-links))
8924 (or entry (push link org-insert-link-history))
8925 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
8926 (not org-keep-stored-link-after-insertion))
8927 (setq org-stored-links (delq (assoc link org-stored-links)
8928 org-stored-links)))
8929 (setq desc (or desc (nth 1 entry)))))
8931 (if (string-match org-plain-link-re link)
8932 ;; URL-like link, normalize the use of angular brackets.
8933 (setq link (org-make-link (org-remove-angle-brackets link))))
8935 ;; Check if we are linking to the current file with a search option
8936 ;; If yes, simplify the link by using only the search option.
8937 (when (and buffer-file-name
8938 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
8939 (let* ((path (match-string 1 link))
8940 (case-fold-search nil)
8941 (search (match-string 2 link)))
8942 (save-match-data
8943 (if (equal (file-truename buffer-file-name) (file-truename path))
8944 ;; We are linking to this same file, with a search option
8945 (setq link search)))))
8947 ;; Check if we can/should use a relative path. If yes, simplify the link
8948 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
8949 (let* ((type (match-string 1 link))
8950 (path (match-string 2 link))
8951 (origpath path)
8952 (case-fold-search nil))
8953 (cond
8954 ((or (eq org-link-file-path-type 'absolute)
8955 (equal complete-file '(16)))
8956 (setq path (abbreviate-file-name (expand-file-name path))))
8957 ((eq org-link-file-path-type 'noabbrev)
8958 (setq path (expand-file-name path)))
8959 ((eq org-link-file-path-type 'relative)
8960 (setq path (file-relative-name path)))
8962 (save-match-data
8963 (if (string-match (concat "^" (regexp-quote
8964 (expand-file-name
8965 (file-name-as-directory
8966 default-directory))))
8967 (expand-file-name path))
8968 ;; We are linking a file with relative path name.
8969 (setq path (substring (expand-file-name path)
8970 (match-end 0)))
8971 (setq path (abbreviate-file-name (expand-file-name path)))))))
8972 (setq link (concat type path))
8973 (if (equal desc origpath)
8974 (setq desc path))))
8976 (if org-make-link-description-function
8977 (setq desc (funcall org-make-link-description-function link desc)))
8979 (setq desc (read-string "Description: " desc))
8980 (unless (string-match "\\S-" desc) (setq desc nil))
8981 (if remove (apply 'delete-region remove))
8982 (insert (org-make-link-string link desc))))
8984 (defun org-link-try-special-completion (type)
8985 "If there is completion support for link type TYPE, offer it."
8986 (let ((fun (intern (concat "org-" type "-complete-link"))))
8987 (if (functionp fun)
8988 (funcall fun)
8989 (read-string "Link (no completion support): " (concat type ":")))))
8991 (defun org-file-complete-link (&optional arg)
8992 "Create a file link using completion."
8993 (let (file link)
8994 (setq file (read-file-name "File: "))
8995 (let ((pwd (file-name-as-directory (expand-file-name ".")))
8996 (pwd1 (file-name-as-directory (abbreviate-file-name
8997 (expand-file-name ".")))))
8998 (cond
8999 ((equal arg '(16))
9000 (setq link (org-make-link
9001 "file:"
9002 (abbreviate-file-name (expand-file-name file)))))
9003 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9004 (setq link (org-make-link "file:" (match-string 1 file))))
9005 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9006 (expand-file-name file))
9007 (setq link (org-make-link
9008 "file:" (match-string 1 (expand-file-name file)))))
9009 (t (setq link (org-make-link "file:" file)))))
9010 link))
9012 (defun org-completing-read (&rest args)
9013 "Completing-read with SPACE being a normal character."
9014 (let ((minibuffer-local-completion-map
9015 (copy-keymap minibuffer-local-completion-map)))
9016 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9017 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9018 (apply 'org-icompleting-read args)))
9020 (defun org-completing-read-no-i (&rest args)
9021 (let (org-completion-use-ido org-completion-use-iswitchb)
9022 (apply 'org-completing-read args)))
9024 (defun org-iswitchb-completing-read (prompt choices &rest args)
9025 "Use iswitch as a completing-read replacement to choose from choices.
9026 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9027 from."
9028 (let* ((iswitchb-use-virtual-buffers nil)
9029 (iswitchb-make-buflist-hook
9030 (lambda ()
9031 (setq iswitchb-temp-buflist choices))))
9032 (iswitchb-read-buffer prompt)))
9034 (defun org-icompleting-read (&rest args)
9035 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9036 (org-without-partial-completion
9037 (if (and org-completion-use-ido
9038 (fboundp 'ido-completing-read)
9039 (boundp 'ido-mode) ido-mode
9040 (listp (second args)))
9041 (let ((ido-enter-matching-directory nil))
9042 (apply 'ido-completing-read (concat (car args))
9043 (if (consp (car (nth 1 args)))
9044 (mapcar 'car (nth 1 args))
9045 (nth 1 args))
9046 (cddr args)))
9047 (if (and org-completion-use-iswitchb
9048 (boundp 'iswitchb-mode) iswitchb-mode
9049 (listp (second args)))
9050 (apply 'org-iswitchb-completing-read (concat (car args))
9051 (if (consp (car (nth 1 args)))
9052 (mapcar 'car (nth 1 args))
9053 (nth 1 args))
9054 (cddr args))
9055 (apply 'completing-read args)))))
9057 (defun org-extract-attributes (s)
9058 "Extract the attributes cookie from a string and set as text property."
9059 (let (a attr (start 0) key value)
9060 (save-match-data
9061 (when (string-match "{{\\([^}]+\\)}}$" s)
9062 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9063 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9064 (setq key (match-string 1 a) value (match-string 2 a)
9065 start (match-end 0)
9066 attr (plist-put attr (intern key) value))))
9067 (org-add-props s nil 'org-attr attr))
9070 (defun org-extract-attributes-from-string (tag)
9071 (let (key value attr)
9072 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9073 (setq key (match-string 1 tag) value (match-string 2 tag)
9074 tag (replace-match "" t t tag)
9075 attr (plist-put attr (intern key) value)))
9076 (cons tag attr)))
9078 (defun org-attributes-to-string (plist)
9079 "Format a property list into an HTML attribute list."
9080 (let ((s "") key value)
9081 (while plist
9082 (setq key (pop plist) value (pop plist))
9083 (and value
9084 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9087 ;;; Opening/following a link
9089 (defvar org-link-search-failed nil)
9091 (defvar org-open-link-functions nil
9092 "Hook for functions finding a plain text link.
9093 These functions must take a single argument, the link content.
9094 They will be called for links that look like [[link text][description]]
9095 when LINK TEXT does not have a protocol like \"http:\" and does not look
9096 like a filename (e.g. \"./blue.png\").
9098 These functions will be called *before* Org attempts to resolve the
9099 link by doing text searches in the current buffer - so if you want a
9100 link \"[[target]]\" to still find \"<<target>>\", your function should
9101 handle this as a special case.
9103 When the function does handle the link, it must return a non-nil value.
9104 If it decides that it is not responsible for this link, it must return
9105 nil to indicate that that Org-mode can continue with other options
9106 like exact and fuzzy text search.")
9108 (defun org-next-link ()
9109 "Move forward to the next link.
9110 If the link is in hidden text, expose it."
9111 (interactive)
9112 (when (and org-link-search-failed (eq this-command last-command))
9113 (goto-char (point-min))
9114 (message "Link search wrapped back to beginning of buffer"))
9115 (setq org-link-search-failed nil)
9116 (let* ((pos (point))
9117 (ct (org-context))
9118 (a (assoc :link ct)))
9119 (if a (goto-char (nth 2 a)))
9120 (if (re-search-forward org-any-link-re nil t)
9121 (progn
9122 (goto-char (match-beginning 0))
9123 (if (outline-invisible-p) (org-show-context)))
9124 (goto-char pos)
9125 (setq org-link-search-failed t)
9126 (error "No further link found"))))
9128 (defun org-previous-link ()
9129 "Move backward to the previous link.
9130 If the link is in hidden text, expose it."
9131 (interactive)
9132 (when (and org-link-search-failed (eq this-command last-command))
9133 (goto-char (point-max))
9134 (message "Link search wrapped back to end of buffer"))
9135 (setq org-link-search-failed nil)
9136 (let* ((pos (point))
9137 (ct (org-context))
9138 (a (assoc :link ct)))
9139 (if a (goto-char (nth 1 a)))
9140 (if (re-search-backward org-any-link-re nil t)
9141 (progn
9142 (goto-char (match-beginning 0))
9143 (if (outline-invisible-p) (org-show-context)))
9144 (goto-char pos)
9145 (setq org-link-search-failed t)
9146 (error "No further link found"))))
9148 (defun org-translate-link (s)
9149 "Translate a link string if a translation function has been defined."
9150 (if (and org-link-translation-function
9151 (fboundp org-link-translation-function)
9152 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9153 (progn
9154 (setq s (funcall org-link-translation-function
9155 (match-string 1) (match-string 2)))
9156 (concat (car s) ":" (cdr s)))
9159 (defun org-translate-link-from-planner (type path)
9160 "Translate a link from Emacs Planner syntax so that Org can follow it.
9161 This is still an experimental function, your mileage may vary."
9162 (cond
9163 ((member type '("http" "https" "news" "ftp"))
9164 ;; standard Internet links are the same.
9165 nil)
9166 ((and (equal type "irc") (string-match "^//" path))
9167 ;; Planner has two / at the beginning of an irc link, we have 1.
9168 ;; We should have zero, actually....
9169 (setq path (substring path 1)))
9170 ((and (equal type "lisp") (string-match "^/" path))
9171 ;; Planner has a slash, we do not.
9172 (setq type "elisp" path (substring path 1)))
9173 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9174 ;; A typical message link. Planner has the id after the final slash,
9175 ;; we separate it with a hash mark
9176 (setq path (concat (match-string 1 path) "#"
9177 (org-remove-angle-brackets (match-string 2 path)))))
9179 (cons type path))
9181 (defun org-find-file-at-mouse (ev)
9182 "Open file link or URL at mouse."
9183 (interactive "e")
9184 (mouse-set-point ev)
9185 (org-open-at-point 'in-emacs))
9187 (defun org-open-at-mouse (ev)
9188 "Open file link or URL at mouse."
9189 (interactive "e")
9190 (mouse-set-point ev)
9191 (if (eq major-mode 'org-agenda-mode)
9192 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9193 (org-open-at-point))
9195 (defvar org-window-config-before-follow-link nil
9196 "The window configuration before following a link.
9197 This is saved in case the need arises to restore it.")
9199 (defvar org-open-link-marker (make-marker)
9200 "Marker pointing to the location where `org-open-at-point; was called.")
9202 ;;;###autoload
9203 (defun org-open-at-point-global ()
9204 "Follow a link like Org-mode does.
9205 This command can be called in any mode to follow a link that has
9206 Org-mode syntax."
9207 (interactive)
9208 (org-run-like-in-org-mode 'org-open-at-point))
9210 ;;;###autoload
9211 (defun org-open-link-from-string (s &optional arg reference-buffer)
9212 "Open a link in the string S, as if it was in Org-mode."
9213 (interactive "sLink: \nP")
9214 (let ((reference-buffer (or reference-buffer (current-buffer))))
9215 (with-temp-buffer
9216 (let ((org-inhibit-startup t))
9217 (org-mode)
9218 (insert s)
9219 (goto-char (point-min))
9220 (when reference-buffer
9221 (setq org-link-abbrev-alist-local
9222 (with-current-buffer reference-buffer
9223 org-link-abbrev-alist-local)))
9224 (org-open-at-point arg reference-buffer)))))
9226 (defvar org-open-at-point-functions nil
9227 "Hook that is run when following a link at point.
9229 Functions in this hook must return t if they identify and follow
9230 a link at point. If they don't find anything interesting at point,
9231 they must return nil.")
9233 (defun org-open-at-point (&optional arg reference-buffer)
9234 "Open link at or after point.
9235 If there is no link at point, this function will search forward up to
9236 the end of the current line.
9237 Normally, files will be opened by an appropriate application. If the
9238 optional prefix argument ARG is non-nil, Emacs will visit the file.
9239 With a double prefix argument, try to open outside of Emacs, in the
9240 application the system uses for this file type."
9241 (interactive "P")
9242 ;; if in a code block, then open the block's results
9243 (unless (call-interactively #'org-babel-open-src-block-result)
9244 (org-load-modules-maybe)
9245 (move-marker org-open-link-marker (point))
9246 (setq org-window-config-before-follow-link (current-window-configuration))
9247 (org-remove-occur-highlights nil nil t)
9248 (cond
9249 ((and (org-on-heading-p)
9250 (not (org-in-regexp
9251 (concat org-plain-link-re "\\|"
9252 org-bracket-link-regexp "\\|"
9253 org-angle-link-re "\\|"
9254 "[ \t]:[^ \t\n]+:[ \t]*$")))
9255 (not (get-text-property (point) 'org-linked-text)))
9256 (or (org-offer-links-in-entry arg)
9257 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9258 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9259 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9260 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9261 (not (org-in-regexp org-bracket-link-regexp)))
9262 (org-footnote-action))
9264 (let (type path link line search (pos (point)))
9265 (catch 'match
9266 (save-excursion
9267 (skip-chars-forward "^]\n\r")
9268 (when (org-in-regexp org-bracket-link-regexp 1)
9269 (setq link (org-extract-attributes
9270 (org-link-unescape (org-match-string-no-properties 1))))
9271 (while (string-match " *\n *" link)
9272 (setq link (replace-match " " t t link)))
9273 (setq link (org-link-expand-abbrev link))
9274 (cond
9275 ((or (file-name-absolute-p link)
9276 (string-match "^\\.\\.?/" link))
9277 (setq type "file" path link))
9278 ((string-match org-link-re-with-space3 link)
9279 (setq type (match-string 1 link) path (match-string 2 link)))
9280 (t (setq type "thisfile" path link)))
9281 (throw 'match t)))
9283 (when (get-text-property (point) 'org-linked-text)
9284 (setq type "thisfile"
9285 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9286 (1+ (point)) (point))
9287 path (buffer-substring
9288 (or (previous-single-property-change pos 'org-linked-text)
9289 (point-min))
9290 (or (next-single-property-change pos 'org-linked-text)
9291 (point-max))))
9292 (throw 'match t))
9294 (save-excursion
9295 (when (or (org-in-regexp org-angle-link-re)
9296 (org-in-regexp org-plain-link-re))
9297 (setq type (match-string 1) path (match-string 2))
9298 (throw 'match t)))
9299 (save-excursion
9300 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9301 (setq type "tags"
9302 path (match-string 1))
9303 (while (string-match ":" path)
9304 (setq path (replace-match "+" t t path)))
9305 (throw 'match t)))
9306 (when (org-in-regexp "<\\([^><\n]+\\)>")
9307 (setq type "tree-match"
9308 path (match-string 1))
9309 (throw 'match t)))
9310 (unless path
9311 (error "No link found"))
9313 ;; switch back to reference buffer
9314 ;; needed when if called in a temporary buffer through
9315 ;; org-open-link-from-string
9316 (with-current-buffer (or reference-buffer (current-buffer))
9318 ;; Remove any trailing spaces in path
9319 (if (string-match " +\\'" path)
9320 (setq path (replace-match "" t t path)))
9321 (if (and org-link-translation-function
9322 (fboundp org-link-translation-function))
9323 ;; Check if we need to translate the link
9324 (let ((tmp (funcall org-link-translation-function type path)))
9325 (setq type (car tmp) path (cdr tmp))))
9327 (cond
9329 ((assoc type org-link-protocols)
9330 (funcall (nth 1 (assoc type org-link-protocols)) path))
9332 ((equal type "mailto")
9333 (let ((cmd (car org-link-mailto-program))
9334 (args (cdr org-link-mailto-program)) args1
9335 (address path) (subject "") a)
9336 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9337 (setq address (match-string 1 path)
9338 subject (org-link-escape (match-string 2 path))))
9339 (while args
9340 (cond
9341 ((not (stringp (car args))) (push (pop args) args1))
9342 (t (setq a (pop args))
9343 (if (string-match "%a" a)
9344 (setq a (replace-match address t t a)))
9345 (if (string-match "%s" a)
9346 (setq a (replace-match subject t t a)))
9347 (push a args1))))
9348 (apply cmd (nreverse args1))))
9350 ((member type '("http" "https" "ftp" "news"))
9351 (browse-url (concat type ":" (org-link-escape
9352 path org-link-escape-chars-browser))))
9354 ((string= type "doi")
9355 (browse-url (concat "http://dx.doi.org/"
9356 (org-link-escape
9357 path org-link-escape-chars-browser))))
9359 ((member type '("message"))
9360 (browse-url (concat type ":" path)))
9362 ((string= type "tags")
9363 (org-tags-view arg path))
9365 ((string= type "tree-match")
9366 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9368 ((string= type "file")
9369 (if (string-match "::\\([0-9]+\\)\\'" path)
9370 (setq line (string-to-number (match-string 1 path))
9371 path (substring path 0 (match-beginning 0)))
9372 (if (string-match "::\\(.+\\)\\'" path)
9373 (setq search (match-string 1 path)
9374 path (substring path 0 (match-beginning 0)))))
9375 (if (string-match "[*?{]" (file-name-nondirectory path))
9376 (dired path)
9377 (org-open-file path arg line search)))
9379 ((string= type "shell")
9380 (let ((cmd path))
9381 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9382 (string-match org-confirm-shell-link-not-regexp cmd))
9383 (not org-confirm-shell-link-function)
9384 (funcall org-confirm-shell-link-function
9385 (format "Execute \"%s\" in shell? "
9386 (org-add-props cmd nil
9387 'face 'org-warning))))
9388 (progn
9389 (message "Executing %s" cmd)
9390 (shell-command cmd))
9391 (error "Abort"))))
9393 ((string= type "elisp")
9394 (let ((cmd path))
9395 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9396 (string-match org-confirm-elisp-link-not-regexp cmd))
9397 (not org-confirm-elisp-link-function)
9398 (funcall org-confirm-elisp-link-function
9399 (format "Execute \"%s\" as elisp? "
9400 (org-add-props cmd nil
9401 'face 'org-warning))))
9402 (message "%s => %s" cmd
9403 (if (equal (string-to-char cmd) ?\()
9404 (eval (read cmd))
9405 (call-interactively (read cmd))))
9406 (error "Abort"))))
9408 ((and (string= type "thisfile")
9409 (run-hook-with-args-until-success
9410 'org-open-link-functions path)))
9412 ((string= type "thisfile")
9413 (if arg
9414 (switch-to-buffer-other-window
9415 (org-get-buffer-for-internal-link (current-buffer)))
9416 (org-mark-ring-push))
9417 (let ((cmd `(org-link-search
9418 ,path
9419 ,(cond ((equal arg '(4)) ''occur)
9420 ((equal arg '(16)) ''org-occur)
9421 (t nil))
9422 ,pos)))
9423 (condition-case nil (eval cmd)
9424 (error (progn (widen) (eval cmd))))))
9427 (browse-url-at-point)))))))
9428 (move-marker org-open-link-marker nil)
9429 (run-hook-with-args 'org-follow-link-hook)))
9431 (defun org-offer-links-in-entry (&optional nth zero)
9432 "Offer links in the current entry and follow the selected link.
9433 If there is only one link, follow it immediately as well.
9434 If NTH is an integer, immediately pick the NTH link found.
9435 If ZERO is a string, check also this string for a link, and if
9436 there is one, offer it as link number zero."
9437 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9438 "\\(" org-angle-link-re "\\)\\|"
9439 "\\(" org-plain-link-re "\\)"))
9440 (cnt ?0)
9441 (in-emacs (if (integerp nth) nil nth))
9442 have-zero end links link c)
9443 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9444 (push (match-string 0 zero) links)
9445 (setq cnt (1- cnt) have-zero t))
9446 (save-excursion
9447 (org-back-to-heading t)
9448 (setq end (save-excursion (outline-next-heading) (point)))
9449 (while (re-search-forward re end t)
9450 (push (match-string 0) links))
9451 (setq links (org-uniquify (reverse links))))
9453 (cond
9454 ((null links)
9455 (message "No links"))
9456 ((equal (length links) 1)
9457 (setq link (list (car links))))
9458 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9459 (setq link (nth (if have-zero nth (1- nth)) links)))
9460 (t ; we have to select a link
9461 (save-excursion
9462 (save-window-excursion
9463 (delete-other-windows)
9464 (with-output-to-temp-buffer "*Select Link*"
9465 (mapc (lambda (l)
9466 (if (not (string-match org-bracket-link-regexp l))
9467 (princ (format "[%c] %s\n" (incf cnt)
9468 (org-remove-angle-brackets l)))
9469 (if (match-end 3)
9470 (princ (format "[%c] %s (%s)\n" (incf cnt)
9471 (match-string 3 l) (match-string 1 l)))
9472 (princ (format "[%c] %s\n" (incf cnt)
9473 (match-string 1 l))))))
9474 links))
9475 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9476 (message "Select link to open, RET to open all:")
9477 (setq c (read-char-exclusive))
9478 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9479 (when (equal c ?q) (error "Abort"))
9480 (if (equal c ?\C-m)
9481 (setq link links)
9482 (setq nth (- c ?0))
9483 (if have-zero (setq nth (1+ nth)))
9484 (unless (and (integerp nth) (>= (length links) nth))
9485 (error "Invalid link selection"))
9486 (setq link (list (nth (1- nth) links))))))
9487 (if link
9488 (let ((buf (current-buffer)))
9489 (dolist (l link)
9490 (org-open-link-from-string l in-emacs buf))
9492 nil)))
9494 ;; Add special file links that specify the way of opening
9496 (org-add-link-type "file+sys" 'org-open-file-with-system)
9497 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9498 (defun org-open-file-with-system (path)
9499 "Open file at PATH using the system way of opening it."
9500 (org-open-file path 'system))
9501 (defun org-open-file-with-emacs (path)
9502 "Open file at PATH in Emacs."
9503 (org-open-file path 'emacs))
9504 (defun org-remove-file-link-modifiers ()
9505 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9506 (goto-char (point-min))
9507 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9508 (org-if-unprotected
9509 (replace-match "file:" t t))))
9510 (eval-after-load "org-exp"
9511 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9512 'org-remove-file-link-modifiers))
9514 ;;;; Time estimates
9516 (defun org-get-effort (&optional pom)
9517 "Get the effort estimate for the current entry."
9518 (org-entry-get pom org-effort-property))
9520 ;;; File search
9522 (defvar org-create-file-search-functions nil
9523 "List of functions to construct the right search string for a file link.
9524 These functions are called in turn with point at the location to
9525 which the link should point.
9527 A function in the hook should first test if it would like to
9528 handle this file type, for example by checking the `major-mode'
9529 or the file extension. If it decides not to handle this file, it
9530 should just return nil to give other functions a chance. If it
9531 does handle the file, it must return the search string to be used
9532 when following the link. The search string will be part of the
9533 file link, given after a double colon, and `org-open-at-point'
9534 will automatically search for it. If special measures must be
9535 taken to make the search successful, another function should be
9536 added to the companion hook `org-execute-file-search-functions',
9537 which see.
9539 A function in this hook may also use `setq' to set the variable
9540 `description' to provide a suggestion for the descriptive text to
9541 be used for this link when it gets inserted into an Org-mode
9542 buffer with \\[org-insert-link].")
9544 (defvar org-execute-file-search-functions nil
9545 "List of functions to execute a file search triggered by a link.
9547 Functions added to this hook must accept a single argument, the
9548 search string that was part of the file link, the part after the
9549 double colon. The function must first check if it would like to
9550 handle this search, for example by checking the `major-mode' or
9551 the file extension. If it decides not to handle this search, it
9552 should just return nil to give other functions a chance. If it
9553 does handle the search, it must return a non-nil value to keep
9554 other functions from trying.
9556 Each function can access the current prefix argument through the
9557 variable `current-prefix-argument'. Note that a single prefix is
9558 used to force opening a link in Emacs, so it may be good to only
9559 use a numeric or double prefix to guide the search function.
9561 In case this is needed, a function in this hook can also restore
9562 the window configuration before `org-open-at-point' was called using:
9564 (set-window-configuration org-window-config-before-follow-link)")
9566 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9567 (defun org-link-search (s &optional type avoid-pos)
9568 "Search for a link search option.
9569 If S is surrounded by forward slashes, it is interpreted as a
9570 regular expression. In org-mode files, this will create an `org-occur'
9571 sparse tree. In ordinary files, `occur' will be used to list matches.
9572 If the current buffer is in `dired-mode', grep will be used to search
9573 in all files. If AVOID-POS is given, ignore matches near that position."
9574 (let ((case-fold-search t)
9575 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9576 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9577 (append '(("") (" ") ("\t") ("\n"))
9578 org-emphasis-alist)
9579 "\\|") "\\)"))
9580 (pos (point))
9581 (pre nil) (post nil)
9582 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9583 (cond
9584 ;; First check if there are any special search functions
9585 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9586 ;; Now try the builtin stuff
9587 ((and (equal (string-to-char s0) ?#)
9588 (> (length s0) 1)
9589 (save-excursion
9590 (goto-char (point-min))
9591 (and
9592 (re-search-forward
9593 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9594 (setq type 'dedicated
9595 pos (match-beginning 0))))
9596 ;; There is an exact target for this
9597 (goto-char pos)
9598 (org-back-to-heading t)))
9599 ((save-excursion
9600 (goto-char (point-min))
9601 (and
9602 (re-search-forward
9603 (concat "<<" (regexp-quote s0) ">>") nil t)
9604 (setq type 'dedicated
9605 pos (match-beginning 0))))
9606 ;; There is an exact target for this
9607 (goto-char pos))
9608 ((and (string-match "^(\\(.*\\))$" s0)
9609 (save-excursion
9610 (goto-char (point-min))
9611 (and
9612 (re-search-forward
9613 (concat "[^[]" (regexp-quote
9614 (format org-coderef-label-format
9615 (match-string 1 s0))))
9616 nil t)
9617 (setq type 'dedicated
9618 pos (1+ (match-beginning 0))))))
9619 ;; There is a coderef target for this
9620 (goto-char pos))
9621 ((string-match "^/\\(.*\\)/$" s)
9622 ;; A regular expression
9623 (cond
9624 ((org-mode-p)
9625 (org-occur (match-string 1 s)))
9626 ;;((eq major-mode 'dired-mode)
9627 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9628 (t (org-do-occur (match-string 1 s)))))
9629 ((and (org-mode-p) org-link-search-must-match-exact-headline)
9630 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
9631 (goto-char (point-min))
9632 (cond
9633 ((let (case-fold-search)
9634 (re-search-forward (format org-complex-heading-regexp-format
9635 (regexp-quote s))
9636 nil t))
9637 ;; OK, found a match
9638 (setq type 'dedicated)
9639 (goto-char (match-beginning 0)))
9640 ((and (not org-link-search-inhibit-query)
9641 (eq org-link-search-must-match-exact-headline 'query-to-create)
9642 (y-or-n-p "No match - create this as a new heading? "))
9643 (goto-char (point-max))
9644 (or (bolp) (newline))
9645 (insert "* " s "\n")
9646 (beginning-of-line 0))
9648 (goto-char pos)
9649 (error "No match"))))
9651 ;; A normal search string
9652 (when (equal (string-to-char s) ?*)
9653 ;; Anchor on headlines, post may include tags.
9654 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
9655 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
9656 s (substring s 1)))
9657 (remove-text-properties
9658 0 (length s)
9659 '(face nil mouse-face nil keymap nil fontified nil) s)
9660 ;; Make a series of regular expressions to find a match
9661 (setq words (org-split-string s "[ \n\r\t]+")
9663 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9664 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
9665 "\\)" markers)
9666 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9667 re2a (concat "[ \t\r\n]" re2a_)
9668 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9669 re4 (concat "[^a-zA-Z_]" re4_)
9671 re1 (concat pre re2 post)
9672 re3 (concat pre (if pre re4_ re4) post)
9673 re5 (concat pre ".*" re4)
9674 re2 (concat pre re2)
9675 re2a (concat pre (if pre re2a_ re2a))
9676 re4 (concat pre (if pre re4_ re4))
9677 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9678 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9679 re5 "\\)"
9681 (cond
9682 ((eq type 'org-occur) (org-occur reall))
9683 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9684 (t (goto-char (point-min))
9685 (setq type 'fuzzy)
9686 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
9687 (org-search-not-self 1 re1 nil t)
9688 (org-search-not-self 1 re2 nil t)
9689 (org-search-not-self 1 re2a nil t)
9690 (org-search-not-self 1 re3 nil t)
9691 (org-search-not-self 1 re4 nil t)
9692 (org-search-not-self 1 re5 nil t)
9694 (goto-char (match-beginning 1))
9695 (goto-char pos)
9696 (error "No match"))))))
9697 (and (org-mode-p) (org-show-context 'link-search))
9698 type))
9700 (defun org-search-not-self (group &rest args)
9701 "Execute `re-search-forward', but only accept matches that do not
9702 enclose the position of `org-open-link-marker'."
9703 (let ((m org-open-link-marker))
9704 (catch 'exit
9705 (while (apply 're-search-forward args)
9706 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
9707 (goto-char (match-end group))
9708 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
9709 (> (match-beginning 0) (marker-position m))
9710 (< (match-end 0) (marker-position m)))
9711 (save-match-data
9712 (or (not (org-in-regexp
9713 org-bracket-link-analytic-regexp 1))
9714 (not (match-end 4)) ; no description
9715 (and (<= (match-beginning 4) (point))
9716 (>= (match-end 4) (point))))))
9717 (throw 'exit (point))))))))
9719 (defun org-get-buffer-for-internal-link (buffer)
9720 "Return a buffer to be used for displaying the link target of internal links."
9721 (cond
9722 ((not org-display-internal-link-with-indirect-buffer)
9723 buffer)
9724 ((string-match "(Clone)$" (buffer-name buffer))
9725 (message "Buffer is already a clone, not making another one")
9726 ;; we also do not modify visibility in this case
9727 buffer)
9728 (t ; make a new indirect buffer for displaying the link
9729 (let* ((bn (buffer-name buffer))
9730 (ibn (concat bn "(Clone)"))
9731 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
9732 (with-current-buffer ib (org-overview))
9733 ib))))
9735 (defun org-do-occur (regexp &optional cleanup)
9736 "Call the Emacs command `occur'.
9737 If CLEANUP is non-nil, remove the printout of the regular expression
9738 in the *Occur* buffer. This is useful if the regex is long and not useful
9739 to read."
9740 (occur regexp)
9741 (when cleanup
9742 (let ((cwin (selected-window)) win beg end)
9743 (when (setq win (get-buffer-window "*Occur*"))
9744 (select-window win))
9745 (goto-char (point-min))
9746 (when (re-search-forward "match[a-z]+" nil t)
9747 (setq beg (match-end 0))
9748 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9749 (setq end (1- (match-beginning 0)))))
9750 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
9751 (goto-char (point-min))
9752 (select-window cwin))))
9754 ;;; The mark ring for links jumps
9756 (defvar org-mark-ring nil
9757 "Mark ring for positions before jumps in Org-mode.")
9758 (defvar org-mark-ring-last-goto nil
9759 "Last position in the mark ring used to go back.")
9760 ;; Fill and close the ring
9761 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9762 (loop for i from 1 to org-mark-ring-length do
9763 (push (make-marker) org-mark-ring))
9764 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
9765 org-mark-ring)
9767 (defun org-mark-ring-push (&optional pos buffer)
9768 "Put the current position or POS into the mark ring and rotate it."
9769 (interactive)
9770 (setq pos (or pos (point)))
9771 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
9772 (move-marker (car org-mark-ring)
9773 (or pos (point))
9774 (or buffer (current-buffer)))
9775 (message "%s"
9776 (substitute-command-keys
9777 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
9779 (defun org-mark-ring-goto (&optional n)
9780 "Jump to the previous position in the mark ring.
9781 With prefix arg N, jump back that many stored positions. When
9782 called several times in succession, walk through the entire ring.
9783 Org-mode commands jumping to a different position in the current file,
9784 or to another Org-mode file, automatically push the old position
9785 onto the ring."
9786 (interactive "p")
9787 (let (p m)
9788 (if (eq last-command this-command)
9789 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
9790 (setq p org-mark-ring))
9791 (setq org-mark-ring-last-goto p)
9792 (setq m (car p))
9793 (switch-to-buffer (marker-buffer m))
9794 (goto-char m)
9795 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
9797 (defun org-remove-angle-brackets (s)
9798 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
9799 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
9801 (defun org-add-angle-brackets (s)
9802 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
9803 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
9805 (defun org-remove-double-quotes (s)
9806 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
9807 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
9810 ;;; Following specific links
9812 (defun org-follow-timestamp-link ()
9813 (cond
9814 ((org-at-date-range-p t)
9815 (let ((org-agenda-start-on-weekday)
9816 (t1 (match-string 1))
9817 (t2 (match-string 2)))
9818 (setq t1 (time-to-days (org-time-string-to-time t1))
9819 t2 (time-to-days (org-time-string-to-time t2)))
9820 (org-agenda-list nil t1 (1+ (- t2 t1)))))
9821 ((org-at-timestamp-p t)
9822 (org-agenda-list nil (time-to-days (org-time-string-to-time
9823 (substring (match-string 1) 0 10)))
9825 (t (error "This should not happen"))))
9828 ;;; Following file links
9829 (defvar org-wait nil)
9830 (defun org-open-file (path &optional in-emacs line search)
9831 "Open the file at PATH.
9832 First, this expands any special file name abbreviations. Then the
9833 configuration variable `org-file-apps' is checked if it contains an
9834 entry for this file type, and if yes, the corresponding command is launched.
9836 If no application is found, Emacs simply visits the file.
9838 With optional prefix argument IN-EMACS, Emacs will visit the file.
9839 With a double \\[universal-argument] \\[universal-argument] \
9840 prefix arg, Org tries to avoid opening in Emacs
9841 and to use an external application to visit the file.
9843 Optional LINE specifies a line to go to, optional SEARCH a string
9844 to search for. If LINE or SEARCH is given, the file will be
9845 opened in Emacs, unless an entry from org-file-apps that makes
9846 use of groups in a regexp matches.
9847 If the file does not exist, an error is thrown."
9848 (let* ((file (if (equal path "")
9849 buffer-file-name
9850 (substitute-in-file-name (expand-file-name path))))
9851 (file-apps (append org-file-apps (org-default-apps)))
9852 (apps (org-remove-if
9853 'org-file-apps-entry-match-against-dlink-p file-apps))
9854 (apps-dlink (org-remove-if-not
9855 'org-file-apps-entry-match-against-dlink-p file-apps))
9856 (remp (and (assq 'remote apps) (org-file-remote-p file)))
9857 (dirp (if remp nil (file-directory-p file)))
9858 (file (if (and dirp org-open-directory-means-index-dot-org)
9859 (concat (file-name-as-directory file) "index.org")
9860 file))
9861 (a-m-a-p (assq 'auto-mode apps))
9862 (dfile (downcase file))
9863 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
9864 (link (cond ((and (eq line nil)
9865 (eq search nil))
9866 file)
9867 (line
9868 (concat file "::" (number-to-string line)))
9869 (search
9870 (concat file "::" search))))
9871 (dlink (downcase link))
9872 (old-buffer (current-buffer))
9873 (old-pos (point))
9874 (old-mode major-mode)
9875 ext cmd link-match-data)
9876 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
9877 (setq ext (match-string 1 dfile))
9878 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
9879 (setq ext (match-string 1 dfile))))
9880 (cond
9881 ((member in-emacs '((16) system))
9882 (setq cmd (cdr (assoc 'system apps))))
9883 (in-emacs (setq cmd 'emacs))
9885 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
9886 (and dirp (cdr (assoc 'directory apps)))
9887 ; first, try matching against apps-dlink
9888 ; if we get a match here, store the match data for later
9889 (let ((match (assoc-default dlink apps-dlink
9890 'string-match)))
9891 (if match
9892 (progn (setq link-match-data (match-data))
9893 match)
9894 (progn (setq in-emacs (or in-emacs line search))
9895 nil))) ; if we have no match in apps-dlink,
9896 ; always open the file in emacs if line or search
9897 ; is given (for backwards compatibility)
9898 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
9899 'string-match)
9900 (cdr (assoc ext apps))
9901 (cdr (assoc t apps))))))
9902 (when (eq cmd 'system)
9903 (setq cmd (cdr (assoc 'system apps))))
9904 (when (eq cmd 'default)
9905 (setq cmd (cdr (assoc t apps))))
9906 (when (eq cmd 'mailcap)
9907 (require 'mailcap)
9908 (mailcap-parse-mailcaps)
9909 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
9910 (command (mailcap-mime-info mime-type)))
9911 (if (stringp command)
9912 (setq cmd command)
9913 (setq cmd 'emacs))))
9914 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
9915 (not (file-exists-p file))
9916 (not org-open-non-existing-files))
9917 (error "No such file: %s" file))
9918 (cond
9919 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
9920 ;; Remove quotes around the file name - we'll use shell-quote-argument.
9921 (while (string-match "['\"]%s['\"]" cmd)
9922 (setq cmd (replace-match "%s" t t cmd)))
9923 (while (string-match "%s" cmd)
9924 (setq cmd (replace-match
9925 (save-match-data
9926 (shell-quote-argument
9927 (convert-standard-filename file)))
9928 t t cmd)))
9930 ;; Replace "%1", "%2" etc. in command with group matches from regex
9931 (save-match-data
9932 (let ((match-index 1)
9933 (number-of-groups (- (/ (length link-match-data) 2) 1)))
9934 (set-match-data link-match-data)
9935 (while (<= match-index number-of-groups)
9936 (let ((regex (concat "%" (number-to-string match-index)))
9937 (replace-with (match-string match-index dlink)))
9938 (while (string-match regex cmd)
9939 (setq cmd (replace-match replace-with t t cmd))))
9940 (setq match-index (+ match-index 1)))))
9942 (save-window-excursion
9943 (start-process-shell-command cmd nil cmd)
9944 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
9946 ((or (stringp cmd)
9947 (eq cmd 'emacs))
9948 (funcall (cdr (assq 'file org-link-frame-setup)) file)
9949 (widen)
9950 (if line (org-goto-line line)
9951 (if search (org-link-search search))))
9952 ((consp cmd)
9953 (let ((file (convert-standard-filename file)))
9954 (save-match-data
9955 (set-match-data link-match-data)
9956 (eval cmd))))
9957 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
9958 (and (org-mode-p) (eq old-mode 'org-mode)
9959 (or (not (equal old-buffer (current-buffer)))
9960 (not (equal old-pos (point))))
9961 (org-mark-ring-push old-pos old-buffer))))
9963 (defun org-file-apps-entry-match-against-dlink-p (entry)
9964 "This function returns non-nil if `entry' uses a regular
9965 expression which should be matched against the whole link by
9966 org-open-file.
9968 It assumes that is the case when the entry uses a regular
9969 expression which has at least one grouping construct and the
9970 action is either a lisp form or a command string containing
9971 '%1', i.e. using at least one subexpression match as a
9972 parameter."
9973 (let ((selector (car entry))
9974 (action (cdr entry)))
9975 (if (stringp selector)
9976 (and (> (regexp-opt-depth selector) 0)
9977 (or (and (stringp action)
9978 (string-match "%[0-9]" action))
9979 (consp action)))
9980 nil)))
9982 (defun org-default-apps ()
9983 "Return the default applications for this operating system."
9984 (cond
9985 ((eq system-type 'darwin)
9986 org-file-apps-defaults-macosx)
9987 ((eq system-type 'windows-nt)
9988 org-file-apps-defaults-windowsnt)
9989 (t org-file-apps-defaults-gnu)))
9991 (defun org-apps-regexp-alist (list &optional add-auto-mode)
9992 "Convert extensions to regular expressions in the cars of LIST.
9993 Also, weed out any non-string entries, because the return value is used
9994 only for regexp matching.
9995 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
9996 point to the symbol `emacs', indicating that the file should
9997 be opened in Emacs."
9998 (append
9999 (delq nil
10000 (mapcar (lambda (x)
10001 (if (not (stringp (car x)))
10003 (if (string-match "\\W" (car x))
10005 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10006 list))
10007 (if add-auto-mode
10008 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10010 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10011 (defun org-file-remote-p (file)
10012 "Test whether FILE specifies a location on a remote system.
10013 Return non-nil if the location is indeed remote.
10015 For example, the filename \"/user@host:/foo\" specifies a location
10016 on the system \"/user@host:\"."
10017 (cond ((fboundp 'file-remote-p)
10018 (file-remote-p file))
10019 ((fboundp 'tramp-handle-file-remote-p)
10020 (tramp-handle-file-remote-p file))
10021 ((and (boundp 'ange-ftp-name-format)
10022 (string-match (car ange-ftp-name-format) file))
10024 (t nil)))
10027 ;;;; Refiling
10029 (defun org-get-org-file ()
10030 "Read a filename, with default directory `org-directory'."
10031 (let ((default (or org-default-notes-file remember-data-file)))
10032 (read-file-name (format "File name [%s]: " default)
10033 (file-name-as-directory org-directory)
10034 default)))
10036 (defun org-notes-order-reversed-p ()
10037 "Check if the current file should receive notes in reversed order."
10038 (cond
10039 ((not org-reverse-note-order) nil)
10040 ((eq t org-reverse-note-order) t)
10041 ((not (listp org-reverse-note-order)) nil)
10042 (t (catch 'exit
10043 (let ((all org-reverse-note-order)
10044 entry)
10045 (while (setq entry (pop all))
10046 (if (string-match (car entry) buffer-file-name)
10047 (throw 'exit (cdr entry))))
10048 nil)))))
10050 (defvar org-refile-target-table nil
10051 "The list of refile targets, created by `org-refile'.")
10053 (defvar org-agenda-new-buffers nil
10054 "Buffers created to visit agenda files.")
10056 (defvar org-refile-cache nil
10057 "Cache for refile targets.")
10059 (defvar org-refile-markers nil
10060 "All the markers used for caching refile locations.")
10062 (defun org-refile-marker (pos)
10063 "Get a new refile marker, but only if caching is in use."
10064 (if (not org-refile-use-cache)
10066 (let ((m (make-marker)))
10067 (move-marker m pos)
10068 (push m org-refile-markers)
10069 m)))
10071 (defun org-refile-cache-clear ()
10072 "Clear the refile cache and disable all the markers."
10073 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10074 (setq org-refile-markers nil)
10075 (setq org-refile-cache nil)
10076 (message "Refile cache has been cleared"))
10078 (defun org-refile-cache-check-set (set)
10079 "Check if all the markers in the cache still have live buffers."
10080 (let (marker)
10081 (catch 'exit
10082 (while (and set (setq marker (nth 3 (pop set))))
10083 ;; if org-refile-use-outline-path is 'file, marker may be nil
10084 (when (and marker (null (marker-buffer marker)))
10085 (message "not found") (sit-for 3)
10086 (throw 'exit nil)))
10087 t)))
10089 (defun org-refile-cache-put (set &rest identifiers)
10090 "Push the refile targets SET into the cache, under IDENTIFIERS."
10091 (let* ((key (sha1 (prin1-to-string identifiers)))
10092 (entry (assoc key org-refile-cache)))
10093 (if entry
10094 (setcdr entry set)
10095 (push (cons key set) org-refile-cache))))
10097 (defun org-refile-cache-get (&rest identifiers)
10098 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10099 (cond
10100 ((not org-refile-cache) nil)
10101 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10103 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10104 org-refile-cache))))
10105 (and set (org-refile-cache-check-set set) set)))))
10107 (defun org-refile-get-targets (&optional default-buffer)
10108 "Produce a table with refile targets."
10109 (let ((case-fold-search nil)
10110 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10111 (entries (or org-refile-targets '((nil . (:level . 1)))))
10112 targets tgs txt re files f desc descre fast-path-p level pos0)
10113 (message "Getting targets...")
10114 (with-current-buffer (or default-buffer (current-buffer))
10115 (while (setq entry (pop entries))
10116 (setq files (car entry) desc (cdr entry))
10117 (setq fast-path-p nil)
10118 (cond
10119 ((null files) (setq files (list (current-buffer))))
10120 ((eq files 'org-agenda-files)
10121 (setq files (org-agenda-files 'unrestricted)))
10122 ((and (symbolp files) (fboundp files))
10123 (setq files (funcall files)))
10124 ((and (symbolp files) (boundp files))
10125 (setq files (symbol-value files))))
10126 (if (stringp files) (setq files (list files)))
10127 (cond
10128 ((eq (car desc) :tag)
10129 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10130 ((eq (car desc) :todo)
10131 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10132 ((eq (car desc) :regexp)
10133 (setq descre (cdr desc)))
10134 ((eq (car desc) :level)
10135 (setq descre (concat "^\\*\\{" (number-to-string
10136 (if org-odd-levels-only
10137 (1- (* 2 (cdr desc)))
10138 (cdr desc)))
10139 "\\}[ \t]")))
10140 ((eq (car desc) :maxlevel)
10141 (setq fast-path-p t)
10142 (setq descre (concat "^\\*\\{1," (number-to-string
10143 (if org-odd-levels-only
10144 (1- (* 2 (cdr desc)))
10145 (cdr desc)))
10146 "\\}[ \t]")))
10147 (t (error "Bad refiling target description %s" desc)))
10148 (while (setq f (pop files))
10149 (with-current-buffer
10150 (if (bufferp f) f (org-get-agenda-file-buffer f))
10152 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10153 (progn
10154 (if (bufferp f) (setq f (buffer-file-name
10155 (buffer-base-buffer f))))
10156 (setq f (and f (expand-file-name f)))
10157 (if (eq org-refile-use-outline-path 'file)
10158 (push (list (file-name-nondirectory f) f nil nil) tgs))
10159 (save-excursion
10160 (save-restriction
10161 (widen)
10162 (goto-char (point-min))
10163 (while (re-search-forward descre nil t)
10164 (goto-char (setq pos0 (point-at-bol)))
10165 (catch 'next
10166 (when org-refile-target-verify-function
10167 (save-match-data
10168 (or (funcall org-refile-target-verify-function)
10169 (throw 'next t))))
10170 (when (looking-at org-complex-heading-regexp)
10171 (setq level (org-reduced-level
10172 (- (match-end 1) (match-beginning 1)))
10173 txt (org-link-display-format (match-string 4))
10174 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10175 re (format org-complex-heading-regexp-format
10176 (regexp-quote (match-string 4))))
10177 (when org-refile-use-outline-path
10178 (setq txt (mapconcat
10179 'org-protect-slash
10180 (append
10181 (if (eq org-refile-use-outline-path
10182 'file)
10183 (list (file-name-nondirectory
10184 (buffer-file-name
10185 (buffer-base-buffer))))
10186 (if (eq org-refile-use-outline-path
10187 'full-file-path)
10188 (list (buffer-file-name
10189 (buffer-base-buffer)))))
10190 (org-get-outline-path fast-path-p
10191 level txt)
10192 (list txt))
10193 "/")))
10194 (push (list txt f re (org-refile-marker (point)))
10195 tgs)))
10196 (when (= (point) pos0)
10197 ;; verification function has not moved point
10198 (goto-char (point-at-eol))))))))
10199 (when org-refile-use-cache
10200 (org-refile-cache-put tgs (buffer-file-name) descre))
10201 (setq targets (append tgs targets))
10202 ))))
10203 (message "Getting targets...done")
10204 (nreverse targets)))
10206 (defun org-protect-slash (s)
10207 (while (string-match "/" s)
10208 (setq s (replace-match "\\" t t s)))
10211 (defvar org-olpa (make-vector 20 nil))
10213 (defun org-get-outline-path (&optional fastp level heading)
10214 "Return the outline path to the current entry, as a list.
10216 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10217 routine which makes outline path derivations for an entire file,
10218 avoiding backtracing. Refile target collection makes use of that."
10219 (if fastp
10220 (progn
10221 (if (> level 19)
10222 (error "Outline path failure, more than 19 levels"))
10223 (loop for i from level upto 19 do
10224 (aset org-olpa i nil))
10225 (prog1
10226 (delq nil (append org-olpa nil))
10227 (aset org-olpa level heading)))
10228 (let (rtn case-fold-search)
10229 (save-excursion
10230 (save-restriction
10231 (widen)
10232 (while (org-up-heading-safe)
10233 (when (looking-at org-complex-heading-regexp)
10234 (push (org-match-string-no-properties 4) rtn)))
10235 rtn)))))
10237 (defun org-format-outline-path (path &optional width prefix)
10238 "Format the outline path PATH for display.
10239 Width is the maximum number of characters that is available.
10240 Prefix is a prefix to be included in the returned string,
10241 such as the file name."
10242 (setq width (or width 79))
10243 (if prefix (setq width (- width (length prefix))))
10244 (if (not path)
10245 (or prefix "")
10246 (let* ((nsteps (length path))
10247 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10248 (maxwidth (if (<= total-width width)
10249 10000 ;; everything fits
10250 ;; we need to shorten the level headings
10251 (/ (- width nsteps) nsteps)))
10252 (org-odd-levels-only nil)
10253 (n 0)
10254 (total (1+ (length prefix))))
10255 (setq maxwidth (max maxwidth 10))
10256 (concat prefix
10257 (mapconcat
10258 (lambda (h)
10259 (setq n (1+ n))
10260 (if (and (= n nsteps) (< maxwidth 10000))
10261 (setq maxwidth (- total-width total)))
10262 (if (< (length h) maxwidth)
10263 (progn (setq total (+ total (length h) 1)) h)
10264 (setq h (substring h 0 (- maxwidth 2))
10265 total (+ total maxwidth 1))
10266 (if (string-match "[ \t]+\\'" h)
10267 (setq h (substring h 0 (match-beginning 0))))
10268 (setq h (concat h "..")))
10269 (org-add-props h nil 'face
10270 (nth (% (1- n) org-n-level-faces)
10271 org-level-faces))
10273 path "/")))))
10275 (defun org-display-outline-path (&optional file current)
10276 "Display the current outline path in the echo area."
10277 (interactive "P")
10278 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10279 (case-fold-search nil)
10280 (path (and (org-mode-p) (org-get-outline-path))))
10281 (if current (setq path (append path
10282 (save-excursion
10283 (org-back-to-heading t)
10284 (if (looking-at org-complex-heading-regexp)
10285 (list (match-string 4)))))))
10286 (message "%s"
10287 (org-format-outline-path
10288 path
10289 (1- (frame-width))
10290 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10292 (defvar org-refile-history nil
10293 "History for refiling operations.")
10295 (defvar org-after-refile-insert-hook nil
10296 "Hook run after `org-refile' has inserted its stuff at the new location.
10297 Note that this is still *before* the stuff will be removed from
10298 the *old* location.")
10300 (defvar org-capture-last-stored-marker)
10301 (defun org-refile (&optional goto default-buffer rfloc)
10302 "Move the entry at point to another heading.
10303 The list of target headings is compiled using the information in
10304 `org-refile-targets', which see. This list is created before each use
10305 and will therefore always be up-to-date.
10307 At the target location, the entry is filed as a subitem of the target heading.
10308 Depending on `org-reverse-note-order', the new subitem will either be the
10309 first or the last subitem.
10311 If there is an active region, all entries in that region will be moved.
10312 However, the region must fulfill the requirement that the first heading
10313 is the first one sets the top-level of the moved text - at most siblings
10314 below it are allowed.
10316 With prefix arg GOTO, the command will only visit the target location,
10317 not actually move anything.
10318 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10319 go to the location where the last refiling
10320 operation has put the subtree.
10321 With a prefix argument of `2', refile to the running clock.
10323 RFLOC can be a refile location obtained in a different way.
10325 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10327 If you are using target caching (see `org-refile-use-cache'),
10328 You have to clear the target cache in order to find new targets.
10329 This can be done with a 0 prefix: `C-0 C-c C-w'"
10330 (interactive "P")
10331 (if (member goto '(0 (64)))
10332 (org-refile-cache-clear)
10333 (let* ((cbuf (current-buffer))
10334 (regionp (org-region-active-p))
10335 (region-start (and regionp (region-beginning)))
10336 (region-end (and regionp (region-end)))
10337 (region-length (and regionp (- region-end region-start)))
10338 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10339 pos it nbuf file re level reversed)
10340 (setq last-command nil)
10341 (when regionp
10342 (goto-char region-start)
10343 (or (bolp) (goto-char (point-at-bol)))
10344 (setq region-start (point))
10345 (unless (org-kill-is-subtree-p
10346 (buffer-substring region-start region-end))
10347 (error "The region is not a (sequence of) subtree(s)")))
10348 (if (equal goto '(16))
10349 (org-refile-goto-last-stored)
10350 (when (or
10351 (and (equal goto 2)
10352 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10353 (prog1
10354 (setq it (list (or org-clock-heading "running clock")
10355 (buffer-file-name
10356 (marker-buffer org-clock-hd-marker))
10358 (marker-position org-clock-hd-marker)))
10359 (setq goto nil)))
10360 (setq it (or rfloc
10361 (save-excursion
10362 (org-refile-get-location
10363 (if goto "Goto" "Refile to") default-buffer
10364 org-refile-allow-creating-parent-nodes)))))
10365 (setq file (nth 1 it)
10366 re (nth 2 it)
10367 pos (nth 3 it))
10368 (if (and (not goto)
10370 (equal (buffer-file-name) file)
10371 (if regionp
10372 (and (>= pos region-start)
10373 (<= pos region-end))
10374 (and (>= pos (point))
10375 (< pos (save-excursion
10376 (org-end-of-subtree t t))))))
10377 (error "Cannot refile to position inside the tree or region"))
10379 (setq nbuf (or (find-buffer-visiting file)
10380 (find-file-noselect file)))
10381 (if goto
10382 (progn
10383 (switch-to-buffer nbuf)
10384 (goto-char pos)
10385 (org-show-context 'org-goto))
10386 (if regionp
10387 (progn
10388 (org-kill-new (buffer-substring region-start region-end))
10389 (org-save-markers-in-region region-start region-end))
10390 (org-copy-subtree 1 nil t))
10391 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10392 (find-file-noselect file)))
10393 (setq reversed (org-notes-order-reversed-p))
10394 (save-excursion
10395 (save-restriction
10396 (widen)
10397 (if pos
10398 (progn
10399 (goto-char pos)
10400 (looking-at outline-regexp)
10401 (setq level (org-get-valid-level (funcall outline-level) 1))
10402 (goto-char
10403 (if reversed
10404 (or (outline-next-heading) (point-max))
10405 (or (save-excursion (org-get-next-sibling))
10406 (org-end-of-subtree t t)
10407 (point-max)))))
10408 (setq level 1)
10409 (if (not reversed)
10410 (goto-char (point-max))
10411 (goto-char (point-min))
10412 (or (outline-next-heading) (goto-char (point-max)))))
10413 (if (not (bolp)) (newline))
10414 (org-paste-subtree level)
10415 (when org-log-refile
10416 (org-add-log-setup 'refile nil nil 'findpos
10417 org-log-refile)
10418 (unless (eq org-log-refile 'note)
10419 (save-excursion (org-add-log-note))))
10420 (and org-auto-align-tags (org-set-tags nil t))
10421 (bookmark-set "org-refile-last-stored")
10422 ;; If we are refiling for capture, make sure that the
10423 ;; last-capture pointers point here
10424 (when (org-bound-and-true-p org-refile-for-capture)
10425 (bookmark-set "org-capture-last-stored-marker")
10426 (move-marker org-capture-last-stored-marker (point)))
10427 (if (fboundp 'deactivate-mark) (deactivate-mark))
10428 (run-hooks 'org-after-refile-insert-hook))))
10429 (if regionp
10430 (delete-region (point) (+ (point) region-length))
10431 (org-cut-subtree))
10432 (when (featurep 'org-inlinetask)
10433 (org-inlinetask-remove-END-maybe))
10434 (setq org-markers-to-move nil)
10435 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10437 (defun org-refile-goto-last-stored ()
10438 "Go to the location where the last refile was stored."
10439 (interactive)
10440 (bookmark-jump "org-refile-last-stored")
10441 (message "This is the location of the last refile"))
10443 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
10444 "Prompt the user for a refile location, using PROMPT.
10445 PROMPT should not be suffixed with a colon and a space, because
10446 this function appends the default value from
10447 `org-refile-history' automatically, if that is not empty."
10448 (let ((org-refile-targets org-refile-targets)
10449 (org-refile-use-outline-path org-refile-use-outline-path))
10450 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
10451 (unless org-refile-target-table
10452 (error "No refile targets"))
10453 (let* ((prompt (concat prompt
10454 (and (car org-refile-history)
10455 (concat " (default " (car org-refile-history) ")"))
10456 ": "))
10457 (cbuf (current-buffer))
10458 (partial-completion-mode nil)
10459 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10460 (cfunc (if (and org-refile-use-outline-path
10461 org-outline-path-complete-in-steps)
10462 'org-olpath-completing-read
10463 'org-icompleting-read))
10464 (extra (if org-refile-use-outline-path "/" ""))
10465 (filename (and cfn (expand-file-name cfn)))
10466 (tbl (mapcar
10467 (lambda (x)
10468 (if (and (not (member org-refile-use-outline-path
10469 '(file full-file-path)))
10470 (not (equal filename (nth 1 x))))
10471 (cons (concat (car x) extra " ("
10472 (file-name-nondirectory (nth 1 x)) ")")
10473 (cdr x))
10474 (cons (concat (car x) extra) (cdr x))))
10475 org-refile-target-table))
10476 (completion-ignore-case t)
10477 pa answ parent-target child parent old-hist)
10478 (setq old-hist org-refile-history)
10479 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10480 nil 'org-refile-history (car org-refile-history)))
10481 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10482 (org-refile-check-position pa)
10483 (if pa
10484 (progn
10485 (when (or (not org-refile-history)
10486 (not (eq old-hist org-refile-history))
10487 (not (equal (car pa) (car org-refile-history))))
10488 (setq org-refile-history
10489 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10490 org-refile-history
10491 (cdr org-refile-history))))
10492 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10493 (pop org-refile-history)))
10495 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10496 (progn
10497 (setq parent (match-string 1 answ)
10498 child (match-string 2 answ))
10499 (setq parent-target (or (assoc parent tbl)
10500 (assoc (concat parent "/") tbl)))
10501 (when (and parent-target
10502 (or (eq new-nodes t)
10503 (and (eq new-nodes 'confirm)
10504 (y-or-n-p (format "Create new node \"%s\"? "
10505 child)))))
10506 (org-refile-new-child parent-target child)))
10507 (error "Invalid target location")))))
10509 (defun org-refile-check-position (refile-pointer)
10510 "Check if the refile pointer matches the readline to which it points."
10511 (let* ((file (nth 1 refile-pointer))
10512 (re (nth 2 refile-pointer))
10513 (pos (nth 3 refile-pointer))
10514 buffer)
10515 (when (org-string-nw-p re)
10516 (setq buffer (if (markerp pos)
10517 (marker-buffer pos)
10518 (or (find-buffer-visiting file)
10519 (find-file-noselect file))))
10520 (with-current-buffer buffer
10521 (save-excursion
10522 (save-restriction
10523 (widen)
10524 (goto-char pos)
10525 (beginning-of-line 1)
10526 (unless (org-looking-at-p re)
10527 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
10529 (defun org-refile-new-child (parent-target child)
10530 "Use refile target PARENT-TARGET to add new CHILD below it."
10531 (unless parent-target
10532 (error "Cannot find parent for new node"))
10533 (let ((file (nth 1 parent-target))
10534 (pos (nth 3 parent-target))
10535 level)
10536 (with-current-buffer (or (find-buffer-visiting file)
10537 (find-file-noselect file))
10538 (save-excursion
10539 (save-restriction
10540 (widen)
10541 (if pos
10542 (goto-char pos)
10543 (goto-char (point-max))
10544 (if (not (bolp)) (newline)))
10545 (when (looking-at outline-regexp)
10546 (setq level (funcall outline-level))
10547 (org-end-of-subtree t t))
10548 (org-back-over-empty-lines)
10549 (insert "\n" (make-string
10550 (if pos (org-get-valid-level level 1) 1) ?*)
10551 " " child "\n")
10552 (beginning-of-line 0)
10553 (list (concat (car parent-target) "/" child) file "" (point)))))))
10555 (defun org-olpath-completing-read (prompt collection &rest args)
10556 "Read an outline path like a file name."
10557 (let ((thetable collection)
10558 (org-completion-use-ido nil) ; does not work with ido.
10559 (org-completion-use-iswitchb nil)) ; or iswitchb
10560 (apply
10561 'org-icompleting-read prompt
10562 (lambda (string predicate &optional flag)
10563 (let (rtn r f (l (length string)))
10564 (cond
10565 ((eq flag nil)
10566 ;; try completion
10567 (try-completion string thetable))
10568 ((eq flag t)
10569 ;; all-completions
10570 (setq rtn (all-completions string thetable predicate))
10571 (mapcar
10572 (lambda (x)
10573 (setq r (substring x l))
10574 (if (string-match " ([^)]*)$" x)
10575 (setq f (match-string 0 x))
10576 (setq f ""))
10577 (if (string-match "/" r)
10578 (concat string (substring r 0 (match-end 0)) f)
10580 rtn))
10581 ((eq flag 'lambda)
10582 ;; exact match?
10583 (assoc string thetable)))
10585 args)))
10587 ;;;; Dynamic blocks
10589 (defun org-find-dblock (name)
10590 "Find the first dynamic block with name NAME in the buffer.
10591 If not found, stay at current position and return nil."
10592 (let (pos)
10593 (save-excursion
10594 (goto-char (point-min))
10595 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
10596 nil t)
10597 (match-beginning 0))))
10598 (if pos (goto-char pos))
10599 pos))
10601 (defconst org-dblock-start-re
10602 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10603 "Matches the start line of a dynamic block, with parameters.")
10605 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
10606 "Matches the end of a dynamic block.")
10608 (defun org-create-dblock (plist)
10609 "Create a dynamic block section, with parameters taken from PLIST.
10610 PLIST must contain a :name entry which is used as name of the block."
10611 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
10612 (end-of-line 1)
10613 (newline))
10614 (let ((col (current-column))
10615 (name (plist-get plist :name)))
10616 (insert "#+BEGIN: " name)
10617 (while plist
10618 (if (eq (car plist) :name)
10619 (setq plist (cddr plist))
10620 (insert " " (prin1-to-string (pop plist)))))
10621 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
10622 (beginning-of-line -2)))
10624 (defun org-prepare-dblock ()
10625 "Prepare dynamic block for refresh.
10626 This empties the block, puts the cursor at the insert position and returns
10627 the property list including an extra property :name with the block name."
10628 (unless (looking-at org-dblock-start-re)
10629 (error "Not at a dynamic block"))
10630 (let* ((begdel (1+ (match-end 0)))
10631 (name (org-no-properties (match-string 1)))
10632 (params (append (list :name name)
10633 (read (concat "(" (match-string 3) ")")))))
10634 (save-excursion
10635 (beginning-of-line 1)
10636 (skip-chars-forward " \t")
10637 (setq params (plist-put params :indentation-column (current-column))))
10638 (unless (re-search-forward org-dblock-end-re nil t)
10639 (error "Dynamic block not terminated"))
10640 (setq params
10641 (append params
10642 (list :content (buffer-substring
10643 begdel (match-beginning 0)))))
10644 (delete-region begdel (match-beginning 0))
10645 (goto-char begdel)
10646 (open-line 1)
10647 params))
10649 (defun org-map-dblocks (&optional command)
10650 "Apply COMMAND to all dynamic blocks in the current buffer.
10651 If COMMAND is not given, use `org-update-dblock'."
10652 (let ((cmd (or command 'org-update-dblock)))
10653 (save-excursion
10654 (goto-char (point-min))
10655 (while (re-search-forward org-dblock-start-re nil t)
10656 (goto-char (match-beginning 0))
10657 (save-excursion
10658 (condition-case nil
10659 (funcall cmd)
10660 (error (message "Error during update of dynamic block"))))
10661 (unless (re-search-forward org-dblock-end-re nil t)
10662 (error "Dynamic block not terminated"))))))
10664 (defun org-dblock-update (&optional arg)
10665 "User command for updating dynamic blocks.
10666 Update the dynamic block at point. With prefix ARG, update all dynamic
10667 blocks in the buffer."
10668 (interactive "P")
10669 (if arg
10670 (org-update-all-dblocks)
10671 (or (looking-at org-dblock-start-re)
10672 (org-beginning-of-dblock))
10673 (org-update-dblock)))
10675 (defun org-update-dblock ()
10676 "Update the dynamic block at point.
10677 This means to empty the block, parse for parameters and then call
10678 the correct writing function."
10679 (interactive)
10680 (save-window-excursion
10681 (let* ((pos (point))
10682 (line (org-current-line))
10683 (params (org-prepare-dblock))
10684 (name (plist-get params :name))
10685 (indent (plist-get params :indentation-column))
10686 (cmd (intern (concat "org-dblock-write:" name))))
10687 (message "Updating dynamic block `%s' at line %d..." name line)
10688 (funcall cmd params)
10689 (message "Updating dynamic block `%s' at line %d...done" name line)
10690 (goto-char pos)
10691 (when (and indent (> indent 0))
10692 (setq indent (make-string indent ?\ ))
10693 (save-excursion
10694 (org-beginning-of-dblock)
10695 (forward-line 1)
10696 (while (not (looking-at org-dblock-end-re))
10697 (insert indent)
10698 (beginning-of-line 2))
10699 (when (looking-at org-dblock-end-re)
10700 (and (looking-at "[ \t]+")
10701 (replace-match ""))
10702 (insert indent)))))))
10704 (defun org-beginning-of-dblock ()
10705 "Find the beginning of the dynamic block at point.
10706 Error if there is no such block at point."
10707 (let ((pos (point))
10708 beg)
10709 (end-of-line 1)
10710 (if (and (re-search-backward org-dblock-start-re nil t)
10711 (setq beg (match-beginning 0))
10712 (re-search-forward org-dblock-end-re nil t)
10713 (> (match-end 0) pos))
10714 (goto-char beg)
10715 (goto-char pos)
10716 (error "Not in a dynamic block"))))
10718 (defun org-update-all-dblocks ()
10719 "Update all dynamic blocks in the buffer.
10720 This function can be used in a hook."
10721 (interactive)
10722 (when (org-mode-p)
10723 (org-map-dblocks 'org-update-dblock)))
10726 ;;;; Completion
10728 (defconst org-additional-option-like-keywords
10729 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
10730 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
10731 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
10732 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
10733 "BEGIN:" "END:"
10734 "ORGTBL" "TBLFM:" "TBLNAME:"
10735 "BEGIN_EXAMPLE" "END_EXAMPLE"
10736 "BEGIN_QUOTE" "END_QUOTE"
10737 "BEGIN_VERSE" "END_VERSE"
10738 "BEGIN_CENTER" "END_CENTER"
10739 "BEGIN_SRC" "END_SRC"
10740 "BEGIN_RESULT" "END_RESULT"
10741 "SOURCE:" "SRCNAME:" "FUNCTION:"
10742 "RESULTS:"
10743 "HEADER:" "HEADERS:"
10744 "BABEL:"
10745 "CATEGORY:" "COLUMNS:" "PROPERTY:"
10746 "CAPTION:" "LABEL:"
10747 "SETUPFILE:"
10748 "INCLUDE:"
10749 "BIND:"
10750 "MACRO:"))
10752 (defcustom org-structure-template-alist
10754 ("s" "#+begin_src ?\n\n#+end_src"
10755 "<src lang=\"?\">\n\n</src>")
10756 ("e" "#+begin_example\n?\n#+end_example"
10757 "<example>\n?\n</example>")
10758 ("q" "#+begin_quote\n?\n#+end_quote"
10759 "<quote>\n?\n</quote>")
10760 ("v" "#+begin_verse\n?\n#+end_verse"
10761 "<verse>\n?\n/verse>")
10762 ("c" "#+begin_center\n?\n#+end_center"
10763 "<center>\n?\n/center>")
10764 ("l" "#+begin_latex\n?\n#+end_latex"
10765 "<literal style=\"latex\">\n?\n</literal>")
10766 ("L" "#+latex: "
10767 "<literal style=\"latex\">?</literal>")
10768 ("h" "#+begin_html\n?\n#+end_html"
10769 "<literal style=\"html\">\n?\n</literal>")
10770 ("H" "#+html: "
10771 "<literal style=\"html\">?</literal>")
10772 ("a" "#+begin_ascii\n?\n#+end_ascii")
10773 ("A" "#+ascii: ")
10774 ("i" "#+index: ?"
10775 "#+index: ?")
10776 ("I" "#+include %file ?"
10777 "<include file=%file markup=\"?\">")
10779 "Structure completion elements.
10780 This is a list of abbreviation keys and values. The value gets inserted
10781 if you type `<' followed by the key and then press the completion key,
10782 usually `M-TAB'. %file will be replaced by a file name after prompting
10783 for the file using completion. The cursor will be placed at the position
10784 of the `?` in the template.
10785 There are two templates for each key, the first uses the original Org syntax,
10786 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
10787 the default when the /org-mtags.el/ module has been loaded. See also the
10788 variable `org-mtags-prefer-muse-templates'.
10789 This is an experimental feature, it is undecided if it is going to stay in."
10790 :group 'org-completion
10791 :type '(repeat
10792 (string :tag "Key")
10793 (string :tag "Template")
10794 (string :tag "Muse Template")))
10796 (defun org-try-structure-completion ()
10797 "Try to complete a structure template before point.
10798 This looks for strings like \"<e\" on an otherwise empty line and
10799 expands them."
10800 (let ((l (buffer-substring (point-at-bol) (point)))
10802 (when (and (looking-at "[ \t]*$")
10803 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
10804 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
10805 (org-complete-expand-structure-template (+ -1 (point-at-bol)
10806 (match-beginning 1)) a)
10807 t)))
10809 (defun org-complete-expand-structure-template (start cell)
10810 "Expand a structure template."
10811 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
10812 (rpl (nth (if musep 2 1) cell))
10813 (ind ""))
10814 (delete-region start (point))
10815 (when (string-match "\\`#\\+" rpl)
10816 (cond
10817 ((bolp))
10818 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
10819 (setq ind (buffer-substring (point-at-bol) (point))))
10820 (t (newline))))
10821 (setq start (point))
10822 (if (string-match "%file" rpl)
10823 (setq rpl (replace-match
10824 (concat
10825 "\""
10826 (save-match-data
10827 (abbreviate-file-name (read-file-name "Include file: ")))
10828 "\"")
10829 t t rpl)))
10830 (setq rpl (mapconcat 'identity (split-string rpl "\n")
10831 (concat "\n" ind)))
10832 (insert rpl)
10833 (if (re-search-backward "\\?" start t) (delete-char 1))))
10835 ;;;; TODO, DEADLINE, Comments
10837 (defun org-toggle-comment ()
10838 "Change the COMMENT state of an entry."
10839 (interactive)
10840 (save-excursion
10841 (org-back-to-heading)
10842 (let (case-fold-search)
10843 (if (looking-at (concat outline-regexp
10844 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
10845 (replace-match "" t t nil 1)
10846 (if (looking-at outline-regexp)
10847 (progn
10848 (goto-char (match-end 0))
10849 (insert org-comment-string " ")))))))
10851 (defvar org-last-todo-state-is-todo nil
10852 "This is non-nil when the last TODO state change led to a TODO state.
10853 If the last change removed the TODO tag or switched to DONE, then
10854 this is nil.")
10856 (defvar org-setting-tags nil) ; dynamically skipped
10858 (defvar org-todo-setup-filter-hook nil
10859 "Hook for functions that pre-filter todo specs.
10860 Each function takes a todo spec and returns either nil or the spec
10861 transformed into canonical form." )
10863 (defvar org-todo-get-default-hook nil
10864 "Hook for functions that get a default item for todo.
10865 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
10866 nil or a string to be used for the todo mark." )
10868 (defvar org-agenda-headline-snapshot-before-repeat)
10870 (defun org-todo (&optional arg)
10871 "Change the TODO state of an item.
10872 The state of an item is given by a keyword at the start of the heading,
10873 like
10874 *** TODO Write paper
10875 *** DONE Call mom
10877 The different keywords are specified in the variable `org-todo-keywords'.
10878 By default the available states are \"TODO\" and \"DONE\".
10879 So for this example: when the item starts with TODO, it is changed to DONE.
10880 When it starts with DONE, the DONE is removed. And when neither TODO nor
10881 DONE are present, add TODO at the beginning of the heading.
10883 With \\[universal-argument] prefix arg, use completion to determine the new \
10884 state.
10885 With numeric prefix arg, switch to that state.
10886 With a double \\[universal-argument] prefix, switch to the next set of TODO \
10887 keywords (nextset).
10888 With a triple \\[universal-argument] prefix, circumvent any state blocking.
10890 For calling through lisp, arg is also interpreted in the following way:
10891 'none -> empty state
10892 \"\"(empty string) -> switch to empty state
10893 'done -> switch to DONE
10894 'nextset -> switch to the next set of keywords
10895 'previousset -> switch to the previous set of keywords
10896 \"WAITING\" -> switch to the specified keyword, but only if it
10897 really is a member of `org-todo-keywords'."
10898 (interactive "P")
10899 (if (equal arg '(16)) (setq arg 'nextset))
10900 (let ((org-blocker-hook org-blocker-hook)
10901 (case-fold-search nil))
10902 (when (equal arg '(64))
10903 (setq arg nil org-blocker-hook nil))
10904 (when (and org-blocker-hook
10905 (or org-inhibit-blocking
10906 (org-entry-get nil "NOBLOCKING")))
10907 (setq org-blocker-hook nil))
10908 (save-excursion
10909 (catch 'exit
10910 (org-back-to-heading t)
10911 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
10912 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
10913 (looking-at " *"))
10914 (let* ((match-data (match-data))
10915 (startpos (point-at-bol))
10916 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
10917 (org-log-done org-log-done)
10918 (org-log-repeat org-log-repeat)
10919 (org-todo-log-states org-todo-log-states)
10920 (this (match-string 1))
10921 (hl-pos (match-beginning 0))
10922 (head (org-get-todo-sequence-head this))
10923 (ass (assoc head org-todo-kwd-alist))
10924 (interpret (nth 1 ass))
10925 (done-word (nth 3 ass))
10926 (final-done-word (nth 4 ass))
10927 (last-state (or this ""))
10928 (completion-ignore-case t)
10929 (member (member this org-todo-keywords-1))
10930 (tail (cdr member))
10931 (state (cond
10932 ((and org-todo-key-trigger
10933 (or (and (equal arg '(4))
10934 (eq org-use-fast-todo-selection 'prefix))
10935 (and (not arg) org-use-fast-todo-selection
10936 (not (eq org-use-fast-todo-selection
10937 'prefix)))))
10938 ;; Use fast selection
10939 (org-fast-todo-selection))
10940 ((and (equal arg '(4))
10941 (or (not org-use-fast-todo-selection)
10942 (not org-todo-key-trigger)))
10943 ;; Read a state with completion
10944 (org-icompleting-read
10945 "State: " (mapcar (lambda(x) (list x))
10946 org-todo-keywords-1)
10947 nil t))
10948 ((eq arg 'right)
10949 (if this
10950 (if tail (car tail) nil)
10951 (car org-todo-keywords-1)))
10952 ((eq arg 'left)
10953 (if (equal member org-todo-keywords-1)
10955 (if this
10956 (nth (- (length org-todo-keywords-1)
10957 (length tail) 2)
10958 org-todo-keywords-1)
10959 (org-last org-todo-keywords-1))))
10960 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
10961 (setq arg nil))) ; hack to fall back to cycling
10962 (arg
10963 ;; user or caller requests a specific state
10964 (cond
10965 ((equal arg "") nil)
10966 ((eq arg 'none) nil)
10967 ((eq arg 'done) (or done-word (car org-done-keywords)))
10968 ((eq arg 'nextset)
10969 (or (car (cdr (member head org-todo-heads)))
10970 (car org-todo-heads)))
10971 ((eq arg 'previousset)
10972 (let ((org-todo-heads (reverse org-todo-heads)))
10973 (or (car (cdr (member head org-todo-heads)))
10974 (car org-todo-heads))))
10975 ((car (member arg org-todo-keywords-1)))
10976 ((stringp arg)
10977 (error "State `%s' not valid in this file" arg))
10978 ((nth (1- (prefix-numeric-value arg))
10979 org-todo-keywords-1))))
10980 ((null member) (or head (car org-todo-keywords-1)))
10981 ((equal this final-done-word) nil) ;; -> make empty
10982 ((null tail) nil) ;; -> first entry
10983 ((memq interpret '(type priority))
10984 (if (eq this-command last-command)
10985 (car tail)
10986 (if (> (length tail) 0)
10987 (or done-word (car org-done-keywords))
10988 nil)))
10990 (car tail))))
10991 (state (or
10992 (run-hook-with-args-until-success
10993 'org-todo-get-default-hook state last-state)
10994 state))
10995 (next (if state (concat " " state " ") " "))
10996 (change-plist (list :type 'todo-state-change :from this :to state
10997 :position startpos))
10998 dolog now-done-p)
10999 (when org-blocker-hook
11000 (setq org-last-todo-state-is-todo
11001 (not (member this org-done-keywords)))
11002 (unless (save-excursion
11003 (save-match-data
11004 (org-with-wide-buffer
11005 (run-hook-with-args-until-failure
11006 'org-blocker-hook change-plist))))
11007 (if (interactive-p)
11008 (error "TODO state change from %s to %s blocked" this state)
11009 ;; fail silently
11010 (message "TODO state change from %s to %s blocked" this state)
11011 (throw 'exit nil))))
11012 (store-match-data match-data)
11013 (replace-match next t t)
11014 (unless (pos-visible-in-window-p hl-pos)
11015 (message "TODO state changed to %s" (org-trim next)))
11016 (unless head
11017 (setq head (org-get-todo-sequence-head state)
11018 ass (assoc head org-todo-kwd-alist)
11019 interpret (nth 1 ass)
11020 done-word (nth 3 ass)
11021 final-done-word (nth 4 ass)))
11022 (when (memq arg '(nextset previousset))
11023 (message "Keyword-Set %d/%d: %s"
11024 (- (length org-todo-sets) -1
11025 (length (memq (assoc state org-todo-sets) org-todo-sets)))
11026 (length org-todo-sets)
11027 (mapconcat 'identity (assoc state org-todo-sets) " ")))
11028 (setq org-last-todo-state-is-todo
11029 (not (member state org-done-keywords)))
11030 (setq now-done-p (and (member state org-done-keywords)
11031 (not (member this org-done-keywords))))
11032 (and logging (org-local-logging logging))
11033 (when (and (or org-todo-log-states org-log-done)
11034 (not (eq org-inhibit-logging t))
11035 (not (memq arg '(nextset previousset))))
11036 ;; we need to look at recording a time and note
11037 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
11038 (nth 2 (assoc this org-todo-log-states))))
11039 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11040 (setq dolog 'time))
11041 (when (and state
11042 (member state org-not-done-keywords)
11043 (not (member this org-not-done-keywords)))
11044 ;; This is now a todo state and was not one before
11045 ;; If there was a CLOSED time stamp, get rid of it.
11046 (org-add-planning-info nil nil 'closed))
11047 (when (and now-done-p org-log-done)
11048 ;; It is now done, and it was not done before
11049 (org-add-planning-info 'closed (org-current-time))
11050 (if (and (not dolog) (eq 'note org-log-done))
11051 (org-add-log-setup 'done state this 'findpos 'note)))
11052 (when (and state dolog)
11053 ;; This is a non-nil state, and we need to log it
11054 (org-add-log-setup 'state state this 'findpos dolog)))
11055 ;; Fixup tag positioning
11056 (org-todo-trigger-tag-changes state)
11057 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11058 (when org-provide-todo-statistics
11059 (org-update-parent-todo-statistics))
11060 (run-hooks 'org-after-todo-state-change-hook)
11061 (if (and arg (not (member state org-done-keywords)))
11062 (setq head (org-get-todo-sequence-head state)))
11063 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11064 ;; Do we need to trigger a repeat?
11065 (when now-done-p
11066 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11067 ;; This is for the agenda, take a snapshot of the headline.
11068 (save-match-data
11069 (setq org-agenda-headline-snapshot-before-repeat
11070 (org-get-heading))))
11071 (org-auto-repeat-maybe state))
11072 ;; Fixup cursor location if close to the keyword
11073 (if (and (outline-on-heading-p)
11074 (not (bolp))
11075 (save-excursion (beginning-of-line 1)
11076 (looking-at org-todo-line-regexp))
11077 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11078 (progn
11079 (goto-char (or (match-end 2) (match-end 1)))
11080 (and (looking-at " ") (just-one-space))))
11081 (when org-trigger-hook
11082 (save-excursion
11083 (run-hook-with-args 'org-trigger-hook change-plist))))))))
11085 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11086 "Block turning an entry into a TODO, using the hierarchy.
11087 This checks whether the current task should be blocked from state
11088 changes. Such blocking occurs when:
11090 1. The task has children which are not all in a completed state.
11092 2. A task has a parent with the property :ORDERED:, and there
11093 are siblings prior to the current task with incomplete
11094 status.
11096 3. The parent of the task is blocked because it has siblings that should
11097 be done first, or is child of a block grandparent TODO entry."
11099 (if (not org-enforce-todo-dependencies)
11100 t ; if locally turned off don't block
11101 (catch 'dont-block
11102 ;; If this is not a todo state change, or if this entry is already DONE,
11103 ;; do not block
11104 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11105 (member (plist-get change-plist :from)
11106 (cons 'done org-done-keywords))
11107 (member (plist-get change-plist :to)
11108 (cons 'todo org-not-done-keywords))
11109 (not (plist-get change-plist :to)))
11110 (throw 'dont-block t))
11111 ;; If this task has children, and any are undone, it's blocked
11112 (save-excursion
11113 (org-back-to-heading t)
11114 (let ((this-level (funcall outline-level)))
11115 (outline-next-heading)
11116 (let ((child-level (funcall outline-level)))
11117 (while (and (not (eobp))
11118 (> child-level this-level))
11119 ;; this todo has children, check whether they are all
11120 ;; completed
11121 (if (and (not (org-entry-is-done-p))
11122 (org-entry-is-todo-p))
11123 (throw 'dont-block nil))
11124 (outline-next-heading)
11125 (setq child-level (funcall outline-level))))))
11126 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11127 ;; any previous siblings are undone, it's blocked
11128 (save-excursion
11129 (org-back-to-heading t)
11130 (let* ((pos (point))
11131 (parent-pos (and (org-up-heading-safe) (point))))
11132 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11133 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11134 (forward-line 1)
11135 (re-search-forward org-not-done-heading-regexp pos t))
11136 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11137 ;; Search further up the hierarchy, to see if an anchestor is blocked
11138 (while t
11139 (goto-char parent-pos)
11140 (if (not (looking-at org-not-done-heading-regexp))
11141 (throw 'dont-block t)) ; do not block, parent is not a TODO
11142 (setq pos (point))
11143 (setq parent-pos (and (org-up-heading-safe) (point)))
11144 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11145 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11146 (forward-line 1)
11147 (re-search-forward org-not-done-heading-regexp pos t))
11148 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11150 (defcustom org-track-ordered-property-with-tag nil
11151 "Should the ORDERED property also be shown as a tag?
11152 The ORDERED property decides if an entry should require subtasks to be
11153 completed in sequence. Since a property is not very visible, setting
11154 this option means that toggling the ORDERED property with the command
11155 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11156 not relevant for the behavior, but it makes things more visible.
11158 Note that toggling the tag with tags commands will not change the property
11159 and therefore not influence behavior!
11161 This can be t, meaning the tag ORDERED should be used, It can also be a
11162 string to select a different tag for this task."
11163 :group 'org-todo
11164 :type '(choice
11165 (const :tag "No tracking" nil)
11166 (const :tag "Track with ORDERED tag" t)
11167 (string :tag "Use other tag")))
11169 (defun org-toggle-ordered-property ()
11170 "Toggle the ORDERED property of the current entry.
11171 For better visibility, you can track the value of this property with a tag.
11172 See variable `org-track-ordered-property-with-tag'."
11173 (interactive)
11174 (let* ((t1 org-track-ordered-property-with-tag)
11175 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11176 (save-excursion
11177 (org-back-to-heading)
11178 (if (org-entry-get nil "ORDERED")
11179 (progn
11180 (org-delete-property "ORDERED")
11181 (and tag (org-toggle-tag tag 'off))
11182 (message "Subtasks can be completed in arbitrary order"))
11183 (org-entry-put nil "ORDERED" "t")
11184 (and tag (org-toggle-tag tag 'on))
11185 (message "Subtasks must be completed in sequence")))))
11187 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11188 (defun org-block-todo-from-checkboxes (change-plist)
11189 "Block turning an entry into a TODO, using checkboxes.
11190 This checks whether the current task should be blocked from state
11191 changes because there are unchecked boxes in this entry."
11192 (if (not org-enforce-todo-checkbox-dependencies)
11193 t ; if locally turned off don't block
11194 (catch 'dont-block
11195 ;; If this is not a todo state change, or if this entry is already DONE,
11196 ;; do not block
11197 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11198 (member (plist-get change-plist :from)
11199 (cons 'done org-done-keywords))
11200 (member (plist-get change-plist :to)
11201 (cons 'todo org-not-done-keywords))
11202 (not (plist-get change-plist :to)))
11203 (throw 'dont-block t))
11204 ;; If this task has checkboxes that are not checked, it's blocked
11205 (save-excursion
11206 (org-back-to-heading t)
11207 (let ((beg (point)) end)
11208 (outline-next-heading)
11209 (setq end (point))
11210 (goto-char beg)
11211 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
11212 end t)
11213 (progn
11214 (if (boundp 'org-blocked-by-checkboxes)
11215 (setq org-blocked-by-checkboxes t))
11216 (throw 'dont-block nil)))))
11217 t))) ; do not block
11219 (defun org-entry-blocked-p ()
11220 "Is the current entry blocked?"
11221 (if (org-entry-get nil "NOBLOCKING")
11222 nil ;; Never block this entry
11223 (not
11224 (run-hook-with-args-until-failure
11225 'org-blocker-hook
11226 (list :type 'todo-state-change
11227 :position (point)
11228 :from 'todo
11229 :to 'done)))))
11231 (defun org-update-statistics-cookies (all)
11232 "Update the statistics cookie, either from TODO or from checkboxes.
11233 This should be called with the cursor in a line with a statistics cookie."
11234 (interactive "P")
11235 (if all
11236 (progn
11237 (org-update-checkbox-count 'all)
11238 (org-map-entries 'org-update-parent-todo-statistics))
11239 (if (not (org-on-heading-p))
11240 (org-update-checkbox-count)
11241 (let ((pos (move-marker (make-marker) (point)))
11242 end l1 l2)
11243 (ignore-errors (org-back-to-heading t))
11244 (if (not (org-on-heading-p))
11245 (org-update-checkbox-count)
11246 (setq l1 (org-outline-level))
11247 (setq end (save-excursion
11248 (outline-next-heading)
11249 (if (org-on-heading-p) (setq l2 (org-outline-level)))
11250 (point)))
11251 (if (and (save-excursion
11252 (re-search-forward
11253 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11254 (not (save-excursion (re-search-forward
11255 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11256 (org-update-checkbox-count)
11257 (if (and l2 (> l2 l1))
11258 (progn
11259 (goto-char end)
11260 (org-update-parent-todo-statistics))
11261 (goto-char pos)
11262 (beginning-of-line 1)
11263 (while (re-search-forward
11264 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11265 (point-at-eol) t)
11266 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11267 (goto-char pos)
11268 (move-marker pos nil)))))
11270 (defvar org-entry-property-inherited-from) ;; defined below
11271 (defun org-update-parent-todo-statistics ()
11272 "Update any statistics cookie in the parent of the current headline.
11273 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11274 the entire subtree and this will travel up the hierarchy and update
11275 statistics everywhere."
11276 (interactive)
11277 (let* ((lim 0) prop
11278 (recursive (or (not org-hierarchical-todo-statistics)
11279 (string-match
11280 "\\<recursive\\>"
11281 (or (setq prop (org-entry-get
11282 nil "COOKIE_DATA" 'inherit)) ""))))
11283 (lim (or (and prop (marker-position
11284 org-entry-property-inherited-from))
11285 lim))
11286 (first t)
11287 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11288 level ltoggle l1 new ndel
11289 (cnt-all 0) (cnt-done 0) is-percent kwd
11290 checkbox-beg ov ovs ove cookie-present)
11291 (catch 'exit
11292 (save-excursion
11293 (beginning-of-line 1)
11294 (if (org-at-heading-p)
11295 (setq ltoggle (funcall outline-level))
11296 (error "This should not happen"))
11297 (while (and (setq level (org-up-heading-safe))
11298 (or recursive first)
11299 (>= (point) lim))
11300 (setq first nil cookie-present nil)
11301 (unless (and level
11302 (not (string-match
11303 "\\<checkbox\\>"
11304 (downcase
11305 (or (org-entry-get
11306 nil "COOKIE_DATA")
11307 "")))))
11308 (throw 'exit nil))
11309 (while (re-search-forward box-re (point-at-eol) t)
11310 (setq cnt-all 0 cnt-done 0 cookie-present t)
11311 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11312 (save-match-data
11313 (unless (outline-next-heading) (throw 'exit nil))
11314 (while (and (looking-at org-complex-heading-regexp)
11315 (> (setq l1 (length (match-string 1))) level))
11316 (setq kwd (and (or recursive (= l1 ltoggle))
11317 (match-string 2)))
11318 (if (or (eq org-provide-todo-statistics 'all-headlines)
11319 (and (listp org-provide-todo-statistics)
11320 (or (member kwd org-provide-todo-statistics)
11321 (member kwd org-done-keywords))))
11322 (setq cnt-all (1+ cnt-all))
11323 (if (eq org-provide-todo-statistics t)
11324 (and kwd (setq cnt-all (1+ cnt-all)))))
11325 (and (member kwd org-done-keywords)
11326 (setq cnt-done (1+ cnt-done)))
11327 (outline-next-heading)))
11328 (setq new
11329 (if is-percent
11330 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11331 (format "[%d/%d]" cnt-done cnt-all))
11332 ndel (- (match-end 0) checkbox-beg))
11333 ;; handle overlays when updating cookie from column view
11334 (when (setq ov (car (overlays-at checkbox-beg)))
11335 (setq ovs (overlay-start ov) ove (overlay-end ov))
11336 (delete-overlay ov))
11337 (goto-char checkbox-beg)
11338 (insert new)
11339 (delete-region (point) (+ (point) ndel))
11340 (when ov (move-overlay ov ovs ove)))
11341 (when cookie-present
11342 (run-hook-with-args 'org-after-todo-statistics-hook
11343 cnt-done (- cnt-all cnt-done))))))
11344 (run-hooks 'org-todo-statistics-hook)))
11346 (defvar org-after-todo-statistics-hook nil
11347 "Hook that is called after a TODO statistics cookie has been updated.
11348 Each function is called with two arguments: the number of not-done entries
11349 and the number of done entries.
11351 For example, the following function, when added to this hook, will switch
11352 an entry to DONE when all children are done, and back to TODO when new
11353 entries are set to a TODO status. Note that this hook is only called
11354 when there is a statistics cookie in the headline!
11356 (defun org-summary-todo (n-done n-not-done)
11357 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11358 (let (org-log-done org-log-states) ; turn off logging
11359 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11362 (defvar org-todo-statistics-hook nil
11363 "Hook that is run whenever Org thinks TODO statistics should be updated.
11364 This hook runs even if there is no statistics cookie present, in which case
11365 `org-after-todo-statistics-hook' would not run.")
11367 (defun org-todo-trigger-tag-changes (state)
11368 "Apply the changes defined in `org-todo-state-tags-triggers'."
11369 (let ((l org-todo-state-tags-triggers)
11370 changes)
11371 (when (or (not state) (equal state ""))
11372 (setq changes (append changes (cdr (assoc "" l)))))
11373 (when (and (stringp state) (> (length state) 0))
11374 (setq changes (append changes (cdr (assoc state l)))))
11375 (when (member state org-not-done-keywords)
11376 (setq changes (append changes (cdr (assoc 'todo l)))))
11377 (when (member state org-done-keywords)
11378 (setq changes (append changes (cdr (assoc 'done l)))))
11379 (dolist (c changes)
11380 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11382 (defun org-local-logging (value)
11383 "Get logging settings from a property VALUE."
11384 (let* (words w a)
11385 ;; directly set the variables, they are already local.
11386 (setq org-log-done nil
11387 org-log-repeat nil
11388 org-todo-log-states nil)
11389 (setq words (org-split-string value))
11390 (while (setq w (pop words))
11391 (cond
11392 ((setq a (assoc w org-startup-options))
11393 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11394 (set (nth 1 a) (nth 2 a))))
11395 ((setq a (org-extract-log-state-settings w))
11396 (and (member (car a) org-todo-keywords-1)
11397 (push a org-todo-log-states)))))))
11399 (defun org-get-todo-sequence-head (kwd)
11400 "Return the head of the TODO sequence to which KWD belongs.
11401 If KWD is not set, check if there is a text property remembering the
11402 right sequence."
11403 (let (p)
11404 (cond
11405 ((not kwd)
11406 (or (get-text-property (point-at-bol) 'org-todo-head)
11407 (progn
11408 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11409 nil (point-at-eol)))
11410 (get-text-property p 'org-todo-head))))
11411 ((not (member kwd org-todo-keywords-1))
11412 (car org-todo-keywords-1))
11413 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11415 (defun org-fast-todo-selection ()
11416 "Fast TODO keyword selection with single keys.
11417 Returns the new TODO keyword, or nil if no state change should occur."
11418 (let* ((fulltable org-todo-key-alist)
11419 (done-keywords org-done-keywords) ;; needed for the faces.
11420 (maxlen (apply 'max (mapcar
11421 (lambda (x)
11422 (if (stringp (car x)) (string-width (car x)) 0))
11423 fulltable)))
11424 (expert nil)
11425 (fwidth (+ maxlen 3 1 3))
11426 (ncol (/ (- (window-width) 4) fwidth))
11427 tg cnt e c tbl
11428 groups ingroup)
11429 (save-excursion
11430 (save-window-excursion
11431 (if expert
11432 (set-buffer (get-buffer-create " *Org todo*"))
11433 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11434 (erase-buffer)
11435 (org-set-local 'org-done-keywords done-keywords)
11436 (setq tbl fulltable cnt 0)
11437 (while (setq e (pop tbl))
11438 (cond
11439 ((equal e '(:startgroup))
11440 (push '() groups) (setq ingroup t)
11441 (when (not (= cnt 0))
11442 (setq cnt 0)
11443 (insert "\n"))
11444 (insert "{ "))
11445 ((equal e '(:endgroup))
11446 (setq ingroup nil cnt 0)
11447 (insert "}\n"))
11448 ((equal e '(:newline))
11449 (when (not (= cnt 0))
11450 (setq cnt 0)
11451 (insert "\n")
11452 (setq e (car tbl))
11453 (while (equal (car tbl) '(:newline))
11454 (insert "\n")
11455 (setq tbl (cdr tbl)))))
11457 (setq tg (car e) c (cdr e))
11458 (if ingroup (push tg (car groups)))
11459 (setq tg (org-add-props tg nil 'face
11460 (org-get-todo-face tg)))
11461 (if (and (= cnt 0) (not ingroup)) (insert " "))
11462 (insert "[" c "] " tg (make-string
11463 (- fwidth 4 (length tg)) ?\ ))
11464 (when (= (setq cnt (1+ cnt)) ncol)
11465 (insert "\n")
11466 (if ingroup (insert " "))
11467 (setq cnt 0)))))
11468 (insert "\n")
11469 (goto-char (point-min))
11470 (if (not expert) (org-fit-window-to-buffer))
11471 (message "[a-z..]:Set [SPC]:clear")
11472 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11473 (cond
11474 ((or (= c ?\C-g)
11475 (and (= c ?q) (not (rassoc c fulltable))))
11476 (setq quit-flag t))
11477 ((= c ?\ ) nil)
11478 ((setq e (rassoc c fulltable) tg (car e))
11480 (t (setq quit-flag t)))))))
11482 (defun org-entry-is-todo-p ()
11483 (member (org-get-todo-state) org-not-done-keywords))
11485 (defun org-entry-is-done-p ()
11486 (member (org-get-todo-state) org-done-keywords))
11488 (defun org-get-todo-state ()
11489 (save-excursion
11490 (org-back-to-heading t)
11491 (and (looking-at org-todo-line-regexp)
11492 (match-end 2)
11493 (match-string 2))))
11495 (defun org-at-date-range-p (&optional inactive-ok)
11496 "Is the cursor inside a date range?"
11497 (interactive)
11498 (save-excursion
11499 (catch 'exit
11500 (let ((pos (point)))
11501 (skip-chars-backward "^[<\r\n")
11502 (skip-chars-backward "<[")
11503 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11504 (>= (match-end 0) pos)
11505 (throw 'exit t))
11506 (skip-chars-backward "^<[\r\n")
11507 (skip-chars-backward "<[")
11508 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11509 (>= (match-end 0) pos)
11510 (throw 'exit t)))
11511 nil)))
11513 (defun org-get-repeat (&optional tagline)
11514 "Check if there is a deadline/schedule with repeater in this entry."
11515 (save-match-data
11516 (save-excursion
11517 (org-back-to-heading t)
11518 (and (re-search-forward (if tagline
11519 (concat tagline "\\s-*" org-repeat-re)
11520 org-repeat-re)
11521 (org-entry-end-position) t)
11522 (match-string-no-properties 1)))))
11524 (defvar org-last-changed-timestamp)
11525 (defvar org-last-inserted-timestamp)
11526 (defvar org-log-post-message)
11527 (defvar org-log-note-purpose)
11528 (defvar org-log-note-how)
11529 (defvar org-log-note-extra)
11530 (defun org-auto-repeat-maybe (done-word)
11531 "Check if the current headline contains a repeated deadline/schedule.
11532 If yes, set TODO state back to what it was and change the base date
11533 of repeating deadline/scheduled time stamps to new date.
11534 This function is run automatically after each state change to a DONE state."
11535 ;; last-state is dynamically scoped into this function
11536 (let* ((repeat (org-get-repeat))
11537 (aa (assoc last-state org-todo-kwd-alist))
11538 (interpret (nth 1 aa))
11539 (head (nth 2 aa))
11540 (whata '(("d" . day) ("m" . month) ("y" . year)))
11541 (msg "Entry repeats: ")
11542 (org-log-done nil)
11543 (org-todo-log-states nil)
11544 re type n what ts time to-state)
11545 (when repeat
11546 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11547 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11548 org-todo-repeat-to-state))
11549 (unless (and to-state (member to-state org-todo-keywords-1))
11550 (setq to-state (if (eq interpret 'type) last-state head)))
11551 (org-todo to-state)
11552 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11553 (org-entry-put nil "LAST_REPEAT" (format-time-string
11554 (org-time-stamp-format t t))))
11555 (when org-log-repeat
11556 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11557 (memq 'org-add-log-note post-command-hook))
11558 ;; OK, we are already setup for some record
11559 (if (eq org-log-repeat 'note)
11560 ;; make sure we take a note, not only a time stamp
11561 (setq org-log-note-how 'note))
11562 ;; Set up for taking a record
11563 (org-add-log-setup 'state (or done-word (car org-done-keywords))
11564 last-state
11565 'findpos org-log-repeat)))
11566 (org-back-to-heading t)
11567 (org-add-planning-info nil nil 'closed)
11568 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11569 org-deadline-time-regexp "\\)\\|\\("
11570 org-ts-regexp "\\)"))
11571 (while (re-search-forward
11572 re (save-excursion (outline-next-heading) (point)) t)
11573 (setq type (if (match-end 1) org-scheduled-string
11574 (if (match-end 3) org-deadline-string "Plain:"))
11575 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
11576 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
11577 (setq n (string-to-number (match-string 2 ts))
11578 what (match-string 3 ts))
11579 (if (equal what "w") (setq n (* n 7) what "d"))
11580 ;; Preparation, see if we need to modify the start date for the change
11581 (when (match-end 1)
11582 (setq time (save-match-data (org-time-string-to-time ts)))
11583 (cond
11584 ((equal (match-string 1 ts) ".")
11585 ;; Shift starting date to today
11586 (org-timestamp-change
11587 (- (time-to-days (current-time)) (time-to-days time))
11588 'day))
11589 ((equal (match-string 1 ts) "+")
11590 (let ((nshiftmax 10) (nshift 0))
11591 (while (or (= nshift 0)
11592 (<= (time-to-days time)
11593 (time-to-days (current-time))))
11594 (when (= (incf nshift) nshiftmax)
11595 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
11596 (error "Abort")))
11597 (org-timestamp-change n (cdr (assoc what whata)))
11598 (org-at-timestamp-p t)
11599 (setq ts (match-string 1))
11600 (setq time (save-match-data (org-time-string-to-time ts)))))
11601 (org-timestamp-change (- n) (cdr (assoc what whata)))
11602 ;; rematch, so that we have everything in place for the real shift
11603 (org-at-timestamp-p t)
11604 (setq ts (match-string 1))
11605 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
11606 (org-timestamp-change n (cdr (assoc what whata)))
11607 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
11608 (setq org-log-post-message msg)
11609 (message "%s" msg))))
11611 (defun org-show-todo-tree (arg)
11612 "Make a compact tree which shows all headlines marked with TODO.
11613 The tree will show the lines where the regexp matches, and all higher
11614 headlines above the match.
11615 With a \\[universal-argument] prefix, prompt for a regexp to match.
11616 With a numeric prefix N, construct a sparse tree for the Nth element
11617 of `org-todo-keywords-1'."
11618 (interactive "P")
11619 (let ((case-fold-search nil)
11620 (kwd-re
11621 (cond ((null arg) org-not-done-regexp)
11622 ((equal arg '(4))
11623 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
11624 (mapcar 'list org-todo-keywords-1))))
11625 (concat "\\("
11626 (mapconcat 'identity (org-split-string kwd "|") "\\|")
11627 "\\)\\>")))
11628 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
11629 (regexp-quote (nth (1- (prefix-numeric-value arg))
11630 org-todo-keywords-1)))
11631 (t (error "Invalid prefix argument: %s" arg)))))
11632 (message "%d TODO entries found"
11633 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
11635 (defun org-deadline (&optional remove time)
11636 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
11637 With argument REMOVE, remove any deadline from the item.
11638 When TIME is set, it should be an internal time specification, and the
11639 scheduling will use the corresponding date."
11640 (interactive "P")
11641 (let* ((old-date (org-entry-get nil "DEADLINE"))
11642 (repeater (and old-date
11643 (string-match
11644 "\\([.+]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
11645 old-date)
11646 (match-string 1 old-date))))
11647 (if remove
11648 (progn
11649 (when (and old-date org-log-redeadline)
11650 (org-add-log-setup 'deldeadline nil old-date 'findpos
11651 org-log-redeadline))
11652 (org-remove-timestamp-with-keyword org-deadline-string)
11653 (message "Item no longer has a deadline."))
11654 (org-add-planning-info 'deadline time 'closed)
11655 (when (and old-date org-log-redeadline
11656 (not (equal old-date
11657 (substring org-last-inserted-timestamp 1 -1))))
11658 (org-add-log-setup 'redeadline nil old-date 'findpos
11659 org-log-redeadline))
11660 (when repeater
11661 (save-excursion
11662 (org-back-to-heading t)
11663 (when (re-search-forward (concat org-deadline-string " "
11664 org-last-inserted-timestamp)
11665 (save-excursion
11666 (outline-next-heading) (point)) t)
11667 (goto-char (1- (match-end 0)))
11668 (insert " " repeater)
11669 (setq org-last-inserted-timestamp
11670 (concat (substring org-last-inserted-timestamp 0 -1)
11671 " " repeater
11672 (substring org-last-inserted-timestamp -1))))))
11673 (message "Deadline on %s" org-last-inserted-timestamp))))
11675 (defun org-schedule (&optional remove time)
11676 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
11677 With argument REMOVE, remove any scheduling date from the item.
11678 When TIME is set, it should be an internal time specification, and the
11679 scheduling will use the corresponding date."
11680 (interactive "P")
11681 (let* ((old-date (org-entry-get nil "SCHEDULED"))
11682 (repeater (and old-date
11683 (string-match
11684 "\\([.+]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
11685 old-date)
11686 (match-string 1 old-date))))
11687 (if remove
11688 (progn
11689 (when (and old-date org-log-reschedule)
11690 (org-add-log-setup 'delschedule nil old-date 'findpos
11691 org-log-reschedule))
11692 (org-remove-timestamp-with-keyword org-scheduled-string)
11693 (message "Item is no longer scheduled."))
11694 (org-add-planning-info 'scheduled time 'closed)
11695 (when (and old-date org-log-reschedule
11696 (not (equal old-date
11697 (substring org-last-inserted-timestamp 1 -1))))
11698 (org-add-log-setup 'reschedule nil old-date 'findpos
11699 org-log-reschedule))
11700 (when repeater
11701 (save-excursion
11702 (org-back-to-heading t)
11703 (when (re-search-forward (concat org-scheduled-string " "
11704 org-last-inserted-timestamp)
11705 (save-excursion
11706 (outline-next-heading) (point)) t)
11707 (goto-char (1- (match-end 0)))
11708 (insert " " repeater)
11709 (setq org-last-inserted-timestamp
11710 (concat (substring org-last-inserted-timestamp 0 -1)
11711 " " repeater
11712 (substring org-last-inserted-timestamp -1))))))
11713 (message "Scheduled to %s" org-last-inserted-timestamp))))
11715 (defun org-get-scheduled-time (pom &optional inherit)
11716 "Get the scheduled time as a time tuple, of a format suitable
11717 for calling org-schedule with, or if there is no scheduling,
11718 returns nil."
11719 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
11720 (when time
11721 (apply 'encode-time (org-parse-time-string time)))))
11723 (defun org-get-deadline-time (pom &optional inherit)
11724 "Get the deadline as a time tuple, of a format suitable for
11725 calling org-deadline with, or if there is no scheduling, returns
11726 nil."
11727 (let ((time (org-entry-get pom "DEADLINE" inherit)))
11728 (when time
11729 (apply 'encode-time (org-parse-time-string time)))))
11731 (defun org-remove-timestamp-with-keyword (keyword)
11732 "Remove all time stamps with KEYWORD in the current entry."
11733 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
11734 beg)
11735 (save-excursion
11736 (org-back-to-heading t)
11737 (setq beg (point))
11738 (outline-next-heading)
11739 (while (re-search-backward re beg t)
11740 (replace-match "")
11741 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
11742 (equal (char-before) ?\ ))
11743 (backward-delete-char 1)
11744 (if (string-match "^[ \t]*$" (buffer-substring
11745 (point-at-bol) (point-at-eol)))
11746 (delete-region (point-at-bol)
11747 (min (point-max) (1+ (point-at-eol))))))))))
11749 (defun org-add-planning-info (what &optional time &rest remove)
11750 "Insert new timestamp with keyword in the line directly after the headline.
11751 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
11752 If non is given, the user is prompted for a date.
11753 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
11754 be removed."
11755 (interactive)
11756 (let (org-time-was-given org-end-time-was-given ts
11757 end default-time default-input)
11759 (catch 'exit
11760 (when (and (not time) (memq what '(scheduled deadline)))
11761 ;; Try to get a default date/time from existing timestamp
11762 (save-excursion
11763 (org-back-to-heading t)
11764 (setq end (save-excursion (outline-next-heading) (point)))
11765 (when (re-search-forward (if (eq what 'scheduled)
11766 org-scheduled-time-regexp
11767 org-deadline-time-regexp)
11768 end t)
11769 (setq ts (match-string 1)
11770 default-time
11771 (apply 'encode-time (org-parse-time-string ts))
11772 default-input (and ts (org-get-compact-tod ts))))))
11773 (when what
11774 ;; If necessary, get the time from the user
11775 (setq time (or time (org-read-date nil 'to-time nil nil
11776 default-time default-input))))
11778 (when (and org-insert-labeled-timestamps-at-point
11779 (member what '(scheduled deadline)))
11780 (insert
11781 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
11782 (org-insert-time-stamp time org-time-was-given
11783 nil nil nil (list org-end-time-was-given))
11784 (setq what nil))
11785 (save-excursion
11786 (save-restriction
11787 (let (col list elt ts buffer-invisibility-spec)
11788 (org-back-to-heading t)
11789 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
11790 (goto-char (match-end 1))
11791 (setq col (current-column))
11792 (goto-char (match-end 0))
11793 (if (eobp) (insert "\n") (forward-char 1))
11794 (when (and (not what)
11795 (not (looking-at
11796 (concat "[ \t]*"
11797 org-keyword-time-not-clock-regexp))))
11798 ;; Nothing to add, nothing to remove...... :-)
11799 (throw 'exit nil))
11800 (if (and (not (looking-at outline-regexp))
11801 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
11802 "[^\r\n]*"))
11803 (not (equal (match-string 1) org-clock-string)))
11804 (narrow-to-region (match-beginning 0) (match-end 0))
11805 (insert-before-markers "\n")
11806 (backward-char 1)
11807 (narrow-to-region (point) (point))
11808 (and org-adapt-indentation (org-indent-to-column col)))
11809 ;; Check if we have to remove something.
11810 (setq list (cons what remove))
11811 (while list
11812 (setq elt (pop list))
11813 (goto-char (point-min))
11814 (when (or (and (eq elt 'scheduled)
11815 (re-search-forward org-scheduled-time-regexp nil t))
11816 (and (eq elt 'deadline)
11817 (re-search-forward org-deadline-time-regexp nil t))
11818 (and (eq elt 'closed)
11819 (re-search-forward org-closed-time-regexp nil t)))
11820 (replace-match "")
11821 (if (looking-at "--+<[^>]+>") (replace-match ""))
11822 (skip-chars-backward " ")
11823 (if (looking-at " +") (replace-match ""))))
11824 (goto-char (point-max))
11825 (and org-adapt-indentation (bolp) (org-indent-to-column col))
11826 (when what
11827 (insert
11828 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
11829 (cond ((eq what 'scheduled) org-scheduled-string)
11830 ((eq what 'deadline) org-deadline-string)
11831 ((eq what 'closed) org-closed-string))
11832 " ")
11833 (setq ts (org-insert-time-stamp
11834 time
11835 (or org-time-was-given
11836 (and (eq what 'closed) org-log-done-with-time))
11837 (eq what 'closed)
11838 nil nil (list org-end-time-was-given)))
11839 (end-of-line 1))
11840 (goto-char (point-min))
11841 (widen)
11842 (if (and (looking-at "[ \t]*\n")
11843 (equal (char-before) ?\n))
11844 (delete-region (1- (point)) (point-at-eol)))
11845 ts))))))
11847 (defvar org-log-note-marker (make-marker))
11848 (defvar org-log-note-purpose nil)
11849 (defvar org-log-note-state nil)
11850 (defvar org-log-note-previous-state nil)
11851 (defvar org-log-note-how nil)
11852 (defvar org-log-note-extra nil)
11853 (defvar org-log-note-window-configuration nil)
11854 (defvar org-log-note-return-to (make-marker))
11855 (defvar org-log-post-message nil
11856 "Message to be displayed after a log note has been stored.
11857 The auto-repeater uses this.")
11859 (defun org-add-note ()
11860 "Add a note to the current entry.
11861 This is done in the same way as adding a state change note."
11862 (interactive)
11863 (org-add-log-setup 'note nil nil 'findpos nil))
11865 (defvar org-property-end-re)
11866 (defun org-add-log-setup (&optional purpose state prev-state
11867 findpos how extra)
11868 "Set up the post command hook to take a note.
11869 If this is about to TODO state change, the new state is expected in STATE.
11870 When FINDPOS is non-nil, find the correct position for the note in
11871 the current entry. If not, assume that it can be inserted at point.
11872 HOW is an indicator what kind of note should be created.
11873 EXTRA is additional text that will be inserted into the notes buffer."
11874 (let* ((org-log-into-drawer (org-log-into-drawer))
11875 (drawer (cond ((stringp org-log-into-drawer)
11876 org-log-into-drawer)
11877 (org-log-into-drawer "LOGBOOK")
11878 (t nil))))
11879 (save-restriction
11880 (save-excursion
11881 (when findpos
11882 (org-back-to-heading t)
11883 (narrow-to-region (point) (save-excursion
11884 (outline-next-heading) (point)))
11885 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
11886 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
11887 "[^\r\n]*\\)?"))
11888 (goto-char (match-end 0))
11889 (cond
11890 (drawer
11891 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
11892 nil t)
11893 (progn
11894 (goto-char (match-end 0))
11895 (or org-log-states-order-reversed
11896 (and (re-search-forward org-property-end-re nil t)
11897 (goto-char (1- (match-beginning 0))))))
11898 (insert "\n:" drawer ":\n:END:")
11899 (beginning-of-line 0)
11900 (org-indent-line-function)
11901 (beginning-of-line 2)
11902 (org-indent-line-function)
11903 (end-of-line 0)))
11904 ((and org-log-state-notes-insert-after-drawers
11905 (save-excursion
11906 (forward-line) (looking-at org-drawer-regexp)))
11907 (forward-line)
11908 (while (looking-at org-drawer-regexp)
11909 (goto-char (match-end 0))
11910 (re-search-forward org-property-end-re (point-max) t)
11911 (forward-line))
11912 (forward-line -1)))
11913 (unless org-log-states-order-reversed
11914 (and (= (char-after) ?\n) (forward-char 1))
11915 (org-skip-over-state-notes)
11916 (skip-chars-backward " \t\n\r")))
11917 (move-marker org-log-note-marker (point))
11918 (setq org-log-note-purpose purpose
11919 org-log-note-state state
11920 org-log-note-previous-state prev-state
11921 org-log-note-how how
11922 org-log-note-extra extra)
11923 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
11925 (defun org-skip-over-state-notes ()
11926 "Skip past the list of State notes in an entry."
11927 (if (looking-at "\n[ \t]*- State") (forward-char 1))
11928 (when (ignore-errors (goto-char (org-in-item-p)))
11929 (let* ((struct (org-list-struct))
11930 (prevs (org-list-prevs-alist struct)))
11931 (while (looking-at "[ \t]*- State")
11932 (goto-char (or (org-list-get-next-item (point) struct prevs)
11933 (org-list-get-item-end (point) struct)))))))
11935 (defun org-add-log-note (&optional purpose)
11936 "Pop up a window for taking a note, and add this note later at point."
11937 (remove-hook 'post-command-hook 'org-add-log-note)
11938 (setq org-log-note-window-configuration (current-window-configuration))
11939 (delete-other-windows)
11940 (move-marker org-log-note-return-to (point))
11941 (switch-to-buffer (marker-buffer org-log-note-marker))
11942 (goto-char org-log-note-marker)
11943 (org-switch-to-buffer-other-window "*Org Note*")
11944 (erase-buffer)
11945 (if (memq org-log-note-how '(time state))
11946 (let (current-prefix-arg) (org-store-log-note))
11947 (let ((org-inhibit-startup t)) (org-mode))
11948 (insert (format "# Insert note for %s.
11949 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
11950 (cond
11951 ((eq org-log-note-purpose 'clock-out) "stopped clock")
11952 ((eq org-log-note-purpose 'done) "closed todo item")
11953 ((eq org-log-note-purpose 'state)
11954 (format "state change from \"%s\" to \"%s\""
11955 (or org-log-note-previous-state "")
11956 (or org-log-note-state "")))
11957 ((eq org-log-note-purpose 'reschedule)
11958 "rescheduling")
11959 ((eq org-log-note-purpose 'delschedule)
11960 "no longer scheduled")
11961 ((eq org-log-note-purpose 'redeadline)
11962 "changing deadline")
11963 ((eq org-log-note-purpose 'deldeadline)
11964 "removing deadline")
11965 ((eq org-log-note-purpose 'refile)
11966 "refiling")
11967 ((eq org-log-note-purpose 'note)
11968 "this entry")
11969 (t (error "This should not happen")))))
11970 (if org-log-note-extra (insert org-log-note-extra))
11971 (org-set-local 'org-finish-function 'org-store-log-note)))
11973 (defvar org-note-abort nil) ; dynamically scoped
11974 (defun org-store-log-note ()
11975 "Finish taking a log note, and insert it to where it belongs."
11976 (let ((txt (buffer-string))
11977 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
11978 lines ind bul)
11979 (kill-buffer (current-buffer))
11980 (while (string-match "\\`#.*\n[ \t\n]*" txt)
11981 (setq txt (replace-match "" t t txt)))
11982 (if (string-match "\\s-+\\'" txt)
11983 (setq txt (replace-match "" t t txt)))
11984 (setq lines (org-split-string txt "\n"))
11985 (when (and note (string-match "\\S-" note))
11986 (setq note
11987 (org-replace-escapes
11988 note
11989 (list (cons "%u" (user-login-name))
11990 (cons "%U" user-full-name)
11991 (cons "%t" (format-time-string
11992 (org-time-stamp-format 'long 'inactive)
11993 (current-time)))
11994 (cons "%T" (format-time-string
11995 (org-time-stamp-format 'long nil)
11996 (current-time)))
11997 (cons "%s" (if org-log-note-state
11998 (concat "\"" org-log-note-state "\"")
11999 ""))
12000 (cons "%S" (if org-log-note-previous-state
12001 (concat "\"" org-log-note-previous-state "\"")
12002 "\"\"")))))
12003 (if lines (setq note (concat note " \\\\")))
12004 (push note lines))
12005 (when (or current-prefix-arg org-note-abort)
12006 (when org-log-into-drawer
12007 (org-remove-empty-drawer-at
12008 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12009 org-log-note-marker))
12010 (setq lines nil))
12011 (when lines
12012 (with-current-buffer (marker-buffer org-log-note-marker)
12013 (save-excursion
12014 (goto-char org-log-note-marker)
12015 (move-marker org-log-note-marker nil)
12016 (end-of-line 1)
12017 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12018 (setq ind (save-excursion
12019 (if (ignore-errors (goto-char (org-in-item-p)))
12020 (let ((struct (org-list-struct)))
12021 (org-list-get-ind
12022 (org-list-get-top-point struct) struct))
12023 (skip-chars-backward " \r\t\n")
12024 (cond
12025 ((and (org-at-heading-p)
12026 org-adapt-indentation)
12027 (1+ (org-current-level)))
12028 ((org-at-heading-p) 0)
12029 (t (org-get-indentation))))))
12030 (setq bul (org-list-bullet-string "-"))
12031 (org-indent-line-to ind)
12032 (insert bul (pop lines))
12033 (let ((ind-body (+ (length bul) ind)))
12034 (while lines
12035 (insert "\n")
12036 (org-indent-line-to ind-body)
12037 (insert (pop lines))))
12038 (message "Note stored")
12039 (org-back-to-heading t)
12040 (org-cycle-hide-drawers 'children)))))
12041 (set-window-configuration org-log-note-window-configuration)
12042 (with-current-buffer (marker-buffer org-log-note-return-to)
12043 (goto-char org-log-note-return-to))
12044 (move-marker org-log-note-return-to nil)
12045 (and org-log-post-message (message "%s" org-log-post-message)))
12047 (defun org-remove-empty-drawer-at (drawer pos)
12048 "Remove an empty drawer DRAWER at position POS.
12049 POS may also be a marker."
12050 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12051 (save-excursion
12052 (save-restriction
12053 (widen)
12054 (goto-char pos)
12055 (if (org-in-regexp
12056 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12057 (replace-match ""))))))
12059 (defun org-sparse-tree (&optional arg)
12060 "Create a sparse tree, prompt for the details.
12061 This command can create sparse trees. You first need to select the type
12062 of match used to create the tree:
12064 t Show all TODO entries.
12065 T Show entries with a specific TODO keyword.
12066 m Show entries selected by a tags/property match.
12067 p Enter a property name and its value (both with completion on existing
12068 names/values) and show entries with that property.
12069 r Show entries matching a regular expression (`/' can be used as well)
12070 d Show deadlines due within `org-deadline-warning-days'.
12071 b Show deadlines and scheduled items before a date.
12072 a Show deadlines and scheduled items after a date."
12073 (interactive "P")
12074 (let (ans kwd value)
12075 (message "Sparse tree: [r]egexp [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty\n [d]eadlines [b]efore-date [a]fter-date")
12076 (setq ans (read-char-exclusive))
12077 (cond
12078 ((equal ans ?d)
12079 (call-interactively 'org-check-deadlines))
12080 ((equal ans ?b)
12081 (call-interactively 'org-check-before-date))
12082 ((equal ans ?a)
12083 (call-interactively 'org-check-after-date))
12084 ((equal ans ?t)
12085 (org-show-todo-tree nil))
12086 ((equal ans ?T)
12087 (org-show-todo-tree '(4)))
12088 ((member ans '(?T ?m))
12089 (call-interactively 'org-match-sparse-tree))
12090 ((member ans '(?p ?P))
12091 (setq kwd (org-icompleting-read "Property: "
12092 (mapcar 'list (org-buffer-property-keys))))
12093 (setq value (org-icompleting-read "Value: "
12094 (mapcar 'list (org-property-values kwd))))
12095 (unless (string-match "\\`{.*}\\'" value)
12096 (setq value (concat "\"" value "\"")))
12097 (org-match-sparse-tree arg (concat kwd "=" value)))
12098 ((member ans '(?r ?R ?/))
12099 (call-interactively 'org-occur))
12100 (t (error "No such sparse tree command \"%c\"" ans)))))
12102 (defvar org-occur-highlights nil
12103 "List of overlays used for occur matches.")
12104 (make-variable-buffer-local 'org-occur-highlights)
12105 (defvar org-occur-parameters nil
12106 "Parameters of the active org-occur calls.
12107 This is a list, each call to org-occur pushes as cons cell,
12108 containing the regular expression and the callback, onto the list.
12109 The list can contain several entries if `org-occur' has been called
12110 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12111 will only contain one set of parameters. When the highlights are
12112 removed (for example with `C-c C-c', or with the next edit (depending
12113 on `org-remove-highlights-with-change'), this variable is emptied
12114 as well.")
12115 (make-variable-buffer-local 'org-occur-parameters)
12117 (defun org-occur (regexp &optional keep-previous callback)
12118 "Make a compact tree which shows all matches of REGEXP.
12119 The tree will show the lines where the regexp matches, and all higher
12120 headlines above the match. It will also show the heading after the match,
12121 to make sure editing the matching entry is easy.
12122 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12123 call to `org-occur' will be kept, to allow stacking of calls to this
12124 command.
12125 If CALLBACK is non-nil, it is a function which is called to confirm
12126 that the match should indeed be shown."
12127 (interactive "sRegexp: \nP")
12128 (when (equal regexp "")
12129 (error "Regexp cannot be empty"))
12130 (unless keep-previous
12131 (org-remove-occur-highlights nil nil t))
12132 (push (cons regexp callback) org-occur-parameters)
12133 (let ((cnt 0))
12134 (save-excursion
12135 (goto-char (point-min))
12136 (if (or (not keep-previous) ; do not want to keep
12137 (not org-occur-highlights)) ; no previous matches
12138 ;; hide everything
12139 (org-overview))
12140 (while (re-search-forward regexp nil t)
12141 (when (or (not callback)
12142 (save-match-data (funcall callback)))
12143 (setq cnt (1+ cnt))
12144 (when org-highlight-sparse-tree-matches
12145 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12146 (org-show-context 'occur-tree))))
12147 (when org-remove-highlights-with-change
12148 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12149 nil 'local))
12150 (unless org-sparse-tree-open-archived-trees
12151 (org-hide-archived-subtrees (point-min) (point-max)))
12152 (run-hooks 'org-occur-hook)
12153 (if (interactive-p)
12154 (message "%d match(es) for regexp %s" cnt regexp))
12155 cnt))
12157 (defun org-occur-next-match (&optional n reset)
12158 "Function for `next-error-function' to find sparse tree matches.
12159 N is the number of matches to move, when negative move backwards.
12160 RESET is entirely ignored - this function always goes back to the
12161 starting point when no match is found."
12162 (let* ((limit (if (< n 0) (point-min) (point-max)))
12163 (search-func (if (< n 0)
12164 'previous-single-char-property-change
12165 'next-single-char-property-change))
12166 (n (abs n))
12167 (pos (point))
12169 (catch 'exit
12170 (while (setq p1 (funcall search-func (point) 'org-type))
12171 (when (equal p1 limit)
12172 (goto-char pos)
12173 (error "No more matches"))
12174 (when (equal (get-char-property p1 'org-type) 'org-occur)
12175 (setq n (1- n))
12176 (when (= n 0)
12177 (goto-char p1)
12178 (throw 'exit (point))))
12179 (goto-char p1))
12180 (goto-char p1)
12181 (error "No more matches"))))
12183 (defun org-show-context (&optional key)
12184 "Make sure point and context are visible.
12185 How much context is shown depends upon the variables
12186 `org-show-hierarchy-above', `org-show-following-heading'. and
12187 `org-show-siblings'."
12188 (let ((heading-p (org-on-heading-p t))
12189 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12190 (following-p (org-get-alist-option org-show-following-heading key))
12191 (entry-p (org-get-alist-option org-show-entry-below key))
12192 (siblings-p (org-get-alist-option org-show-siblings key)))
12193 (catch 'exit
12194 ;; Show heading or entry text
12195 (if (and heading-p (not entry-p))
12196 (org-flag-heading nil) ; only show the heading
12197 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12198 (org-show-hidden-entry))) ; show entire entry
12199 (when following-p
12200 ;; Show next sibling, or heading below text
12201 (save-excursion
12202 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12203 (org-flag-heading nil))))
12204 (when siblings-p (org-show-siblings))
12205 (when hierarchy-p
12206 ;; show all higher headings, possibly with siblings
12207 (save-excursion
12208 (while (and (condition-case nil
12209 (progn (org-up-heading-all 1) t)
12210 (error nil))
12211 (not (bobp)))
12212 (org-flag-heading nil)
12213 (when siblings-p (org-show-siblings))))))))
12215 (defvar org-reveal-start-hook nil
12216 "Hook run before revealing a location.")
12218 (defun org-reveal (&optional siblings)
12219 "Show current entry, hierarchy above it, and the following headline.
12220 This can be used to show a consistent set of context around locations
12221 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12222 not t for the search context.
12224 With optional argument SIBLINGS, on each level of the hierarchy all
12225 siblings are shown. This repairs the tree structure to what it would
12226 look like when opened with hierarchical calls to `org-cycle'.
12227 With double optional argument \\[universal-argument] \\[universal-argument], \
12228 go to the parent and show the
12229 entire tree."
12230 (interactive "P")
12231 (run-hooks 'org-reveal-start-hook)
12232 (let ((org-show-hierarchy-above t)
12233 (org-show-following-heading t)
12234 (org-show-siblings (if siblings t org-show-siblings)))
12235 (org-show-context nil))
12236 (when (equal siblings '(16))
12237 (save-excursion
12238 (when (org-up-heading-safe)
12239 (org-show-subtree)
12240 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12242 (defun org-highlight-new-match (beg end)
12243 "Highlight from BEG to END and mark the highlight is an occur headline."
12244 (let ((ov (make-overlay beg end)))
12245 (overlay-put ov 'face 'secondary-selection)
12246 (overlay-put ov 'org-type 'org-occur)
12247 (push ov org-occur-highlights)))
12249 (defun org-remove-occur-highlights (&optional beg end noremove)
12250 "Remove the occur highlights from the buffer.
12251 BEG and END are ignored. If NOREMOVE is nil, remove this function
12252 from the `before-change-functions' in the current buffer."
12253 (interactive)
12254 (unless org-inhibit-highlight-removal
12255 (mapc 'delete-overlay org-occur-highlights)
12256 (setq org-occur-highlights nil)
12257 (setq org-occur-parameters nil)
12258 (unless noremove
12259 (remove-hook 'before-change-functions
12260 'org-remove-occur-highlights 'local))))
12262 ;;;; Priorities
12264 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12265 "Regular expression matching the priority indicator.")
12267 (defvar org-remove-priority-next-time nil)
12269 (defun org-priority-up ()
12270 "Increase the priority of the current item."
12271 (interactive)
12272 (org-priority 'up))
12274 (defun org-priority-down ()
12275 "Decrease the priority of the current item."
12276 (interactive)
12277 (org-priority 'down))
12279 (defun org-priority (&optional action)
12280 "Change the priority of an item by ARG.
12281 ACTION can be `set', `up', `down', or a character."
12282 (interactive)
12283 (unless org-enable-priority-commands
12284 (error "Priority commands are disabled"))
12285 (setq action (or action 'set))
12286 (let (current new news have remove)
12287 (save-excursion
12288 (org-back-to-heading t)
12289 (if (looking-at org-priority-regexp)
12290 (setq current (string-to-char (match-string 2))
12291 have t)
12292 (setq current org-default-priority))
12293 (cond
12294 ((eq action 'remove)
12295 (setq remove t new ?\ ))
12296 ((or (eq action 'set)
12297 (if (featurep 'xemacs) (characterp action) (integerp action)))
12298 (if (not (eq action 'set))
12299 (setq new action)
12300 (message "Priority %c-%c, SPC to remove: "
12301 org-highest-priority org-lowest-priority)
12302 (save-match-data
12303 (setq new (read-char-exclusive))))
12304 (if (and (= (upcase org-highest-priority) org-highest-priority)
12305 (= (upcase org-lowest-priority) org-lowest-priority))
12306 (setq new (upcase new)))
12307 (cond ((equal new ?\ ) (setq remove t))
12308 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12309 (error "Priority must be between `%c' and `%c'"
12310 org-highest-priority org-lowest-priority))))
12311 ((eq action 'up)
12312 (if (and (not have) (eq last-command this-command))
12313 (setq new org-lowest-priority)
12314 (setq new (if (and org-priority-start-cycle-with-default (not have))
12315 org-default-priority (1- current)))
12316 (when (< (upcase new) org-highest-priority)
12317 (error
12318 "See `org-default-priority' for range limit exceeded here"))))
12319 ((eq action 'down)
12320 (if (and (not have) (eq last-command this-command))
12321 (setq new org-highest-priority)
12322 (setq new (if (and org-priority-start-cycle-with-default (not have))
12323 org-default-priority (1+ current)))
12324 (when (> (upcase new) org-lowest-priority)
12325 (error
12326 "See `org-default-priority' for range limit exceeded here"))))
12327 (t (error "Invalid action")))
12328 (if (or (< (upcase new) org-highest-priority)
12329 (> (upcase new) org-lowest-priority))
12330 (setq remove t))
12331 (setq news (format "%c" new))
12332 (if have
12333 (if remove
12334 (replace-match "" t t nil 1)
12335 (replace-match news t t nil 2))
12336 (if remove
12337 (error "No priority cookie found in line")
12338 (let ((case-fold-search nil))
12339 (looking-at org-todo-line-regexp))
12340 (if (match-end 2)
12341 (progn
12342 (goto-char (match-end 2))
12343 (insert " [#" news "]"))
12344 (goto-char (match-beginning 3))
12345 (insert "[#" news "] "))))
12346 (org-preserve-lc (org-set-tags nil 'align)))
12347 (if remove
12348 (message "Priority removed")
12349 (message "Priority of current item set to %s" news))))
12351 (defun org-get-priority (s)
12352 "Find priority cookie and return priority."
12353 (if (functionp org-get-priority-function)
12354 (funcall org-get-priority-function)
12355 (save-match-data
12356 (if (not (string-match org-priority-regexp s))
12357 (* 1000 (- org-lowest-priority org-default-priority))
12358 (* 1000 (- org-lowest-priority
12359 (string-to-char (match-string 2 s))))))))
12361 ;;;; Tags
12363 (defvar org-agenda-archives-mode)
12364 (defvar org-map-continue-from nil
12365 "Position from where mapping should continue.
12366 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
12368 (defvar org-scanner-tags nil
12369 "The current tag list while the tags scanner is running.")
12370 (defvar org-trust-scanner-tags nil
12371 "Should `org-get-tags-at' use the tags for the scanner.
12372 This is for internal dynamical scoping only.
12373 When this is non-nil, the function `org-get-tags-at' will return the value
12374 of `org-scanner-tags' instead of building the list by itself. This
12375 can lead to large speed-ups when the tags scanner is used in a file with
12376 many entries, and when the list of tags is retrieved, for example to
12377 obtain a list of properties. Building the tags list for each entry in such
12378 a file becomes an N^2 operation - but with this variable set, it scales
12379 as N.")
12381 (defun org-scan-tags (action matcher &optional todo-only)
12382 "Scan headline tags with inheritance and produce output ACTION.
12384 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12385 or `agenda' to produce an entry list for an agenda view. It can also be
12386 a Lisp form or a function that should be called at each matched headline, in
12387 this case the return value is a list of all return values from these calls.
12389 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12390 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12391 only lines with a TODO keyword are included in the output."
12392 (require 'org-agenda)
12393 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
12394 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12395 (org-re
12396 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
12397 (props (list 'face 'default
12398 'done-face 'org-agenda-done
12399 'undone-face 'default
12400 'mouse-face 'highlight
12401 'org-not-done-regexp org-not-done-regexp
12402 'org-todo-regexp org-todo-regexp
12403 'help-echo
12404 (format "mouse-2 or RET jump to org file %s"
12405 (abbreviate-file-name
12406 (or (buffer-file-name (buffer-base-buffer))
12407 (buffer-name (buffer-base-buffer)))))))
12408 (case-fold-search nil)
12409 (org-map-continue-from nil)
12410 lspos tags tags-list
12411 (tags-alist (list (cons 0 org-file-tags)))
12412 (llast 0) rtn rtn1 level category i txt
12413 todo marker entry priority)
12414 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12415 (setq action (list 'lambda nil action)))
12416 (save-excursion
12417 (goto-char (point-min))
12418 (when (eq action 'sparse-tree)
12419 (org-overview)
12420 (org-remove-occur-highlights))
12421 (while (re-search-forward re nil t)
12422 (catch :skip
12423 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12424 tags (if (match-end 4) (org-match-string-no-properties 4)))
12425 (goto-char (setq lspos (match-beginning 0)))
12426 (setq level (org-reduced-level (funcall outline-level))
12427 category (org-get-category))
12428 (setq i llast llast level)
12429 ;; remove tag lists from same and sublevels
12430 (while (>= i level)
12431 (when (setq entry (assoc i tags-alist))
12432 (setq tags-alist (delete entry tags-alist)))
12433 (setq i (1- i)))
12434 ;; add the next tags
12435 (when tags
12436 (setq tags (org-split-string tags ":")
12437 tags-alist
12438 (cons (cons level tags) tags-alist)))
12439 ;; compile tags for current headline
12440 (setq tags-list
12441 (if org-use-tag-inheritance
12442 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12443 tags)
12444 org-scanner-tags tags-list)
12445 (when org-use-tag-inheritance
12446 (setcdr (car tags-alist)
12447 (mapcar (lambda (x)
12448 (setq x (copy-sequence x))
12449 (org-add-prop-inherited x))
12450 (cdar tags-alist))))
12451 (when (and tags org-use-tag-inheritance
12452 (or (not (eq t org-use-tag-inheritance))
12453 org-tags-exclude-from-inheritance))
12454 ;; selective inheritance, remove uninherited ones
12455 (setcdr (car tags-alist)
12456 (org-remove-uninherited-tags (cdar tags-alist))))
12457 (when (and
12459 ;; eval matcher only when the todo condition is OK
12460 (and (or (not todo-only) (member todo org-not-done-keywords))
12461 (let ((case-fold-search t)) (eval matcher)))
12463 ;; Call the skipper, but return t if it does not skip,
12464 ;; so that the `and' form continues evaluating
12465 (progn
12466 (unless (eq action 'sparse-tree) (org-agenda-skip))
12469 ;; Check if timestamps are deselecting this entry
12470 (or (not todo-only)
12471 (and (member todo org-not-done-keywords)
12472 (or (not org-agenda-tags-todo-honor-ignore-options)
12473 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
12475 ;; Extra check for the archive tag
12476 ;; FIXME: Does the skipper already do this????
12478 (not (member org-archive-tag tags-list))
12479 ;; we have an archive tag, should we use this anyway?
12480 (or (not org-agenda-skip-archived-trees)
12481 (and (eq action 'agenda) org-agenda-archives-mode))))
12483 ;; select this headline
12485 (cond
12486 ((eq action 'sparse-tree)
12487 (and org-highlight-sparse-tree-matches
12488 (org-get-heading) (match-end 0)
12489 (org-highlight-new-match
12490 (match-beginning 0) (match-beginning 1)))
12491 (org-show-context 'tags-tree))
12492 ((eq action 'agenda)
12493 (setq txt (org-format-agenda-item
12495 (concat
12496 (if (eq org-tags-match-list-sublevels 'indented)
12497 (make-string (1- level) ?.) "")
12498 (org-get-heading))
12499 category
12500 tags-list
12502 priority (org-get-priority txt))
12503 (goto-char lspos)
12504 (setq marker (org-agenda-new-marker))
12505 (org-add-props txt props
12506 'org-marker marker 'org-hd-marker marker 'org-category category
12507 'todo-state todo
12508 'priority priority 'type "tagsmatch")
12509 (push txt rtn))
12510 ((functionp action)
12511 (setq org-map-continue-from nil)
12512 (save-excursion
12513 (setq rtn1 (funcall action))
12514 (push rtn1 rtn)))
12515 (t (error "Invalid action")))
12517 ;; if we are to skip sublevels, jump to end of subtree
12518 (unless org-tags-match-list-sublevels
12519 (org-end-of-subtree t)
12520 (backward-char 1))))
12521 ;; Get the correct position from where to continue
12522 (if org-map-continue-from
12523 (goto-char org-map-continue-from)
12524 (and (= (point) lspos) (end-of-line 1)))))
12525 (when (and (eq action 'sparse-tree)
12526 (not org-sparse-tree-open-archived-trees))
12527 (org-hide-archived-subtrees (point-min) (point-max)))
12528 (nreverse rtn)))
12530 (defun org-remove-uninherited-tags (tags)
12531 "Remove all tags that are not inherited from the list TAGS."
12532 (cond
12533 ((eq org-use-tag-inheritance t)
12534 (if org-tags-exclude-from-inheritance
12535 (org-delete-all org-tags-exclude-from-inheritance tags)
12536 tags))
12537 ((not org-use-tag-inheritance) nil)
12538 ((stringp org-use-tag-inheritance)
12539 (delq nil (mapcar
12540 (lambda (x)
12541 (if (and (string-match org-use-tag-inheritance x)
12542 (not (member x org-tags-exclude-from-inheritance)))
12543 x nil))
12544 tags)))
12545 ((listp org-use-tag-inheritance)
12546 (delq nil (mapcar
12547 (lambda (x)
12548 (if (member x org-use-tag-inheritance) x nil))
12549 tags)))))
12551 (defvar todo-only) ;; dynamically scoped
12553 (defun org-match-sparse-tree (&optional todo-only match)
12554 "Create a sparse tree according to tags string MATCH.
12555 MATCH can contain positive and negative selection of tags, like
12556 \"+WORK+URGENT-WITHBOSS\".
12557 If optional argument TODO-ONLY is non-nil, only select lines that are
12558 also TODO lines."
12559 (interactive "P")
12560 (org-prepare-agenda-buffers (list (current-buffer)))
12561 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
12563 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
12565 (defvar org-cached-props nil)
12566 (defun org-cached-entry-get (pom property)
12567 (if (or (eq t org-use-property-inheritance)
12568 (and (stringp org-use-property-inheritance)
12569 (string-match org-use-property-inheritance property))
12570 (and (listp org-use-property-inheritance)
12571 (member property org-use-property-inheritance)))
12572 ;; Caching is not possible, check it directly
12573 (org-entry-get pom property 'inherit)
12574 ;; Get all properties, so that we can do complicated checks easily
12575 (cdr (assoc property (or org-cached-props
12576 (setq org-cached-props
12577 (org-entry-properties pom)))))))
12579 (defun org-global-tags-completion-table (&optional files)
12580 "Return the list of all tags in all agenda buffer/files.
12581 Optional FILES argument is a list of files to which can be used
12582 instead of the agenda files."
12583 (save-excursion
12584 (org-uniquify
12585 (delq nil
12586 (apply 'append
12587 (mapcar
12588 (lambda (file)
12589 (set-buffer (find-file-noselect file))
12590 (append (org-get-buffer-tags)
12591 (mapcar (lambda (x) (if (stringp (car-safe x))
12592 (list (car-safe x)) nil))
12593 org-tag-alist)))
12594 (if (and files (car files))
12595 files
12596 (org-agenda-files))))))))
12598 (defun org-make-tags-matcher (match)
12599 "Create the TAGS/TODO matcher form for the selection string MATCH."
12600 ;; todo-only is scoped dynamically into this function, and the function
12601 ;; may change it if the matcher asks for it.
12602 (unless match
12603 ;; Get a new match request, with completion
12604 (let ((org-last-tags-completion-table
12605 (org-global-tags-completion-table)))
12606 (setq match (org-completing-read-no-i
12607 "Match: " 'org-tags-completion-function nil nil nil
12608 'org-tags-history))))
12610 ;; Parse the string and create a lisp form
12611 (let ((match0 match)
12612 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
12613 minus tag mm
12614 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
12615 orterms term orlist re-p str-p level-p level-op time-p
12616 prop-p pn pv po gv rest)
12617 (if (string-match "/+" match)
12618 ;; match contains also a todo-matching request
12619 (progn
12620 (setq tagsmatch (substring match 0 (match-beginning 0))
12621 todomatch (substring match (match-end 0)))
12622 (if (string-match "^!" todomatch)
12623 (setq todo-only t todomatch (substring todomatch 1)))
12624 (if (string-match "^\\s-*$" todomatch)
12625 (setq todomatch nil)))
12626 ;; only matching tags
12627 (setq tagsmatch match todomatch nil))
12629 ;; Make the tags matcher
12630 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
12631 (setq tagsmatcher t)
12632 (setq orterms (org-split-string tagsmatch "|") orlist nil)
12633 (while (setq term (pop orterms))
12634 (while (and (equal (substring term -1) "\\") orterms)
12635 (setq term (concat term "|" (pop orterms)))) ; repair bad split
12636 (while (string-match re term)
12637 (setq rest (substring term (match-end 0))
12638 minus (and (match-end 1)
12639 (equal (match-string 1 term) "-"))
12640 tag (save-match-data (replace-regexp-in-string
12641 "\\\\-" "-"
12642 (match-string 2 term)))
12643 re-p (equal (string-to-char tag) ?{)
12644 level-p (match-end 4)
12645 prop-p (match-end 5)
12646 mm (cond
12647 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
12648 (level-p
12649 (setq level-op (org-op-to-function (match-string 3 term)))
12650 `(,level-op level ,(string-to-number
12651 (match-string 4 term))))
12652 (prop-p
12653 (setq pn (match-string 5 term)
12654 po (match-string 6 term)
12655 pv (match-string 7 term)
12656 re-p (equal (string-to-char pv) ?{)
12657 str-p (equal (string-to-char pv) ?\")
12658 time-p (save-match-data
12659 (string-match "^\"[[<].*[]>]\"$" pv))
12660 pv (if (or re-p str-p) (substring pv 1 -1) pv))
12661 (if time-p (setq pv (org-matcher-time pv)))
12662 (setq po (org-op-to-function po (if time-p 'time str-p)))
12663 (cond
12664 ((equal pn "CATEGORY")
12665 (setq gv '(get-text-property (point) 'org-category)))
12666 ((equal pn "TODO")
12667 (setq gv 'todo))
12669 (setq gv `(org-cached-entry-get nil ,pn))))
12670 (if re-p
12671 (if (eq po 'org<>)
12672 `(not (string-match ,pv (or ,gv "")))
12673 `(string-match ,pv (or ,gv "")))
12674 (if str-p
12675 `(,po (or ,gv "") ,pv)
12676 `(,po (string-to-number (or ,gv ""))
12677 ,(string-to-number pv) ))))
12678 (t `(member ,tag tags-list)))
12679 mm (if minus (list 'not mm) mm)
12680 term rest)
12681 (push mm tagsmatcher))
12682 (push (if (> (length tagsmatcher) 1)
12683 (cons 'and tagsmatcher)
12684 (car tagsmatcher))
12685 orlist)
12686 (setq tagsmatcher nil))
12687 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
12688 (setq tagsmatcher
12689 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
12690 ;; Make the todo matcher
12691 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
12692 (setq todomatcher t)
12693 (setq orterms (org-split-string todomatch "|") orlist nil)
12694 (while (setq term (pop orterms))
12695 (while (string-match re term)
12696 (setq minus (and (match-end 1)
12697 (equal (match-string 1 term) "-"))
12698 kwd (match-string 2 term)
12699 re-p (equal (string-to-char kwd) ?{)
12700 term (substring term (match-end 0))
12701 mm (if re-p
12702 `(string-match ,(substring kwd 1 -1) todo)
12703 (list 'equal 'todo kwd))
12704 mm (if minus (list 'not mm) mm))
12705 (push mm todomatcher))
12706 (push (if (> (length todomatcher) 1)
12707 (cons 'and todomatcher)
12708 (car todomatcher))
12709 orlist)
12710 (setq todomatcher nil))
12711 (setq todomatcher (if (> (length orlist) 1)
12712 (cons 'or orlist) (car orlist))))
12714 ;; Return the string and lisp forms of the matcher
12715 (setq matcher (if todomatcher
12716 (list 'and tagsmatcher todomatcher)
12717 tagsmatcher))
12718 (cons match0 matcher)))
12720 (defun org-op-to-function (op &optional stringp)
12721 "Turn an operator into the appropriate function."
12722 (setq op
12723 (cond
12724 ((equal op "<" ) '(< string< org-time<))
12725 ((equal op ">" ) '(> org-string> org-time>))
12726 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
12727 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
12728 ((member op '("=" "==")) '(= string= org-time=))
12729 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
12730 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
12732 (defun org<> (a b) (not (= a b)))
12733 (defun org-string<= (a b) (or (string= a b) (string< a b)))
12734 (defun org-string>= (a b) (not (string< a b)))
12735 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
12736 (defun org-string<> (a b) (not (string= a b)))
12737 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
12738 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
12739 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
12740 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
12741 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
12742 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
12743 (defun org-2ft (s)
12744 "Convert S to a floating point time.
12745 If S is already a number, just return it. If it is a string, parse
12746 it as a time string and apply `float-time' to it. If S is nil, just return 0."
12747 (cond
12748 ((numberp s) s)
12749 ((stringp s)
12750 (condition-case nil
12751 (float-time (apply 'encode-time (org-parse-time-string s)))
12752 (error 0.)))
12753 (t 0.)))
12755 (defun org-time-today ()
12756 "Time in seconds today at 0:00.
12757 Returns the float number of seconds since the beginning of the
12758 epoch to the beginning of today (00:00)."
12759 (float-time (apply 'encode-time
12760 (append '(0 0 0) (nthcdr 3 (decode-time))))))
12762 (defun org-matcher-time (s)
12763 "Interpret a time comparison value."
12764 (save-match-data
12765 (cond
12766 ((string= s "<now>") (float-time))
12767 ((string= s "<today>") (org-time-today))
12768 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
12769 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
12770 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
12771 (+ (org-time-today)
12772 (* (string-to-number (match-string 1 s))
12773 (cdr (assoc (match-string 2 s)
12774 '(("d" . 86400.0) ("w" . 604800.0)
12775 ("m" . 2678400.0) ("y" . 31557600.0)))))))
12776 (t (org-2ft s)))))
12778 (defun org-match-any-p (re list)
12779 "Does re match any element of list?"
12780 (setq list (mapcar (lambda (x) (string-match re x)) list))
12781 (delq nil list))
12783 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
12784 (defvar org-tags-overlay (make-overlay 1 1))
12785 (org-detach-overlay org-tags-overlay)
12787 (defun org-get-local-tags-at (&optional pos)
12788 "Get a list of tags defined in the current headline."
12789 (org-get-tags-at pos 'local))
12791 (defun org-get-local-tags ()
12792 "Get a list of tags defined in the current headline."
12793 (org-get-tags-at nil 'local))
12795 (defun org-get-tags-at (&optional pos local)
12796 "Get a list of all headline tags applicable at POS.
12797 POS defaults to point. If tags are inherited, the list contains
12798 the targets in the same sequence as the headlines appear, i.e.
12799 the tags of the current headline come last.
12800 When LOCAL is non-nil, only return tags from the current headline,
12801 ignore inherited ones."
12802 (interactive)
12803 (if (and org-trust-scanner-tags
12804 (or (not pos) (equal pos (point)))
12805 (not local))
12806 org-scanner-tags
12807 (let (tags ltags lastpos parent)
12808 (save-excursion
12809 (save-restriction
12810 (widen)
12811 (goto-char (or pos (point)))
12812 (save-match-data
12813 (catch 'done
12814 (condition-case nil
12815 (progn
12816 (org-back-to-heading t)
12817 (while (not (equal lastpos (point)))
12818 (setq lastpos (point))
12819 (when (looking-at
12820 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
12821 (setq ltags (org-split-string
12822 (org-match-string-no-properties 1) ":"))
12823 (when parent
12824 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
12825 (setq tags (append
12826 (if parent
12827 (org-remove-uninherited-tags ltags)
12828 ltags)
12829 tags)))
12830 (or org-use-tag-inheritance (throw 'done t))
12831 (if local (throw 'done t))
12832 (or (org-up-heading-safe) (error nil))
12833 (setq parent t)))
12834 (error nil)))))
12835 (if local
12836 tags
12837 (append (org-remove-uninherited-tags org-file-tags) tags))))))
12839 (defun org-add-prop-inherited (s)
12840 (add-text-properties 0 (length s) '(inherited t) s)
12843 (defun org-toggle-tag (tag &optional onoff)
12844 "Toggle the tag TAG for the current line.
12845 If ONOFF is `on' or `off', don't toggle but set to this state."
12846 (let (res current)
12847 (save-excursion
12848 (org-back-to-heading t)
12849 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
12850 (point-at-eol) t)
12851 (progn
12852 (setq current (match-string 1))
12853 (replace-match ""))
12854 (setq current ""))
12855 (setq current (nreverse (org-split-string current ":")))
12856 (cond
12857 ((eq onoff 'on)
12858 (setq res t)
12859 (or (member tag current) (push tag current)))
12860 ((eq onoff 'off)
12861 (or (not (member tag current)) (setq current (delete tag current))))
12862 (t (if (member tag current)
12863 (setq current (delete tag current))
12864 (setq res t)
12865 (push tag current))))
12866 (end-of-line 1)
12867 (if current
12868 (progn
12869 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
12870 (org-set-tags nil t))
12871 (delete-horizontal-space))
12872 (run-hooks 'org-after-tags-change-hook))
12873 res))
12875 (defun org-align-tags-here (to-col)
12876 ;; Assumes that this is a headline
12877 (let ((pos (point)) (col (current-column)) ncol tags-l p)
12878 (beginning-of-line 1)
12879 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
12880 (< pos (match-beginning 2)))
12881 (progn
12882 (setq tags-l (- (match-end 2) (match-beginning 2)))
12883 (goto-char (match-beginning 1))
12884 (insert " ")
12885 (delete-region (point) (1+ (match-beginning 2)))
12886 (setq ncol (max (1+ (current-column))
12887 (1+ col)
12888 (if (> to-col 0)
12889 to-col
12890 (- (abs to-col) tags-l))))
12891 (setq p (point))
12892 (insert (make-string (- ncol (current-column)) ?\ ))
12893 (setq ncol (current-column))
12894 (when indent-tabs-mode (tabify p (point-at-eol)))
12895 (org-move-to-column (min ncol col) t))
12896 (goto-char pos))))
12898 (defun org-set-tags-command (&optional arg just-align)
12899 "Call the set-tags command for the current entry."
12900 (interactive "P")
12901 (if (org-on-heading-p)
12902 (org-set-tags arg just-align)
12903 (save-excursion
12904 (org-back-to-heading t)
12905 (org-set-tags arg just-align))))
12907 (defun org-set-tags-to (data)
12908 "Set the tags of the current entry to DATA, replacing the current tags.
12909 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
12910 If DATA is nil or the empty string, any tags will be removed."
12911 (interactive "sTags: ")
12912 (setq data
12913 (cond
12914 ((eq data nil) "")
12915 ((equal data "") "")
12916 ((stringp data)
12917 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
12918 ":"))
12919 ((listp data)
12920 (concat ":" (mapconcat 'identity data ":") ":"))
12921 (t nil)))
12922 (when data
12923 (save-excursion
12924 (org-back-to-heading t)
12925 (when (looking-at org-complex-heading-regexp)
12926 (if (match-end 5)
12927 (progn
12928 (goto-char (match-beginning 5))
12929 (insert data)
12930 (delete-region (point) (point-at-eol))
12931 (org-set-tags nil 'align))
12932 (goto-char (point-at-eol))
12933 (insert " " data)
12934 (org-set-tags nil 'align)))
12935 (beginning-of-line 1)
12936 (if (looking-at ".*?\\([ \t]+\\)$")
12937 (delete-region (match-beginning 1) (match-end 1))))))
12939 (defun org-align-all-tags ()
12940 "Align the tags i all headings."
12941 (interactive)
12942 (save-excursion
12943 (or (ignore-errors (org-back-to-heading t))
12944 (outline-next-heading))
12945 (if (org-on-heading-p)
12946 (org-set-tags t)
12947 (message "No headings"))))
12949 (defvar org-indent-indentation-per-level)
12950 (defun org-set-tags (&optional arg just-align)
12951 "Set the tags for the current headline.
12952 With prefix ARG, realign all tags in headings in the current buffer."
12953 (interactive "P")
12954 (let* ((re (concat "^" outline-regexp))
12955 (current (org-get-tags-string))
12956 (col (current-column))
12957 (org-setting-tags t)
12958 table current-tags inherited-tags ; computed below when needed
12959 tags p0 c0 c1 rpl di tc level)
12960 (if arg
12961 (save-excursion
12962 (goto-char (point-min))
12963 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
12964 (while (re-search-forward re nil t)
12965 (org-set-tags nil t)
12966 (end-of-line 1)))
12967 (message "All tags realigned to column %d" org-tags-column))
12968 (if just-align
12969 (setq tags current)
12970 ;; Get a new set of tags from the user
12971 (save-excursion
12972 (setq table (append org-tag-persistent-alist
12973 (or org-tag-alist (org-get-buffer-tags))
12974 (and
12975 org-complete-tags-always-offer-all-agenda-tags
12976 (org-global-tags-completion-table
12977 (org-agenda-files))))
12978 org-last-tags-completion-table table
12979 current-tags (org-split-string current ":")
12980 inherited-tags (nreverse
12981 (nthcdr (length current-tags)
12982 (nreverse (org-get-tags-at))))
12983 tags
12984 (if (or (eq t org-use-fast-tag-selection)
12985 (and org-use-fast-tag-selection
12986 (delq nil (mapcar 'cdr table))))
12987 (org-fast-tag-selection
12988 current-tags inherited-tags table
12989 (if org-fast-tag-selection-include-todo
12990 org-todo-key-alist))
12991 (let ((org-add-colon-after-tag-completion t))
12992 (org-trim
12993 (org-without-partial-completion
12994 (org-icompleting-read "Tags: "
12995 'org-tags-completion-function
12996 nil nil current 'org-tags-history)))))))
12997 (while (string-match "[-+&]+" tags)
12998 ;; No boolean logic, just a list
12999 (setq tags (replace-match ":" t t tags))))
13001 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13003 (if org-tags-sort-function
13004 (setq tags (mapconcat 'identity
13005 (sort (org-split-string
13006 tags (org-re "[^[:alnum:]_@#%]+"))
13007 org-tags-sort-function) ":")))
13009 (if (string-match "\\`[\t ]*\\'" tags)
13010 (setq tags "")
13011 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13012 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13014 ;; Insert new tags at the correct column
13015 (beginning-of-line 1)
13016 (setq level (or (and (looking-at org-outline-regexp)
13017 (- (match-end 0) (point) 1))
13019 (cond
13020 ((and (equal current "") (equal tags "")))
13021 ((re-search-forward
13022 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13023 (point-at-eol) t)
13024 (if (equal tags "")
13025 (setq rpl "")
13026 (goto-char (match-beginning 0))
13027 (setq c0 (current-column)
13028 ;; compute offset for the case of org-indent-mode active
13029 di (if org-indent-mode
13030 (* (1- org-indent-indentation-per-level) (1- level))
13032 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13033 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13034 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13035 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13036 (replace-match rpl t t)
13037 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13038 tags)
13039 (t (error "Tags alignment failed")))
13040 (org-move-to-column col)
13041 (unless just-align
13042 (run-hooks 'org-after-tags-change-hook)))))
13044 (defun org-change-tag-in-region (beg end tag off)
13045 "Add or remove TAG for each entry in the region.
13046 This works in the agenda, and also in an org-mode buffer."
13047 (interactive
13048 (list (region-beginning) (region-end)
13049 (let ((org-last-tags-completion-table
13050 (if (org-mode-p)
13051 (org-get-buffer-tags)
13052 (org-global-tags-completion-table))))
13053 (org-icompleting-read
13054 "Tag: " 'org-tags-completion-function nil nil nil
13055 'org-tags-history))
13056 (progn
13057 (message "[s]et or [r]emove? ")
13058 (equal (read-char-exclusive) ?r))))
13059 (if (fboundp 'deactivate-mark) (deactivate-mark))
13060 (let ((agendap (equal major-mode 'org-agenda-mode))
13061 l1 l2 m buf pos newhead (cnt 0))
13062 (goto-char end)
13063 (setq l2 (1- (org-current-line)))
13064 (goto-char beg)
13065 (setq l1 (org-current-line))
13066 (loop for l from l1 to l2 do
13067 (org-goto-line l)
13068 (setq m (get-text-property (point) 'org-hd-marker))
13069 (when (or (and (org-mode-p) (org-on-heading-p))
13070 (and agendap m))
13071 (setq buf (if agendap (marker-buffer m) (current-buffer))
13072 pos (if agendap m (point)))
13073 (with-current-buffer buf
13074 (save-excursion
13075 (save-restriction
13076 (goto-char pos)
13077 (setq cnt (1+ cnt))
13078 (org-toggle-tag tag (if off 'off 'on))
13079 (setq newhead (org-get-heading)))))
13080 (and agendap (org-agenda-change-all-lines newhead m))))
13081 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13083 (defun org-tags-completion-function (string predicate &optional flag)
13084 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13085 (confirm (lambda (x) (stringp (car x)))))
13086 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13087 (setq s1 (match-string 1 string)
13088 s2 (match-string 2 string))
13089 (setq s1 "" s2 string))
13090 (cond
13091 ((eq flag nil)
13092 ;; try completion
13093 (setq rtn (try-completion s2 ctable confirm))
13094 (if (stringp rtn)
13095 (setq rtn
13096 (concat s1 s2 (substring rtn (length s2))
13097 (if (and org-add-colon-after-tag-completion
13098 (assoc rtn ctable))
13099 ":" ""))))
13100 rtn)
13101 ((eq flag t)
13102 ;; all-completions
13103 (all-completions s2 ctable confirm)
13105 ((eq flag 'lambda)
13106 ;; exact match?
13107 (assoc s2 ctable)))
13110 (defun org-fast-tag-insert (kwd tags face &optional end)
13111 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13112 (insert (format "%-12s" (concat kwd ":"))
13113 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13114 (or end "")))
13116 (defun org-fast-tag-show-exit (flag)
13117 (save-excursion
13118 (org-goto-line 3)
13119 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13120 (replace-match ""))
13121 (when flag
13122 (end-of-line 1)
13123 (org-move-to-column (- (window-width) 19) t)
13124 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13126 (defun org-set-current-tags-overlay (current prefix)
13127 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13128 (if (featurep 'xemacs)
13129 (org-overlay-display org-tags-overlay (concat prefix s)
13130 'secondary-selection)
13131 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13132 (org-overlay-display org-tags-overlay (concat prefix s)))))
13134 (defvar org-last-tag-selection-key nil)
13135 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13136 "Fast tag selection with single keys.
13137 CURRENT is the current list of tags in the headline, INHERITED is the
13138 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13139 possibly with grouping information. TODO-TABLE is a similar table with
13140 TODO keywords, should these have keys assigned to them.
13141 If the keys are nil, a-z are automatically assigned.
13142 Returns the new tags string, or nil to not change the current settings."
13143 (let* ((fulltable (append table todo-table))
13144 (maxlen (apply 'max (mapcar
13145 (lambda (x)
13146 (if (stringp (car x)) (string-width (car x)) 0))
13147 fulltable)))
13148 (buf (current-buffer))
13149 (expert (eq org-fast-tag-selection-single-key 'expert))
13150 (buffer-tags nil)
13151 (fwidth (+ maxlen 3 1 3))
13152 (ncol (/ (- (window-width) 4) fwidth))
13153 (i-face 'org-done)
13154 (c-face 'org-todo)
13155 tg cnt e c char c1 c2 ntable tbl rtn
13156 ov-start ov-end ov-prefix
13157 (exit-after-next org-fast-tag-selection-single-key)
13158 (done-keywords org-done-keywords)
13159 groups ingroup)
13160 (save-excursion
13161 (beginning-of-line 1)
13162 (if (looking-at
13163 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13164 (setq ov-start (match-beginning 1)
13165 ov-end (match-end 1)
13166 ov-prefix "")
13167 (setq ov-start (1- (point-at-eol))
13168 ov-end (1+ ov-start))
13169 (skip-chars-forward "^\n\r")
13170 (setq ov-prefix
13171 (concat
13172 (buffer-substring (1- (point)) (point))
13173 (if (> (current-column) org-tags-column)
13175 (make-string (- org-tags-column (current-column)) ?\ ))))))
13176 (move-overlay org-tags-overlay ov-start ov-end)
13177 (save-window-excursion
13178 (if expert
13179 (set-buffer (get-buffer-create " *Org tags*"))
13180 (delete-other-windows)
13181 (split-window-vertically)
13182 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13183 (erase-buffer)
13184 (org-set-local 'org-done-keywords done-keywords)
13185 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13186 (org-fast-tag-insert "Current" current c-face "\n\n")
13187 (org-fast-tag-show-exit exit-after-next)
13188 (org-set-current-tags-overlay current ov-prefix)
13189 (setq tbl fulltable char ?a cnt 0)
13190 (while (setq e (pop tbl))
13191 (cond
13192 ((equal (car e) :startgroup)
13193 (push '() groups) (setq ingroup t)
13194 (when (not (= cnt 0))
13195 (setq cnt 0)
13196 (insert "\n"))
13197 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13198 ((equal (car e) :endgroup)
13199 (setq ingroup nil cnt 0)
13200 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13201 ((equal e '(:newline))
13202 (when (not (= cnt 0))
13203 (setq cnt 0)
13204 (insert "\n")
13205 (setq e (car tbl))
13206 (while (equal (car tbl) '(:newline))
13207 (insert "\n")
13208 (setq tbl (cdr tbl)))))
13210 (setq tg (copy-sequence (car e)) c2 nil)
13211 (if (cdr e)
13212 (setq c (cdr e))
13213 ;; automatically assign a character.
13214 (setq c1 (string-to-char
13215 (downcase (substring
13216 tg (if (= (string-to-char tg) ?@) 1 0)))))
13217 (if (or (rassoc c1 ntable) (rassoc c1 table))
13218 (while (or (rassoc char ntable) (rassoc char table))
13219 (setq char (1+ char)))
13220 (setq c2 c1))
13221 (setq c (or c2 char)))
13222 (if ingroup (push tg (car groups)))
13223 (setq tg (org-add-props tg nil 'face
13224 (cond
13225 ((not (assoc tg table))
13226 (org-get-todo-face tg))
13227 ((member tg current) c-face)
13228 ((member tg inherited) i-face)
13229 (t nil))))
13230 (if (and (= cnt 0) (not ingroup)) (insert " "))
13231 (insert "[" c "] " tg (make-string
13232 (- fwidth 4 (length tg)) ?\ ))
13233 (push (cons tg c) ntable)
13234 (when (= (setq cnt (1+ cnt)) ncol)
13235 (insert "\n")
13236 (if ingroup (insert " "))
13237 (setq cnt 0)))))
13238 (setq ntable (nreverse ntable))
13239 (insert "\n")
13240 (goto-char (point-min))
13241 (if (not expert) (org-fit-window-to-buffer))
13242 (setq rtn
13243 (catch 'exit
13244 (while t
13245 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13246 (if (not groups) "no " "")
13247 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13248 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13249 (setq org-last-tag-selection-key c)
13250 (cond
13251 ((= c ?\r) (throw 'exit t))
13252 ((= c ?!)
13253 (setq groups (not groups))
13254 (goto-char (point-min))
13255 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13256 ((= c ?\C-c)
13257 (if (not expert)
13258 (org-fast-tag-show-exit
13259 (setq exit-after-next (not exit-after-next)))
13260 (setq expert nil)
13261 (delete-other-windows)
13262 (set-window-buffer (split-window-vertically) " *Org tags*")
13263 (org-switch-to-buffer-other-window " *Org tags*")
13264 (org-fit-window-to-buffer)))
13265 ((or (= c ?\C-g)
13266 (and (= c ?q) (not (rassoc c ntable))))
13267 (org-detach-overlay org-tags-overlay)
13268 (setq quit-flag t))
13269 ((= c ?\ )
13270 (setq current nil)
13271 (if exit-after-next (setq exit-after-next 'now)))
13272 ((= c ?\t)
13273 (condition-case nil
13274 (setq tg (org-icompleting-read
13275 "Tag: "
13276 (or buffer-tags
13277 (with-current-buffer buf
13278 (org-get-buffer-tags)))))
13279 (quit (setq tg "")))
13280 (when (string-match "\\S-" tg)
13281 (add-to-list 'buffer-tags (list tg))
13282 (if (member tg current)
13283 (setq current (delete tg current))
13284 (push tg current)))
13285 (if exit-after-next (setq exit-after-next 'now)))
13286 ((setq e (rassoc c todo-table) tg (car e))
13287 (with-current-buffer buf
13288 (save-excursion (org-todo tg)))
13289 (if exit-after-next (setq exit-after-next 'now)))
13290 ((setq e (rassoc c ntable) tg (car e))
13291 (if (member tg current)
13292 (setq current (delete tg current))
13293 (loop for g in groups do
13294 (if (member tg g)
13295 (mapc (lambda (x)
13296 (setq current (delete x current)))
13297 g)))
13298 (push tg current))
13299 (if exit-after-next (setq exit-after-next 'now))))
13301 ;; Create a sorted list
13302 (setq current
13303 (sort current
13304 (lambda (a b)
13305 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13306 (if (eq exit-after-next 'now) (throw 'exit t))
13307 (goto-char (point-min))
13308 (beginning-of-line 2)
13309 (delete-region (point) (point-at-eol))
13310 (org-fast-tag-insert "Current" current c-face)
13311 (org-set-current-tags-overlay current ov-prefix)
13312 (while (re-search-forward
13313 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13314 (setq tg (match-string 1))
13315 (add-text-properties
13316 (match-beginning 1) (match-end 1)
13317 (list 'face
13318 (cond
13319 ((member tg current) c-face)
13320 ((member tg inherited) i-face)
13321 (t (get-text-property (match-beginning 1) 'face))))))
13322 (goto-char (point-min)))))
13323 (org-detach-overlay org-tags-overlay)
13324 (if rtn
13325 (mapconcat 'identity current ":")
13326 nil))))
13328 (defun org-get-tags-string ()
13329 "Get the TAGS string in the current headline."
13330 (unless (org-on-heading-p t)
13331 (error "Not on a heading"))
13332 (save-excursion
13333 (beginning-of-line 1)
13334 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13335 (org-match-string-no-properties 1)
13336 "")))
13338 (defun org-get-tags ()
13339 "Get the list of tags specified in the current headline."
13340 (org-split-string (org-get-tags-string) ":"))
13342 (defun org-get-buffer-tags ()
13343 "Get a table of all tags used in the buffer, for completion."
13344 (let (tags)
13345 (save-excursion
13346 (goto-char (point-min))
13347 (while (re-search-forward
13348 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13349 (when (equal (char-after (point-at-bol 0)) ?*)
13350 (mapc (lambda (x) (add-to-list 'tags x))
13351 (org-split-string (org-match-string-no-properties 1) ":")))))
13352 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13353 (mapcar 'list tags)))
13355 ;;;; The mapping API
13357 ;;;###autoload
13358 (defun org-map-entries (func &optional match scope &rest skip)
13359 "Call FUNC at each headline selected by MATCH in SCOPE.
13361 FUNC is a function or a lisp form. The function will be called without
13362 arguments, with the cursor positioned at the beginning of the headline.
13363 The return values of all calls to the function will be collected and
13364 returned as a list.
13366 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13367 does not need to preserve point. After evaluation, the cursor will be
13368 moved to the end of the line (presumably of the headline of the
13369 processed entry) and search continues from there. Under some
13370 circumstances, this may not produce the wanted results. For example,
13371 if you have removed (e.g. archived) the current (sub)tree it could
13372 mean that the next entry will be skipped entirely. In such cases, you
13373 can specify the position from where search should continue by making
13374 FUNC set the variable `org-map-continue-from' to the desired buffer
13375 position.
13377 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13378 Only headlines that are matched by this query will be considered during
13379 the iteration. When MATCH is nil or t, all headlines will be
13380 visited by the iteration.
13382 SCOPE determines the scope of this command. It can be any of:
13384 nil The current buffer, respecting the restriction if any
13385 tree The subtree started with the entry at point
13386 file The current buffer, without restriction
13387 file-with-archives
13388 The current buffer, and any archives associated with it
13389 agenda All agenda files
13390 agenda-with-archives
13391 All agenda files with any archive files associated with them
13392 \(file1 file2 ...)
13393 If this is a list, all files in the list will be scanned
13395 The remaining args are treated as settings for the skipping facilities of
13396 the scanner. The following items can be given here:
13398 archive skip trees with the archive tag.
13399 comment skip trees with the COMMENT keyword
13400 function or Emacs Lisp form:
13401 will be used as value for `org-agenda-skip-function', so whenever
13402 the function returns t, FUNC will not be called for that
13403 entry and search will continue from the point where the
13404 function leaves it.
13406 If your function needs to retrieve the tags including inherited tags
13407 at the *current* entry, you can use the value of the variable
13408 `org-scanner-tags' which will be much faster than getting the value
13409 with `org-get-tags-at'. If your function gets properties with
13410 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13411 to t around the call to `org-entry-properties' to get the same speedup.
13412 Note that if your function moves around to retrieve tags and properties at
13413 a *different* entry, you cannot use these techniques."
13414 (let* ((org-agenda-archives-mode nil) ; just to make sure
13415 (org-agenda-skip-archived-trees (memq 'archive skip))
13416 (org-agenda-skip-comment-trees (memq 'comment skip))
13417 (org-agenda-skip-function
13418 (car (org-delete-all '(comment archive) skip)))
13419 (org-tags-match-list-sublevels t)
13420 matcher file res
13421 org-todo-keywords-for-agenda
13422 org-done-keywords-for-agenda
13423 org-todo-keyword-alist-for-agenda
13424 org-drawers-for-agenda
13425 org-tag-alist-for-agenda)
13427 (cond
13428 ((eq match t) (setq matcher t))
13429 ((eq match nil) (setq matcher t))
13430 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13432 (save-excursion
13433 (save-restriction
13434 (when (eq scope 'tree)
13435 (org-back-to-heading t)
13436 (org-narrow-to-subtree)
13437 (setq scope nil))
13439 (if (not scope)
13440 (progn
13441 (org-prepare-agenda-buffers
13442 (list (buffer-file-name (current-buffer))))
13443 (setq res (org-scan-tags func matcher)))
13444 ;; Get the right scope
13445 (cond
13446 ((and scope (listp scope) (symbolp (car scope)))
13447 (setq scope (eval scope)))
13448 ((eq scope 'agenda)
13449 (setq scope (org-agenda-files t)))
13450 ((eq scope 'agenda-with-archives)
13451 (setq scope (org-agenda-files t))
13452 (setq scope (org-add-archive-files scope)))
13453 ((eq scope 'file)
13454 (setq scope (list (buffer-file-name))))
13455 ((eq scope 'file-with-archives)
13456 (setq scope (org-add-archive-files (list (buffer-file-name))))))
13457 (org-prepare-agenda-buffers scope)
13458 (while (setq file (pop scope))
13459 (with-current-buffer (org-find-base-buffer-visiting file)
13460 (save-excursion
13461 (save-restriction
13462 (widen)
13463 (goto-char (point-min))
13464 (setq res (append res (org-scan-tags func matcher))))))))))
13465 res))
13467 ;;;; Properties
13469 ;;; Setting and retrieving properties
13471 (defconst org-special-properties
13472 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
13473 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM")
13474 "The special properties valid in Org-mode.
13476 These are properties that are not defined in the property drawer,
13477 but in some other way.")
13479 (defconst org-default-properties
13480 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
13481 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
13482 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
13483 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
13484 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
13485 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
13486 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
13487 "Some properties that are used by Org-mode for various purposes.
13488 Being in this list makes sure that they are offered for completion.")
13490 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
13491 "Regular expression matching the first line of a property drawer.")
13493 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
13494 "Regular expression matching the last line of a property drawer.")
13496 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
13497 "Regular expression matching the first line of a property drawer.")
13499 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
13500 "Regular expression matching the first line of a property drawer.")
13502 (defconst org-property-drawer-re
13503 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
13504 org-property-end-re "\\)\n?")
13505 "Matches an entire property drawer.")
13507 (defconst org-clock-drawer-re
13508 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
13509 org-property-end-re "\\)\n?")
13510 "Matches an entire clock drawer.")
13512 (defun org-property-action ()
13513 "Do an action on properties."
13514 (interactive)
13515 (let (c)
13516 (org-at-property-p)
13517 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
13518 (setq c (read-char-exclusive))
13519 (cond
13520 ((equal c ?s)
13521 (call-interactively 'org-set-property))
13522 ((equal c ?d)
13523 (call-interactively 'org-delete-property))
13524 ((equal c ?D)
13525 (call-interactively 'org-delete-property-globally))
13526 ((equal c ?c)
13527 (call-interactively 'org-compute-property-at-point))
13528 (t (error "No such property action %c" c)))))
13530 (defun org-set-effort (&optional value)
13531 "Set the effort property of the current entry.
13532 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
13533 allowed value."
13534 (interactive "P")
13535 (if (equal value 0) (setq value 10))
13536 (let* ((completion-ignore-case t)
13537 (prop org-effort-property)
13538 (cur (org-entry-get nil prop))
13539 (allowed (org-property-get-allowed-values nil prop 'table))
13540 (existing (mapcar 'list (org-property-values prop)))
13542 (val (cond
13543 ((stringp value) value)
13544 ((and allowed (integerp value))
13545 (or (car (nth (1- value) allowed))
13546 (car (org-last allowed))))
13547 (allowed
13548 (message "Select 1-9,0, [RET%s]: %s"
13549 (if cur (concat "=" cur) "")
13550 (mapconcat 'car allowed " "))
13551 (setq rpl (read-char-exclusive))
13552 (if (equal rpl ?\r)
13554 (setq rpl (- rpl ?0))
13555 (if (equal rpl 0) (setq rpl 10))
13556 (if (and (> rpl 0) (<= rpl (length allowed)))
13557 (car (nth (1- rpl) allowed))
13558 (org-completing-read "Effort: " allowed nil))))
13560 (let (org-completion-use-ido org-completion-use-iswitchb)
13561 (org-completing-read
13562 (concat "Effort " (if (and cur (string-match "\\S-" cur))
13563 (concat "[" cur "]") "")
13564 ": ")
13565 existing nil nil "" nil cur))))))
13566 (unless (equal (org-entry-get nil prop) val)
13567 (org-entry-put nil prop val))
13568 (message "%s is now %s" prop val)))
13570 (defun org-at-property-p ()
13571 "Is cursor inside a property drawer?"
13572 (save-excursion
13573 (beginning-of-line 1)
13574 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
13575 (save-match-data ;; Used by calling procedures
13576 (let ((p (point))
13577 (range (unless (org-before-first-heading-p)
13578 (org-get-property-block))))
13579 (and range (<= (car range) p) (< p (cdr range))))))))
13581 (defun org-get-property-block (&optional beg end force)
13582 "Return the (beg . end) range of the body of the property drawer.
13583 BEG and END can be beginning and end of subtree, if not given
13584 they will be found.
13585 If the drawer does not exist and FORCE is non-nil, create the drawer."
13586 (catch 'exit
13587 (save-excursion
13588 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
13589 (end (or end (progn (outline-next-heading) (point)))))
13590 (goto-char beg)
13591 (if (re-search-forward org-property-start-re end t)
13592 (setq beg (1+ (match-end 0)))
13593 (if force
13594 (save-excursion
13595 (org-insert-property-drawer)
13596 (setq end (progn (outline-next-heading) (point))))
13597 (throw 'exit nil))
13598 (goto-char beg)
13599 (if (re-search-forward org-property-start-re end t)
13600 (setq beg (1+ (match-end 0)))))
13601 (if (re-search-forward org-property-end-re end t)
13602 (setq end (match-beginning 0))
13603 (or force (throw 'exit nil))
13604 (goto-char beg)
13605 (setq end beg)
13606 (org-indent-line-function)
13607 (insert ":END:\n"))
13608 (cons beg end)))))
13610 (defun org-entry-properties (&optional pom which specific)
13611 "Get all properties of the entry at point-or-marker POM.
13612 This includes the TODO keyword, the tags, time strings for deadline,
13613 scheduled, and clocking, and any additional properties defined in the
13614 entry. The return value is an alist, keys may occur multiple times
13615 if the property key was used several times.
13616 POM may also be nil, in which case the current entry is used.
13617 If WHICH is nil or `all', get all properties. If WHICH is
13618 `special' or `standard', only get that subclass. If WHICH
13619 is a string only get exactly this property. SPECIFIC can be a string, the
13620 specific property we are interested in. Specifying it can speed
13621 things up because then unnecessary parsing is avoided."
13622 (setq which (or which 'all))
13623 (org-with-point-at pom
13624 (let ((clockstr (substring org-clock-string 0 -1))
13625 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
13626 (case-fold-search nil)
13627 beg end range props sum-props key key1 value string clocksum)
13628 (save-excursion
13629 (when (condition-case nil
13630 (and (org-mode-p) (org-back-to-heading t))
13631 (error nil))
13632 (setq beg (point))
13633 (setq sum-props (get-text-property (point) 'org-summaries))
13634 (setq clocksum (get-text-property (point) :org-clock-minutes))
13635 (outline-next-heading)
13636 (setq end (point))
13637 (when (memq which '(all special))
13638 ;; Get the special properties, like TODO and tags
13639 (goto-char beg)
13640 (when (and (or (not specific) (string= specific "TODO"))
13641 (looking-at org-todo-line-regexp) (match-end 2))
13642 (push (cons "TODO" (org-match-string-no-properties 2)) props))
13643 (when (and (or (not specific) (string= specific "PRIORITY"))
13644 (looking-at org-priority-regexp))
13645 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
13646 (when (or (not specific) (string= specific "FILE"))
13647 (push (cons "FILE" buffer-file-name) props))
13648 (when (and (or (not specific) (string= specific "TAGS"))
13649 (setq value (org-get-tags-string))
13650 (string-match "\\S-" value))
13651 (push (cons "TAGS" value) props))
13652 (when (and (or (not specific) (string= specific "ALLTAGS"))
13653 (setq value (org-get-tags-at)))
13654 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
13655 ":"))
13656 props))
13657 (when (or (not specific) (string= specific "BLOCKED"))
13658 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
13659 (when (or (not specific)
13660 (member specific
13661 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
13662 "TIMESTAMP" "TIMESTAMP_IA")))
13663 (catch 'match
13664 (while (re-search-forward org-maybe-keyword-time-regexp end t)
13665 (setq key (if (match-end 1)
13666 (substring (org-match-string-no-properties 1)
13667 0 -1))
13668 string (if (equal key clockstr)
13669 (org-no-properties
13670 (org-trim
13671 (buffer-substring
13672 (match-beginning 3) (goto-char
13673 (point-at-eol)))))
13674 (substring (org-match-string-no-properties 3)
13675 1 -1)))
13676 ;; Get the correct property name from the key. This is
13677 ;; necessary if the user has configured time keywords.
13678 (setq key1 (concat key ":"))
13679 (cond
13680 ((not key)
13681 (setq key
13682 (if (= (char-after (match-beginning 3)) ?\[)
13683 "TIMESTAMP_IA" "TIMESTAMP")))
13684 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
13685 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
13686 ((equal key1 org-closed-string) (setq key "CLOSED"))
13687 ((equal key1 org-clock-string) (setq key "CLOCK")))
13688 (if (and specific (equal key specific) (not (equal key "CLOCK")))
13689 (progn
13690 (push (cons key string) props)
13691 ;; no need to search further if match is found
13692 (throw 'match t))
13693 (when (or (equal key "CLOCK") (not (assoc key props)))
13694 (push (cons key string) props))))))
13697 (when (memq which '(all standard))
13698 ;; Get the standard properties, like :PROP: ...
13699 (setq range (org-get-property-block beg end))
13700 (when range
13701 (goto-char (car range))
13702 (while (re-search-forward
13703 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
13704 (cdr range) t)
13705 (setq key (org-match-string-no-properties 1)
13706 value (org-trim (or (org-match-string-no-properties 2) "")))
13707 (unless (member key excluded)
13708 (push (cons key (or value "")) props)))))
13709 (if clocksum
13710 (push (cons "CLOCKSUM"
13711 (org-columns-number-to-string (/ (float clocksum) 60.)
13712 'add_times))
13713 props))
13714 (unless (assoc "CATEGORY" props)
13715 (push (cons "CATEGORY" (org-get-category)) props))
13716 (append sum-props (nreverse props)))))))
13718 (defun org-entry-get (pom property &optional inherit literal-nil)
13719 "Get value of PROPERTY for entry at point-or-marker POM.
13720 If INHERIT is non-nil and the entry does not have the property,
13721 then also check higher levels of the hierarchy.
13722 If INHERIT is the symbol `selective', use inheritance only if the setting
13723 in `org-use-property-inheritance' selects PROPERTY for inheritance.
13724 If the property is present but empty, the return value is the empty string.
13725 If the property is not present at all, nil is returned.
13727 If LITERAL-NIL is set, return the string value \"nil\" as a string,
13728 do not interpret it as the list atom nil. This is used for inheritance
13729 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
13730 (org-with-point-at pom
13731 (if (and inherit (if (eq inherit 'selective)
13732 (org-property-inherit-p property)
13734 (org-entry-get-with-inheritance property literal-nil)
13735 (if (member property org-special-properties)
13736 ;; We need a special property. Use `org-entry-properties' to
13737 ;; retrieve it, but specify the wanted property
13738 (cdr (assoc property (org-entry-properties nil 'special property)))
13739 (let ((range (unless (org-before-first-heading-p)
13740 (org-get-property-block))))
13741 (if (and range
13742 (goto-char (car range))
13743 (re-search-forward
13744 (org-re-property property)
13745 (cdr range) t))
13746 ;; Found the property, return it.
13747 (if (match-end 1)
13748 (if literal-nil
13749 (org-match-string-no-properties 1)
13750 (org-not-nil (org-match-string-no-properties 1)))
13751 "")))))))
13753 (defun org-property-or-variable-value (var &optional inherit)
13754 "Check if there is a property fixing the value of VAR.
13755 If yes, return this value. If not, return the current value of the variable."
13756 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
13757 (if (and prop (stringp prop) (string-match "\\S-" prop))
13758 (read prop)
13759 (symbol-value var))))
13761 (defun org-entry-delete (pom property)
13762 "Delete the property PROPERTY from entry at point-or-marker POM."
13763 (org-with-point-at pom
13764 (if (member property org-special-properties)
13765 nil ; cannot delete these properties.
13766 (let ((range (org-get-property-block)))
13767 (if (and range
13768 (goto-char (car range))
13769 (re-search-forward
13770 (org-re-property property)
13771 (cdr range) t))
13772 (progn
13773 (delete-region (match-beginning 0) (1+ (point-at-eol)))
13775 nil)))))
13777 ;; Multi-values properties are properties that contain multiple values
13778 ;; These values are assumed to be single words, separated by whitespace.
13779 (defun org-entry-add-to-multivalued-property (pom property value)
13780 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
13781 (let* ((old (org-entry-get pom property))
13782 (values (and old (org-split-string old "[ \t]"))))
13783 (setq value (org-entry-protect-space value))
13784 (unless (member value values)
13785 (setq values (cons value values))
13786 (org-entry-put pom property
13787 (mapconcat 'identity values " ")))))
13789 (defun org-entry-remove-from-multivalued-property (pom property value)
13790 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
13791 (let* ((old (org-entry-get pom property))
13792 (values (and old (org-split-string old "[ \t]"))))
13793 (setq value (org-entry-protect-space value))
13794 (when (member value values)
13795 (setq values (delete value values))
13796 (org-entry-put pom property
13797 (mapconcat 'identity values " ")))))
13799 (defun org-entry-member-in-multivalued-property (pom property value)
13800 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
13801 (let* ((old (org-entry-get pom property))
13802 (values (and old (org-split-string old "[ \t]"))))
13803 (setq value (org-entry-protect-space value))
13804 (member value values)))
13806 (defun org-entry-get-multivalued-property (pom property)
13807 "Return a list of values in a multivalued property."
13808 (let* ((value (org-entry-get pom property))
13809 (values (and value (org-split-string value "[ \t]"))))
13810 (mapcar 'org-entry-restore-space values)))
13812 (defun org-entry-put-multivalued-property (pom property &rest values)
13813 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
13814 VALUES should be a list of strings. Spaces will be protected."
13815 (org-entry-put pom property
13816 (mapconcat 'org-entry-protect-space values " "))
13817 (let* ((value (org-entry-get pom property))
13818 (values (and value (org-split-string value "[ \t]"))))
13819 (mapcar 'org-entry-restore-space values)))
13821 (defun org-entry-protect-space (s)
13822 "Protect spaces and newline in string S."
13823 (while (string-match " " s)
13824 (setq s (replace-match "%20" t t s)))
13825 (while (string-match "\n" s)
13826 (setq s (replace-match "%0A" t t s)))
13829 (defun org-entry-restore-space (s)
13830 "Restore spaces and newline in string S."
13831 (while (string-match "%20" s)
13832 (setq s (replace-match " " t t s)))
13833 (while (string-match "%0A" s)
13834 (setq s (replace-match "\n" t t s)))
13837 (defvar org-entry-property-inherited-from (make-marker)
13838 "Marker pointing to the entry from where a property was inherited.
13839 Each call to `org-entry-get-with-inheritance' will set this marker to the
13840 location of the entry where the inheritance search matched. If there was
13841 no match, the marker will point nowhere.
13842 Note that also `org-entry-get' calls this function, if the INHERIT flag
13843 is set.")
13845 (defun org-entry-get-with-inheritance (property &optional literal-nil)
13846 "Get entry property, and search higher levels if not present.
13847 The search will stop at the first ancestor which has the property defined.
13848 If the value found is \"nil\", return nil to show that the property
13849 should be considered as undefined (this is the meaning of nil here).
13850 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
13851 (move-marker org-entry-property-inherited-from nil)
13852 (let (tmp)
13853 (unless (org-before-first-heading-p)
13854 (save-excursion
13855 (save-restriction
13856 (widen)
13857 (catch 'ex
13858 (while t
13859 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
13860 (org-back-to-heading t)
13861 (move-marker org-entry-property-inherited-from (point))
13862 (throw 'ex tmp))
13863 (or (org-up-heading-safe) (throw 'ex nil)))))))
13864 (setq tmp (or tmp
13865 (cdr (assoc property org-file-properties))
13866 (cdr (assoc property org-global-properties))
13867 (cdr (assoc property org-global-properties-fixed))))
13868 (if literal-nil tmp (org-not-nil tmp))))
13870 (defvar org-property-changed-functions nil
13871 "Hook called when the value of a property has changed.
13872 Each hook function should accept two arguments, the name of the property
13873 and the new value.")
13875 (defun org-entry-put (pom property value)
13876 "Set PROPERTY to VALUE for entry at point-or-marker POM."
13877 (org-with-point-at pom
13878 (org-back-to-heading t)
13879 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
13880 range)
13881 (cond
13882 ((equal property "TODO")
13883 (when (and (stringp value) (string-match "\\S-" value)
13884 (not (member value org-todo-keywords-1)))
13885 (error "\"%s\" is not a valid TODO state" value))
13886 (if (or (not value)
13887 (not (string-match "\\S-" value)))
13888 (setq value 'none))
13889 (org-todo value)
13890 (org-set-tags nil 'align))
13891 ((equal property "PRIORITY")
13892 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
13893 (string-to-char value) ?\ ))
13894 (org-set-tags nil 'align))
13895 ((equal property "SCHEDULED")
13896 (if (re-search-forward org-scheduled-time-regexp end t)
13897 (cond
13898 ((eq value 'earlier) (org-timestamp-change -1 'day))
13899 ((eq value 'later) (org-timestamp-change 1 'day))
13900 (t (call-interactively 'org-schedule)))
13901 (call-interactively 'org-schedule)))
13902 ((equal property "DEADLINE")
13903 (if (re-search-forward org-deadline-time-regexp end t)
13904 (cond
13905 ((eq value 'earlier) (org-timestamp-change -1 'day))
13906 ((eq value 'later) (org-timestamp-change 1 'day))
13907 (t (call-interactively 'org-deadline)))
13908 (call-interactively 'org-deadline)))
13909 ((member property org-special-properties)
13910 (error "The %s property can not yet be set with `org-entry-put'"
13911 property))
13912 (t ; a non-special property
13913 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
13914 (setq range (org-get-property-block beg end 'force))
13915 (goto-char (car range))
13916 (if (re-search-forward
13917 (org-re-property property) (cdr range) t)
13918 (progn
13919 (delete-region (match-beginning 0) (match-end 0))
13920 (goto-char (match-beginning 0)))
13921 (goto-char (cdr range))
13922 (insert "\n")
13923 (backward-char 1)
13924 (org-indent-line-function))
13925 (insert ":" property ":")
13926 (and value (insert " " value))
13927 (org-indent-line-function)))))
13928 (run-hook-with-args 'org-property-changed-functions property value)))
13930 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
13931 "Get all property keys in the current buffer.
13932 With INCLUDE-SPECIALS, also list the special properties that reflect things
13933 like tags and TODO state.
13934 With INCLUDE-DEFAULTS, also include properties that has special meaning
13935 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
13936 and others.
13937 With INCLUDE-COLUMNS, also include property names given in COLUMN
13938 formats in the current buffer."
13939 (let (rtn range cfmt s p)
13940 (save-excursion
13941 (save-restriction
13942 (widen)
13943 (goto-char (point-min))
13944 (while (re-search-forward org-property-start-re nil t)
13945 (setq range (org-get-property-block))
13946 (goto-char (car range))
13947 (while (re-search-forward
13948 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
13949 (cdr range) t)
13950 (add-to-list 'rtn (org-match-string-no-properties 1)))
13951 (outline-next-heading))))
13953 (when include-specials
13954 (setq rtn (append org-special-properties rtn)))
13956 (when include-defaults
13957 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
13958 (add-to-list 'rtn org-effort-property))
13960 (when include-columns
13961 (save-excursion
13962 (save-restriction
13963 (widen)
13964 (goto-char (point-min))
13965 (while (re-search-forward
13966 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
13967 nil t)
13968 (setq cfmt (match-string 2) s 0)
13969 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
13970 cfmt s)
13971 (setq s (match-end 0)
13972 p (match-string 1 cfmt))
13973 (unless (or (equal p "ITEM")
13974 (member p org-special-properties))
13975 (add-to-list 'rtn (match-string 1 cfmt))))))))
13977 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
13979 (defsubst org-re-property (property)
13980 "Return a regexp matching PROPERTY.
13981 Match group 1 will be set to the value "
13982 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
13984 (defun org-property-values (key)
13985 "Return a list of all values of property KEY in the current buffer."
13986 (save-excursion
13987 (save-restriction
13988 (widen)
13989 (goto-char (point-min))
13990 (let ((re (org-re-property key))
13991 values)
13992 (while (re-search-forward re nil t)
13993 (add-to-list 'values (org-trim (match-string 1))))
13994 (delete "" values)))))
13996 (defun org-insert-property-drawer ()
13997 "Insert a property drawer into the current entry."
13998 (interactive)
13999 (org-back-to-heading t)
14000 (looking-at outline-regexp)
14001 (let ((indent (if org-adapt-indentation
14002 (- (match-end 0)(match-beginning 0))
14004 (beg (point))
14005 (re (concat "^[ \t]*" org-keyword-time-regexp))
14006 end hiddenp)
14007 (outline-next-heading)
14008 (setq end (point))
14009 (goto-char beg)
14010 (while (re-search-forward re end t))
14011 (setq hiddenp (outline-invisible-p))
14012 (end-of-line 1)
14013 (and (equal (char-after) ?\n) (forward-char 1))
14014 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14015 (if (member (match-string 1) '("CLOCK:" ":END:"))
14016 ;; just skip this line
14017 (beginning-of-line 2)
14018 ;; Drawer start, find the end
14019 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14020 (beginning-of-line 1)))
14021 (org-skip-over-state-notes)
14022 (skip-chars-backward " \t\n\r")
14023 (if (eq (char-before) ?*) (forward-char 1))
14024 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14025 (beginning-of-line 0)
14026 (org-indent-to-column indent)
14027 (beginning-of-line 2)
14028 (org-indent-to-column indent)
14029 (beginning-of-line 0)
14030 (if hiddenp
14031 (save-excursion
14032 (org-back-to-heading t)
14033 (hide-entry))
14034 (org-flag-drawer t))))
14036 (defvar org-property-set-functions-alist nil
14037 "Property set function alist.
14038 Each entry should have the following format:
14040 (PROPERTY . READ-FUNCTION)
14042 The read function will be called with the same argument as
14043 `org-completing-read'.")
14045 (defun org-set-property-function (property)
14046 "Get the function that should be used to set PROPERTY.
14047 This is computed according to `org-property-set-functions-alist'."
14048 (or (cdr (assoc property org-property-set-functions-alist))
14049 'org-completing-read))
14051 (defun org-read-property-value (property)
14052 "Read PROPERTY value from user."
14053 (let* ((completion-ignore-case t)
14054 (allowed (org-property-get-allowed-values nil property 'table))
14055 (cur (org-entry-get nil property))
14056 (prompt (concat property " value"
14057 (if (and cur (string-match "\\S-" cur))
14058 (concat " [" cur "]") "") ": "))
14059 (set-function (org-set-property-function property))
14060 (val (if allowed
14061 (funcall set-function prompt allowed nil
14062 (not (get-text-property 0 'org-unrestricted
14063 (caar allowed))))
14064 (let (org-completion-use-ido org-completion-use-iswitchb)
14065 (funcall set-function prompt
14066 (mapcar 'list (org-property-values property))
14067 nil nil "" nil cur)))))
14068 (if (equal val "")
14070 val)))
14072 (defun org-read-property-name ()
14073 "Read a property name."
14074 (let* ((completion-ignore-case t)
14075 (keys (org-buffer-property-keys nil t t))
14076 (property (org-icompleting-read "Property: " (mapcar 'list keys))))
14077 (if (member property keys)
14078 property
14079 (or (cdr (assoc (downcase property)
14080 (mapcar (lambda (x) (cons (downcase x) x))
14081 keys)))
14082 property))))
14084 (defun org-set-property (property value)
14085 "In the current entry, set PROPERTY to VALUE.
14086 When called interactively, this will prompt for a property name, offering
14087 completion on existing and default properties. And then it will prompt
14088 for a value, offering completion either on allowed values (via an inherited
14089 xxx_ALL property) or on existing values in other instances of this property
14090 in the current file."
14091 (interactive (list nil nil))
14092 (let* ((property (or property (org-read-property-name)))
14093 (value (or value (org-read-property-value property))))
14094 (unless (equal (org-entry-get nil property) value)
14095 (org-entry-put nil property value))))
14097 (defun org-delete-property (property)
14098 "In the current entry, delete PROPERTY."
14099 (interactive
14100 (let* ((completion-ignore-case t)
14101 (prop (org-icompleting-read "Property: "
14102 (org-entry-properties nil 'standard))))
14103 (list prop)))
14104 (message "Property %s %s" property
14105 (if (org-entry-delete nil property)
14106 "deleted"
14107 "was not present in the entry")))
14109 (defun org-delete-property-globally (property)
14110 "Remove PROPERTY globally, from all entries."
14111 (interactive
14112 (let* ((completion-ignore-case t)
14113 (prop (org-icompleting-read
14114 "Globally remove property: "
14115 (mapcar 'list (org-buffer-property-keys)))))
14116 (list prop)))
14117 (save-excursion
14118 (save-restriction
14119 (widen)
14120 (goto-char (point-min))
14121 (let ((cnt 0))
14122 (while (re-search-forward
14123 (org-re-property property)
14124 nil t)
14125 (setq cnt (1+ cnt))
14126 (replace-match ""))
14127 (message "Property \"%s\" removed from %d entries" property cnt)))))
14129 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14131 (defun org-compute-property-at-point ()
14132 "Compute the property at point.
14133 This looks for an enclosing column format, extracts the operator and
14134 then applies it to the property in the column format's scope."
14135 (interactive)
14136 (unless (org-at-property-p)
14137 (error "Not at a property"))
14138 (let ((prop (org-match-string-no-properties 2)))
14139 (org-columns-get-format-and-top-level)
14140 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14141 (error "No operator defined for property %s" prop))
14142 (org-columns-compute prop)))
14144 (defvar org-property-allowed-value-functions nil
14145 "Hook for functions supplying allowed values for a specific property.
14146 The functions must take a single argument, the name of the property, and
14147 return a flat list of allowed values. If \":ETC\" is one of
14148 the values, this means that these values are intended as defaults for
14149 completion, but that other values should be allowed too.
14150 The functions must return nil if they are not responsible for this
14151 property.")
14153 (defun org-property-get-allowed-values (pom property &optional table)
14154 "Get allowed values for the property PROPERTY.
14155 When TABLE is non-nil, return an alist that can directly be used for
14156 completion."
14157 (let (vals)
14158 (cond
14159 ((equal property "TODO")
14160 (setq vals (org-with-point-at pom
14161 (append org-todo-keywords-1 '("")))))
14162 ((equal property "PRIORITY")
14163 (let ((n org-lowest-priority))
14164 (while (>= n org-highest-priority)
14165 (push (char-to-string n) vals)
14166 (setq n (1- n)))))
14167 ((member property org-special-properties))
14168 ((setq vals (run-hook-with-args-until-success
14169 'org-property-allowed-value-functions property)))
14171 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14172 (when (and vals (string-match "\\S-" vals))
14173 (setq vals (car (read-from-string (concat "(" vals ")"))))
14174 (setq vals (mapcar (lambda (x)
14175 (cond ((stringp x) x)
14176 ((numberp x) (number-to-string x))
14177 ((symbolp x) (symbol-name x))
14178 (t "???")))
14179 vals)))))
14180 (when (member ":ETC" vals)
14181 (setq vals (remove ":ETC" vals))
14182 (org-add-props (car vals) '(org-unrestricted t)))
14183 (if table (mapcar 'list vals) vals)))
14185 (defun org-property-previous-allowed-value (&optional previous)
14186 "Switch to the next allowed value for this property."
14187 (interactive)
14188 (org-property-next-allowed-value t))
14190 (defun org-property-next-allowed-value (&optional previous)
14191 "Switch to the next allowed value for this property."
14192 (interactive)
14193 (unless (org-at-property-p)
14194 (error "Not at a property"))
14195 (let* ((key (match-string 2))
14196 (value (match-string 3))
14197 (allowed (or (org-property-get-allowed-values (point) key)
14198 (and (member value '("[ ]" "[-]" "[X]"))
14199 '("[ ]" "[X]"))))
14200 nval)
14201 (unless allowed
14202 (error "Allowed values for this property have not been defined"))
14203 (if previous (setq allowed (reverse allowed)))
14204 (if (member value allowed)
14205 (setq nval (car (cdr (member value allowed)))))
14206 (setq nval (or nval (car allowed)))
14207 (if (equal nval value)
14208 (error "Only one allowed value for this property"))
14209 (org-at-property-p)
14210 (replace-match (concat " :" key ": " nval) t t)
14211 (org-indent-line-function)
14212 (beginning-of-line 1)
14213 (skip-chars-forward " \t")
14214 (run-hook-with-args 'org-property-changed-functions key nval)))
14216 (defun org-find-olp (path &optional this-buffer)
14217 "Return a marker pointing to the entry at outline path OLP.
14218 If anything goes wrong, throw an error.
14219 You can wrap this call to catch the error like this:
14221 (condition-case msg
14222 (org-mobile-locate-entry (match-string 4))
14223 (error (nth 1 msg)))
14225 The return value will then be either a string with the error message,
14226 or a marker if everything is OK.
14228 If THIS-BUFFER is set, the outline path does not contain a file,
14229 only headings."
14230 (let* ((file (if this-buffer buffer-file-name (pop path)))
14231 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14232 (level 1)
14233 (lmin 1)
14234 (lmax 1)
14235 limit re end found pos heading cnt flevel)
14236 (unless buffer (error "File not found :%s" file))
14237 (with-current-buffer buffer
14238 (save-excursion
14239 (save-restriction
14240 (widen)
14241 (setq limit (point-max))
14242 (goto-char (point-min))
14243 (while (setq heading (pop path))
14244 (setq re (format org-complex-heading-regexp-format
14245 (regexp-quote heading)))
14246 (setq cnt 0 pos (point))
14247 (while (re-search-forward re end t)
14248 (setq level (- (match-end 1) (match-beginning 1)))
14249 (if (and (>= level lmin) (<= level lmax))
14250 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
14251 (when (= cnt 0) (error "Heading not found on level %d: %s"
14252 lmax heading))
14253 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14254 lmax heading))
14255 (goto-char found)
14256 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
14257 (setq end (save-excursion (org-end-of-subtree t t))))
14258 (when (org-on-heading-p)
14259 (move-marker (make-marker) (point))))))))
14261 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14262 "Find node HEADING in BUFFER.
14263 Return a marker to the heading if it was found, or nil if not.
14264 If POS-ONLY is set, return just the position instead of a marker.
14266 The heading text must match exact, but it may have a TODO keyword,
14267 a priority cookie and tags in the standard locations."
14268 (with-current-buffer (or buffer (current-buffer))
14269 (save-excursion
14270 (save-restriction
14271 (widen)
14272 (goto-char (point-min))
14273 (let (case-fold-search)
14274 (if (re-search-forward
14275 (format org-complex-heading-regexp-format
14276 (regexp-quote heading)) nil t)
14277 (if pos-only
14278 (match-beginning 0)
14279 (move-marker (make-marker) (match-beginning 0)))))))))
14281 (defun org-find-exact-heading-in-directory (heading &optional dir)
14282 "Find Org node headline HEADING in all .org files in directory DIR.
14283 When the target headline is found, return a marker to this location."
14284 (let ((files (directory-files (or dir default-directory)
14285 nil "\\`[^.#].*\\.org\\'"))
14286 file visiting m buffer)
14287 (catch 'found
14288 (while (setq file (pop files))
14289 (message "trying %s" file)
14290 (setq visiting (org-find-base-buffer-visiting file))
14291 (setq buffer (or visiting (find-file-noselect file)))
14292 (setq m (org-find-exact-headline-in-buffer
14293 heading buffer))
14294 (when (and (not m) (not visiting)) (kill-buffer buffer))
14295 (and m (throw 'found m))))))
14297 (defun org-find-entry-with-id (ident)
14298 "Locate the entry that contains the ID property with exact value IDENT.
14299 IDENT can be a string, a symbol or a number, this function will search for
14300 the string representation of it.
14301 Return the position where this entry starts, or nil if there is no such entry."
14302 (interactive "sID: ")
14303 (let ((id (cond
14304 ((stringp ident) ident)
14305 ((symbol-name ident) (symbol-name ident))
14306 ((numberp ident) (number-to-string ident))
14307 (t (error "IDENT %s must be a string, symbol or number" ident))))
14308 (case-fold-search nil))
14309 (save-excursion
14310 (save-restriction
14311 (widen)
14312 (goto-char (point-min))
14313 (when (re-search-forward
14314 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
14315 nil t)
14316 (org-back-to-heading t)
14317 (point))))))
14319 ;;;; Timestamps
14321 (defvar org-last-changed-timestamp nil)
14322 (defvar org-last-inserted-timestamp nil
14323 "The last time stamp inserted with `org-insert-time-stamp'.")
14324 (defvar org-time-was-given) ; dynamically scoped parameter
14325 (defvar org-end-time-was-given) ; dynamically scoped parameter
14326 (defvar org-ts-what) ; dynamically scoped parameter
14328 (defun org-time-stamp (arg &optional inactive)
14329 "Prompt for a date/time and insert a time stamp.
14330 If the user specifies a time like HH:MM, or if this command is called
14331 with a prefix argument, the time stamp will contain date and time.
14332 Otherwise, only the date will be included. All parts of a date not
14333 specified by the user will be filled in from the current date/time.
14334 So if you press just return without typing anything, the time stamp
14335 will represent the current date/time. If there is already a timestamp
14336 at the cursor, it will be modified."
14337 (interactive "P")
14338 (let* ((ts nil)
14339 (default-time
14340 ;; Default time is either today, or, when entering a range,
14341 ;; the range start.
14342 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
14343 (save-excursion
14344 (re-search-backward
14345 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
14346 (- (point) 20) t)))
14347 (apply 'encode-time (org-parse-time-string (match-string 1)))
14348 (current-time)))
14349 (default-input (and ts (org-get-compact-tod ts)))
14350 org-time-was-given org-end-time-was-given time)
14351 (cond
14352 ((and (org-at-timestamp-p t)
14353 (memq last-command '(org-time-stamp org-time-stamp-inactive))
14354 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
14355 (insert "--")
14356 (setq time (let ((this-command this-command))
14357 (org-read-date arg 'totime nil nil
14358 default-time default-input)))
14359 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
14360 ((org-at-timestamp-p t)
14361 (setq time (let ((this-command this-command))
14362 (org-read-date arg 'totime nil nil default-time default-input)))
14363 (when (org-at-timestamp-p t) ; just to get the match data
14364 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
14365 (replace-match "")
14366 (setq org-last-changed-timestamp
14367 (org-insert-time-stamp
14368 time (or org-time-was-given arg)
14369 inactive nil nil (list org-end-time-was-given))))
14370 (message "Timestamp updated"))
14372 (setq time (let ((this-command this-command))
14373 (org-read-date arg 'totime nil nil default-time default-input)))
14374 (org-insert-time-stamp time (or org-time-was-given arg) inactive
14375 nil nil (list org-end-time-was-given))))))
14377 ;; FIXME: can we use this for something else, like computing time differences?
14378 (defun org-get-compact-tod (s)
14379 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
14380 (let* ((t1 (match-string 1 s))
14381 (h1 (string-to-number (match-string 2 s)))
14382 (m1 (string-to-number (match-string 3 s)))
14383 (t2 (and (match-end 4) (match-string 5 s)))
14384 (h2 (and t2 (string-to-number (match-string 6 s))))
14385 (m2 (and t2 (string-to-number (match-string 7 s))))
14386 dh dm)
14387 (if (not t2)
14389 (setq dh (- h2 h1) dm (- m2 m1))
14390 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
14391 (concat t1 "+" (number-to-string dh)
14392 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
14394 (defun org-time-stamp-inactive (&optional arg)
14395 "Insert an inactive time stamp.
14396 An inactive time stamp is enclosed in square brackets instead of angle
14397 brackets. It is inactive in the sense that it does not trigger agenda entries,
14398 does not link to the calendar and cannot be changed with the S-cursor keys.
14399 So these are more for recording a certain time/date."
14400 (interactive "P")
14401 (org-time-stamp arg 'inactive))
14403 (defvar org-date-ovl (make-overlay 1 1))
14404 (overlay-put org-date-ovl 'face 'org-warning)
14405 (org-detach-overlay org-date-ovl)
14407 (defvar org-ans1) ; dynamically scoped parameter
14408 (defvar org-ans2) ; dynamically scoped parameter
14410 (defvar org-plain-time-of-day-regexp) ; defined below
14412 (defvar org-overriding-default-time nil) ; dynamically scoped
14413 (defvar org-read-date-overlay nil)
14414 (defvar org-dcst nil) ; dynamically scoped
14415 (defvar org-read-date-history nil)
14416 (defvar org-read-date-final-answer nil)
14417 (defvar org-read-date-analyze-futurep nil)
14418 (defvar org-read-date-analyze-forced-year nil)
14420 (defun org-read-date (&optional with-time to-time from-string prompt
14421 default-time default-input)
14422 "Read a date, possibly a time, and make things smooth for the user.
14423 The prompt will suggest to enter an ISO date, but you can also enter anything
14424 which will at least partially be understood by `parse-time-string'.
14425 Unrecognized parts of the date will default to the current day, month, year,
14426 hour and minute. If this command is called to replace a timestamp at point,
14427 of to enter the second timestamp of a range, the default time is taken
14428 from the existing stamp. Furthermore, the command prefers the future,
14429 so if you are giving a date where the year is not given, and the day-month
14430 combination is already past in the current year, it will assume you
14431 mean next year. For details, see the manual. A few examples:
14433 3-2-5 --> 2003-02-05
14434 feb 15 --> currentyear-02-15
14435 2/15 --> currentyear-02-15
14436 sep 12 9 --> 2009-09-12
14437 12:45 --> today 12:45
14438 22 sept 0:34 --> currentyear-09-22 0:34
14439 12 --> currentyear-currentmonth-12
14440 Fri --> nearest Friday (today or later)
14441 etc.
14443 Furthermore you can specify a relative date by giving, as the *first* thing
14444 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
14445 change in days weeks, months, years.
14446 With a single plus or minus, the date is relative to today. With a double
14447 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
14448 +4d --> four days from today
14449 +4 --> same as above
14450 +2w --> two weeks from today
14451 ++5 --> five days from default date
14453 The function understands only English month and weekday abbreviations,
14454 but this can be configured with the variables `parse-time-months' and
14455 `parse-time-weekdays'.
14457 While prompting, a calendar is popped up - you can also select the
14458 date with the mouse (button 1). The calendar shows a period of three
14459 months. To scroll it to other months, use the keys `>' and `<'.
14460 If you don't like the calendar, turn it off with
14461 \(setq org-read-date-popup-calendar nil)
14463 With optional argument TO-TIME, the date will immediately be converted
14464 to an internal time.
14465 With an optional argument WITH-TIME, the prompt will suggest to also
14466 insert a time. Note that when WITH-TIME is not set, you can still
14467 enter a time, and this function will inform the calling routine about
14468 this change. The calling routine may then choose to change the format
14469 used to insert the time stamp into the buffer to include the time.
14470 With optional argument FROM-STRING, read from this string instead from
14471 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
14472 the time/date that is used for everything that is not specified by the
14473 user."
14474 (require 'parse-time)
14475 (let* ((org-time-stamp-rounding-minutes
14476 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
14477 (org-dcst org-display-custom-times)
14478 (ct (org-current-time))
14479 (def (or org-overriding-default-time default-time ct))
14480 (defdecode (decode-time def))
14481 (dummy (progn
14482 (when (< (nth 2 defdecode) org-extend-today-until)
14483 (setcar (nthcdr 2 defdecode) -1)
14484 (setcar (nthcdr 1 defdecode) 59)
14485 (setq def (apply 'encode-time defdecode)
14486 defdecode (decode-time def)))))
14487 (calendar-frame-setup nil)
14488 (calendar-setup nil)
14489 (calendar-move-hook nil)
14490 (calendar-view-diary-initially-flag nil)
14491 (calendar-view-holidays-initially-flag nil)
14492 (timestr (format-time-string
14493 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
14494 (prompt (concat (if prompt (concat prompt " ") "")
14495 (format "Date+time [%s]: " timestr)))
14496 ans (org-ans0 "") org-ans1 org-ans2 final)
14498 (cond
14499 (from-string (setq ans from-string))
14500 (org-read-date-popup-calendar
14501 (save-excursion
14502 (save-window-excursion
14503 (calendar)
14504 (unwind-protect
14505 (progn
14506 (calendar-forward-day (- (time-to-days def)
14507 (calendar-absolute-from-gregorian
14508 (calendar-current-date))))
14509 (org-eval-in-calendar nil t)
14510 (let* ((old-map (current-local-map))
14511 (map (copy-keymap calendar-mode-map))
14512 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
14513 (org-defkey map (kbd "RET") 'org-calendar-select)
14514 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
14515 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
14516 (org-defkey minibuffer-local-map [(meta shift left)]
14517 (lambda () (interactive)
14518 (org-eval-in-calendar '(calendar-backward-month 1))))
14519 (org-defkey minibuffer-local-map [(meta shift right)]
14520 (lambda () (interactive)
14521 (org-eval-in-calendar '(calendar-forward-month 1))))
14522 (org-defkey minibuffer-local-map [(meta shift up)]
14523 (lambda () (interactive)
14524 (org-eval-in-calendar '(calendar-backward-year 1))))
14525 (org-defkey minibuffer-local-map [(meta shift down)]
14526 (lambda () (interactive)
14527 (org-eval-in-calendar '(calendar-forward-year 1))))
14528 (org-defkey minibuffer-local-map [?\e (shift left)]
14529 (lambda () (interactive)
14530 (org-eval-in-calendar '(calendar-backward-month 1))))
14531 (org-defkey minibuffer-local-map [?\e (shift right)]
14532 (lambda () (interactive)
14533 (org-eval-in-calendar '(calendar-forward-month 1))))
14534 (org-defkey minibuffer-local-map [?\e (shift up)]
14535 (lambda () (interactive)
14536 (org-eval-in-calendar '(calendar-backward-year 1))))
14537 (org-defkey minibuffer-local-map [?\e (shift down)]
14538 (lambda () (interactive)
14539 (org-eval-in-calendar '(calendar-forward-year 1))))
14540 (org-defkey minibuffer-local-map [(shift up)]
14541 (lambda () (interactive)
14542 (org-eval-in-calendar '(calendar-backward-week 1))))
14543 (org-defkey minibuffer-local-map [(shift down)]
14544 (lambda () (interactive)
14545 (org-eval-in-calendar '(calendar-forward-week 1))))
14546 (org-defkey minibuffer-local-map [(shift left)]
14547 (lambda () (interactive)
14548 (org-eval-in-calendar '(calendar-backward-day 1))))
14549 (org-defkey minibuffer-local-map [(shift right)]
14550 (lambda () (interactive)
14551 (org-eval-in-calendar '(calendar-forward-day 1))))
14552 (org-defkey minibuffer-local-map ">"
14553 (lambda () (interactive)
14554 (org-eval-in-calendar '(scroll-calendar-left 1))))
14555 (org-defkey minibuffer-local-map "<"
14556 (lambda () (interactive)
14557 (org-eval-in-calendar '(scroll-calendar-right 1))))
14558 (org-defkey minibuffer-local-map "\C-v"
14559 (lambda () (interactive)
14560 (org-eval-in-calendar
14561 '(calendar-scroll-left-three-months 1))))
14562 (org-defkey minibuffer-local-map "\M-v"
14563 (lambda () (interactive)
14564 (org-eval-in-calendar
14565 '(calendar-scroll-right-three-months 1))))
14566 (run-hooks 'org-read-date-minibuffer-setup-hook)
14567 (unwind-protect
14568 (progn
14569 (use-local-map map)
14570 (add-hook 'post-command-hook 'org-read-date-display)
14571 (setq org-ans0 (read-string prompt default-input
14572 'org-read-date-history nil))
14573 ;; org-ans0: from prompt
14574 ;; org-ans1: from mouse click
14575 ;; org-ans2: from calendar motion
14576 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
14577 (remove-hook 'post-command-hook 'org-read-date-display)
14578 (use-local-map old-map)
14579 (when org-read-date-overlay
14580 (delete-overlay org-read-date-overlay)
14581 (setq org-read-date-overlay nil)))))
14582 (bury-buffer "*Calendar*")))))
14584 (t ; Naked prompt only
14585 (unwind-protect
14586 (setq ans (read-string prompt default-input
14587 'org-read-date-history timestr))
14588 (when org-read-date-overlay
14589 (delete-overlay org-read-date-overlay)
14590 (setq org-read-date-overlay nil)))))
14592 (setq final (org-read-date-analyze ans def defdecode))
14594 (when org-read-date-analyze-forced-year
14595 (message "Year was forced into %s"
14596 (if org-read-date-force-compatible-dates
14597 "compatible range (1970-2037)"
14598 "range representable on this machine"))
14599 (ding))
14601 ;; One round trip to get rid of 34th of August and stuff like that....
14602 (setq final (decode-time (apply 'encode-time final)))
14604 (setq org-read-date-final-answer ans)
14606 (if to-time
14607 (apply 'encode-time final)
14608 (if (and (boundp 'org-time-was-given) org-time-was-given)
14609 (format "%04d-%02d-%02d %02d:%02d"
14610 (nth 5 final) (nth 4 final) (nth 3 final)
14611 (nth 2 final) (nth 1 final))
14612 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
14614 (defvar def)
14615 (defvar defdecode)
14616 (defvar with-time)
14617 (defun org-read-date-display ()
14618 "Display the current date prompt interpretation in the minibuffer."
14619 (when org-read-date-display-live
14620 (when org-read-date-overlay
14621 (delete-overlay org-read-date-overlay))
14622 (let ((p (point)))
14623 (end-of-line 1)
14624 (while (not (equal (buffer-substring
14625 (max (point-min) (- (point) 4)) (point))
14626 " "))
14627 (insert " "))
14628 (goto-char p))
14629 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
14630 " " (or org-ans1 org-ans2)))
14631 (org-end-time-was-given nil)
14632 (f (org-read-date-analyze ans def defdecode))
14633 (fmts (if org-dcst
14634 org-time-stamp-custom-formats
14635 org-time-stamp-formats))
14636 (fmt (if (or with-time
14637 (and (boundp 'org-time-was-given) org-time-was-given))
14638 (cdr fmts)
14639 (car fmts)))
14640 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
14641 (when (and org-end-time-was-given
14642 (string-match org-plain-time-of-day-regexp txt))
14643 (setq txt (concat (substring txt 0 (match-end 0)) "-"
14644 org-end-time-was-given
14645 (substring txt (match-end 0)))))
14646 (when org-read-date-analyze-futurep
14647 (setq txt (concat txt " (=>F)")))
14648 (setq org-read-date-overlay
14649 (make-overlay (1- (point-at-eol)) (point-at-eol)))
14650 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
14652 (defun org-read-date-analyze (ans def defdecode)
14653 "Analyze the combined answer of the date prompt."
14654 ;; FIXME: cleanup and comment
14655 (let ((nowdecode (decode-time (current-time)))
14656 delta deltan deltaw deltadef year month day
14657 hour minute second wday pm h2 m2 tl wday1
14658 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
14659 (setq org-read-date-analyze-futurep nil
14660 org-read-date-analyze-forced-year nil)
14661 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
14662 (setq ans "+0"))
14664 (when (setq delta (org-read-date-get-relative ans (current-time) def))
14665 (setq ans (replace-match "" t t ans)
14666 deltan (car delta)
14667 deltaw (nth 1 delta)
14668 deltadef (nth 2 delta)))
14670 ;; Check if there is an iso week date in there
14671 ;; If yes, store the info and postpone interpreting it until the rest
14672 ;; of the parsing is done
14673 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
14674 (setq iso-year (if (match-end 1)
14675 (org-small-year-to-year
14676 (string-to-number (match-string 1 ans))))
14677 iso-weekday (if (match-end 3)
14678 (string-to-number (match-string 3 ans)))
14679 iso-week (string-to-number (match-string 2 ans)))
14680 (setq ans (replace-match "" t t ans)))
14682 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
14683 (when (string-match
14684 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
14685 (setq year (if (match-end 2)
14686 (string-to-number (match-string 2 ans))
14687 (progn (setq kill-year t)
14688 (string-to-number (format-time-string "%Y"))))
14689 month (string-to-number (match-string 3 ans))
14690 day (string-to-number (match-string 4 ans)))
14691 (if (< year 100) (setq year (+ 2000 year)))
14692 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14693 t nil ans)))
14695 ;; Help matching dottet european dates
14696 (when (string-match
14697 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
14698 (setq year (if (match-end 3)
14699 (string-to-number (match-string 3 ans))
14700 (progn (setq kill-year t)
14701 (string-to-number (format-time-string "%Y"))))
14702 day (string-to-number (match-string 1 ans))
14703 month (string-to-number (match-string 2 ans))
14704 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14705 t nil ans)))
14707 ;; Help matching american dates, like 5/30 or 5/30/7
14708 (when (string-match
14709 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
14710 (setq year (if (match-end 4)
14711 (string-to-number (match-string 4 ans))
14712 (progn (setq kill-year t)
14713 (string-to-number (format-time-string "%Y"))))
14714 month (string-to-number (match-string 1 ans))
14715 day (string-to-number (match-string 2 ans)))
14716 (if (< year 100) (setq year (+ 2000 year)))
14717 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14718 t nil ans)))
14719 ;; Help matching am/pm times, because `parse-time-string' does not do that.
14720 ;; If there is a time with am/pm, and *no* time without it, we convert
14721 ;; so that matching will be successful.
14722 (loop for i from 1 to 2 do ; twice, for end time as well
14723 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
14724 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
14725 (setq hour (string-to-number (match-string 1 ans))
14726 minute (if (match-end 3)
14727 (string-to-number (match-string 3 ans))
14729 pm (equal ?p
14730 (string-to-char (downcase (match-string 4 ans)))))
14731 (if (and (= hour 12) (not pm))
14732 (setq hour 0)
14733 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
14734 (setq ans (replace-match (format "%02d:%02d" hour minute)
14735 t t ans))))
14737 ;; Check if a time range is given as a duration
14738 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
14739 (setq hour (string-to-number (match-string 1 ans))
14740 h2 (+ hour (string-to-number (match-string 3 ans)))
14741 minute (string-to-number (match-string 2 ans))
14742 m2 (+ minute (if (match-end 5) (string-to-number
14743 (match-string 5 ans))0)))
14744 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
14745 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
14746 t t ans)))
14748 ;; Check if there is a time range
14749 (when (boundp 'org-end-time-was-given)
14750 (setq org-time-was-given nil)
14751 (when (and (string-match org-plain-time-of-day-regexp ans)
14752 (match-end 8))
14753 (setq org-end-time-was-given (match-string 8 ans))
14754 (setq ans (concat (substring ans 0 (match-beginning 7))
14755 (substring ans (match-end 7))))))
14757 (setq tl (parse-time-string ans)
14758 day (or (nth 3 tl) (nth 3 defdecode))
14759 month (or (nth 4 tl)
14760 (if (and org-read-date-prefer-future
14761 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
14762 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
14763 (nth 4 defdecode)))
14764 year (or (and (not kill-year) (nth 5 tl))
14765 (if (and org-read-date-prefer-future
14766 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
14767 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
14768 (nth 5 defdecode)))
14769 hour (or (nth 2 tl) (nth 2 defdecode))
14770 minute (or (nth 1 tl) (nth 1 defdecode))
14771 second (or (nth 0 tl) 0)
14772 wday (nth 6 tl))
14774 (when (and (eq org-read-date-prefer-future 'time)
14775 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
14776 (equal day (nth 3 nowdecode))
14777 (equal month (nth 4 nowdecode))
14778 (equal year (nth 5 nowdecode))
14779 (nth 2 tl)
14780 (or (< (nth 2 tl) (nth 2 nowdecode))
14781 (and (= (nth 2 tl) (nth 2 nowdecode))
14782 (nth 1 tl)
14783 (< (nth 1 tl) (nth 1 nowdecode)))))
14784 (setq day (1+ day)
14785 futurep t))
14787 ;; Special date definitions below
14788 (cond
14789 (iso-week
14790 ;; There was an iso week
14791 (require 'cal-iso)
14792 (setq futurep nil)
14793 (setq year (or iso-year year)
14794 day (or iso-weekday wday 1)
14795 wday nil ; to make sure that the trigger below does not match
14796 iso-date (calendar-gregorian-from-absolute
14797 (calendar-absolute-from-iso
14798 (list iso-week day year))))
14799 ; FIXME: Should we also push ISO weeks into the future?
14800 ; (when (and org-read-date-prefer-future
14801 ; (not iso-year)
14802 ; (< (calendar-absolute-from-gregorian iso-date)
14803 ; (time-to-days (current-time))))
14804 ; (setq year (1+ year)
14805 ; iso-date (calendar-gregorian-from-absolute
14806 ; (calendar-absolute-from-iso
14807 ; (list iso-week day year)))))
14808 (setq month (car iso-date)
14809 year (nth 2 iso-date)
14810 day (nth 1 iso-date)))
14811 (deltan
14812 (setq futurep nil)
14813 (unless deltadef
14814 (let ((now (decode-time (current-time))))
14815 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
14816 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
14817 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
14818 ((equal deltaw "m") (setq month (+ month deltan)))
14819 ((equal deltaw "y") (setq year (+ year deltan)))))
14820 ((and wday (not (nth 3 tl)))
14821 (setq futurep nil)
14822 ;; Weekday was given, but no day, so pick that day in the week
14823 ;; on or after the derived date.
14824 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
14825 (unless (equal wday wday1)
14826 (setq day (+ day (% (- wday wday1 -7) 7))))))
14827 (if (and (boundp 'org-time-was-given)
14828 (nth 2 tl))
14829 (setq org-time-was-given t))
14830 (if (< year 100) (setq year (+ 2000 year)))
14831 ;; Check of the date is representable
14832 (if org-read-date-force-compatible-dates
14833 (progn
14834 (if (< year 1970)
14835 (setq year 1970 org-read-date-analyze-forced-year t))
14836 (if (> year 2037)
14837 (setq year 2037 org-read-date-analyze-forced-year t)))
14838 (condition-case nil
14839 (encode-time second minute hour day month year)
14840 (error
14841 (setq year (nth 5 defdecode))
14842 (setq org-read-date-analyze-forced-year t))))
14843 (setq org-read-date-analyze-futurep futurep)
14844 (list second minute hour day month year)))
14846 (defvar parse-time-weekdays)
14848 (defun org-read-date-get-relative (s today default)
14849 "Check string S for special relative date string.
14850 TODAY and DEFAULT are internal times, for today and for a default.
14851 Return shift list (N what def-flag)
14852 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
14853 N is the number of WHATs to shift.
14854 DEF-FLAG is t when a double ++ or -- indicates shift relative to
14855 the DEFAULT date rather than TODAY."
14856 (when (and
14857 (string-match
14858 (concat
14859 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
14860 "\\([0-9]+\\)?"
14861 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
14862 "\\([ \t]\\|$\\)") s)
14863 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
14864 (let* ((dir (if (> (match-end 1) (match-beginning 1))
14865 (string-to-char (substring (match-string 1 s) -1))
14866 ?+))
14867 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
14868 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
14869 (what (if (match-end 3) (match-string 3 s) "d"))
14870 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
14871 (date (if rel default today))
14872 (wday (nth 6 (decode-time date)))
14873 delta)
14874 (if wday1
14875 (progn
14876 (setq delta (mod (+ 7 (- wday1 wday)) 7))
14877 (if (= dir ?-) (setq delta (- delta 7)))
14878 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
14879 (list delta "d" rel))
14880 (list (* n (if (= dir ?-) -1 1)) what rel)))))
14882 (defun org-order-calendar-date-args (arg1 arg2 arg3)
14883 "Turn a user-specified date into the internal representation.
14884 The internal representation needed by the calendar is (month day year).
14885 This is a wrapper to handle the brain-dead convention in calendar that
14886 user function argument order change dependent on argument order."
14887 (if (boundp 'calendar-date-style)
14888 (cond
14889 ((eq calendar-date-style 'american)
14890 (list arg1 arg2 arg3))
14891 ((eq calendar-date-style 'european)
14892 (list arg2 arg1 arg3))
14893 ((eq calendar-date-style 'iso)
14894 (list arg2 arg3 arg1)))
14895 (with-no-warnings ;; european-calendar-style is obsolete as of version 23.1
14896 (if (org-bound-and-true-p european-calendar-style)
14897 (list arg2 arg1 arg3)
14898 (list arg1 arg2 arg3)))))
14900 (defun org-eval-in-calendar (form &optional keepdate)
14901 "Eval FORM in the calendar window and return to current window.
14902 Also, store the cursor date in variable org-ans2."
14903 (let ((sf (selected-frame))
14904 (sw (selected-window)))
14905 (select-window (get-buffer-window "*Calendar*" t))
14906 (eval form)
14907 (when (and (not keepdate) (calendar-cursor-to-date))
14908 (let* ((date (calendar-cursor-to-date))
14909 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14910 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
14911 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
14912 (select-window sw)
14913 (org-select-frame-set-input-focus sf)))
14915 (defun org-calendar-select ()
14916 "Return to `org-read-date' with the date currently selected.
14917 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
14918 (interactive)
14919 (when (calendar-cursor-to-date)
14920 (let* ((date (calendar-cursor-to-date))
14921 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14922 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
14923 (if (active-minibuffer-window) (exit-minibuffer))))
14925 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
14926 "Insert a date stamp for the date given by the internal TIME.
14927 WITH-HM means use the stamp format that includes the time of the day.
14928 INACTIVE means use square brackets instead of angular ones, so that the
14929 stamp will not contribute to the agenda.
14930 PRE and POST are optional strings to be inserted before and after the
14931 stamp.
14932 The command returns the inserted time stamp."
14933 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
14934 stamp)
14935 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
14936 (insert-before-markers (or pre ""))
14937 (when (listp extra)
14938 (setq extra (car extra))
14939 (if (and (stringp extra)
14940 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
14941 (setq extra (format "-%02d:%02d"
14942 (string-to-number (match-string 1 extra))
14943 (string-to-number (match-string 2 extra))))
14944 (setq extra nil)))
14945 (when extra
14946 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
14947 (insert-before-markers (setq stamp (format-time-string fmt time)))
14948 (insert-before-markers (or post ""))
14949 (setq org-last-inserted-timestamp stamp)))
14951 (defun org-toggle-time-stamp-overlays ()
14952 "Toggle the use of custom time stamp formats."
14953 (interactive)
14954 (setq org-display-custom-times (not org-display-custom-times))
14955 (unless org-display-custom-times
14956 (let ((p (point-min)) (bmp (buffer-modified-p)))
14957 (while (setq p (next-single-property-change p 'display))
14958 (if (and (get-text-property p 'display)
14959 (eq (get-text-property p 'face) 'org-date))
14960 (remove-text-properties
14961 p (setq p (next-single-property-change p 'display))
14962 '(display t))))
14963 (set-buffer-modified-p bmp)))
14964 (if (featurep 'xemacs)
14965 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
14966 (org-restart-font-lock)
14967 (setq org-table-may-need-update t)
14968 (if org-display-custom-times
14969 (message "Time stamps are overlayed with custom format")
14970 (message "Time stamp overlays removed")))
14972 (defun org-display-custom-time (beg end)
14973 "Overlay modified time stamp format over timestamp between BEG and END."
14974 (let* ((ts (buffer-substring beg end))
14975 t1 w1 with-hm tf time str w2 (off 0))
14976 (save-match-data
14977 (setq t1 (org-parse-time-string ts t))
14978 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
14979 (setq off (- (match-end 0) (match-beginning 0)))))
14980 (setq end (- end off))
14981 (setq w1 (- end beg)
14982 with-hm (and (nth 1 t1) (nth 2 t1))
14983 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
14984 time (org-fix-decoded-time t1)
14985 str (org-add-props
14986 (format-time-string
14987 (substring tf 1 -1) (apply 'encode-time time))
14988 nil 'mouse-face 'highlight)
14989 w2 (length str))
14990 (if (not (= w2 w1))
14991 (add-text-properties (1+ beg) (+ 2 beg)
14992 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
14993 (if (featurep 'xemacs)
14994 (progn
14995 (put-text-property beg end 'invisible t)
14996 (put-text-property beg end 'end-glyph (make-glyph str)))
14997 (put-text-property beg end 'display str))))
14999 (defun org-translate-time (string)
15000 "Translate all timestamps in STRING to custom format.
15001 But do this only if the variable `org-display-custom-times' is set."
15002 (when org-display-custom-times
15003 (save-match-data
15004 (let* ((start 0)
15005 (re org-ts-regexp-both)
15006 t1 with-hm inactive tf time str beg end)
15007 (while (setq start (string-match re string start))
15008 (setq beg (match-beginning 0)
15009 end (match-end 0)
15010 t1 (save-match-data
15011 (org-parse-time-string (substring string beg end) t))
15012 with-hm (and (nth 1 t1) (nth 2 t1))
15013 inactive (equal (substring string beg (1+ beg)) "[")
15014 tf (funcall (if with-hm 'cdr 'car)
15015 org-time-stamp-custom-formats)
15016 time (org-fix-decoded-time t1)
15017 str (format-time-string
15018 (concat
15019 (if inactive "[" "<") (substring tf 1 -1)
15020 (if inactive "]" ">"))
15021 (apply 'encode-time time))
15022 string (replace-match str t t string)
15023 start (+ start (length str)))))))
15024 string)
15026 (defun org-fix-decoded-time (time)
15027 "Set 0 instead of nil for the first 6 elements of time.
15028 Don't touch the rest."
15029 (let ((n 0))
15030 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15032 (defun org-days-to-time (timestamp-string)
15033 "Difference between TIMESTAMP-STRING and now in days."
15034 (- (time-to-days (org-time-string-to-time timestamp-string))
15035 (time-to-days (current-time))))
15037 (defun org-deadline-close (timestamp-string &optional ndays)
15038 "Is the time in TIMESTAMP-STRING close to the current date?"
15039 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15040 (and (< (org-days-to-time timestamp-string) ndays)
15041 (not (org-entry-is-done-p))))
15043 (defun org-get-wdays (ts)
15044 "Get the deadline lead time appropriate for timestring TS."
15045 (cond
15046 ((<= org-deadline-warning-days 0)
15047 ;; 0 or negative, enforce this value no matter what
15048 (- org-deadline-warning-days))
15049 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
15050 ;; lead time is specified.
15051 (floor (* (string-to-number (match-string 1 ts))
15052 (cdr (assoc (match-string 2 ts)
15053 '(("d" . 1) ("w" . 7)
15054 ("m" . 30.4) ("y" . 365.25)))))))
15055 ;; go for the default.
15056 (t org-deadline-warning-days)))
15058 (defun org-calendar-select-mouse (ev)
15059 "Return to `org-read-date' with the date currently selected.
15060 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15061 (interactive "e")
15062 (mouse-set-point ev)
15063 (when (calendar-cursor-to-date)
15064 (let* ((date (calendar-cursor-to-date))
15065 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15066 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15067 (if (active-minibuffer-window) (exit-minibuffer))))
15069 (defun org-check-deadlines (ndays)
15070 "Check if there are any deadlines due or past due.
15071 A deadline is considered due if it happens within `org-deadline-warning-days'
15072 days from today's date. If the deadline appears in an entry marked DONE,
15073 it is not shown. The prefix arg NDAYS can be used to test that many
15074 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15075 (interactive "P")
15076 (let* ((org-warn-days
15077 (cond
15078 ((equal ndays '(4)) 100000)
15079 (ndays (prefix-numeric-value ndays))
15080 (t (abs org-deadline-warning-days))))
15081 (case-fold-search nil)
15082 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15083 (callback
15084 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15086 (message "%d deadlines past-due or due within %d days"
15087 (org-occur regexp nil callback)
15088 org-warn-days)))
15090 (defun org-check-before-date (date)
15091 "Check if there are deadlines or scheduled entries before DATE."
15092 (interactive (list (org-read-date)))
15093 (let ((case-fold-search nil)
15094 (regexp (concat "\\<\\(" org-deadline-string
15095 "\\|" org-scheduled-string
15096 "\\) *<\\([^>]+\\)>"))
15097 (callback
15098 (lambda () (time-less-p
15099 (org-time-string-to-time (match-string 2))
15100 (org-time-string-to-time date)))))
15101 (message "%d entries before %s"
15102 (org-occur regexp nil callback) date)))
15104 (defun org-check-after-date (date)
15105 "Check if there are deadlines or scheduled entries after DATE."
15106 (interactive (list (org-read-date)))
15107 (let ((case-fold-search nil)
15108 (regexp (concat "\\<\\(" org-deadline-string
15109 "\\|" org-scheduled-string
15110 "\\) *<\\([^>]+\\)>"))
15111 (callback
15112 (lambda () (not
15113 (time-less-p
15114 (org-time-string-to-time (match-string 2))
15115 (org-time-string-to-time date))))))
15116 (message "%d entries after %s"
15117 (org-occur regexp nil callback) date)))
15119 (defun org-evaluate-time-range (&optional to-buffer)
15120 "Evaluate a time range by computing the difference between start and end.
15121 Normally the result is just printed in the echo area, but with prefix arg
15122 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15123 If the time range is actually in a table, the result is inserted into the
15124 next column.
15125 For time difference computation, a year is assumed to be exactly 365
15126 days in order to avoid rounding problems."
15127 (interactive "P")
15129 (org-clock-update-time-maybe)
15130 (save-excursion
15131 (unless (org-at-date-range-p t)
15132 (goto-char (point-at-bol))
15133 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15134 (if (not (org-at-date-range-p t))
15135 (error "Not at a time-stamp range, and none found in current line")))
15136 (let* ((ts1 (match-string 1))
15137 (ts2 (match-string 2))
15138 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15139 (match-end (match-end 0))
15140 (time1 (org-time-string-to-time ts1))
15141 (time2 (org-time-string-to-time ts2))
15142 (t1 (org-float-time time1))
15143 (t2 (org-float-time time2))
15144 (diff (abs (- t2 t1)))
15145 (negative (< (- t2 t1) 0))
15146 ;; (ys (floor (* 365 24 60 60)))
15147 (ds (* 24 60 60))
15148 (hs (* 60 60))
15149 (fy "%dy %dd %02d:%02d")
15150 (fy1 "%dy %dd")
15151 (fd "%dd %02d:%02d")
15152 (fd1 "%dd")
15153 (fh "%02d:%02d")
15154 y d h m align)
15155 (if havetime
15156 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15158 d (floor (/ diff ds)) diff (mod diff ds)
15159 h (floor (/ diff hs)) diff (mod diff hs)
15160 m (floor (/ diff 60)))
15161 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15163 d (floor (+ (/ diff ds) 0.5))
15164 h 0 m 0))
15165 (if (not to-buffer)
15166 (message "%s" (org-make-tdiff-string y d h m))
15167 (if (org-at-table-p)
15168 (progn
15169 (goto-char match-end)
15170 (setq align t)
15171 (and (looking-at " *|") (goto-char (match-end 0))))
15172 (goto-char match-end))
15173 (if (looking-at
15174 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15175 (replace-match ""))
15176 (if negative (insert " -"))
15177 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15178 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15179 (insert " " (format fh h m))))
15180 (if align (org-table-align))
15181 (message "Time difference inserted")))))
15183 (defun org-make-tdiff-string (y d h m)
15184 (let ((fmt "")
15185 (l nil))
15186 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15187 l (push y l)))
15188 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15189 l (push d l)))
15190 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15191 l (push h l)))
15192 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15193 l (push m l)))
15194 (apply 'format fmt (nreverse l))))
15196 (defun org-time-string-to-time (s)
15197 (apply 'encode-time (org-parse-time-string s)))
15198 (defun org-time-string-to-seconds (s)
15199 (org-float-time (org-time-string-to-time s)))
15201 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
15202 "Convert a time stamp to an absolute day number.
15203 If there is a specifier for a cyclic time stamp, get the closest date to
15204 DAYNR.
15205 PREFER and SHOW-ALL are passed through to `org-closest-date'.
15206 The variable date is bound by the calendar when this is called."
15207 (cond
15208 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15209 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15210 daynr
15211 (+ daynr 1000)))
15212 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
15213 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15214 (time-to-days (current-time))) (match-string 0 s)
15215 prefer show-all))
15216 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
15218 (defun org-days-to-iso-week (days)
15219 "Return the iso week number."
15220 (require 'cal-iso)
15221 (car (calendar-iso-from-absolute days)))
15223 (defun org-small-year-to-year (year)
15224 "Convert 2-digit years into 4-digit years.
15225 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15226 The year 2000 cannot be abbreviated. Any year larger than 99
15227 is returned unchanged."
15228 (if (< year 38)
15229 (setq year (+ 2000 year))
15230 (if (< year 100)
15231 (setq year (+ 1900 year))))
15232 year)
15234 (defun org-time-from-absolute (d)
15235 "Return the time corresponding to date D.
15236 D may be an absolute day number, or a calendar-type list (month day year)."
15237 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15238 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15240 (defun org-calendar-holiday ()
15241 "List of holidays, for Diary display in Org-mode."
15242 (require 'holidays)
15243 (let ((hl (funcall
15244 (if (fboundp 'calendar-check-holidays)
15245 'calendar-check-holidays 'check-calendar-holidays) date)))
15246 (if hl (mapconcat 'identity hl "; "))))
15248 (defun org-diary-sexp-entry (sexp entry date)
15249 "Process a SEXP diary ENTRY for DATE."
15250 (require 'diary-lib)
15251 (let ((result (if calendar-debug-sexp
15252 (let ((stack-trace-on-error t))
15253 (eval (car (read-from-string sexp))))
15254 (condition-case nil
15255 (eval (car (read-from-string sexp)))
15256 (error
15257 (beep)
15258 (message "Bad sexp at line %d in %s: %s"
15259 (org-current-line)
15260 (buffer-file-name) sexp)
15261 (sleep-for 2))))))
15262 (cond ((stringp result) (split-string result "; "))
15263 ((and (consp result)
15264 (not (consp (cdr result)))
15265 (stringp (cdr result))) (cdr result))
15266 ((and (consp result)
15267 (stringp (car result))) result)
15268 (result entry)
15269 (t nil))))
15271 (defun org-diary-to-ical-string (frombuf)
15272 "Get iCalendar entries from diary entries in buffer FROMBUF.
15273 This uses the icalendar.el library."
15274 (let* ((tmpdir (if (featurep 'xemacs)
15275 (temp-directory)
15276 temporary-file-directory))
15277 (tmpfile (make-temp-name
15278 (expand-file-name "orgics" tmpdir)))
15279 buf rtn b e)
15280 (with-current-buffer frombuf
15281 (icalendar-export-region (point-min) (point-max) tmpfile)
15282 (setq buf (find-buffer-visiting tmpfile))
15283 (set-buffer buf)
15284 (goto-char (point-min))
15285 (if (re-search-forward "^BEGIN:VEVENT" nil t)
15286 (setq b (match-beginning 0)))
15287 (goto-char (point-max))
15288 (if (re-search-backward "^END:VEVENT" nil t)
15289 (setq e (match-end 0)))
15290 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
15291 (kill-buffer buf)
15292 (delete-file tmpfile)
15293 rtn))
15295 (defun org-closest-date (start current change prefer show-all)
15296 "Find the date closest to CURRENT that is consistent with START and CHANGE.
15297 When PREFER is `past', return a date that is either CURRENT or past.
15298 When PREFER is `future', return a date that is either CURRENT or future.
15299 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
15300 ;; Make the proper lists from the dates
15301 (catch 'exit
15302 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
15303 dn dw sday cday n1 n2 n0
15304 d m y y1 y2 date1 date2 nmonths nm ny m2)
15306 (setq start (org-date-to-gregorian start)
15307 current (org-date-to-gregorian
15308 (if show-all
15309 current
15310 (time-to-days (current-time))))
15311 sday (calendar-absolute-from-gregorian start)
15312 cday (calendar-absolute-from-gregorian current))
15314 (if (<= cday sday) (throw 'exit sday))
15316 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
15317 (setq dn (string-to-number (match-string 1 change))
15318 dw (cdr (assoc (match-string 2 change) a1)))
15319 (error "Invalid change specifier: %s" change))
15320 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
15321 (cond
15322 ((eq dw 'day)
15323 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
15324 n2 (+ n1 dn)))
15325 ((eq dw 'year)
15326 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
15327 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
15328 (setq date1 (list m d y1)
15329 n1 (calendar-absolute-from-gregorian date1)
15330 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
15331 n2 (calendar-absolute-from-gregorian date2)))
15332 ((eq dw 'month)
15333 ;; approx number of month between the two dates
15334 (setq nmonths (floor (/ (- cday sday) 30.436875)))
15335 ;; How often does dn fit in there?
15336 (setq d (nth 1 start) m (car start) y (nth 2 start)
15337 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
15338 m (+ m nm)
15339 ny (floor (/ m 12))
15340 y (+ y ny)
15341 m (- m (* ny 12)))
15342 (while (> m 12) (setq m (- m 12) y (1+ y)))
15343 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
15344 (setq m2 (+ m dn) y2 y)
15345 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15346 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
15347 (while (<= n2 cday)
15348 (setq n1 n2 m m2 y y2)
15349 (setq m2 (+ m dn) y2 y)
15350 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15351 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
15352 ;; Make sure n1 is the earlier date
15353 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
15354 (if show-all
15355 (cond
15356 ((eq prefer 'past) (if (= cday n2) n2 n1))
15357 ((eq prefer 'future) (if (= cday n1) n1 n2))
15358 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
15359 (cond
15360 ((eq prefer 'past) (if (= cday n2) n2 n1))
15361 ((eq prefer 'future) (if (= cday n1) n1 n2))
15362 (t (if (= cday n1) n1 n2)))))))
15364 (defun org-date-to-gregorian (date)
15365 "Turn any specification of DATE into a Gregorian date for the calendar."
15366 (cond ((integerp date) (calendar-gregorian-from-absolute date))
15367 ((and (listp date) (= (length date) 3)) date)
15368 ((stringp date)
15369 (setq date (org-parse-time-string date))
15370 (list (nth 4 date) (nth 3 date) (nth 5 date)))
15371 ((listp date)
15372 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
15374 (defun org-parse-time-string (s &optional nodefault)
15375 "Parse the standard Org-mode time string.
15376 This should be a lot faster than the normal `parse-time-string'.
15377 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
15378 hour and minute fields will be nil if not given."
15379 (if (string-match org-ts-regexp0 s)
15380 (list 0
15381 (if (or (match-beginning 8) (not nodefault))
15382 (string-to-number (or (match-string 8 s) "0")))
15383 (if (or (match-beginning 7) (not nodefault))
15384 (string-to-number (or (match-string 7 s) "0")))
15385 (string-to-number (match-string 4 s))
15386 (string-to-number (match-string 3 s))
15387 (string-to-number (match-string 2 s))
15388 nil nil nil)
15389 (error "Not a standard Org-mode time string: %s" s)))
15391 (defun org-timestamp-up (&optional arg)
15392 "Increase the date item at the cursor by one.
15393 If the cursor is on the year, change the year. If it is on the month or
15394 the day, change that.
15395 With prefix ARG, change by that many units."
15396 (interactive "p")
15397 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
15399 (defun org-timestamp-down (&optional arg)
15400 "Decrease the date item at the cursor by one.
15401 If the cursor is on the year, change the year. If it is on the month or
15402 the day, change that.
15403 With prefix ARG, change by that many units."
15404 (interactive "p")
15405 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
15407 (defun org-timestamp-up-day (&optional arg)
15408 "Increase the date in the time stamp by one day.
15409 With prefix ARG, change that many days."
15410 (interactive "p")
15411 (if (and (not (org-at-timestamp-p t))
15412 (org-on-heading-p))
15413 (org-todo 'up)
15414 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
15416 (defun org-timestamp-down-day (&optional arg)
15417 "Decrease the date in the time stamp by one day.
15418 With prefix ARG, change that many days."
15419 (interactive "p")
15420 (if (and (not (org-at-timestamp-p t))
15421 (org-on-heading-p))
15422 (org-todo 'down)
15423 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
15425 (defun org-at-timestamp-p (&optional inactive-ok)
15426 "Determine if the cursor is in or at a timestamp."
15427 (interactive)
15428 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
15429 (pos (point))
15430 (ans (or (looking-at tsr)
15431 (save-excursion
15432 (skip-chars-backward "^[<\n\r\t")
15433 (if (> (point) (point-min)) (backward-char 1))
15434 (and (looking-at tsr)
15435 (> (- (match-end 0) pos) -1))))))
15436 (and ans
15437 (boundp 'org-ts-what)
15438 (setq org-ts-what
15439 (cond
15440 ((= pos (match-beginning 0)) 'bracket)
15441 ((= pos (1- (match-end 0))) 'bracket)
15442 ((org-pos-in-match-range pos 2) 'year)
15443 ((org-pos-in-match-range pos 3) 'month)
15444 ((org-pos-in-match-range pos 7) 'hour)
15445 ((org-pos-in-match-range pos 8) 'minute)
15446 ((or (org-pos-in-match-range pos 4)
15447 (org-pos-in-match-range pos 5)) 'day)
15448 ((and (> pos (or (match-end 8) (match-end 5)))
15449 (< pos (match-end 0)))
15450 (- pos (or (match-end 8) (match-end 5))))
15451 (t 'day))))
15452 ans))
15454 (defun org-toggle-timestamp-type ()
15455 "Toggle the type (<active> or [inactive]) of a time stamp."
15456 (interactive)
15457 (when (org-at-timestamp-p t)
15458 (let ((beg (match-beginning 0)) (end (match-end 0))
15459 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
15460 (save-excursion
15461 (goto-char beg)
15462 (while (re-search-forward "[][<>]" end t)
15463 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
15464 t t)))
15465 (message "Timestamp is now %sactive"
15466 (if (equal (char-after beg) ?<) "" "in")))))
15468 (defun org-timestamp-change (n &optional what updown)
15469 "Change the date in the time stamp at point.
15470 The date will be changed by N times WHAT. WHAT can be `day', `month',
15471 `year', `minute', `second'. If WHAT is not given, the cursor position
15472 in the timestamp determines what will be changed."
15473 (let ((pos (point))
15474 with-hm inactive
15475 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
15476 org-ts-what
15477 extra rem
15478 ts time time0)
15479 (if (not (org-at-timestamp-p t))
15480 (error "Not at a timestamp"))
15481 (if (and (not what) (eq org-ts-what 'bracket))
15482 (org-toggle-timestamp-type)
15483 (if (and (not what) (not (eq org-ts-what 'day))
15484 org-display-custom-times
15485 (get-text-property (point) 'display)
15486 (not (get-text-property (1- (point)) 'display)))
15487 (setq org-ts-what 'day))
15488 (setq org-ts-what (or what org-ts-what)
15489 inactive (= (char-after (match-beginning 0)) ?\[)
15490 ts (match-string 0))
15491 (replace-match "")
15492 (if (string-match
15493 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
15495 (setq extra (match-string 1 ts)))
15496 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
15497 (setq with-hm t))
15498 (setq time0 (org-parse-time-string ts))
15499 (when (and updown
15500 (eq org-ts-what 'minute)
15501 (not current-prefix-arg))
15502 ;; This looks like s-up and s-down. Change by one rounding step.
15503 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
15504 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
15505 (setcar (cdr time0) (+ (nth 1 time0)
15506 (if (> n 0) (- rem) (- dm rem))))))
15507 (setq time
15508 (encode-time (or (car time0) 0)
15509 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
15510 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
15511 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
15512 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
15513 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
15514 (nthcdr 6 time0)))
15515 (when (and (member org-ts-what '(hour minute))
15516 extra
15517 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
15518 (setq extra (org-modify-ts-extra
15519 extra
15520 (if (eq org-ts-what 'hour) 2 5)
15521 n dm)))
15522 (when (integerp org-ts-what)
15523 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
15524 (if (eq what 'calendar)
15525 (let ((cal-date (org-get-date-from-calendar)))
15526 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
15527 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
15528 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
15529 (setcar time0 (or (car time0) 0))
15530 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
15531 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
15532 (setq time (apply 'encode-time time0))))
15533 (setq org-last-changed-timestamp
15534 (org-insert-time-stamp time with-hm inactive nil nil extra))
15535 (org-clock-update-time-maybe)
15536 (goto-char pos)
15537 ;; Try to recenter the calendar window, if any
15538 (if (and org-calendar-follow-timestamp-change
15539 (get-buffer-window "*Calendar*" t)
15540 (memq org-ts-what '(day month year)))
15541 (org-recenter-calendar (time-to-days time))))))
15543 (defun org-modify-ts-extra (s pos n dm)
15544 "Change the different parts of the lead-time and repeat fields in timestamp."
15545 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
15546 ng h m new rem)
15547 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
15548 (cond
15549 ((or (org-pos-in-match-range pos 2)
15550 (org-pos-in-match-range pos 3))
15551 (setq m (string-to-number (match-string 3 s))
15552 h (string-to-number (match-string 2 s)))
15553 (if (org-pos-in-match-range pos 2)
15554 (setq h (+ h n))
15555 (setq n (* dm (org-no-warnings (signum n))))
15556 (when (not (= 0 (setq rem (% m dm))))
15557 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
15558 (setq m (+ m n)))
15559 (if (< m 0) (setq m (+ m 60) h (1- h)))
15560 (if (> m 59) (setq m (- m 60) h (1+ h)))
15561 (setq h (min 24 (max 0 h)))
15562 (setq ng 1 new (format "-%02d:%02d" h m)))
15563 ((org-pos-in-match-range pos 6)
15564 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
15565 ((org-pos-in-match-range pos 5)
15566 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
15568 ((org-pos-in-match-range pos 9)
15569 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
15570 ((org-pos-in-match-range pos 8)
15571 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
15573 (when ng
15574 (setq s (concat
15575 (substring s 0 (match-beginning ng))
15577 (substring s (match-end ng))))))
15580 (defun org-recenter-calendar (date)
15581 "If the calendar is visible, recenter it to DATE."
15582 (let* ((win (selected-window))
15583 (cwin (get-buffer-window "*Calendar*" t))
15584 (calendar-move-hook nil))
15585 (when cwin
15586 (select-window cwin)
15587 (calendar-goto-date (if (listp date) date
15588 (calendar-gregorian-from-absolute date)))
15589 (select-window win))))
15591 (defun org-goto-calendar (&optional arg)
15592 "Go to the Emacs calendar at the current date.
15593 If there is a time stamp in the current line, go to that date.
15594 A prefix ARG can be used to force the current date."
15595 (interactive "P")
15596 (let ((tsr org-ts-regexp) diff
15597 (calendar-move-hook nil)
15598 (calendar-view-holidays-initially-flag nil)
15599 (calendar-view-diary-initially-flag nil))
15600 (if (or (org-at-timestamp-p)
15601 (save-excursion
15602 (beginning-of-line 1)
15603 (looking-at (concat ".*" tsr))))
15604 (let ((d1 (time-to-days (current-time)))
15605 (d2 (time-to-days
15606 (org-time-string-to-time (match-string 1)))))
15607 (setq diff (- d2 d1))))
15608 (calendar)
15609 (calendar-goto-today)
15610 (if (and diff (not arg)) (calendar-forward-day diff))))
15612 (defun org-get-date-from-calendar ()
15613 "Return a list (month day year) of date at point in calendar."
15614 (with-current-buffer "*Calendar*"
15615 (save-match-data
15616 (calendar-cursor-to-date))))
15618 (defun org-date-from-calendar ()
15619 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
15620 If there is already a time stamp at the cursor position, update it."
15621 (interactive)
15622 (if (org-at-timestamp-p t)
15623 (org-timestamp-change 0 'calendar)
15624 (let ((cal-date (org-get-date-from-calendar)))
15625 (org-insert-time-stamp
15626 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
15628 (defun org-minutes-to-hh:mm-string (m)
15629 "Compute H:MM from a number of minutes."
15630 (let ((h (/ m 60)))
15631 (setq m (- m (* 60 h)))
15632 (format org-time-clocksum-format h m)))
15634 (defun org-hh:mm-string-to-minutes (s)
15635 "Convert a string H:MM to a number of minutes.
15636 If the string is just a number, interpret it as minutes.
15637 In fact, the first hh:mm or number in the string will be taken,
15638 there can be extra stuff in the string.
15639 If no number is found, the return value is 0."
15640 (cond
15641 ((integerp s) s)
15642 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
15643 (+ (* (string-to-number (match-string 1 s)) 60)
15644 (string-to-number (match-string 2 s))))
15645 ((string-match "\\([0-9]+\\)" s)
15646 (string-to-number (match-string 1 s)))
15647 (t 0)))
15649 (defcustom org-effort-durations
15650 `(("h" . 60)
15651 ("d" . ,(* 60 8))
15652 ("w" . ,(* 60 8 5))
15653 ("m" . ,(* 60 8 5 4))
15654 ("y" . ,(* 60 8 5 40)))
15655 "Conversion factor to minutes for an effort modifier.
15657 Each entry has the form (MODIFIER . MINUTES).
15659 In an effort string, a number followed by MODIFIER is multiplied
15660 by the specified number of MINUTES to obtain an effort in
15661 minutes.
15663 For example, if the value of this variable is ((\"hours\" . 60)), then an
15664 effort string \"2hours\" is equivalent to 120 minutes."
15665 :group 'org-agenda
15666 :type '(alist :key-type (string :tag "Modifier")
15667 :value-type (number :tag "Minutes")))
15669 (defun org-duration-string-to-minutes (s)
15670 "Convert a duration string S to minutes.
15672 A bare number is interpreted as minutes, modifiers can be set by
15673 customizing `org-effort-durations' (which see).
15675 Entries containing a colon are interpreted as H:MM by
15676 `org-hh:mm-string-to-minutes'."
15677 (let ((result 0)
15678 (re (concat "\\([0-9]+\\) *\\("
15679 (regexp-opt (mapcar 'car org-effort-durations))
15680 "\\)")))
15681 (while (string-match re s)
15682 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
15683 (string-to-number (match-string 1 s))))
15684 (setq s (replace-match "" nil t s)))
15685 (incf result (org-hh:mm-string-to-minutes s))
15686 result))
15688 ;;;; Files
15690 (defun org-save-all-org-buffers ()
15691 "Save all Org-mode buffers without user confirmation."
15692 (interactive)
15693 (message "Saving all Org-mode buffers...")
15694 (save-some-buffers t 'org-mode-p)
15695 (when (featurep 'org-id) (org-id-locations-save))
15696 (message "Saving all Org-mode buffers... done"))
15698 (defun org-revert-all-org-buffers ()
15699 "Revert all Org-mode buffers.
15700 Prompt for confirmation when there are unsaved changes.
15701 Be sure you know what you are doing before letting this function
15702 overwrite your changes.
15704 This function is useful in a setup where one tracks org files
15705 with a version control system, to revert on one machine after pulling
15706 changes from another. I believe the procedure must be like this:
15708 1. M-x org-save-all-org-buffers
15709 2. Pull changes from the other machine, resolve conflicts
15710 3. M-x org-revert-all-org-buffers"
15711 (interactive)
15712 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
15713 (error "Abort"))
15714 (save-excursion
15715 (save-window-excursion
15716 (mapc
15717 (lambda (b)
15718 (when (and (with-current-buffer b (org-mode-p))
15719 (with-current-buffer b buffer-file-name))
15720 (switch-to-buffer b)
15721 (revert-buffer t 'no-confirm)))
15722 (buffer-list))
15723 (when (and (featurep 'org-id) org-id-track-globally)
15724 (org-id-locations-load)))))
15726 ;;;; Agenda files
15728 ;;;###autoload
15729 (defun org-switchb (&optional arg)
15730 "Switch between Org buffers.
15731 With a prefix argument, restrict available to files.
15732 With two prefix arguments, restrict available buffers to agenda files.
15734 Defaults to `iswitchb' for buffer name completion.
15735 Set `org-completion-use-ido' to make it use ido instead."
15736 (interactive "P")
15737 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
15738 ((equal arg '(16)) (org-buffer-list 'agenda))
15739 (t (org-buffer-list))))
15740 (org-completion-use-iswitchb org-completion-use-iswitchb)
15741 (org-completion-use-ido org-completion-use-ido))
15742 (unless (or org-completion-use-ido org-completion-use-iswitchb)
15743 (setq org-completion-use-iswitchb t))
15744 (switch-to-buffer
15745 (org-icompleting-read "Org buffer: "
15746 (mapcar 'list (mapcar 'buffer-name blist))
15747 nil t))))
15749 ;;; Define some older names previously used for this functionality
15750 ;;;###autoload
15751 (defalias 'org-ido-switchb 'org-switchb)
15752 ;;;###autoload
15753 (defalias 'org-iswitchb 'org-switchb)
15755 (defun org-buffer-list (&optional predicate exclude-tmp)
15756 "Return a list of Org buffers.
15757 PREDICATE can be `export', `files' or `agenda'.
15759 export restrict the list to Export buffers.
15760 files restrict the list to buffers visiting Org files.
15761 agenda restrict the list to buffers visiting agenda files.
15763 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
15764 (let* ((bfn nil)
15765 (agenda-files (and (eq predicate 'agenda)
15766 (mapcar 'file-truename (org-agenda-files t))))
15767 (filter
15768 (cond
15769 ((eq predicate 'files)
15770 (lambda (b) (with-current-buffer b (org-mode-p))))
15771 ((eq predicate 'export)
15772 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
15773 ((eq predicate 'agenda)
15774 (lambda (b)
15775 (with-current-buffer b
15776 (and (org-mode-p)
15777 (setq bfn (buffer-file-name b))
15778 (member (file-truename bfn) agenda-files)))))
15779 (t (lambda (b) (with-current-buffer b
15780 (or (org-mode-p)
15781 (string-match "\*Org .*Export"
15782 (buffer-name b)))))))))
15783 (delq nil
15784 (mapcar
15785 (lambda(b)
15786 (if (and (funcall filter b)
15787 (or (not exclude-tmp)
15788 (not (string-match "tmp" (buffer-name b)))))
15790 nil))
15791 (buffer-list)))))
15793 (defun org-agenda-files (&optional unrestricted archives)
15794 "Get the list of agenda files.
15795 Optional UNRESTRICTED means return the full list even if a restriction
15796 is currently in place.
15797 When ARCHIVES is t, include all archive files that are really being
15798 used by the agenda files. If ARCHIVE is `ifmode', do this only if
15799 `org-agenda-archives-mode' is t."
15800 (let ((files
15801 (cond
15802 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
15803 ((stringp org-agenda-files) (org-read-agenda-file-list))
15804 ((listp org-agenda-files) org-agenda-files)
15805 (t (error "Invalid value of `org-agenda-files'")))))
15806 (setq files (apply 'append
15807 (mapcar (lambda (f)
15808 (if (file-directory-p f)
15809 (directory-files
15810 f t org-agenda-file-regexp)
15811 (list f)))
15812 files)))
15813 (when org-agenda-skip-unavailable-files
15814 (setq files (delq nil
15815 (mapcar (function
15816 (lambda (file)
15817 (and (file-readable-p file) file)))
15818 files))))
15819 (when (or (eq archives t)
15820 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
15821 (setq files (org-add-archive-files files)))
15822 files))
15824 (defun org-agenda-file-p (&optional file)
15825 "Return non-nil, if FILE is an agenda file.
15826 If FILE is omitted, use the file associated with the current
15827 buffer."
15828 (member (or file (buffer-file-name))
15829 (org-agenda-files t)))
15831 (defun org-edit-agenda-file-list ()
15832 "Edit the list of agenda files.
15833 Depending on setup, this either uses customize to edit the variable
15834 `org-agenda-files', or it visits the file that is holding the list. In the
15835 latter case, the buffer is set up in a way that saving it automatically kills
15836 the buffer and restores the previous window configuration."
15837 (interactive)
15838 (if (stringp org-agenda-files)
15839 (let ((cw (current-window-configuration)))
15840 (find-file org-agenda-files)
15841 (org-set-local 'org-window-configuration cw)
15842 (org-add-hook 'after-save-hook
15843 (lambda ()
15844 (set-window-configuration
15845 (prog1 org-window-configuration
15846 (kill-buffer (current-buffer))))
15847 (org-install-agenda-files-menu)
15848 (message "New agenda file list installed"))
15849 nil 'local)
15850 (message "%s" (substitute-command-keys
15851 "Edit list and finish with \\[save-buffer]")))
15852 (customize-variable 'org-agenda-files)))
15854 (defun org-store-new-agenda-file-list (list)
15855 "Set new value for the agenda file list and save it correctly."
15856 (if (stringp org-agenda-files)
15857 (let ((fe (org-read-agenda-file-list t)) b u)
15858 (while (setq b (find-buffer-visiting org-agenda-files))
15859 (kill-buffer b))
15860 (with-temp-file org-agenda-files
15861 (insert
15862 (mapconcat
15863 (lambda (f) ;; Keep un-expanded entries.
15864 (if (setq u (assoc f fe))
15865 (cdr u)
15867 list "\n")
15868 "\n")))
15869 (let ((org-mode-hook nil) (org-inhibit-startup t)
15870 (org-insert-mode-line-in-empty-file nil))
15871 (setq org-agenda-files list)
15872 (customize-save-variable 'org-agenda-files org-agenda-files))))
15874 (defun org-read-agenda-file-list (&optional pair-with-expansion)
15875 "Read the list of agenda files from a file.
15876 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
15877 filenames, used by `org-store-new-agenda-file-list' to write back
15878 un-expanded file names."
15879 (when (file-directory-p org-agenda-files)
15880 (error "`org-agenda-files' cannot be a single directory"))
15881 (when (stringp org-agenda-files)
15882 (with-temp-buffer
15883 (insert-file-contents org-agenda-files)
15884 (mapcar
15885 (lambda (f)
15886 (let ((e (expand-file-name (substitute-in-file-name f)
15887 org-directory)))
15888 (if pair-with-expansion
15889 (cons e f)
15890 e)))
15891 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
15893 ;;;###autoload
15894 (defun org-cycle-agenda-files ()
15895 "Cycle through the files in `org-agenda-files'.
15896 If the current buffer visits an agenda file, find the next one in the list.
15897 If the current buffer does not, find the first agenda file."
15898 (interactive)
15899 (let* ((fs (org-agenda-files t))
15900 (files (append fs (list (car fs))))
15901 (tcf (if buffer-file-name (file-truename buffer-file-name)))
15902 file)
15903 (unless files (error "No agenda files"))
15904 (catch 'exit
15905 (while (setq file (pop files))
15906 (if (equal (file-truename file) tcf)
15907 (when (car files)
15908 (find-file (car files))
15909 (throw 'exit t))))
15910 (find-file (car fs)))
15911 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
15913 (defun org-agenda-file-to-front (&optional to-end)
15914 "Move/add the current file to the top of the agenda file list.
15915 If the file is not present in the list, it is added to the front. If it is
15916 present, it is moved there. With optional argument TO-END, add/move to the
15917 end of the list."
15918 (interactive "P")
15919 (let ((org-agenda-skip-unavailable-files nil)
15920 (file-alist (mapcar (lambda (x)
15921 (cons (file-truename x) x))
15922 (org-agenda-files t)))
15923 (ctf (file-truename buffer-file-name))
15924 x had)
15925 (setq x (assoc ctf file-alist) had x)
15927 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
15928 (if to-end
15929 (setq file-alist (append (delq x file-alist) (list x)))
15930 (setq file-alist (cons x (delq x file-alist))))
15931 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
15932 (org-install-agenda-files-menu)
15933 (message "File %s to %s of agenda file list"
15934 (if had "moved" "added") (if to-end "end" "front"))))
15936 (defun org-remove-file (&optional file)
15937 "Remove current file from the list of files in variable `org-agenda-files'.
15938 These are the files which are being checked for agenda entries.
15939 Optional argument FILE means use this file instead of the current."
15940 (interactive)
15941 (let* ((org-agenda-skip-unavailable-files nil)
15942 (file (or file buffer-file-name))
15943 (true-file (file-truename file))
15944 (afile (abbreviate-file-name file))
15945 (files (delq nil (mapcar
15946 (lambda (x)
15947 (if (equal true-file
15948 (file-truename x))
15949 nil x))
15950 (org-agenda-files t)))))
15951 (if (not (= (length files) (length (org-agenda-files t))))
15952 (progn
15953 (org-store-new-agenda-file-list files)
15954 (org-install-agenda-files-menu)
15955 (message "Removed file: %s" afile))
15956 (message "File was not in list: %s (not removed)" afile))))
15958 (defun org-file-menu-entry (file)
15959 (vector file (list 'find-file file) t))
15961 (defun org-check-agenda-file (file)
15962 "Make sure FILE exists. If not, ask user what to do."
15963 (when (not (file-exists-p file))
15964 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
15965 (abbreviate-file-name file))
15966 (let ((r (downcase (read-char-exclusive))))
15967 (cond
15968 ((equal r ?r)
15969 (org-remove-file file)
15970 (throw 'nextfile t))
15971 (t (error "Abort"))))))
15973 (defun org-get-agenda-file-buffer (file)
15974 "Get a buffer visiting FILE. If the buffer needs to be created, add
15975 it to the list of buffers which might be released later."
15976 (let ((buf (org-find-base-buffer-visiting file)))
15977 (if buf
15978 buf ; just return it
15979 ;; Make a new buffer and remember it
15980 (setq buf (find-file-noselect file))
15981 (if buf (push buf org-agenda-new-buffers))
15982 buf)))
15984 (defun org-release-buffers (blist)
15985 "Release all buffers in list, asking the user for confirmation when needed.
15986 When a buffer is unmodified, it is just killed. When modified, it is saved
15987 \(if the user agrees) and then killed."
15988 (let (buf file)
15989 (while (setq buf (pop blist))
15990 (setq file (buffer-file-name buf))
15991 (when (and (buffer-modified-p buf)
15992 file
15993 (y-or-n-p (format "Save file %s? " file)))
15994 (with-current-buffer buf (save-buffer)))
15995 (kill-buffer buf))))
15997 (defun org-prepare-agenda-buffers (files)
15998 "Create buffers for all agenda files, protect archived trees and comments."
15999 (interactive)
16000 (let ((pa '(:org-archived t))
16001 (pc '(:org-comment t))
16002 (pall '(:org-archived t :org-comment t))
16003 (inhibit-read-only t)
16004 (rea (concat ":" org-archive-tag ":"))
16005 bmp file re)
16006 (save-excursion
16007 (save-restriction
16008 (while (setq file (pop files))
16009 (catch 'nextfile
16010 (if (bufferp file)
16011 (set-buffer file)
16012 (org-check-agenda-file file)
16013 (set-buffer (org-get-agenda-file-buffer file)))
16014 (widen)
16015 (setq bmp (buffer-modified-p))
16016 (org-refresh-category-properties)
16017 (setq org-todo-keywords-for-agenda
16018 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16019 (setq org-done-keywords-for-agenda
16020 (append org-done-keywords-for-agenda org-done-keywords))
16021 (setq org-todo-keyword-alist-for-agenda
16022 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16023 (setq org-drawers-for-agenda
16024 (append org-drawers-for-agenda org-drawers))
16025 (setq org-tag-alist-for-agenda
16026 (append org-tag-alist-for-agenda org-tag-alist))
16028 (save-excursion
16029 (remove-text-properties (point-min) (point-max) pall)
16030 (when org-agenda-skip-archived-trees
16031 (goto-char (point-min))
16032 (while (re-search-forward rea nil t)
16033 (if (org-on-heading-p t)
16034 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16035 (goto-char (point-min))
16036 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
16037 (while (re-search-forward re nil t)
16038 (add-text-properties
16039 (match-beginning 0) (org-end-of-subtree t) pc)))
16040 (set-buffer-modified-p bmp)))))
16041 (setq org-todo-keywords-for-agenda
16042 (org-uniquify org-todo-keywords-for-agenda))
16043 (setq org-todo-keyword-alist-for-agenda
16044 (org-uniquify org-todo-keyword-alist-for-agenda)
16045 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16047 ;;;; Embedded LaTeX
16049 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16050 "Keymap for the minor `org-cdlatex-mode'.")
16052 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16053 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16054 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16055 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16056 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16058 (defvar org-cdlatex-texmathp-advice-is-done nil
16059 "Flag remembering if we have applied the advice to texmathp already.")
16061 (define-minor-mode org-cdlatex-mode
16062 "Toggle the minor `org-cdlatex-mode'.
16063 This mode supports entering LaTeX environment and math in LaTeX fragments
16064 in Org-mode.
16065 \\{org-cdlatex-mode-map}"
16066 nil " OCDL" nil
16067 (when org-cdlatex-mode (require 'cdlatex))
16068 (unless org-cdlatex-texmathp-advice-is-done
16069 (setq org-cdlatex-texmathp-advice-is-done t)
16070 (defadvice texmathp (around org-math-always-on activate)
16071 "Always return t in org-mode buffers.
16072 This is because we want to insert math symbols without dollars even outside
16073 the LaTeX math segments. If Orgmode thinks that point is actually inside
16074 an embedded LaTeX fragment, let texmathp do its job.
16075 \\[org-cdlatex-mode-map]"
16076 (interactive)
16077 (let (p)
16078 (cond
16079 ((not (org-mode-p)) ad-do-it)
16080 ((eq this-command 'cdlatex-math-symbol)
16081 (setq ad-return-value t
16082 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16084 (let ((p (org-inside-LaTeX-fragment-p)))
16085 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16086 (setq ad-return-value t
16087 texmathp-why '("Org-mode embedded math" . 0))
16088 (if p ad-do-it)))))))))
16090 (defun turn-on-org-cdlatex ()
16091 "Unconditionally turn on `org-cdlatex-mode'."
16092 (org-cdlatex-mode 1))
16094 (defun org-inside-LaTeX-fragment-p ()
16095 "Test if point is inside a LaTeX fragment.
16096 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16097 sequence appearing also before point.
16098 Even though the matchers for math are configurable, this function assumes
16099 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16100 delimiters are skipped when they have been removed by customization.
16101 The return value is nil, or a cons cell with the delimiter and
16102 and the position of this delimiter.
16104 This function does a reasonably good job, but can locally be fooled by
16105 for example currency specifications. For example it will assume being in
16106 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16107 fragments that are properly closed, but during editing, we have to live
16108 with the uncertainty caused by missing closing delimiters. This function
16109 looks only before point, not after."
16110 (catch 'exit
16111 (let ((pos (point))
16112 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16113 (lim (progn
16114 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16115 (point)))
16116 dd-on str (start 0) m re)
16117 (goto-char pos)
16118 (when dodollar
16119 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16120 re (nth 1 (assoc "$" org-latex-regexps)))
16121 (while (string-match re str start)
16122 (cond
16123 ((= (match-end 0) (length str))
16124 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16125 ((= (match-end 0) (- (length str) 5))
16126 (throw 'exit nil))
16127 (t (setq start (match-end 0))))))
16128 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16129 (goto-char pos)
16130 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16131 (and (match-beginning 2) (throw 'exit nil))
16132 ;; count $$
16133 (while (re-search-backward "\\$\\$" lim t)
16134 (setq dd-on (not dd-on)))
16135 (goto-char pos)
16136 (if dd-on (cons "$$" m))))))
16138 (defun org-inside-latex-macro-p ()
16139 "Is point inside a LaTeX macro or its arguments?"
16140 (save-match-data
16141 (org-in-regexp
16142 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16144 (defun org-try-cdlatex-tab ()
16145 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16146 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16147 - inside a LaTeX fragment, or
16148 - after the first word in a line, where an abbreviation expansion could
16149 insert a LaTeX environment."
16150 (when org-cdlatex-mode
16151 (cond
16152 ((save-excursion
16153 (skip-chars-backward "a-zA-Z0-9*")
16154 (skip-chars-backward " \t")
16155 (bolp))
16156 (cdlatex-tab) t)
16157 ((org-inside-LaTeX-fragment-p)
16158 (cdlatex-tab) t)
16159 (t nil))))
16161 (defun org-cdlatex-underscore-caret (&optional arg)
16162 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16163 Revert to the normal definition outside of these fragments."
16164 (interactive "P")
16165 (if (org-inside-LaTeX-fragment-p)
16166 (call-interactively 'cdlatex-sub-superscript)
16167 (let (org-cdlatex-mode)
16168 (call-interactively (key-binding (vector last-input-event))))))
16170 (defun org-cdlatex-math-modify (&optional arg)
16171 "Execute `cdlatex-math-modify' in LaTeX fragments.
16172 Revert to the normal definition outside of these fragments."
16173 (interactive "P")
16174 (if (org-inside-LaTeX-fragment-p)
16175 (call-interactively 'cdlatex-math-modify)
16176 (let (org-cdlatex-mode)
16177 (call-interactively (key-binding (vector last-input-event))))))
16179 (defvar org-latex-fragment-image-overlays nil
16180 "List of overlays carrying the images of latex fragments.")
16181 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16183 (defun org-remove-latex-fragment-image-overlays ()
16184 "Remove all overlays with LaTeX fragment images in current buffer."
16185 (mapc 'delete-overlay org-latex-fragment-image-overlays)
16186 (setq org-latex-fragment-image-overlays nil))
16188 (defun org-preview-latex-fragment (&optional subtree)
16189 "Preview the LaTeX fragment at point, or all locally or globally.
16190 If the cursor is in a LaTeX fragment, create the image and overlay
16191 it over the source code. If there is no fragment at point, display
16192 all fragments in the current text, from one headline to the next. With
16193 prefix SUBTREE, display all fragments in the current subtree. With a
16194 double prefix arg \\[universal-argument] \\[universal-argument], or when \
16195 the cursor is before the first headline,
16196 display all fragments in the buffer.
16197 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16198 (interactive "P")
16199 (org-remove-latex-fragment-image-overlays)
16200 (save-excursion
16201 (save-restriction
16202 (let (beg end at msg)
16203 (cond
16204 ((or (equal subtree '(16))
16205 (not (save-excursion
16206 (re-search-backward (concat "^" outline-regexp) nil t))))
16207 (setq beg (point-min) end (point-max)
16208 msg "Creating images for buffer...%s"))
16209 ((equal subtree '(4))
16210 (org-back-to-heading)
16211 (setq beg (point) end (org-end-of-subtree t)
16212 msg "Creating images for subtree...%s"))
16214 (if (setq at (org-inside-LaTeX-fragment-p))
16215 (goto-char (max (point-min) (- (cdr at) 2)))
16216 (org-back-to-heading))
16217 (setq beg (point) end (progn (outline-next-heading) (point))
16218 msg (if at "Creating image...%s"
16219 "Creating images for entry...%s"))))
16220 (message msg "")
16221 (narrow-to-region beg end)
16222 (goto-char beg)
16223 (org-format-latex
16224 (concat "ltxpng/" (file-name-sans-extension
16225 (file-name-nondirectory
16226 buffer-file-name)))
16227 default-directory 'overlays msg at 'forbuffer 'dvipng)
16228 (message msg "done. Use `C-c C-c' to remove images.")))))
16230 (defvar org-latex-regexps
16231 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16232 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16233 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16234 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16235 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16236 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16237 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
16238 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
16239 "Regular expressions for matching embedded LaTeX.")
16241 (defvar org-export-have-math nil) ;; dynamic scoping
16242 (defun org-format-latex (prefix &optional dir overlays msg at
16243 forbuffer processing-type)
16244 "Replace LaTeX fragments with links to an image, and produce images.
16245 Some of the options can be changed using the variable
16246 `org-format-latex-options'."
16247 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16248 (let* ((prefixnodir (file-name-nondirectory prefix))
16249 (absprefix (expand-file-name prefix dir))
16250 (todir (file-name-directory absprefix))
16251 (opt org-format-latex-options)
16252 (matchers (plist-get opt :matchers))
16253 (re-list org-latex-regexps)
16254 (org-format-latex-header-extra
16255 (plist-get (org-infile-export-plist) :latex-header-extra))
16256 (cnt 0) txt hash link beg end re e checkdir
16257 executables-checked string
16258 m n block linkfile movefile ov)
16259 ;; Check the different regular expressions
16260 (while (setq e (pop re-list))
16261 (setq m (car e) re (nth 1 e) n (nth 2 e)
16262 block (if (nth 3 e) "\n\n" ""))
16263 (when (member m matchers)
16264 (goto-char (point-min))
16265 (while (re-search-forward re nil t)
16266 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
16267 (not (get-text-property (match-beginning n)
16268 'org-protected))
16269 (or (not overlays)
16270 (not (eq (get-char-property (match-beginning n)
16271 'org-overlay-type)
16272 'org-latex-overlay))))
16273 (setq org-export-have-math t)
16274 (cond
16275 ((eq processing-type 'verbatim)
16276 ;; Leave the text verbatim, just protect it
16277 (add-text-properties (match-beginning n) (match-end n)
16278 '(org-protected t)))
16279 ((eq processing-type 'mathjax)
16280 ;; Prepare for MathJax processing
16281 (setq string (match-string n))
16282 (if (member m '("$" "$1"))
16283 (save-excursion
16284 (delete-region (match-beginning n) (match-end n))
16285 (goto-char (match-beginning n))
16286 (insert (org-add-props (concat "\\(" (substring string 1 -1)
16287 "\\)")
16288 '(org-protected t))))
16289 (add-text-properties (match-beginning n) (match-end n)
16290 '(org-protected t))))
16291 ((or (eq processing-type 'dvipng) t)
16292 ;; Process to an image
16293 (setq txt (match-string n)
16294 beg (match-beginning n) end (match-end n)
16295 cnt (1+ cnt))
16296 (let (print-length print-level) ; make sure full list is printed
16297 (setq hash (sha1 (prin1-to-string
16298 (list org-format-latex-header
16299 org-format-latex-header-extra
16300 org-export-latex-default-packages-alist
16301 org-export-latex-packages-alist
16302 org-format-latex-options
16303 forbuffer txt)))
16304 linkfile (format "%s_%s.png" prefix hash)
16305 movefile (format "%s_%s.png" absprefix hash)))
16306 (setq link (concat block "[[file:" linkfile "]]" block))
16307 (if msg (message msg cnt))
16308 (goto-char beg)
16309 (unless checkdir ; make sure the directory exists
16310 (setq checkdir t)
16311 (or (file-directory-p todir) (make-directory todir t)))
16313 (unless executables-checked
16314 (org-check-external-command
16315 "latex" "needed to convert LaTeX fragments to images")
16316 (org-check-external-command
16317 "dvipng" "needed to convert LaTeX fragments to images")
16318 (setq executables-checked t))
16320 (unless (file-exists-p movefile)
16321 (org-create-formula-image
16322 txt movefile opt forbuffer))
16323 (if overlays
16324 (progn
16325 (mapc (lambda (o)
16326 (if (eq (overlay-get o 'org-overlay-type)
16327 'org-latex-overlay)
16328 (delete-overlay o)))
16329 (overlays-in beg end))
16330 (setq ov (make-overlay beg end))
16331 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
16332 (if (featurep 'xemacs)
16333 (progn
16334 (overlay-put ov 'invisible t)
16335 (overlay-put
16336 ov 'end-glyph
16337 (make-glyph (vector 'png :file movefile))))
16338 (overlay-put
16339 ov 'display
16340 (list 'image :type 'png :file movefile :ascent 'center)))
16341 (push ov org-latex-fragment-image-overlays)
16342 (goto-char end))
16343 (delete-region beg end)
16344 (insert (org-add-props link
16345 (list 'org-latex-src
16346 (replace-regexp-in-string
16347 "\"" "" txt)))))))))))))
16349 ;; This function borrows from Ganesh Swami's latex2png.el
16350 (defun org-create-formula-image (string tofile options buffer)
16351 "This calls dvipng."
16352 (require 'org-latex)
16353 (let* ((tmpdir (if (featurep 'xemacs)
16354 (temp-directory)
16355 temporary-file-directory))
16356 (texfilebase (make-temp-name
16357 (expand-file-name "orgtex" tmpdir)))
16358 (texfile (concat texfilebase ".tex"))
16359 (dvifile (concat texfilebase ".dvi"))
16360 (pngfile (concat texfilebase ".png"))
16361 (fnh (if (featurep 'xemacs)
16362 (font-height (get-face-font 'default))
16363 (face-attribute 'default :height nil)))
16364 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
16365 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
16366 (fg (or (plist-get options (if buffer :foreground :html-foreground))
16367 "Black"))
16368 (bg (or (plist-get options (if buffer :background :html-background))
16369 "Transparent")))
16370 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
16371 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
16372 (with-temp-file texfile
16373 (insert (org-splice-latex-header
16374 org-format-latex-header
16375 org-export-latex-default-packages-alist
16376 org-export-latex-packages-alist t
16377 org-format-latex-header-extra))
16378 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
16379 (require 'org-latex)
16380 (org-export-latex-fix-inputenc))
16381 (let ((dir default-directory))
16382 (condition-case nil
16383 (progn
16384 (cd tmpdir)
16385 (call-process "latex" nil nil nil texfile))
16386 (error nil))
16387 (cd dir))
16388 (if (not (file-exists-p dvifile))
16389 (progn (message "Failed to create dvi file from %s" texfile) nil)
16390 (condition-case nil
16391 (call-process "dvipng" nil nil nil
16392 "-fg" fg "-bg" bg
16393 "-D" dpi
16394 ;;"-x" scale "-y" scale
16395 "-T" "tight"
16396 "-o" pngfile
16397 dvifile)
16398 (error nil))
16399 (if (not (file-exists-p pngfile))
16400 (if org-format-latex-signal-error
16401 (error "Failed to create png file from %s" texfile)
16402 (message "Failed to create png file from %s" texfile)
16403 nil)
16404 ;; Use the requested file name and clean up
16405 (copy-file pngfile tofile 'replace)
16406 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
16407 (delete-file (concat texfilebase e)))
16408 pngfile))))
16410 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
16411 "Fill a LaTeX header template TPL.
16412 In the template, the following place holders will be recognized:
16414 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
16415 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
16416 [PACKAGES] \\usepackage statements for PKG
16417 [NO-PACKAGES] do not include PKG
16418 [EXTRA] the string EXTRA
16419 [NO-EXTRA] do not include EXTRA
16421 For backward compatibility, if both the positive and the negative place
16422 holder is missing, the positive one (without the \"NO-\") will be
16423 assumed to be present at the end of the template.
16424 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
16425 EXTRA is a string.
16426 SNIPPETS-P indicates if this is run to create snippet images for HTML."
16427 (let (rpl (end ""))
16428 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
16429 (setq rpl (if (or (match-end 1) (not def-pkg))
16430 "" (org-latex-packages-to-string def-pkg snippets-p t))
16431 tpl (replace-match rpl t t tpl))
16432 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
16434 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
16435 (setq rpl (if (or (match-end 1) (not pkg))
16436 "" (org-latex-packages-to-string pkg snippets-p t))
16437 tpl (replace-match rpl t t tpl))
16438 (if pkg (setq end
16439 (concat end "\n"
16440 (org-latex-packages-to-string pkg snippets-p)))))
16442 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
16443 (setq rpl (if (or (match-end 1) (not extra))
16444 "" (concat extra "\n"))
16445 tpl (replace-match rpl t t tpl))
16446 (if (and extra (string-match "\\S-" extra))
16447 (setq end (concat end "\n" extra))))
16449 (if (string-match "\\S-" end)
16450 (concat tpl "\n" end)
16451 tpl)))
16453 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
16454 "Turn an alist of packages into a string with the \\usepackage macros."
16455 (setq pkg (mapconcat (lambda(p)
16456 (cond
16457 ((stringp p) p)
16458 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
16459 (format "%% Package %s omitted" (cadr p)))
16460 ((equal "" (car p))
16461 (format "\\usepackage{%s}" (cadr p)))
16463 (format "\\usepackage[%s]{%s}"
16464 (car p) (cadr p)))))
16466 "\n"))
16467 (if newline (concat pkg "\n") pkg))
16469 (defun org-dvipng-color (attr)
16470 "Return an rgb color specification for dvipng."
16471 (apply 'format "rgb %s %s %s"
16472 (mapcar 'org-normalize-color
16473 (color-values (face-attribute 'default attr nil)))))
16475 (defun org-normalize-color (value)
16476 "Return string to be used as color value for an RGB component."
16477 (format "%g" (/ value 65535.0)))
16479 ;; Image display
16482 (defvar org-inline-image-overlays nil)
16483 (make-variable-buffer-local 'org-inline-image-overlays)
16485 (defun org-toggle-inline-images (&optional include-linked)
16486 "Toggle the display of inline images.
16487 INCLUDE-LINKED is passed to `org-display-inline-images'."
16488 (interactive "P")
16489 (if org-inline-image-overlays
16490 (progn
16491 (org-remove-inline-images)
16492 (message "Inline image display turned off"))
16493 (org-display-inline-images include-linked)
16494 (if org-inline-image-overlays
16495 (message "%d images displayed inline"
16496 (length org-inline-image-overlays))
16497 (message "No images to display inline"))))
16499 (defun org-display-inline-images (&optional include-linked refresh beg end)
16500 "Display inline images.
16501 Normally only links without a description part are inlined, because this
16502 is how it will work for export. When INCLUDE-LINKED is set, also links
16503 with a description part will be inlined. This can be nice for a quick
16504 look at those images, but it does not reflect what exported files will look
16505 like.
16506 When REFRESH is set, refresh existing images between BEG and END.
16507 This will create new image displays only if necessary.
16508 BEG and END default to the buffer boundaries."
16509 (interactive "P")
16510 (unless refresh
16511 (org-remove-inline-images)
16512 (if (fboundp 'clear-image-cache) (clear-image-cache)))
16513 (save-excursion
16514 (save-restriction
16515 (widen)
16516 (setq beg (or beg (point-min)) end (or end (point-max)))
16517 (goto-char (point-min))
16518 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
16519 (substring (org-image-file-name-regexp) 0 -2)
16520 "\\)\\]" (if include-linked "" "\\]")))
16521 old file ov img)
16522 (while (re-search-forward re end t)
16523 (setq old (get-char-property-and-overlay (match-beginning 1)
16524 'org-image-overlay))
16525 (setq file (expand-file-name
16526 (concat (or (match-string 3) "") (match-string 4))))
16527 (when (file-exists-p file)
16528 (if (and (car-safe old) refresh)
16529 (image-refresh (overlay-get (cdr old) 'display))
16530 (setq img (save-match-data (create-image file)))
16531 (when img
16532 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
16533 (overlay-put ov 'display img)
16534 (overlay-put ov 'face 'default)
16535 (overlay-put ov 'org-image-overlay t)
16536 (overlay-put ov 'modification-hooks
16537 (list 'org-display-inline-modification-hook))
16538 (push ov org-inline-image-overlays)))))))))
16540 (defun org-display-inline-modification-hook (ov after beg end &optional len)
16541 "Remove inline-display overlay if a corresponding region is modified."
16542 (let ((inhibit-modification-hooks t))
16543 (when (and ov after)
16544 (delete ov org-inline-image-overlays)
16545 (delete-overlay ov))))
16547 (defun org-remove-inline-images ()
16548 "Remove inline display of images."
16549 (interactive)
16550 (mapc 'delete-overlay org-inline-image-overlays)
16551 (setq org-inline-image-overlays nil))
16553 ;;;; Key bindings
16555 ;; Make `C-c C-x' a prefix key
16556 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
16558 ;; TAB key with modifiers
16559 (org-defkey org-mode-map "\C-i" 'org-cycle)
16560 (org-defkey org-mode-map [(tab)] 'org-cycle)
16561 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
16562 (org-defkey org-mode-map [(meta tab)] 'pcomplete)
16563 (org-defkey org-mode-map "\M-\t" 'pcomplete)
16564 (org-defkey org-mode-map "\M-\C-i" 'pcomplete)
16565 ;; The following line is necessary under Suse GNU/Linux
16566 (unless (featurep 'xemacs)
16567 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
16568 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
16569 (define-key org-mode-map [backtab] 'org-shifttab)
16571 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
16572 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
16573 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
16575 ;; Cursor keys with modifiers
16576 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
16577 (org-defkey org-mode-map [(meta right)] 'org-metaright)
16578 (org-defkey org-mode-map [(meta up)] 'org-metaup)
16579 (org-defkey org-mode-map [(meta down)] 'org-metadown)
16581 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
16582 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
16583 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
16584 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
16586 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
16587 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
16588 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
16589 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
16591 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
16592 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
16594 ;; Babel keys
16595 (define-key org-mode-map org-babel-key-prefix org-babel-map)
16596 (mapc (lambda (pair)
16597 (define-key org-babel-map (car pair) (cdr pair)))
16598 org-babel-key-bindings)
16600 ;;; Extra keys for tty access.
16601 ;; We only set them when really needed because otherwise the
16602 ;; menus don't show the simple keys
16604 (when (or org-use-extra-keys
16605 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
16606 (not window-system))
16607 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
16608 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
16609 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
16610 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
16611 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
16612 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
16613 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
16614 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
16615 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
16616 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
16617 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
16618 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
16619 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
16620 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
16621 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
16622 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
16623 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
16624 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
16625 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
16626 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
16627 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
16628 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
16629 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
16630 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
16631 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
16632 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
16633 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
16634 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
16636 ;; All the other keys
16638 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
16639 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
16640 (if (boundp 'narrow-map)
16641 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
16642 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
16643 (if (boundp 'narrow-map)
16644 (org-defkey narrow-map "b" 'org-narrow-to-block)
16645 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
16646 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
16647 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
16648 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
16649 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
16650 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
16651 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
16652 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
16653 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
16654 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
16655 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
16656 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
16657 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
16658 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
16659 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
16660 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
16661 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
16662 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
16663 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
16664 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
16665 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
16666 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
16667 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
16668 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
16669 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
16670 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
16671 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
16672 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
16673 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
16674 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
16675 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
16676 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
16677 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
16678 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
16679 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
16680 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
16681 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
16682 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
16683 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
16684 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
16685 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
16686 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
16687 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
16688 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
16689 (org-defkey org-mode-map "\C-c^" 'org-sort)
16690 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
16691 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
16692 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
16693 (org-defkey org-mode-map "\C-m" 'org-return)
16694 (org-defkey org-mode-map "\C-j" 'org-return-indent)
16695 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
16696 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
16697 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
16698 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
16699 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
16700 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
16701 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
16702 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
16703 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
16704 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
16705 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
16706 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
16707 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
16708 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
16709 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
16710 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
16711 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
16712 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
16713 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
16714 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
16715 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
16717 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
16718 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
16719 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
16720 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
16722 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
16723 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
16724 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
16725 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
16726 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
16727 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
16728 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
16729 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
16730 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
16731 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
16732 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
16733 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
16734 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
16735 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
16736 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
16737 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
16738 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
16739 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
16741 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
16742 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
16743 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
16744 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
16745 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
16747 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
16749 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
16751 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
16752 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
16754 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
16757 (when (featurep 'xemacs)
16758 (org-defkey org-mode-map 'button3 'popup-mode-menu))
16761 (defconst org-speed-commands-default
16763 ("Outline Navigation")
16764 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
16765 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
16766 ("f" . (org-speed-move-safe 'org-forward-same-level))
16767 ("b" . (org-speed-move-safe 'org-backward-same-level))
16768 ("u" . (org-speed-move-safe 'outline-up-heading))
16769 ("j" . org-goto)
16770 ("g" . (org-refile t))
16771 ("Outline Visibility")
16772 ("c" . org-cycle)
16773 ("C" . org-shifttab)
16774 (" " . org-display-outline-path)
16775 ("Outline Structure Editing")
16776 ("U" . org-shiftmetaup)
16777 ("D" . org-shiftmetadown)
16778 ("r" . org-metaright)
16779 ("l" . org-metaleft)
16780 ("R" . org-shiftmetaright)
16781 ("L" . org-shiftmetaleft)
16782 ("i" . (progn (forward-char 1) (call-interactively
16783 'org-insert-heading-respect-content)))
16784 ("^" . org-sort)
16785 ("w" . org-refile)
16786 ("a" . org-archive-subtree-default-with-confirmation)
16787 ("." . org-mark-subtree)
16788 ("Clock Commands")
16789 ("I" . org-clock-in)
16790 ("O" . org-clock-out)
16791 ("Meta Data Editing")
16792 ("t" . org-todo)
16793 ("0" . (org-priority ?\ ))
16794 ("1" . (org-priority ?A))
16795 ("2" . (org-priority ?B))
16796 ("3" . (org-priority ?C))
16797 (";" . org-set-tags-command)
16798 ("e" . org-set-effort)
16799 ("Agenda Views etc")
16800 ("v" . org-agenda)
16801 ("/" . org-sparse-tree)
16802 ("Misc")
16803 ("o" . org-open-at-point)
16804 ("?" . org-speed-command-help)
16805 ("<" . (org-agenda-set-restriction-lock 'subtree))
16806 (">" . (org-agenda-remove-restriction-lock))
16808 "The default speed commands.")
16810 (defun org-print-speed-command (e)
16811 (if (> (length (car e)) 1)
16812 (progn
16813 (princ "\n")
16814 (princ (car e))
16815 (princ "\n")
16816 (princ (make-string (length (car e)) ?-))
16817 (princ "\n"))
16818 (princ (car e))
16819 (princ " ")
16820 (if (symbolp (cdr e))
16821 (princ (symbol-name (cdr e)))
16822 (prin1 (cdr e)))
16823 (princ "\n")))
16825 (defun org-speed-command-help ()
16826 "Show the available speed commands."
16827 (interactive)
16828 (if (not org-use-speed-commands)
16829 (error "Speed commands are not activated, customize `org-use-speed-commands'")
16830 (with-output-to-temp-buffer "*Help*"
16831 (princ "User-defined Speed commands\n===========================\n")
16832 (mapc 'org-print-speed-command org-speed-commands-user)
16833 (princ "\n")
16834 (princ "Built-in Speed commands\n=======================\n")
16835 (mapc 'org-print-speed-command org-speed-commands-default))
16836 (with-current-buffer "*Help*"
16837 (setq truncate-lines t))))
16839 (defun org-speed-move-safe (cmd)
16840 "Execute CMD, but make sure that the cursor always ends up in a headline.
16841 If not, return to the original position and throw an error."
16842 (interactive)
16843 (let ((pos (point)))
16844 (call-interactively cmd)
16845 (unless (and (bolp) (org-on-heading-p))
16846 (goto-char pos)
16847 (error "Boundary reached while executing %s" cmd))))
16849 (defvar org-self-insert-command-undo-counter 0)
16851 (defvar org-table-auto-blank-field) ; defined in org-table.el
16852 (defvar org-speed-command nil)
16854 (defun org-speed-command-default-hook (keys)
16855 "Hook for activating single-letter speed commands.
16856 `org-speed-commands-default' specifies a minimal command set. Use
16857 `org-speed-commands-user' for further customization."
16858 (when (or (and (bolp) (looking-at outline-regexp))
16859 (and (functionp org-use-speed-commands)
16860 (funcall org-use-speed-commands)))
16861 (cdr (assoc keys (append org-speed-commands-user
16862 org-speed-commands-default)))))
16864 (defun org-babel-speed-command-hook (keys)
16865 "Hook for activating single-letter code block commands."
16866 (when (and (bolp) (looking-at org-babel-src-block-regexp))
16867 (cdr (assoc keys org-babel-key-bindings))))
16869 (defcustom org-speed-command-hook
16870 '(org-speed-command-default-hook org-babel-speed-command-hook)
16871 "Hook for activating speed commands at strategic locations.
16872 Hook functions are called in sequence until a valid handler is
16873 found.
16875 Each hook takes a single argument, a user-pressed command key
16876 which is also a `self-insert-command' from the global map.
16878 Within the hook, examine the cursor position and the command key
16879 and return nil or a valid handler as appropriate. Handler could
16880 be one of an interactive command, a function, or a form.
16882 Set `org-use-speed-commands' to non-nil value to enable this
16883 hook. The default setting is `org-speed-command-default-hook'."
16884 :group 'org-structure
16885 :type 'hook)
16887 (defun org-self-insert-command (N)
16888 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
16889 If the cursor is in a table looking at whitespace, the whitespace is
16890 overwritten, and the table is not marked as requiring realignment."
16891 (interactive "p")
16892 (cond
16893 ((and org-use-speed-commands
16894 (setq org-speed-command
16895 (run-hook-with-args-until-success
16896 'org-speed-command-hook (this-command-keys))))
16897 (cond
16898 ((commandp org-speed-command)
16899 (setq this-command org-speed-command)
16900 (call-interactively org-speed-command))
16901 ((functionp org-speed-command)
16902 (funcall org-speed-command))
16903 ((and org-speed-command (listp org-speed-command))
16904 (eval org-speed-command))
16905 (t (let (org-use-speed-commands)
16906 (call-interactively 'org-self-insert-command)))))
16907 ((and
16908 (org-table-p)
16909 (progn
16910 ;; check if we blank the field, and if that triggers align
16911 (and (featurep 'org-table) org-table-auto-blank-field
16912 (member last-command
16913 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
16914 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
16915 ;; got extra space, this field does not determine column width
16916 (let (org-table-may-need-update) (org-table-blank-field))
16917 ;; no extra space, this field may determine column width
16918 (org-table-blank-field)))
16920 (eq N 1)
16921 (looking-at "[^|\n]* |"))
16922 (let (org-table-may-need-update)
16923 (goto-char (1- (match-end 0)))
16924 (delete-backward-char 1)
16925 (goto-char (match-beginning 0))
16926 (self-insert-command N)))
16928 (setq org-table-may-need-update t)
16929 (self-insert-command N)
16930 (org-fix-tags-on-the-fly)
16931 (if org-self-insert-cluster-for-undo
16932 (if (not (eq last-command 'org-self-insert-command))
16933 (setq org-self-insert-command-undo-counter 1)
16934 (if (>= org-self-insert-command-undo-counter 20)
16935 (setq org-self-insert-command-undo-counter 1)
16936 (and (> org-self-insert-command-undo-counter 0)
16937 buffer-undo-list (listp buffer-undo-list)
16938 (not (cadr buffer-undo-list)) ; remove nil entry
16939 (setcdr buffer-undo-list (cddr buffer-undo-list)))
16940 (setq org-self-insert-command-undo-counter
16941 (1+ org-self-insert-command-undo-counter))))))))
16943 (defun org-fix-tags-on-the-fly ()
16944 (when (and (equal (char-after (point-at-bol)) ?*)
16945 (org-on-heading-p))
16946 (org-align-tags-here org-tags-column)))
16948 (defun org-delete-backward-char (N)
16949 "Like `delete-backward-char', insert whitespace at field end in tables.
16950 When deleting backwards, in tables this function will insert whitespace in
16951 front of the next \"|\" separator, to keep the table aligned. The table will
16952 still be marked for re-alignment if the field did fill the entire column,
16953 because, in this case the deletion might narrow the column."
16954 (interactive "p")
16955 (if (and (org-table-p)
16956 (eq N 1)
16957 (string-match "|" (buffer-substring (point-at-bol) (point)))
16958 (looking-at ".*?|"))
16959 (let ((pos (point))
16960 (noalign (looking-at "[^|\n\r]* |"))
16961 (c org-table-may-need-update))
16962 (backward-delete-char N)
16963 (if (not overwrite-mode)
16964 (progn
16965 (skip-chars-forward "^|")
16966 (insert " ")
16967 (goto-char (1- pos))))
16968 ;; noalign: if there were two spaces at the end, this field
16969 ;; does not determine the width of the column.
16970 (if noalign (setq org-table-may-need-update c)))
16971 (backward-delete-char N)
16972 (org-fix-tags-on-the-fly)))
16974 (defun org-delete-char (N)
16975 "Like `delete-char', but insert whitespace at field end in tables.
16976 When deleting characters, in tables this function will insert whitespace in
16977 front of the next \"|\" separator, to keep the table aligned. The table will
16978 still be marked for re-alignment if the field did fill the entire column,
16979 because, in this case the deletion might narrow the column."
16980 (interactive "p")
16981 (if (and (org-table-p)
16982 (not (bolp))
16983 (not (= (char-after) ?|))
16984 (eq N 1))
16985 (if (looking-at ".*?|")
16986 (let ((pos (point))
16987 (noalign (looking-at "[^|\n\r]* |"))
16988 (c org-table-may-need-update))
16989 (replace-match (concat
16990 (substring (match-string 0) 1 -1)
16991 " |"))
16992 (goto-char pos)
16993 ;; noalign: if there were two spaces at the end, this field
16994 ;; does not determine the width of the column.
16995 (if noalign (setq org-table-may-need-update c)))
16996 (delete-char N))
16997 (delete-char N)
16998 (org-fix-tags-on-the-fly)))
17000 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
17001 (put 'org-self-insert-command 'delete-selection t)
17002 (put 'orgtbl-self-insert-command 'delete-selection t)
17003 (put 'org-delete-char 'delete-selection 'supersede)
17004 (put 'org-delete-backward-char 'delete-selection 'supersede)
17005 (put 'org-yank 'delete-selection 'yank)
17007 ;; Make `flyspell-mode' delay after some commands
17008 (put 'org-self-insert-command 'flyspell-delayed t)
17009 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
17010 (put 'org-delete-char 'flyspell-delayed t)
17011 (put 'org-delete-backward-char 'flyspell-delayed t)
17013 ;; Make pabbrev-mode expand after org-mode commands
17014 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
17015 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
17017 ;; How to do this: Measure non-white length of current string
17018 ;; If equal to column width, we should realign.
17020 (defun org-remap (map &rest commands)
17021 "In MAP, remap the functions given in COMMANDS.
17022 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
17023 (let (new old)
17024 (while commands
17025 (setq old (pop commands) new (pop commands))
17026 (if (fboundp 'command-remapping)
17027 (org-defkey map (vector 'remap old) new)
17028 (substitute-key-definition old new map global-map)))))
17030 (when (eq org-enable-table-editor 'optimized)
17031 ;; If the user wants maximum table support, we need to hijack
17032 ;; some standard editing functions
17033 (org-remap org-mode-map
17034 'self-insert-command 'org-self-insert-command
17035 'delete-char 'org-delete-char
17036 'delete-backward-char 'org-delete-backward-char)
17037 (org-defkey org-mode-map "|" 'org-force-self-insert))
17039 (defvar org-ctrl-c-ctrl-c-hook nil
17040 "Hook for functions attaching themselves to `C-c C-c'.
17041 This can be used to add additional functionality to the C-c C-c key which
17042 executes context-dependent commands.
17043 Each function will be called with no arguments. The function must check
17044 if the context is appropriate for it to act. If yes, it should do its
17045 thing and then return a non-nil value. If the context is wrong,
17046 just do nothing and return nil.")
17048 (defvar org-tab-first-hook nil
17049 "Hook for functions to attach themselves to TAB.
17050 See `org-ctrl-c-ctrl-c-hook' for more information.
17051 This hook runs as the first action when TAB is pressed, even before
17052 `org-cycle' messes around with the `outline-regexp' to cater for
17053 inline tasks and plain list item folding.
17054 If any function in this hook returns t, any other actions that
17055 would have been caused by TAB (such as table field motion or visibility
17056 cycling) will not occur.")
17058 (defvar org-tab-after-check-for-table-hook nil
17059 "Hook for functions to attach themselves to TAB.
17060 See `org-ctrl-c-ctrl-c-hook' for more information.
17061 This hook runs after it has been established that the cursor is not in a
17062 table, but before checking if the cursor is in a headline or if global cycling
17063 should be done.
17064 If any function in this hook returns t, not other actions like visibility
17065 cycling will be done.")
17067 (defvar org-tab-after-check-for-cycling-hook nil
17068 "Hook for functions to attach themselves to TAB.
17069 See `org-ctrl-c-ctrl-c-hook' for more information.
17070 This hook runs after it has been established that not table field motion and
17071 not visibility should be done because of current context. This is probably
17072 the place where a package like yasnippets can hook in.")
17074 (defvar org-tab-before-tab-emulation-hook nil
17075 "Hook for functions to attach themselves to TAB.
17076 See `org-ctrl-c-ctrl-c-hook' for more information.
17077 This hook runs after every other options for TAB have been exhausted, but
17078 before indentation and \t insertion takes place.")
17080 (defvar org-metaleft-hook nil
17081 "Hook for functions attaching themselves to `M-left'.
17082 See `org-ctrl-c-ctrl-c-hook' for more information.")
17083 (defvar org-metaright-hook nil
17084 "Hook for functions attaching themselves to `M-right'.
17085 See `org-ctrl-c-ctrl-c-hook' for more information.")
17086 (defvar org-metaup-hook nil
17087 "Hook for functions attaching themselves to `M-up'.
17088 See `org-ctrl-c-ctrl-c-hook' for more information.")
17089 (defvar org-metadown-hook nil
17090 "Hook for functions attaching themselves to `M-down'.
17091 See `org-ctrl-c-ctrl-c-hook' for more information.")
17092 (defvar org-shiftmetaleft-hook nil
17093 "Hook for functions attaching themselves to `M-S-left'.
17094 See `org-ctrl-c-ctrl-c-hook' for more information.")
17095 (defvar org-shiftmetaright-hook nil
17096 "Hook for functions attaching themselves to `M-S-right'.
17097 See `org-ctrl-c-ctrl-c-hook' for more information.")
17098 (defvar org-shiftmetaup-hook nil
17099 "Hook for functions attaching themselves to `M-S-up'.
17100 See `org-ctrl-c-ctrl-c-hook' for more information.")
17101 (defvar org-shiftmetadown-hook nil
17102 "Hook for functions attaching themselves to `M-S-down'.
17103 See `org-ctrl-c-ctrl-c-hook' for more information.")
17104 (defvar org-metareturn-hook nil
17105 "Hook for functions attaching themselves to `M-RET'.
17106 See `org-ctrl-c-ctrl-c-hook' for more information.")
17107 (defvar org-shiftup-hook nil
17108 "Hook for functions attaching themselves to `S-up'.
17109 See `org-ctrl-c-ctrl-c-hook' for more information.")
17110 (defvar org-shiftup-final-hook nil
17111 "Hook for functions attaching themselves to `S-up'.
17112 This one runs after all other options except shift-select have been excluded.
17113 See `org-ctrl-c-ctrl-c-hook' for more information.")
17114 (defvar org-shiftdown-hook nil
17115 "Hook for functions attaching themselves to `S-down'.
17116 See `org-ctrl-c-ctrl-c-hook' for more information.")
17117 (defvar org-shiftdown-final-hook nil
17118 "Hook for functions attaching themselves to `S-down'.
17119 This one runs after all other options except shift-select have been excluded.
17120 See `org-ctrl-c-ctrl-c-hook' for more information.")
17121 (defvar org-shiftleft-hook nil
17122 "Hook for functions attaching themselves to `S-left'.
17123 See `org-ctrl-c-ctrl-c-hook' for more information.")
17124 (defvar org-shiftleft-final-hook nil
17125 "Hook for functions attaching themselves to `S-left'.
17126 This one runs after all other options except shift-select have been excluded.
17127 See `org-ctrl-c-ctrl-c-hook' for more information.")
17128 (defvar org-shiftright-hook nil
17129 "Hook for functions attaching themselves to `S-right'.
17130 See `org-ctrl-c-ctrl-c-hook' for more information.")
17131 (defvar org-shiftright-final-hook nil
17132 "Hook for functions attaching themselves to `S-right'.
17133 This one runs after all other options except shift-select have been excluded.
17134 See `org-ctrl-c-ctrl-c-hook' for more information.")
17136 (defun org-modifier-cursor-error ()
17137 "Throw an error, a modified cursor command was applied in wrong context."
17138 (error "This command is active in special context like tables, headlines or items"))
17140 (defun org-shiftselect-error ()
17141 "Throw an error because Shift-Cursor command was applied in wrong context."
17142 (if (and (boundp 'shift-select-mode) shift-select-mode)
17143 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
17144 (error "This command works only in special context like headlines or timestamps")))
17146 (defun org-call-for-shift-select (cmd)
17147 (let ((this-command-keys-shift-translated t))
17148 (call-interactively cmd)))
17150 (defun org-shifttab (&optional arg)
17151 "Global visibility cycling or move to previous table field.
17152 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
17153 on context.
17154 See the individual commands for more information."
17155 (interactive "P")
17156 (cond
17157 ((org-at-table-p) (call-interactively 'org-table-previous-field))
17158 ((integerp arg)
17159 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
17160 (message "Content view to level: %d" arg)
17161 (org-content (prefix-numeric-value arg2))
17162 (setq org-cycle-global-status 'overview)))
17163 (t (call-interactively 'org-global-cycle))))
17165 (defun org-shiftmetaleft ()
17166 "Promote subtree or delete table column.
17167 Calls `org-promote-subtree', `org-outdent-item',
17168 or `org-table-delete-column', depending on context.
17169 See the individual commands for more information."
17170 (interactive)
17171 (cond
17172 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
17173 ((org-at-table-p) (call-interactively 'org-table-delete-column))
17174 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
17175 ((org-at-item-p) (call-interactively 'org-outdent-item-tree))
17176 (t (org-modifier-cursor-error))))
17178 (defun org-shiftmetaright ()
17179 "Demote subtree or insert table column.
17180 Calls `org-demote-subtree', `org-indent-item',
17181 or `org-table-insert-column', depending on context.
17182 See the individual commands for more information."
17183 (interactive)
17184 (cond
17185 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
17186 ((org-at-table-p) (call-interactively 'org-table-insert-column))
17187 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
17188 ((org-at-item-p) (call-interactively 'org-indent-item-tree))
17189 (t (org-modifier-cursor-error))))
17191 (defun org-shiftmetaup (&optional arg)
17192 "Move subtree up or kill table row.
17193 Calls `org-move-subtree-up' or `org-table-kill-row' or
17194 `org-move-item-up' depending on context. See the individual commands
17195 for more information."
17196 (interactive "P")
17197 (cond
17198 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
17199 ((org-at-table-p) (call-interactively 'org-table-kill-row))
17200 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17201 ((org-at-item-p) (call-interactively 'org-move-item-up))
17202 (t (org-modifier-cursor-error))))
17204 (defun org-shiftmetadown (&optional arg)
17205 "Move subtree down or insert table row.
17206 Calls `org-move-subtree-down' or `org-table-insert-row' or
17207 `org-move-item-down', depending on context. See the individual
17208 commands for more information."
17209 (interactive "P")
17210 (cond
17211 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
17212 ((org-at-table-p) (call-interactively 'org-table-insert-row))
17213 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17214 ((org-at-item-p) (call-interactively 'org-move-item-down))
17215 (t (org-modifier-cursor-error))))
17217 (defsubst org-hidden-tree-error ()
17218 (error
17219 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
17221 (defun org-metaleft (&optional arg)
17222 "Promote heading or move table column to left.
17223 Calls `org-do-promote' or `org-table-move-column', depending on context.
17224 With no specific context, calls the Emacs default `backward-word'.
17225 See the individual commands for more information."
17226 (interactive "P")
17227 (cond
17228 ((run-hook-with-args-until-success 'org-metaleft-hook))
17229 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
17230 ((org-with-limited-levels
17231 (or (org-on-heading-p)
17232 (and (org-region-active-p)
17233 (save-excursion
17234 (goto-char (region-beginning))
17235 (org-on-heading-p)))))
17236 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17237 (call-interactively 'org-do-promote))
17238 ;; At an inline task.
17239 ((org-on-heading-p)
17240 (call-interactively 'org-inlinetask-promote))
17241 ((or (org-at-item-p)
17242 (and (org-region-active-p)
17243 (save-excursion
17244 (goto-char (region-beginning))
17245 (org-at-item-p))))
17246 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17247 (call-interactively 'org-outdent-item))
17248 (t (call-interactively 'backward-word))))
17250 (defun org-metaright (&optional arg)
17251 "Demote subtree or move table column to right.
17252 Calls `org-do-demote' or `org-table-move-column', depending on context.
17253 With no specific context, calls the Emacs default `forward-word'.
17254 See the individual commands for more information."
17255 (interactive "P")
17256 (cond
17257 ((run-hook-with-args-until-success 'org-metaright-hook))
17258 ((org-at-table-p) (call-interactively 'org-table-move-column))
17259 ((org-with-limited-levels
17260 (or (org-on-heading-p)
17261 (and (org-region-active-p)
17262 (save-excursion
17263 (goto-char (region-beginning))
17264 (org-on-heading-p)))))
17265 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17266 (call-interactively 'org-do-demote))
17267 ;; At an inline task.
17268 ((org-on-heading-p)
17269 (call-interactively 'org-inlinetask-demote))
17270 ((or (org-at-item-p)
17271 (and (org-region-active-p)
17272 (save-excursion
17273 (goto-char (region-beginning))
17274 (org-at-item-p))))
17275 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17276 (call-interactively 'org-indent-item))
17277 (t (call-interactively 'forward-word))))
17279 (defun org-check-for-hidden (what)
17280 "Check if there are hidden headlines/items in the current visual line.
17281 WHAT can be either `headlines' or `items'. If the current line is
17282 an outline or item heading and it has a folded subtree below it,
17283 this function returns t, nil otherwise."
17284 (let ((re (cond
17285 ((eq what 'headlines) (concat "^" org-outline-regexp))
17286 ((eq what 'items) (org-item-beginning-re))
17287 (t (error "This should not happen"))))
17288 beg end)
17289 (save-excursion
17290 (catch 'exit
17291 (unless (org-region-active-p)
17292 (setq beg (point-at-bol))
17293 (beginning-of-line 2)
17294 (while (and (not (eobp)) ;; this is like `next-line'
17295 (get-char-property (1- (point)) 'invisible))
17296 (beginning-of-line 2))
17297 (setq end (point))
17298 (goto-char beg)
17299 (goto-char (point-at-eol))
17300 (setq end (max end (point)))
17301 (while (re-search-forward re end t)
17302 (if (get-char-property (match-beginning 0) 'invisible)
17303 (throw 'exit t))))
17304 nil))))
17306 (defun org-metaup (&optional arg)
17307 "Move subtree up or move table row up.
17308 Calls `org-move-subtree-up' or `org-table-move-row' or
17309 `org-move-item-up', depending on context. See the individual commands
17310 for more information."
17311 (interactive "P")
17312 (cond
17313 ((run-hook-with-args-until-success 'org-metaup-hook))
17314 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
17315 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17316 ((org-at-item-p) (call-interactively 'org-move-item-up))
17317 (t (transpose-lines 1) (beginning-of-line -1))))
17319 (defun org-metadown (&optional arg)
17320 "Move subtree down or move table row down.
17321 Calls `org-move-subtree-down' or `org-table-move-row' or
17322 `org-move-item-down', depending on context. See the individual
17323 commands for more information."
17324 (interactive "P")
17325 (cond
17326 ((run-hook-with-args-until-success 'org-metadown-hook))
17327 ((org-at-table-p) (call-interactively 'org-table-move-row))
17328 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17329 ((org-at-item-p) (call-interactively 'org-move-item-down))
17330 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
17332 (defun org-shiftup (&optional arg)
17333 "Increase item in timestamp or increase priority of current headline.
17334 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
17335 depending on context. See the individual commands for more information."
17336 (interactive "P")
17337 (cond
17338 ((run-hook-with-args-until-success 'org-shiftup-hook))
17339 ((and org-support-shift-select (org-region-active-p))
17340 (org-call-for-shift-select 'previous-line))
17341 ((org-at-timestamp-p t)
17342 (call-interactively (if org-edit-timestamp-down-means-later
17343 'org-timestamp-down 'org-timestamp-up)))
17344 ((and (not (eq org-support-shift-select 'always))
17345 org-enable-priority-commands
17346 (org-on-heading-p))
17347 (call-interactively 'org-priority-up))
17348 ((and (not org-support-shift-select) (org-at-item-p))
17349 (call-interactively 'org-previous-item))
17350 ((org-clocktable-try-shift 'up arg))
17351 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
17352 (org-support-shift-select
17353 (org-call-for-shift-select 'previous-line))
17354 (t (org-shiftselect-error))))
17356 (defun org-shiftdown (&optional arg)
17357 "Decrease item in timestamp or decrease priority of current headline.
17358 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
17359 depending on context. See the individual commands for more information."
17360 (interactive "P")
17361 (cond
17362 ((run-hook-with-args-until-success 'org-shiftdown-hook))
17363 ((and org-support-shift-select (org-region-active-p))
17364 (org-call-for-shift-select 'next-line))
17365 ((org-at-timestamp-p t)
17366 (call-interactively (if org-edit-timestamp-down-means-later
17367 'org-timestamp-up 'org-timestamp-down)))
17368 ((and (not (eq org-support-shift-select 'always))
17369 org-enable-priority-commands
17370 (org-on-heading-p))
17371 (call-interactively 'org-priority-down))
17372 ((and (not org-support-shift-select) (org-at-item-p))
17373 (call-interactively 'org-next-item))
17374 ((org-clocktable-try-shift 'down arg))
17375 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
17376 (org-support-shift-select
17377 (org-call-for-shift-select 'next-line))
17378 (t (org-shiftselect-error))))
17380 (defun org-shiftright (&optional arg)
17381 "Cycle the thing at point or in the current line, depending on context.
17382 Depending on context, this does one of the following:
17384 - switch a timestamp at point one day into the future
17385 - on a headline, switch to the next TODO keyword.
17386 - on an item, switch entire list to the next bullet type
17387 - on a property line, switch to the next allowed value
17388 - on a clocktable definition line, move time block into the future"
17389 (interactive "P")
17390 (cond
17391 ((run-hook-with-args-until-success 'org-shiftright-hook))
17392 ((and org-support-shift-select (org-region-active-p))
17393 (org-call-for-shift-select 'forward-char))
17394 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
17395 ((and (not (eq org-support-shift-select 'always))
17396 (org-on-heading-p))
17397 (let ((org-inhibit-logging
17398 (not org-treat-S-cursor-todo-selection-as-state-change))
17399 (org-inhibit-blocking
17400 (not org-treat-S-cursor-todo-selection-as-state-change)))
17401 (org-call-with-arg 'org-todo 'right)))
17402 ((or (and org-support-shift-select
17403 (not (eq org-support-shift-select 'always))
17404 (org-at-item-bullet-p))
17405 (and (not org-support-shift-select) (org-at-item-p)))
17406 (org-call-with-arg 'org-cycle-list-bullet nil))
17407 ((and (not (eq org-support-shift-select 'always))
17408 (org-at-property-p))
17409 (call-interactively 'org-property-next-allowed-value))
17410 ((org-clocktable-try-shift 'right arg))
17411 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
17412 (org-support-shift-select
17413 (org-call-for-shift-select 'forward-char))
17414 (t (org-shiftselect-error))))
17416 (defun org-shiftleft (&optional arg)
17417 "Cycle the thing at point or in the current line, depending on context.
17418 Depending on context, this does one of the following:
17420 - switch a timestamp at point one day into the past
17421 - on a headline, switch to the previous TODO keyword.
17422 - on an item, switch entire list to the previous bullet type
17423 - on a property line, switch to the previous allowed value
17424 - on a clocktable definition line, move time block into the past"
17425 (interactive "P")
17426 (cond
17427 ((run-hook-with-args-until-success 'org-shiftleft-hook))
17428 ((and org-support-shift-select (org-region-active-p))
17429 (org-call-for-shift-select 'backward-char))
17430 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
17431 ((and (not (eq org-support-shift-select 'always))
17432 (org-on-heading-p))
17433 (let ((org-inhibit-logging
17434 (not org-treat-S-cursor-todo-selection-as-state-change))
17435 (org-inhibit-blocking
17436 (not org-treat-S-cursor-todo-selection-as-state-change)))
17437 (org-call-with-arg 'org-todo 'left)))
17438 ((or (and org-support-shift-select
17439 (not (eq org-support-shift-select 'always))
17440 (org-at-item-bullet-p))
17441 (and (not org-support-shift-select) (org-at-item-p)))
17442 (org-call-with-arg 'org-cycle-list-bullet 'previous))
17443 ((and (not (eq org-support-shift-select 'always))
17444 (org-at-property-p))
17445 (call-interactively 'org-property-previous-allowed-value))
17446 ((org-clocktable-try-shift 'left arg))
17447 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
17448 (org-support-shift-select
17449 (org-call-for-shift-select 'backward-char))
17450 (t (org-shiftselect-error))))
17452 (defun org-shiftcontrolright ()
17453 "Switch to next TODO set."
17454 (interactive)
17455 (cond
17456 ((and org-support-shift-select (org-region-active-p))
17457 (org-call-for-shift-select 'forward-word))
17458 ((and (not (eq org-support-shift-select 'always))
17459 (org-on-heading-p))
17460 (org-call-with-arg 'org-todo 'nextset))
17461 (org-support-shift-select
17462 (org-call-for-shift-select 'forward-word))
17463 (t (org-shiftselect-error))))
17465 (defun org-shiftcontrolleft ()
17466 "Switch to previous TODO set."
17467 (interactive)
17468 (cond
17469 ((and org-support-shift-select (org-region-active-p))
17470 (org-call-for-shift-select 'backward-word))
17471 ((and (not (eq org-support-shift-select 'always))
17472 (org-on-heading-p))
17473 (org-call-with-arg 'org-todo 'previousset))
17474 (org-support-shift-select
17475 (org-call-for-shift-select 'backward-word))
17476 (t (org-shiftselect-error))))
17478 (defun org-ctrl-c-ret ()
17479 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
17480 (interactive)
17481 (cond
17482 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
17483 (t (call-interactively 'org-insert-heading))))
17485 (defun org-copy-special ()
17486 "Copy region in table or copy current subtree.
17487 Calls `org-table-copy' or `org-copy-subtree', depending on context.
17488 See the individual commands for more information."
17489 (interactive)
17490 (call-interactively
17491 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
17493 (defun org-cut-special ()
17494 "Cut region in table or cut current subtree.
17495 Calls `org-table-copy' or `org-cut-subtree', depending on context.
17496 See the individual commands for more information."
17497 (interactive)
17498 (call-interactively
17499 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
17501 (defun org-paste-special (arg)
17502 "Paste rectangular region into table, or past subtree relative to level.
17503 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
17504 See the individual commands for more information."
17505 (interactive "P")
17506 (if (org-at-table-p)
17507 (org-table-paste-rectangle)
17508 (org-paste-subtree arg)))
17510 (defun org-edit-special (&optional arg)
17511 "Call a special editor for the stuff at point.
17512 When at a table, call the formula editor with `org-table-edit-formulas'.
17513 When at the first line of an src example, call `org-edit-src-code'.
17514 When in an #+include line, visit the include file. Otherwise call
17515 `ffap' to visit the file at point."
17516 (interactive)
17517 ;; possibly prep session before editing source
17518 (when arg
17519 (let* ((info (org-babel-get-src-block-info))
17520 (lang (nth 0 info))
17521 (params (nth 2 info))
17522 (session (cdr (assoc :session params))))
17523 (when (and info session) ;; we are in a source-code block with a session
17524 (funcall
17525 (intern (concat "org-babel-prep-session:" lang)) session params))))
17526 (cond ;; proceed with `org-edit-special'
17527 ((save-excursion
17528 (beginning-of-line 1)
17529 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
17530 (find-file (org-trim (match-string 1))))
17531 ((org-edit-src-code))
17532 ((org-edit-fixed-width-region))
17533 ((org-at-table.el-p)
17534 (org-edit-src-code))
17535 ((or (org-at-table-p)
17536 (save-excursion
17537 (beginning-of-line 1)
17538 (looking-at "[ \t]*#\\+TBLFM:")))
17539 (call-interactively 'org-table-edit-formulas))
17540 (t (call-interactively 'ffap))))
17542 (defun org-ctrl-c-ctrl-c (&optional arg)
17543 "Set tags in headline, or update according to changed information at point.
17545 This command does many different things, depending on context:
17547 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
17548 this is what we do.
17550 - If the cursor is on a statistics cookie, update it.
17552 - If the cursor is in a headline, prompt for tags and insert them
17553 into the current line, aligned to `org-tags-column'. When called
17554 with prefix arg, realign all tags in the current buffer.
17556 - If the cursor is in one of the special #+KEYWORD lines, this
17557 triggers scanning the buffer for these lines and updating the
17558 information.
17560 - If the cursor is inside a table, realign the table. This command
17561 works even if the automatic table editor has been turned off.
17563 - If the cursor is on a #+TBLFM line, re-apply the formulas to
17564 the entire table.
17566 - If the cursor is at a footnote reference or definition, jump to
17567 the corresponding definition or references, respectively.
17569 - If the cursor is a the beginning of a dynamic block, update it.
17571 - If the current buffer is a capture buffer, close note and file it.
17573 - If the cursor is on a <<<target>>>, update radio targets and
17574 corresponding links in this buffer.
17576 - If the cursor is on a numbered item in a plain list, renumber the
17577 ordered list.
17579 - If the cursor is on a checkbox, toggle it.
17581 - If the cursor is on a code block, evaluate it. The variable
17582 `org-confirm-babel-evaluate' can be used to control prompting
17583 before code block evaluation, by default every code block
17584 evaluation requires confirmation. Code block evaluation can be
17585 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
17586 (interactive "P")
17587 (let ((org-enable-table-editor t))
17588 (cond
17589 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
17590 org-occur-highlights
17591 org-latex-fragment-image-overlays)
17592 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
17593 (org-remove-occur-highlights)
17594 (org-remove-latex-fragment-image-overlays)
17595 (message "Temporary highlights/overlays removed from current buffer"))
17596 ((and (local-variable-p 'org-finish-function (current-buffer))
17597 (fboundp org-finish-function))
17598 (funcall org-finish-function))
17599 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
17600 ((or (looking-at org-property-start-re)
17601 (org-at-property-p))
17602 (call-interactively 'org-property-action))
17603 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
17604 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
17605 (or (org-on-heading-p) (org-at-item-p)))
17606 (call-interactively 'org-update-statistics-cookies))
17607 ((org-on-heading-p) (call-interactively 'org-set-tags))
17608 ((org-at-table.el-p)
17609 (message "Use C-c ' to edit table.el tables"))
17610 ((org-at-table-p)
17611 (org-table-maybe-eval-formula)
17612 (if arg
17613 (call-interactively 'org-table-recalculate)
17614 (org-table-maybe-recalculate-line))
17615 (call-interactively 'org-table-align)
17616 (orgtbl-send-table 'maybe))
17617 ((or (org-footnote-at-reference-p)
17618 (org-footnote-at-definition-p))
17619 (call-interactively 'org-footnote-action))
17620 ((org-at-item-checkbox-p)
17621 ;; Cursor at a checkbox: repair list and update checkboxes. Send
17622 ;; list only if at top item.
17623 (let* ((cbox (match-string 1))
17624 (struct (org-list-struct))
17625 (old-struct (copy-tree struct))
17626 (parents (org-list-parents-alist struct))
17627 (prevs (org-list-prevs-alist struct))
17628 (orderedp (org-entry-get nil "ORDERED"))
17629 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
17630 block-item)
17631 ;; Use a light version of `org-toggle-checkbox' to avoid
17632 ;; computing list structure twice.
17633 (org-list-set-checkbox (point-at-bol) struct
17634 (cond
17635 ((equal arg '(16)) "[-]")
17636 ((equal arg '(4)) nil)
17637 ((equal "[X]" cbox) "[ ]")
17638 (t "[X]")))
17639 (org-list-struct-fix-ind struct parents)
17640 (org-list-struct-fix-bul struct prevs)
17641 (setq block-item
17642 (org-list-struct-fix-box struct parents prevs orderedp))
17643 (when block-item
17644 (message
17645 "Checkboxes were removed due to unchecked box at line %d"
17646 (org-current-line block-item)))
17647 (org-list-struct-apply-struct struct old-struct)
17648 (org-update-checkbox-count-maybe)
17649 (when firstp (org-list-send-list 'maybe))))
17650 ((org-at-item-p)
17651 ;; Cursor at an item: repair list. Do checkbox related actions
17652 ;; only if function was called with an argument. Send list only
17653 ;; if at top item.
17654 (let* ((struct (org-list-struct))
17655 (old-struct (copy-tree struct))
17656 (parents (org-list-parents-alist struct))
17657 (prevs (org-list-prevs-alist struct))
17658 (firstp (= (org-list-get-top-point struct) (point-at-bol))))
17659 (org-list-struct-fix-ind struct parents)
17660 (org-list-struct-fix-bul struct prevs)
17661 (when arg
17662 (org-list-set-checkbox (point-at-bol) struct "[ ]")
17663 (org-list-struct-fix-box struct parents prevs))
17664 (org-list-struct-apply-struct struct old-struct)
17665 (when arg (org-update-checkbox-count-maybe))
17666 (when firstp (org-list-send-list 'maybe))))
17667 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
17668 ;; Dynamic block
17669 (beginning-of-line 1)
17670 (save-excursion (org-update-dblock)))
17671 ((save-excursion
17672 (beginning-of-line 1)
17673 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
17674 (cond
17675 ((equal (match-string 1) "TBLFM")
17676 ;; Recalculate the table before this line
17677 (save-excursion
17678 (beginning-of-line 1)
17679 (skip-chars-backward " \r\n\t")
17680 (if (org-at-table-p)
17681 (org-call-with-arg 'org-table-recalculate (or arg t)))))
17683 (let ((org-inhibit-startup-visibility-stuff t)
17684 (org-startup-align-all-tables nil))
17685 (org-save-outline-visibility 'use-markers (org-mode-restart)))
17686 (message "Local setup has been refreshed"))))
17687 ((org-clock-update-time-maybe))
17688 (t (error "C-c C-c can do nothing useful at this location")))))
17690 (defun org-mode-restart ()
17691 "Restart Org-mode, to scan again for special lines.
17692 Also updates the keyword regular expressions."
17693 (interactive)
17694 (org-mode)
17695 (message "Org-mode restarted"))
17697 (defun org-kill-note-or-show-branches ()
17698 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
17699 (interactive)
17700 (if (not org-finish-function)
17701 (progn
17702 (hide-subtree)
17703 (call-interactively 'show-branches))
17704 (let ((org-note-abort t))
17705 (funcall org-finish-function))))
17707 (defun org-return (&optional indent)
17708 "Goto next table row or insert a newline.
17709 Calls `org-table-next-row' or `newline', depending on context.
17710 See the individual commands for more information."
17711 (interactive)
17712 (cond
17713 ((bobp) (if indent (newline-and-indent) (newline)))
17714 ((org-at-table-p)
17715 (org-table-justify-field-maybe)
17716 (call-interactively 'org-table-next-row))
17717 ;; when `newline-and-indent' is called within a list, make sure
17718 ;; text moved stays inside the item.
17719 ((and (org-in-item-p) indent)
17720 (if (and (org-at-item-p) (>= (point) (match-end 0)))
17721 (progn
17722 (newline)
17723 (org-indent-line-to (length (match-string 0))))
17724 (let ((ind (org-get-indentation)))
17725 (newline)
17726 (if (org-looking-back org-list-end-re)
17727 (org-indent-line-function)
17728 (org-indent-line-to ind)))))
17729 ((and org-return-follows-link
17730 (eq (get-text-property (point) 'face) 'org-link))
17731 (call-interactively 'org-open-at-point))
17732 ((and (org-at-heading-p)
17733 (looking-at
17734 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
17735 (org-show-entry)
17736 (end-of-line 1)
17737 (newline))
17738 (t (if indent (newline-and-indent) (newline)))))
17740 (defun org-return-indent ()
17741 "Goto next table row or insert a newline and indent.
17742 Calls `org-table-next-row' or `newline-and-indent', depending on
17743 context. See the individual commands for more information."
17744 (interactive)
17745 (org-return t))
17747 (defun org-ctrl-c-star ()
17748 "Compute table, or change heading status of lines.
17749 Calls `org-table-recalculate' or `org-toggle-heading',
17750 depending on context."
17751 (interactive)
17752 (cond
17753 ((org-at-table-p)
17754 (call-interactively 'org-table-recalculate))
17756 ;; Convert all lines in region to list items
17757 (call-interactively 'org-toggle-heading))))
17759 (defun org-ctrl-c-minus ()
17760 "Insert separator line in table or modify bullet status of line.
17761 Also turns a plain line or a region of lines into list items.
17762 Calls `org-table-insert-hline', `org-toggle-item', or
17763 `org-cycle-list-bullet', depending on context."
17764 (interactive)
17765 (cond
17766 ((org-at-table-p)
17767 (call-interactively 'org-table-insert-hline))
17768 ((org-region-active-p)
17769 (call-interactively 'org-toggle-item))
17770 ((org-in-item-p)
17771 (call-interactively 'org-cycle-list-bullet))
17773 (call-interactively 'org-toggle-item))))
17775 (defun org-toggle-item (arg)
17776 "Convert headings or normal lines to items, items to normal lines.
17777 If there is no active region, only the current line is considered.
17779 If the first non blank line in the region is an headline, convert
17780 all headlines to items, shifting text accordingly.
17782 If it is an item, convert all items to normal lines.
17784 If it is normal text, change region into an item. With a prefix
17785 argument ARG, change each line in region into an item."
17786 (interactive "P")
17787 (let ((shift-text
17788 (function
17789 ;; Shift text in current section to IND, from point to END.
17790 ;; The function leaves point to END line.
17791 (lambda (ind end)
17792 (let ((min-i 1000) (end (copy-marker end)))
17793 ;; First determine the minimum indentation (MIN-I) of
17794 ;; the text.
17795 (save-excursion
17796 (catch 'exit
17797 (while (< (point) end)
17798 (let ((i (org-get-indentation)))
17799 (cond
17800 ;; Skip blank lines and inline tasks.
17801 ((looking-at "^[ \t]*$"))
17802 ((looking-at "^\\*+ "))
17803 ;; We can't find less than 0 indentation.
17804 ((zerop i) (throw 'exit (setq min-i 0)))
17805 ((< i min-i) (setq min-i i))))
17806 (forward-line))))
17807 ;; Then indent each line so that a line indented to
17808 ;; MIN-I becomes indented to IND. Ignore blank lines
17809 ;; and inline tasks in the process.
17810 (let ((delta (- ind min-i)))
17811 (while (< (point) end)
17812 (unless (or (looking-at "^[ \t]*$")
17813 (looking-at "^\\*+ "))
17814 (org-indent-line-to (+ (org-get-indentation) delta)))
17815 (forward-line)))))))
17816 (skip-blanks
17817 (function
17818 ;; Return beginning of first non-blank line, starting from
17819 ;; line at POS.
17820 (lambda (pos)
17821 (save-excursion
17822 (goto-char pos)
17823 (skip-chars-forward " \r\t\n")
17824 (point-at-bol)))))
17825 beg end)
17826 ;; Determine boundaries of changes.
17827 (if (org-region-active-p)
17828 (setq beg (funcall skip-blanks (region-beginning))
17829 end (copy-marker (region-end)))
17830 (setq beg (funcall skip-blanks (point-at-bol))
17831 end (copy-marker (point-at-eol))))
17832 ;; Depending on the starting line, choose an action on the text
17833 ;; between BEG and END.
17834 (org-with-limited-levels
17835 (save-excursion
17836 (goto-char beg)
17837 (cond
17838 ;; Case 1. Start at an item: de-itemize. Note that it only
17839 ;; happens when a region is active: `org-ctrl-c-minus'
17840 ;; would call `org-cycle-list-bullet' otherwise.
17841 ((org-at-item-p)
17842 (while (< (point) end)
17843 (when (org-at-item-p)
17844 (skip-chars-forward " \t")
17845 (delete-region (point) (match-end 0)))
17846 (forward-line)))
17847 ;; Case 2. Start at an heading: convert to items.
17848 ((org-on-heading-p)
17849 (let* ((bul (org-list-bullet-string "-"))
17850 (bul-len (length bul))
17851 ;; Indentation of the first heading. It should be
17852 ;; relative to the indentation of its parent, if any.
17853 (start-ind (save-excursion
17854 (cond
17855 ((not org-adapt-indentation) 0)
17856 ((not (outline-previous-heading)) 0)
17857 (t (length (match-string 0))))))
17858 ;; Level of first heading. Further headings will be
17859 ;; compared to it to determine hierarchy in the list.
17860 (ref-level (org-reduced-level (org-outline-level))))
17861 (while (< (point) end)
17862 (let* ((level (org-reduced-level (org-outline-level)))
17863 (delta (max 0 (- level ref-level))))
17864 ;; If current headline is less indented than the first
17865 ;; one, set it as reference, in order to preserve
17866 ;; subtrees.
17867 (when (< level ref-level) (setq ref-level level))
17868 (replace-match bul t t)
17869 (org-indent-line-to (+ start-ind (* delta bul-len)))
17870 ;; Ensure all text down to END (or SECTION-END) belongs
17871 ;; to the newly created item.
17872 (let ((section-end (save-excursion
17873 (or (outline-next-heading) (point)))))
17874 (forward-line)
17875 (funcall shift-text
17876 (+ start-ind (* (1+ delta) bul-len))
17877 (min end section-end)))))))
17878 ;; Case 3. Normal line with ARG: turn each non-item line into
17879 ;; an item.
17880 (arg
17881 (while (< (point end))
17882 (unless (or (org-on-heading-p) (org-at-item-p))
17883 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
17884 (replace-match
17885 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
17886 (forward-line)))
17887 ;; Case 4. Normal line without ARG: make the first line of
17888 ;; region an item, and shift indentation of others
17889 ;; lines to set them as item's body.
17890 (t (let* ((bul (org-list-bullet-string "-"))
17891 (bul-len (length bul))
17892 (ref-ind (org-get-indentation)))
17893 (skip-chars-forward " \t")
17894 (insert bul)
17895 (forward-line)
17896 (while (< (point) end)
17897 ;; Ensure that lines less indented than first one
17898 ;; still get included in item body.
17899 (funcall shift-text
17900 (+ ref-ind bul-len)
17901 (min end (save-excursion (or (outline-next-heading)
17902 (point)))))
17903 (forward-line)))))))))
17905 (defun org-toggle-heading (&optional nstars)
17906 "Convert headings to normal text, or items or text to headings.
17907 If there is no active region, only the current line is considered.
17909 If the first non blank line is an headline, remove the stars from
17910 all headlines in the region.
17912 If it is a plain list item, turn all plain list items into headings.
17914 If it is a normal line, turn each and every normal line (i.e. not
17915 an heading or an item) in the region into a heading.
17917 When converting a line into a heading, the number of stars is chosen
17918 such that the lines become children of the current entry. However,
17919 when a prefix argument is given, its value determines the number of
17920 stars to add."
17921 (interactive "P")
17922 (let ((skip-blanks
17923 (function
17924 ;; Return beginning of first non-blank line, starting from
17925 ;; line at POS.
17926 (lambda (pos)
17927 (save-excursion
17928 (goto-char pos)
17929 (skip-chars-forward " \r\t\n")
17930 (point-at-bol)))))
17931 beg end)
17932 ;; Determine boundaries of changes. If region ends at a bol, do
17933 ;; not consider the last line to be in the region.
17934 (if (org-region-active-p)
17935 (setq beg (funcall skip-blanks (region-beginning))
17936 end (copy-marker (save-excursion
17937 (goto-char (region-end))
17938 (if (bolp) (point) (point-at-eol)))))
17939 (setq beg (funcall skip-blanks (point-at-bol))
17940 end (copy-marker (point-at-eol))))
17941 ;; Ensure inline tasks don't count as headings.
17942 (org-with-limited-levels
17943 (save-excursion
17944 (goto-char beg)
17945 (cond
17946 ;; Case 1. Started at an heading: de-star headings.
17947 ((org-on-heading-p)
17948 (while (< (point) end)
17949 (when (org-on-heading-p t)
17950 (looking-at outline-regexp) (replace-match ""))
17951 (forward-line)))
17952 ;; Case 2. Started at an item: change items into headlines.
17953 ((org-at-item-p)
17954 (let ((stars (make-string
17955 (if nstars
17956 (prefix-numeric-value current-prefix-arg)
17957 (or (org-current-level) 0))
17958 ?*)))
17959 (while (< (point) end)
17960 (when (org-at-item-p)
17961 ;; Pay attention to cases when region ends before list.
17962 (let* ((struct (org-list-struct))
17963 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
17964 (save-restriction
17965 (narrow-to-region (point) list-end)
17966 (insert
17967 (org-list-to-subtree
17968 (org-list-parse-list t)
17969 '(:istart (concat stars (funcall get-stars depth))
17970 :icount (concat stars
17971 (funcall get-stars depth))))))))
17972 (forward-line))))
17973 ;; Case 3. Started at normal text: make every line an heading,
17974 ;; skipping headlines and items.
17975 (t (let* ((stars (make-string
17976 (if nstars
17977 (prefix-numeric-value current-prefix-arg)
17978 (or (org-current-level) 0))
17979 ?*))
17980 (add-stars (cond (nstars "")
17981 ((equal stars "") "*")
17982 (org-odd-levels-only "**")
17983 (t "*")))
17984 (rpl (concat stars add-stars " ")))
17985 (while (< (point) end)
17986 (when (and (not (org-on-heading-p)) (not (org-at-item-p))
17987 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
17988 (replace-match (concat rpl (match-string 2))))
17989 (forward-line)))))))))
17991 (defun org-meta-return (&optional arg)
17992 "Insert a new heading or wrap a region in a table.
17993 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
17994 See the individual commands for more information."
17995 (interactive "P")
17996 (cond
17997 ((run-hook-with-args-until-success 'org-metareturn-hook))
17998 ((org-at-table-p)
17999 (call-interactively 'org-table-wrap-region))
18000 (t (call-interactively 'org-insert-heading))))
18002 ;;; Menu entries
18004 ;; Define the Org-mode menus
18005 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
18006 '("Tbl"
18007 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
18008 ["Next Field" org-cycle (org-at-table-p)]
18009 ["Previous Field" org-shifttab (org-at-table-p)]
18010 ["Next Row" org-return (org-at-table-p)]
18011 "--"
18012 ["Blank Field" org-table-blank-field (org-at-table-p)]
18013 ["Edit Field" org-table-edit-field (org-at-table-p)]
18014 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
18015 "--"
18016 ("Column"
18017 ["Move Column Left" org-metaleft (org-at-table-p)]
18018 ["Move Column Right" org-metaright (org-at-table-p)]
18019 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
18020 ["Insert Column" org-shiftmetaright (org-at-table-p)])
18021 ("Row"
18022 ["Move Row Up" org-metaup (org-at-table-p)]
18023 ["Move Row Down" org-metadown (org-at-table-p)]
18024 ["Delete Row" org-shiftmetaup (org-at-table-p)]
18025 ["Insert Row" org-shiftmetadown (org-at-table-p)]
18026 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
18027 "--"
18028 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
18029 ("Rectangle"
18030 ["Copy Rectangle" org-copy-special (org-at-table-p)]
18031 ["Cut Rectangle" org-cut-special (org-at-table-p)]
18032 ["Paste Rectangle" org-paste-special (org-at-table-p)]
18033 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
18034 "--"
18035 ("Calculate"
18036 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
18037 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
18038 ["Edit Formulas" org-edit-special (org-at-table-p)]
18039 "--"
18040 ["Recalculate line" org-table-recalculate (org-at-table-p)]
18041 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
18042 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
18043 "--"
18044 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
18045 "--"
18046 ["Sum Column/Rectangle" org-table-sum
18047 (or (org-at-table-p) (org-region-active-p))]
18048 ["Which Column?" org-table-current-column (org-at-table-p)])
18049 ["Debug Formulas"
18050 org-table-toggle-formula-debugger
18051 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
18052 ["Show Col/Row Numbers"
18053 org-table-toggle-coordinate-overlays
18054 :style toggle
18055 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
18056 "--"
18057 ["Create" org-table-create (and (not (org-at-table-p))
18058 org-enable-table-editor)]
18059 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
18060 ["Import from File" org-table-import (not (org-at-table-p))]
18061 ["Export to File" org-table-export (org-at-table-p)]
18062 "--"
18063 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
18065 (easy-menu-define org-org-menu org-mode-map "Org menu"
18066 '("Org"
18067 ("Show/Hide"
18068 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
18069 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
18070 ["Sparse Tree..." org-sparse-tree t]
18071 ["Reveal Context" org-reveal t]
18072 ["Show All" show-all t]
18073 "--"
18074 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
18075 "--"
18076 ["New Heading" org-insert-heading t]
18077 ("Navigate Headings"
18078 ["Up" outline-up-heading t]
18079 ["Next" outline-next-visible-heading t]
18080 ["Previous" outline-previous-visible-heading t]
18081 ["Next Same Level" outline-forward-same-level t]
18082 ["Previous Same Level" outline-backward-same-level t]
18083 "--"
18084 ["Jump" org-goto t])
18085 ("Edit Structure"
18086 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
18087 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
18088 "--"
18089 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
18090 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
18091 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
18092 "--"
18093 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
18094 "--"
18095 ["Promote Heading" org-metaleft (not (org-at-table-p))]
18096 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
18097 ["Demote Heading" org-metaright (not (org-at-table-p))]
18098 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
18099 "--"
18100 ["Sort Region/Children" org-sort (not (org-at-table-p))]
18101 "--"
18102 ["Convert to odd levels" org-convert-to-odd-levels t]
18103 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
18104 ("Editing"
18105 ["Emphasis..." org-emphasize t]
18106 ["Edit Source Example" org-edit-special t]
18107 "--"
18108 ["Footnote new/jump" org-footnote-action t]
18109 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
18110 ("Archive"
18111 ["Archive (default method)" org-archive-subtree-default t]
18112 "--"
18113 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
18114 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
18115 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
18117 "--"
18118 ("Hyperlinks"
18119 ["Store Link (Global)" org-store-link t]
18120 ["Find existing link to here" org-occur-link-in-agenda-files t]
18121 ["Insert Link" org-insert-link t]
18122 ["Follow Link" org-open-at-point t]
18123 "--"
18124 ["Next link" org-next-link t]
18125 ["Previous link" org-previous-link t]
18126 "--"
18127 ["Descriptive Links"
18128 (progn (add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
18129 :style radio
18130 :selected (member '(org-link) buffer-invisibility-spec)]
18131 ["Literal Links"
18132 (progn
18133 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
18134 :style radio
18135 :selected (not (member '(org-link) buffer-invisibility-spec))])
18136 "--"
18137 ("TODO Lists"
18138 ["TODO/DONE/-" org-todo t]
18139 ("Select keyword"
18140 ["Next keyword" org-shiftright (org-on-heading-p)]
18141 ["Previous keyword" org-shiftleft (org-on-heading-p)]
18142 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
18143 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
18144 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
18145 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
18146 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
18147 "--"
18148 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
18149 :selected org-enforce-todo-dependencies :style toggle :active t]
18150 "Settings for tree at point"
18151 ["Do Children sequentially" org-toggle-ordered-property :style radio
18152 :selected (org-entry-get nil "ORDERED")
18153 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
18154 ["Do Children parallel" org-toggle-ordered-property :style radio
18155 :selected (not (org-entry-get nil "ORDERED"))
18156 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
18157 "--"
18158 ["Set Priority" org-priority t]
18159 ["Priority Up" org-shiftup t]
18160 ["Priority Down" org-shiftdown t]
18161 "--"
18162 ["Get news from all feeds" org-feed-update-all t]
18163 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
18164 ["Customize feeds" (customize-variable 'org-feed-alist) t])
18165 ("TAGS and Properties"
18166 ["Set Tags" org-set-tags-command t]
18167 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
18168 "--"
18169 ["Set property" org-set-property t]
18170 ["Column view of properties" org-columns t]
18171 ["Insert Column View DBlock" org-insert-columns-dblock t])
18172 ("Dates and Scheduling"
18173 ["Timestamp" org-time-stamp t]
18174 ["Timestamp (inactive)" org-time-stamp-inactive t]
18175 ("Change Date"
18176 ["1 Day Later" org-shiftright t]
18177 ["1 Day Earlier" org-shiftleft t]
18178 ["1 ... Later" org-shiftup t]
18179 ["1 ... Earlier" org-shiftdown t])
18180 ["Compute Time Range" org-evaluate-time-range t]
18181 ["Schedule Item" org-schedule t]
18182 ["Deadline" org-deadline t]
18183 "--"
18184 ["Custom time format" org-toggle-time-stamp-overlays
18185 :style radio :selected org-display-custom-times]
18186 "--"
18187 ["Goto Calendar" org-goto-calendar t]
18188 ["Date from Calendar" org-date-from-calendar t]
18189 "--"
18190 ["Start/Restart Timer" org-timer-start t]
18191 ["Pause/Continue Timer" org-timer-pause-or-continue t]
18192 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
18193 ["Insert Timer String" org-timer t]
18194 ["Insert Timer Item" org-timer-item t])
18195 ("Logging work"
18196 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
18197 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
18198 ["Clock out" org-clock-out t]
18199 ["Clock cancel" org-clock-cancel t]
18200 "--"
18201 ["Mark as default task" org-clock-mark-default-task t]
18202 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
18203 ["Goto running clock" org-clock-goto t]
18204 "--"
18205 ["Display times" org-clock-display t]
18206 ["Create clock table" org-clock-report t]
18207 "--"
18208 ["Record DONE time"
18209 (progn (setq org-log-done (not org-log-done))
18210 (message "Switching to %s will %s record a timestamp"
18211 (car org-done-keywords)
18212 (if org-log-done "automatically" "not")))
18213 :style toggle :selected org-log-done])
18214 "--"
18215 ["Agenda Command..." org-agenda t]
18216 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
18217 ("File List for Agenda")
18218 ("Special views current file"
18219 ["TODO Tree" org-show-todo-tree t]
18220 ["Check Deadlines" org-check-deadlines t]
18221 ["Timeline" org-timeline t]
18222 ["Tags/Property tree" org-match-sparse-tree t])
18223 "--"
18224 ["Export/Publish..." org-export t]
18225 ("LaTeX"
18226 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
18227 :selected org-cdlatex-mode]
18228 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
18229 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
18230 ["Modify math symbol" org-cdlatex-math-modify
18231 (org-inside-LaTeX-fragment-p)]
18232 ["Insert citation" org-reftex-citation t]
18233 "--"
18234 ["Template for BEAMER" org-insert-beamer-options-template t])
18235 "--"
18236 ("MobileOrg"
18237 ["Push Files and Views" org-mobile-push t]
18238 ["Get Captured and Flagged" org-mobile-pull t]
18239 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
18240 "--"
18241 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
18242 "--"
18243 ("Documentation"
18244 ["Show Version" org-version t]
18245 ["Info Documentation" org-info t])
18246 ("Customize"
18247 ["Browse Org Group" org-customize t]
18248 "--"
18249 ["Expand This Menu" org-create-customize-menu
18250 (fboundp 'customize-menu-create)])
18251 ["Send bug report" org-submit-bug-report t]
18252 "--"
18253 ("Refresh/Reload"
18254 ["Refresh setup current buffer" org-mode-restart t]
18255 ["Reload Org (after update)" org-reload t]
18256 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
18259 (defun org-info (&optional node)
18260 "Read documentation for Org-mode in the info system.
18261 With optional NODE, go directly to that node."
18262 (interactive)
18263 (info (format "(org)%s" (or node ""))))
18265 ;;;###autoload
18266 (defun org-submit-bug-report ()
18267 "Submit a bug report on Org-mode via mail.
18269 Don't hesitate to report any problems or inaccurate documentation.
18271 If you don't have setup sending mail from (X)Emacs, please copy the
18272 output buffer into your mail program, as it gives us important
18273 information about your Org-mode version and configuration."
18274 (interactive)
18275 (require 'reporter)
18276 (org-load-modules-maybe)
18277 (org-require-autoloaded-modules)
18278 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
18279 (reporter-submit-bug-report
18280 "emacs-orgmode@gnu.org"
18281 (org-version)
18282 (let (list)
18283 (save-window-excursion
18284 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
18285 (delete-other-windows)
18286 (erase-buffer)
18287 (insert "You are about to submit a bug report to the Org-mode mailing list.
18289 We would like to add your full Org-mode and Outline configuration to the
18290 bug report. This greatly simplifies the work of the maintainer and
18291 other experts on the mailing list.
18293 HOWEVER, some variables you have customized may contain private
18294 information. The names of customers, colleagues, or friends, might
18295 appear in the form of file names, tags, todo states, or search strings.
18296 If you answer yes to the prompt, you might want to check and remove
18297 such private information before sending the email.")
18298 (add-text-properties (point-min) (point-max) '(face org-warning))
18299 (when (yes-or-no-p "Include your Org-mode configuration ")
18300 (mapatoms
18301 (lambda (v)
18302 (and (boundp v)
18303 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
18304 (or (and (symbol-value v)
18305 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
18306 (and
18307 (get v 'custom-type) (get v 'standard-value)
18308 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
18309 (push v list)))))
18310 (kill-buffer (get-buffer "*Warn about privacy*"))
18311 list))
18312 nil nil
18313 "Remember to cover the basics, that is, what you expected to happen and
18314 what in fact did happen. You don't know how to make a good report? See
18316 http://orgmode.org/manual/Feedback.html#Feedback
18318 Your bug report will be posted to the Org-mode mailing list.
18319 ------------------------------------------------------------------------")
18320 (save-excursion
18321 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
18322 (replace-match "\\1Bug: \\3 [\\2]")))))
18325 (defun org-install-agenda-files-menu ()
18326 (let ((bl (buffer-list)))
18327 (save-excursion
18328 (while bl
18329 (set-buffer (pop bl))
18330 (if (org-mode-p) (setq bl nil)))
18331 (when (org-mode-p)
18332 (easy-menu-change
18333 '("Org") "File List for Agenda"
18334 (append
18335 (list
18336 ["Edit File List" (org-edit-agenda-file-list) t]
18337 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
18338 ["Remove Current File from List" org-remove-file t]
18339 ["Cycle through agenda files" org-cycle-agenda-files t]
18340 ["Occur in all agenda files" org-occur-in-agenda-files t]
18341 "--")
18342 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
18344 ;;;; Documentation
18346 ;;;###autoload
18347 (defun org-require-autoloaded-modules ()
18348 (interactive)
18349 (mapc 'require
18350 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
18351 org-docbook org-exp org-html org-icalendar
18352 org-id org-latex
18353 org-publish org-remember org-table
18354 org-timer org-xoxo)))
18356 ;;;###autoload
18357 (defun org-reload (&optional uncompiled)
18358 "Reload all org lisp files.
18359 With prefix arg UNCOMPILED, load the uncompiled versions."
18360 (interactive "P")
18361 (require 'find-func)
18362 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
18363 (dir-org (file-name-directory (org-find-library-name "org")))
18364 (dir-org-contrib (ignore-errors
18365 (file-name-directory
18366 (org-find-library-name "org-contribdir"))))
18367 (babel-files
18368 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
18369 (append (list nil "comint" "eval" "exp" "keys"
18370 "lob" "ref" "table" "tangle")
18371 (delq nil
18372 (mapcar
18373 (lambda (lang)
18374 (when (cdr lang) (symbol-name (car lang))))
18375 org-babel-load-languages)))))
18376 (files
18377 (append (directory-files dir-org t file-re)
18378 babel-files
18379 (and dir-org-contrib
18380 (directory-files dir-org-contrib t file-re))))
18381 (remove-re (concat (if (featurep 'xemacs)
18382 "org-colview" "org-colview-xemacs")
18383 "\\'")))
18384 (setq files (mapcar 'file-name-sans-extension files))
18385 (setq files (mapcar
18386 (lambda (x) (if (string-match remove-re x) nil x))
18387 files))
18388 (setq files (delq nil files))
18389 (mapc
18390 (lambda (f)
18391 (when (featurep (intern (file-name-nondirectory f)))
18392 (if (and (not uncompiled)
18393 (file-exists-p (concat f ".elc")))
18394 (load (concat f ".elc") nil nil t)
18395 (load (concat f ".el") nil nil t))))
18396 files))
18397 (org-version))
18399 ;;;###autoload
18400 (defun org-customize ()
18401 "Call the customize function with org as argument."
18402 (interactive)
18403 (org-load-modules-maybe)
18404 (org-require-autoloaded-modules)
18405 (customize-browse 'org))
18407 (defun org-create-customize-menu ()
18408 "Create a full customization menu for Org-mode, insert it into the menu."
18409 (interactive)
18410 (org-load-modules-maybe)
18411 (org-require-autoloaded-modules)
18412 (if (fboundp 'customize-menu-create)
18413 (progn
18414 (easy-menu-change
18415 '("Org") "Customize"
18416 `(["Browse Org group" org-customize t]
18417 "--"
18418 ,(customize-menu-create 'org)
18419 ["Set" Custom-set t]
18420 ["Save" Custom-save t]
18421 ["Reset to Current" Custom-reset-current t]
18422 ["Reset to Saved" Custom-reset-saved t]
18423 ["Reset to Standard Settings" Custom-reset-standard t]))
18424 (message "\"Org\"-menu now contains full customization menu"))
18425 (error "Cannot expand menu (outdated version of cus-edit.el)")))
18427 ;;;; Miscellaneous stuff
18429 ;;; Generally useful functions
18431 (defun org-get-at-bol (property)
18432 "Get text property PROPERTY at beginning of line."
18433 (get-text-property (point-at-bol) property))
18435 (defun org-find-text-property-in-string (prop s)
18436 "Return the first non-nil value of property PROP in string S."
18437 (or (get-text-property 0 prop s)
18438 (get-text-property (or (next-single-property-change 0 prop s) 0)
18439 prop s)))
18441 (defun org-display-warning (message) ;; Copied from Emacs-Muse
18442 "Display the given MESSAGE as a warning."
18443 (if (fboundp 'display-warning)
18444 (display-warning 'org message
18445 (if (featurep 'xemacs) 'warning :warning))
18446 (let ((buf (get-buffer-create "*Org warnings*")))
18447 (with-current-buffer buf
18448 (goto-char (point-max))
18449 (insert "Warning (Org): " message)
18450 (unless (bolp)
18451 (newline)))
18452 (display-buffer buf)
18453 (sit-for 0))))
18455 (defun org-eval (form)
18456 "Eval FORM and return result."
18457 (condition-case error
18458 (eval form)
18459 (error (format "%%![Error: %s]" error))))
18461 (defun org-in-commented-line ()
18462 "Is point in a line starting with `#'?"
18463 (equal (char-after (point-at-bol)) ?#))
18465 (defun org-in-indented-comment-line ()
18466 "Is point in a line starting with `#' after some white space?"
18467 (save-excursion
18468 (save-match-data
18469 (goto-char (point-at-bol))
18470 (looking-at "[ \t]*#"))))
18472 (defun org-in-verbatim-emphasis ()
18473 (save-match-data
18474 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
18476 (defun org-goto-marker-or-bmk (marker &optional bookmark)
18477 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
18478 (if (and marker (marker-buffer marker)
18479 (buffer-live-p (marker-buffer marker)))
18480 (progn
18481 (switch-to-buffer (marker-buffer marker))
18482 (if (or (> marker (point-max)) (< marker (point-min)))
18483 (widen))
18484 (goto-char marker)
18485 (org-show-context 'org-goto))
18486 (if bookmark
18487 (bookmark-jump bookmark)
18488 (error "Cannot find location"))))
18490 (defun org-quote-csv-field (s)
18491 "Quote field for inclusion in CSV material."
18492 (if (string-match "[\",]" s)
18493 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
18496 (defun org-force-self-insert (N)
18497 "Needed to enforce self-insert under remapping."
18498 (interactive "p")
18499 (self-insert-command N))
18501 (defun org-string-width (s)
18502 "Compute width of string, ignoring invisible characters.
18503 This ignores character with invisibility property `org-link', and also
18504 characters with property `org-cwidth', because these will become invisible
18505 upon the next fontification round."
18506 (let (b l)
18507 (when (or (eq t buffer-invisibility-spec)
18508 (assq 'org-link buffer-invisibility-spec))
18509 (while (setq b (text-property-any 0 (length s)
18510 'invisible 'org-link s))
18511 (setq s (concat (substring s 0 b)
18512 (substring s (or (next-single-property-change
18513 b 'invisible s) (length s)))))))
18514 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
18515 (setq s (concat (substring s 0 b)
18516 (substring s (or (next-single-property-change
18517 b 'org-cwidth s) (length s))))))
18518 (setq l (string-width s) b -1)
18519 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
18520 (setq l (- l (get-text-property b 'org-dwidth-n s))))
18523 (defun org-shorten-string (s maxlength)
18524 "Shorten string S so tht it is no longer than MAXLENGTH characters.
18525 If the string is shorter or has length MAXLENGTH, just return the
18526 original string. If it is longer, the functions finds a space in the
18527 string, breaks this string off at that locations and adds three dots
18528 as ellipsis. Including the ellipsis, the string will not be longer
18529 than MAXLENGTH. If finding a good breaking point in the string does
18530 not work, the string is just chopped off in the middle of a word
18531 if necessary."
18532 (if (<= (length s) maxlength)
18534 (let* ((n (max (- maxlength 4) 1))
18535 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
18536 (if (string-match re s)
18537 (concat (match-string 1 s) "...")
18538 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
18540 (defun org-get-indentation (&optional line)
18541 "Get the indentation of the current line, interpreting tabs.
18542 When LINE is given, assume it represents a line and compute its indentation."
18543 (if line
18544 (if (string-match "^ *" (org-remove-tabs line))
18545 (match-end 0))
18546 (save-excursion
18547 (beginning-of-line 1)
18548 (skip-chars-forward " \t")
18549 (current-column))))
18551 (defun org-get-string-indentation (s)
18552 "What indentation has S due to SPACE and TAB at the beginning of the string?"
18553 (let ((n -1) (i 0) (w tab-width) c)
18554 (catch 'exit
18555 (while (< (setq n (1+ n)) (length s))
18556 (setq c (aref s n))
18557 (cond ((= c ?\ ) (setq i (1+ i)))
18558 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
18559 (t (throw 'exit t)))))
18562 (defun org-remove-tabs (s &optional width)
18563 "Replace tabulators in S with spaces.
18564 Assumes that s is a single line, starting in column 0."
18565 (setq width (or width tab-width))
18566 (while (string-match "\t" s)
18567 (setq s (replace-match
18568 (make-string
18569 (- (* width (/ (+ (match-beginning 0) width) width))
18570 (match-beginning 0)) ?\ )
18571 t t s)))
18574 (defun org-fix-indentation (line ind)
18575 "Fix indentation in LINE.
18576 IND is a cons cell with target and minimum indentation.
18577 If the current indentation in LINE is smaller than the minimum,
18578 leave it alone. If it is larger than ind, set it to the target."
18579 (let* ((l (org-remove-tabs line))
18580 (i (org-get-indentation l))
18581 (i1 (car ind)) (i2 (cdr ind)))
18582 (if (>= i i2) (setq l (substring line i2)))
18583 (if (> i1 0)
18584 (concat (make-string i1 ?\ ) l)
18585 l)))
18587 (defun org-remove-indentation (code &optional n)
18588 "Remove the maximum common indentation from the lines in CODE.
18589 N may optionally be the number of spaces to remove."
18590 (with-temp-buffer
18591 (insert code)
18592 (org-do-remove-indentation n)
18593 (buffer-string)))
18595 (defun org-do-remove-indentation (&optional n)
18596 "Remove the maximum common indentation from the buffer."
18597 (untabify (point-min) (point-max))
18598 (let ((min 10000) re)
18599 (if n
18600 (setq min n)
18601 (goto-char (point-min))
18602 (while (re-search-forward "^ *[^ \n]" nil t)
18603 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
18604 (unless (or (= min 0) (= min 10000))
18605 (setq re (format "^ \\{%d\\}" min))
18606 (goto-char (point-min))
18607 (while (re-search-forward re nil t)
18608 (replace-match "")
18609 (end-of-line 1))
18610 min)))
18612 (defun org-fill-template (template alist)
18613 "Find each %key of ALIST in TEMPLATE and replace it."
18614 (let ((case-fold-search nil)
18615 entry key value)
18616 (setq alist (sort (copy-sequence alist)
18617 (lambda (a b) (< (length (car a)) (length (car b))))))
18618 (while (setq entry (pop alist))
18619 (setq template
18620 (replace-regexp-in-string
18621 (concat "%" (regexp-quote (car entry)))
18622 (cdr entry) template t t)))
18623 template))
18625 (defun org-base-buffer (buffer)
18626 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
18627 (if (not buffer)
18628 buffer
18629 (or (buffer-base-buffer buffer)
18630 buffer)))
18632 (defun org-trim (s)
18633 "Remove whitespace at beginning and end of string."
18634 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
18635 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
18638 (defun org-wrap (string &optional width lines)
18639 "Wrap string to either a number of lines, or a width in characters.
18640 If WIDTH is non-nil, the string is wrapped to that width, however many lines
18641 that costs. If there is a word longer than WIDTH, the text is actually
18642 wrapped to the length of that word.
18643 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
18644 many lines, whatever width that takes.
18645 The return value is a list of lines, without newlines at the end."
18646 (let* ((words (org-split-string string "[ \t\n]+"))
18647 (maxword (apply 'max (mapcar 'org-string-width words)))
18648 w ll)
18649 (cond (width
18650 (org-do-wrap words (max maxword width)))
18651 (lines
18652 (setq w maxword)
18653 (setq ll (org-do-wrap words maxword))
18654 (if (<= (length ll) lines)
18656 (setq ll words)
18657 (while (> (length ll) lines)
18658 (setq w (1+ w))
18659 (setq ll (org-do-wrap words w)))
18660 ll))
18661 (t (error "Cannot wrap this")))))
18663 (defun org-do-wrap (words width)
18664 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
18665 (let (lines line)
18666 (while words
18667 (setq line (pop words))
18668 (while (and words (< (+ (length line) (length (car words))) width))
18669 (setq line (concat line " " (pop words))))
18670 (setq lines (push line lines)))
18671 (nreverse lines)))
18673 (defun org-split-string (string &optional separators)
18674 "Splits STRING into substrings at SEPARATORS.
18675 No empty strings are returned if there are matches at the beginning
18676 and end of string."
18677 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
18678 (start 0)
18679 notfirst
18680 (list nil))
18681 (while (and (string-match rexp string
18682 (if (and notfirst
18683 (= start (match-beginning 0))
18684 (< start (length string)))
18685 (1+ start) start))
18686 (< (match-beginning 0) (length string)))
18687 (setq notfirst t)
18688 (or (eq (match-beginning 0) 0)
18689 (and (eq (match-beginning 0) (match-end 0))
18690 (eq (match-beginning 0) start))
18691 (setq list
18692 (cons (substring string start (match-beginning 0))
18693 list)))
18694 (setq start (match-end 0)))
18695 (or (eq start (length string))
18696 (setq list
18697 (cons (substring string start)
18698 list)))
18699 (nreverse list)))
18701 (defun org-quote-vert (s)
18702 "Replace \"|\" with \"\\vert\"."
18703 (while (string-match "|" s)
18704 (setq s (replace-match "\\vert" t t s)))
18707 (defun org-uuidgen-p (s)
18708 "Is S an ID created by UUIDGEN?"
18709 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
18711 (defun org-context ()
18712 "Return a list of contexts of the current cursor position.
18713 If several contexts apply, all are returned.
18714 Each context entry is a list with a symbol naming the context, and
18715 two positions indicating start and end of the context. Possible
18716 contexts are:
18718 :headline anywhere in a headline
18719 :headline-stars on the leading stars in a headline
18720 :todo-keyword on a TODO keyword (including DONE) in a headline
18721 :tags on the TAGS in a headline
18722 :priority on the priority cookie in a headline
18723 :item on the first line of a plain list item
18724 :item-bullet on the bullet/number of a plain list item
18725 :checkbox on the checkbox in a plain list item
18726 :table in an org-mode table
18727 :table-special on a special filed in a table
18728 :table-table in a table.el table
18729 :link on a hyperlink
18730 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
18731 :target on a <<target>>
18732 :radio-target on a <<<radio-target>>>
18733 :latex-fragment on a LaTeX fragment
18734 :latex-preview on a LaTeX fragment with overlayed preview image
18736 This function expects the position to be visible because it uses font-lock
18737 faces as a help to recognize the following contexts: :table-special, :link,
18738 and :keyword."
18739 (let* ((f (get-text-property (point) 'face))
18740 (faces (if (listp f) f (list f)))
18741 (p (point)) clist o)
18742 ;; First the large context
18743 (cond
18744 ((org-on-heading-p t)
18745 (push (list :headline (point-at-bol) (point-at-eol)) clist)
18746 (when (progn
18747 (beginning-of-line 1)
18748 (looking-at org-todo-line-tags-regexp))
18749 (push (org-point-in-group p 1 :headline-stars) clist)
18750 (push (org-point-in-group p 2 :todo-keyword) clist)
18751 (push (org-point-in-group p 4 :tags) clist))
18752 (goto-char p)
18753 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
18754 (if (looking-at "\\[#[A-Z0-9]\\]")
18755 (push (org-point-in-group p 0 :priority) clist)))
18757 ((org-at-item-p)
18758 (push (org-point-in-group p 2 :item-bullet) clist)
18759 (push (list :item (point-at-bol)
18760 (save-excursion (org-end-of-item) (point)))
18761 clist)
18762 (and (org-at-item-checkbox-p)
18763 (push (org-point-in-group p 0 :checkbox) clist)))
18765 ((org-at-table-p)
18766 (push (list :table (org-table-begin) (org-table-end)) clist)
18767 (if (memq 'org-formula faces)
18768 (push (list :table-special
18769 (previous-single-property-change p 'face)
18770 (next-single-property-change p 'face)) clist)))
18771 ((org-at-table-p 'any)
18772 (push (list :table-table) clist)))
18773 (goto-char p)
18775 ;; Now the small context
18776 (cond
18777 ((org-at-timestamp-p)
18778 (push (org-point-in-group p 0 :timestamp) clist))
18779 ((memq 'org-link faces)
18780 (push (list :link
18781 (previous-single-property-change p 'face)
18782 (next-single-property-change p 'face)) clist))
18783 ((memq 'org-special-keyword faces)
18784 (push (list :keyword
18785 (previous-single-property-change p 'face)
18786 (next-single-property-change p 'face)) clist))
18787 ((org-on-target-p)
18788 (push (org-point-in-group p 0 :target) clist)
18789 (goto-char (1- (match-beginning 0)))
18790 (if (looking-at org-radio-target-regexp)
18791 (push (org-point-in-group p 0 :radio-target) clist))
18792 (goto-char p))
18793 ((setq o (car (delq nil
18794 (mapcar
18795 (lambda (x)
18796 (if (memq x org-latex-fragment-image-overlays) x))
18797 (overlays-at (point))))))
18798 (push (list :latex-fragment
18799 (overlay-start o) (overlay-end o)) clist)
18800 (push (list :latex-preview
18801 (overlay-start o) (overlay-end o)) clist))
18802 ((org-inside-LaTeX-fragment-p)
18803 ;; FIXME: positions wrong.
18804 (push (list :latex-fragment (point) (point)) clist)))
18806 (setq clist (nreverse (delq nil clist)))
18807 clist))
18809 ;; FIXME: Compare with at-regexp-p Do we need both?
18810 (defun org-in-regexp (re &optional nlines visually)
18811 "Check if point is inside a match of regexp.
18812 Normally only the current line is checked, but you can include NLINES extra
18813 lines both before and after point into the search.
18814 If VISUALLY is set, require that the cursor is not after the match but
18815 really on, so that the block visually is on the match."
18816 (catch 'exit
18817 (let ((pos (point))
18818 (eol (point-at-eol (+ 1 (or nlines 0))))
18819 (inc (if visually 1 0)))
18820 (save-excursion
18821 (beginning-of-line (- 1 (or nlines 0)))
18822 (while (re-search-forward re eol t)
18823 (if (and (<= (match-beginning 0) pos)
18824 (>= (+ inc (match-end 0)) pos))
18825 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
18827 (defun org-at-regexp-p (regexp)
18828 "Is point inside a match of REGEXP in the current line?"
18829 (catch 'exit
18830 (save-excursion
18831 (let ((pos (point)) (end (point-at-eol)))
18832 (beginning-of-line 1)
18833 (while (re-search-forward regexp end t)
18834 (if (and (<= (match-beginning 0) pos)
18835 (>= (match-end 0) pos))
18836 (throw 'exit t)))
18837 nil))))
18839 (defun org-in-regexps-block-p (start-re end-re &optional bound)
18840 "Return t if the current point is between matches of START-RE and END-RE.
18841 This will also return t if point is on one of the two matches or
18842 in an unfinished block. END-RE can be a string or a form
18843 returning a string.
18845 An optional third argument bounds the search for START-RE. It
18846 defaults to previous heading or `point-min'."
18847 (let ((pos (point))
18848 (limit (or bound (save-excursion (outline-previous-heading)))))
18849 (save-excursion
18850 ;; we're on a block when point is on start-re...
18851 (or (org-at-regexp-p start-re)
18852 ;; ... or start-re can be found above...
18853 (and (re-search-backward start-re limit t)
18854 ;; ... but no end-re between start-re and point.
18855 (not (re-search-forward (eval end-re) pos t)))))))
18857 (defun org-occur-in-agenda-files (regexp &optional nlines)
18858 "Call `multi-occur' with buffers for all agenda files."
18859 (interactive "sOrg-files matching: \np")
18860 (let* ((files (org-agenda-files))
18861 (tnames (mapcar 'file-truename files))
18862 (extra org-agenda-text-search-extra-files)
18864 (when (eq (car extra) 'agenda-archives)
18865 (setq extra (cdr extra))
18866 (setq files (org-add-archive-files files)))
18867 (while (setq f (pop extra))
18868 (unless (member (file-truename f) tnames)
18869 (add-to-list 'files f 'append)
18870 (add-to-list 'tnames (file-truename f) 'append)))
18871 (multi-occur
18872 (mapcar (lambda (x)
18873 (with-current-buffer
18874 (or (get-file-buffer x) (find-file-noselect x))
18875 (widen)
18876 (current-buffer)))
18877 files)
18878 regexp)))
18880 (if (boundp 'occur-mode-find-occurrence-hook)
18881 ;; Emacs 23
18882 (add-hook 'occur-mode-find-occurrence-hook
18883 (lambda ()
18884 (when (org-mode-p)
18885 (org-reveal))))
18886 ;; Emacs 22
18887 (defadvice occur-mode-goto-occurrence
18888 (after org-occur-reveal activate)
18889 (and (org-mode-p) (org-reveal)))
18890 (defadvice occur-mode-goto-occurrence-other-window
18891 (after org-occur-reveal activate)
18892 (and (org-mode-p) (org-reveal)))
18893 (defadvice occur-mode-display-occurrence
18894 (after org-occur-reveal activate)
18895 (when (org-mode-p)
18896 (let ((pos (occur-mode-find-occurrence)))
18897 (with-current-buffer (marker-buffer pos)
18898 (save-excursion
18899 (goto-char pos)
18900 (org-reveal)))))))
18902 (defun org-occur-link-in-agenda-files ()
18903 "Create a link and search for it in the agendas.
18904 The link is not stored in `org-stored-links', it is just created
18905 for the search purpose."
18906 (interactive)
18907 (let ((link (condition-case nil
18908 (org-store-link nil)
18909 (error "Unable to create a link to here"))))
18910 (org-occur-in-agenda-files (regexp-quote link))))
18912 (defun org-uniquify (list)
18913 "Remove duplicate elements from LIST."
18914 (let (res)
18915 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
18916 res))
18918 (defun org-delete-all (elts list)
18919 "Remove all elements in ELTS from LIST."
18920 (while elts
18921 (setq list (delete (pop elts) list)))
18922 list)
18924 (defun org-count (cl-item cl-seq)
18925 "Count the number of occurrences of ITEM in SEQ.
18926 Taken from `count' in cl-seq.el with all keyword arguments removed."
18927 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
18928 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
18929 (while (< cl-start cl-end)
18930 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
18931 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
18932 (setq cl-start (1+ cl-start)))
18933 cl-count))
18935 (defun org-remove-if (predicate seq)
18936 "Remove everything from SEQ that fulfills PREDICATE."
18937 (let (res e)
18938 (while seq
18939 (setq e (pop seq))
18940 (if (not (funcall predicate e)) (push e res)))
18941 (nreverse res)))
18943 (defun org-remove-if-not (predicate seq)
18944 "Remove everything from SEQ that does not fulfill PREDICATE."
18945 (let (res e)
18946 (while seq
18947 (setq e (pop seq))
18948 (if (funcall predicate e) (push e res)))
18949 (nreverse res)))
18951 (defun org-back-over-empty-lines ()
18952 "Move backwards over whitespace, to the beginning of the first empty line.
18953 Returns the number of empty lines passed."
18954 (let ((pos (point)))
18955 (if (cdr (assoc 'heading org-blank-before-new-entry))
18956 (skip-chars-backward " \t\n\r")
18957 (forward-line -1))
18958 (beginning-of-line 2)
18959 (goto-char (min (point) pos))
18960 (count-lines (point) pos)))
18962 (defun org-skip-whitespace ()
18963 (skip-chars-forward " \t\n\r"))
18965 (defun org-point-in-group (point group &optional context)
18966 "Check if POINT is in match-group GROUP.
18967 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
18968 match. If the match group does not exist or point is not inside it,
18969 return nil."
18970 (and (match-beginning group)
18971 (>= point (match-beginning group))
18972 (<= point (match-end group))
18973 (if context
18974 (list context (match-beginning group) (match-end group))
18975 t)))
18977 (defun org-switch-to-buffer-other-window (&rest args)
18978 "Switch to buffer in a second window on the current frame.
18979 In particular, do not allow pop-up frames.
18980 Returns the newly created buffer."
18981 (let (pop-up-frames special-display-buffer-names special-display-regexps
18982 special-display-function)
18983 (apply 'switch-to-buffer-other-window args)))
18985 (defun org-combine-plists (&rest plists)
18986 "Create a single property list from all plists in PLISTS.
18987 The process starts by copying the first list, and then setting properties
18988 from the other lists. Settings in the last list are the most significant
18989 ones and overrule settings in the other lists."
18990 (let ((rtn (copy-sequence (pop plists)))
18991 p v ls)
18992 (while plists
18993 (setq ls (pop plists))
18994 (while ls
18995 (setq p (pop ls) v (pop ls))
18996 (setq rtn (plist-put rtn p v))))
18997 rtn))
18999 (defun org-move-line-down (arg)
19000 "Move the current line down. With prefix argument, move it past ARG lines."
19001 (interactive "p")
19002 (let ((col (current-column))
19003 beg end pos)
19004 (beginning-of-line 1) (setq beg (point))
19005 (beginning-of-line 2) (setq end (point))
19006 (beginning-of-line (+ 1 arg))
19007 (setq pos (move-marker (make-marker) (point)))
19008 (insert (delete-and-extract-region beg end))
19009 (goto-char pos)
19010 (org-move-to-column col)))
19012 (defun org-move-line-up (arg)
19013 "Move the current line up. With prefix argument, move it past ARG lines."
19014 (interactive "p")
19015 (let ((col (current-column))
19016 beg end pos)
19017 (beginning-of-line 1) (setq beg (point))
19018 (beginning-of-line 2) (setq end (point))
19019 (beginning-of-line (- arg))
19020 (setq pos (move-marker (make-marker) (point)))
19021 (insert (delete-and-extract-region beg end))
19022 (goto-char pos)
19023 (org-move-to-column col)))
19025 (defun org-replace-escapes (string table)
19026 "Replace %-escapes in STRING with values in TABLE.
19027 TABLE is an association list with keys like \"%a\" and string values.
19028 The sequences in STRING may contain normal field width and padding information,
19029 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
19030 so values can contain further %-escapes if they are define later in TABLE."
19031 (let ((tbl (copy-alist table))
19032 (case-fold-search nil)
19033 (pchg 0)
19034 e re rpl)
19035 (while (setq e (pop tbl))
19036 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
19037 (when (and (cdr e) (string-match re (cdr e)))
19038 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
19039 (safe "SREF"))
19040 (add-text-properties 0 3 (list 'sref sref) safe)
19041 (setcdr e (replace-match safe t t (cdr e)))))
19042 (while (string-match re string)
19043 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
19044 (cdr e)))
19045 (setq string (replace-match rpl t t string))))
19046 (while (setq pchg (next-property-change pchg string))
19047 (let ((sref (get-text-property pchg 'sref string)))
19048 (when (and sref (string-match "SREF" string pchg))
19049 (setq string (replace-match sref t t string)))))
19050 string))
19052 (defun org-sublist (list start end)
19053 "Return a section of LIST, from START to END.
19054 Counting starts at 1."
19055 (let (rtn (c start))
19056 (setq list (nthcdr (1- start) list))
19057 (while (and list (<= c end))
19058 (push (pop list) rtn)
19059 (setq c (1+ c)))
19060 (nreverse rtn)))
19062 (defun org-find-base-buffer-visiting (file)
19063 "Like `find-buffer-visiting' but always return the base buffer and
19064 not an indirect buffer."
19065 (let ((buf (or (get-file-buffer file)
19066 (find-buffer-visiting file))))
19067 (if buf
19068 (or (buffer-base-buffer buf) buf)
19069 nil)))
19071 (defun org-image-file-name-regexp (&optional extensions)
19072 "Return regexp matching the file names of images.
19073 If EXTENSIONS is given, only match these."
19074 (if (and (not extensions) (fboundp 'image-file-name-regexp))
19075 (image-file-name-regexp)
19076 (let ((image-file-name-extensions
19077 (or extensions
19078 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
19079 "xbm" "xpm" "pbm" "pgm" "ppm"))))
19080 (concat "\\."
19081 (regexp-opt (nconc (mapcar 'upcase
19082 image-file-name-extensions)
19083 image-file-name-extensions)
19085 "\\'"))))
19087 (defun org-file-image-p (file &optional extensions)
19088 "Return non-nil if FILE is an image."
19089 (save-match-data
19090 (string-match (org-image-file-name-regexp extensions) file)))
19092 (defun org-get-cursor-date ()
19093 "Return the date at cursor in as a time.
19094 This works in the calendar and in the agenda, anywhere else it just
19095 returns the current time."
19096 (let (date day defd)
19097 (cond
19098 ((eq major-mode 'calendar-mode)
19099 (setq date (calendar-cursor-to-date)
19100 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
19101 ((eq major-mode 'org-agenda-mode)
19102 (setq day (get-text-property (point) 'day))
19103 (if day
19104 (setq date (calendar-gregorian-from-absolute day)
19105 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
19106 (nth 2 date))))))
19107 (or defd (current-time))))
19109 (defvar org-agenda-action-marker (make-marker)
19110 "Marker pointing to the entry for the next agenda action.")
19112 (defun org-mark-entry-for-agenda-action ()
19113 "Mark the current entry as target of an agenda action.
19114 Agenda actions are actions executed from the agenda with the key `k',
19115 which make use of the date at the cursor."
19116 (interactive)
19117 (move-marker org-agenda-action-marker
19118 (save-excursion (org-back-to-heading t) (point))
19119 (current-buffer))
19120 (message
19121 "Entry marked for action; press `k' at desired date in agenda or calendar"))
19123 (defun org-mark-subtree ()
19124 "Mark the current subtree.
19125 This puts point at the start of the current subtree, and mark at the end.
19127 If point is in an inline task, mark that task instead."
19128 (interactive)
19129 (let ((inline-task-p
19130 (and (featurep 'org-inlinetask)
19131 (org-inlinetask-in-task-p)))
19132 (beg))
19133 ;; Get beginning of subtree
19134 (cond
19135 (inline-task-p (org-inlinetask-goto-beginning))
19136 ((org-at-heading-p) (beginning-of-line))
19137 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
19138 (setq beg (point))
19139 ;; Get end of it
19140 (if inline-task-p
19141 (org-inlinetask-goto-end)
19142 (org-end-of-subtree))
19143 ;; Mark zone
19144 (push-mark (point) nil t)
19145 (goto-char beg)))
19147 ;;; Paragraph filling stuff.
19148 ;; We want this to be just right, so use the full arsenal.
19150 (defun org-indent-line-function ()
19151 "Indent line depending on context."
19152 (interactive)
19153 (let* ((pos (point))
19154 (itemp (org-at-item-p))
19155 (case-fold-search t)
19156 (org-drawer-regexp (or org-drawer-regexp "\000"))
19157 (inline-task-p (and (featurep 'org-inlinetask)
19158 (org-inlinetask-in-task-p)))
19159 (inline-re (and inline-task-p
19160 (org-inlinetask-outline-regexp)))
19161 column)
19162 (beginning-of-line 1)
19163 (cond
19164 ;; Comments
19165 ((looking-at "# ") (setq column 0))
19166 ;; Headings
19167 ((looking-at "\\*+ ") (setq column 0))
19168 ;; Included files
19169 ((looking-at "#\\+include:") (setq column 0))
19170 ;; Footnote definition
19171 ((looking-at org-footnote-definition-re) (setq column 0))
19172 ;; Literal examples
19173 ((looking-at "[ \t]*:[ \t]")
19174 (setq column (org-get-indentation))) ; do nothing
19175 ;; Lists
19176 ((ignore-errors (goto-char (org-in-item-p)))
19177 (setq column (if itemp
19178 (org-get-indentation)
19179 (org-list-item-body-column (point))))
19180 (goto-char pos))
19181 ;; Drawers
19182 ((and (looking-at "[ \t]*:END:")
19183 (save-excursion (re-search-backward org-drawer-regexp nil t)))
19184 (save-excursion
19185 (goto-char (1- (match-beginning 1)))
19186 (setq column (current-column))))
19187 ;; Special blocks
19188 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
19189 (save-excursion
19190 (re-search-backward
19191 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
19192 (setq column (org-get-indentation (match-string 0))))
19193 ((and (not (looking-at "[ \t]*#\\+begin_"))
19194 (org-in-regexps-block-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
19195 (save-excursion
19196 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
19197 (setq column
19198 (if (equal (downcase (match-string 1)) "src")
19199 ;; src blocks: let `org-edit-src-exit' handle them
19200 (org-get-indentation)
19201 (org-get-indentation (match-string 0)))))
19202 ;; This line has nothing special, look at the previous relevant
19203 ;; line to compute indentation
19205 (beginning-of-line 0)
19206 (while (and (not (bobp))
19207 (not (looking-at org-drawer-regexp))
19208 ;; When point started in an inline task, do not move
19209 ;; above task starting line.
19210 (not (and inline-task-p (looking-at inline-re)))
19211 ;; Skip drawers, blocks, empty lines, verbatim,
19212 ;; comments, tables, footnotes definitions, lists,
19213 ;; inline tasks.
19214 (or (and (looking-at "[ \t]*:END:")
19215 (re-search-backward org-drawer-regexp nil t))
19216 (and (looking-at "[ \t]*#\\+end_")
19217 (re-search-backward "[ \t]*#\\+begin_"nil t))
19218 (looking-at "[ \t]*[\n:#|]")
19219 (looking-at org-footnote-definition-re)
19220 (and (ignore-errors (goto-char (org-in-item-p)))
19221 (goto-char
19222 (org-list-get-top-point (org-list-struct))))
19223 (and (not inline-task-p)
19224 (featurep 'org-inlinetask)
19225 (org-inlinetask-in-task-p)
19226 (or (org-inlinetask-goto-beginning) t))))
19227 (beginning-of-line 0))
19228 (cond
19229 ;; There was an heading above.
19230 ((looking-at "\\*+[ \t]+")
19231 (if (not org-adapt-indentation)
19232 (setq column 0)
19233 (goto-char (match-end 0))
19234 (setq column (current-column))))
19235 ;; A drawer had started and is unfinished
19236 ((looking-at org-drawer-regexp)
19237 (goto-char (1- (match-beginning 1)))
19238 (setq column (current-column)))
19239 ;; Else, nothing noticeable found: get indentation and go on.
19240 (t (setq column (org-get-indentation))))))
19241 ;; Now apply indentation and move cursor accordingly
19242 (goto-char pos)
19243 (if (<= (current-column) (current-indentation))
19244 (org-indent-line-to column)
19245 (save-excursion (org-indent-line-to column)))
19246 ;; Special polishing for properties, see `org-property-format'
19247 (setq column (current-column))
19248 (beginning-of-line 1)
19249 (if (looking-at
19250 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
19251 (replace-match (concat (match-string 1)
19252 (format org-property-format
19253 (match-string 2) (match-string 3)))
19254 t t))
19255 (org-move-to-column column)))
19257 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
19258 "Variable to store copy of `adaptive-fill-regexp'.
19259 Since `adaptive-fill-regexp' is set to never match, we need to
19260 store a backup of its value before entering `org-mode' so that
19261 the functionality can be provided as a fall-back.")
19263 (defun org-set-autofill-regexps ()
19264 (interactive)
19265 ;; In the paragraph separator we include headlines, because filling
19266 ;; text in a line directly attached to a headline would otherwise
19267 ;; fill the headline as well.
19268 (org-set-local 'comment-start-skip "^#+[ \t]*")
19269 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
19270 ;; The paragraph starter includes hand-formatted lists.
19271 (org-set-local
19272 'paragraph-start
19273 (concat
19274 "\f" "\\|"
19275 "[ ]*$" "\\|"
19276 "\\*+ " "\\|"
19277 "[ \t]*#" "\\|"
19278 (org-item-re) "\\|"
19279 "[ \t]*[:|]" "\\|"
19280 "\\$\\$" "\\|"
19281 "\\\\\\(begin\\|end\\|[][]\\)"))
19282 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
19283 ;; But only if the user has not turned off tables or fixed-width regions
19284 (org-set-local
19285 'auto-fill-inhibit-regexp
19286 (concat "\\*+ \\|#\\+"
19287 "\\|[ \t]*" org-keyword-time-regexp
19288 (if (or org-enable-table-editor org-enable-fixed-width-editor)
19289 (concat
19290 "\\|[ \t]*["
19291 (if org-enable-table-editor "|" "")
19292 (if org-enable-fixed-width-editor ":" "")
19293 "]"))))
19294 ;; We use our own fill-paragraph function, to make sure that tables
19295 ;; and fixed-width regions are not wrapped. That function will pass
19296 ;; through to `fill-paragraph' when appropriate.
19297 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
19298 ;; Prevent auto-fill from inserting unwanted new items.
19299 (org-set-local 'fill-nobreak-predicate
19300 (if (memq 'org-fill-item-nobreak-p fill-nobreak-predicate)
19301 fill-nobreak-predicate
19302 (cons 'org-fill-item-nobreak-p fill-nobreak-predicate)))
19303 ;; Adaptive filling: To get full control, first make sure that
19304 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
19305 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
19306 (org-set-local 'org-adaptive-fill-regexp-backup
19307 adaptive-fill-regexp))
19308 (org-set-local 'adaptive-fill-regexp "\000")
19309 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
19310 (org-set-local 'adaptive-fill-function
19311 'org-adaptive-fill-function)
19312 (org-set-local
19313 'align-mode-rules-list
19314 '((org-in-buffer-settings
19315 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
19316 (modes . '(org-mode))))))
19318 (defun org-fill-item-nobreak-p ()
19319 "Non-nil when a line break at point would insert a new item."
19320 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
19322 (defun org-fill-paragraph (&optional justify)
19323 "Re-align a table, pass through to fill-paragraph if no table."
19324 (let ((table-p (org-at-table-p))
19325 (table.el-p (org-at-table.el-p))
19326 (itemp (org-in-item-p)))
19327 (cond ((and (equal (char-after (point-at-bol)) ?*)
19328 (save-excursion (goto-char (point-at-bol))
19329 (looking-at outline-regexp)))
19330 t) ; skip headlines
19331 (table.el-p t) ; skip table.el tables
19332 (table-p (org-table-align) t) ; align Org tables
19333 (itemp ; align text in items
19334 (let* ((struct (save-excursion (goto-char itemp)
19335 (org-list-struct)))
19336 (parents (org-list-parents-alist struct))
19337 (children (org-list-get-children itemp struct parents))
19338 beg end prev next prefix)
19339 ;; Determine in which part of item point is: before
19340 ;; first child, after last child, between two
19341 ;; sub-lists, or simply in item if there's no child.
19342 (cond
19343 ((not children)
19344 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
19345 beg itemp
19346 end (org-list-get-item-end itemp struct)))
19347 ((< (point) (setq next (car children)))
19348 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
19349 beg itemp
19350 end next))
19351 ((> (point) (setq prev (car (last children))))
19352 (setq beg (org-list-get-item-end prev struct)
19353 end (org-list-get-item-end itemp struct)
19354 prefix (save-excursion
19355 (goto-char beg)
19356 (skip-chars-forward " \t")
19357 (make-string (current-column) ?\ ))))
19358 (t (catch 'exit
19359 (while (setq next (pop children))
19360 (if (> (point) next)
19361 (setq prev next)
19362 (setq beg (org-list-get-item-end prev struct)
19363 end next
19364 prefix (save-excursion
19365 (goto-char beg)
19366 (skip-chars-forward " \t")
19367 (make-string (current-column) ?\ )))
19368 (throw 'exit nil))))))
19369 ;; Use `fill-paragraph' with buffer narrowed to item
19370 ;; without any child, and with our computed PREFIX.
19371 (flet ((fill-context-prefix (from to &optional flr) prefix))
19372 (save-restriction
19373 (narrow-to-region beg end)
19374 (save-excursion (fill-paragraph justify)))) t))
19375 ;; Special case where point is not in a list but is on
19376 ;; a paragraph adjacent to a list: make sure this paragraph
19377 ;; doesn't get merged with the end of the list by narrowing
19378 ;; buffer first.
19379 ((save-excursion (forward-paragraph -1)
19380 (setq itemp (org-in-item-p)))
19381 (let ((struct (save-excursion (goto-char itemp)
19382 (org-list-struct))))
19383 (save-restriction
19384 (narrow-to-region (org-list-get-bottom-point struct)
19385 (save-excursion (forward-paragraph 1)
19386 (point)))
19387 (fill-paragraph justify) t)))
19388 ;; Else simply call `fill-paragraph'.
19389 (t nil))))
19391 ;; For reference, this is the default value of adaptive-fill-regexp
19392 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
19394 (defun org-adaptive-fill-function ()
19395 "Return a fill prefix for org-mode files."
19396 (let (itemp)
19397 (save-excursion
19398 (cond
19399 ;; Comment line
19400 ((looking-at "#[ \t]+")
19401 (match-string-no-properties 0))
19402 ;; Plain list item
19403 ((org-at-item-p)
19404 (make-string (org-list-item-body-column (point-at-bol)) ?\ ))
19405 ;; Point is in a list after `backward-paragraph': original
19406 ;; point wasn't in the list, or filling would have been taken
19407 ;; care of by `org-auto-fill-function', but the list and the
19408 ;; real paragraph are not separated by a blank line. Thus, move
19409 ;; point after the list to go back to real paragraph and
19410 ;; determine fill-prefix.
19411 ((setq itemp (org-in-item-p))
19412 (goto-char itemp)
19413 (let* ((struct (org-list-struct))
19414 (bottom (org-list-get-bottom-point struct)))
19415 (goto-char bottom)
19416 (make-string (org-get-indentation) ?\ )))
19417 ;; Other text
19418 ((looking-at org-adaptive-fill-regexp-backup)
19419 (match-string-no-properties 0))))))
19421 (defun org-auto-fill-function ()
19422 "Auto-fill function."
19423 (let (itemp prefix)
19424 ;; When in a list, compute an appropriate fill-prefix and make
19425 ;; sure it will be used by `do-auto-fill'.
19426 (if (setq itemp (org-in-item-p))
19427 (progn
19428 (setq prefix (make-string (org-list-item-body-column itemp) ?\ ))
19429 (flet ((fill-context-prefix (from to &optional flr) prefix))
19430 (do-auto-fill)))
19431 ;; Else just use `do-auto-fill'.
19432 (do-auto-fill))))
19434 ;;; Other stuff.
19436 (defun org-toggle-fixed-width-section (arg)
19437 "Toggle the fixed-width export.
19438 If there is no active region, the QUOTE keyword at the current headline is
19439 inserted or removed. When present, it causes the text between this headline
19440 and the next to be exported as fixed-width text, and unmodified.
19441 If there is an active region, this command adds or removes a colon as the
19442 first character of this line. If the first character of a line is a colon,
19443 this line is also exported in fixed-width font."
19444 (interactive "P")
19445 (let* ((cc 0)
19446 (regionp (org-region-active-p))
19447 (beg (if regionp (region-beginning) (point)))
19448 (end (if regionp (region-end)))
19449 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
19450 (case-fold-search nil)
19451 (re "[ \t]*\\(: \\)")
19452 off)
19453 (if regionp
19454 (save-excursion
19455 (goto-char beg)
19456 (setq cc (current-column))
19457 (beginning-of-line 1)
19458 (setq off (looking-at re))
19459 (while (> nlines 0)
19460 (setq nlines (1- nlines))
19461 (beginning-of-line 1)
19462 (cond
19463 (arg
19464 (org-move-to-column cc t)
19465 (insert ": \n")
19466 (forward-line -1))
19467 ((and off (looking-at re))
19468 (replace-match "" t t nil 1))
19469 ((not off) (org-move-to-column cc t) (insert ": ")))
19470 (forward-line 1)))
19471 (save-excursion
19472 (org-back-to-heading)
19473 (if (looking-at (concat outline-regexp
19474 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
19475 (replace-match "" t t nil 1)
19476 (if (looking-at outline-regexp)
19477 (progn
19478 (goto-char (match-end 0))
19479 (insert org-quote-string " "))))))))
19481 (defun org-reftex-citation ()
19482 "Use reftex-citation to insert a citation into the buffer.
19483 This looks for a line like
19485 #+BIBLIOGRAPHY: foo plain option:-d
19487 and derives from it that foo.bib is the bibliography file relevant
19488 for this document. It then installs the necessary environment for RefTeX
19489 to work in this buffer and calls `reftex-citation' to insert a citation
19490 into the buffer.
19492 Export of such citations to both LaTeX and HTML is handled by the contributed
19493 package org-exp-bibtex by Taru Karttunen."
19494 (interactive)
19495 (let ((reftex-docstruct-symbol 'rds)
19496 (reftex-cite-format "\\cite{%l}")
19497 rds bib)
19498 (save-excursion
19499 (save-restriction
19500 (widen)
19501 (let ((case-fold-search t)
19502 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
19503 (if (not (save-excursion
19504 (or (re-search-forward re nil t)
19505 (re-search-backward re nil t))))
19506 (error "No bibliography defined in file")
19507 (setq bib (concat (match-string 1) ".bib")
19508 rds (list (list 'bib bib)))))))
19509 (call-interactively 'reftex-citation)))
19511 ;;;; Functions extending outline functionality
19513 (defun org-beginning-of-line (&optional arg)
19514 "Go to the beginning of the current line. If that is invisible, continue
19515 to a visible line beginning. This makes the function of C-a more intuitive.
19516 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
19517 first attempt, and only move to after the tags when the cursor is already
19518 beyond the end of the headline."
19519 (interactive "P")
19520 (let ((pos (point))
19521 (special (if (consp org-special-ctrl-a/e)
19522 (car org-special-ctrl-a/e)
19523 org-special-ctrl-a/e))
19524 refpos)
19525 (if (org-bound-and-true-p line-move-visual)
19526 (beginning-of-visual-line 1)
19527 (beginning-of-line 1))
19528 (if (and arg (fboundp 'move-beginning-of-line))
19529 (call-interactively 'move-beginning-of-line)
19530 (if (bobp)
19532 (backward-char 1)
19533 (if (org-truely-invisible-p)
19534 (while (and (not (bobp)) (org-truely-invisible-p))
19535 (backward-char 1)
19536 (beginning-of-line 1))
19537 (forward-char 1))))
19538 (when special
19539 (cond
19540 ((and (looking-at org-complex-heading-regexp)
19541 (= (char-after (match-end 1)) ?\ ))
19542 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
19543 (point-at-eol)))
19544 (goto-char
19545 (if (eq special t)
19546 (cond ((> pos refpos) refpos)
19547 ((= pos (point)) refpos)
19548 (t (point)))
19549 (cond ((> pos (point)) (point))
19550 ((not (eq last-command this-command)) (point))
19551 (t refpos)))))
19552 ((org-at-item-p)
19553 (goto-char
19554 (if (eq special t)
19555 (cond ((> pos (match-end 0)) (match-end 0))
19556 ((= pos (point)) (match-end 0))
19557 (t (point)))
19558 (cond ((> pos (point)) (point))
19559 ((not (eq last-command this-command)) (point))
19560 (t (match-end 0))))))))
19561 (org-no-warnings
19562 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
19564 (defun org-end-of-line (&optional arg)
19565 "Go to the end of the line.
19566 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
19567 first attempt, and only move to after the tags when the cursor is already
19568 beyond the end of the headline."
19569 (interactive "P")
19570 (let ((special (if (consp org-special-ctrl-a/e)
19571 (cdr org-special-ctrl-a/e)
19572 org-special-ctrl-a/e)))
19573 (if (or (not special)
19574 (not (org-on-heading-p))
19575 arg)
19576 (call-interactively
19577 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
19578 ((fboundp 'move-end-of-line) 'move-end-of-line)
19579 (t 'end-of-line)))
19580 (let ((pos (point)))
19581 (beginning-of-line 1)
19582 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
19583 (if (eq special t)
19584 (if (or (< pos (match-beginning 1))
19585 (= pos (match-end 0)))
19586 (goto-char (match-beginning 1))
19587 (goto-char (match-end 0)))
19588 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
19589 (goto-char (match-end 0))
19590 (goto-char (match-beginning 1))))
19591 (call-interactively (if (fboundp 'move-end-of-line)
19592 'move-end-of-line
19593 'end-of-line)))))
19594 (org-no-warnings
19595 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
19597 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
19598 (define-key org-mode-map "\C-e" 'org-end-of-line)
19600 (defun org-backward-sentence (&optional arg)
19601 "Go to beginning of sentence, or beginning of table field.
19602 This will call `backward-sentence' or `org-table-beginning-of-field',
19603 depending on context."
19604 (interactive "P")
19605 (cond
19606 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
19607 (t (call-interactively 'backward-sentence))))
19609 (defun org-forward-sentence (&optional arg)
19610 "Go to end of sentence, or end of table field.
19611 This will call `forward-sentence' or `org-table-end-of-field',
19612 depending on context."
19613 (interactive "P")
19614 (cond
19615 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
19616 (t (call-interactively 'forward-sentence))))
19618 (define-key org-mode-map "\M-a" 'org-backward-sentence)
19619 (define-key org-mode-map "\M-e" 'org-forward-sentence)
19621 (defun org-kill-line (&optional arg)
19622 "Kill line, to tags or end of line."
19623 (interactive "P")
19624 (cond
19625 ((or (not org-special-ctrl-k)
19626 (bolp)
19627 (not (org-on-heading-p)))
19628 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
19629 org-ctrl-k-protect-subtree)
19630 (if (or (eq org-ctrl-k-protect-subtree 'error)
19631 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
19632 (error "C-k aborted - would kill hidden subtree")))
19633 (call-interactively 'kill-line))
19634 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
19635 (kill-region (point) (match-beginning 1))
19636 (org-set-tags nil t))
19637 (t (kill-region (point) (point-at-eol)))))
19639 (define-key org-mode-map "\C-k" 'org-kill-line)
19641 (defun org-yank (&optional arg)
19642 "Yank. If the kill is a subtree, treat it specially.
19643 This command will look at the current kill and check if is a single
19644 subtree, or a series of subtrees[1]. If it passes the test, and if the
19645 cursor is at the beginning of a line or after the stars of a currently
19646 empty headline, then the yank is handled specially. How exactly depends
19647 on the value of the following variables, both set by default.
19649 org-yank-folded-subtrees
19650 When set, the subtree(s) will be folded after insertion, but only
19651 if doing so would now swallow text after the yanked text.
19653 org-yank-adjusted-subtrees
19654 When set, the subtree will be promoted or demoted in order to
19655 fit into the local outline tree structure, which means that the level
19656 will be adjusted so that it becomes the smaller one of the two
19657 *visible* surrounding headings.
19659 Any prefix to this command will cause `yank' to be called directly with
19660 no special treatment. In particular, a simple \\[universal-argument] prefix \
19661 will just
19662 plainly yank the text as it is.
19664 \[1] The test checks if the first non-white line is a heading
19665 and if there are no other headings with fewer stars."
19666 (interactive "P")
19667 (org-yank-generic 'yank arg))
19669 (defun org-yank-generic (command arg)
19670 "Perform some yank-like command.
19672 This function implements the behavior described in the `org-yank'
19673 documentation. However, it has been generalized to work for any
19674 interactive command with similar behavior."
19676 ;; pretend to be command COMMAND
19677 (setq this-command command)
19679 (if arg
19680 (call-interactively command)
19682 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
19683 (and (org-kill-is-subtree-p)
19684 (or (bolp)
19685 (and (looking-at "[ \t]*$")
19686 (string-match
19687 "\\`\\*+\\'"
19688 (buffer-substring (point-at-bol) (point)))))))
19689 swallowp)
19690 (cond
19691 ((and subtreep org-yank-folded-subtrees)
19692 (let ((beg (point))
19693 end)
19694 (if (and subtreep org-yank-adjusted-subtrees)
19695 (org-paste-subtree nil nil 'for-yank)
19696 (call-interactively command))
19698 (setq end (point))
19699 (goto-char beg)
19700 (when (and (bolp) subtreep
19701 (not (setq swallowp
19702 (org-yank-folding-would-swallow-text beg end))))
19703 (or (looking-at outline-regexp)
19704 (re-search-forward (concat "^" outline-regexp) end t))
19705 (while (and (< (point) end) (looking-at outline-regexp))
19706 (hide-subtree)
19707 (org-cycle-show-empty-lines 'folded)
19708 (condition-case nil
19709 (outline-forward-same-level 1)
19710 (error (goto-char end)))))
19711 (when swallowp
19712 (message
19713 "Inserted text not folded because that would swallow text"))
19715 (goto-char end)
19716 (skip-chars-forward " \t\n\r")
19717 (beginning-of-line 1)
19718 (push-mark beg 'nomsg)))
19719 ((and subtreep org-yank-adjusted-subtrees)
19720 (let ((beg (point-at-bol)))
19721 (org-paste-subtree nil nil 'for-yank)
19722 (push-mark beg 'nomsg)))
19724 (call-interactively command))))))
19726 (defun org-yank-folding-would-swallow-text (beg end)
19727 "Would hide-subtree at BEG swallow any text after END?"
19728 (let (level)
19729 (save-excursion
19730 (goto-char beg)
19731 (when (or (looking-at outline-regexp)
19732 (re-search-forward (concat "^" outline-regexp) end t))
19733 (setq level (org-outline-level)))
19734 (goto-char end)
19735 (skip-chars-forward " \t\r\n\v\f")
19736 (if (or (eobp)
19737 (and (bolp) (looking-at org-outline-regexp)
19738 (<= (org-outline-level) level)))
19739 nil ; Nothing would be swallowed
19740 t)))) ; something would swallow
19742 (define-key org-mode-map "\C-y" 'org-yank)
19744 (defun org-truely-invisible-p ()
19745 "Check if point is at a character currently not visible.
19746 This version does not only check the character property, but also
19747 `visible-mode'."
19748 ;; Early versions of noutline don't have `outline-invisible-p'.
19749 (if (org-bound-and-true-p visible-mode)
19751 (outline-invisible-p)))
19753 (defun org-invisible-p2 ()
19754 "Check if point is at a character currently not visible."
19755 (save-excursion
19756 (if (and (eolp) (not (bobp))) (backward-char 1))
19757 ;; Early versions of noutline don't have `outline-invisible-p'.
19758 (outline-invisible-p)))
19760 (defun org-back-to-heading (&optional invisible-ok)
19761 "Call `outline-back-to-heading', but provide a better error message."
19762 (condition-case nil
19763 (outline-back-to-heading invisible-ok)
19764 (error (error "Before first headline at position %d in buffer %s"
19765 (point) (current-buffer)))))
19767 (defun org-beginning-of-defun ()
19768 "Go to the beginning of the subtree, i.e. back to the heading."
19769 (org-back-to-heading))
19770 (defun org-end-of-defun ()
19771 "Go to the end of the subtree."
19772 (org-end-of-subtree nil t))
19774 (defun org-before-first-heading-p ()
19775 "Before first heading?"
19776 (save-excursion
19777 (end-of-line)
19778 (null (re-search-backward "^\\*+ " nil t))))
19780 (defun org-on-heading-p (&optional ignored)
19781 (outline-on-heading-p t))
19782 (defun org-at-heading-p (&optional ignored)
19783 (outline-on-heading-p t))
19785 (defun org-point-at-end-of-empty-headline ()
19786 "If point is at the end of an empty headline, return t, else nil.
19787 If the heading only contains a TODO keyword, it is still still considered
19788 empty."
19789 (and (looking-at "[ \t]*$")
19790 (save-excursion
19791 (beginning-of-line 1)
19792 (let ((case-fold-search nil))
19793 (looking-at (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp
19794 "\\)?[ \t]*$"))))))
19795 (defun org-at-heading-or-item-p ()
19796 (or (org-on-heading-p) (org-at-item-p)))
19798 (defun org-on-target-p ()
19799 (or (org-in-regexp org-radio-target-regexp)
19800 (org-in-regexp org-target-regexp)))
19802 (defun org-up-heading-all (arg)
19803 "Move to the heading line of which the present line is a subheading.
19804 This function considers both visible and invisible heading lines.
19805 With argument, move up ARG levels."
19806 (if (fboundp 'outline-up-heading-all)
19807 (outline-up-heading-all arg) ; emacs 21 version of outline.el
19808 (outline-up-heading arg t))) ; emacs 22 version of outline.el
19810 (defun org-up-heading-safe ()
19811 "Move to the heading line of which the present line is a subheading.
19812 This version will not throw an error. It will return the level of the
19813 headline found, or nil if no higher level is found.
19815 Also, this function will be a lot faster than `outline-up-heading',
19816 because it relies on stars being the outline starters. This can really
19817 make a significant difference in outlines with very many siblings."
19818 (let (start-level re)
19819 (org-back-to-heading t)
19820 (setq start-level (funcall outline-level))
19821 (if (equal start-level 1)
19823 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
19824 (if (re-search-backward re nil t)
19825 (funcall outline-level)))))
19827 (defun org-first-sibling-p ()
19828 "Is this heading the first child of its parents?"
19829 (interactive)
19830 (let ((re (concat "^" outline-regexp))
19831 level l)
19832 (unless (org-at-heading-p t)
19833 (error "Not at a heading"))
19834 (setq level (funcall outline-level))
19835 (save-excursion
19836 (if (not (re-search-backward re nil t))
19838 (setq l (funcall outline-level))
19839 (< l level)))))
19841 (defun org-goto-sibling (&optional previous)
19842 "Goto the next sibling, even if it is invisible.
19843 When PREVIOUS is set, go to the previous sibling instead. Returns t
19844 when a sibling was found. When none is found, return nil and don't
19845 move point."
19846 (let ((fun (if previous 're-search-backward 're-search-forward))
19847 (pos (point))
19848 (re (concat "^" outline-regexp))
19849 level l)
19850 (when (condition-case nil (org-back-to-heading t) (error nil))
19851 (setq level (funcall outline-level))
19852 (catch 'exit
19853 (or previous (forward-char 1))
19854 (while (funcall fun re nil t)
19855 (setq l (funcall outline-level))
19856 (when (< l level) (goto-char pos) (throw 'exit nil))
19857 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
19858 (goto-char pos)
19859 nil))))
19861 (defun org-show-siblings ()
19862 "Show all siblings of the current headline."
19863 (save-excursion
19864 (while (org-goto-sibling) (org-flag-heading nil)))
19865 (save-excursion
19866 (while (org-goto-sibling 'previous)
19867 (org-flag-heading nil))))
19869 (defun org-goto-first-child ()
19870 "Goto the first child, even if it is invisible.
19871 Return t when a child was found. Otherwise don't move point and
19872 return nil."
19873 (let (level (pos (point)) (re (concat "^" outline-regexp)))
19874 (when (condition-case nil (org-back-to-heading t) (error nil))
19875 (setq level (outline-level))
19876 (forward-char 1)
19877 (if (and (re-search-forward re nil t) (> (outline-level) level))
19878 (progn (goto-char (match-beginning 0)) t)
19879 (goto-char pos) nil))))
19881 (defun org-show-hidden-entry ()
19882 "Show an entry where even the heading is hidden."
19883 (save-excursion
19884 (org-show-entry)))
19886 (defun org-flag-heading (flag &optional entry)
19887 "Flag the current heading. FLAG non-nil means make invisible.
19888 When ENTRY is non-nil, show the entire entry."
19889 (save-excursion
19890 (org-back-to-heading t)
19891 ;; Check if we should show the entire entry
19892 (if entry
19893 (progn
19894 (org-show-entry)
19895 (save-excursion
19896 (and (outline-next-heading)
19897 (org-flag-heading nil))))
19898 (outline-flag-region (max (point-min) (1- (point)))
19899 (save-excursion (outline-end-of-heading) (point))
19900 flag))))
19902 (defun org-get-next-sibling ()
19903 "Move to next heading of the same level, and return point.
19904 If there is no such heading, return nil.
19905 This is like outline-next-sibling, but invisible headings are ok."
19906 (let ((level (funcall outline-level)))
19907 (outline-next-heading)
19908 (while (and (not (eobp)) (> (funcall outline-level) level))
19909 (outline-next-heading))
19910 (if (or (eobp) (< (funcall outline-level) level))
19912 (point))))
19914 (defun org-get-last-sibling ()
19915 "Move to previous heading of the same level, and return point.
19916 If there is no such heading, return nil."
19917 (let ((opoint (point))
19918 (level (funcall outline-level)))
19919 (outline-previous-heading)
19920 (when (and (/= (point) opoint) (outline-on-heading-p t))
19921 (while (and (> (funcall outline-level) level)
19922 (not (bobp)))
19923 (outline-previous-heading))
19924 (if (< (funcall outline-level) level)
19926 (point)))))
19928 (defun org-end-of-subtree (&optional invisible-OK to-heading)
19929 ;; This contains an exact copy of the original function, but it uses
19930 ;; `org-back-to-heading', to make it work also in invisible
19931 ;; trees. And is uses an invisible-OK argument.
19932 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
19933 ;; Furthermore, when used inside Org, finding the end of a large subtree
19934 ;; with many children and grandchildren etc, this can be much faster
19935 ;; than the outline version.
19936 (org-back-to-heading invisible-OK)
19937 (let ((first t)
19938 (level (funcall outline-level)))
19939 (if (and (org-mode-p) (< level 1000))
19940 ;; A true heading (not a plain list item), in Org-mode
19941 ;; This means we can easily find the end by looking
19942 ;; only for the right number of stars. Using a regexp to do
19943 ;; this is so much faster than using a Lisp loop.
19944 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
19945 (forward-char 1)
19946 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
19947 ;; something else, do it the slow way
19948 (while (and (not (eobp))
19949 (or first (> (funcall outline-level) level)))
19950 (setq first nil)
19951 (outline-next-heading)))
19952 (unless to-heading
19953 (if (memq (preceding-char) '(?\n ?\^M))
19954 (progn
19955 ;; Go to end of line before heading
19956 (forward-char -1)
19957 (if (memq (preceding-char) '(?\n ?\^M))
19958 ;; leave blank line before heading
19959 (forward-char -1))))))
19960 (point))
19962 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
19963 "Use Org version in org-mode, for dramatic speed-up."
19964 (if (org-mode-p)
19965 (progn
19966 (org-end-of-subtree nil t)
19967 (unless (eobp) (backward-char 1)))
19968 ad-do-it))
19970 (defun org-end-of-meta-data-and-drawers ()
19971 "Jump to the first text after meta data and drawers in the current entry.
19972 This will move over empty lines, lines with planning time stamps,
19973 clocking lines, and drawers."
19974 (org-back-to-heading t)
19975 (let ((end (save-excursion (outline-next-heading) (point)))
19976 (re (concat "[ \t]*$"
19977 "\\|"
19978 "\\(" org-drawer-regexp "\\)" ; group 1 are drawers
19979 "\\|"
19980 "\\([ \t]*\\(" org-keyword-time-regexp "\\)\\)")))
19981 (forward-line 1)
19982 (while (looking-at (concat "[ \t]*\\(" org-keyword-time-regexp "\\)"))
19983 (if (not (match-end 1))
19984 ;; empty or planning line
19985 (forward-line 1)
19986 ;; a drawer, find the end
19987 (re-search-forward "^[ \t]*:END:" end 'move)
19988 (forward-line 1)))
19989 (point)))
19991 (defun org-forward-same-level (arg &optional invisible-ok)
19992 "Move forward to the arg'th subheading at same level as this one.
19993 Stop at the first and last subheadings of a superior heading.
19994 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
19995 it wil also look at invisible ones."
19996 (interactive "p")
19997 (org-back-to-heading invisible-ok)
19998 (org-on-heading-p)
19999 (let* ((level (- (match-end 0) (match-beginning 0) 1))
20000 (re (format "^\\*\\{1,%d\\} " level))
20002 (forward-char 1)
20003 (while (> arg 0)
20004 (while (and (re-search-forward re nil 'move)
20005 (setq l (- (match-end 0) (match-beginning 0) 1))
20006 (= l level)
20007 (not invisible-ok)
20008 (progn (backward-char 1) (outline-invisible-p)))
20009 (if (< l level) (setq arg 1)))
20010 (setq arg (1- arg)))
20011 (beginning-of-line 1)))
20013 (defun org-backward-same-level (arg &optional invisible-ok)
20014 "Move backward to the arg'th subheading at same level as this one.
20015 Stop at the first and last subheadings of a superior heading."
20016 (interactive "p")
20017 (org-back-to-heading)
20018 (org-on-heading-p)
20019 (let* ((level (- (match-end 0) (match-beginning 0) 1))
20020 (re (format "^\\*\\{1,%d\\} " level))
20022 (while (> arg 0)
20023 (while (and (re-search-backward re nil 'move)
20024 (setq l (- (match-end 0) (match-beginning 0) 1))
20025 (= l level)
20026 (not invisible-ok)
20027 (outline-invisible-p))
20028 (if (< l level) (setq arg 1)))
20029 (setq arg (1- arg)))))
20031 (defun org-show-subtree ()
20032 "Show everything after this heading at deeper levels."
20033 (outline-flag-region
20034 (point)
20035 (save-excursion
20036 (org-end-of-subtree t t))
20037 nil))
20039 (defun org-show-entry ()
20040 "Show the body directly following this heading.
20041 Show the heading too, if it is currently invisible."
20042 (interactive)
20043 (save-excursion
20044 (condition-case nil
20045 (progn
20046 (org-back-to-heading t)
20047 (outline-flag-region
20048 (max (point-min) (1- (point)))
20049 (save-excursion
20050 (if (re-search-forward
20051 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
20052 (match-beginning 1)
20053 (point-max)))
20054 nil)
20055 (org-cycle-hide-drawers 'children))
20056 (error nil))))
20058 (defun org-make-options-regexp (kwds &optional extra)
20059 "Make a regular expression for keyword lines."
20060 (concat
20062 "#?[ \t]*\\+\\("
20063 (mapconcat 'regexp-quote kwds "\\|")
20064 (if extra (concat "\\|" extra))
20065 "\\):[ \t]*"
20066 "\\(.*\\)"))
20068 ;; Make isearch reveal the necessary context
20069 (defun org-isearch-end ()
20070 "Reveal context after isearch exits."
20071 (when isearch-success ; only if search was successful
20072 (if (featurep 'xemacs)
20073 ;; Under XEmacs, the hook is run in the correct place,
20074 ;; we directly show the context.
20075 (org-show-context 'isearch)
20076 ;; In Emacs the hook runs *before* restoring the overlays.
20077 ;; So we have to use a one-time post-command-hook to do this.
20078 ;; (Emacs 22 has a special variable, see function `org-mode')
20079 (unless (and (boundp 'isearch-mode-end-hook-quit)
20080 isearch-mode-end-hook-quit)
20081 ;; Only when the isearch was not quitted.
20082 (org-add-hook 'post-command-hook 'org-isearch-post-command
20083 'append 'local)))))
20085 (defun org-isearch-post-command ()
20086 "Remove self from hook, and show context."
20087 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
20088 (org-show-context 'isearch))
20091 ;;;; Integration with and fixes for other packages
20093 ;;; Imenu support
20095 (defvar org-imenu-markers nil
20096 "All markers currently used by Imenu.")
20097 (make-variable-buffer-local 'org-imenu-markers)
20099 (defun org-imenu-new-marker (&optional pos)
20100 "Return a new marker for use by Imenu, and remember the marker."
20101 (let ((m (make-marker)))
20102 (move-marker m (or pos (point)))
20103 (push m org-imenu-markers)
20106 (defun org-imenu-get-tree ()
20107 "Produce the index for Imenu."
20108 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
20109 (setq org-imenu-markers nil)
20110 (let* ((n org-imenu-depth)
20111 (re (concat "^" outline-regexp))
20112 (subs (make-vector (1+ n) nil))
20113 (last-level 0)
20114 m level head)
20115 (save-excursion
20116 (save-restriction
20117 (widen)
20118 (goto-char (point-max))
20119 (while (re-search-backward re nil t)
20120 (setq level (org-reduced-level (funcall outline-level)))
20121 (when (<= level n)
20122 (looking-at org-complex-heading-regexp)
20123 (setq head (org-link-display-format
20124 (org-match-string-no-properties 4))
20125 m (org-imenu-new-marker))
20126 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
20127 (if (>= level last-level)
20128 (push (cons head m) (aref subs level))
20129 (push (cons head (aref subs (1+ level))) (aref subs level))
20130 (loop for i from (1+ level) to n do (aset subs i nil)))
20131 (setq last-level level)))))
20132 (aref subs 1)))
20134 (eval-after-load "imenu"
20135 '(progn
20136 (add-hook 'imenu-after-jump-hook
20137 (lambda ()
20138 (if (org-mode-p)
20139 (org-show-context 'org-goto))))))
20141 (defun org-link-display-format (link)
20142 "Replace a link with either the description, or the link target
20143 if no description is present"
20144 (save-match-data
20145 (if (string-match org-bracket-link-analytic-regexp link)
20146 (replace-match (if (match-end 5)
20147 (match-string 5 link)
20148 (concat (match-string 1 link)
20149 (match-string 3 link)))
20150 nil t link)
20151 link)))
20153 ;; Speedbar support
20155 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
20156 "Overlay marking the agenda restriction line in speedbar.")
20157 (overlay-put org-speedbar-restriction-lock-overlay
20158 'face 'org-agenda-restriction-lock)
20159 (overlay-put org-speedbar-restriction-lock-overlay
20160 'help-echo "Agendas are currently limited to this item.")
20161 (org-detach-overlay org-speedbar-restriction-lock-overlay)
20163 (defun org-speedbar-set-agenda-restriction ()
20164 "Restrict future agenda commands to the location at point in speedbar.
20165 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
20166 (interactive)
20167 (require 'org-agenda)
20168 (let (p m tp np dir txt)
20169 (cond
20170 ((setq p (text-property-any (point-at-bol) (point-at-eol)
20171 'org-imenu t))
20172 (setq m (get-text-property p 'org-imenu-marker))
20173 (with-current-buffer (marker-buffer m)
20174 (goto-char m)
20175 (org-agenda-set-restriction-lock 'subtree)))
20176 ((setq p (text-property-any (point-at-bol) (point-at-eol)
20177 'speedbar-function 'speedbar-find-file))
20178 (setq tp (previous-single-property-change
20179 (1+ p) 'speedbar-function)
20180 np (next-single-property-change
20181 tp 'speedbar-function)
20182 dir (speedbar-line-directory)
20183 txt (buffer-substring-no-properties (or tp (point-min))
20184 (or np (point-max))))
20185 (with-current-buffer (find-file-noselect
20186 (let ((default-directory dir))
20187 (expand-file-name txt)))
20188 (unless (org-mode-p)
20189 (error "Cannot restrict to non-Org-mode file"))
20190 (org-agenda-set-restriction-lock 'file)))
20191 (t (error "Don't know how to restrict Org-mode's agenda")))
20192 (move-overlay org-speedbar-restriction-lock-overlay
20193 (point-at-bol) (point-at-eol))
20194 (setq current-prefix-arg nil)
20195 (org-agenda-maybe-redo)))
20197 (eval-after-load "speedbar"
20198 '(progn
20199 (speedbar-add-supported-extension ".org")
20200 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
20201 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
20202 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
20203 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
20204 (add-hook 'speedbar-visiting-tag-hook
20205 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
20207 ;;; Fixes and Hacks for problems with other packages
20209 ;; Make flyspell not check words in links, to not mess up our keymap
20210 (defun org-mode-flyspell-verify ()
20211 "Don't let flyspell put overlays at active buttons."
20212 (and (not (get-text-property (max (1- (point)) (point-min)) 'keymap))
20213 (not (get-text-property (max (1- (point)) (point-min)) 'org-no-flyspell))))
20215 (defun org-remove-flyspell-overlays-in (beg end)
20216 "Remove flyspell overlays in region."
20217 (and (org-bound-and-true-p flyspell-mode)
20218 (fboundp 'flyspell-delete-region-overlays)
20219 (flyspell-delete-region-overlays beg end))
20220 (add-text-properties beg end '(org-no-flyspell t)))
20222 ;; Make `bookmark-jump' shows the jump location if it was hidden.
20223 (eval-after-load "bookmark"
20224 '(if (boundp 'bookmark-after-jump-hook)
20225 ;; We can use the hook
20226 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
20227 ;; Hook not available, use advice
20228 (defadvice bookmark-jump (after org-make-visible activate)
20229 "Make the position visible."
20230 (org-bookmark-jump-unhide))))
20232 ;; Make sure saveplace shows the location if it was hidden
20233 (eval-after-load "saveplace"
20234 '(defadvice save-place-find-file-hook (after org-make-visible activate)
20235 "Make the position visible."
20236 (org-bookmark-jump-unhide)))
20238 ;; Make sure ecb shows the location if it was hidden
20239 (eval-after-load "ecb"
20240 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
20241 "Make hierarchy visible when jumping into location from ECB tree buffer."
20242 (if (org-mode-p)
20243 (org-show-context))))
20245 (defun org-bookmark-jump-unhide ()
20246 "Unhide the current position, to show the bookmark location."
20247 (and (org-mode-p)
20248 (or (outline-invisible-p)
20249 (save-excursion (goto-char (max (point-min) (1- (point))))
20250 (outline-invisible-p)))
20251 (org-show-context 'bookmark-jump)))
20253 ;; Make session.el ignore our circular variable
20254 (eval-after-load "session"
20255 '(add-to-list 'session-globals-exclude 'org-mark-ring))
20257 ;;;; Experimental code
20259 (defun org-closed-in-range ()
20260 "Sparse tree of items closed in a certain time range.
20261 Still experimental, may disappear in the future."
20262 (interactive)
20263 ;; Get the time interval from the user.
20264 (let* ((time1 (org-float-time
20265 (org-read-date nil 'to-time nil "Starting date: ")))
20266 (time2 (org-float-time
20267 (org-read-date nil 'to-time nil "End date:")))
20268 ;; callback function
20269 (callback (lambda ()
20270 (let ((time
20271 (org-float-time
20272 (apply 'encode-time
20273 (org-parse-time-string
20274 (match-string 1))))))
20275 ;; check if time in interval
20276 (and (>= time time1) (<= time time2))))))
20277 ;; make tree, check each match with the callback
20278 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
20280 ;;;; Finish up
20282 (provide 'org)
20284 (run-hooks 'org-load-hook)
20286 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
20288 ;;; org.el ends here