Minor docstring fix.
[org-mode.git] / lisp / org.el
bloba572b945a4b5e37c4a4e6369b5f34415e08c9104
1 ;;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004-2011 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Maintainer: Bastien Guerry <bzg at gnu dot org>
7 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; Homepage: http://orgmode.org
9 ;; Version: 7.7
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" ())
109 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
110 (declare-function org-at-clock-log-p "org-clock" ())
111 (declare-function org-clock-timestamps-up "org-clock" ())
112 (declare-function org-clock-timestamps-down "org-clock" ())
114 ;; babel
115 (require 'ob)
116 (require 'ob-table)
117 (require 'ob-lob)
118 (require 'ob-ref)
119 (require 'ob-tangle)
120 (require 'ob-comint)
121 (require 'ob-keys)
123 ;; load languages based on value of `org-babel-load-languages'
124 (defvar org-babel-load-languages)
125 ;;;###autoload
126 (defun org-babel-do-load-languages (sym value)
127 "Load the languages defined in `org-babel-load-languages'."
128 (set-default sym value)
129 (mapc (lambda (pair)
130 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
131 (if active
132 (progn
133 (require (intern (concat "ob-" lang))))
134 (progn
135 (funcall 'fmakunbound
136 (intern (concat "org-babel-execute:" lang)))
137 (funcall 'fmakunbound
138 (intern (concat "org-babel-expand-body:" lang)))))))
139 org-babel-load-languages))
141 (defcustom org-babel-load-languages '((emacs-lisp . t))
142 "Languages which can be evaluated in Org-mode buffers.
143 This list can be used to load support for any of the languages
144 below, note that each language will depend on a different set of
145 system executables and/or Emacs modes. When a language is
146 \"loaded\", then code blocks in that language can be evaluated
147 with `org-babel-execute-src-block' bound by default to C-c
148 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
149 be set to remove code block evaluation from the C-c C-c
150 keybinding. By default only Emacs Lisp (which has no
151 requirements) is loaded."
152 :group 'org-babel
153 :set 'org-babel-do-load-languages
154 :type '(alist :tag "Babel Languages"
155 :key-type
156 (choice
157 (const :tag "Awk" awk)
158 (const :tag "C" C)
159 (const :tag "R" R)
160 (const :tag "Asymptote" asymptote)
161 (const :tag "Calc" calc)
162 (const :tag "Clojure" clojure)
163 (const :tag "CSS" css)
164 (const :tag "Ditaa" ditaa)
165 (const :tag "Dot" dot)
166 (const :tag "Emacs Lisp" emacs-lisp)
167 (const :tag "Gnuplot" gnuplot)
168 (const :tag "Haskell" haskell)
169 (const :tag "Java" java)
170 (const :tag "Javascript" js)
171 (const :tag "Latex" latex)
172 (const :tag "Ledger" ledger)
173 (const :tag "Lilypond" lilypond)
174 (const :tag "Maxima" maxima)
175 (const :tag "Matlab" matlab)
176 (const :tag "Mscgen" mscgen)
177 (const :tag "Ocaml" ocaml)
178 (const :tag "Octave" octave)
179 (const :tag "Org" org)
180 (const :tag "Perl" perl)
181 (const :tag "PlantUML" plantuml)
182 (const :tag "Python" python)
183 (const :tag "Ruby" ruby)
184 (const :tag "Sass" sass)
185 (const :tag "Scheme" scheme)
186 (const :tag "Screen" screen)
187 (const :tag "Shell Script" sh)
188 (const :tag "Shen" shen)
189 (const :tag "Sql" sql)
190 (const :tag "Sqlite" sqlite))
191 :value-type (boolean :tag "Activate" :value t)))
193 ;;;; Customization variables
194 (defcustom org-clone-delete-id nil
195 "Remove ID property of clones of a subtree.
196 When non-nil, clones of a subtree don't inherit the ID property.
197 Otherwise they inherit the ID property with a new unique
198 identifier."
199 :type 'boolean
200 :group 'org-id)
202 ;;; Version
204 (defconst org-version "7.7"
205 "The version number of the file org.el.")
207 (defun org-version (&optional here)
208 "Show the org-mode version in the echo area.
209 With prefix arg HERE, insert it at point."
210 (interactive "P")
211 (let* ((origin default-directory)
212 (version org-version)
213 (git-version)
214 (dir (concat (file-name-directory (locate-library "org")) "../" )))
215 (when (and (file-exists-p (expand-file-name ".git" dir))
216 (executable-find "git"))
217 (unwind-protect
218 (progn
219 (cd dir)
220 (when (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
221 (with-current-buffer "*Shell Command Output*"
222 (goto-char (point-min))
223 (setq git-version (buffer-substring (point) (point-at-eol))))
224 (subst-char-in-string ?- ?. git-version t)
225 (when (string-match "\\S-"
226 (shell-command-to-string
227 "git diff-index --name-only HEAD --"))
228 (setq git-version (concat git-version ".dirty")))
229 (setq version (concat version " (" git-version ")"))))
230 (cd origin)))
231 (setq version (format "Org-mode version %s" version))
232 (if here (insert version))
233 (message version)))
235 ;;; Compatibility constants
237 ;;; The custom variables
239 (defgroup org nil
240 "Outline-based notes management and organizer."
241 :tag "Org"
242 :group 'outlines
243 :group 'calendar)
245 (defcustom org-mode-hook nil
246 "Mode hook for Org-mode, run after the mode was turned on."
247 :group 'org
248 :type 'hook)
250 (defcustom org-load-hook nil
251 "Hook that is run after org.el has been loaded."
252 :group 'org
253 :type 'hook)
255 (defcustom org-log-buffer-setup-hook nil
256 "Hook that is run after an Org log buffer is created."
257 :group 'org
258 :type 'hook)
260 (defvar org-modules) ; defined below
261 (defvar org-modules-loaded nil
262 "Have the modules been loaded already?")
264 (defun org-load-modules-maybe (&optional force)
265 "Load all extensions listed in `org-modules'."
266 (when (or force (not org-modules-loaded))
267 (mapc (lambda (ext)
268 (condition-case nil (require ext)
269 (error (message "Problems while trying to load feature `%s'" ext))))
270 org-modules)
271 (setq org-modules-loaded t)))
273 (defun org-set-modules (var value)
274 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
275 (set var value)
276 (when (featurep 'org)
277 (org-load-modules-maybe 'force)))
279 (when (org-bound-and-true-p org-modules)
280 (let ((a (member 'org-infojs org-modules)))
281 (and a (setcar a 'org-jsinfo))))
283 (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)
284 "Modules that should always be loaded together with org.el.
285 If a description starts with <C>, the file is not part of Emacs
286 and loading it will require that you have downloaded and properly installed
287 the org-mode distribution.
289 You can also use this system to load external packages (i.e. neither Org
290 core modules, nor modules from the CONTRIB directory). Just add symbols
291 to the end of the list. If the package is called org-xyz.el, then you need
292 to add the symbol `xyz', and the package must have a call to
294 (provide 'org-xyz)"
295 :group 'org
296 :set 'org-set-modules
297 :type
298 '(set :greedy t
299 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
300 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
301 (const :tag " crypt: Encryption of subtrees" org-crypt)
302 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
303 (const :tag " docview: Links to doc-view buffers" org-docview)
304 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
305 (const :tag " id: Global IDs for identifying entries" org-id)
306 (const :tag " info: Links to Info nodes" org-info)
307 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
308 (const :tag " habit: Track your consistency with habits" org-habit)
309 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
310 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
311 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
312 (const :tag " mew Links to Mew folders/messages" org-mew)
313 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
314 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
315 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
316 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
317 (const :tag " vm: Links to VM folders/messages" org-vm)
318 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
319 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
320 (const :tag " mouse: Additional mouse support" org-mouse)
321 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
323 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
324 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
325 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
326 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
327 (const :tag "C collector: Collect properties into tables" org-collector)
328 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
329 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
330 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
331 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
332 (const :tag "C eval: Include command output as text" org-eval)
333 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
334 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
335 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
336 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
337 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
339 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
341 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
342 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
343 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
344 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
345 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
346 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
347 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
348 (const :tag "C mtags: Support for muse-like tags" org-mtags)
349 (const :tag "C odt: OpenDocumentText exporter for Org-mode" org-odt)
350 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
351 (const :tag "C registry: A registry for Org-mode links" org-registry)
352 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
353 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
354 (const :tag "C secretary: Team management with org-mode" org-secretary)
355 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
356 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
357 (const :tag "C track: Keep up with Org-mode development" org-track)
358 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
359 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
360 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
362 (defcustom org-support-shift-select nil
363 "Non-nil means make shift-cursor commands select text when possible.
365 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
366 start selecting a region, or enlarge regions started in this way.
367 In Org-mode, in special contexts, these same keys are used for
368 other purposes, important enough to compete with shift selection.
369 Org tries to balance these needs by supporting `shift-select-mode'
370 outside these special contexts, under control of this variable.
372 The default of this variable is nil, to avoid confusing behavior. Shifted
373 cursor keys will then execute Org commands in the following contexts:
374 - on a headline, changing TODO state (left/right) and priority (up/down)
375 - on a time stamp, changing the time
376 - in a plain list item, changing the bullet type
377 - in a property definition line, switching between allowed values
378 - in the BEGIN line of a clock table (changing the time block).
379 Outside these contexts, the commands will throw an error.
381 When this variable is t and the cursor is not in a special
382 context, Org-mode will support shift-selection for making and
383 enlarging regions. To make this more effective, the bullet
384 cycling will no longer happen anywhere in an item line, but only
385 if the cursor is exactly on the bullet.
387 If you set this variable to the symbol `always', then the keys
388 will not be special in headlines, property lines, and item lines,
389 to make shift selection work there as well. If this is what you
390 want, you can use the following alternative commands: `C-c C-t'
391 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
392 can be used to switch TODO sets, `C-c -' to cycle item bullet
393 types, and properties can be edited by hand or in column view.
395 However, when the cursor is on a timestamp, shift-cursor commands
396 will still edit the time stamp - this is just too good to give up.
398 XEmacs user should have this variable set to nil, because
399 `shift-select-mode' is in Emacs 23 or later only."
400 :group 'org
401 :type '(choice
402 (const :tag "Never" nil)
403 (const :tag "When outside special context" t)
404 (const :tag "Everywhere except timestamps" always)))
406 (defcustom org-loop-over-headlines-in-active-region nil
407 "Shall some commands act upon headlines in the active region?
409 When set to `t', some commands will be performed in all headlines
410 within the active region.
412 When set to a string, those commands will be performed on the
413 matching headlines within the active region. Such string must be
414 a tags/property/todo match as it is used in the agenda tags view.
416 The list of commands is:
417 - `org-schedule'
418 - `org-deadline'"
419 :type '(choice (const :tag "Don't loop" nil)
420 (const :tag "All headlines in active region" t)
421 (string :tag "Tags/Property/Todo matcher"))
422 :group 'org-todo
423 :group 'org-archive)
425 (defgroup org-startup nil
426 "Options concerning startup of Org-mode."
427 :tag "Org Startup"
428 :group 'org)
430 (defcustom org-startup-folded t
431 "Non-nil means entering Org-mode will switch to OVERVIEW.
432 This can also be configured on a per-file basis by adding one of
433 the following lines anywhere in the buffer:
435 #+STARTUP: fold (or `overview', this is equivalent)
436 #+STARTUP: nofold (or `showall', this is equivalent)
437 #+STARTUP: content
438 #+STARTUP: showeverything"
439 :group 'org-startup
440 :type '(choice
441 (const :tag "nofold: show all" nil)
442 (const :tag "fold: overview" t)
443 (const :tag "content: all headlines" content)
444 (const :tag "show everything, even drawers" showeverything)))
446 (defcustom org-startup-truncated t
447 "Non-nil means entering Org-mode will set `truncate-lines'.
448 This is useful since some lines containing links can be very long and
449 uninteresting. Also tables look terrible when wrapped."
450 :group 'org-startup
451 :type 'boolean)
453 (defcustom org-startup-indented nil
454 "Non-nil means turn on `org-indent-mode' on startup.
455 This can also be configured on a per-file basis by adding one of
456 the following lines anywhere in the buffer:
458 #+STARTUP: indent
459 #+STARTUP: noindent"
460 :group 'org-structure
461 :type '(choice
462 (const :tag "Not" nil)
463 (const :tag "Globally (slow on startup in large files)" t)))
465 (defcustom org-use-sub-superscripts t
466 "Non-nil means interpret \"_\" and \"^\" for export.
467 When this option is turned on, you can use TeX-like syntax for sub- and
468 superscripts. Several characters after \"_\" or \"^\" will be
469 considered as a single item - so grouping with {} is normally not
470 needed. For example, the following things will be parsed as single
471 sub- or superscripts.
473 10^24 or 10^tau several digits will be considered 1 item.
474 10^-12 or 10^-tau a leading sign with digits or a word
475 x^2-y^3 will be read as x^2 - y^3, because items are
476 terminated by almost any nonword/nondigit char.
477 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
479 Still, ambiguity is possible - so when in doubt use {} to enclose the
480 sub/superscript. If you set this variable to the symbol `{}',
481 the braces are *required* in order to trigger interpretations as
482 sub/superscript. This can be helpful in documents that need \"_\"
483 frequently in plain text.
485 Not all export backends support this, but HTML does.
487 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
488 :group 'org-startup
489 :group 'org-export-translation
490 :type '(choice
491 (const :tag "Always interpret" t)
492 (const :tag "Only with braces" {})
493 (const :tag "Never interpret" nil)))
495 (if (fboundp 'defvaralias)
496 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
499 (defcustom org-startup-with-beamer-mode nil
500 "Non-nil means turn on `org-beamer-mode' on startup.
501 This can also be configured on a per-file basis by adding one of
502 the following lines anywhere in the buffer:
504 #+STARTUP: beamer"
505 :group 'org-startup
506 :type 'boolean)
508 (defcustom org-startup-align-all-tables nil
509 "Non-nil means align all tables when visiting a file.
510 This is useful when the column width in tables is forced with <N> cookies
511 in table fields. Such tables will look correct only after the first re-align.
512 This can also be configured on a per-file basis by adding one of
513 the following lines anywhere in the buffer:
514 #+STARTUP: align
515 #+STARTUP: noalign"
516 :group 'org-startup
517 :type 'boolean)
519 (defcustom org-startup-with-inline-images nil
520 "Non-nil means show inline images when loading a new Org file.
521 This can also be configured on a per-file basis by adding one of
522 the following lines anywhere in the buffer:
523 #+STARTUP: inlineimages
524 #+STARTUP: noinlineimages"
525 :group 'org-startup
526 :type 'boolean)
528 (defcustom org-insert-mode-line-in-empty-file nil
529 "Non-nil means insert the first line setting Org-mode in empty files.
530 When the function `org-mode' is called interactively in an empty file, this
531 normally means that the file name does not automatically trigger Org-mode.
532 To ensure that the file will always be in Org-mode in the future, a
533 line enforcing Org-mode will be inserted into the buffer, if this option
534 has been set."
535 :group 'org-startup
536 :type 'boolean)
538 (defcustom org-replace-disputed-keys nil
539 "Non-nil means use alternative key bindings for some keys.
540 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
541 These keys are also used by other packages like shift-selection-mode'
542 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
543 If you want to use Org-mode together with one of these other modes,
544 or more generally if you would like to move some Org-mode commands to
545 other keys, set this variable and configure the keys with the variable
546 `org-disputed-keys'.
548 This option is only relevant at load-time of Org-mode, and must be set
549 *before* org.el is loaded. Changing it requires a restart of Emacs to
550 become effective."
551 :group 'org-startup
552 :type 'boolean)
554 (defcustom org-use-extra-keys nil
555 "Non-nil means use extra key sequence definitions for certain commands.
556 This happens automatically if you run XEmacs or if `window-system'
557 is nil. This variable lets you do the same manually. You must
558 set it before loading org.
560 Example: on Carbon Emacs 22 running graphically, with an external
561 keyboard on a Powerbook, the default way of setting M-left might
562 not work for either Alt or ESC. Setting this variable will make
563 it work for ESC."
564 :group 'org-startup
565 :type 'boolean)
567 (if (fboundp 'defvaralias)
568 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
570 (defcustom org-disputed-keys
571 '(([(shift up)] . [(meta p)])
572 ([(shift down)] . [(meta n)])
573 ([(shift left)] . [(meta -)])
574 ([(shift right)] . [(meta +)])
575 ([(control shift right)] . [(meta shift +)])
576 ([(control shift left)] . [(meta shift -)]))
577 "Keys for which Org-mode and other modes compete.
578 This is an alist, cars are the default keys, second element specifies
579 the alternative to use when `org-replace-disputed-keys' is t.
581 Keys can be specified in any syntax supported by `define-key'.
582 The value of this option takes effect only at Org-mode's startup,
583 therefore you'll have to restart Emacs to apply it after changing."
584 :group 'org-startup
585 :type 'alist)
587 (defun org-key (key)
588 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
589 Or return the original if not disputed.
590 Also apply the translations defined in `org-xemacs-key-equivalents'."
591 (when org-replace-disputed-keys
592 (let* ((nkey (key-description key))
593 (x (org-find-if (lambda (x)
594 (equal (key-description (car x)) nkey))
595 org-disputed-keys)))
596 (setq key (if x (cdr x) key))))
597 (when (featurep 'xemacs)
598 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
599 key)
601 (defun org-find-if (predicate seq)
602 (catch 'exit
603 (while seq
604 (if (funcall predicate (car seq))
605 (throw 'exit (car seq))
606 (pop seq)))))
608 (defun org-defkey (keymap key def)
609 "Define a key, possibly translated, as returned by `org-key'."
610 (define-key keymap (org-key key) def))
612 (defcustom org-ellipsis nil
613 "The ellipsis to use in the Org-mode outline.
614 When nil, just use the standard three dots. When a string, use that instead,
615 When a face, use the standard 3 dots, but with the specified face.
616 The change affects only Org-mode (which will then use its own display table).
617 Changing this requires executing `M-x org-mode' in a buffer to become
618 effective."
619 :group 'org-startup
620 :type '(choice (const :tag "Default" nil)
621 (face :tag "Face" :value org-warning)
622 (string :tag "String" :value "...#")))
624 (defvar org-display-table nil
625 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
627 (defgroup org-keywords nil
628 "Keywords in Org-mode."
629 :tag "Org Keywords"
630 :group 'org)
632 (defcustom org-deadline-string "DEADLINE:"
633 "String to mark deadline entries.
634 A deadline is this string, followed by a time stamp. Should be a word,
635 terminated by a colon. You can insert a schedule keyword and
636 a timestamp with \\[org-deadline].
637 Changes become only effective after restarting Emacs."
638 :group 'org-keywords
639 :type 'string)
641 (defcustom org-scheduled-string "SCHEDULED:"
642 "String to mark scheduled TODO entries.
643 A schedule is this string, followed by a time stamp. Should be a word,
644 terminated by a colon. You can insert a schedule keyword and
645 a timestamp with \\[org-schedule].
646 Changes become only effective after restarting Emacs."
647 :group 'org-keywords
648 :type 'string)
650 (defcustom org-closed-string "CLOSED:"
651 "String used as the prefix for timestamps logging closing a TODO entry."
652 :group 'org-keywords
653 :type 'string)
655 (defcustom org-clock-string "CLOCK:"
656 "String used as prefix for timestamps clocking work hours on an item."
657 :group 'org-keywords
658 :type 'string)
660 (defcustom org-comment-string "COMMENT"
661 "Entries starting with this keyword will never be exported.
662 An entry can be toggled between COMMENT and normal with
663 \\[org-toggle-comment].
664 Changes become only effective after restarting Emacs."
665 :group 'org-keywords
666 :type 'string)
668 (defcustom org-quote-string "QUOTE"
669 "Entries starting with this keyword will be exported in fixed-width font.
670 Quoting applies only to the text in the entry following the headline, and does
671 not extend beyond the next headline, even if that is lower level.
672 An entry can be toggled between QUOTE and normal with
673 \\[org-toggle-fixed-width-section]."
674 :group 'org-keywords
675 :type 'string)
677 (defconst org-repeat-re
678 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
679 "Regular expression for specifying repeated events.
680 After a match, group 1 contains the repeat expression.")
682 (defgroup org-structure nil
683 "Options concerning the general structure of Org-mode files."
684 :tag "Org Structure"
685 :group 'org)
687 (defgroup org-reveal-location nil
688 "Options about how to make context of a location visible."
689 :tag "Org Reveal Location"
690 :group 'org-structure)
692 (defconst org-context-choice
693 '(choice
694 (const :tag "Always" t)
695 (const :tag "Never" nil)
696 (repeat :greedy t :tag "Individual contexts"
697 (cons
698 (choice :tag "Context"
699 (const agenda)
700 (const org-goto)
701 (const occur-tree)
702 (const tags-tree)
703 (const link-search)
704 (const mark-goto)
705 (const bookmark-jump)
706 (const isearch)
707 (const default))
708 (boolean))))
709 "Contexts for the reveal options.")
711 (defcustom org-show-hierarchy-above '((default . t))
712 "Non-nil means show full hierarchy 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 hierarchy of headings
715 above the exposed location is shown.
716 Turning this off for example for sparse trees makes them very compact.
717 Instead of t, this can also be an alist specifying this option for different
718 contexts. Valid contexts are
719 agenda when exposing an entry from the agenda
720 org-goto when using the command `org-goto' on key C-c C-j
721 occur-tree when using the command `org-occur' on key C-c /
722 tags-tree when constructing a sparse tree based on tags matches
723 link-search when exposing search matches associated with a link
724 mark-goto when exposing the jump goal of a mark
725 bookmark-jump when exposing a bookmark location
726 isearch when exiting from an incremental search
727 default default for all contexts not set explicitly"
728 :group 'org-reveal-location
729 :type org-context-choice)
731 (defcustom org-show-following-heading '((default . nil))
732 "Non-nil means show following heading when revealing a location.
733 Org-mode often shows locations in an org-mode file which might have
734 been invisible before. When this is set, the heading following the
735 match is shown.
736 Turning this off for example for sparse trees makes them very compact,
737 but makes it harder to edit the location of the match. In such a case,
738 use the command \\[org-reveal] to show more context.
739 Instead of t, this can also be an alist specifying this option for different
740 contexts. See `org-show-hierarchy-above' for valid contexts."
741 :group 'org-reveal-location
742 :type org-context-choice)
744 (defcustom org-show-siblings '((default . nil) (isearch t))
745 "Non-nil means show all sibling heading when revealing a location.
746 Org-mode often shows locations in an org-mode file which might have
747 been invisible before. When this is set, the sibling of the current entry
748 heading are all made visible. If `org-show-hierarchy-above' is t,
749 the same happens on each level of the hierarchy above the current entry.
751 By default this is on for the isearch context, off for all other contexts.
752 Turning this off for example for sparse trees makes them very compact,
753 but makes it harder to edit the location of the match. In such a case,
754 use the command \\[org-reveal] to show more context.
755 Instead of t, this can also be an alist specifying this option for different
756 contexts. See `org-show-hierarchy-above' for valid contexts."
757 :group 'org-reveal-location
758 :type org-context-choice)
760 (defcustom org-show-entry-below '((default . nil))
761 "Non-nil means show the entry below a headline when revealing a location.
762 Org-mode often shows locations in an org-mode file which might have
763 been invisible before. When this is set, the text below the headline that is
764 exposed is also shown.
766 By default this is off for all contexts.
767 Instead of t, this can also be an alist specifying this option for different
768 contexts. See `org-show-hierarchy-above' for valid contexts."
769 :group 'org-reveal-location
770 :type org-context-choice)
772 (defcustom org-indirect-buffer-display 'other-window
773 "How should indirect tree buffers be displayed?
774 This applies to indirect buffers created with the commands
775 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
776 Valid values are:
777 current-window Display in the current window
778 other-window Just display in another window.
779 dedicated-frame Create one new frame, and re-use it each time.
780 new-frame Make a new frame each time. Note that in this case
781 previously-made indirect buffers are kept, and you need to
782 kill these buffers yourself."
783 :group 'org-structure
784 :group 'org-agenda-windows
785 :type '(choice
786 (const :tag "In current window" current-window)
787 (const :tag "In current frame, other window" other-window)
788 (const :tag "Each time a new frame" new-frame)
789 (const :tag "One dedicated frame" dedicated-frame)))
791 (defcustom org-use-speed-commands nil
792 "Non-nil means activate single letter commands at beginning of a headline.
793 This may also be a function to test for appropriate locations where speed
794 commands should be active."
795 :group 'org-structure
796 :type '(choice
797 (const :tag "Never" nil)
798 (const :tag "At beginning of headline stars" t)
799 (function)))
801 (defcustom org-speed-commands-user nil
802 "Alist of additional speed commands.
803 This list will be checked before `org-speed-commands-default'
804 when the variable `org-use-speed-commands' is non-nil
805 and when the cursor is at the beginning of a headline.
806 The car if each entry is a string with a single letter, which must
807 be assigned to `self-insert-command' in the global map.
808 The cdr is either a command to be called interactively, a function
809 to be called, or a form to be evaluated.
810 An entry that is just a list with a single string will be interpreted
811 as a descriptive headline that will be added when listing the speed
812 commands in the Help buffer using the `?' speed command."
813 :group 'org-structure
814 :type '(repeat :value ("k" . ignore)
815 (choice :value ("k" . ignore)
816 (list :tag "Descriptive Headline" (string :tag "Headline"))
817 (cons :tag "Letter and Command"
818 (string :tag "Command letter")
819 (choice
820 (function)
821 (sexp))))))
823 (defgroup org-cycle nil
824 "Options concerning visibility cycling in Org-mode."
825 :tag "Org Cycle"
826 :group 'org-structure)
828 (defcustom org-cycle-skip-children-state-if-no-children t
829 "Non-nil means skip CHILDREN state in entries that don't have any."
830 :group 'org-cycle
831 :type 'boolean)
833 (defcustom org-cycle-max-level nil
834 "Maximum level which should still be subject to visibility cycling.
835 Levels higher than this will, for cycling, be treated as text, not a headline.
836 When `org-odd-levels-only' is set, a value of N in this variable actually
837 means 2N-1 stars as the limiting headline.
838 When nil, cycle all levels.
839 Note that the limiting level of cycling is also influenced by
840 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
841 `org-inlinetask-min-level' is, cycling will be limited to levels one less
842 than its value."
843 :group 'org-cycle
844 :type '(choice
845 (const :tag "No limit" nil)
846 (integer :tag "Maximum level")))
848 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
849 "Names of drawers. Drawers are not opened by cycling on the headline above.
850 Drawers only open with a TAB on the drawer line itself. A drawer looks like
851 this:
852 :DRAWERNAME:
853 .....
854 :END:
855 The drawer \"PROPERTIES\" is special for capturing properties through
856 the property API.
858 Drawers can be defined on the per-file basis with a line like:
860 #+DRAWERS: HIDDEN STATE PROPERTIES"
861 :group 'org-structure
862 :group 'org-cycle
863 :type '(repeat (string :tag "Drawer Name")))
865 (defcustom org-hide-block-startup nil
866 "Non-nil means entering Org-mode will fold all blocks.
867 This can also be set in on a per-file basis with
869 #+STARTUP: hideblocks
870 #+STARTUP: showblocks"
871 :group 'org-startup
872 :group 'org-cycle
873 :type 'boolean)
875 (defcustom org-cycle-global-at-bob nil
876 "Cycle globally if cursor is at beginning of buffer and not at a headline.
877 This makes it possible to do global cycling without having to use S-TAB or
878 \\[universal-argument] TAB. For this special case to work, the first line \
879 of the buffer
880 must not be a headline - it may be empty or some other text. When used in
881 this way, `org-cycle-hook' is disables temporarily, to make sure the
882 cursor stays at the beginning of the buffer.
883 When this option is nil, don't do anything special at the beginning
884 of the buffer."
885 :group 'org-cycle
886 :type 'boolean)
888 (defcustom org-cycle-level-after-item/entry-creation t
889 "Non-nil means cycle entry level or item indentation in new empty entries.
891 When the cursor is at the end of an empty headline, i.e with only stars
892 and maybe a TODO keyword, TAB will then switch the entry to become a child,
893 and then all possible ancestor states, before returning to the original state.
894 This makes data entry extremely fast: M-RET to create a new headline,
895 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
897 When the cursor is at the end of an empty plain list item, one TAB will
898 make it a subitem, two or more tabs will back up to make this an item
899 higher up in the item hierarchy."
900 :group 'org-cycle
901 :type 'boolean)
903 (defcustom org-cycle-emulate-tab t
904 "Where should `org-cycle' emulate TAB.
905 nil Never
906 white Only in completely white lines
907 whitestart Only at the beginning of lines, before the first non-white char
908 t Everywhere except in headlines
909 exc-hl-bol Everywhere except at the start of a headline
910 If TAB is used in a place where it does not emulate TAB, the current subtree
911 visibility is cycled."
912 :group 'org-cycle
913 :type '(choice (const :tag "Never" nil)
914 (const :tag "Only in completely white lines" white)
915 (const :tag "Before first char in a line" whitestart)
916 (const :tag "Everywhere except in headlines" t)
917 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
920 (defcustom org-cycle-separator-lines 2
921 "Number of empty lines needed to keep an empty line between collapsed trees.
922 If you leave an empty line between the end of a subtree and the following
923 headline, this empty line is hidden when the subtree is folded.
924 Org-mode will leave (exactly) one empty line visible if the number of
925 empty lines is equal or larger to the number given in this variable.
926 So the default 2 means at least 2 empty lines after the end of a subtree
927 are needed to produce free space between a collapsed subtree and the
928 following headline.
930 If the number is negative, and the number of empty lines is at least -N,
931 all empty lines are shown.
933 Special case: when 0, never leave empty lines in collapsed view."
934 :group 'org-cycle
935 :type 'integer)
936 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
938 (defcustom org-pre-cycle-hook nil
939 "Hook that is run before visibility cycling is happening.
940 The function(s) in this hook must accept a single argument which indicates
941 the new state that will be set right after running this hook. The
942 argument is a symbol. Before a global state change, it can have the values
943 `overview', `content', or `all'. Before a local state change, it can have
944 the values `folded', `children', or `subtree'."
945 :group 'org-cycle
946 :type 'hook)
948 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
949 org-cycle-hide-drawers
950 org-cycle-show-empty-lines
951 org-optimize-window-after-visibility-change)
952 "Hook that is run after `org-cycle' has changed the buffer visibility.
953 The function(s) in this hook must accept a single argument which indicates
954 the new state that was set by the most recent `org-cycle' command. The
955 argument is a symbol. After a global state change, it can have the values
956 `overview', `content', or `all'. After a local state change, it can have
957 the values `folded', `children', or `subtree'."
958 :group 'org-cycle
959 :type 'hook)
961 (defgroup org-edit-structure nil
962 "Options concerning structure editing in Org-mode."
963 :tag "Org Edit Structure"
964 :group 'org-structure)
966 (defcustom org-odd-levels-only nil
967 "Non-nil means skip even levels and only use odd levels for the outline.
968 This has the effect that two stars are being added/taken away in
969 promotion/demotion commands. It also influences how levels are
970 handled by the exporters.
971 Changing it requires restart of `font-lock-mode' to become effective
972 for fontification also in regions already fontified.
973 You may also set this on a per-file basis by adding one of the following
974 lines to the buffer:
976 #+STARTUP: odd
977 #+STARTUP: oddeven"
978 :group 'org-edit-structure
979 :group 'org-appearance
980 :type 'boolean)
982 (defcustom org-adapt-indentation t
983 "Non-nil means adapt indentation to outline node level.
985 When this variable is set, Org assumes that you write outlines by
986 indenting text in each node to align with the headline (after the stars).
987 The following issues are influenced by this variable:
989 - When this is set and the *entire* text in an entry is indented, the
990 indentation is increased by one space in a demotion command, and
991 decreased by one in a promotion command. If any line in the entry
992 body starts with text at column 0, indentation is not changed at all.
994 - Property drawers and planning information is inserted indented when
995 this variable s set. When nil, they will not be indented.
997 - TAB indents a line relative to context. The lines below a headline
998 will be indented when this variable is set.
1000 Note that this is all about true indentation, by adding and removing
1001 space characters. See also `org-indent.el' which does level-dependent
1002 indentation in a virtual way, i.e. at display time in Emacs."
1003 :group 'org-edit-structure
1004 :type 'boolean)
1006 (defcustom org-special-ctrl-a/e nil
1007 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1009 When t, `C-a' will bring back the cursor to the beginning of the
1010 headline text, i.e. after the stars and after a possible TODO keyword.
1011 In an item, this will be the position after the bullet.
1012 When the cursor is already at that position, another `C-a' will bring
1013 it to the beginning of the line.
1015 `C-e' will jump to the end of the headline, ignoring the presence of tags
1016 in the headline. A second `C-e' will then jump to the true end of the
1017 line, after any tags. This also means that, when this variable is
1018 non-nil, `C-e' also will never jump beyond the end of the heading of a
1019 folded section, i.e. not after the ellipses.
1021 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
1022 going to the true line boundary first. Only a directly following, identical
1023 keypress will bring the cursor to the special positions.
1025 This may also be a cons cell where the behavior for `C-a' and `C-e' is
1026 set separately."
1027 :group 'org-edit-structure
1028 :type '(choice
1029 (const :tag "off" nil)
1030 (const :tag "on: after stars/bullet and before tags first" t)
1031 (const :tag "reversed: true line boundary first" reversed)
1032 (cons :tag "Set C-a and C-e separately"
1033 (choice :tag "Special C-a"
1034 (const :tag "off" nil)
1035 (const :tag "on: after stars/bullet first" t)
1036 (const :tag "reversed: before stars/bullet first" reversed))
1037 (choice :tag "Special C-e"
1038 (const :tag "off" nil)
1039 (const :tag "on: before tags first" t)
1040 (const :tag "reversed: after tags first" reversed)))))
1041 (if (fboundp 'defvaralias)
1042 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1044 (defcustom org-special-ctrl-k nil
1045 "Non-nil means `C-k' will behave specially in headlines.
1046 When nil, `C-k' will call the default `kill-line' command.
1047 When t, the following will happen while the cursor is in the headline:
1049 - When the cursor is at the beginning of a headline, kill the entire
1050 line and possible the folded subtree below the line.
1051 - When in the middle of the headline text, kill the headline up to the tags.
1052 - When after the headline text, kill the tags."
1053 :group 'org-edit-structure
1054 :type 'boolean)
1056 (defcustom org-ctrl-k-protect-subtree nil
1057 "Non-nil means, do not delete a hidden subtree with C-k.
1058 When set to the symbol `error', simply throw an error when C-k is
1059 used to kill (part-of) a headline that has hidden text behind it.
1060 Any other non-nil value will result in a query to the user, if it is
1061 OK to kill that hidden subtree. When nil, kill without remorse."
1062 :group 'org-edit-structure
1063 :type '(choice
1064 (const :tag "Do not protect hidden subtrees" nil)
1065 (const :tag "Protect hidden subtrees with a security query" t)
1066 (const :tag "Never kill a hidden subtree with C-k" error)))
1068 (defcustom org-yank-folded-subtrees t
1069 "Non-nil means when yanking subtrees, fold them.
1070 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1071 it starts with a heading and all other headings in it are either children
1072 or siblings, then fold all the subtrees. However, do this only if no
1073 text after the yank would be swallowed into a folded tree by this action."
1074 :group 'org-edit-structure
1075 :type 'boolean)
1077 (defcustom org-yank-adjusted-subtrees nil
1078 "Non-nil means when yanking subtrees, adjust the level.
1079 With this setting, `org-paste-subtree' is used to insert the subtree, see
1080 this function for details."
1081 :group 'org-edit-structure
1082 :type 'boolean)
1084 (defcustom org-M-RET-may-split-line '((default . t))
1085 "Non-nil means M-RET will split the line at the cursor position.
1086 When nil, it will go to the end of the line before making a
1087 new line.
1088 You may also set this option in a different way for different
1089 contexts. Valid contexts are:
1091 headline when creating a new headline
1092 item when creating a new item
1093 table in a table field
1094 default the value to be used for all contexts not explicitly
1095 customized"
1096 :group 'org-structure
1097 :group 'org-table
1098 :type '(choice
1099 (const :tag "Always" t)
1100 (const :tag "Never" nil)
1101 (repeat :greedy t :tag "Individual contexts"
1102 (cons
1103 (choice :tag "Context"
1104 (const headline)
1105 (const item)
1106 (const table)
1107 (const default))
1108 (boolean)))))
1111 (defcustom org-insert-heading-respect-content nil
1112 "Non-nil means insert new headings after the current subtree.
1113 When nil, the new heading is created directly after the current line.
1114 The commands \\[org-insert-heading-respect-content] and
1115 \\[org-insert-todo-heading-respect-content] turn this variable on
1116 for the duration of the command."
1117 :group 'org-structure
1118 :type 'boolean)
1120 (defcustom org-blank-before-new-entry '((heading . auto)
1121 (plain-list-item . auto))
1122 "Should `org-insert-heading' leave a blank line before new heading/item?
1123 The value is an alist, with `heading' and `plain-list-item' as CAR,
1124 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1125 which case Org will look at the surrounding headings/items and try to
1126 make an intelligent decision whether to insert a blank line or not.
1128 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1129 set, the setting here is ignored and no empty line is inserted, to avoid
1130 breaking the list structure."
1131 :group 'org-edit-structure
1132 :type '(list
1133 (cons (const heading)
1134 (choice (const :tag "Never" nil)
1135 (const :tag "Always" t)
1136 (const :tag "Auto" auto)))
1137 (cons (const plain-list-item)
1138 (choice (const :tag "Never" nil)
1139 (const :tag "Always" t)
1140 (const :tag "Auto" auto)))))
1142 (defcustom org-insert-heading-hook nil
1143 "Hook being run after inserting a new heading."
1144 :group 'org-edit-structure
1145 :type 'hook)
1147 (defcustom org-enable-fixed-width-editor t
1148 "Non-nil means lines starting with \":\" are treated as fixed-width.
1149 This currently only means they are never auto-wrapped.
1150 When nil, such lines will be treated like ordinary lines.
1151 See also the QUOTE keyword."
1152 :group 'org-edit-structure
1153 :type 'boolean)
1155 (defcustom org-goto-auto-isearch t
1156 "Non-nil means typing characters in `org-goto' starts incremental search."
1157 :group 'org-edit-structure
1158 :type 'boolean)
1160 (defgroup org-sparse-trees nil
1161 "Options concerning sparse trees in Org-mode."
1162 :tag "Org Sparse Trees"
1163 :group 'org-structure)
1165 (defcustom org-highlight-sparse-tree-matches t
1166 "Non-nil means highlight all matches that define a sparse tree.
1167 The highlights will automatically disappear the next time the buffer is
1168 changed by an edit command."
1169 :group 'org-sparse-trees
1170 :type 'boolean)
1172 (defcustom org-remove-highlights-with-change t
1173 "Non-nil means any change to the buffer will remove temporary highlights.
1174 Such highlights are created by `org-occur' and `org-clock-display'.
1175 When nil, `C-c C-c needs to be used to get rid of the highlights.
1176 The highlights created by `org-preview-latex-fragment' always need
1177 `C-c C-c' to be removed."
1178 :group 'org-sparse-trees
1179 :group 'org-time
1180 :type 'boolean)
1183 (defcustom org-occur-hook '(org-first-headline-recenter)
1184 "Hook that is run after `org-occur' has constructed a sparse tree.
1185 This can be used to recenter the window to show as much of the structure
1186 as possible."
1187 :group 'org-sparse-trees
1188 :type 'hook)
1190 (defgroup org-imenu-and-speedbar nil
1191 "Options concerning imenu and speedbar in Org-mode."
1192 :tag "Org Imenu and Speedbar"
1193 :group 'org-structure)
1195 (defcustom org-imenu-depth 2
1196 "The maximum level for Imenu access to Org-mode headlines.
1197 This also applied for speedbar access."
1198 :group 'org-imenu-and-speedbar
1199 :type 'integer)
1201 (defgroup org-table nil
1202 "Options concerning tables in Org-mode."
1203 :tag "Org Table"
1204 :group 'org)
1206 (defcustom org-enable-table-editor 'optimized
1207 "Non-nil means lines starting with \"|\" are handled by the table editor.
1208 When nil, such lines will be treated like ordinary lines.
1210 When equal to the symbol `optimized', the table editor will be optimized to
1211 do the following:
1212 - Automatic overwrite mode in front of whitespace in table fields.
1213 This makes the structure of the table stay in tact as long as the edited
1214 field does not exceed the column width.
1215 - Minimize the number of realigns. Normally, the table is aligned each time
1216 TAB or RET are pressed to move to another field. With optimization this
1217 happens only if changes to a field might have changed the column width.
1218 Optimization requires replacing the functions `self-insert-command',
1219 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1220 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1221 very good at guessing when a re-align will be necessary, but you can always
1222 force one with \\[org-ctrl-c-ctrl-c].
1224 If you would like to use the optimized version in Org-mode, but the
1225 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1227 This variable can be used to turn on and off the table editor during a session,
1228 but in order to toggle optimization, a restart is required.
1230 See also the variable `org-table-auto-blank-field'."
1231 :group 'org-table
1232 :type '(choice
1233 (const :tag "off" nil)
1234 (const :tag "on" t)
1235 (const :tag "on, optimized" optimized)))
1237 (defcustom org-self-insert-cluster-for-undo t
1238 "Non-nil means cluster self-insert commands for undo when possible.
1239 If this is set, then, like in the Emacs command loop, 20 consecutive
1240 characters will be undone together.
1241 This is configurable, because there is some impact on typing performance."
1242 :group 'org-table
1243 :type 'boolean)
1245 (defcustom org-table-tab-recognizes-table.el t
1246 "Non-nil means TAB will automatically notice a table.el table.
1247 When it sees such a table, it moves point into it and - if necessary -
1248 calls `table-recognize-table'."
1249 :group 'org-table-editing
1250 :type 'boolean)
1252 (defgroup org-link nil
1253 "Options concerning links in Org-mode."
1254 :tag "Org Link"
1255 :group 'org)
1257 (defvar org-link-abbrev-alist-local nil
1258 "Buffer-local version of `org-link-abbrev-alist', which see.
1259 The value of this is taken from the #+LINK lines.")
1260 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1262 (defcustom org-link-abbrev-alist nil
1263 "Alist of link abbreviations.
1264 The car of each element is a string, to be replaced at the start of a link.
1265 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1266 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1268 [[linkkey:tag][description]]
1270 The 'linkkey' must be a word word, starting with a letter, followed
1271 by letters, numbers, '-' or '_'.
1273 If REPLACE is a string, the tag will simply be appended to create the link.
1274 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1275 the placeholder \"%h\" will cause a url-encoded version of the tag to
1276 be inserted at that point (see the function `url-hexify-string').
1278 REPLACE may also be a function that will be called with the tag as the
1279 only argument to create the link, which should be returned as a string.
1281 See the manual for examples."
1282 :group 'org-link
1283 :type '(repeat
1284 (cons
1285 (string :tag "Protocol")
1286 (choice
1287 (string :tag "Format")
1288 (function)))))
1290 (defcustom org-descriptive-links t
1291 "Non-nil means Org will display descriptive links.
1292 E.g. [[http://orgmode.org][Org website]] will be displayed as
1293 \"Org Website\", hiding the link itself and just displaying its
1294 description. When set to `nil', Org will display the full links
1295 literally.
1297 You can interactively set the value of this variable by calling
1298 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1299 :group 'org-link
1300 :type 'boolean)
1302 (defcustom org-link-file-path-type 'adaptive
1303 "How the path name in file links should be stored.
1304 Valid values are:
1306 relative Relative to the current directory, i.e. the directory of the file
1307 into which the link is being inserted.
1308 absolute Absolute path, if possible with ~ for home directory.
1309 noabbrev Absolute path, no abbreviation of home directory.
1310 adaptive Use relative path for files in the current directory and sub-
1311 directories of it. For other files, use an absolute path."
1312 :group 'org-link
1313 :type '(choice
1314 (const relative)
1315 (const absolute)
1316 (const noabbrev)
1317 (const adaptive)))
1319 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1320 "Types of links that should be activated in Org-mode files.
1321 This is a list of symbols, each leading to the activation of a certain link
1322 type. In principle, it does not hurt to turn on most link types - there may
1323 be a small gain when turning off unused link types. The types are:
1325 bracket The recommended [[link][description]] or [[link]] links with hiding.
1326 angle Links in angular brackets that may contain whitespace like
1327 <bbdb:Carsten Dominik>.
1328 plain Plain links in normal text, no whitespace, like http://google.com.
1329 radio Text that is matched by a radio target, see manual for details.
1330 tag Tag settings in a headline (link to tag search).
1331 date Time stamps (link to calendar).
1332 footnote Footnote labels.
1334 Changing this variable requires a restart of Emacs to become effective."
1335 :group 'org-link
1336 :type '(set :greedy t
1337 (const :tag "Double bracket links" bracket)
1338 (const :tag "Angular bracket links" angle)
1339 (const :tag "Plain text links" plain)
1340 (const :tag "Radio target matches" radio)
1341 (const :tag "Tags" tag)
1342 (const :tag "Timestamps" date)
1343 (const :tag "Footnotes" footnote)))
1345 (defcustom org-make-link-description-function nil
1346 "Function to use to generate link descriptions from links.
1347 If nil the link location will be used. This function must take
1348 two parameters; the first is the link and the second the
1349 description `org-insert-link' has generated, and should return the
1350 description to use."
1351 :group 'org-link
1352 :type 'function)
1354 (defgroup org-link-store nil
1355 "Options concerning storing links in Org-mode."
1356 :tag "Org Store Link"
1357 :group 'org-link)
1359 (defcustom org-email-link-description-format "Email %c: %.30s"
1360 "Format of the description part of a link to an email or usenet message.
1361 The following %-escapes will be replaced by corresponding information:
1363 %F full \"From\" field
1364 %f name, taken from \"From\" field, address if no name
1365 %T full \"To\" field
1366 %t first name in \"To\" field, address if no name
1367 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1368 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1369 %s subject
1370 %d date
1371 %m message-id.
1373 You may use normal field width specification between the % and the letter.
1374 This is for example useful to limit the length of the subject.
1376 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1377 :group 'org-link-store
1378 :type 'string)
1380 (defcustom org-from-is-user-regexp
1381 (let (r1 r2)
1382 (when (and user-mail-address (not (string= user-mail-address "")))
1383 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1384 (when (and user-full-name (not (string= user-full-name "")))
1385 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1386 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1387 "Regexp matched against the \"From:\" header of an email or usenet message.
1388 It should match if the message is from the user him/herself."
1389 :group 'org-link-store
1390 :type 'regexp)
1392 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1393 "Non-nil means storing a link to an Org file will use entry IDs.
1395 Note that before this variable is even considered, org-id must be loaded,
1396 so please customize `org-modules' and turn it on.
1398 The variable can have the following values:
1400 t Create an ID if needed to make a link to the current entry.
1402 create-if-interactive
1403 If `org-store-link' is called directly (interactively, as a user
1404 command), do create an ID to support the link. But when doing the
1405 job for remember, only use the ID if it already exists. The
1406 purpose of this setting is to avoid proliferation of unwanted
1407 IDs, just because you happen to be in an Org file when you
1408 call `org-remember' that automatically and preemptively
1409 creates a link. If you do want to get an ID link in a remember
1410 template to an entry not having an ID, create it first by
1411 explicitly creating a link to it, using `C-c C-l' first.
1413 create-if-interactive-and-no-custom-id
1414 Like create-if-interactive, but do not create an ID if there is
1415 a CUSTOM_ID property defined in the entry. This is the default.
1417 use-existing
1418 Use existing ID, do not create one.
1420 nil Never use an ID to make a link, instead link using a text search for
1421 the headline text."
1422 :group 'org-link-store
1423 :type '(choice
1424 (const :tag "Create ID to make link" t)
1425 (const :tag "Create if storing link interactively"
1426 create-if-interactive)
1427 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1428 create-if-interactive-and-no-custom-id)
1429 (const :tag "Only use existing" use-existing)
1430 (const :tag "Do not use ID to create link" nil)))
1432 (defcustom org-context-in-file-links t
1433 "Non-nil means file links from `org-store-link' contain context.
1434 A search string will be added to the file name with :: as separator and
1435 used to find the context when the link is activated by the command
1436 `org-open-at-point'. When this option is t, the entire active region
1437 will be placed in the search string of the file link. If set to a
1438 positive integer, only the first n lines of context will be stored.
1440 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1441 negates this setting for the duration of the command."
1442 :group 'org-link-store
1443 :type '(choice boolean integer))
1445 (defcustom org-keep-stored-link-after-insertion nil
1446 "Non-nil means keep link in list for entire session.
1448 The command `org-store-link' adds a link pointing to the current
1449 location to an internal list. These links accumulate during a session.
1450 The command `org-insert-link' can be used to insert links into any
1451 Org-mode file (offering completion for all stored links). When this
1452 option is nil, every link which has been inserted once using \\[org-insert-link]
1453 will be removed from the list, to make completing the unused links
1454 more efficient."
1455 :group 'org-link-store
1456 :type 'boolean)
1458 (defgroup org-link-follow nil
1459 "Options concerning following links in Org-mode."
1460 :tag "Org Follow Link"
1461 :group 'org-link)
1463 (defcustom org-link-translation-function nil
1464 "Function to translate links with different syntax to Org syntax.
1465 This can be used to translate links created for example by the Planner
1466 or emacs-wiki packages to Org syntax.
1467 The function must accept two parameters, a TYPE containing the link
1468 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1469 which is everything after the link protocol. It should return a cons
1470 with possibly modified values of type and path.
1471 Org contains a function for this, so if you set this variable to
1472 `org-translate-link-from-planner', you should be able follow many
1473 links created by planner."
1474 :group 'org-link-follow
1475 :type 'function)
1477 (defcustom org-follow-link-hook nil
1478 "Hook that is run after a link has been followed."
1479 :group 'org-link-follow
1480 :type 'hook)
1482 (defcustom org-tab-follows-link nil
1483 "Non-nil means on links TAB will follow the link.
1484 Needs to be set before org.el is loaded.
1485 This really should not be used, it does not make sense, and the
1486 implementation is bad."
1487 :group 'org-link-follow
1488 :type 'boolean)
1490 (defcustom org-return-follows-link nil
1491 "Non-nil means on links RET will follow the link."
1492 :group 'org-link-follow
1493 :type 'boolean)
1495 (defcustom org-mouse-1-follows-link
1496 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1497 "Non-nil means mouse-1 on a link will follow the link.
1498 A longer mouse click will still set point. Does not work on XEmacs.
1499 Needs to be set before org.el is loaded."
1500 :group 'org-link-follow
1501 :type 'boolean)
1503 (defcustom org-mark-ring-length 4
1504 "Number of different positions to be recorded in the ring.
1505 Changing this requires a restart of Emacs to work correctly."
1506 :group 'org-link-follow
1507 :type 'integer)
1509 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1510 "Non-nil means internal links in Org files must exactly match a headline.
1511 When nil, the link search tries to match a phrase with all words
1512 in the search text."
1513 :group 'org-link-follow
1514 :type '(choice
1515 (const :tag "Use fuzzy text search" nil)
1516 (const :tag "Match only exact headline" t)
1517 (const :tag "Match exact headline or query to create it"
1518 query-to-create)))
1520 (defcustom org-link-frame-setup
1521 '((vm . vm-visit-folder-other-frame)
1522 (gnus . org-gnus-no-new-news)
1523 (file . find-file-other-window)
1524 (wl . wl-other-frame))
1525 "Setup the frame configuration for following links.
1526 When following a link with Emacs, it may often be useful to display
1527 this link in another window or frame. This variable can be used to
1528 set this up for the different types of links.
1529 For VM, use any of
1530 `vm-visit-folder'
1531 `vm-visit-folder-other-window'
1532 `vm-visit-folder-other-frame'
1533 For Gnus, use any of
1534 `gnus'
1535 `gnus-other-frame'
1536 `org-gnus-no-new-news'
1537 For FILE, use any of
1538 `find-file'
1539 `find-file-other-window'
1540 `find-file-other-frame'
1541 For Wanderlust use any of
1542 `wl'
1543 `wl-other-frame'
1544 For the calendar, use the variable `calendar-setup'.
1545 For BBDB, it is currently only possible to display the matches in
1546 another window."
1547 :group 'org-link-follow
1548 :type '(list
1549 (cons (const vm)
1550 (choice
1551 (const vm-visit-folder)
1552 (const vm-visit-folder-other-window)
1553 (const vm-visit-folder-other-frame)))
1554 (cons (const gnus)
1555 (choice
1556 (const gnus)
1557 (const gnus-other-frame)
1558 (const org-gnus-no-new-news)))
1559 (cons (const file)
1560 (choice
1561 (const find-file)
1562 (const find-file-other-window)
1563 (const find-file-other-frame)))
1564 (cons (const wl)
1565 (choice
1566 (const wl)
1567 (const wl-other-frame)))))
1569 (defcustom org-display-internal-link-with-indirect-buffer nil
1570 "Non-nil means use indirect buffer to display infile links.
1571 Activating internal links (from one location in a file to another location
1572 in the same file) normally just jumps to the location. When the link is
1573 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1574 is displayed in
1575 another window. When this option is set, the other window actually displays
1576 an indirect buffer clone of the current buffer, to avoid any visibility
1577 changes to the current buffer."
1578 :group 'org-link-follow
1579 :type 'boolean)
1581 (defcustom org-open-non-existing-files nil
1582 "Non-nil means `org-open-file' will open non-existing files.
1583 When nil, an error will be generated.
1584 This variable applies only to external applications because they
1585 might choke on non-existing files. If the link is to a file that
1586 will be opened in Emacs, the variable is ignored."
1587 :group 'org-link-follow
1588 :type 'boolean)
1590 (defcustom org-open-directory-means-index-dot-org nil
1591 "Non-nil means a link to a directory really means to index.org.
1592 When nil, following a directory link will run dired or open a finder/explorer
1593 window on that directory."
1594 :group 'org-link-follow
1595 :type 'boolean)
1597 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1598 "Function and arguments to call for following mailto links.
1599 This is a list with the first element being a Lisp function, and the
1600 remaining elements being arguments to the function. In string arguments,
1601 %a will be replaced by the address, and %s will be replaced by the subject
1602 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1603 :group 'org-link-follow
1604 :type '(choice
1605 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1606 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1607 (const :tag "message-mail" (message-mail "%a" "%s"))
1608 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1610 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1611 "Non-nil means ask for confirmation before executing shell links.
1612 Shell links can be dangerous: just think about a link
1614 [[shell:rm -rf ~/*][Google Search]]
1616 This link would show up in your Org-mode document as \"Google Search\",
1617 but really it would remove your entire home directory.
1618 Therefore we advise against setting this variable to nil.
1619 Just change it to `y-or-n-p' if you want to confirm with a
1620 single keystroke rather than having to type \"yes\"."
1621 :group 'org-link-follow
1622 :type '(choice
1623 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1624 (const :tag "with y-or-n (faster)" y-or-n-p)
1625 (const :tag "no confirmation (dangerous)" nil)))
1626 (put 'org-confirm-shell-link-function
1627 'safe-local-variable
1628 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1630 (defcustom org-confirm-shell-link-not-regexp ""
1631 "A regexp to skip confirmation for shell links."
1632 :group 'org-link-follow
1633 :type 'regexp)
1635 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1636 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1637 Elisp links can be dangerous: just think about a link
1639 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1641 This link would show up in your Org-mode document as \"Google Search\",
1642 but really it would remove your entire home directory.
1643 Therefore we advise against setting this variable to nil.
1644 Just change it to `y-or-n-p' if you want to confirm with a
1645 single keystroke rather than having to type \"yes\"."
1646 :group 'org-link-follow
1647 :type '(choice
1648 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1649 (const :tag "with y-or-n (faster)" y-or-n-p)
1650 (const :tag "no confirmation (dangerous)" nil)))
1651 (put 'org-confirm-shell-link-function
1652 'safe-local-variable
1653 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1655 (defcustom org-confirm-elisp-link-not-regexp ""
1656 "A regexp to skip confirmation for Elisp links."
1657 :group 'org-link-follow
1658 :type 'regexp)
1660 (defconst org-file-apps-defaults-gnu
1661 '((remote . emacs)
1662 (system . mailcap)
1663 (t . mailcap))
1664 "Default file applications on a UNIX or GNU/Linux system.
1665 See `org-file-apps'.")
1667 (defconst org-file-apps-defaults-macosx
1668 '((remote . emacs)
1669 (t . "open %s")
1670 (system . "open %s")
1671 ("ps.gz" . "gv %s")
1672 ("eps.gz" . "gv %s")
1673 ("dvi" . "xdvi %s")
1674 ("fig" . "xfig %s"))
1675 "Default file applications on a MacOS X system.
1676 The system \"open\" is known as a default, but we use X11 applications
1677 for some files for which the OS does not have a good default.
1678 See `org-file-apps'.")
1680 (defconst org-file-apps-defaults-windowsnt
1681 (list
1682 '(remote . emacs)
1683 (cons t
1684 (list (if (featurep 'xemacs)
1685 'mswindows-shell-execute
1686 'w32-shell-execute)
1687 "open" 'file))
1688 (cons 'system
1689 (list (if (featurep 'xemacs)
1690 'mswindows-shell-execute
1691 'w32-shell-execute)
1692 "open" 'file)))
1693 "Default file applications on a Windows NT system.
1694 The system \"open\" is used for most files.
1695 See `org-file-apps'.")
1697 (defcustom org-file-apps
1699 (auto-mode . emacs)
1700 ("\\.mm\\'" . default)
1701 ("\\.x?html?\\'" . default)
1702 ("\\.pdf\\'" . default)
1704 "External applications for opening `file:path' items in a document.
1705 Org-mode uses system defaults for different file types, but
1706 you can use this variable to set the application for a given file
1707 extension. The entries in this list are cons cells where the car identifies
1708 files and the cdr the corresponding command. Possible values for the
1709 file identifier are
1710 \"string\" A string as a file identifier can be interpreted in different
1711 ways, depending on its contents:
1713 - Alphanumeric characters only:
1714 Match links with this file extension.
1715 Example: (\"pdf\" . \"evince %s\")
1716 to open PDFs with evince.
1718 - Regular expression: Match links where the
1719 filename matches the regexp. If you want to
1720 use groups here, use shy groups.
1722 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1723 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1724 to open *.html and *.xhtml with firefox.
1726 - Regular expression which contains (non-shy) groups:
1727 Match links where the whole link, including \"::\", and
1728 anything after that, matches the regexp.
1729 In a custom command string, %1, %2, etc. are replaced with
1730 the parts of the link that were matched by the groups.
1731 For backwards compatibility, if a command string is given
1732 that does not use any of the group matches, this case is
1733 handled identically to the second one (i.e. match against
1734 file name only).
1735 In a custom lisp form, you can access the group matches with
1736 (match-string n link).
1738 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1739 to open [[file:document.pdf::5]] with evince at page 5.
1741 `directory' Matches a directory
1742 `remote' Matches a remote file, accessible through tramp or efs.
1743 Remote files most likely should be visited through Emacs
1744 because external applications cannot handle such paths.
1745 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1746 so all files Emacs knows how to handle. Using this with
1747 command `emacs' will open most files in Emacs. Beware that this
1748 will also open html files inside Emacs, unless you add
1749 (\"html\" . default) to the list as well.
1750 t Default for files not matched by any of the other options.
1751 `system' The system command to open files, like `open' on Windows
1752 and Mac OS X, and mailcap under GNU/Linux. This is the command
1753 that will be selected if you call `C-c C-o' with a double
1754 \\[universal-argument] \\[universal-argument] prefix.
1756 Possible values for the command are:
1757 `emacs' The file will be visited by the current Emacs process.
1758 `default' Use the default application for this file type, which is the
1759 association for t in the list, most likely in the system-specific
1760 part.
1761 This can be used to overrule an unwanted setting in the
1762 system-specific variable.
1763 `system' Use the system command for opening files, like \"open\".
1764 This command is specified by the entry whose car is `system'.
1765 Most likely, the system-specific version of this variable
1766 does define this command, but you can overrule/replace it
1767 here.
1768 string A command to be executed by a shell; %s will be replaced
1769 by the path to the file.
1770 sexp A Lisp form which will be evaluated. The file path will
1771 be available in the Lisp variable `file'.
1772 For more examples, see the system specific constants
1773 `org-file-apps-defaults-macosx'
1774 `org-file-apps-defaults-windowsnt'
1775 `org-file-apps-defaults-gnu'."
1776 :group 'org-link-follow
1777 :type '(repeat
1778 (cons (choice :value ""
1779 (string :tag "Extension")
1780 (const :tag "System command to open files" system)
1781 (const :tag "Default for unrecognized files" t)
1782 (const :tag "Remote file" remote)
1783 (const :tag "Links to a directory" directory)
1784 (const :tag "Any files that have Emacs modes"
1785 auto-mode))
1786 (choice :value ""
1787 (const :tag "Visit with Emacs" emacs)
1788 (const :tag "Use default" default)
1789 (const :tag "Use the system command" system)
1790 (string :tag "Command")
1791 (sexp :tag "Lisp form")))))
1795 (defgroup org-refile nil
1796 "Options concerning refiling entries in Org-mode."
1797 :tag "Org Refile"
1798 :group 'org)
1800 (defcustom org-directory "~/org"
1801 "Directory with org files.
1802 This is just a default location to look for Org files. There is no need
1803 at all to put your files into this directory. It is only used in the
1804 following situations:
1806 1. When a remember template specifies a target file that is not an
1807 absolute path. The path will then be interpreted relative to
1808 `org-directory'
1809 2. When a remember note is filed away in an interactive way (when exiting the
1810 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1811 with `org-directory' as the default path."
1812 :group 'org-refile
1813 :group 'org-remember
1814 :type 'directory)
1816 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1817 "Default target for storing notes.
1818 Used as a fall back file for org-remember.el and org-capture.el, for
1819 templates that do not specify a target file."
1820 :group 'org-refile
1821 :group 'org-remember
1822 :type '(choice
1823 (const :tag "Default from remember-data-file" nil)
1824 file))
1826 (defcustom org-goto-interface 'outline
1827 "The default interface to be used for `org-goto'.
1828 Allowed values are:
1829 outline The interface shows an outline of the relevant file
1830 and the correct heading is found by moving through
1831 the outline or by searching with incremental search.
1832 outline-path-completion Headlines in the current buffer are offered via
1833 completion. This is the interface also used by
1834 the refile command."
1835 :group 'org-refile
1836 :type '(choice
1837 (const :tag "Outline" outline)
1838 (const :tag "Outline-path-completion" outline-path-completion)))
1840 (defcustom org-goto-max-level 5
1841 "Maximum target level when running `org-goto' with refile interface."
1842 :group 'org-refile
1843 :type 'integer)
1845 (defcustom org-reverse-note-order nil
1846 "Non-nil means store new notes at the beginning of a file or entry.
1847 When nil, new notes will be filed to the end of a file or entry.
1848 This can also be a list with cons cells of regular expressions that
1849 are matched against file names, and values."
1850 :group 'org-remember
1851 :group 'org-refile
1852 :type '(choice
1853 (const :tag "Reverse always" t)
1854 (const :tag "Reverse never" nil)
1855 (repeat :tag "By file name regexp"
1856 (cons regexp boolean))))
1858 (defcustom org-log-refile nil
1859 "Information to record when a task is refiled.
1861 Possible values are:
1863 nil Don't add anything
1864 time Add a time stamp to the task
1865 note Prompt for a note and add it with template `org-log-note-headings'
1867 This option can also be set with on a per-file-basis with
1869 #+STARTUP: nologrefile
1870 #+STARTUP: logrefile
1871 #+STARTUP: lognoterefile
1873 You can have local logging settings for a subtree by setting the LOGGING
1874 property to one or more of these keywords.
1876 When bulk-refiling from the agenda, the value `note' is forbidden and
1877 will temporarily be changed to `time'."
1878 :group 'org-refile
1879 :group 'org-progress
1880 :type '(choice
1881 (const :tag "No logging" nil)
1882 (const :tag "Record timestamp" time)
1883 (const :tag "Record timestamp with note." note)))
1885 (defcustom org-refile-targets nil
1886 "Targets for refiling entries with \\[org-refile].
1887 This is a list of cons cells. Each cell contains:
1888 - a specification of the files to be considered, either a list of files,
1889 or a symbol whose function or variable value will be used to retrieve
1890 a file name or a list of file names. If you use `org-agenda-files' for
1891 that, all agenda files will be scanned for targets. Nil means consider
1892 headings in the current buffer.
1893 - A specification of how to find candidate refile targets. This may be
1894 any of:
1895 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1896 This tag has to be present in all target headlines, inheritance will
1897 not be considered.
1898 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1899 todo keyword.
1900 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1901 headlines that are refiling targets.
1902 - a cons cell (:level . N). Any headline of level N is considered a target.
1903 Note that, when `org-odd-levels-only' is set, level corresponds to
1904 order in hierarchy, not to the number of stars.
1905 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1906 Note that, when `org-odd-levels-only' is set, level corresponds to
1907 order in hierarchy, not to the number of stars.
1909 Each element of this list generates a set of possible targets.
1910 The union of these sets is presented (with completion) to
1911 the user by `org-refile'.
1913 You can set the variable `org-refile-target-verify-function' to a function
1914 to verify each headline found by the simple criteria above.
1916 When this variable is nil, all top-level headlines in the current buffer
1917 are used, equivalent to the value `((nil . (:level . 1))'."
1918 :group 'org-refile
1919 :type '(repeat
1920 (cons
1921 (choice :value org-agenda-files
1922 (const :tag "All agenda files" org-agenda-files)
1923 (const :tag "Current buffer" nil)
1924 (function) (variable) (file))
1925 (choice :tag "Identify target headline by"
1926 (cons :tag "Specific tag" (const :value :tag) (string))
1927 (cons :tag "TODO keyword" (const :value :todo) (string))
1928 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1929 (cons :tag "Level number" (const :value :level) (integer))
1930 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1932 (defcustom org-refile-target-verify-function nil
1933 "Function to verify if the headline at point should be a refile target.
1934 The function will be called without arguments, with point at the
1935 beginning of the headline. It should return t and leave point
1936 where it is if the headline is a valid target for refiling.
1938 If the target should not be selected, the function must return nil.
1939 In addition to this, it may move point to a place from where the search
1940 should be continued. For example, the function may decide that the entire
1941 subtree of the current entry should be excluded and move point to the end
1942 of the subtree."
1943 :group 'org-refile
1944 :type 'function)
1946 (defcustom org-refile-use-cache nil
1947 "Non-nil means cache refile targets to speed up the process.
1948 The cache for a particular file will be updated automatically when
1949 the buffer has been killed, or when any of the marker used for flagging
1950 refile targets no longer points at a live buffer.
1951 If you have added new entries to a buffer that might themselves be targets,
1952 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
1953 find that easier, `C-u C-u C-u C-c C-w'."
1954 :group 'org-refile
1955 :type 'boolean)
1957 (defcustom org-refile-use-outline-path nil
1958 "Non-nil means provide refile targets as paths.
1959 So a level 3 headline will be available as level1/level2/level3.
1961 When the value is `file', also include the file name (without directory)
1962 into the path. In this case, you can also stop the completion after
1963 the file name, to get entries inserted as top level in the file.
1965 When `full-file-path', include the full file path."
1966 :group 'org-refile
1967 :type '(choice
1968 (const :tag "Not" nil)
1969 (const :tag "Yes" t)
1970 (const :tag "Start with file name" file)
1971 (const :tag "Start with full file path" full-file-path)))
1973 (defcustom org-outline-path-complete-in-steps t
1974 "Non-nil means complete the outline path in hierarchical steps.
1975 When Org-mode uses the refile interface to select an outline path
1976 \(see variable `org-refile-use-outline-path'), the completion of
1977 the path can be done is a single go, or if can be done in steps down
1978 the headline hierarchy. Going in steps is probably the best if you
1979 do not use a special completion package like `ido' or `icicles'.
1980 However, when using these packages, going in one step can be very
1981 fast, while still showing the whole path to the entry."
1982 :group 'org-refile
1983 :type 'boolean)
1985 (defcustom org-refile-allow-creating-parent-nodes nil
1986 "Non-nil means allow to create new nodes as refile targets.
1987 New nodes are then created by adding \"/new node name\" to the completion
1988 of an existing node. When the value of this variable is `confirm',
1989 new node creation must be confirmed by the user (recommended)
1990 When nil, the completion must match an existing entry.
1992 Note that, if the new heading is not seen by the criteria
1993 listed in `org-refile-targets', multiple instances of the same
1994 heading would be created by trying again to file under the new
1995 heading."
1996 :group 'org-refile
1997 :type '(choice
1998 (const :tag "Never" nil)
1999 (const :tag "Always" t)
2000 (const :tag "Prompt for confirmation" confirm)))
2002 (defcustom org-refile-active-region-within-subtree nil
2003 "Non-nil means also refile active region within a subtree.
2005 By default `org-refile' doesn't allow refiling regions if they
2006 don't contain a set of subtrees, but it might be convenient to
2007 do so sometimes: in that case, the first line of the region is
2008 converted to a headline before refiling."
2009 :group 'org-refile
2010 :type 'boolean)
2012 (defgroup org-todo nil
2013 "Options concerning TODO items in Org-mode."
2014 :tag "Org TODO"
2015 :group 'org)
2017 (defgroup org-progress nil
2018 "Options concerning Progress logging in Org-mode."
2019 :tag "Org Progress"
2020 :group 'org-time)
2022 (defvar org-todo-interpretation-widgets
2023 '((:tag "Sequence (cycling hits every state)" sequence)
2024 (:tag "Type (cycling directly to DONE)" type))
2025 "The available interpretation symbols for customizing `org-todo-keywords'.
2026 Interested libraries should add to this list.")
2028 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2029 "List of TODO entry keyword sequences and their interpretation.
2030 \\<org-mode-map>This is a list of sequences.
2032 Each sequence starts with a symbol, either `sequence' or `type',
2033 indicating if the keywords should be interpreted as a sequence of
2034 action steps, or as different types of TODO items. The first
2035 keywords are states requiring action - these states will select a headline
2036 for inclusion into the global TODO list Org-mode produces. If one of
2037 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2038 signify that no further action is necessary. If \"|\" is not found,
2039 the last keyword is treated as the only DONE state of the sequence.
2041 The command \\[org-todo] cycles an entry through these states, and one
2042 additional state where no keyword is present. For details about this
2043 cycling, see the manual.
2045 TODO keywords and interpretation can also be set on a per-file basis with
2046 the special #+SEQ_TODO and #+TYP_TODO lines.
2048 Each keyword can optionally specify a character for fast state selection
2049 \(in combination with the variable `org-use-fast-todo-selection')
2050 and specifiers for state change logging, using the same syntax
2051 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
2052 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2053 indicates to record a time stamp each time this state is selected.
2055 Each keyword may also specify if a timestamp or a note should be
2056 recorded when entering or leaving the state, by adding additional
2057 characters in the parenthesis after the keyword. This looks like this:
2058 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2059 record only the time of the state change. With X and Y being either
2060 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2061 Y when leaving the state if and only if the *target* state does not
2062 define X. You may omit any of the fast-selection key or X or /Y,
2063 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2065 For backward compatibility, this variable may also be just a list
2066 of keywords - in this case the interpretation (sequence or type) will be
2067 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2068 :group 'org-todo
2069 :group 'org-keywords
2070 :type '(choice
2071 (repeat :tag "Old syntax, just keywords"
2072 (string :tag "Keyword"))
2073 (repeat :tag "New syntax"
2074 (cons
2075 (choice
2076 :tag "Interpretation"
2077 ;;Quick and dirty way to see
2078 ;;`org-todo-interpretations'. This takes the
2079 ;;place of item arguments
2080 :convert-widget
2081 (lambda (widget)
2082 (widget-put widget
2083 :args (mapcar
2084 #'(lambda (x)
2085 (widget-convert
2086 (cons 'const x)))
2087 org-todo-interpretation-widgets))
2088 widget))
2089 (repeat
2090 (string :tag "Keyword"))))))
2092 (defvar org-todo-keywords-1 nil
2093 "All TODO and DONE keywords active in a buffer.")
2094 (make-variable-buffer-local 'org-todo-keywords-1)
2095 (defvar org-todo-keywords-for-agenda nil)
2096 (defvar org-done-keywords-for-agenda nil)
2097 (defvar org-drawers-for-agenda nil)
2098 (defvar org-todo-keyword-alist-for-agenda nil)
2099 (defvar org-tag-alist-for-agenda nil)
2100 (defvar org-agenda-contributing-files nil)
2101 (defvar org-not-done-keywords nil)
2102 (make-variable-buffer-local 'org-not-done-keywords)
2103 (defvar org-done-keywords nil)
2104 (make-variable-buffer-local 'org-done-keywords)
2105 (defvar org-todo-heads nil)
2106 (make-variable-buffer-local 'org-todo-heads)
2107 (defvar org-todo-sets nil)
2108 (make-variable-buffer-local 'org-todo-sets)
2109 (defvar org-todo-log-states nil)
2110 (make-variable-buffer-local 'org-todo-log-states)
2111 (defvar org-todo-kwd-alist nil)
2112 (make-variable-buffer-local 'org-todo-kwd-alist)
2113 (defvar org-todo-key-alist nil)
2114 (make-variable-buffer-local 'org-todo-key-alist)
2115 (defvar org-todo-key-trigger nil)
2116 (make-variable-buffer-local 'org-todo-key-trigger)
2118 (defcustom org-todo-interpretation 'sequence
2119 "Controls how TODO keywords are interpreted.
2120 This variable is in principle obsolete and is only used for
2121 backward compatibility, if the interpretation of todo keywords is
2122 not given already in `org-todo-keywords'. See that variable for
2123 more information."
2124 :group 'org-todo
2125 :group 'org-keywords
2126 :type '(choice (const sequence)
2127 (const type)))
2129 (defcustom org-use-fast-todo-selection t
2130 "Non-nil means use the fast todo selection scheme with C-c C-t.
2131 This variable describes if and under what circumstances the cycling
2132 mechanism for TODO keywords will be replaced by a single-key, direct
2133 selection scheme.
2135 When nil, fast selection is never used.
2137 When the symbol `prefix', it will be used when `org-todo' is called with
2138 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
2139 in an agenda buffer.
2141 When t, fast selection is used by default. In this case, the prefix
2142 argument forces cycling instead.
2144 In all cases, the special interface is only used if access keys have actually
2145 been assigned by the user, i.e. if keywords in the configuration are followed
2146 by a letter in parenthesis, like TODO(t)."
2147 :group 'org-todo
2148 :type '(choice
2149 (const :tag "Never" nil)
2150 (const :tag "By default" t)
2151 (const :tag "Only with C-u C-c C-t" prefix)))
2153 (defcustom org-provide-todo-statistics t
2154 "Non-nil means update todo statistics after insert and toggle.
2155 ALL-HEADLINES means update todo statistics by including headlines
2156 with no TODO keyword as well, counting them as not done.
2157 A list of TODO keywords means the same, but skip keywords that are
2158 not in this list.
2160 When this is set, todo statistics is updated in the parent of the
2161 current entry each time a todo state is changed."
2162 :group 'org-todo
2163 :type '(choice
2164 (const :tag "Yes, only for TODO entries" t)
2165 (const :tag "Yes, including all entries" 'all-headlines)
2166 (repeat :tag "Yes, for TODOs in this list"
2167 (string :tag "TODO keyword"))
2168 (other :tag "No TODO statistics" nil)))
2170 (defcustom org-hierarchical-todo-statistics t
2171 "Non-nil means TODO statistics covers just direct children.
2172 When nil, all entries in the subtree are considered.
2173 This has only an effect if `org-provide-todo-statistics' is set.
2174 To set this to nil for only a single subtree, use a COOKIE_DATA
2175 property and include the word \"recursive\" into the value."
2176 :group 'org-todo
2177 :type 'boolean)
2179 (defcustom org-after-todo-state-change-hook nil
2180 "Hook which is run after the state of a TODO item was changed.
2181 The new state (a string with a TODO keyword, or nil) is available in the
2182 Lisp variable `state'."
2183 :group 'org-todo
2184 :type 'hook)
2186 (defvar org-blocker-hook nil
2187 "Hook for functions that are allowed to block a state change.
2189 Each function gets as its single argument a property list, see
2190 `org-trigger-hook' for more information about this list.
2192 If any of the functions in this hook returns nil, the state change
2193 is blocked.")
2195 (defvar org-trigger-hook nil
2196 "Hook for functions that are triggered by a state change.
2198 Each function gets as its single argument a property list with at least
2199 the following elements:
2201 (:type type-of-change :position pos-at-entry-start
2202 :from old-state :to new-state)
2204 Depending on the type, more properties may be present.
2206 This mechanism is currently implemented for:
2208 TODO state changes
2209 ------------------
2210 :type todo-state-change
2211 :from previous state (keyword as a string), or nil, or a symbol
2212 'todo' or 'done', to indicate the general type of state.
2213 :to new state, like in :from")
2215 (defcustom org-enforce-todo-dependencies nil
2216 "Non-nil means undone TODO entries will block switching the parent to DONE.
2217 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2218 be blocked if any prior sibling is not yet done.
2219 Finally, if the parent is blocked because of ordered siblings of its own,
2220 the child will also be blocked.
2221 This variable needs to be set before org.el is loaded, and you need to
2222 restart Emacs after a change to make the change effective. The only way
2223 to change is while Emacs is running is through the customize interface."
2224 :set (lambda (var val)
2225 (set var val)
2226 (if val
2227 (add-hook 'org-blocker-hook
2228 'org-block-todo-from-children-or-siblings-or-parent)
2229 (remove-hook 'org-blocker-hook
2230 'org-block-todo-from-children-or-siblings-or-parent)))
2231 :group 'org-todo
2232 :type 'boolean)
2234 (defcustom org-enforce-todo-checkbox-dependencies nil
2235 "Non-nil means unchecked boxes will block switching the parent to DONE.
2236 When this is nil, checkboxes have no influence on switching TODO states.
2237 When non-nil, you first need to check off all check boxes before the TODO
2238 entry can be switched to DONE.
2239 This variable needs to be set before org.el is loaded, and you need to
2240 restart Emacs after a change to make the change effective. The only way
2241 to change is while Emacs is running is through the customize interface."
2242 :set (lambda (var val)
2243 (set var val)
2244 (if val
2245 (add-hook 'org-blocker-hook
2246 'org-block-todo-from-checkboxes)
2247 (remove-hook 'org-blocker-hook
2248 'org-block-todo-from-checkboxes)))
2249 :group 'org-todo
2250 :type 'boolean)
2252 (defcustom org-treat-insert-todo-heading-as-state-change nil
2253 "Non-nil means inserting a TODO heading is treated as state change.
2254 So when the command \\[org-insert-todo-heading] is used, state change
2255 logging will apply if appropriate. When nil, the new TODO item will
2256 be inserted directly, and no logging will take place."
2257 :group 'org-todo
2258 :type 'boolean)
2260 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2261 "Non-nil means switching TODO states with S-cursor counts as state change.
2262 This is the default behavior. However, setting this to nil allows a
2263 convenient way to select a TODO state and bypass any logging associated
2264 with that."
2265 :group 'org-todo
2266 :type 'boolean)
2268 (defcustom org-todo-state-tags-triggers nil
2269 "Tag changes that should be triggered by TODO state changes.
2270 This is a list. Each entry is
2272 (state-change (tag . flag) .......)
2274 State-change can be a string with a state, and empty string to indicate the
2275 state that has no TODO keyword, or it can be one of the symbols `todo'
2276 or `done', meaning any not-done or done state, respectively."
2277 :group 'org-todo
2278 :group 'org-tags
2279 :type '(repeat
2280 (cons (choice :tag "When changing to"
2281 (const :tag "Not-done state" todo)
2282 (const :tag "Done state" done)
2283 (string :tag "State"))
2284 (repeat
2285 (cons :tag "Tag action"
2286 (string :tag "Tag")
2287 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2289 (defcustom org-log-done nil
2290 "Information to record when a task moves to the DONE state.
2292 Possible values are:
2294 nil Don't add anything, just change the keyword
2295 time Add a time stamp to the task
2296 note Prompt for a note and add it with template `org-log-note-headings'
2298 This option can also be set with on a per-file-basis with
2300 #+STARTUP: nologdone
2301 #+STARTUP: logdone
2302 #+STARTUP: lognotedone
2304 You can have local logging settings for a subtree by setting the LOGGING
2305 property to one or more of these keywords."
2306 :group 'org-todo
2307 :group 'org-progress
2308 :type '(choice
2309 (const :tag "No logging" nil)
2310 (const :tag "Record CLOSED timestamp" time)
2311 (const :tag "Record CLOSED timestamp with note." note)))
2313 ;; Normalize old uses of org-log-done.
2314 (cond
2315 ((eq org-log-done t) (setq org-log-done 'time))
2316 ((and (listp org-log-done) (memq 'done org-log-done))
2317 (setq org-log-done 'note)))
2319 (defcustom org-log-reschedule nil
2320 "Information to record when the scheduling date of a tasks is modified.
2322 Possible values are:
2324 nil Don't add anything, just change the date
2325 time Add a time stamp to the task
2326 note Prompt for a note and add it with template `org-log-note-headings'
2328 This option can also be set with on a per-file-basis with
2330 #+STARTUP: nologreschedule
2331 #+STARTUP: logreschedule
2332 #+STARTUP: lognotereschedule"
2333 :group 'org-todo
2334 :group 'org-progress
2335 :type '(choice
2336 (const :tag "No logging" nil)
2337 (const :tag "Record timestamp" time)
2338 (const :tag "Record timestamp with note." note)))
2340 (defcustom org-log-redeadline nil
2341 "Information to record when the deadline date of a tasks is modified.
2343 Possible values are:
2345 nil Don't add anything, just change the date
2346 time Add a time stamp to the task
2347 note Prompt for a note and add it with template `org-log-note-headings'
2349 This option can also be set with on a per-file-basis with
2351 #+STARTUP: nologredeadline
2352 #+STARTUP: logredeadline
2353 #+STARTUP: lognoteredeadline
2355 You can have local logging settings for a subtree by setting the LOGGING
2356 property to one or more of these keywords."
2357 :group 'org-todo
2358 :group 'org-progress
2359 :type '(choice
2360 (const :tag "No logging" nil)
2361 (const :tag "Record timestamp" time)
2362 (const :tag "Record timestamp with note." note)))
2364 (defcustom org-log-note-clock-out nil
2365 "Non-nil means record a note when clocking out of an item.
2366 This can also be configured on a per-file basis by adding one of
2367 the following lines anywhere in the buffer:
2369 #+STARTUP: lognoteclock-out
2370 #+STARTUP: nolognoteclock-out"
2371 :group 'org-todo
2372 :group 'org-progress
2373 :type 'boolean)
2375 (defcustom org-log-done-with-time t
2376 "Non-nil means the CLOSED time stamp will contain date and time.
2377 When nil, only the date will be recorded."
2378 :group 'org-progress
2379 :type 'boolean)
2381 (defcustom org-log-note-headings
2382 '((done . "CLOSING NOTE %t")
2383 (state . "State %-12s from %-12S %t")
2384 (note . "Note taken on %t")
2385 (reschedule . "Rescheduled from %S on %t")
2386 (delschedule . "Not scheduled, was %S on %t")
2387 (redeadline . "New deadline from %S on %t")
2388 (deldeadline . "Removed deadline, was %S on %t")
2389 (refile . "Refiled on %t")
2390 (clock-out . ""))
2391 "Headings for notes added to entries.
2392 The value is an alist, with the car being a symbol indicating the note
2393 context, and the cdr is the heading to be used. The heading may also be the
2394 empty string.
2395 %t in the heading will be replaced by a time stamp.
2396 %T will be an active time stamp instead the default inactive one
2397 %d will be replaced by a short-format time stamp.
2398 %D will be replaced by an active short-format time stamp.
2399 %s will be replaced by the new TODO state, in double quotes.
2400 %S will be replaced by the old TODO state, in double quotes.
2401 %u will be replaced by the user name.
2402 %U will be replaced by the full user name.
2404 In fact, it is not a good idea to change the `state' entry, because
2405 agenda log mode depends on the format of these entries."
2406 :group 'org-todo
2407 :group 'org-progress
2408 :type '(list :greedy t
2409 (cons (const :tag "Heading when closing an item" done) string)
2410 (cons (const :tag
2411 "Heading when changing todo state (todo sequence only)"
2412 state) string)
2413 (cons (const :tag "Heading when just taking a note" note) string)
2414 (cons (const :tag "Heading when clocking out" clock-out) string)
2415 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2416 (cons (const :tag "Heading when rescheduling" reschedule) string)
2417 (cons (const :tag "Heading when changing deadline" redeadline) string)
2418 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2419 (cons (const :tag "Heading when refiling" refile) string)))
2421 (unless (assq 'note org-log-note-headings)
2422 (push '(note . "%t") org-log-note-headings))
2424 (defcustom org-log-into-drawer nil
2425 "Non-nil means insert state change notes and time stamps into a drawer.
2426 When nil, state changes notes will be inserted after the headline and
2427 any scheduling and clock lines, but not inside a drawer.
2429 The value of this variable should be the name of the drawer to use.
2430 LOGBOOK is proposed as the default drawer for this purpose, you can
2431 also set this to a string to define the drawer of your choice.
2433 A value of t is also allowed, representing \"LOGBOOK\".
2435 If this variable is set, `org-log-state-notes-insert-after-drawers'
2436 will be ignored.
2438 You can set the property LOG_INTO_DRAWER to overrule this setting for
2439 a subtree."
2440 :group 'org-todo
2441 :group 'org-progress
2442 :type '(choice
2443 (const :tag "Not into a drawer" nil)
2444 (const :tag "LOGBOOK" t)
2445 (string :tag "Other")))
2447 (if (fboundp 'defvaralias)
2448 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2450 (defun org-log-into-drawer ()
2451 "Return the value of `org-log-into-drawer', but let properties overrule.
2452 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2453 used instead of the default value."
2454 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2455 (cond
2456 ((or (not p) (equal p "nil")) org-log-into-drawer)
2457 ((equal p "t") "LOGBOOK")
2458 (t p))))
2460 (defcustom org-log-state-notes-insert-after-drawers nil
2461 "Non-nil means insert state change notes after any drawers in entry.
2462 Only the drawers that *immediately* follow the headline and the
2463 deadline/scheduled line are skipped.
2464 When nil, insert notes right after the heading and perhaps the line
2465 with deadline/scheduling if present.
2467 This variable will have no effect if `org-log-into-drawer' is
2468 set."
2469 :group 'org-todo
2470 :group 'org-progress
2471 :type 'boolean)
2473 (defcustom org-log-states-order-reversed t
2474 "Non-nil means the latest state note will be directly after heading.
2475 When nil, the state change notes will be ordered according to time."
2476 :group 'org-todo
2477 :group 'org-progress
2478 :type 'boolean)
2480 (defcustom org-todo-repeat-to-state nil
2481 "The TODO state to which a repeater should return the repeating task.
2482 By default this is the first task in a TODO sequence, or the previous state
2483 in a TODO_TYP set. But you can specify another task here.
2484 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2485 :group 'org-todo
2486 :type '(choice (const :tag "Head of sequence" nil)
2487 (string :tag "Specific state")))
2489 (defcustom org-log-repeat 'time
2490 "Non-nil means record moving through the DONE state when triggering repeat.
2491 An auto-repeating task is immediately switched back to TODO when
2492 marked DONE. If you are not logging state changes (by adding \"@\"
2493 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2494 record a closing note, there will be no record of the task moving
2495 through DONE. This variable forces taking a note anyway.
2497 nil Don't force a record
2498 time Record a time stamp
2499 note Record a note
2501 This option can also be set with on a per-file-basis with
2503 #+STARTUP: logrepeat
2504 #+STARTUP: lognoterepeat
2505 #+STARTUP: nologrepeat
2507 You can have local logging settings for a subtree by setting the LOGGING
2508 property to one or more of these keywords."
2509 :group 'org-todo
2510 :group 'org-progress
2511 :type '(choice
2512 (const :tag "Don't force a record" nil)
2513 (const :tag "Force recording the DONE state" time)
2514 (const :tag "Force recording a note with the DONE state" note)))
2517 (defgroup org-priorities nil
2518 "Priorities in Org-mode."
2519 :tag "Org Priorities"
2520 :group 'org-todo)
2522 (defcustom org-enable-priority-commands t
2523 "Non-nil means priority commands are active.
2524 When nil, these commands will be disabled, so that you never accidentally
2525 set a priority."
2526 :group 'org-priorities
2527 :type 'boolean)
2529 (defcustom org-highest-priority ?A
2530 "The highest priority of TODO items. A character like ?A, ?B etc.
2531 Must have a smaller ASCII number than `org-lowest-priority'."
2532 :group 'org-priorities
2533 :type 'character)
2535 (defcustom org-lowest-priority ?C
2536 "The lowest priority of TODO items. A character like ?A, ?B etc.
2537 Must have a larger ASCII number than `org-highest-priority'."
2538 :group 'org-priorities
2539 :type 'character)
2541 (defcustom org-default-priority ?B
2542 "The default priority of TODO items.
2543 This is the priority an item gets if no explicit priority is given.
2544 When starting to cycle on an empty priority the first step in the cycle
2545 depends on `org-priority-start-cycle-with-default'. The resulting first
2546 step priority must not exceed the range from `org-highest-priority' to
2547 `org-lowest-priority' which means that `org-default-priority' has to be
2548 in this range exclusive or inclusive the range boundaries. Else the
2549 first step refuses to set the default and the second will fall back
2550 to (depending on the command used) the highest or lowest priority."
2551 :group 'org-priorities
2552 :type 'character)
2554 (defcustom org-priority-start-cycle-with-default t
2555 "Non-nil means start with default priority when starting to cycle.
2556 When this is nil, the first step in the cycle will be (depending on the
2557 command used) one higher or lower than the default priority.
2558 See also `org-default-priority'."
2559 :group 'org-priorities
2560 :type 'boolean)
2562 (defcustom org-get-priority-function nil
2563 "Function to extract the priority from a string.
2564 The string is normally the headline. If this is nil Org computes the
2565 priority from the priority cookie like [#A] in the headline. It returns
2566 an integer, increasing by 1000 for each priority level.
2567 The user can set a different function here, which should take a string
2568 as an argument and return the numeric priority."
2569 :group 'org-priorities
2570 :type 'function)
2572 (defgroup org-time nil
2573 "Options concerning time stamps and deadlines in Org-mode."
2574 :tag "Org Time"
2575 :group 'org)
2577 (defcustom org-insert-labeled-timestamps-at-point nil
2578 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2579 When nil, these labeled time stamps are forces into the second line of an
2580 entry, just after the headline. When scheduling from the global TODO list,
2581 the time stamp will always be forced into the second line."
2582 :group 'org-time
2583 :type 'boolean)
2585 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2586 "Formats for `format-time-string' which are used for time stamps.
2587 It is not recommended to change this constant.")
2589 (defcustom org-time-stamp-rounding-minutes '(0 5)
2590 "Number of minutes to round time stamps to.
2591 These are two values, the first applies when first creating a time stamp.
2592 The second applies when changing it with the commands `S-up' and `S-down'.
2593 When changing the time stamp, this means that it will change in steps
2594 of N minutes, as given by the second value.
2596 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2597 numbers should be factors of 60, so for example 5, 10, 15.
2599 When this is larger than 1, you can still force an exact time stamp by using
2600 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2601 and by using a prefix arg to `S-up/down' to specify the exact number
2602 of minutes to shift."
2603 :group 'org-time
2604 :get #'(lambda (var) ; Make sure both elements are there
2605 (if (integerp (default-value var))
2606 (list (default-value var) 5)
2607 (default-value var)))
2608 :type '(list
2609 (integer :tag "when inserting times")
2610 (integer :tag "when modifying times")))
2612 ;; Normalize old customizations of this variable.
2613 (when (integerp org-time-stamp-rounding-minutes)
2614 (setq org-time-stamp-rounding-minutes
2615 (list org-time-stamp-rounding-minutes
2616 org-time-stamp-rounding-minutes)))
2618 (defcustom org-display-custom-times nil
2619 "Non-nil means overlay custom formats over all time stamps.
2620 The formats are defined through the variable `org-time-stamp-custom-formats'.
2621 To turn this on on a per-file basis, insert anywhere in the file:
2622 #+STARTUP: customtime"
2623 :group 'org-time
2624 :set 'set-default
2625 :type 'sexp)
2626 (make-variable-buffer-local 'org-display-custom-times)
2628 (defcustom org-time-stamp-custom-formats
2629 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2630 "Custom formats for time stamps. See `format-time-string' for the syntax.
2631 These are overlayed over the default ISO format if the variable
2632 `org-display-custom-times' is set. Time like %H:%M should be at the
2633 end of the second format. The custom formats are also honored by export
2634 commands, if custom time display is turned on at the time of export."
2635 :group 'org-time
2636 :type 'sexp)
2638 (defun org-time-stamp-format (&optional long inactive)
2639 "Get the right format for a time string."
2640 (let ((f (if long (cdr org-time-stamp-formats)
2641 (car org-time-stamp-formats))))
2642 (if inactive
2643 (concat "[" (substring f 1 -1) "]")
2644 f)))
2646 (defcustom org-time-clocksum-format "%d:%02d"
2647 "The format string used when creating CLOCKSUM lines.
2648 This is also used when org-mode generates a time duration."
2649 :group 'org-time
2650 :type 'string)
2652 (defcustom org-time-clocksum-use-fractional nil
2653 "If non-nil, \\[org-clock-display] uses fractional times.
2654 org-mode generates a time duration."
2655 :group 'org-time
2656 :type 'boolean)
2658 (defcustom org-time-clocksum-fractional-format "%.2f"
2659 "The format string used when creating CLOCKSUM lines, or when
2660 org-mode generates a time duration."
2661 :group 'org-time
2662 :type 'string)
2664 (defcustom org-deadline-warning-days 14
2665 "No. of days before expiration during which a deadline becomes active.
2666 This variable governs the display in sparse trees and in the agenda.
2667 When 0 or negative, it means use this number (the absolute value of it)
2668 even if a deadline has a different individual lead time specified.
2670 Custom commands can set this variable in the options section."
2671 :group 'org-time
2672 :group 'org-agenda-daily/weekly
2673 :type 'integer)
2675 (defcustom org-read-date-prefer-future t
2676 "Non-nil means assume future for incomplete date input from user.
2677 This affects the following situations:
2678 1. The user gives a month but not a year.
2679 For example, if it is April and you enter \"feb 2\", this will be read
2680 as Feb 2, *next* year. \"May 5\", however, will be this year.
2681 2. The user gives a day, but no month.
2682 For example, if today is the 15th, and you enter \"3\", Org-mode will
2683 read this as the third of *next* month. However, if you enter \"17\",
2684 it will be considered as *this* month.
2686 If you set this variable to the symbol `time', then also the following
2687 will work:
2689 3. If the user gives a time, but no day. If the time is before now,
2690 to will be interpreted as tomorrow.
2692 Currently none of this works for ISO week specifications.
2694 When this option is nil, the current day, month and year will always be
2695 used as defaults.
2697 See also `org-agenda-jump-prefer-future'."
2698 :group 'org-time
2699 :type '(choice
2700 (const :tag "Never" nil)
2701 (const :tag "Check month and day" t)
2702 (const :tag "Check month, day, and time" time)))
2704 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2705 "Should the agenda jump command prefer the future for incomplete dates?
2706 The default is to do the same as configured in `org-read-date-prefer-future'.
2707 But you can also set a deviating value here.
2708 This may t or nil, or the symbol `org-read-date-prefer-future'."
2709 :group 'org-agenda
2710 :group 'org-time
2711 :type '(choice
2712 (const :tag "Use org-read-date-prefer-future"
2713 org-read-date-prefer-future)
2714 (const :tag "Never" nil)
2715 (const :tag "Always" t)))
2717 (defcustom org-read-date-force-compatible-dates t
2718 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2720 Depending on the system Emacs is running on, certain dates cannot
2721 be represented with the type used internally to represent time.
2722 Dates between 1970-1-1 and 2038-1-1 can always be represented
2723 correctly. Some systems allow for earlier dates, some for later,
2724 some for both. One way to find out it to insert any date into an
2725 Org buffer, putting the cursor on the year and hitting S-up and
2726 S-down to test the range.
2728 When this variable is set to t, the date/time prompt will not let
2729 you specify dates outside the 1970-2037 range, so it is certain that
2730 these dates will work in whatever version of Emacs you are
2731 running, and also that you can move a file from one Emacs implementation
2732 to another. WHenever Org is forcing the year for you, it will display
2733 a message and beep.
2735 When this variable is nil, Org will check if the date is
2736 representable in the specific Emacs implementation you are using.
2737 If not, it will force a year, usually the current year, and beep
2738 to remind you. Currently this setting is not recommended because
2739 the likelihood that you will open your Org files in an Emacs that
2740 has limited date range is not negligible.
2742 A workaround for this problem is to use diary sexp dates for time
2743 stamps outside of this range."
2744 :group 'org-time
2745 :type 'boolean)
2747 (defcustom org-read-date-display-live t
2748 "Non-nil means display current interpretation of date prompt live.
2749 This display will be in an overlay, in the minibuffer."
2750 :group 'org-time
2751 :type 'boolean)
2753 (defcustom org-read-date-popup-calendar t
2754 "Non-nil means pop up a calendar when prompting for a date.
2755 In the calendar, the date can be selected with mouse-1. However, the
2756 minibuffer will also be active, and you can simply enter the date as well.
2757 When nil, only the minibuffer will be available."
2758 :group 'org-time
2759 :type 'boolean)
2760 (if (fboundp 'defvaralias)
2761 (defvaralias 'org-popup-calendar-for-date-prompt
2762 'org-read-date-popup-calendar))
2764 (defcustom org-read-date-minibuffer-setup-hook nil
2765 "Hook to be used to set up keys for the date/time interface.
2766 Add key definitions to `minibuffer-local-map', which will be a temporary
2767 copy."
2768 :group 'org-time
2769 :type 'hook)
2771 (defcustom org-extend-today-until 0
2772 "The hour when your day really ends. Must be an integer.
2773 This has influence for the following applications:
2774 - When switching the agenda to \"today\". It it is still earlier than
2775 the time given here, the day recognized as TODAY is actually yesterday.
2776 - When a date is read from the user and it is still before the time given
2777 here, the current date and time will be assumed to be yesterday, 23:59.
2778 Also, timestamps inserted in remember templates follow this rule.
2780 IMPORTANT: This is a feature whose implementation is and likely will
2781 remain incomplete. Really, it is only here because past midnight seems to
2782 be the favorite working time of John Wiegley :-)"
2783 :group 'org-time
2784 :type 'integer)
2786 (defcustom org-use-effective-time nil
2787 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2788 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2789 \"effective time\" of any timestamps between midnight and 8am will be
2790 23:59 of the previous day."
2791 :group 'boolean
2792 :type 'integer)
2794 (defcustom org-edit-timestamp-down-means-later nil
2795 "Non-nil means S-down will increase the time in a time stamp.
2796 When nil, S-up will increase."
2797 :group 'org-time
2798 :type 'boolean)
2800 (defcustom org-calendar-follow-timestamp-change t
2801 "Non-nil means make the calendar window follow timestamp changes.
2802 When a timestamp is modified and the calendar window is visible, it will be
2803 moved to the new date."
2804 :group 'org-time
2805 :type 'boolean)
2807 (defgroup org-tags nil
2808 "Options concerning tags in Org-mode."
2809 :tag "Org Tags"
2810 :group 'org)
2812 (defcustom org-tag-alist nil
2813 "List of tags allowed in Org-mode files.
2814 When this list is nil, Org-mode will base TAG input on what is already in the
2815 buffer.
2816 The value of this variable is an alist, the car of each entry must be a
2817 keyword as a string, the cdr may be a character that is used to select
2818 that tag through the fast-tag-selection interface.
2819 See the manual for details."
2820 :group 'org-tags
2821 :type '(repeat
2822 (choice
2823 (cons (string :tag "Tag name")
2824 (character :tag "Access char"))
2825 (list :tag "Start radio group"
2826 (const :startgroup)
2827 (option (string :tag "Group description")))
2828 (list :tag "End radio group"
2829 (const :endgroup)
2830 (option (string :tag "Group description")))
2831 (const :tag "New line" (:newline)))))
2833 (defcustom org-tag-persistent-alist nil
2834 "List of tags that will always appear in all Org-mode files.
2835 This is in addition to any in buffer settings or customizations
2836 of `org-tag-alist'.
2837 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2838 The value of this variable is an alist, the car of each entry must be a
2839 keyword as a string, the cdr may be a character that is used to select
2840 that tag through the fast-tag-selection interface.
2841 See the manual for details.
2842 To disable these tags on a per-file basis, insert anywhere in the file:
2843 #+STARTUP: noptag"
2844 :group 'org-tags
2845 :type '(repeat
2846 (choice
2847 (cons (string :tag "Tag name")
2848 (character :tag "Access char"))
2849 (const :tag "Start radio group" (:startgroup))
2850 (const :tag "End radio group" (:endgroup))
2851 (const :tag "New line" (:newline)))))
2853 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2854 "If non-nil, always offer completion for all tags of all agenda files.
2855 Instead of customizing this variable directly, you might want to
2856 set it locally for capture buffers, because there no list of
2857 tags in that file can be created dynamically (there are none).
2859 (add-hook 'org-capture-mode-hook
2860 (lambda ()
2861 (set (make-local-variable
2862 'org-complete-tags-always-offer-all-agenda-tags)
2863 t)))"
2864 :group 'org-tags
2865 :type 'boolean)
2867 (defvar org-file-tags nil
2868 "List of tags that can be inherited by all entries in the file.
2869 The tags will be inherited if the variable `org-use-tag-inheritance'
2870 says they should be.
2871 This variable is populated from #+FILETAGS lines.")
2873 (defcustom org-use-fast-tag-selection 'auto
2874 "Non-nil means use fast tag selection scheme.
2875 This is a special interface to select and deselect tags with single keys.
2876 When nil, fast selection is never used.
2877 When the symbol `auto', fast selection is used if and only if selection
2878 characters for tags have been configured, either through the variable
2879 `org-tag-alist' or through a #+TAGS line in the buffer.
2880 When t, fast selection is always used and selection keys are assigned
2881 automatically if necessary."
2882 :group 'org-tags
2883 :type '(choice
2884 (const :tag "Always" t)
2885 (const :tag "Never" nil)
2886 (const :tag "When selection characters are configured" 'auto)))
2888 (defcustom org-fast-tag-selection-single-key nil
2889 "Non-nil means fast tag selection exits after first change.
2890 When nil, you have to press RET to exit it.
2891 During fast tag selection, you can toggle this flag with `C-c'.
2892 This variable can also have the value `expert'. In this case, the window
2893 displaying the tags menu is not even shown, until you press C-c again."
2894 :group 'org-tags
2895 :type '(choice
2896 (const :tag "No" nil)
2897 (const :tag "Yes" t)
2898 (const :tag "Expert" expert)))
2900 (defvar org-fast-tag-selection-include-todo nil
2901 "Non-nil means fast tags selection interface will also offer TODO states.
2902 This is an undocumented feature, you should not rely on it.")
2904 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2905 "The column to which tags should be indented in a headline.
2906 If this number is positive, it specifies the column. If it is negative,
2907 it means that the tags should be flushright to that column. For example,
2908 -80 works well for a normal 80 character screen.
2909 When 0, place tags directly after headline text, with only one space in
2910 between."
2911 :group 'org-tags
2912 :type 'integer)
2914 (defcustom org-auto-align-tags t
2915 "Non-nil keeps tags aligned when modifying headlines.
2916 Some operations (i.e. demoting) change the length of a headline and
2917 therefore shift the tags around. With this option turned on, after
2918 each such operation the tags are again aligned to `org-tags-column'."
2919 :group 'org-tags
2920 :type 'boolean)
2922 (defcustom org-use-tag-inheritance t
2923 "Non-nil means tags in levels apply also for sublevels.
2924 When nil, only the tags directly given in a specific line apply there.
2925 This may also be a list of tags that should be inherited, or a regexp that
2926 matches tags that should be inherited. Additional control is possible
2927 with the variable `org-tags-exclude-from-inheritance' which gives an
2928 explicit list of tags to be excluded from inheritance., even if the value of
2929 `org-use-tag-inheritance' would select it for inheritance.
2931 If this option is t, a match early-on in a tree can lead to a large
2932 number of matches in the subtree when constructing the agenda or creating
2933 a sparse tree. If you only want to see the first match in a tree during
2934 a search, check out the variable `org-tags-match-list-sublevels'."
2935 :group 'org-tags
2936 :type '(choice
2937 (const :tag "Not" nil)
2938 (const :tag "Always" t)
2939 (repeat :tag "Specific tags" (string :tag "Tag"))
2940 (regexp :tag "Tags matched by regexp")))
2942 (defcustom org-tags-exclude-from-inheritance nil
2943 "List of tags that should never be inherited.
2944 This is a way to exclude a few tags from inheritance. For way to do
2945 the opposite, to actively allow inheritance for selected tags,
2946 see the variable `org-use-tag-inheritance'."
2947 :group 'org-tags
2948 :type '(repeat (string :tag "Tag")))
2950 (defun org-tag-inherit-p (tag)
2951 "Check if TAG is one that should be inherited."
2952 (cond
2953 ((member tag org-tags-exclude-from-inheritance) nil)
2954 ((eq org-use-tag-inheritance t) t)
2955 ((not org-use-tag-inheritance) nil)
2956 ((stringp org-use-tag-inheritance)
2957 (string-match org-use-tag-inheritance tag))
2958 ((listp org-use-tag-inheritance)
2959 (member tag org-use-tag-inheritance))
2960 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2962 (defcustom org-tags-match-list-sublevels t
2963 "Non-nil means list also sublevels of headlines matching a search.
2964 This variable applies to tags/property searches, and also to stuck
2965 projects because this search is based on a tags match as well.
2967 When set to the symbol `indented', sublevels are indented with
2968 leading dots.
2970 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2971 the sublevels of a headline matching a tag search often also match
2972 the same search. Listing all of them can create very long lists.
2973 Setting this variable to nil causes subtrees of a match to be skipped.
2975 This variable is semi-obsolete and probably should always be true. It
2976 is better to limit inheritance to certain tags using the variables
2977 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2978 :group 'org-tags
2979 :type '(choice
2980 (const :tag "No, don't list them" nil)
2981 (const :tag "Yes, do list them" t)
2982 (const :tag "List them, indented with leading dots" indented)))
2984 (defcustom org-tags-sort-function nil
2985 "When set, tags are sorted using this function as a comparator."
2986 :group 'org-tags
2987 :type '(choice
2988 (const :tag "No sorting" nil)
2989 (const :tag "Alphabetical" string<)
2990 (const :tag "Reverse alphabetical" string>)
2991 (function :tag "Custom function" nil)))
2993 (defvar org-tags-history nil
2994 "History of minibuffer reads for tags.")
2995 (defvar org-last-tags-completion-table nil
2996 "The last used completion table for tags.")
2997 (defvar org-after-tags-change-hook nil
2998 "Hook that is run after the tags in a line have changed.")
3000 (defgroup org-properties nil
3001 "Options concerning properties in Org-mode."
3002 :tag "Org Properties"
3003 :group 'org)
3005 (defcustom org-property-format "%-10s %s"
3006 "How property key/value pairs should be formatted by `indent-line'.
3007 When `indent-line' hits a property definition, it will format the line
3008 according to this format, mainly to make sure that the values are
3009 lined-up with respect to each other."
3010 :group 'org-properties
3011 :type 'string)
3013 (defcustom org-properties-postprocess-alist nil
3014 "Alist of properties and functions to adjust inserted values.
3015 Elements of this alist must be of the form
3017 ([string] [function])
3019 where [string] must be a property name and [function] must be a
3020 lambda expression: this lambda expression must take one argument,
3021 the value to adjust, and return the new value as a string.
3023 For example, this element will allow the property \"Remaining\"
3024 to be updated wrt the relation between the \"Effort\" property
3025 and the clock summary:
3027 ((\"Remaining\" (lambda(value)
3028 (let ((clocksum (org-clock-sum-current-item))
3029 (effort (org-duration-string-to-minutes
3030 (org-entry-get (point) \"Effort\"))))
3031 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3032 :group 'org-properties
3033 :type 'alist)
3035 (defcustom org-use-property-inheritance nil
3036 "Non-nil means properties apply also for sublevels.
3038 This setting is chiefly used during property searches. Turning it on can
3039 cause significant overhead when doing a search, which is why it is not
3040 on by default.
3042 When nil, only the properties directly given in the current entry count.
3043 When t, every property is inherited. The value may also be a list of
3044 properties that should have inheritance, or a regular expression matching
3045 properties that should be inherited.
3047 However, note that some special properties use inheritance under special
3048 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3049 and the properties ending in \"_ALL\" when they are used as descriptor
3050 for valid values of a property.
3052 Note for programmers:
3053 When querying an entry with `org-entry-get', you can control if inheritance
3054 should be used. By default, `org-entry-get' looks only at the local
3055 properties. You can request inheritance by setting the inherit argument
3056 to t (to force inheritance) or to `selective' (to respect the setting
3057 in this variable)."
3058 :group 'org-properties
3059 :type '(choice
3060 (const :tag "Not" nil)
3061 (const :tag "Always" t)
3062 (repeat :tag "Specific properties" (string :tag "Property"))
3063 (regexp :tag "Properties matched by regexp")))
3065 (defun org-property-inherit-p (property)
3066 "Check if PROPERTY is one that should be inherited."
3067 (cond
3068 ((eq org-use-property-inheritance t) t)
3069 ((not org-use-property-inheritance) nil)
3070 ((stringp org-use-property-inheritance)
3071 (string-match org-use-property-inheritance property))
3072 ((listp org-use-property-inheritance)
3073 (member property org-use-property-inheritance))
3074 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3076 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3077 "The default column format, if no other format has been defined.
3078 This variable can be set on the per-file basis by inserting a line
3080 #+COLUMNS: %25ITEM ....."
3081 :group 'org-properties
3082 :type 'string)
3084 (defcustom org-columns-ellipses ".."
3085 "The ellipses to be used when a field in column view is truncated.
3086 When this is the empty string, as many characters as possible are shown,
3087 but then there will be no visual indication that the field has been truncated.
3088 When this is a string of length N, the last N characters of a truncated
3089 field are replaced by this string. If the column is narrower than the
3090 ellipses string, only part of the ellipses string will be shown."
3091 :group 'org-properties
3092 :type 'string)
3094 (defcustom org-columns-modify-value-for-display-function nil
3095 "Function that modifies values for display in column view.
3096 For example, it can be used to cut out a certain part from a time stamp.
3097 The function must take 2 arguments:
3099 column-title The title of the column (*not* the property name)
3100 value The value that should be modified.
3102 The function should return the value that should be displayed,
3103 or nil if the normal value should be used."
3104 :group 'org-properties
3105 :type 'function)
3107 (defcustom org-effort-property "Effort"
3108 "The property that is being used to keep track of effort estimates.
3109 Effort estimates given in this property need to have the format H:MM."
3110 :group 'org-properties
3111 :group 'org-progress
3112 :type '(string :tag "Property"))
3114 (defconst org-global-properties-fixed
3115 '(("VISIBILITY_ALL" . "folded children content all")
3116 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3117 "List of property/value pairs that can be inherited by any entry.
3119 These are fixed values, for the preset properties. The user variable
3120 that can be used to add to this list is `org-global-properties'.
3122 The entries in this list are cons cells where the car is a property
3123 name and cdr is a string with the value. If the value represents
3124 multiple items like an \"_ALL\" property, separate the items by
3125 spaces.")
3127 (defcustom org-global-properties nil
3128 "List of property/value pairs that can be inherited by any entry.
3130 This list will be combined with the constant `org-global-properties-fixed'.
3132 The entries in this list are cons cells where the car is a property
3133 name and cdr is a string with the value.
3135 You can set buffer-local values for the same purpose in the variable
3136 `org-file-properties' this by adding lines like
3138 #+PROPERTY: NAME VALUE"
3139 :group 'org-properties
3140 :type '(repeat
3141 (cons (string :tag "Property")
3142 (string :tag "Value"))))
3144 (defvar org-file-properties nil
3145 "List of property/value pairs that can be inherited by any entry.
3146 Valid for the current buffer.
3147 This variable is populated from #+PROPERTY lines.")
3148 (make-variable-buffer-local 'org-file-properties)
3150 (defgroup org-agenda nil
3151 "Options concerning agenda views in Org-mode."
3152 :tag "Org Agenda"
3153 :group 'org)
3155 (defvar org-category nil
3156 "Variable used by org files to set a category for agenda display.
3157 Such files should use a file variable to set it, for example
3159 # -*- mode: org; org-category: \"ELisp\"
3161 or contain a special line
3163 #+CATEGORY: ELisp
3165 If the file does not specify a category, then file's base name
3166 is used instead.")
3167 (make-variable-buffer-local 'org-category)
3168 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3170 (defcustom org-agenda-files nil
3171 "The files to be used for agenda display.
3172 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3173 \\[org-remove-file]. You can also use customize to edit the list.
3175 If an entry is a directory, all files in that directory that are matched by
3176 `org-agenda-file-regexp' will be part of the file list.
3178 If the value of the variable is not a list but a single file name, then
3179 the list of agenda files is actually stored and maintained in that file, one
3180 agenda file per line. In this file paths can be given relative to
3181 `org-directory'. Tilde expansion and environment variable substitution
3182 are also made."
3183 :group 'org-agenda
3184 :type '(choice
3185 (repeat :tag "List of files and directories" file)
3186 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3188 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3189 "Regular expression to match files for `org-agenda-files'.
3190 If any element in the list in that variable contains a directory instead
3191 of a normal file, all files in that directory that are matched by this
3192 regular expression will be included."
3193 :group 'org-agenda
3194 :type 'regexp)
3196 (defcustom org-agenda-text-search-extra-files nil
3197 "List of extra files to be searched by text search commands.
3198 These files will be search in addition to the agenda files by the
3199 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3200 Note that these files will only be searched for text search commands,
3201 not for the other agenda views like todo lists, tag searches or the weekly
3202 agenda. This variable is intended to list notes and possibly archive files
3203 that should also be searched by these two commands.
3204 In fact, if the first element in the list is the symbol `agenda-archives',
3205 than all archive files of all agenda files will be added to the search
3206 scope."
3207 :group 'org-agenda
3208 :type '(set :greedy t
3209 (const :tag "Agenda Archives" agenda-archives)
3210 (repeat :inline t (file))))
3212 (if (fboundp 'defvaralias)
3213 (defvaralias 'org-agenda-multi-occur-extra-files
3214 'org-agenda-text-search-extra-files))
3216 (defcustom org-agenda-skip-unavailable-files nil
3217 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3218 A nil value means to remove them, after a query, from the list."
3219 :group 'org-agenda
3220 :type 'boolean)
3222 (defcustom org-calendar-to-agenda-key [?c]
3223 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3224 The command `org-calendar-goto-agenda' will be bound to this key. The
3225 default is the character `c' because then `c' can be used to switch back and
3226 forth between agenda and calendar."
3227 :group 'org-agenda
3228 :type 'sexp)
3230 (defcustom org-calendar-agenda-action-key [?k]
3231 "The key to be installed in `calendar-mode-map' for agenda-action.
3232 The command `org-agenda-action' will be bound to this key. The
3233 default is the character `k' because we use the same key in the agenda."
3234 :group 'org-agenda
3235 :type 'sexp)
3237 (defcustom org-calendar-insert-diary-entry-key [?i]
3238 "The key to be installed in `calendar-mode-map' for adding diary entries.
3239 This option is irrelevant until `org-agenda-diary-file' has been configured
3240 to point to an Org-mode file. When that is the case, the command
3241 `org-agenda-diary-entry' will be bound to the key given here, by default
3242 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3243 if you want to continue doing this, you need to change this to a different
3244 key."
3245 :group 'org-agenda
3246 :type 'sexp)
3248 (defcustom org-agenda-diary-file 'diary-file
3249 "File to which to add new entries with the `i' key in agenda and calendar.
3250 When this is the symbol `diary-file', the functionality in the Emacs
3251 calendar will be used to add entries to the `diary-file'. But when this
3252 points to a file, `org-agenda-diary-entry' will be used instead."
3253 :group 'org-agenda
3254 :type '(choice
3255 (const :tag "The standard Emacs diary file" diary-file)
3256 (file :tag "Special Org file diary entries")))
3258 (eval-after-load "calendar"
3259 '(progn
3260 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3261 'org-calendar-goto-agenda)
3262 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3263 'org-agenda-action)
3264 (add-hook 'calendar-mode-hook
3265 (lambda ()
3266 (unless (eq org-agenda-diary-file 'diary-file)
3267 (define-key calendar-mode-map
3268 org-calendar-insert-diary-entry-key
3269 'org-agenda-diary-entry))))))
3271 (defgroup org-latex nil
3272 "Options for embedding LaTeX code into Org-mode."
3273 :tag "Org LaTeX"
3274 :group 'org)
3276 (defcustom org-format-latex-options
3277 '(:foreground default :background default :scale 1.0
3278 :html-foreground "Black" :html-background "Transparent"
3279 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3280 "Options for creating images from LaTeX fragments.
3281 This is a property list with the following properties:
3282 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3283 `default' means use the foreground of the default face.
3284 :background the background color, or \"Transparent\".
3285 `default' means use the background of the default face.
3286 :scale a scaling factor for the size of the images, to get more pixels
3287 :html-foreground, :html-background, :html-scale
3288 the same numbers for HTML export.
3289 :matchers a list indicating which matchers should be used to
3290 find LaTeX fragments. Valid members of this list are:
3291 \"begin\" find environments
3292 \"$1\" find single characters surrounded by $.$
3293 \"$\" find math expressions surrounded by $...$
3294 \"$$\" find math expressions surrounded by $$....$$
3295 \"\\(\" find math expressions surrounded by \\(...\\)
3296 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3297 :group 'org-latex
3298 :type 'plist)
3300 (defcustom org-format-latex-signal-error t
3301 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3302 When nil, just push out a message."
3303 :group 'org-latex
3304 :type 'boolean)
3305 (defcustom org-latex-to-mathml-jar-file nil
3306 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3307 Use this to specify additional executable file say a jar file.
3309 When using MathToWeb as the converter, specify the full-path to
3310 your mathtoweb.jar file."
3311 :group 'org-latex
3312 :type '(choice
3313 (const :tag "None" nil)
3314 (file :tag "JAR file" :must-match t)))
3316 (defcustom org-latex-to-mathml-convert-command nil
3317 "Command to convert LaTeX fragments to MathML.
3318 Replace format-specifiers in the command as noted below and use
3319 `shell-command' to convert LaTeX to MathML.
3320 %j: Executable file in fully expanded form as specified by
3321 `org-latex-to-mathml-jar-file'.
3322 %I: Input LaTeX file in fully expanded form
3323 %o: Output MathML file
3324 This command is used by `org-create-math-formula'.
3326 When using MathToWeb as the converter, set this to
3327 \"java -jar %j -unicode -force -df %o %I\"."
3328 :group 'org-latex
3329 :type '(choice
3330 (const :tag "None" nil)
3331 (string :tag "\nShell command")))
3333 (defun org-format-latex-mathml-available-p ()
3334 "Return t if `org-latex-to-mathml-convert-command' is usable."
3335 (save-match-data
3336 (when (and (boundp 'org-latex-to-mathml-convert-command)
3337 org-latex-to-mathml-convert-command)
3338 (let ((executable (car (split-string
3339 org-latex-to-mathml-convert-command))))
3340 (when (executable-find executable)
3341 (if (string-match
3342 "%j" org-latex-to-mathml-convert-command)
3343 (file-readable-p org-latex-to-mathml-jar-file)
3344 t))))))
3346 (defcustom org-format-latex-header "\\documentclass{article}
3347 \\usepackage[usenames]{color}
3348 \\usepackage{amsmath}
3349 \\usepackage[mathscr]{eucal}
3350 \\pagestyle{empty} % do not remove
3351 \[PACKAGES]
3352 \[DEFAULT-PACKAGES]
3353 % The settings below are copied from fullpage.sty
3354 \\setlength{\\textwidth}{\\paperwidth}
3355 \\addtolength{\\textwidth}{-3cm}
3356 \\setlength{\\oddsidemargin}{1.5cm}
3357 \\addtolength{\\oddsidemargin}{-2.54cm}
3358 \\setlength{\\evensidemargin}{\\oddsidemargin}
3359 \\setlength{\\textheight}{\\paperheight}
3360 \\addtolength{\\textheight}{-\\headheight}
3361 \\addtolength{\\textheight}{-\\headsep}
3362 \\addtolength{\\textheight}{-\\footskip}
3363 \\addtolength{\\textheight}{-3cm}
3364 \\setlength{\\topmargin}{1.5cm}
3365 \\addtolength{\\topmargin}{-2.54cm}"
3366 "The document header used for processing LaTeX fragments.
3367 It is imperative that this header make sure that no page number
3368 appears on the page. The package defined in the variables
3369 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3370 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3371 will be appended."
3372 :group 'org-latex
3373 :type 'string)
3375 (defvar org-format-latex-header-extra nil)
3377 (defun org-set-packages-alist (var val)
3378 "Set the packages alist and make sure it has 3 elements per entry."
3379 (set var (mapcar (lambda (x)
3380 (if (and (consp x) (= (length x) 2))
3381 (list (car x) (nth 1 x) t)
3383 val)))
3385 (defun org-get-packages-alist (var)
3387 "Get the packages alist and make sure it has 3 elements per entry."
3388 (mapcar (lambda (x)
3389 (if (and (consp x) (= (length x) 2))
3390 (list (car x) (nth 1 x) t)
3392 (default-value var)))
3394 ;; The following variables are defined here because is it also used
3395 ;; when formatting latex fragments. Originally it was part of the
3396 ;; LaTeX exporter, which is why the name includes "export".
3397 (defcustom org-export-latex-default-packages-alist
3398 '(("AUTO" "inputenc" t)
3399 ("T1" "fontenc" t)
3400 ("" "fixltx2e" nil)
3401 ("" "graphicx" t)
3402 ("" "longtable" nil)
3403 ("" "float" nil)
3404 ("" "wrapfig" nil)
3405 ("" "soul" t)
3406 ("" "textcomp" t)
3407 ("" "marvosym" t)
3408 ("" "wasysym" t)
3409 ("" "latexsym" t)
3410 ("" "amssymb" t)
3411 ("" "hyperref" nil)
3412 "\\tolerance=1000"
3414 "Alist of default packages to be inserted in the header.
3415 Change this only if one of the packages here causes an incompatibility
3416 with another package you are using.
3417 The packages in this list are needed by one part or another of Org-mode
3418 to function properly.
3420 - inputenc, fontenc: for basic font and character selection
3421 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3422 for interpreting the entities in `org-entities'. You can skip some of these
3423 packages if you don't use any of the symbols in it.
3424 - graphicx: for including images
3425 - float, wrapfig: for figure placement
3426 - longtable: for long tables
3427 - hyperref: for cross references
3429 Therefore you should not modify this variable unless you know what you
3430 are doing. The one reason to change it anyway is that you might be loading
3431 some other package that conflicts with one of the default packages.
3432 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3433 If SNIPPET-FLAG is t, the package also needs to be included when
3434 compiling LaTeX snippets into images for inclusion into HTML."
3435 :group 'org-export-latex
3436 :set 'org-set-packages-alist
3437 :get 'org-get-packages-alist
3438 :type '(repeat
3439 (choice
3440 (list :tag "options/package pair"
3441 (string :tag "options")
3442 (string :tag "package")
3443 (boolean :tag "Snippet"))
3444 (string :tag "A line of LaTeX"))))
3446 (defcustom org-export-latex-packages-alist nil
3447 "Alist of packages to be inserted in every LaTeX header.
3448 These will be inserted after `org-export-latex-default-packages-alist'.
3449 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3450 SNIPPET-FLAG, when t, indicates that this package is also needed when
3451 turning LaTeX snippets into images for inclusion into HTML.
3452 Make sure that you only list packages here which:
3453 - you want in every file
3454 - do not conflict with the default packages in
3455 `org-export-latex-default-packages-alist'
3456 - do not conflict with the setup in `org-format-latex-header'."
3457 :group 'org-export-latex
3458 :set 'org-set-packages-alist
3459 :get 'org-get-packages-alist
3460 :type '(repeat
3461 (choice
3462 (list :tag "options/package pair"
3463 (string :tag "options")
3464 (string :tag "package")
3465 (boolean :tag "Snippet"))
3466 (string :tag "A line of LaTeX"))))
3469 (defgroup org-appearance nil
3470 "Settings for Org-mode appearance."
3471 :tag "Org Appearance"
3472 :group 'org)
3474 (defcustom org-level-color-stars-only nil
3475 "Non-nil means fontify only the stars in each headline.
3476 When nil, the entire headline is fontified.
3477 Changing it requires restart of `font-lock-mode' to become effective
3478 also in regions already fontified."
3479 :group 'org-appearance
3480 :type 'boolean)
3482 (defcustom org-hide-leading-stars nil
3483 "Non-nil means hide the first N-1 stars in a headline.
3484 This works by using the face `org-hide' for these stars. This
3485 face is white for a light background, and black for a dark
3486 background. You may have to customize the face `org-hide' to
3487 make this work.
3488 Changing it requires restart of `font-lock-mode' to become effective
3489 also in regions already fontified.
3490 You may also set this on a per-file basis by adding one of the following
3491 lines to the buffer:
3493 #+STARTUP: hidestars
3494 #+STARTUP: showstars"
3495 :group 'org-appearance
3496 :type 'boolean)
3498 (defcustom org-hidden-keywords nil
3499 "List of symbols corresponding to keywords to be hidden the org buffer.
3500 For example, a value '(title) for this list will make the document's title
3501 appear in the buffer without the initial #+TITLE: keyword."
3502 :group 'org-appearance
3503 :type '(set (const :tag "#+AUTHOR" author)
3504 (const :tag "#+DATE" date)
3505 (const :tag "#+EMAIL" email)
3506 (const :tag "#+TITLE" title)))
3508 (defcustom org-fontify-done-headline nil
3509 "Non-nil means change the face of a headline if it is marked DONE.
3510 Normally, only the TODO/DONE keyword indicates the state of a headline.
3511 When this is non-nil, the headline after the keyword is set to the
3512 `org-headline-done' as an additional indication."
3513 :group 'org-appearance
3514 :type 'boolean)
3516 (defcustom org-fontify-emphasized-text t
3517 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3518 Changing this variable requires a restart of Emacs to take effect."
3519 :group 'org-appearance
3520 :type 'boolean)
3522 (defcustom org-fontify-whole-heading-line nil
3523 "Non-nil means fontify the whole line for headings.
3524 This is useful when setting a background color for the
3525 org-level-* faces."
3526 :group 'org-appearance
3527 :type 'boolean)
3529 (defcustom org-highlight-latex-fragments-and-specials nil
3530 "Non-nil means fontify what is treated specially by the exporters."
3531 :group 'org-appearance
3532 :type 'boolean)
3534 (defcustom org-hide-emphasis-markers nil
3535 "Non-nil mean font-lock should hide the emphasis marker characters."
3536 :group 'org-appearance
3537 :type 'boolean)
3539 (defcustom org-pretty-entities nil
3540 "Non-nil means show entities as UTF8 characters.
3541 When nil, the \\name form remains in the buffer."
3542 :group 'org-appearance
3543 :type 'boolean)
3545 (defcustom org-pretty-entities-include-sub-superscripts t
3546 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3547 :group 'org-appearance
3548 :type 'boolean)
3550 (defvar org-emph-re nil
3551 "Regular expression for matching emphasis.
3552 After a match, the match groups contain these elements:
3553 0 The match of the full regular expression, including the characters
3554 before and after the proper match
3555 1 The character before the proper match, or empty at beginning of line
3556 2 The proper match, including the leading and trailing markers
3557 3 The leading marker like * or /, indicating the type of highlighting
3558 4 The text between the emphasis markers, not including the markers
3559 5 The character after the match, empty at the end of a line")
3560 (defvar org-verbatim-re nil
3561 "Regular expression for matching verbatim text.")
3562 (defvar org-emphasis-regexp-components) ; defined just below
3563 (defvar org-emphasis-alist) ; defined just below
3564 (defun org-set-emph-re (var val)
3565 "Set variable and compute the emphasis regular expression."
3566 (set var val)
3567 (when (and (boundp 'org-emphasis-alist)
3568 (boundp 'org-emphasis-regexp-components)
3569 org-emphasis-alist org-emphasis-regexp-components)
3570 (let* ((e org-emphasis-regexp-components)
3571 (pre (car e))
3572 (post (nth 1 e))
3573 (border (nth 2 e))
3574 (body (nth 3 e))
3575 (nl (nth 4 e))
3576 (body1 (concat body "*?"))
3577 (markers (mapconcat 'car org-emphasis-alist ""))
3578 (vmarkers (mapconcat
3579 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3580 org-emphasis-alist "")))
3581 ;; make sure special characters appear at the right position in the class
3582 (if (string-match "\\^" markers)
3583 (setq markers (concat (replace-match "" t t markers) "^")))
3584 (if (string-match "-" markers)
3585 (setq markers (concat (replace-match "" t t markers) "-")))
3586 (if (string-match "\\^" vmarkers)
3587 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3588 (if (string-match "-" vmarkers)
3589 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3590 (if (> nl 0)
3591 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3592 (int-to-string nl) "\\}")))
3593 ;; Make the regexp
3594 (setq org-emph-re
3595 (concat "\\([" pre "]\\|^\\)"
3596 "\\("
3597 "\\([" markers "]\\)"
3598 "\\("
3599 "[^" border "]\\|"
3600 "[^" border "]"
3601 body1
3602 "[^" border "]"
3603 "\\)"
3604 "\\3\\)"
3605 "\\([" post "]\\|$\\)"))
3606 (setq org-verbatim-re
3607 (concat "\\([" pre "]\\|^\\)"
3608 "\\("
3609 "\\([" vmarkers "]\\)"
3610 "\\("
3611 "[^" border "]\\|"
3612 "[^" border "]"
3613 body1
3614 "[^" border "]"
3615 "\\)"
3616 "\\3\\)"
3617 "\\([" post "]\\|$\\)")))))
3619 (defcustom org-emphasis-regexp-components
3620 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3621 "Components used to build the regular expression for emphasis.
3622 This is a list with five entries. Terminology: In an emphasis string
3623 like \" *strong word* \", we call the initial space PREMATCH, the final
3624 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3625 and \"trong wor\" is the body. The different components in this variable
3626 specify what is allowed/forbidden in each part:
3628 pre Chars allowed as prematch. Beginning of line will be allowed too.
3629 post Chars allowed as postmatch. End of line will be allowed too.
3630 border The chars *forbidden* as border characters.
3631 body-regexp A regexp like \".\" to match a body character. Don't use
3632 non-shy groups here, and don't allow newline here.
3633 newline The maximum number of newlines allowed in an emphasis exp.
3635 Use customize to modify this, or restart Emacs after changing it."
3636 :group 'org-appearance
3637 :set 'org-set-emph-re
3638 :type '(list
3639 (sexp :tag "Allowed chars in pre ")
3640 (sexp :tag "Allowed chars in post ")
3641 (sexp :tag "Forbidden chars in border ")
3642 (sexp :tag "Regexp for body ")
3643 (integer :tag "number of newlines allowed")
3644 (option (boolean :tag "Please ignore this button"))))
3646 (defcustom org-emphasis-alist
3647 `(("*" bold "<b>" "</b>")
3648 ("/" italic "<i>" "</i>")
3649 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3650 ("=" org-code "<code>" "</code>" verbatim)
3651 ("~" org-verbatim "<code>" "</code>" verbatim)
3652 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3653 "<del>" "</del>")
3655 "Special syntax for emphasized text.
3656 Text starting and ending with a special character will be emphasized, for
3657 example *bold*, _underlined_ and /italic/. This variable sets the marker
3658 characters, the face to be used by font-lock for highlighting in Org-mode
3659 Emacs buffers, and the HTML tags to be used for this.
3660 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3661 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3662 Use customize to modify this, or restart Emacs after changing it."
3663 :group 'org-appearance
3664 :set 'org-set-emph-re
3665 :type '(repeat
3666 (list
3667 (string :tag "Marker character")
3668 (choice
3669 (face :tag "Font-lock-face")
3670 (plist :tag "Face property list"))
3671 (string :tag "HTML start tag")
3672 (string :tag "HTML end tag")
3673 (option (const verbatim)))))
3675 (defvar org-protecting-blocks
3676 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3677 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3678 This is needed for font-lock setup.")
3680 ;;; Miscellaneous options
3682 (defgroup org-completion nil
3683 "Completion in Org-mode."
3684 :tag "Org Completion"
3685 :group 'org)
3687 (defcustom org-completion-use-ido nil
3688 "Non-nil means use ido completion wherever possible.
3689 Note that `ido-mode' must be active for this variable to be relevant.
3690 If you decide to turn this variable on, you might well want to turn off
3691 `org-outline-path-complete-in-steps'.
3692 See also `org-completion-use-iswitchb'."
3693 :group 'org-completion
3694 :type 'boolean)
3696 (defcustom org-completion-use-iswitchb nil
3697 "Non-nil means use iswitchb completion wherever possible.
3698 Note that `iswitchb-mode' must be active for this variable to be relevant.
3699 If you decide to turn this variable on, you might well want to turn off
3700 `org-outline-path-complete-in-steps'.
3701 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3702 :group 'org-completion
3703 :type 'boolean)
3705 (defcustom org-completion-fallback-command 'hippie-expand
3706 "The expansion command called by \\[pcomplete] in normal context.
3707 Normal means, no org-mode-specific context."
3708 :group 'org-completion
3709 :type 'function)
3711 ;;; Functions and variables from their packages
3712 ;; Declared here to avoid compiler warnings
3714 ;; XEmacs only
3715 (defvar outline-mode-menu-heading)
3716 (defvar outline-mode-menu-show)
3717 (defvar outline-mode-menu-hide)
3718 (defvar zmacs-regions) ; XEmacs regions
3720 ;; Emacs only
3721 (defvar mark-active)
3723 ;; Various packages
3724 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3725 (declare-function calendar-forward-day "cal-move" (arg))
3726 (declare-function calendar-goto-date "cal-move" (date))
3727 (declare-function calendar-goto-today "cal-move" ())
3728 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3729 (defvar calc-embedded-close-formula)
3730 (defvar calc-embedded-open-formula)
3731 (declare-function cdlatex-tab "ext:cdlatex" ())
3732 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3733 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3734 (defvar font-lock-unfontify-region-function)
3735 (declare-function iswitchb-read-buffer "iswitchb"
3736 (prompt &optional default require-match start matches-set))
3737 (defvar iswitchb-temp-buflist)
3738 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3739 (defvar org-agenda-tags-todo-honor-ignore-options)
3740 (declare-function org-agenda-skip "org-agenda" ())
3741 (declare-function
3742 org-agenda-format-item "org-agenda"
3743 (extra txt &optional category tags dotime noprefix remove-re habitp))
3744 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3745 (declare-function org-agenda-change-all-lines "org-agenda"
3746 (newhead hdmarker &optional fixface just-this))
3747 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3748 (declare-function org-agenda-maybe-redo "org-agenda" ())
3749 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3750 (beg end))
3751 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3752 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3753 "org-agenda" (&optional end))
3754 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3755 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3756 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3757 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3758 (declare-function org-indent-mode "org-indent" (&optional arg))
3759 (declare-function parse-time-string "parse-time" (string))
3760 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3761 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3762 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3763 (defvar remember-data-file)
3764 (defvar texmathp-why)
3765 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3766 (declare-function table--at-cell-p "table" (position &optional object at-column))
3768 (defvar w3m-current-url)
3769 (defvar w3m-current-title)
3771 (defvar org-latex-regexps)
3773 ;;; Autoload and prepare some org modules
3775 ;; Some table stuff that needs to be defined here, because it is used
3776 ;; by the functions setting up org-mode or checking for table context.
3778 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3779 "Detect an org-type or table-type table.")
3780 (defconst org-table-line-regexp "^[ \t]*|"
3781 "Detect an org-type table line.")
3782 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3783 "Detect an org-type table line.")
3784 (defconst org-table-hline-regexp "^[ \t]*|-"
3785 "Detect an org-type table hline.")
3786 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3787 "Detect a table-type table hline.")
3788 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3789 "Detect the first line outside a table when searching from within it.
3790 This works for both table types.")
3792 ;; Autoload the functions in org-table.el that are needed by functions here.
3794 (eval-and-compile
3795 (org-autoload "org-table"
3796 '(org-table-align org-table-begin org-table-blank-field
3797 org-table-convert org-table-convert-region org-table-copy-down
3798 org-table-copy-region org-table-create
3799 org-table-create-or-convert-from-region
3800 org-table-create-with-table.el org-table-current-dline
3801 org-table-cut-region org-table-delete-column org-table-edit-field
3802 org-table-edit-formulas org-table-end org-table-eval-formula
3803 org-table-export org-table-field-info
3804 org-table-get-stored-formulas org-table-goto-column
3805 org-table-hline-and-move org-table-import org-table-insert-column
3806 org-table-insert-hline org-table-insert-row org-table-iterate
3807 org-table-justify-field-maybe org-table-kill-row
3808 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3809 org-table-move-column org-table-move-column-left
3810 org-table-move-column-right org-table-move-row
3811 org-table-move-row-down org-table-move-row-up
3812 org-table-next-field org-table-next-row org-table-paste-rectangle
3813 org-table-previous-field org-table-recalculate
3814 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3815 org-table-toggle-coordinate-overlays
3816 org-table-toggle-formula-debugger org-table-wrap-region
3817 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3818 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3819 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3821 (defun org-at-table-p (&optional table-type)
3822 "Return t if the cursor is inside an org-type table.
3823 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3824 (if org-enable-table-editor
3825 (save-excursion
3826 (beginning-of-line 1)
3827 (looking-at (if table-type org-table-any-line-regexp
3828 org-table-line-regexp)))
3829 nil))
3830 (defsubst org-table-p () (org-at-table-p))
3832 (defun org-at-table.el-p ()
3833 "Return t if and only if we are at a table.el table."
3834 (and (org-at-table-p 'any)
3835 (save-excursion
3836 (goto-char (org-table-begin 'any))
3837 (looking-at org-table1-hline-regexp))))
3838 (defun org-table-recognize-table.el ()
3839 "If there is a table.el table nearby, recognize it and move into it."
3840 (if org-table-tab-recognizes-table.el
3841 (if (org-at-table.el-p)
3842 (progn
3843 (beginning-of-line 1)
3844 (if (looking-at org-table-dataline-regexp)
3846 (if (looking-at org-table1-hline-regexp)
3847 (progn
3848 (beginning-of-line 2)
3849 (if (looking-at org-table-any-border-regexp)
3850 (beginning-of-line -1)))))
3851 (if (re-search-forward "|" (org-table-end t) t)
3852 (progn
3853 (require 'table)
3854 (if (table--at-cell-p (point))
3856 (message "recognizing table.el table...")
3857 (table-recognize-table)
3858 (message "recognizing table.el table...done")))
3859 (error "This should not happen"))
3861 nil)
3862 nil))
3864 (defun org-at-table-hline-p ()
3865 "Return t if the cursor is inside a hline in a table."
3866 (if org-enable-table-editor
3867 (save-excursion
3868 (beginning-of-line 1)
3869 (looking-at org-table-hline-regexp))
3870 nil))
3872 (defvar org-table-clean-did-remove-column nil)
3874 (defun org-table-map-tables (function &optional quietly)
3875 "Apply FUNCTION to the start of all tables in the buffer."
3876 (save-excursion
3877 (save-restriction
3878 (widen)
3879 (goto-char (point-min))
3880 (while (re-search-forward org-table-any-line-regexp nil t)
3881 (unless quietly
3882 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3883 (beginning-of-line 1)
3884 (when (looking-at org-table-line-regexp)
3885 (save-excursion (funcall function))
3886 (or (looking-at org-table-line-regexp)
3887 (forward-char 1)))
3888 (re-search-forward org-table-any-border-regexp nil 1))))
3889 (unless quietly (message "Mapping tables: done")))
3891 ;; Declare and autoload functions from org-exp.el & Co
3893 (declare-function org-default-export-plist "org-exp")
3894 (declare-function org-infile-export-plist "org-exp")
3895 (declare-function org-get-current-options "org-exp")
3896 (eval-and-compile
3897 (org-autoload "org-exp"
3898 '(org-export org-export-visible
3899 org-insert-export-options-template
3900 org-table-clean-before-export))
3901 (org-autoload "org-ascii"
3902 '(org-export-as-ascii org-export-ascii-preprocess
3903 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3904 org-export-region-as-ascii))
3905 (org-autoload "org-latex"
3906 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3907 org-replace-region-by-latex org-export-region-as-latex
3908 org-export-as-latex org-export-as-pdf
3909 org-export-as-pdf-and-open))
3910 (org-autoload "org-html"
3911 '(org-export-as-html-and-open
3912 org-export-as-html-batch org-export-as-html-to-buffer
3913 org-replace-region-by-html org-export-region-as-html
3914 org-export-as-html))
3915 (org-autoload "org-docbook"
3916 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3917 org-replace-region-by-docbook org-export-region-as-docbook
3918 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3919 org-export-as-docbook))
3920 (org-autoload "org-icalendar"
3921 '(org-export-icalendar-this-file
3922 org-export-icalendar-all-agenda-files
3923 org-export-icalendar-combine-agenda-files))
3924 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3925 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3927 ;; Declare and autoload functions from org-agenda.el
3929 (eval-and-compile
3930 (org-autoload "org-agenda"
3931 '(org-agenda org-agenda-list org-search-view
3932 org-todo-list org-tags-view org-agenda-list-stuck-projects
3933 org-diary org-agenda-to-appt
3934 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3936 ;; Autoload org-remember
3938 (eval-and-compile
3939 (org-autoload "org-remember"
3940 '(org-remember-insinuate org-remember-annotation
3941 org-remember-apply-template org-remember org-remember-handler)))
3943 (eval-and-compile
3944 (org-autoload "org-capture"
3945 '(org-capture org-capture-insert-template-here
3946 org-capture-import-remember-templates)))
3948 ;; Autoload org-clock.el
3950 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3951 (beg end))
3952 (declare-function org-clock-update-mode-line "org-clock" ())
3953 (declare-function org-resolve-clocks "org-clock"
3954 (&optional also-non-dangling-p prompt last-valid))
3955 (defvar org-clock-start-time)
3956 (defvar org-clock-marker (make-marker)
3957 "Marker recording the last clock-in.")
3958 (defvar org-clock-hd-marker (make-marker)
3959 "Marker recording the last clock-in, but the headline position.")
3960 (defvar org-clock-heading ""
3961 "The heading of the current clock entry.")
3962 (defun org-clock-is-active ()
3963 "Return non-nil if clock is currently running.
3964 The return value is actually the clock marker."
3965 (marker-buffer org-clock-marker))
3967 (eval-and-compile
3968 (org-autoload
3969 "org-clock"
3970 '(org-clock-in org-clock-out org-clock-cancel
3971 org-clock-goto org-clock-sum org-clock-display
3972 org-clock-remove-overlays org-clock-report
3973 org-clocktable-shift org-dblock-write:clocktable
3974 org-get-clocktable org-resolve-clocks)))
3976 (defun org-clock-update-time-maybe ()
3977 "If this is a CLOCK line, update it and return t.
3978 Otherwise, return nil."
3979 (interactive)
3980 (save-excursion
3981 (beginning-of-line 1)
3982 (skip-chars-forward " \t")
3983 (when (looking-at org-clock-string)
3984 (let ((re (concat "[ \t]*" org-clock-string
3985 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3986 "\\([ \t]*=>.*\\)?\\)?"))
3987 ts te h m s neg)
3988 (cond
3989 ((not (looking-at re))
3990 nil)
3991 ((not (match-end 2))
3992 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3993 (> org-clock-marker (point))
3994 (<= org-clock-marker (point-at-eol)))
3995 ;; The clock is running here
3996 (setq org-clock-start-time
3997 (apply 'encode-time
3998 (org-parse-time-string (match-string 1))))
3999 (org-clock-update-mode-line)))
4001 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
4002 (end-of-line 1)
4003 (setq ts (match-string 1)
4004 te (match-string 3))
4005 (setq s (- (org-float-time
4006 (apply 'encode-time (org-parse-time-string te)))
4007 (org-float-time
4008 (apply 'encode-time (org-parse-time-string ts))))
4009 neg (< s 0)
4010 s (abs s)
4011 h (floor (/ s 3600))
4012 s (- s (* 3600 h))
4013 m (floor (/ s 60))
4014 s (- s (* 60 s)))
4015 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
4016 t))))))
4018 (defun org-check-running-clock ()
4019 "Check if the current buffer contains the running clock.
4020 If yes, offer to stop it and to save the buffer with the changes."
4021 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4022 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4023 (buffer-name))))
4024 (org-clock-out)
4025 (when (y-or-n-p "Save changed buffer?")
4026 (save-buffer))))
4028 (defun org-clocktable-try-shift (dir n)
4029 "Check if this line starts a clock table, if yes, shift the time block."
4030 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4031 (org-clocktable-shift dir n)))
4033 ;; Autoload org-timer.el
4035 (eval-and-compile
4036 (org-autoload
4037 "org-timer"
4038 '(org-timer-start org-timer org-timer-item
4039 org-timer-change-times-in-region
4040 org-timer-set-timer
4041 org-timer-reset-timers
4042 org-timer-show-remaining-time)))
4044 ;; Autoload org-feed.el
4046 (eval-and-compile
4047 (org-autoload
4048 "org-feed"
4049 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
4052 ;; Autoload org-indent.el
4054 ;; Define the variable already here, to make sure we have it.
4055 (defvar org-indent-mode nil
4056 "Non-nil if Org-Indent mode is enabled.
4057 Use the command `org-indent-mode' to change this variable.")
4059 (eval-and-compile
4060 (org-autoload
4061 "org-indent"
4062 '(org-indent-mode)))
4064 ;; Autoload org-mobile.el
4066 (eval-and-compile
4067 (org-autoload
4068 "org-mobile"
4069 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
4071 ;; Autoload archiving code
4072 ;; The stuff that is needed for cycling and tags has to be defined here.
4074 (defgroup org-archive nil
4075 "Options concerning archiving in Org-mode."
4076 :tag "Org Archive"
4077 :group 'org-structure)
4079 (defcustom org-archive-location "%s_archive::"
4080 "The location where subtrees should be archived.
4082 The value of this variable is a string, consisting of two parts,
4083 separated by a double-colon. The first part is a filename and
4084 the second part is a headline.
4086 When the filename is omitted, archiving happens in the same file.
4087 %s in the filename will be replaced by the current file
4088 name (without the directory part). Archiving to a different file
4089 is useful to keep archived entries from contributing to the
4090 Org-mode Agenda.
4092 The archived entries will be filed as subtrees of the specified
4093 headline. When the headline is omitted, the subtrees are simply
4094 filed away at the end of the file, as top-level entries. Also in
4095 the heading you can use %s to represent the file name, this can be
4096 useful when using the same archive for a number of different files.
4098 Here are a few examples:
4099 \"%s_archive::\"
4100 If the current file is Projects.org, archive in file
4101 Projects.org_archive, as top-level trees. This is the default.
4103 \"::* Archived Tasks\"
4104 Archive in the current file, under the top-level headline
4105 \"* Archived Tasks\".
4107 \"~/org/archive.org::\"
4108 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4110 \"~/org/archive.org::* From %s\"
4111 Archive in file ~/org/archive.org (absolute path), under headlines
4112 \"From FILENAME\" where file name is the current file name.
4114 \"basement::** Finished Tasks\"
4115 Archive in file ./basement (relative path), as level 3 trees
4116 below the level 2 heading \"** Finished Tasks\".
4118 You may set this option on a per-file basis by adding to the buffer a
4119 line like
4121 #+ARCHIVE: basement::** Finished Tasks
4123 You may also define it locally for a subtree by setting an ARCHIVE property
4124 in the entry. If such a property is found in an entry, or anywhere up
4125 the hierarchy, it will be used."
4126 :group 'org-archive
4127 :type 'string)
4129 (defcustom org-archive-tag "ARCHIVE"
4130 "The tag that marks a subtree as archived.
4131 An archived subtree does not open during visibility cycling, and does
4132 not contribute to the agenda listings.
4133 After changing this, font-lock must be restarted in the relevant buffers to
4134 get the proper fontification."
4135 :group 'org-archive
4136 :group 'org-keywords
4137 :type 'string)
4139 (defcustom org-agenda-skip-archived-trees t
4140 "Non-nil means the agenda will skip any items located in archived trees.
4141 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4142 variable is no longer recommended, you should leave it at the value t.
4143 Instead, use the key `v' to cycle the archives-mode in the agenda."
4144 :group 'org-archive
4145 :group 'org-agenda-skip
4146 :type 'boolean)
4148 (defcustom org-columns-skip-archived-trees t
4149 "Non-nil means ignore archived trees when creating column view."
4150 :group 'org-archive
4151 :group 'org-properties
4152 :type 'boolean)
4154 (defcustom org-cycle-open-archived-trees nil
4155 "Non-nil means `org-cycle' will open archived trees.
4156 An archived tree is a tree marked with the tag ARCHIVE.
4157 When nil, archived trees will stay folded. You can still open them with
4158 normal outline commands like `show-all', but not with the cycling commands."
4159 :group 'org-archive
4160 :group 'org-cycle
4161 :type 'boolean)
4163 (defcustom org-sparse-tree-open-archived-trees nil
4164 "Non-nil means sparse tree construction shows matches in archived trees.
4165 When nil, matches in these trees are highlighted, but the trees are kept in
4166 collapsed state."
4167 :group 'org-archive
4168 :group 'org-sparse-trees
4169 :type 'boolean)
4171 (defun org-cycle-hide-archived-subtrees (state)
4172 "Re-hide all archived subtrees after a visibility state change."
4173 (when (and (not org-cycle-open-archived-trees)
4174 (not (memq state '(overview folded))))
4175 (save-excursion
4176 (let* ((globalp (memq state '(contents all)))
4177 (beg (if globalp (point-min) (point)))
4178 (end (if globalp (point-max) (org-end-of-subtree t))))
4179 (org-hide-archived-subtrees beg end)
4180 (goto-char beg)
4181 (if (looking-at (concat ".*:" org-archive-tag ":"))
4182 (message "%s" (substitute-command-keys
4183 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4185 (defun org-force-cycle-archived ()
4186 "Cycle subtree even if it is archived."
4187 (interactive)
4188 (setq this-command 'org-cycle)
4189 (let ((org-cycle-open-archived-trees t))
4190 (call-interactively 'org-cycle)))
4192 (defun org-hide-archived-subtrees (beg end)
4193 "Re-hide all archived subtrees after a visibility state change."
4194 (save-excursion
4195 (let* ((re (concat ":" org-archive-tag ":")))
4196 (goto-char beg)
4197 (while (re-search-forward re end t)
4198 (when (org-on-heading-p)
4199 (org-flag-subtree t)
4200 (org-end-of-subtree t))))))
4202 (defun org-flag-subtree (flag)
4203 (save-excursion
4204 (org-back-to-heading t)
4205 (outline-end-of-heading)
4206 (outline-flag-region (point)
4207 (progn (org-end-of-subtree t) (point))
4208 flag)))
4210 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4212 (eval-and-compile
4213 (org-autoload "org-archive"
4214 '(org-add-archive-files org-archive-subtree
4215 org-archive-to-archive-sibling org-toggle-archive-tag
4216 org-archive-subtree-default
4217 org-archive-subtree-default-with-confirmation)))
4219 ;; Autoload Column View Code
4221 (declare-function org-columns-number-to-string "org-colview")
4222 (declare-function org-columns-get-format-and-top-level "org-colview")
4223 (declare-function org-columns-compute "org-colview")
4225 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4226 '(org-columns-number-to-string org-columns-get-format-and-top-level
4227 org-columns-compute org-agenda-columns org-columns-remove-overlays
4228 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4230 ;; Autoload ID code
4232 (declare-function org-id-store-link "org-id")
4233 (declare-function org-id-locations-load "org-id")
4234 (declare-function org-id-locations-save "org-id")
4235 (defvar org-id-track-globally)
4236 (org-autoload "org-id"
4237 '(org-id-get-create org-id-new org-id-copy org-id-get
4238 org-id-get-with-outline-path-completion
4239 org-id-get-with-outline-drilling org-id-store-link
4240 org-id-goto org-id-find org-id-store-link))
4242 ;; Autoload Plotting Code
4244 (org-autoload "org-plot"
4245 '(org-plot/gnuplot))
4247 ;;; Variables for pre-computed regular expressions, all buffer local
4249 (defvar org-heading-regexp nil
4250 "Matches an headline.
4251 Stars are put in group 1 and the trimmed body in group 2.")
4252 (make-variable-buffer-local 'org-heading-regexp)
4253 (defvar org-drawer-regexp nil
4254 "Matches first line of a hidden block.")
4255 (make-variable-buffer-local 'org-drawer-regexp)
4256 (defvar org-todo-regexp nil
4257 "Matches any of the TODO state keywords.")
4258 (make-variable-buffer-local 'org-todo-regexp)
4259 (defvar org-not-done-regexp nil
4260 "Matches any of the TODO state keywords except the last one.")
4261 (make-variable-buffer-local 'org-not-done-regexp)
4262 (defvar org-not-done-heading-regexp nil
4263 "Matches a TODO headline that is not done.")
4264 (make-variable-buffer-local 'org-not-done-regexp)
4265 (defvar org-todo-line-regexp nil
4266 "Matches a headline and puts TODO state into group 2 if present.")
4267 (make-variable-buffer-local 'org-todo-line-regexp)
4268 (defvar org-complex-heading-regexp nil
4269 "Matches a headline and puts everything into groups:
4270 group 1: the stars
4271 group 2: The todo keyword, maybe
4272 group 3: Priority cookie
4273 group 4: True headline
4274 group 5: Tags")
4275 (make-variable-buffer-local 'org-complex-heading-regexp)
4276 (defvar org-heading-keyword-regexp-format nil
4277 "Printf format to make regexp to match an headline with some keyword.
4278 This regexp will match the headline of any node which has the
4279 exact keyword that is put into the format. The keyword isn't in
4280 any group by default, but the stars and the body are.")
4281 (make-variable-buffer-local 'org-heading-keyword-regexp-format)
4282 (defvar org-heading-keyword-maybe-regexp-format nil
4283 "Printf format to make regexp to match an headline with some keyword.
4284 This regexp can match any headline with the specified keyword, or
4285 a without a keyword. The keyword isn't in any group by default,
4286 but the stars and the body are.")
4287 (make-variable-buffer-local 'org-heading-keyword-maybe-regexp-format)
4288 (defvar org-complex-heading-regexp-format nil
4289 "Printf format to make regexp to match an exact headline.
4290 This regexp will match the headline of any node which has the
4291 exact headline text that is put into the format, but may have any
4292 TODO state, priority and tags.")
4293 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4294 (defvar org-todo-line-tags-regexp nil
4295 "Matches a headline and puts TODO state into group 2 if present.
4296 Also put tags into group 4 if tags are present.")
4297 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4298 (defvar org-ds-keyword-length 12
4299 "Maximum length of the Deadline and SCHEDULED keywords.")
4300 (make-variable-buffer-local 'org-ds-keyword-length)
4301 (defvar org-deadline-regexp nil
4302 "Matches the DEADLINE keyword.")
4303 (make-variable-buffer-local 'org-deadline-regexp)
4304 (defvar org-deadline-time-regexp nil
4305 "Matches the DEADLINE keyword together with a time stamp.")
4306 (make-variable-buffer-local 'org-deadline-time-regexp)
4307 (defvar org-deadline-line-regexp nil
4308 "Matches the DEADLINE keyword and the rest of the line.")
4309 (make-variable-buffer-local 'org-deadline-line-regexp)
4310 (defvar org-scheduled-regexp nil
4311 "Matches the SCHEDULED keyword.")
4312 (make-variable-buffer-local 'org-scheduled-regexp)
4313 (defvar org-scheduled-time-regexp nil
4314 "Matches the SCHEDULED keyword together with a time stamp.")
4315 (make-variable-buffer-local 'org-scheduled-time-regexp)
4316 (defvar org-closed-time-regexp nil
4317 "Matches the CLOSED keyword together with a time stamp.")
4318 (make-variable-buffer-local 'org-closed-time-regexp)
4320 (defvar org-keyword-time-regexp nil
4321 "Matches any of the 4 keywords, together with the time stamp.")
4322 (make-variable-buffer-local 'org-keyword-time-regexp)
4323 (defvar org-keyword-time-not-clock-regexp nil
4324 "Matches any of the 3 keywords, together with the time stamp.")
4325 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4326 (defvar org-maybe-keyword-time-regexp nil
4327 "Matches a timestamp, possibly preceded by a keyword.")
4328 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4329 (defvar org-planning-or-clock-line-re nil
4330 "Matches a line with planning or clock info.")
4331 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4332 (defvar org-all-time-keywords nil
4333 "List of time keywords.")
4334 (make-variable-buffer-local 'org-all-time-keywords)
4336 (defconst org-plain-time-of-day-regexp
4337 (concat
4338 "\\(\\<[012]?[0-9]"
4339 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4340 "\\(--?"
4341 "\\(\\<[012]?[0-9]"
4342 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4343 "\\)?")
4344 "Regular expression to match a plain time or time range.
4345 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4346 groups carry important information:
4347 0 the full match
4348 1 the first time, range or not
4349 8 the second time, if it is a range.")
4351 (defconst org-plain-time-extension-regexp
4352 (concat
4353 "\\(\\<[012]?[0-9]"
4354 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4355 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4356 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4357 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4358 groups carry important information:
4359 0 the full match
4360 7 hours of duration
4361 9 minutes of duration")
4363 (defconst org-stamp-time-of-day-regexp
4364 (concat
4365 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4366 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4367 "\\(--?"
4368 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4369 "Regular expression to match a timestamp time or time range.
4370 After a match, the following groups carry important information:
4371 0 the full match
4372 1 date plus weekday, for back referencing to make sure both times are on the same day
4373 2 the first time, range or not
4374 4 the second time, if it is a range.")
4376 (defconst org-startup-options
4377 '(("fold" org-startup-folded t)
4378 ("overview" org-startup-folded t)
4379 ("nofold" org-startup-folded nil)
4380 ("showall" org-startup-folded nil)
4381 ("showeverything" org-startup-folded showeverything)
4382 ("content" org-startup-folded content)
4383 ("indent" org-startup-indented t)
4384 ("noindent" org-startup-indented nil)
4385 ("hidestars" org-hide-leading-stars t)
4386 ("showstars" org-hide-leading-stars nil)
4387 ("odd" org-odd-levels-only t)
4388 ("oddeven" org-odd-levels-only nil)
4389 ("align" org-startup-align-all-tables t)
4390 ("noalign" org-startup-align-all-tables nil)
4391 ("inlineimages" org-startup-with-inline-images t)
4392 ("noinlineimages" org-startup-with-inline-images nil)
4393 ("customtime" org-display-custom-times t)
4394 ("logdone" org-log-done time)
4395 ("lognotedone" org-log-done note)
4396 ("nologdone" org-log-done nil)
4397 ("lognoteclock-out" org-log-note-clock-out t)
4398 ("nolognoteclock-out" org-log-note-clock-out nil)
4399 ("logrepeat" org-log-repeat state)
4400 ("lognoterepeat" org-log-repeat note)
4401 ("nologrepeat" org-log-repeat nil)
4402 ("logreschedule" org-log-reschedule time)
4403 ("lognotereschedule" org-log-reschedule note)
4404 ("nologreschedule" org-log-reschedule nil)
4405 ("logredeadline" org-log-redeadline time)
4406 ("lognoteredeadline" org-log-redeadline note)
4407 ("nologredeadline" org-log-redeadline nil)
4408 ("logrefile" org-log-refile time)
4409 ("lognoterefile" org-log-refile note)
4410 ("nologrefile" org-log-refile nil)
4411 ("fninline" org-footnote-define-inline t)
4412 ("nofninline" org-footnote-define-inline nil)
4413 ("fnlocal" org-footnote-section nil)
4414 ("fnauto" org-footnote-auto-label t)
4415 ("fnprompt" org-footnote-auto-label nil)
4416 ("fnconfirm" org-footnote-auto-label confirm)
4417 ("fnplain" org-footnote-auto-label plain)
4418 ("fnadjust" org-footnote-auto-adjust t)
4419 ("nofnadjust" org-footnote-auto-adjust nil)
4420 ("constcgs" constants-unit-system cgs)
4421 ("constSI" constants-unit-system SI)
4422 ("noptag" org-tag-persistent-alist nil)
4423 ("hideblocks" org-hide-block-startup t)
4424 ("nohideblocks" org-hide-block-startup nil)
4425 ("beamer" org-startup-with-beamer-mode t)
4426 ("entitiespretty" org-pretty-entities t)
4427 ("entitiesplain" org-pretty-entities nil))
4428 "Variable associated with STARTUP options for org-mode.
4429 Each element is a list of three items: The startup options as written
4430 in the #+STARTUP line, the corresponding variable, and the value to
4431 set this variable to if the option is found. An optional forth element PUSH
4432 means to push this value onto the list in the variable.")
4434 (defun org-set-regexps-and-options ()
4435 "Precompute regular expressions for current buffer."
4436 (when (eq major-mode 'org-mode)
4437 (org-set-local 'org-todo-kwd-alist nil)
4438 (org-set-local 'org-todo-key-alist nil)
4439 (org-set-local 'org-todo-key-trigger nil)
4440 (org-set-local 'org-todo-keywords-1 nil)
4441 (org-set-local 'org-done-keywords nil)
4442 (org-set-local 'org-todo-heads nil)
4443 (org-set-local 'org-todo-sets nil)
4444 (org-set-local 'org-todo-log-states nil)
4445 (org-set-local 'org-file-properties nil)
4446 (org-set-local 'org-file-tags nil)
4447 (let ((re (org-make-options-regexp
4448 '("CATEGORY" "TODO" "COLUMNS"
4449 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4450 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4451 "OPTIONS")
4452 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4453 (splitre "[ \t]+")
4454 (scripts org-use-sub-superscripts)
4455 kwds kws0 kwsa key log value cat arch tags const links hw dws
4456 tail sep kws1 prio props ftags drawers beamer-p
4457 ext-setup-or-nil setup-contents (start 0))
4458 (save-excursion
4459 (save-restriction
4460 (widen)
4461 (goto-char (point-min))
4462 (while (or (and ext-setup-or-nil
4463 (string-match re ext-setup-or-nil start)
4464 (setq start (match-end 0)))
4465 (and (setq ext-setup-or-nil nil start 0)
4466 (re-search-forward re nil t)))
4467 (setq key (upcase (match-string 1 ext-setup-or-nil))
4468 value (org-match-string-no-properties 2 ext-setup-or-nil))
4469 (if (stringp value) (setq value (org-trim value)))
4470 (cond
4471 ((equal key "CATEGORY")
4472 (setq cat value))
4473 ((member key '("SEQ_TODO" "TODO"))
4474 (push (cons 'sequence (org-split-string value splitre)) kwds))
4475 ((equal key "TYP_TODO")
4476 (push (cons 'type (org-split-string value splitre)) kwds))
4477 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4478 ;; general TODO-like setup
4479 (push (cons (intern (downcase (match-string 1 key)))
4480 (org-split-string value splitre)) kwds))
4481 ((equal key "TAGS")
4482 (setq tags (append tags (if tags '("\\n") nil)
4483 (org-split-string value splitre))))
4484 ((equal key "COLUMNS")
4485 (org-set-local 'org-columns-default-format value))
4486 ((equal key "LINK")
4487 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4488 (push (cons (match-string 1 value)
4489 (org-trim (match-string 2 value)))
4490 links)))
4491 ((equal key "PRIORITIES")
4492 (setq prio (org-split-string value " +")))
4493 ((equal key "PROPERTY")
4494 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4495 (push (cons (match-string 1 value) (match-string 2 value))
4496 props)))
4497 ((equal key "FILETAGS")
4498 (when (string-match "\\S-" value)
4499 (setq ftags
4500 (append
4501 ftags
4502 (apply 'append
4503 (mapcar (lambda (x) (org-split-string x ":"))
4504 (org-split-string value)))))))
4505 ((equal key "DRAWERS")
4506 (setq drawers (org-split-string value splitre)))
4507 ((equal key "CONSTANTS")
4508 (setq const (append const (org-split-string value splitre))))
4509 ((equal key "STARTUP")
4510 (let ((opts (org-split-string value splitre))
4511 l var val)
4512 (while (setq l (pop opts))
4513 (when (setq l (assoc l org-startup-options))
4514 (setq var (nth 1 l) val (nth 2 l))
4515 (if (not (nth 3 l))
4516 (set (make-local-variable var) val)
4517 (if (not (listp (symbol-value var)))
4518 (set (make-local-variable var) nil))
4519 (set (make-local-variable var) (symbol-value var))
4520 (add-to-list var val))))))
4521 ((equal key "ARCHIVE")
4522 (setq arch value)
4523 (remove-text-properties 0 (length arch)
4524 '(face t fontified t) arch))
4525 ((equal key "LATEX_CLASS")
4526 (setq beamer-p (equal value "beamer")))
4527 ((equal key "OPTIONS")
4528 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4529 (setq scripts (read (match-string 2 value)))))
4530 ((equal key "SETUPFILE")
4531 (setq setup-contents (org-file-contents
4532 (expand-file-name
4533 (org-remove-double-quotes value))
4534 'noerror))
4535 (if (not ext-setup-or-nil)
4536 (setq ext-setup-or-nil setup-contents start 0)
4537 (setq ext-setup-or-nil
4538 (concat (substring ext-setup-or-nil 0 start)
4539 "\n" setup-contents "\n"
4540 (substring ext-setup-or-nil start)))))
4541 ))))
4542 (org-set-local 'org-use-sub-superscripts scripts)
4543 (when cat
4544 (org-set-local 'org-category (intern cat))
4545 (push (cons "CATEGORY" cat) props))
4546 (when prio
4547 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4548 (setq prio (mapcar 'string-to-char prio))
4549 (org-set-local 'org-highest-priority (nth 0 prio))
4550 (org-set-local 'org-lowest-priority (nth 1 prio))
4551 (org-set-local 'org-default-priority (nth 2 prio)))
4552 (and props (org-set-local 'org-file-properties (nreverse props)))
4553 (and ftags (org-set-local 'org-file-tags
4554 (mapcar 'org-add-prop-inherited ftags)))
4555 (and drawers (org-set-local 'org-drawers drawers))
4556 (and arch (org-set-local 'org-archive-location arch))
4557 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4558 ;; Process the TODO keywords
4559 (unless kwds
4560 ;; Use the global values as if they had been given locally.
4561 (setq kwds (default-value 'org-todo-keywords))
4562 (if (stringp (car kwds))
4563 (setq kwds (list (cons org-todo-interpretation
4564 (default-value 'org-todo-keywords)))))
4565 (setq kwds (reverse kwds)))
4566 (setq kwds (nreverse kwds))
4567 (let (inter kws kw)
4568 (while (setq kws (pop kwds))
4569 (let ((kws (or
4570 (run-hook-with-args-until-success
4571 'org-todo-setup-filter-hook kws)
4572 kws)))
4573 (setq inter (pop kws) sep (member "|" kws)
4574 kws0 (delete "|" (copy-sequence kws))
4575 kwsa nil
4576 kws1 (mapcar
4577 (lambda (x)
4578 ;; 1 2
4579 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4580 (progn
4581 (setq kw (match-string 1 x)
4582 key (and (match-end 2) (match-string 2 x))
4583 log (org-extract-log-state-settings x))
4584 (push (cons kw (and key (string-to-char key))) kwsa)
4585 (and log (push log org-todo-log-states))
4587 (error "Invalid TODO keyword %s" x)))
4588 kws0)
4589 kwsa (if kwsa (append '((:startgroup))
4590 (nreverse kwsa)
4591 '((:endgroup))))
4592 hw (car kws1)
4593 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4594 tail (list inter hw (car dws) (org-last dws))))
4595 (add-to-list 'org-todo-heads hw 'append)
4596 (push kws1 org-todo-sets)
4597 (setq org-done-keywords (append org-done-keywords dws nil))
4598 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4599 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4600 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4601 (setq org-todo-sets (nreverse org-todo-sets)
4602 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4603 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4604 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4605 ;; Process the constants
4606 (when const
4607 (let (e cst)
4608 (while (setq e (pop const))
4609 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4610 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4611 (setq org-table-formula-constants-local cst)))
4613 ;; Process the tags.
4614 (when tags
4615 (let (e tgs)
4616 (while (setq e (pop tags))
4617 (cond
4618 ((equal e "{") (push '(:startgroup) tgs))
4619 ((equal e "}") (push '(:endgroup) tgs))
4620 ((equal e "\\n") (push '(:newline) tgs))
4621 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4622 (push (cons (match-string 1 e)
4623 (string-to-char (match-string 2 e)))
4624 tgs))
4625 (t (push (list e) tgs))))
4626 (org-set-local 'org-tag-alist nil)
4627 (while (setq e (pop tgs))
4628 (or (and (stringp (car e))
4629 (assoc (car e) org-tag-alist))
4630 (push e org-tag-alist)))))
4632 ;; Compute the regular expressions and other local variables.
4633 ;; Using `org-outline-regexp-bol' would complicate them much,
4634 ;; because of the fixed white space at the end of that string.
4635 (if (not org-done-keywords)
4636 (setq org-done-keywords (and org-todo-keywords-1
4637 (list (org-last org-todo-keywords-1)))))
4638 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4639 (length org-scheduled-string)
4640 (length org-clock-string)
4641 (length org-closed-string)))
4642 org-drawer-regexp
4643 (concat "^[ \t]*:\\("
4644 (mapconcat 'regexp-quote org-drawers "\\|")
4645 "\\):[ \t]*$")
4646 org-not-done-keywords
4647 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4648 org-todo-regexp
4649 (concat "\\("
4650 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4651 "\\)")
4652 org-not-done-regexp
4653 (concat "\\("
4654 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4655 "\\)")
4656 org-heading-regexp
4657 "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4658 org-heading-keyword-regexp-format
4659 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4660 org-heading-keyword-maybe-regexp-format
4661 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4662 org-not-done-heading-regexp
4663 (format org-heading-keyword-regexp-format org-not-done-regexp)
4664 org-todo-line-regexp
4665 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4666 org-complex-heading-regexp
4667 (concat "^\\(\\*+\\)"
4668 "\\(?: +" org-todo-regexp "\\)?"
4669 "\\(?: +\\(\\[#.\\]\\)\\)?"
4670 "\\(?: +\\(.*?\\)\\)?"
4671 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4672 "[ \t]*$")
4673 org-complex-heading-regexp-format
4674 (concat "^\\(\\*+\\)"
4675 "\\(?: +" org-todo-regexp "\\)?"
4676 "\\(?: +\\(\\[#.\\]\\)\\)?"
4677 "\\(?: +"
4678 ;; Stats cookies can be sticked to body.
4679 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4680 "\\(%s\\)"
4681 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4682 "\\)"
4683 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4684 "[ \t]*$")
4685 org-todo-line-tags-regexp
4686 (concat "^\\(\\*+\\)"
4687 "\\(?: +" org-todo-regexp "\\)?"
4688 "\\(?: +\\(.*?\\)\\)?"
4689 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4690 "[ \t]*$")
4691 org-deadline-regexp (concat "\\<" org-deadline-string)
4692 org-deadline-time-regexp
4693 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4694 org-deadline-line-regexp
4695 (concat "\\<\\(" org-deadline-string "\\).*")
4696 org-scheduled-regexp
4697 (concat "\\<" org-scheduled-string)
4698 org-scheduled-time-regexp
4699 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4700 org-closed-time-regexp
4701 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4702 org-keyword-time-regexp
4703 (concat "\\<\\(" org-scheduled-string
4704 "\\|" org-deadline-string
4705 "\\|" org-closed-string
4706 "\\|" org-clock-string "\\)"
4707 " *[[<]\\([^]>]+\\)[]>]")
4708 org-keyword-time-not-clock-regexp
4709 (concat "\\<\\(" org-scheduled-string
4710 "\\|" org-deadline-string
4711 "\\|" org-closed-string
4712 "\\)"
4713 " *[[<]\\([^]>]+\\)[]>]")
4714 org-maybe-keyword-time-regexp
4715 (concat "\\(\\<\\(" org-scheduled-string
4716 "\\|" org-deadline-string
4717 "\\|" org-closed-string
4718 "\\|" org-clock-string "\\)\\)?"
4719 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4720 org-planning-or-clock-line-re
4721 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4722 "\\|" org-deadline-string
4723 "\\|" org-closed-string "\\|" org-clock-string
4724 "\\)\\>\\)")
4725 org-all-time-keywords
4726 (mapcar (lambda (w) (substring w 0 -1))
4727 (list org-scheduled-string org-deadline-string
4728 org-clock-string org-closed-string))
4730 (org-compute-latex-and-specials-regexp)
4731 (org-set-font-lock-defaults))))
4733 (defun org-file-contents (file &optional noerror)
4734 "Return the contents of FILE, as a string."
4735 (if (or (not file)
4736 (not (file-readable-p file)))
4737 (if noerror
4738 (progn
4739 (message "Cannot read file \"%s\"" file)
4740 (ding) (sit-for 2)
4742 (error "Cannot read file \"%s\"" file))
4743 (with-temp-buffer
4744 (insert-file-contents file)
4745 (buffer-string))))
4747 (defun org-extract-log-state-settings (x)
4748 "Extract the log state setting from a TODO keyword string.
4749 This will extract info from a string like \"WAIT(w@/!)\"."
4750 (let (kw key log1 log2)
4751 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4752 (setq kw (match-string 1 x)
4753 key (and (match-end 2) (match-string 2 x))
4754 log1 (and (match-end 3) (match-string 3 x))
4755 log2 (and (match-end 4) (match-string 4 x)))
4756 (and (or log1 log2)
4757 (list kw
4758 (and log1 (if (equal log1 "!") 'time 'note))
4759 (and log2 (if (equal log2 "!") 'time 'note)))))))
4761 (defun org-remove-keyword-keys (list)
4762 "Remove a pair of parenthesis at the end of each string in LIST."
4763 (mapcar (lambda (x)
4764 (if (string-match "(.*)$" x)
4765 (substring x 0 (match-beginning 0))
4767 list))
4769 (defun org-assign-fast-keys (alist)
4770 "Assign fast keys to a keyword-key alist.
4771 Respect keys that are already there."
4772 (let (new e (alt ?0))
4773 (while (setq e (pop alist))
4774 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4775 (cdr e)) ;; Key already assigned.
4776 (push e new)
4777 (let ((clist (string-to-list (downcase (car e))))
4778 (used (append new alist)))
4779 (when (= (car clist) ?@)
4780 (pop clist))
4781 (while (and clist (rassoc (car clist) used))
4782 (pop clist))
4783 (unless clist
4784 (while (rassoc alt used)
4785 (incf alt)))
4786 (push (cons (car e) (or (car clist) alt)) new))))
4787 (nreverse new)))
4789 ;;; Some variables used in various places
4791 (defvar org-window-configuration nil
4792 "Used in various places to store a window configuration.")
4793 (defvar org-selected-window nil
4794 "Used in various places to store a window configuration.")
4795 (defvar org-finish-function nil
4796 "Function to be called when `C-c C-c' is used.
4797 This is for getting out of special buffers like remember.")
4800 ;; FIXME: Occasionally check by commenting these, to make sure
4801 ;; no other functions uses these, forgetting to let-bind them.
4802 (defvar entry)
4803 (defvar last-state)
4804 (defvar date)
4806 ;; Defined somewhere in this file, but used before definition.
4807 (defvar org-entities) ;; defined in org-entities.el
4808 (defvar org-struct-menu)
4809 (defvar org-org-menu)
4810 (defvar org-tbl-menu)
4812 ;;;; Define the Org-mode
4814 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4815 (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"))
4818 ;; We use a before-change function to check if a table might need
4819 ;; an update.
4820 (defvar org-table-may-need-update t
4821 "Indicates that a table might need an update.
4822 This variable is set by `org-before-change-function'.
4823 `org-table-align' sets it back to nil.")
4824 (defun org-before-change-function (beg end)
4825 "Every change indicates that a table might need an update."
4826 (setq org-table-may-need-update t))
4827 (defvar org-mode-map)
4828 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4829 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4830 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4831 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4832 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4833 (defvar org-table-buffer-is-an nil)
4835 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
4836 ;; some places -- e.g. see the macro org-with-limited-levels.
4838 ;; In Org buffers, the value of `outline-regexp' is that of
4839 ;; `org-outline-regexp'. The only function still directly relying on
4840 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
4841 ;; job when `orgstruct-mode' is active.
4842 (defvar org-outline-regexp "\\*+ "
4843 "Regexp to match Org headlines.")
4844 (defconst org-outline-regexp-bol "^\\*+ "
4845 "Regexp to match Org headlines.
4846 This is similar to `org-outline-regexp' but additionally makes
4847 sure that we are at the beginning of the line.")
4849 ;;;###autoload
4850 (define-derived-mode org-mode outline-mode "Org"
4851 "Outline-based notes management and organizer, alias
4852 \"Carsten's outline-mode for keeping track of everything.\"
4854 Org-mode develops organizational tasks around a NOTES file which
4855 contains information about projects as plain text. Org-mode is
4856 implemented on top of outline-mode, which is ideal to keep the content
4857 of large files well structured. It supports ToDo items, deadlines and
4858 time stamps, which magically appear in the diary listing of the Emacs
4859 calendar. Tables are easily created with a built-in table editor.
4860 Plain text URL-like links connect to websites, emails (VM), Usenet
4861 messages (Gnus), BBDB entries, and any files related to the project.
4862 For printing and sharing of notes, an Org-mode file (or a part of it)
4863 can be exported as a structured ASCII or HTML file.
4865 The following commands are available:
4867 \\{org-mode-map}"
4869 ;; Get rid of Outline menus, they are not needed
4870 ;; Need to do this here because define-derived-mode sets up
4871 ;; the keymap so late. Still, it is a waste to call this each time
4872 ;; we switch another buffer into org-mode.
4873 (if (featurep 'xemacs)
4874 (when (boundp 'outline-mode-menu-heading)
4875 ;; Assume this is Greg's port, it uses easymenu
4876 (easy-menu-remove outline-mode-menu-heading)
4877 (easy-menu-remove outline-mode-menu-show)
4878 (easy-menu-remove outline-mode-menu-hide))
4879 (define-key org-mode-map [menu-bar headings] 'undefined)
4880 (define-key org-mode-map [menu-bar hide] 'undefined)
4881 (define-key org-mode-map [menu-bar show] 'undefined))
4883 (org-load-modules-maybe)
4884 (easy-menu-add org-org-menu)
4885 (easy-menu-add org-tbl-menu)
4886 (org-install-agenda-files-menu)
4887 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4888 (add-to-invisibility-spec '(org-cwidth))
4889 (add-to-invisibility-spec '(org-hide-block . t))
4890 (when (featurep 'xemacs)
4891 (org-set-local 'line-move-ignore-invisible t))
4892 (org-set-local 'outline-regexp org-outline-regexp)
4893 (org-set-local 'outline-level 'org-outline-level)
4894 (setq bidi-paragraph-direction 'left-to-right)
4895 (when (and org-ellipsis
4896 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4897 (fboundp 'make-glyph-code))
4898 (unless org-display-table
4899 (setq org-display-table (make-display-table)))
4900 (set-display-table-slot
4901 org-display-table 4
4902 (vconcat (mapcar
4903 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4904 org-ellipsis)))
4905 (if (stringp org-ellipsis) org-ellipsis "..."))))
4906 (setq buffer-display-table org-display-table))
4907 (org-set-regexps-and-options)
4908 (when (and org-tag-faces (not org-tags-special-faces-re))
4909 ;; tag faces set outside customize.... force initialization.
4910 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4911 ;; Calc embedded
4912 (org-set-local 'calc-embedded-open-mode "# ")
4913 (modify-syntax-entry ?@ "w")
4914 (if org-startup-truncated (setq truncate-lines t))
4915 (org-set-local 'font-lock-unfontify-region-function
4916 'org-unfontify-region)
4917 ;; Activate before-change-function
4918 (org-set-local 'org-table-may-need-update t)
4919 (org-add-hook 'before-change-functions 'org-before-change-function nil
4920 'local)
4921 ;; Check for running clock before killing a buffer
4922 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4923 ;; Paragraphs and auto-filling
4924 (org-set-autofill-regexps)
4925 (setq indent-line-function 'org-indent-line-function)
4926 (org-update-radio-target-regexp)
4927 ;; Beginning/end of defun
4928 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
4929 (org-set-local 'end-of-defun-function 'org-end-of-defun)
4930 ;; Next error for sparse trees
4931 (org-set-local 'next-error-function 'org-occur-next-match)
4932 ;; Make sure dependence stuff works reliably, even for users who set it
4933 ;; too late :-(
4934 (if org-enforce-todo-dependencies
4935 (add-hook 'org-blocker-hook
4936 'org-block-todo-from-children-or-siblings-or-parent)
4937 (remove-hook 'org-blocker-hook
4938 'org-block-todo-from-children-or-siblings-or-parent))
4939 (if org-enforce-todo-checkbox-dependencies
4940 (add-hook 'org-blocker-hook
4941 'org-block-todo-from-checkboxes)
4942 (remove-hook 'org-blocker-hook
4943 'org-block-todo-from-checkboxes))
4945 ;; Comment characters
4946 (org-set-local 'comment-start "#")
4947 (org-set-local 'comment-padding " ")
4949 ;; Align options lines
4950 (org-set-local
4951 'align-mode-rules-list
4952 '((org-in-buffer-settings
4953 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4954 (modes . '(org-mode)))))
4956 ;; Imenu
4957 (org-set-local 'imenu-create-index-function
4958 'org-imenu-get-tree)
4960 ;; Make isearch reveal context
4961 (if (or (featurep 'xemacs)
4962 (not (boundp 'outline-isearch-open-invisible-function)))
4963 ;; Emacs 21 and XEmacs make use of the hook
4964 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4965 ;; Emacs 22 deals with this through a special variable
4966 (org-set-local 'outline-isearch-open-invisible-function
4967 (lambda (&rest ignore) (org-show-context 'isearch))))
4969 ;; Turn on org-beamer-mode?
4970 (and org-startup-with-beamer-mode (org-beamer-mode 1))
4972 ;; Setup the pcomplete hooks
4973 (set (make-local-variable 'pcomplete-command-completion-function)
4974 'org-pcomplete-initial)
4975 (set (make-local-variable 'pcomplete-command-name-function)
4976 'org-command-at-point)
4977 (set (make-local-variable 'pcomplete-default-completion-function)
4978 'ignore)
4979 (set (make-local-variable 'pcomplete-parse-arguments-function)
4980 'org-parse-arguments)
4981 (set (make-local-variable 'pcomplete-termination-string) "")
4982 (set (make-local-variable 'face-remapping-alist)
4983 '((default org-default)))
4985 ;; If empty file that did not turn on org-mode automatically, make it to.
4986 (if (and org-insert-mode-line-in-empty-file
4987 (org-called-interactively-p 'any)
4988 (= (point-min) (point-max)))
4989 (insert "# -*- mode: org -*-\n\n"))
4990 (unless org-inhibit-startup
4991 (when org-startup-align-all-tables
4992 (let ((bmp (buffer-modified-p)))
4993 (org-table-map-tables 'org-table-align 'quietly)
4994 (set-buffer-modified-p bmp)))
4995 (when org-startup-with-inline-images
4996 (org-display-inline-images))
4997 (when org-startup-indented
4998 (require 'org-indent)
4999 (org-indent-mode 1))
5000 (unless org-inhibit-startup-visibility-stuff
5001 (org-set-startup-visibility))))
5003 (when (fboundp 'abbrev-table-put)
5004 (abbrev-table-put org-mode-abbrev-table
5005 :parents (list text-mode-abbrev-table)))
5007 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5009 (defun org-current-time ()
5010 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5011 (if (> (car org-time-stamp-rounding-minutes) 1)
5012 (let ((r (car org-time-stamp-rounding-minutes))
5013 (time (decode-time)))
5014 (apply 'encode-time
5015 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5016 (nthcdr 2 time))))
5017 (current-time)))
5019 (defun org-today ()
5020 "Return today date, considering `org-extend-today-until'."
5021 (time-to-days
5022 (time-subtract (current-time)
5023 (list 0 (* 3600 org-extend-today-until) 0))))
5025 ;;;; Font-Lock stuff, including the activators
5027 (defvar org-mouse-map (make-sparse-keymap))
5028 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5029 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5030 (when org-mouse-1-follows-link
5031 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5032 (when org-tab-follows-link
5033 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5034 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5036 (require 'font-lock)
5038 (defconst org-non-link-chars "]\t\n\r<>")
5039 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5040 "shell" "elisp" "doi" "message"))
5041 (defvar org-link-types-re nil
5042 "Matches a link that has a url-like prefix like \"http:\"")
5043 (defvar org-link-re-with-space nil
5044 "Matches a link with spaces, optional angular brackets around it.")
5045 (defvar org-link-re-with-space2 nil
5046 "Matches a link with spaces, optional angular brackets around it.")
5047 (defvar org-link-re-with-space3 nil
5048 "Matches a link with spaces, only for internal part in bracket links.")
5049 (defvar org-angle-link-re nil
5050 "Matches link with angular brackets, spaces are allowed.")
5051 (defvar org-plain-link-re nil
5052 "Matches plain link, without spaces.")
5053 (defvar org-bracket-link-regexp nil
5054 "Matches a link in double brackets.")
5055 (defvar org-bracket-link-analytic-regexp nil
5056 "Regular expression used to analyze links.
5057 Here is what the match groups contain after a match:
5058 1: http:
5059 2: http
5060 3: path
5061 4: [desc]
5062 5: desc")
5063 (defvar org-bracket-link-analytic-regexp++ nil
5064 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5065 (defvar org-any-link-re nil
5066 "Regular expression matching any link.")
5068 (defcustom org-match-sexp-depth 3
5069 "Number of stacked braces for sub/superscript matching.
5070 This has to be set before loading org.el to be effective."
5071 :group 'org-export-translation ; ??????????????????????????/
5072 :type 'integer)
5074 (defun org-create-multibrace-regexp (left right n)
5075 "Create a regular expression which will match a balanced sexp.
5076 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5077 as single character strings.
5078 The regexp returned will match the entire expression including the
5079 delimiters. It will also define a single group which contains the
5080 match except for the outermost delimiters. The maximum depth of
5081 stacked delimiters is N. Escaping delimiters is not possible."
5082 (let* ((nothing (concat "[^" left right "]*?"))
5083 (or "\\|")
5084 (re nothing)
5085 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5086 (while (> n 1)
5087 (setq n (1- n)
5088 re (concat re or next)
5089 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5090 (concat left "\\(" re "\\)" right)))
5092 (defvar org-match-substring-regexp
5093 (concat
5094 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5095 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5096 "\\|"
5097 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5098 "\\|"
5099 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5100 "The regular expression matching a sub- or superscript.")
5102 (defvar org-match-substring-with-braces-regexp
5103 (concat
5104 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5105 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5106 "\\)")
5107 "The regular expression matching a sub- or superscript, forcing braces.")
5109 (defun org-make-link-regexps ()
5110 "Update the link regular expressions.
5111 This should be called after the variable `org-link-types' has changed."
5112 (setq org-link-types-re
5113 (concat
5114 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5115 org-link-re-with-space
5116 (concat
5117 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5118 "\\([^" org-non-link-chars " ]"
5119 "[^" org-non-link-chars "]*"
5120 "[^" org-non-link-chars " ]\\)>?")
5121 org-link-re-with-space2
5122 (concat
5123 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5124 "\\([^" org-non-link-chars " ]"
5125 "[^\t\n\r]*"
5126 "[^" org-non-link-chars " ]\\)>?")
5127 org-link-re-with-space3
5128 (concat
5129 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5130 "\\([^" org-non-link-chars " ]"
5131 "[^\t\n\r]*\\)")
5132 org-angle-link-re
5133 (concat
5134 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5135 "\\([^" org-non-link-chars " ]"
5136 "[^" org-non-link-chars "]*"
5137 "\\)>")
5138 org-plain-link-re
5139 (concat
5140 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5141 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5142 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5143 org-bracket-link-regexp
5144 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5145 org-bracket-link-analytic-regexp
5146 (concat
5147 "\\[\\["
5148 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5149 "\\([^]]+\\)"
5150 "\\]"
5151 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5152 "\\]")
5153 org-bracket-link-analytic-regexp++
5154 (concat
5155 "\\[\\["
5156 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5157 "\\([^]]+\\)"
5158 "\\]"
5159 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5160 "\\]")
5161 org-any-link-re
5162 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5163 org-angle-link-re "\\)\\|\\("
5164 org-plain-link-re "\\)")))
5166 (org-make-link-regexps)
5168 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
5169 "Regular expression for fast time stamp matching.")
5170 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?\\)[]>]"
5171 "Regular expression for fast time stamp matching.")
5172 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5173 "Regular expression matching time strings for analysis.
5174 This one does not require the space after the date, so it can be used
5175 on a string that terminates immediately after the date.")
5176 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5177 "Regular expression matching time strings for analysis.")
5178 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5179 "Regular expression matching time stamps, with groups.")
5180 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5181 "Regular expression matching time stamps (also [..]), with groups.")
5182 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5183 "Regular expression matching a time stamp range.")
5184 (defconst org-tr-regexp-both
5185 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5186 "Regular expression matching a time stamp range.")
5187 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5188 org-ts-regexp "\\)?")
5189 "Regular expression matching a time stamp or time stamp range.")
5190 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5191 org-ts-regexp-both "\\)?")
5192 "Regular expression matching a time stamp or time stamp range.
5193 The time stamps may be either active or inactive.")
5195 (defvar org-emph-face nil)
5197 (defun org-do-emphasis-faces (limit)
5198 "Run through the buffer and add overlays to emphasised strings."
5199 (let (rtn a)
5200 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5201 (if (not (= (char-after (match-beginning 3))
5202 (char-after (match-beginning 4))))
5203 (progn
5204 (setq rtn t)
5205 (setq a (assoc (match-string 3) org-emphasis-alist))
5206 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5207 'face
5208 (nth 1 a))
5209 (and (nth 4 a)
5210 (org-remove-flyspell-overlays-in
5211 (match-beginning 0) (match-end 0)))
5212 (add-text-properties (match-beginning 2) (match-end 2)
5213 '(font-lock-multiline t org-emphasis t))
5214 (when org-hide-emphasis-markers
5215 (add-text-properties (match-end 4) (match-beginning 5)
5216 '(invisible org-link))
5217 (add-text-properties (match-beginning 3) (match-end 3)
5218 '(invisible org-link)))))
5219 (backward-char 1))
5220 rtn))
5222 (defun org-emphasize (&optional char)
5223 "Insert or change an emphasis, i.e. a font like bold or italic.
5224 If there is an active region, change that region to a new emphasis.
5225 If there is no region, just insert the marker characters and position
5226 the cursor between them.
5227 CHAR should be either the marker character, or the first character of the
5228 HTML tag associated with that emphasis. If CHAR is a space, the means
5229 to remove the emphasis of the selected region.
5230 If char is not given (for example in an interactive call) it
5231 will be prompted for."
5232 (interactive)
5233 (let ((eal org-emphasis-alist) e det
5234 (erc org-emphasis-regexp-components)
5235 (prompt "")
5236 (string "") beg end move tag c s)
5237 (if (org-region-active-p)
5238 (setq beg (region-beginning) end (region-end)
5239 string (buffer-substring beg end))
5240 (setq move t))
5242 (while (setq e (pop eal))
5243 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5244 c (aref tag 0))
5245 (push (cons c (string-to-char (car e))) det)
5246 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5247 (substring tag 1)))))
5248 (setq det (nreverse det))
5249 (unless char
5250 (message "%s" (concat "Emphasis marker or tag:" prompt))
5251 (setq char (read-char-exclusive)))
5252 (setq char (or (cdr (assoc char det)) char))
5253 (if (equal char ?\ )
5254 (setq s "" move nil)
5255 (unless (assoc (char-to-string char) org-emphasis-alist)
5256 (error "No such emphasis marker: \"%c\"" char))
5257 (setq s (char-to-string char)))
5258 (while (and (> (length string) 1)
5259 (equal (substring string 0 1) (substring string -1))
5260 (assoc (substring string 0 1) org-emphasis-alist))
5261 (setq string (substring string 1 -1)))
5262 (setq string (concat s string s))
5263 (if beg (delete-region beg end))
5264 (unless (or (bolp)
5265 (string-match (concat "[" (nth 0 erc) "\n]")
5266 (char-to-string (char-before (point)))))
5267 (insert " "))
5268 (unless (or (eobp)
5269 (string-match (concat "[" (nth 1 erc) "\n]")
5270 (char-to-string (char-after (point)))))
5271 (insert " ") (backward-char 1))
5272 (insert string)
5273 (and move (backward-char 1))))
5275 (defconst org-nonsticky-props
5276 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5278 (defsubst org-rear-nonsticky-at (pos)
5279 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5281 (defun org-activate-plain-links (limit)
5282 "Run through the buffer and add overlays to links."
5283 (catch 'exit
5284 (let (f)
5285 (if (re-search-forward org-plain-link-re limit t)
5286 (progn
5287 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5288 (setq f (get-text-property (match-beginning 0) 'face))
5289 (if (or (eq f 'org-tag)
5290 (and (listp f) (memq 'org-tag f)))
5292 (add-text-properties (match-beginning 0) (match-end 0)
5293 (list 'mouse-face 'highlight
5294 'face 'org-link
5295 'keymap org-mouse-map))
5296 (org-rear-nonsticky-at (match-end 0)))
5297 t)))))
5299 (defun org-activate-code (limit)
5300 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5301 (progn
5302 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5303 (remove-text-properties (match-beginning 0) (match-end 0)
5304 '(display t invisible t intangible t))
5305 t)))
5307 (defcustom org-src-fontify-natively nil
5308 "When non-nil, fontify code in code blocks."
5309 :type 'boolean
5310 :group 'org-appearance
5311 :group 'org-babel)
5313 (defun org-fontify-meta-lines-and-blocks (limit)
5314 (condition-case nil
5315 (org-fontify-meta-lines-and-blocks-1 limit)
5316 (error (message "org-mode fontification error"))))
5318 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5319 "Fontify #+ lines and blocks, in the correct ways."
5320 (let ((case-fold-search t))
5321 (if (re-search-forward
5322 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5323 limit t)
5324 (let ((beg (match-beginning 0))
5325 (block-start (match-end 0))
5326 (block-end nil)
5327 (lang (match-string 7))
5328 (beg1 (line-beginning-position 2))
5329 (dc1 (downcase (match-string 2)))
5330 (dc3 (downcase (match-string 3)))
5331 end end1 quoting block-type ovl)
5332 (cond
5333 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
5334 ;; a single line of backend-specific content
5335 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5336 (remove-text-properties (match-beginning 0) (match-end 0)
5337 '(display t invisible t intangible t))
5338 (add-text-properties (match-beginning 1) (match-end 3)
5339 '(font-lock-fontified t face org-meta-line))
5340 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5341 '(font-lock-fontified t face org-block))
5342 ; for backend-specific code
5344 ((and (match-end 4) (equal dc3 "begin"))
5345 ;; Truly a block
5346 (setq block-type (downcase (match-string 5))
5347 quoting (member block-type org-protecting-blocks))
5348 (when (re-search-forward
5349 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5350 nil t) ;; on purpose, we look further than LIMIT
5351 (setq end (match-end 0) end1 (1- (match-beginning 0)))
5352 (setq block-end (match-beginning 0))
5353 (when quoting
5354 (remove-text-properties beg end
5355 '(display t invisible t intangible t)))
5356 (add-text-properties
5357 beg end
5358 '(font-lock-fontified t font-lock-multiline t))
5359 (add-text-properties beg beg1 '(face org-meta-line))
5360 (add-text-properties end1 (min (point-max) (1+ end))
5361 '(face org-meta-line)) ; for end_src
5362 (cond
5363 ((and lang (not (string= lang "")) org-src-fontify-natively)
5364 (org-src-font-lock-fontify-block lang block-start block-end)
5365 ;; remove old background overlays
5366 (mapc (lambda (ov)
5367 (if (eq (overlay-get ov 'face) 'org-block-background)
5368 (delete-overlay ov)))
5369 (overlays-at (/ (+ beg1 block-end) 2)))
5370 ;; add a background overlay
5371 (setq ovl (make-overlay beg1 block-end))
5372 (overlay-put ovl 'face 'org-block-background)
5373 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5374 (quoting
5375 (add-text-properties beg1 (min (point-max) (1+ end1))
5376 '(face org-block))) ; end of source block
5377 ((not org-fontify-quote-and-verse-blocks))
5378 ((string= block-type "quote")
5379 (add-text-properties beg1 (1+ end1) '(face org-quote)))
5380 ((string= block-type "verse")
5381 (add-text-properties beg1 (1+ end1) '(face org-verse))))
5382 (add-text-properties beg beg1 '(face org-block-begin-line))
5383 (add-text-properties (1+ end) (1+ end1) '(face org-block-end-line))
5385 ((member dc1 '("title:" "author:" "email:" "date:"))
5386 (add-text-properties
5387 beg (match-end 3)
5388 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5389 '(font-lock-fontified t invisible t)
5390 '(font-lock-fontified t face org-document-info-keyword)))
5391 (add-text-properties
5392 (match-beginning 6) (match-end 6)
5393 (if (string-equal dc1 "title:")
5394 '(font-lock-fontified t face org-document-title)
5395 '(font-lock-fontified t face org-document-info))))
5396 ((not (member (char-after beg) '(?\ ?\t)))
5397 ;; just any other in-buffer setting, but not indented
5398 (add-text-properties
5399 beg (1+ (match-end 0))
5400 '(font-lock-fontified t face org-meta-line))
5402 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
5403 "orgtbl:" "tblfm:" "tblname:" "result:"
5404 "results:" "source:" "srcname:" "call:"
5405 "data:" "header:" "headers:"))
5406 (and (match-end 4) (equal dc3 "attr")))
5407 (add-text-properties
5408 beg (match-end 0)
5409 '(font-lock-fontified t face org-meta-line))
5411 ((member dc3 '(" " ""))
5412 (add-text-properties
5413 beg (match-end 0)
5414 '(font-lock-fontified t face font-lock-comment-face)))
5415 (t nil))))))
5417 (defun org-activate-angle-links (limit)
5418 "Run through the buffer and add overlays to links."
5419 (if (re-search-forward org-angle-link-re limit t)
5420 (progn
5421 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5422 (add-text-properties (match-beginning 0) (match-end 0)
5423 (list 'mouse-face 'highlight
5424 'keymap org-mouse-map))
5425 (org-rear-nonsticky-at (match-end 0))
5426 t)))
5428 (defun org-activate-footnote-links (limit)
5429 "Run through the buffer and add overlays to footnotes."
5430 (let ((fn (org-footnote-next-reference-or-definition limit)))
5431 (when fn
5432 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5433 (org-remove-flyspell-overlays-in beg end)
5434 (add-text-properties beg end
5435 (list 'mouse-face 'highlight
5436 'keymap org-mouse-map
5437 'help-echo
5438 (if (= (point-at-bol) beg)
5439 "Footnote definition"
5440 "Footnote reference")
5441 'font-lock-fontified t
5442 'font-lock-multiline t
5443 'face 'org-footnote))))))
5445 (defun org-activate-bracket-links (limit)
5446 "Run through the buffer and add overlays to bracketed links."
5447 (if (re-search-forward org-bracket-link-regexp limit t)
5448 (let* ((help (concat "LINK: "
5449 (org-match-string-no-properties 1)))
5450 ;; FIXME: above we should remove the escapes.
5451 ;; but that requires another match, protecting match data,
5452 ;; a lot of overhead for font-lock.
5453 (ip (org-maybe-intangible
5454 (list 'invisible 'org-link
5455 'keymap org-mouse-map 'mouse-face 'highlight
5456 'font-lock-multiline t 'help-echo help)))
5457 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5458 'font-lock-multiline t 'help-echo help)))
5459 ;; We need to remove the invisible property here. Table narrowing
5460 ;; may have made some of this invisible.
5461 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5462 (remove-text-properties (match-beginning 0) (match-end 0)
5463 '(invisible nil))
5464 (if (match-end 3)
5465 (progn
5466 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5467 (org-rear-nonsticky-at (match-beginning 3))
5468 (add-text-properties (match-beginning 3) (match-end 3) vp)
5469 (org-rear-nonsticky-at (match-end 3))
5470 (add-text-properties (match-end 3) (match-end 0) ip)
5471 (org-rear-nonsticky-at (match-end 0)))
5472 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5473 (org-rear-nonsticky-at (match-beginning 1))
5474 (add-text-properties (match-beginning 1) (match-end 1) vp)
5475 (org-rear-nonsticky-at (match-end 1))
5476 (add-text-properties (match-end 1) (match-end 0) ip)
5477 (org-rear-nonsticky-at (match-end 0)))
5478 t)))
5480 (defun org-activate-dates (limit)
5481 "Run through the buffer and add overlays to dates."
5482 (if (re-search-forward org-tsr-regexp-both limit t)
5483 (progn
5484 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5485 (add-text-properties (match-beginning 0) (match-end 0)
5486 (list 'mouse-face 'highlight
5487 'keymap org-mouse-map))
5488 (org-rear-nonsticky-at (match-end 0))
5489 (when org-display-custom-times
5490 (if (match-end 3)
5491 (org-display-custom-time (match-beginning 3) (match-end 3)))
5492 (org-display-custom-time (match-beginning 1) (match-end 1)))
5493 t)))
5495 (defvar org-target-link-regexp nil
5496 "Regular expression matching radio targets in plain text.")
5497 (make-variable-buffer-local 'org-target-link-regexp)
5498 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5499 "Regular expression matching a link target.")
5500 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5501 "Regular expression matching a radio target.")
5502 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5503 "Regular expression matching any target.")
5505 (defun org-activate-target-links (limit)
5506 "Run through the buffer and add overlays to target matches."
5507 (when org-target-link-regexp
5508 (let ((case-fold-search t))
5509 (if (re-search-forward org-target-link-regexp limit t)
5510 (progn
5511 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5512 (add-text-properties (match-beginning 0) (match-end 0)
5513 (list 'mouse-face 'highlight
5514 'keymap org-mouse-map
5515 'help-echo "Radio target link"
5516 'org-linked-text t))
5517 (org-rear-nonsticky-at (match-end 0))
5518 t)))))
5520 (defun org-update-radio-target-regexp ()
5521 "Find all radio targets in this file and update the regular expression."
5522 (interactive)
5523 (when (memq 'radio org-activate-links)
5524 (setq org-target-link-regexp
5525 (org-make-target-link-regexp (org-all-targets 'radio)))
5526 (org-restart-font-lock)))
5528 (defun org-hide-wide-columns (limit)
5529 (let (s e)
5530 (setq s (text-property-any (point) (or limit (point-max))
5531 'org-cwidth t))
5532 (when s
5533 (setq e (next-single-property-change s 'org-cwidth))
5534 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5535 (goto-char e)
5536 t)))
5538 (defvar org-latex-and-specials-regexp nil
5539 "Regular expression for highlighting export special stuff.")
5540 (defvar org-match-substring-regexp)
5541 (defvar org-match-substring-with-braces-regexp)
5543 ;; This should be with the exporter code, but we also use if for font-locking
5544 (defconst org-export-html-special-string-regexps
5545 '(("\\\\-" . "&shy;")
5546 ("---\\([^-]\\)" . "&mdash;\\1")
5547 ("--\\([^-]\\)" . "&ndash;\\1")
5548 ("\\.\\.\\." . "&hellip;"))
5549 "Regular expressions for special string conversion.")
5552 (defun org-compute-latex-and-specials-regexp ()
5553 "Compute regular expression for stuff treated specially by exporters."
5554 (if (not org-highlight-latex-fragments-and-specials)
5555 (org-set-local 'org-latex-and-specials-regexp nil)
5556 (require 'org-exp)
5557 (let*
5558 ((matchers (plist-get org-format-latex-options :matchers))
5559 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5560 org-latex-regexps)))
5561 (org-export-allow-BIND nil)
5562 (options (org-combine-plists (org-default-export-plist)
5563 (org-infile-export-plist)))
5564 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5565 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5566 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5567 (org-export-html-expand (plist-get options :expand-quoted-html))
5568 (org-export-with-special-strings (plist-get options :special-strings))
5569 (re-sub
5570 (cond
5571 ((equal org-export-with-sub-superscripts '{})
5572 (list org-match-substring-with-braces-regexp))
5573 (org-export-with-sub-superscripts
5574 (list org-match-substring-regexp))
5575 (t nil)))
5576 (re-latex
5577 (if org-export-with-LaTeX-fragments
5578 (mapcar (lambda (x) (nth 1 x)) latexs)))
5579 (re-macros
5580 (if org-export-with-TeX-macros
5581 (list (concat "\\\\"
5582 (regexp-opt
5583 (append
5585 (delq nil
5586 (mapcar 'car-safe
5587 (append org-entities-user
5588 org-entities)))
5589 (if (boundp 'org-latex-entities)
5590 (mapcar (lambda (x)
5591 (or (car-safe x) x))
5592 org-latex-entities)
5593 nil))
5594 'words))) ; FIXME
5596 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5597 (re-special (if org-export-with-special-strings
5598 (mapcar (lambda (x) (car x))
5599 org-export-html-special-string-regexps)))
5600 (re-rest
5601 (delq nil
5602 (list
5603 (if org-export-html-expand "@<[^>\n]+>")
5604 ))))
5605 (org-set-local
5606 'org-latex-and-specials-regexp
5607 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5608 re-rest) "\\|")))))
5610 (defun org-do-latex-and-special-faces (limit)
5611 "Run through the buffer and add overlays to links."
5612 (when org-latex-and-specials-regexp
5613 (let (rtn d)
5614 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5615 limit t))
5616 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5617 'face))
5618 '(org-code org-verbatim underline)))
5619 (progn
5620 (setq rtn t
5621 d (cond ((member (char-after (1+ (match-beginning 0)))
5622 '(?_ ?^)) 1)
5623 (t 0)))
5624 (font-lock-prepend-text-property
5625 (+ d (match-beginning 0)) (match-end 0)
5626 'face 'org-latex-and-export-specials)
5627 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5628 '(font-lock-multiline t)))))
5629 rtn)))
5631 (defun org-restart-font-lock ()
5632 "Restart `font-lock-mode', to force refontification."
5633 (when (and (boundp 'font-lock-mode) font-lock-mode)
5634 (font-lock-mode -1)
5635 (font-lock-mode 1)))
5637 (defun org-all-targets (&optional radio)
5638 "Return a list of all targets in this file.
5639 With optional argument RADIO, only find radio targets."
5640 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5641 rtn)
5642 (save-excursion
5643 (goto-char (point-min))
5644 (while (re-search-forward re nil t)
5645 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5646 rtn)))
5648 (defun org-make-target-link-regexp (targets)
5649 "Make regular expression matching all strings in TARGETS.
5650 The regular expression finds the targets also if there is a line break
5651 between words."
5652 (and targets
5653 (concat
5654 "\\<\\("
5655 (mapconcat
5656 (lambda (x)
5657 (setq x (regexp-quote x))
5658 (while (string-match " +" x)
5659 (setq x (replace-match "\\s-+" t t x)))
5661 targets
5662 "\\|")
5663 "\\)\\>")))
5665 (defun org-activate-tags (limit)
5666 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5667 (progn
5668 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5669 (add-text-properties (match-beginning 1) (match-end 1)
5670 (list 'mouse-face 'highlight
5671 'keymap org-mouse-map))
5672 (org-rear-nonsticky-at (match-end 1))
5673 t)))
5675 (defun org-outline-level ()
5676 "Compute the outline level of the heading at point.
5677 This function assumes that the cursor is at the beginning of a line matched
5678 by `outline-regexp'. Otherwise it returns garbage.
5679 If this is called at a normal headline, the level is the number of stars.
5680 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5681 (save-excursion
5682 (looking-at org-outline-regexp)
5683 (1- (- (match-end 0) (match-beginning 0)))))
5685 (defvar org-font-lock-keywords nil)
5687 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5688 "Regular expression matching a property line.")
5690 (defvar org-font-lock-hook nil
5691 "Functions to be called for special font lock stuff.")
5693 (defvar org-font-lock-set-keywords-hook nil
5694 "Functions that can manipulate `org-font-lock-extra-keywords'.
5695 This is calles after `org-font-lock-extra-keywords' is defined, but before
5696 it is installed to be used by font lock. This can be useful if something
5697 needs to be inserted at a specific position in the font-lock sequence.")
5699 (defun org-font-lock-hook (limit)
5700 (run-hook-with-args 'org-font-lock-hook limit))
5702 (defun org-set-font-lock-defaults ()
5703 (let* ((em org-fontify-emphasized-text)
5704 (lk org-activate-links)
5705 (org-font-lock-extra-keywords
5706 (list
5707 ;; Call the hook
5708 '(org-font-lock-hook)
5709 ;; Headlines
5710 `(,(if org-fontify-whole-heading-line
5711 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5712 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5713 (1 (org-get-level-face 1))
5714 (2 (org-get-level-face 2))
5715 (3 (org-get-level-face 3)))
5716 ;; Table lines
5717 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5718 (1 'org-table t))
5719 ;; Table internals
5720 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5721 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5722 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5723 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5724 ;; Drawers
5725 (list org-drawer-regexp '(0 'org-special-keyword t))
5726 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5727 ;; Properties
5728 (list org-property-re
5729 '(1 'org-special-keyword t)
5730 '(3 'org-property-value t))
5731 ;; Links
5732 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5733 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5734 (if (memq 'plain lk) '(org-activate-plain-links))
5735 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5736 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5737 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5738 (if (memq 'footnote lk) '(org-activate-footnote-links))
5739 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5740 '(org-hide-wide-columns (0 nil append))
5741 ;; TODO keyword
5742 (list (format org-heading-keyword-regexp-format
5743 org-todo-regexp)
5744 '(2 (org-get-todo-face 2) t))
5745 ;; DONE
5746 (if org-fontify-done-headline
5747 (list (format org-heading-keyword-regexp-format
5748 (concat
5749 "\\("
5750 (mapconcat 'regexp-quote org-done-keywords "\\|")
5751 "\\)"))
5752 '(2 'org-headline-done t))
5753 nil)
5754 ;; Priorities
5755 '(org-font-lock-add-priority-faces)
5756 ;; Tags
5757 '(org-font-lock-add-tag-faces)
5758 ;; Special keywords
5759 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5760 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5761 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5762 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5763 ;; Emphasis
5764 (if em
5765 (if (featurep 'xemacs)
5766 '(org-do-emphasis-faces (0 nil append))
5767 '(org-do-emphasis-faces)))
5768 ;; Checkboxes
5769 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5770 1 'org-checkbox prepend)
5771 (if (cdr (assq 'checkbox org-list-automatic-rules))
5772 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5773 (0 (org-get-checkbox-statistics-face) t)))
5774 ;; Description list items
5775 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5776 1 'bold prepend)
5777 ;; ARCHIVEd headings
5778 (list (concat
5779 org-outline-regexp-bol
5780 "\\(.*:" org-archive-tag ":.*\\)")
5781 '(1 'org-archived prepend))
5782 ;; Specials
5783 '(org-do-latex-and-special-faces)
5784 '(org-fontify-entities)
5785 '(org-raise-scripts)
5786 ;; Code
5787 '(org-activate-code (1 'org-code t))
5788 ;; COMMENT
5789 (list (format org-heading-keyword-regexp-format
5790 (concat "\\("
5791 org-comment-string "\\|" org-quote-string
5792 "\\)"))
5793 '(1 'org-special-keyword t))
5794 '("^#.*" (0 'font-lock-comment-face t))
5795 ;; Blocks and meta lines
5796 '(org-fontify-meta-lines-and-blocks)
5798 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5799 (run-hooks 'org-font-lock-set-keywords-hook)
5800 ;; Now set the full font-lock-keywords
5801 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5802 (org-set-local 'font-lock-defaults
5803 '(org-font-lock-keywords t nil nil backward-paragraph))
5804 (kill-local-variable 'font-lock-keywords) nil))
5806 (defun org-toggle-pretty-entities ()
5807 "Toggle the composition display of entities as UTF8 characters."
5808 (interactive)
5809 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5810 (org-restart-font-lock)
5811 (if org-pretty-entities
5812 (message "Entities are displayed as UTF8 characers")
5813 (save-restriction
5814 (widen)
5815 (org-decompose-region (point-min) (point-max))
5816 (message "Entities are displayed plain"))))
5818 (defun org-fontify-entities (limit)
5819 "Find an entity to fontify."
5820 (let (ee)
5821 (when org-pretty-entities
5822 (catch 'match
5823 (while (re-search-forward
5824 "\\\\\\(frac[13][24]\\|[a-zA-Z]+\\)\\($\\|[^[:alpha:]\n]\\)"
5825 limit t)
5826 (if (and (not (org-in-indented-comment-line))
5827 (setq ee (org-entity-get (match-string 1)))
5828 (= (length (nth 6 ee)) 1))
5829 (progn
5830 (add-text-properties
5831 (match-beginning 0) (match-end 1)
5832 (list 'font-lock-fontified t))
5833 (compose-region (match-beginning 0) (match-end 1)
5834 (nth 6 ee) nil)
5835 (backward-char 1)
5836 (throw 'match t))))
5837 nil))))
5839 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5840 "Fontify string S like in Org-mode."
5841 (with-temp-buffer
5842 (insert s)
5843 (let ((org-odd-levels-only odd-levels))
5844 (org-mode)
5845 (font-lock-fontify-buffer)
5846 (buffer-string))))
5848 (defvar org-m nil)
5849 (defvar org-l nil)
5850 (defvar org-f nil)
5851 (defun org-get-level-face (n)
5852 "Get the right face for match N in font-lock matching of headlines."
5853 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5854 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5855 (if org-cycle-level-faces
5856 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5857 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5858 (cond
5859 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5860 ((eq n 2) org-f)
5861 (t (if org-level-color-stars-only nil org-f))))
5864 (defun org-get-todo-face (kwd)
5865 "Get the right face for a TODO keyword KWD.
5866 If KWD is a number, get the corresponding match group."
5867 (if (numberp kwd) (setq kwd (match-string kwd)))
5868 (or (org-face-from-face-or-color
5869 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5870 (and (member kwd org-done-keywords) 'org-done)
5871 'org-todo))
5873 (defun org-face-from-face-or-color (context inherit face-or-color)
5874 "Create a face list that inherits INHERIT, but sets the foreground color.
5875 When FACE-OR-COLOR is not a string, just return it."
5876 (if (stringp face-or-color)
5877 (list :inherit inherit
5878 (cdr (assoc context org-faces-easy-properties))
5879 face-or-color)
5880 face-or-color))
5882 (defun org-font-lock-add-tag-faces (limit)
5883 "Add the special tag faces."
5884 (when (and org-tag-faces org-tags-special-faces-re)
5885 (while (re-search-forward org-tags-special-faces-re limit t)
5886 (add-text-properties (match-beginning 1) (match-end 1)
5887 (list 'face (org-get-tag-face 1)
5888 'font-lock-fontified t))
5889 (backward-char 1))))
5891 (defun org-font-lock-add-priority-faces (limit)
5892 "Add the special priority faces."
5893 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5894 (add-text-properties
5895 (match-beginning 0) (match-end 0)
5896 (list 'face (or (org-face-from-face-or-color
5897 'priority 'org-special-keyword
5898 (cdr (assoc (char-after (match-beginning 1))
5899 org-priority-faces)))
5900 'org-special-keyword)
5901 'font-lock-fontified t))))
5903 (defun org-get-tag-face (kwd)
5904 "Get the right face for a TODO keyword KWD.
5905 If KWD is a number, get the corresponding match group."
5906 (if (numberp kwd) (setq kwd (match-string kwd)))
5907 (or (org-face-from-face-or-color
5908 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5909 'org-tag))
5911 (defun org-unfontify-region (beg end &optional maybe_loudly)
5912 "Remove fontification and activation overlays from links."
5913 (font-lock-default-unfontify-region beg end)
5914 (let* ((buffer-undo-list t)
5915 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5916 (inhibit-modification-hooks t)
5917 deactivate-mark buffer-file-name buffer-file-truename)
5918 (org-decompose-region beg end)
5919 (remove-text-properties beg end
5920 '(mouse-face t keymap t org-linked-text t
5921 invisible t intangible t
5922 org-no-flyspell t org-emphasis t))
5923 (org-remove-font-lock-display-properties beg end)))
5925 (defconst org-script-display '(((raise -0.3) (height 0.7))
5926 ((raise 0.3) (height 0.7))
5927 ((raise -0.5))
5928 ((raise 0.5)))
5929 "Display properties for showing superscripts and subscripts.")
5931 (defun org-remove-font-lock-display-properties (beg end)
5932 "Remove specific display properties that have been added by font lock.
5933 The will remove the raise properties that are used to show superscripts
5934 and subscripts."
5935 (let (next prop)
5936 (while (< beg end)
5937 (setq next (next-single-property-change beg 'display nil end)
5938 prop (get-text-property beg 'display))
5939 (if (member prop org-script-display)
5940 (put-text-property beg next 'display nil))
5941 (setq beg next))))
5943 (defun org-raise-scripts (limit)
5944 "Add raise properties to sub/superscripts."
5945 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
5946 (if (re-search-forward
5947 (if (eq org-use-sub-superscripts t)
5948 org-match-substring-regexp
5949 org-match-substring-with-braces-regexp)
5950 limit t)
5951 (let* ((pos (point)) table-p comment-p
5952 (mpos (match-beginning 3))
5953 (emph-p (get-text-property mpos 'org-emphasis))
5954 (link-p (get-text-property mpos 'mouse-face))
5955 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
5956 (goto-char (point-at-bol))
5957 (setq table-p (org-looking-at-p org-table-dataline-regexp)
5958 comment-p (org-looking-at-p "[ \t]*#"))
5959 (goto-char pos)
5960 ;; FIXME: Should we go back one character here, for a_b^c
5961 ;; (goto-char (1- pos)) ;????????????????????
5962 (if (or comment-p emph-p link-p keyw-p)
5964 (put-text-property (match-beginning 3) (match-end 0)
5965 'display
5966 (if (equal (char-after (match-beginning 2)) ?^)
5967 (nth (if table-p 3 1) org-script-display)
5968 (nth (if table-p 2 0) org-script-display)))
5969 (add-text-properties (match-beginning 2) (match-end 2)
5970 (list 'invisible t
5971 'org-dwidth t 'org-dwidth-n 1))
5972 (if (and (eq (char-after (match-beginning 3)) ?{)
5973 (eq (char-before (match-end 3)) ?}))
5974 (progn
5975 (add-text-properties
5976 (match-beginning 3) (1+ (match-beginning 3))
5977 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
5978 (add-text-properties
5979 (1- (match-end 3)) (match-end 3)
5980 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
5981 t)))))
5983 ;;;; Visibility cycling, including org-goto and indirect buffer
5985 ;;; Cycling
5987 (defvar org-cycle-global-status nil)
5988 (make-variable-buffer-local 'org-cycle-global-status)
5989 (defvar org-cycle-subtree-status nil)
5990 (make-variable-buffer-local 'org-cycle-subtree-status)
5992 ;;;###autoload
5994 (defvar org-inlinetask-min-level)
5996 (defun org-cycle (&optional arg)
5997 "TAB-action and visibility cycling for Org-mode.
5999 This is the command invoked in Org-mode by the TAB key. Its main purpose
6000 is outline visibility cycling, but it also invokes other actions
6001 in special contexts.
6003 - When this function is called with a prefix argument, rotate the entire
6004 buffer through 3 states (global cycling)
6005 1. OVERVIEW: Show only top-level headlines.
6006 2. CONTENTS: Show all headlines of all levels, but no body text.
6007 3. SHOW ALL: Show everything.
6008 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6009 determined by the variable `org-startup-folded', and by any VISIBILITY
6010 properties in the buffer.
6011 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6012 including any drawers.
6014 - When inside a table, re-align the table and move to the next field.
6016 - When point is at the beginning of a headline, rotate the subtree started
6017 by this line through 3 different states (local cycling)
6018 1. FOLDED: Only the main headline is shown.
6019 2. CHILDREN: The main headline and the direct children are shown.
6020 From this state, you can move to one of the children
6021 and zoom in further.
6022 3. SUBTREE: Show the entire subtree, including body text.
6023 If there is no subtree, switch directly from CHILDREN to FOLDED.
6025 - When point is at the beginning of an empty headline and the variable
6026 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6027 of the headline by demoting and promoting it to likely levels. This
6028 speeds up creation document structure by pressing TAB once or several
6029 times right after creating a new headline.
6031 - When there is a numeric prefix, go up to a heading with level ARG, do
6032 a `show-subtree' and return to the previous cursor position. If ARG
6033 is negative, go up that many levels.
6035 - When point is not at the beginning of a headline, execute the global
6036 binding for TAB, which is re-indenting the line. See the option
6037 `org-cycle-emulate-tab' for details.
6039 - Special case: if point is at the beginning of the buffer and there is
6040 no headline in line 1, this function will act as if called with prefix arg
6041 (C-u TAB, same as S-TAB) also when called without prefix arg.
6042 But only if also the variable `org-cycle-global-at-bob' is t."
6043 (interactive "P")
6044 (org-load-modules-maybe)
6045 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6046 (and org-cycle-level-after-item/entry-creation
6047 (or (org-cycle-level)
6048 (org-cycle-item-indentation))))
6049 (let* ((limit-level
6050 (or org-cycle-max-level
6051 (and (boundp 'org-inlinetask-min-level)
6052 org-inlinetask-min-level
6053 (1- org-inlinetask-min-level))))
6054 (nstars (and limit-level
6055 (if org-odd-levels-only
6056 (and limit-level (1- (* limit-level 2)))
6057 limit-level)))
6058 (org-outline-regexp
6059 (if (not (eq major-mode 'org-mode))
6060 outline-regexp
6061 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6062 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6063 (not (looking-at org-outline-regexp))))
6064 (org-cycle-hook
6065 (if bob-special
6066 (delq 'org-optimize-window-after-visibility-change
6067 (copy-sequence org-cycle-hook))
6068 org-cycle-hook))
6069 (pos (point)))
6071 (if (or bob-special (equal arg '(4)))
6072 ;; special case: use global cycling
6073 (setq arg t))
6075 (cond
6077 ((equal arg '(16))
6078 (setq last-command 'dummy)
6079 (org-set-startup-visibility)
6080 (message "Startup visibility, plus VISIBILITY properties"))
6082 ((equal arg '(64))
6083 (show-all)
6084 (message "Entire buffer visible, including drawers"))
6086 ;; Table: enter it or move to the next field.
6087 ((org-at-table-p 'any)
6088 (if (org-at-table.el-p)
6089 (message "Use C-c ' to edit table.el tables")
6090 (if arg (org-table-edit-field t)
6091 (org-table-justify-field-maybe)
6092 (call-interactively 'org-table-next-field))))
6094 ((run-hook-with-args-until-success
6095 'org-tab-after-check-for-table-hook))
6097 ;; Global cycling: delegate to `org-cycle-internal-global'.
6098 ((eq arg t) (org-cycle-internal-global))
6100 ;; Drawers: delegate to `org-flag-drawer'.
6101 ((and org-drawers org-drawer-regexp
6102 (save-excursion
6103 (beginning-of-line 1)
6104 (looking-at org-drawer-regexp)))
6105 (org-flag-drawer ; toggle block visibility
6106 (not (get-char-property (match-end 0) 'invisible))))
6108 ;; Show-subtree, ARG levels up from here.
6109 ((integerp arg)
6110 (save-excursion
6111 (org-back-to-heading)
6112 (outline-up-heading (if (< arg 0) (- arg)
6113 (- (funcall outline-level) arg)))
6114 (org-show-subtree)))
6116 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6117 ((and (featurep 'org-inlinetask)
6118 (org-inlinetask-at-task-p)
6119 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6120 (org-inlinetask-toggle-visibility))
6122 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6123 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6124 (save-excursion (beginning-of-line 1)
6125 (looking-at org-outline-regexp)))
6126 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6127 (org-cycle-internal-local))
6129 ;; From there: TAB emulation and template completion.
6130 (buffer-read-only (org-back-to-heading))
6132 ((run-hook-with-args-until-success
6133 'org-tab-after-check-for-cycling-hook))
6135 ((org-try-structure-completion))
6137 ((org-try-cdlatex-tab))
6139 ((run-hook-with-args-until-success
6140 'org-tab-before-tab-emulation-hook))
6142 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6143 (or (not (bolp))
6144 (not (looking-at org-outline-regexp))))
6145 (call-interactively (global-key-binding "\t")))
6147 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6148 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6149 (or (and (eq org-cycle-emulate-tab 'white)
6150 (= (match-end 0) (point-at-eol)))
6151 (and (eq org-cycle-emulate-tab 'whitestart)
6152 (>= (match-end 0) pos))))
6154 (eq org-cycle-emulate-tab t))
6155 (call-interactively (global-key-binding "\t")))
6157 (t (save-excursion
6158 (org-back-to-heading)
6159 (org-cycle)))))))
6161 (defun org-cycle-internal-global ()
6162 "Do the global cycling action."
6163 (cond
6164 ((and (eq last-command this-command)
6165 (eq org-cycle-global-status 'overview))
6166 ;; We just created the overview - now do table of contents
6167 ;; This can be slow in very large buffers, so indicate action
6168 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6169 (message "CONTENTS...")
6170 (org-content)
6171 (message "CONTENTS...done")
6172 (setq org-cycle-global-status 'contents)
6173 (run-hook-with-args 'org-cycle-hook 'contents))
6175 ((and (eq last-command this-command)
6176 (eq org-cycle-global-status 'contents))
6177 ;; We just showed the table of contents - now show everything
6178 (run-hook-with-args 'org-pre-cycle-hook 'all)
6179 (show-all)
6180 (message "SHOW ALL")
6181 (setq org-cycle-global-status 'all)
6182 (run-hook-with-args 'org-cycle-hook 'all))
6185 ;; Default action: go to overview
6186 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6187 (org-overview)
6188 (message "OVERVIEW")
6189 (setq org-cycle-global-status 'overview)
6190 (run-hook-with-args 'org-cycle-hook 'overview))))
6192 (defun org-cycle-internal-local ()
6193 "Do the local cycling action."
6194 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6195 ;; First, determine end of headline (EOH), end of subtree or item
6196 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6197 (save-excursion
6198 (if (org-at-item-p)
6199 (progn
6200 (beginning-of-line)
6201 (setq struct (org-list-struct))
6202 (setq eoh (point-at-eol))
6203 (setq eos (org-list-get-item-end-before-blank (point) struct))
6204 (setq has-children (org-list-has-child-p (point) struct)))
6205 (org-back-to-heading)
6206 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6207 (setq eos (save-excursion
6208 (org-end-of-subtree t)
6209 (unless (eobp)
6210 (skip-chars-forward " \t\n"))
6211 (if (eobp) (point) (1- (point)))))
6212 (setq has-children
6213 (or (save-excursion
6214 (let ((level (funcall outline-level)))
6215 (outline-next-heading)
6216 (and (org-at-heading-p t)
6217 (> (funcall outline-level) level))))
6218 (save-excursion
6219 (org-list-search-forward (org-item-beginning-re) eos t)))))
6220 ;; Determine end invisible part of buffer (EOL)
6221 (beginning-of-line 2)
6222 ;; XEmacs doesn't have `next-single-char-property-change'
6223 (if (featurep 'xemacs)
6224 (while (and (not (eobp)) ;; this is like `next-line'
6225 (get-char-property (1- (point)) 'invisible))
6226 (beginning-of-line 2))
6227 (while (and (not (eobp)) ;; this is like `next-line'
6228 (get-char-property (1- (point)) 'invisible))
6229 (goto-char (next-single-char-property-change (point) 'invisible))
6230 (and (eolp) (beginning-of-line 2))))
6231 (setq eol (point)))
6232 ;; Find out what to do next and set `this-command'
6233 (cond
6234 ((= eos eoh)
6235 ;; Nothing is hidden behind this heading
6236 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6237 (message "EMPTY ENTRY")
6238 (setq org-cycle-subtree-status nil)
6239 (save-excursion
6240 (goto-char eos)
6241 (outline-next-heading)
6242 (if (outline-invisible-p) (org-flag-heading nil))))
6243 ((and (or (>= eol eos)
6244 (not (string-match "\\S-" (buffer-substring eol eos))))
6245 (or has-children
6246 (not (setq children-skipped
6247 org-cycle-skip-children-state-if-no-children))))
6248 ;; Entire subtree is hidden in one line: children view
6249 (run-hook-with-args 'org-pre-cycle-hook 'children)
6250 (if (org-at-item-p)
6251 (org-list-set-item-visibility (point-at-bol) struct 'children)
6252 (org-show-entry)
6253 (show-children)
6254 ;; Fold every list in subtree to top-level items.
6255 (when (eq org-cycle-include-plain-lists 'integrate)
6256 (save-excursion
6257 (org-back-to-heading)
6258 (while (org-list-search-forward (org-item-beginning-re) eos t)
6259 (beginning-of-line 1)
6260 (let* ((struct (org-list-struct))
6261 (prevs (org-list-prevs-alist struct))
6262 (end (org-list-get-bottom-point struct)))
6263 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6264 (org-list-get-all-items (point) struct prevs))
6265 (goto-char end))))))
6266 (message "CHILDREN")
6267 (save-excursion
6268 (goto-char eos)
6269 (outline-next-heading)
6270 (if (outline-invisible-p) (org-flag-heading nil)))
6271 (setq org-cycle-subtree-status 'children)
6272 (run-hook-with-args 'org-cycle-hook 'children))
6273 ((or children-skipped
6274 (and (eq last-command this-command)
6275 (eq org-cycle-subtree-status 'children)))
6276 ;; We just showed the children, or no children are there,
6277 ;; now show everything.
6278 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6279 (outline-flag-region eoh eos nil)
6280 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6281 (setq org-cycle-subtree-status 'subtree)
6282 (run-hook-with-args 'org-cycle-hook 'subtree))
6284 ;; Default action: hide the subtree.
6285 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6286 (outline-flag-region eoh eos t)
6287 (message "FOLDED")
6288 (setq org-cycle-subtree-status 'folded)
6289 (run-hook-with-args 'org-cycle-hook 'folded)))))
6291 ;;;###autoload
6292 (defun org-global-cycle (&optional arg)
6293 "Cycle the global visibility. For details see `org-cycle'.
6294 With \\[universal-argument] prefix arg, switch to startup visibility.
6295 With a numeric prefix, show all headlines up to that level."
6296 (interactive "P")
6297 (let ((org-cycle-include-plain-lists
6298 (if (eq major-mode 'org-mode) org-cycle-include-plain-lists nil)))
6299 (cond
6300 ((integerp arg)
6301 (show-all)
6302 (hide-sublevels arg)
6303 (setq org-cycle-global-status 'contents))
6304 ((equal arg '(4))
6305 (org-set-startup-visibility)
6306 (message "Startup visibility, plus VISIBILITY properties."))
6308 (org-cycle '(4))))))
6310 (defun org-set-startup-visibility ()
6311 "Set the visibility required by startup options and properties."
6312 (cond
6313 ((eq org-startup-folded t)
6314 (org-cycle '(4)))
6315 ((eq org-startup-folded 'content)
6316 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6317 (org-cycle '(4)) (org-cycle '(4)))))
6318 (unless (eq org-startup-folded 'showeverything)
6319 (if org-hide-block-startup (org-hide-block-all))
6320 (org-set-visibility-according-to-property 'no-cleanup)
6321 (org-cycle-hide-archived-subtrees 'all)
6322 (org-cycle-hide-drawers 'all)
6323 (org-cycle-show-empty-lines t)))
6325 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6326 "Switch subtree visibilities according to :VISIBILITY: property."
6327 (interactive)
6328 (let (org-show-entry-below state)
6329 (save-excursion
6330 (goto-char (point-min))
6331 (while (re-search-forward
6332 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6333 nil t)
6334 (setq state (match-string 1))
6335 (save-excursion
6336 (org-back-to-heading t)
6337 (hide-subtree)
6338 (org-reveal)
6339 (cond
6340 ((equal state '("fold" "folded"))
6341 (hide-subtree))
6342 ((equal state "children")
6343 (org-show-hidden-entry)
6344 (show-children))
6345 ((equal state "content")
6346 (save-excursion
6347 (save-restriction
6348 (org-narrow-to-subtree)
6349 (org-content))))
6350 ((member state '("all" "showall"))
6351 (show-subtree)))))
6352 (unless no-cleanup
6353 (org-cycle-hide-archived-subtrees 'all)
6354 (org-cycle-hide-drawers 'all)
6355 (org-cycle-show-empty-lines 'all)))))
6357 ;; This function uses outline-regexp instead of the more fundamental
6358 ;; org-outline-regexp so that org-cycle-global works outside of Org
6359 ;; buffers, where outline-regexp is needed.
6360 (defun org-overview ()
6361 "Switch to overview mode, showing only top-level headlines.
6362 Really, this shows all headlines with level equal or greater than the level
6363 of the first headline in the buffer. This is important, because if the
6364 first headline is not level one, then (hide-sublevels 1) gives confusing
6365 results."
6366 (interactive)
6367 (let ((level (save-excursion
6368 (goto-char (point-min))
6369 (if (re-search-forward (concat "^" outline-regexp) nil t)
6370 (progn
6371 (goto-char (match-beginning 0))
6372 (funcall outline-level))))))
6373 (and level (hide-sublevels level))))
6375 (defun org-content (&optional arg)
6376 "Show all headlines in the buffer, like a table of contents.
6377 With numerical argument N, show content up to level N."
6378 (interactive "P")
6379 (save-excursion
6380 ;; Visit all headings and show their offspring
6381 (and (integerp arg) (org-overview))
6382 (goto-char (point-max))
6383 (catch 'exit
6384 (while (and (progn (condition-case nil
6385 (outline-previous-visible-heading 1)
6386 (error (goto-char (point-min))))
6388 (looking-at org-outline-regexp))
6389 (if (integerp arg)
6390 (show-children (1- arg))
6391 (show-branches))
6392 (if (bobp) (throw 'exit nil))))))
6395 (defun org-optimize-window-after-visibility-change (state)
6396 "Adjust the window after a change in outline visibility.
6397 This function is the default value of the hook `org-cycle-hook'."
6398 (when (get-buffer-window (current-buffer))
6399 (cond
6400 ((eq state 'content) nil)
6401 ((eq state 'all) nil)
6402 ((eq state 'folded) nil)
6403 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6404 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6406 (defun org-remove-empty-overlays-at (pos)
6407 "Remove outline overlays that do not contain non-white stuff."
6408 (mapc
6409 (lambda (o)
6410 (and (eq 'outline (overlay-get o 'invisible))
6411 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6412 (overlay-end o))))
6413 (delete-overlay o)))
6414 (overlays-at pos)))
6416 (defun org-clean-visibility-after-subtree-move ()
6417 "Fix visibility issues after moving a subtree."
6418 ;; First, find a reasonable region to look at:
6419 ;; Start two siblings above, end three below
6420 (let* ((beg (save-excursion
6421 (and (org-get-last-sibling)
6422 (org-get-last-sibling))
6423 (point)))
6424 (end (save-excursion
6425 (and (org-get-next-sibling)
6426 (org-get-next-sibling)
6427 (org-get-next-sibling))
6428 (if (org-at-heading-p)
6429 (point-at-eol)
6430 (point))))
6431 (level (looking-at "\\*+"))
6432 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6433 (save-excursion
6434 (save-restriction
6435 (narrow-to-region beg end)
6436 (when re
6437 ;; Properly fold already folded siblings
6438 (goto-char (point-min))
6439 (while (re-search-forward re nil t)
6440 (if (and (not (outline-invisible-p))
6441 (save-excursion
6442 (goto-char (point-at-eol)) (outline-invisible-p)))
6443 (hide-entry))))
6444 (org-cycle-show-empty-lines 'overview)
6445 (org-cycle-hide-drawers 'overview)))))
6447 (defun org-cycle-show-empty-lines (state)
6448 "Show empty lines above all visible headlines.
6449 The region to be covered depends on STATE when called through
6450 `org-cycle-hook'. Lisp program can use t for STATE to get the
6451 entire buffer covered. Note that an empty line is only shown if there
6452 are at least `org-cycle-separator-lines' empty lines before the headline."
6453 (when (not (= org-cycle-separator-lines 0))
6454 (save-excursion
6455 (let* ((n (abs org-cycle-separator-lines))
6456 (re (cond
6457 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6458 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6459 (t (let ((ns (number-to-string (- n 2))))
6460 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6461 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6462 beg end b e)
6463 (cond
6464 ((memq state '(overview contents t))
6465 (setq beg (point-min) end (point-max)))
6466 ((memq state '(children folded))
6467 (setq beg (point) end (progn (org-end-of-subtree t t)
6468 (beginning-of-line 2)
6469 (point)))))
6470 (when beg
6471 (goto-char beg)
6472 (while (re-search-forward re end t)
6473 (unless (get-char-property (match-end 1) 'invisible)
6474 (setq e (match-end 1))
6475 (if (< org-cycle-separator-lines 0)
6476 (setq b (save-excursion
6477 (goto-char (match-beginning 0))
6478 (org-back-over-empty-lines)
6479 (if (save-excursion
6480 (goto-char (max (point-min) (1- (point))))
6481 (org-on-heading-p))
6482 (1- (point))
6483 (point))))
6484 (setq b (match-beginning 1)))
6485 (outline-flag-region b e nil)))))))
6486 ;; Never hide empty lines at the end of the file.
6487 (save-excursion
6488 (goto-char (point-max))
6489 (outline-previous-heading)
6490 (outline-end-of-heading)
6491 (if (and (looking-at "[ \t\n]+")
6492 (= (match-end 0) (point-max)))
6493 (outline-flag-region (point) (match-end 0) nil))))
6495 (defun org-show-empty-lines-in-parent ()
6496 "Move to the parent and re-show empty lines before visible headlines."
6497 (save-excursion
6498 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6499 (org-cycle-show-empty-lines context))))
6501 (defun org-files-list ()
6502 "Return `org-agenda-files' list, plus all open org-mode files.
6503 This is useful for operations that need to scan all of a user's
6504 open and agenda-wise Org files."
6505 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6506 (dolist (buf (buffer-list))
6507 (with-current-buffer buf
6508 (if (and (eq major-mode 'org-mode) (buffer-file-name))
6509 (let ((file (expand-file-name (buffer-file-name))))
6510 (unless (member file files)
6511 (push file files))))))
6512 files))
6514 (defsubst org-entry-beginning-position ()
6515 "Return the beginning position of the current entry."
6516 (save-excursion (outline-back-to-heading t) (point)))
6518 (defsubst org-entry-end-position ()
6519 "Return the end position of the current entry."
6520 (save-excursion (outline-next-heading) (point)))
6522 (defun org-cycle-hide-drawers (state)
6523 "Re-hide all drawers after a visibility state change."
6524 (when (and (eq major-mode 'org-mode)
6525 (not (memq state '(overview folded contents))))
6526 (save-excursion
6527 (let* ((globalp (memq state '(contents all)))
6528 (beg (if globalp (point-min) (point)))
6529 (end (if globalp (point-max)
6530 (if (eq state 'children)
6531 (save-excursion (outline-next-heading) (point))
6532 (org-end-of-subtree t)))))
6533 (goto-char beg)
6534 (while (re-search-forward org-drawer-regexp end t)
6535 (org-flag-drawer t))))))
6537 (defun org-flag-drawer (flag)
6538 (save-excursion
6539 (beginning-of-line 1)
6540 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6541 (let ((b (match-end 0)))
6542 (if (re-search-forward
6543 "^[ \t]*:END:"
6544 (save-excursion (outline-next-heading) (point)) t)
6545 (outline-flag-region b (point-at-eol) flag)
6546 (error ":END: line missing at position %s" b))))))
6548 (defun org-subtree-end-visible-p ()
6549 "Is the end of the current subtree visible?"
6550 (pos-visible-in-window-p
6551 (save-excursion (org-end-of-subtree t) (point))))
6553 (defun org-first-headline-recenter (&optional N)
6554 "Move cursor to the first headline and recenter the headline.
6555 Optional argument N means put the headline into the Nth line of the window."
6556 (goto-char (point-min))
6557 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6558 (beginning-of-line)
6559 (recenter (prefix-numeric-value N))))
6561 ;;; Saving and restoring visibility
6563 (defun org-outline-overlay-data (&optional use-markers)
6564 "Return a list of the locations of all outline overlays.
6565 These are overlays with the `invisible' property value `outline'.
6566 The return value is a list of cons cells, with start and stop
6567 positions for each overlay.
6568 If USE-MARKERS is set, return the positions as markers."
6569 (let (beg end)
6570 (save-excursion
6571 (save-restriction
6572 (widen)
6573 (delq nil
6574 (mapcar (lambda (o)
6575 (when (eq (overlay-get o 'invisible) 'outline)
6576 (setq beg (overlay-start o)
6577 end (overlay-end o))
6578 (and beg end (> end beg)
6579 (if use-markers
6580 (cons (move-marker (make-marker) beg)
6581 (move-marker (make-marker) end))
6582 (cons beg end)))))
6583 (overlays-in (point-min) (point-max))))))))
6585 (defun org-set-outline-overlay-data (data)
6586 "Create visibility overlays for all positions in DATA.
6587 DATA should have been made by `org-outline-overlay-data'."
6588 (let (o)
6589 (save-excursion
6590 (save-restriction
6591 (widen)
6592 (show-all)
6593 (mapc (lambda (c)
6594 (setq o (make-overlay (car c) (cdr c)))
6595 (overlay-put o 'invisible 'outline))
6596 data)))))
6598 ;;; Folding of blocks
6600 (defconst org-block-regexp
6601 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
6602 "Regular expression for hiding blocks.")
6604 (defvar org-hide-block-overlays nil
6605 "Overlays hiding blocks.")
6606 (make-variable-buffer-local 'org-hide-block-overlays)
6608 (defun org-block-map (function &optional start end)
6609 "Call FUNCTION at the head of all source blocks in the current buffer.
6610 Optional arguments START and END can be used to limit the range."
6611 (let ((start (or start (point-min)))
6612 (end (or end (point-max))))
6613 (save-excursion
6614 (goto-char start)
6615 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6616 (save-excursion
6617 (save-match-data
6618 (goto-char (match-beginning 0))
6619 (funcall function)))))))
6621 (defun org-hide-block-toggle-all ()
6622 "Toggle the visibility of all blocks in the current buffer."
6623 (org-block-map #'org-hide-block-toggle))
6625 (defun org-hide-block-all ()
6626 "Fold all blocks in the current buffer."
6627 (interactive)
6628 (org-show-block-all)
6629 (org-block-map #'org-hide-block-toggle-maybe))
6631 (defun org-show-block-all ()
6632 "Unfold all blocks in the current buffer."
6633 (interactive)
6634 (mapc 'delete-overlay org-hide-block-overlays)
6635 (setq org-hide-block-overlays nil))
6637 (defun org-hide-block-toggle-maybe ()
6638 "Toggle visibility of block at point."
6639 (interactive)
6640 (let ((case-fold-search t))
6641 (if (save-excursion
6642 (beginning-of-line 1)
6643 (looking-at org-block-regexp))
6644 (progn (org-hide-block-toggle)
6645 t) ;; to signal that we took action
6646 nil))) ;; to signal that we did not
6648 (defun org-hide-block-toggle (&optional force)
6649 "Toggle the visibility of the current block."
6650 (interactive)
6651 (save-excursion
6652 (beginning-of-line)
6653 (if (re-search-forward org-block-regexp nil t)
6654 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6655 (end (match-end 0)) ;; end of entire body
6657 (if (memq t (mapcar (lambda (overlay)
6658 (eq (overlay-get overlay 'invisible)
6659 'org-hide-block))
6660 (overlays-at start)))
6661 (if (or (not force) (eq force 'off))
6662 (mapc (lambda (ov)
6663 (when (member ov org-hide-block-overlays)
6664 (setq org-hide-block-overlays
6665 (delq ov org-hide-block-overlays)))
6666 (when (eq (overlay-get ov 'invisible)
6667 'org-hide-block)
6668 (delete-overlay ov)))
6669 (overlays-at start)))
6670 (setq ov (make-overlay start end))
6671 (overlay-put ov 'invisible 'org-hide-block)
6672 ;; make the block accessible to isearch
6673 (overlay-put
6674 ov 'isearch-open-invisible
6675 (lambda (ov)
6676 (when (member ov org-hide-block-overlays)
6677 (setq org-hide-block-overlays
6678 (delq ov org-hide-block-overlays)))
6679 (when (eq (overlay-get ov 'invisible)
6680 'org-hide-block)
6681 (delete-overlay ov))))
6682 (push ov org-hide-block-overlays)))
6683 (error "Not looking at a source block"))))
6685 ;; org-tab-after-check-for-cycling-hook
6686 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6687 ;; Remove overlays when changing major mode
6688 (add-hook 'org-mode-hook
6689 (lambda () (org-add-hook 'change-major-mode-hook
6690 'org-show-block-all 'append 'local)))
6692 ;;; Org-goto
6694 (defvar org-goto-window-configuration nil)
6695 (defvar org-goto-marker nil)
6696 (defvar org-goto-map
6697 (let ((map (make-sparse-keymap)))
6698 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6699 (while (setq cmd (pop cmds))
6700 (substitute-key-definition cmd cmd map global-map)))
6701 (suppress-keymap map)
6702 (org-defkey map "\C-m" 'org-goto-ret)
6703 (org-defkey map [(return)] 'org-goto-ret)
6704 (org-defkey map [(left)] 'org-goto-left)
6705 (org-defkey map [(right)] 'org-goto-right)
6706 (org-defkey map [(control ?g)] 'org-goto-quit)
6707 (org-defkey map "\C-i" 'org-cycle)
6708 (org-defkey map [(tab)] 'org-cycle)
6709 (org-defkey map [(down)] 'outline-next-visible-heading)
6710 (org-defkey map [(up)] 'outline-previous-visible-heading)
6711 (if org-goto-auto-isearch
6712 (if (fboundp 'define-key-after)
6713 (define-key-after map [t] 'org-goto-local-auto-isearch)
6714 nil)
6715 (org-defkey map "q" 'org-goto-quit)
6716 (org-defkey map "n" 'outline-next-visible-heading)
6717 (org-defkey map "p" 'outline-previous-visible-heading)
6718 (org-defkey map "f" 'outline-forward-same-level)
6719 (org-defkey map "b" 'outline-backward-same-level)
6720 (org-defkey map "u" 'outline-up-heading))
6721 (org-defkey map "/" 'org-occur)
6722 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6723 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6724 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6725 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6726 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6727 map))
6729 (defconst org-goto-help
6730 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6731 RET=jump to location [Q]uit and return to previous location
6732 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6734 (defvar org-goto-start-pos) ; dynamically scoped parameter
6736 ;; FIXME: Docstring does not mention both interfaces
6737 (defun org-goto (&optional alternative-interface)
6738 "Look up a different location in the current file, keeping current visibility.
6740 When you want look-up or go to a different location in a document, the
6741 fastest way is often to fold the entire buffer and then dive into the tree.
6742 This method has the disadvantage, that the previous location will be folded,
6743 which may not be what you want.
6745 This command works around this by showing a copy of the current buffer
6746 in an indirect buffer, in overview mode. You can dive into the tree in
6747 that copy, use org-occur and incremental search to find a location.
6748 When pressing RET or `Q', the command returns to the original buffer in
6749 which the visibility is still unchanged. After RET is will also jump to
6750 the location selected in the indirect buffer and expose the headline
6751 hierarchy above."
6752 (interactive "P")
6753 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6754 (org-refile-use-outline-path t)
6755 (org-refile-target-verify-function nil)
6756 (interface
6757 (if (not alternative-interface)
6758 org-goto-interface
6759 (if (eq org-goto-interface 'outline)
6760 'outline-path-completion
6761 'outline)))
6762 (org-goto-start-pos (point))
6763 (selected-point
6764 (if (eq interface 'outline)
6765 (car (org-get-location (current-buffer) org-goto-help))
6766 (let ((pa (org-refile-get-location "Goto")))
6767 (org-refile-check-position pa)
6768 (nth 3 pa)))))
6769 (if selected-point
6770 (progn
6771 (org-mark-ring-push org-goto-start-pos)
6772 (goto-char selected-point)
6773 (if (or (outline-invisible-p) (org-invisible-p2))
6774 (org-show-context 'org-goto)))
6775 (message "Quit"))))
6777 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6778 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6779 (defvar org-goto-local-auto-isearch-map) ; defined below
6781 (defun org-get-location (buf help)
6782 "Let the user select a location in the Org-mode buffer BUF.
6783 This function uses a recursive edit. It returns the selected position
6784 or nil."
6785 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6786 (isearch-hide-immediately nil)
6787 (isearch-search-fun-function
6788 (lambda () 'org-goto-local-search-headings))
6789 (org-goto-selected-point org-goto-exit-command)
6790 (pop-up-frames nil)
6791 (special-display-buffer-names nil)
6792 (special-display-regexps nil)
6793 (special-display-function nil))
6794 (save-excursion
6795 (save-window-excursion
6796 (delete-other-windows)
6797 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6798 (org-pop-to-buffer-same-window
6799 (condition-case nil
6800 (make-indirect-buffer (current-buffer) "*org-goto*")
6801 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6802 (with-output-to-temp-buffer "*Help*"
6803 (princ help))
6804 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6805 (setq buffer-read-only nil)
6806 (let ((org-startup-truncated t)
6807 (org-startup-folded nil)
6808 (org-startup-align-all-tables nil))
6809 (org-mode)
6810 (org-overview))
6811 (setq buffer-read-only t)
6812 (if (and (boundp 'org-goto-start-pos)
6813 (integer-or-marker-p org-goto-start-pos))
6814 (let ((org-show-hierarchy-above t)
6815 (org-show-siblings t)
6816 (org-show-following-heading t))
6817 (goto-char org-goto-start-pos)
6818 (and (outline-invisible-p) (org-show-context)))
6819 (goto-char (point-min)))
6820 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6821 (message "Select location and press RET")
6822 (use-local-map org-goto-map)
6823 (recursive-edit)
6825 (kill-buffer "*org-goto*")
6826 (cons org-goto-selected-point org-goto-exit-command)))
6828 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6829 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6830 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6831 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6833 (defun org-goto-local-search-headings (string bound noerror)
6834 "Search and make sure that any matches are in headlines."
6835 (catch 'return
6836 (while (if isearch-forward
6837 (search-forward string bound noerror)
6838 (search-backward string bound noerror))
6839 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6840 (and (member :headline context)
6841 (not (member :tags context))))
6842 (throw 'return (point))))))
6844 (defun org-goto-local-auto-isearch ()
6845 "Start isearch."
6846 (interactive)
6847 (goto-char (point-min))
6848 (let ((keys (this-command-keys)))
6849 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6850 (isearch-mode t)
6851 (isearch-process-search-char (string-to-char keys)))))
6853 (defun org-goto-ret (&optional arg)
6854 "Finish `org-goto' by going to the new location."
6855 (interactive "P")
6856 (setq org-goto-selected-point (point)
6857 org-goto-exit-command 'return)
6858 (throw 'exit nil))
6860 (defun org-goto-left ()
6861 "Finish `org-goto' by going to the new location."
6862 (interactive)
6863 (if (org-on-heading-p)
6864 (progn
6865 (beginning-of-line 1)
6866 (setq org-goto-selected-point (point)
6867 org-goto-exit-command 'left)
6868 (throw 'exit nil))
6869 (error "Not on a heading")))
6871 (defun org-goto-right ()
6872 "Finish `org-goto' by going to the new location."
6873 (interactive)
6874 (if (org-on-heading-p)
6875 (progn
6876 (setq org-goto-selected-point (point)
6877 org-goto-exit-command 'right)
6878 (throw 'exit nil))
6879 (error "Not on a heading")))
6881 (defun org-goto-quit ()
6882 "Finish `org-goto' without cursor motion."
6883 (interactive)
6884 (setq org-goto-selected-point nil)
6885 (setq org-goto-exit-command 'quit)
6886 (throw 'exit nil))
6888 ;;; Indirect buffer display of subtrees
6890 (defvar org-indirect-dedicated-frame nil
6891 "This is the frame being used for indirect tree display.")
6892 (defvar org-last-indirect-buffer nil)
6894 (defun org-tree-to-indirect-buffer (&optional arg)
6895 "Create indirect buffer and narrow it to current subtree.
6896 With numerical prefix ARG, go up to this level and then take that tree.
6897 If ARG is negative, go up that many levels.
6898 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6899 indirect buffer previously made with this command, to avoid proliferation of
6900 indirect buffers. However, when you call the command with a \
6901 \\[universal-argument] prefix, or
6902 when `org-indirect-buffer-display' is `new-frame', the last buffer
6903 is kept so that you can work with several indirect buffers at the same time.
6904 If `org-indirect-buffer-display' is `dedicated-frame', the \
6905 \\[universal-argument] prefix also
6906 requests that a new frame be made for the new buffer, so that the dedicated
6907 frame is not changed."
6908 (interactive "P")
6909 (let ((cbuf (current-buffer))
6910 (cwin (selected-window))
6911 (pos (point))
6912 beg end level heading ibuf)
6913 (save-excursion
6914 (org-back-to-heading t)
6915 (when (numberp arg)
6916 (setq level (org-outline-level))
6917 (if (< arg 0) (setq arg (+ level arg)))
6918 (while (> (setq level (org-outline-level)) arg)
6919 (outline-up-heading 1 t)))
6920 (setq beg (point)
6921 heading (org-get-heading))
6922 (org-end-of-subtree t t)
6923 (if (org-on-heading-p) (backward-char 1))
6924 (setq end (point)))
6925 (if (and (buffer-live-p org-last-indirect-buffer)
6926 (not (eq org-indirect-buffer-display 'new-frame))
6927 (not arg))
6928 (kill-buffer org-last-indirect-buffer))
6929 (setq ibuf (org-get-indirect-buffer cbuf)
6930 org-last-indirect-buffer ibuf)
6931 (cond
6932 ((or (eq org-indirect-buffer-display 'new-frame)
6933 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6934 (select-frame (make-frame))
6935 (delete-other-windows)
6936 (org-pop-to-buffer-same-window ibuf)
6937 (org-set-frame-title heading))
6938 ((eq org-indirect-buffer-display 'dedicated-frame)
6939 (raise-frame
6940 (select-frame (or (and org-indirect-dedicated-frame
6941 (frame-live-p org-indirect-dedicated-frame)
6942 org-indirect-dedicated-frame)
6943 (setq org-indirect-dedicated-frame (make-frame)))))
6944 (delete-other-windows)
6945 (org-pop-to-buffer-same-window ibuf)
6946 (org-set-frame-title (concat "Indirect: " heading)))
6947 ((eq org-indirect-buffer-display 'current-window)
6948 (org-pop-to-buffer-same-window ibuf))
6949 ((eq org-indirect-buffer-display 'other-window)
6950 (pop-to-buffer ibuf))
6951 (t (error "Invalid value")))
6952 (if (featurep 'xemacs)
6953 (save-excursion (org-mode) (turn-on-font-lock)))
6954 (narrow-to-region beg end)
6955 (show-all)
6956 (goto-char pos)
6957 (run-hook-with-args 'org-cycle-hook 'all)
6958 (and (window-live-p cwin) (select-window cwin))))
6960 (defun org-get-indirect-buffer (&optional buffer)
6961 (setq buffer (or buffer (current-buffer)))
6962 (let ((n 1) (base (buffer-name buffer)) bname)
6963 (while (buffer-live-p
6964 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6965 (setq n (1+ n)))
6966 (condition-case nil
6967 (make-indirect-buffer buffer bname 'clone)
6968 (error (make-indirect-buffer buffer bname)))))
6970 (defun org-set-frame-title (title)
6971 "Set the title of the current frame to the string TITLE."
6972 ;; FIXME: how to name a single frame in XEmacs???
6973 (unless (featurep 'xemacs)
6974 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6976 ;;;; Structure editing
6978 ;;; Inserting headlines
6980 (defun org-previous-line-empty-p ()
6981 (save-excursion
6982 (and (not (bobp))
6983 (or (beginning-of-line 0) t)
6984 (save-match-data
6985 (looking-at "[ \t]*$")))))
6987 (defun org-insert-heading (&optional force-heading invisible-ok)
6988 "Insert a new heading or item with same depth at point.
6989 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6990 If point is at the beginning of a headline, insert a sibling before the
6991 current headline. If point is not at the beginning, split the line,
6992 create the new headline with the text in the current line after point
6993 \(but see also the variable `org-M-RET-may-split-line').
6995 When INVISIBLE-OK is set, stop at invisible headlines when going back.
6996 This is important for non-interactive uses of the command."
6997 (interactive "P")
6998 (if (or (= (buffer-size) 0)
6999 (and (not (save-excursion
7000 (and (ignore-errors (org-back-to-heading invisible-ok))
7001 (org-on-heading-p))))
7002 (or force-heading (not (org-in-item-p)))))
7003 (progn
7004 (insert "\n* ")
7005 (run-hooks 'org-insert-heading-hook))
7006 (when (or force-heading (not (org-insert-item)))
7007 (let* ((empty-line-p nil)
7008 (level nil)
7009 (on-heading (org-on-heading-p))
7010 (head (save-excursion
7011 (condition-case nil
7012 (progn
7013 (org-back-to-heading invisible-ok)
7014 (when (and (not on-heading)
7015 (featurep 'org-inlinetask)
7016 (integerp org-inlinetask-min-level)
7017 (>= (length (match-string 0))
7018 org-inlinetask-min-level))
7019 ;; Find a heading level before the inline task
7020 (while (and (setq level (org-up-heading-safe))
7021 (>= level org-inlinetask-min-level)))
7022 (if (org-on-heading-p)
7023 (org-back-to-heading invisible-ok)
7024 (error "This should not happen")))
7025 (setq empty-line-p (org-previous-line-empty-p))
7026 (match-string 0))
7027 (error "*"))))
7028 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7029 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7030 pos hide-previous previous-pos)
7031 (cond
7032 ((and (org-on-heading-p) (bolp)
7033 (or (bobp)
7034 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7035 ;; insert before the current line
7036 (open-line (if blank 2 1)))
7037 ((and (bolp)
7038 (not org-insert-heading-respect-content)
7039 (or (bobp)
7040 (save-excursion
7041 (backward-char 1) (not (outline-invisible-p)))))
7042 ;; insert right here
7043 nil)
7045 ;; somewhere in the line
7046 (save-excursion
7047 (setq previous-pos (point-at-bol))
7048 (end-of-line)
7049 (setq hide-previous (outline-invisible-p)))
7050 (and org-insert-heading-respect-content (org-show-subtree))
7051 (let ((split
7052 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7053 (save-excursion
7054 (let ((p (point)))
7055 (goto-char (point-at-bol))
7056 (and (looking-at org-complex-heading-regexp)
7057 (match-beginning 4)
7058 (> p (match-beginning 4)))))))
7059 tags pos)
7060 (cond
7061 (org-insert-heading-respect-content
7062 (org-end-of-subtree nil t)
7063 (when (featurep 'org-inlinetask)
7064 (while (and (not (eobp))
7065 (looking-at "\\(\\*+\\)[ \t]+")
7066 (>= (length (match-string 1))
7067 org-inlinetask-min-level))
7068 (org-end-of-subtree nil t)))
7069 (or (bolp) (newline))
7070 (or (org-previous-line-empty-p)
7071 (and blank (newline)))
7072 (open-line 1))
7073 ((org-on-heading-p)
7074 (when hide-previous
7075 (show-children)
7076 (org-show-entry))
7077 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7078 (setq tags (and (match-end 2) (match-string 2)))
7079 (and (match-end 1)
7080 (delete-region (match-beginning 1) (match-end 1)))
7081 (setq pos (point-at-bol))
7082 (or split (end-of-line 1))
7083 (delete-horizontal-space)
7084 (if (string-match "\\`\\*+\\'"
7085 (buffer-substring (point-at-bol) (point)))
7086 (insert " "))
7087 (newline (if blank 2 1))
7088 (when tags
7089 (save-excursion
7090 (goto-char pos)
7091 (end-of-line 1)
7092 (insert " " tags)
7093 (org-set-tags nil 'align))))
7095 (or split (end-of-line 1))
7096 (newline (if blank 2 1)))))))
7097 (insert head) (just-one-space)
7098 (setq pos (point))
7099 (end-of-line 1)
7100 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7101 (when (and org-insert-heading-respect-content hide-previous)
7102 (save-excursion
7103 (goto-char previous-pos)
7104 (hide-subtree)))
7105 (run-hooks 'org-insert-heading-hook)))))
7107 (defun org-get-heading (&optional no-tags no-todo)
7108 "Return the heading of the current entry, without the stars.
7109 When NO-TAGS is non-nil, don't include tags.
7110 When NO-TODO is non-nil, don't include TODO keywords."
7111 (save-excursion
7112 (org-back-to-heading t)
7113 (cond
7114 ((and no-tags no-todo)
7115 (looking-at org-complex-heading-regexp)
7116 (match-string 4))
7117 (no-tags
7118 (looking-at (concat org-outline-regexp
7119 "\\(.*?\\)"
7120 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7121 (match-string 1))
7122 (no-todo
7123 (looking-at org-todo-line-regexp)
7124 (match-string 3))
7125 (t (looking-at org-heading-regexp)
7126 (match-string 2)))))
7128 (defun org-heading-components ()
7129 "Return the components of the current heading.
7130 This is a list with the following elements:
7131 - the level as an integer
7132 - the reduced level, different if `org-odd-levels-only' is set.
7133 - the TODO keyword, or nil
7134 - the priority character, like ?A, or nil if no priority is given
7135 - the headline text itself, or the tags string if no headline text
7136 - the tags string, or nil."
7137 (save-excursion
7138 (org-back-to-heading t)
7139 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7140 (list (length (match-string 1))
7141 (org-reduced-level (length (match-string 1)))
7142 (org-match-string-no-properties 2)
7143 (and (match-end 3) (aref (match-string 3) 2))
7144 (org-match-string-no-properties 4)
7145 (org-match-string-no-properties 5)))))
7147 (defun org-get-entry ()
7148 "Get the entry text, after heading, entire subtree."
7149 (save-excursion
7150 (org-back-to-heading t)
7151 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7153 (defun org-insert-heading-after-current ()
7154 "Insert a new heading with same level as current, after current subtree."
7155 (interactive)
7156 (org-back-to-heading)
7157 (org-insert-heading)
7158 (org-move-subtree-down)
7159 (end-of-line 1))
7161 (defun org-insert-heading-respect-content ()
7162 (interactive)
7163 (let ((org-insert-heading-respect-content t))
7164 (org-insert-heading t)))
7166 (defun org-insert-todo-heading-respect-content (&optional force-state)
7167 (interactive "P")
7168 (let ((org-insert-heading-respect-content t))
7169 (org-insert-todo-heading force-state t)))
7171 (defun org-insert-todo-heading (arg &optional force-heading)
7172 "Insert a new heading with the same level and TODO state as current heading.
7173 If the heading has no TODO state, or if the state is DONE, use the first
7174 state (TODO by default). Also with prefix arg, force first state."
7175 (interactive "P")
7176 (when (or force-heading (not (org-insert-item 'checkbox)))
7177 (org-insert-heading force-heading)
7178 (save-excursion
7179 (org-back-to-heading)
7180 (outline-previous-heading)
7181 (looking-at org-todo-line-regexp))
7182 (let*
7183 ((new-mark-x
7184 (if (or arg
7185 (not (match-beginning 2))
7186 (member (match-string 2) org-done-keywords))
7187 (car org-todo-keywords-1)
7188 (match-string 2)))
7189 (new-mark
7191 (run-hook-with-args-until-success
7192 'org-todo-get-default-hook new-mark-x nil)
7193 new-mark-x)))
7194 (beginning-of-line 1)
7195 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7196 (if org-treat-insert-todo-heading-as-state-change
7197 (org-todo new-mark)
7198 (insert new-mark " "))))
7199 (when org-provide-todo-statistics
7200 (org-update-parent-todo-statistics))))
7202 (defun org-insert-subheading (arg)
7203 "Insert a new subheading and demote it.
7204 Works for outline headings and for plain lists alike."
7205 (interactive "P")
7206 (org-insert-heading arg)
7207 (cond
7208 ((org-on-heading-p) (org-do-demote))
7209 ((org-at-item-p) (org-indent-item))))
7211 (defun org-insert-todo-subheading (arg)
7212 "Insert a new subheading with TODO keyword or checkbox and demote it.
7213 Works for outline headings and for plain lists alike."
7214 (interactive "P")
7215 (org-insert-todo-heading arg)
7216 (cond
7217 ((org-on-heading-p) (org-do-demote))
7218 ((org-at-item-p) (org-indent-item))))
7220 ;;; Promotion and Demotion
7222 (defvar org-after-demote-entry-hook nil
7223 "Hook run after an entry has been demoted.
7224 The cursor will be at the beginning of the entry.
7225 When a subtree is being demoted, the hook will be called for each node.")
7227 (defvar org-after-promote-entry-hook nil
7228 "Hook run after an entry has been promoted.
7229 The cursor will be at the beginning of the entry.
7230 When a subtree is being promoted, the hook will be called for each node.")
7232 (defun org-promote-subtree ()
7233 "Promote the entire subtree.
7234 See also `org-promote'."
7235 (interactive)
7236 (save-excursion
7237 (org-with-limited-levels (org-map-tree 'org-promote)))
7238 (org-fix-position-after-promote))
7240 (defun org-demote-subtree ()
7241 "Demote the entire subtree. See `org-demote'.
7242 See also `org-promote'."
7243 (interactive)
7244 (save-excursion
7245 (org-with-limited-levels (org-map-tree 'org-demote)))
7246 (org-fix-position-after-promote))
7249 (defun org-do-promote ()
7250 "Promote the current heading higher up the tree.
7251 If the region is active in `transient-mark-mode', promote all headings
7252 in the region."
7253 (interactive)
7254 (save-excursion
7255 (if (org-region-active-p)
7256 (org-map-region 'org-promote (region-beginning) (region-end))
7257 (org-promote)))
7258 (org-fix-position-after-promote))
7260 (defun org-do-demote ()
7261 "Demote the current heading lower down the tree.
7262 If the region is active in `transient-mark-mode', demote all headings
7263 in the region."
7264 (interactive)
7265 (save-excursion
7266 (if (org-region-active-p)
7267 (org-map-region 'org-demote (region-beginning) (region-end))
7268 (org-demote)))
7269 (org-fix-position-after-promote))
7271 (defun org-fix-position-after-promote ()
7272 "Make sure that after pro/demotion cursor position is right."
7273 (let ((pos (point)))
7274 (when (save-excursion
7275 (beginning-of-line 1)
7276 (looking-at org-todo-line-regexp)
7277 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7278 (cond ((eobp) (insert " "))
7279 ((eolp) (insert " "))
7280 ((equal (char-after) ?\ ) (forward-char 1))))))
7282 (defun org-current-level ()
7283 "Return the level of the current entry, or nil if before the first headline.
7284 The level is the number of stars at the beginning of the headline."
7285 (save-excursion
7286 (org-with-limited-levels
7287 (if (ignore-errors (org-back-to-heading t))
7288 (funcall outline-level)))))
7290 (defun org-get-previous-line-level ()
7291 "Return the outline depth of the last headline before the current line.
7292 Returns 0 for the first headline in the buffer, and nil if before the
7293 first headline."
7294 (let ((current-level (org-current-level))
7295 (prev-level (when (> (line-number-at-pos) 1)
7296 (save-excursion
7297 (beginning-of-line 0)
7298 (org-current-level)))))
7299 (cond ((null current-level) nil) ; Before first headline
7300 ((null prev-level) 0) ; At first headline
7301 (prev-level))))
7303 (defun org-reduced-level (l)
7304 "Compute the effective level of a heading.
7305 This takes into account the setting of `org-odd-levels-only'."
7306 (cond
7307 ((zerop l) 0)
7308 (org-odd-levels-only (1+ (floor (/ l 2))))
7309 (t l)))
7311 (defun org-level-increment ()
7312 "Return the number of stars that will be added or removed at a
7313 time to headlines when structure editing, based on the value of
7314 `org-odd-levels-only'."
7315 (if org-odd-levels-only 2 1))
7317 (defun org-get-valid-level (level &optional change)
7318 "Rectify a level change under the influence of `org-odd-levels-only'
7319 LEVEL is a current level, CHANGE is by how much the level should be
7320 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7321 even level numbers will become the next higher odd number."
7322 (if org-odd-levels-only
7323 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7324 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7325 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7326 (max 1 (+ level (or change 0)))))
7328 (if (boundp 'define-obsolete-function-alias)
7329 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7330 (define-obsolete-function-alias 'org-get-legal-level
7331 'org-get-valid-level)
7332 (define-obsolete-function-alias 'org-get-legal-level
7333 'org-get-valid-level "23.1")))
7335 (defun org-promote ()
7336 "Promote the current heading higher up the tree.
7337 If the region is active in `transient-mark-mode', promote all headings
7338 in the region."
7339 (org-back-to-heading t)
7340 (let* ((level (save-match-data (funcall outline-level)))
7341 (after-change-functions (remove 'flyspell-after-change-function
7342 after-change-functions))
7343 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7344 (diff (abs (- level (length up-head) -1))))
7345 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
7346 (replace-match up-head nil t)
7347 ;; Fixup tag positioning
7348 (and org-auto-align-tags (org-set-tags nil t))
7349 (if org-adapt-indentation (org-fixup-indentation (- diff)))
7350 (run-hooks 'org-after-promote-entry-hook)))
7352 (defun org-demote ()
7353 "Demote the current heading lower down the tree.
7354 If the region is active in `transient-mark-mode', demote all headings
7355 in the region."
7356 (org-back-to-heading t)
7357 (let* ((level (save-match-data (funcall outline-level)))
7358 (after-change-functions (remove 'flyspell-after-change-function
7359 after-change-functions))
7360 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7361 (diff (abs (- level (length down-head) -1))))
7362 (replace-match down-head nil t)
7363 ;; Fixup tag positioning
7364 (and org-auto-align-tags (org-set-tags nil t))
7365 (if org-adapt-indentation (org-fixup-indentation diff))
7366 (run-hooks 'org-after-demote-entry-hook)))
7368 (defun org-cycle-level ()
7369 "Cycle the level of an empty headline through possible states.
7370 This goes first to child, then to parent, level, then up the hierarchy.
7371 After top level, it switches back to sibling level."
7372 (interactive)
7373 (let ((org-adapt-indentation nil))
7374 (when (org-point-at-end-of-empty-headline)
7375 (setq this-command 'org-cycle-level) ; Only needed for caching
7376 (let ((cur-level (org-current-level))
7377 (prev-level (org-get-previous-line-level)))
7378 (cond
7379 ;; If first headline in file, promote to top-level.
7380 ((= prev-level 0)
7381 (loop repeat (/ (- cur-level 1) (org-level-increment))
7382 do (org-do-promote)))
7383 ;; If same level as prev, demote one.
7384 ((= prev-level cur-level)
7385 (org-do-demote))
7386 ;; If parent is top-level, promote to top level if not already.
7387 ((= prev-level 1)
7388 (loop repeat (/ (- cur-level 1) (org-level-increment))
7389 do (org-do-promote)))
7390 ;; If top-level, return to prev-level.
7391 ((= cur-level 1)
7392 (loop repeat (/ (- prev-level 1) (org-level-increment))
7393 do (org-do-demote)))
7394 ;; If less than prev-level, promote one.
7395 ((< cur-level prev-level)
7396 (org-do-promote))
7397 ;; If deeper than prev-level, promote until higher than
7398 ;; prev-level.
7399 ((> cur-level prev-level)
7400 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7401 do (org-do-promote))))
7402 t))))
7404 (defun org-map-tree (fun)
7405 "Call FUN for every heading underneath the current one."
7406 (org-back-to-heading)
7407 (let ((level (funcall outline-level)))
7408 (save-excursion
7409 (funcall fun)
7410 (while (and (progn
7411 (outline-next-heading)
7412 (> (funcall outline-level) level))
7413 (not (eobp)))
7414 (funcall fun)))))
7416 (defun org-map-region (fun beg end)
7417 "Call FUN for every heading between BEG and END."
7418 (let ((org-ignore-region t))
7419 (save-excursion
7420 (setq end (copy-marker end))
7421 (goto-char beg)
7422 (if (and (re-search-forward org-outline-regexp-bol nil t)
7423 (< (point) end))
7424 (funcall fun))
7425 (while (and (progn
7426 (outline-next-heading)
7427 (< (point) end))
7428 (not (eobp)))
7429 (funcall fun)))))
7431 (defvar org-property-end-re) ; silence byte-compiler
7432 (defun org-fixup-indentation (diff)
7433 "Change the indentation in the current entry by DIFF.
7434 However, if any line in the current entry has no indentation, or if it
7435 would end up with no indentation after the change, nothing at all is done."
7436 (save-excursion
7437 (let ((end (save-excursion (outline-next-heading)
7438 (point-marker)))
7439 (prohibit (if (> diff 0)
7440 "^\\S-"
7441 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7442 col)
7443 (unless (save-excursion (end-of-line 1)
7444 (re-search-forward prohibit end t))
7445 (while (and (< (point) end)
7446 (re-search-forward "^[ \t]+" end t))
7447 (goto-char (match-end 0))
7448 (setq col (current-column))
7449 (if (< diff 0) (replace-match ""))
7450 (org-indent-to-column (+ diff col))))
7451 (move-marker end nil))))
7453 (defun org-convert-to-odd-levels ()
7454 "Convert an org-mode file with all levels allowed to one with odd levels.
7455 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7456 level 5 etc."
7457 (interactive)
7458 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7459 (let ((outline-level 'org-outline-level)
7460 (org-odd-levels-only nil) n)
7461 (save-excursion
7462 (goto-char (point-min))
7463 (while (re-search-forward "^\\*\\*+ " nil t)
7464 (setq n (- (length (match-string 0)) 2))
7465 (while (>= (setq n (1- n)) 0)
7466 (org-demote))
7467 (end-of-line 1))))))
7469 (defun org-convert-to-oddeven-levels ()
7470 "Convert an org-mode file with only odd levels to one with odd/even levels.
7471 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7472 file contains a section with an even level, conversion would
7473 destroy the structure of the file. An error is signaled in this
7474 case."
7475 (interactive)
7476 (goto-char (point-min))
7477 ;; First check if there are no even levels
7478 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7479 (org-show-context t)
7480 (error "Not all levels are odd in this file. Conversion not possible"))
7481 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7482 (let ((outline-regexp org-outline-regexp)
7483 (outline-level 'org-outline-level)
7484 (org-odd-levels-only nil) n)
7485 (save-excursion
7486 (goto-char (point-min))
7487 (while (re-search-forward "^\\*\\*+ " nil t)
7488 (setq n (/ (1- (length (match-string 0))) 2))
7489 (while (>= (setq n (1- n)) 0)
7490 (org-promote))
7491 (end-of-line 1))))))
7493 (defun org-tr-level (n)
7494 "Make N odd if required."
7495 (if org-odd-levels-only (1+ (/ n 2)) n))
7497 ;;; Vertical tree motion, cutting and pasting of subtrees
7499 (defun org-move-subtree-up (&optional arg)
7500 "Move the current subtree up past ARG headlines of the same level."
7501 (interactive "p")
7502 (org-move-subtree-down (- (prefix-numeric-value arg))))
7504 (defun org-move-subtree-down (&optional arg)
7505 "Move the current subtree down past ARG headlines of the same level."
7506 (interactive "p")
7507 (setq arg (prefix-numeric-value arg))
7508 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7509 'org-get-last-sibling))
7510 (ins-point (make-marker))
7511 (cnt (abs arg))
7512 (col (current-column))
7513 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7514 ;; Select the tree
7515 (org-back-to-heading)
7516 (setq beg0 (point))
7517 (save-excursion
7518 (setq ne-beg (org-back-over-empty-lines))
7519 (setq beg (point)))
7520 (save-match-data
7521 (save-excursion (outline-end-of-heading)
7522 (setq folded (outline-invisible-p)))
7523 (outline-end-of-subtree))
7524 (outline-next-heading)
7525 (setq ne-end (org-back-over-empty-lines))
7526 (setq end (point))
7527 (goto-char beg0)
7528 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7529 ;; include less whitespace
7530 (save-excursion
7531 (goto-char beg)
7532 (forward-line (- ne-beg ne-end))
7533 (setq beg (point))))
7534 ;; Find insertion point, with error handling
7535 (while (> cnt 0)
7536 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7537 (progn (goto-char beg0)
7538 (error "Cannot move past superior level or buffer limit")))
7539 (setq cnt (1- cnt)))
7540 (if (> arg 0)
7541 ;; Moving forward - still need to move over subtree
7542 (progn (org-end-of-subtree t t)
7543 (save-excursion
7544 (org-back-over-empty-lines)
7545 (or (bolp) (newline)))))
7546 (setq ne-ins (org-back-over-empty-lines))
7547 (move-marker ins-point (point))
7548 (setq txt (buffer-substring beg end))
7549 (org-save-markers-in-region beg end)
7550 (delete-region beg end)
7551 (org-remove-empty-overlays-at beg)
7552 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7553 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7554 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7555 (let ((bbb (point)))
7556 (insert-before-markers txt)
7557 (org-reinstall-markers-in-region bbb)
7558 (move-marker ins-point bbb))
7559 (or (bolp) (insert "\n"))
7560 (setq ins-end (point))
7561 (goto-char ins-point)
7562 (org-skip-whitespace)
7563 (when (and (< arg 0)
7564 (org-first-sibling-p)
7565 (> ne-ins ne-beg))
7566 ;; Move whitespace back to beginning
7567 (save-excursion
7568 (goto-char ins-end)
7569 (let ((kill-whole-line t))
7570 (kill-line (- ne-ins ne-beg)) (point)))
7571 (insert (make-string (- ne-ins ne-beg) ?\n)))
7572 (move-marker ins-point nil)
7573 (if folded
7574 (hide-subtree)
7575 (org-show-entry)
7576 (show-children)
7577 (org-cycle-hide-drawers 'children))
7578 (org-clean-visibility-after-subtree-move)
7579 ;; move back to the initial column we were at
7580 (move-to-column col)))
7582 (defvar org-subtree-clip ""
7583 "Clipboard for cut and paste of subtrees.
7584 This is actually only a copy of the kill, because we use the normal kill
7585 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7587 (defvar org-subtree-clip-folded nil
7588 "Was the last copied subtree folded?
7589 This is used to fold the tree back after pasting.")
7591 (defun org-cut-subtree (&optional n)
7592 "Cut the current subtree into the clipboard.
7593 With prefix arg N, cut this many sequential subtrees.
7594 This is a short-hand for marking the subtree and then cutting it."
7595 (interactive "p")
7596 (org-copy-subtree n 'cut))
7598 (defun org-copy-subtree (&optional n cut force-store-markers)
7599 "Cut the current subtree into the clipboard.
7600 With prefix arg N, cut this many sequential subtrees.
7601 This is a short-hand for marking the subtree and then copying it.
7602 If CUT is non-nil, actually cut the subtree.
7603 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7604 of some markers in the region, even if CUT is non-nil. This is
7605 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7606 (interactive "p")
7607 (let (beg end folded (beg0 (point)))
7608 (if (org-called-interactively-p 'any)
7609 (org-back-to-heading nil) ; take what looks like a subtree
7610 (org-back-to-heading t)) ; take what is really there
7611 (org-back-over-empty-lines)
7612 (setq beg (point))
7613 (skip-chars-forward " \t\r\n")
7614 (save-match-data
7615 (save-excursion (outline-end-of-heading)
7616 (setq folded (outline-invisible-p)))
7617 (condition-case nil
7618 (org-forward-same-level (1- n) t)
7619 (error nil))
7620 (org-end-of-subtree t t))
7621 (org-back-over-empty-lines)
7622 (setq end (point))
7623 (goto-char beg0)
7624 (when (> end beg)
7625 (setq org-subtree-clip-folded folded)
7626 (when (or cut force-store-markers)
7627 (org-save-markers-in-region beg end))
7628 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7629 (setq org-subtree-clip (current-kill 0))
7630 (message "%s: Subtree(s) with %d characters"
7631 (if cut "Cut" "Copied")
7632 (length org-subtree-clip)))))
7634 (defun org-paste-subtree (&optional level tree for-yank)
7635 "Paste the clipboard as a subtree, with modification of headline level.
7636 The entire subtree is promoted or demoted in order to match a new headline
7637 level.
7639 If the cursor is at the beginning of a headline, the same level as
7640 that headline is used to paste the tree
7642 If not, the new level is derived from the *visible* headings
7643 before and after the insertion point, and taken to be the inferior headline
7644 level of the two. So if the previous visible heading is level 3 and the
7645 next is level 4 (or vice versa), level 4 will be used for insertion.
7646 This makes sure that the subtree remains an independent subtree and does
7647 not swallow low level entries.
7649 You can also force a different level, either by using a numeric prefix
7650 argument, or by inserting the heading marker by hand. For example, if the
7651 cursor is after \"*****\", then the tree will be shifted to level 5.
7653 If optional TREE is given, use this text instead of the kill ring.
7655 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7656 move back over whitespace before inserting, and move point to the end of
7657 the inserted text when done."
7658 (interactive "P")
7659 (setq tree (or tree (and kill-ring (current-kill 0))))
7660 (unless (org-kill-is-subtree-p tree)
7661 (error "%s"
7662 (substitute-command-keys
7663 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7664 (org-with-limited-levels
7665 (let* ((visp (not (outline-invisible-p)))
7666 (txt tree)
7667 (^re_ "\\(\\*+\\)[ \t]*")
7668 (old-level (if (string-match org-outline-regexp-bol txt)
7669 (- (match-end 0) (match-beginning 0) 1)
7670 -1))
7671 (force-level (cond (level (prefix-numeric-value level))
7672 ((and (looking-at "[ \t]*$")
7673 (string-match
7674 "^\\*+$" (buffer-substring
7675 (point-at-bol) (point))))
7676 (- (match-end 1) (match-beginning 1)))
7677 ((and (bolp)
7678 (looking-at org-outline-regexp))
7679 (- (match-end 0) (point) 1))
7680 (t nil)))
7681 (previous-level (save-excursion
7682 (condition-case nil
7683 (progn
7684 (outline-previous-visible-heading 1)
7685 (if (looking-at ^re_)
7686 (- (match-end 0) (match-beginning 0) 1)
7688 (error 1))))
7689 (next-level (save-excursion
7690 (condition-case nil
7691 (progn
7692 (or (looking-at org-outline-regexp)
7693 (outline-next-visible-heading 1))
7694 (if (looking-at ^re_)
7695 (- (match-end 0) (match-beginning 0) 1)
7697 (error 1))))
7698 (new-level (or force-level (max previous-level next-level)))
7699 (shift (if (or (= old-level -1)
7700 (= new-level -1)
7701 (= old-level new-level))
7703 (- new-level old-level)))
7704 (delta (if (> shift 0) -1 1))
7705 (func (if (> shift 0) 'org-demote 'org-promote))
7706 (org-odd-levels-only nil)
7707 beg end newend)
7708 ;; Remove the forced level indicator
7709 (if force-level
7710 (delete-region (point-at-bol) (point)))
7711 ;; Paste
7712 (beginning-of-line (if (bolp) 1 2))
7713 (unless for-yank (org-back-over-empty-lines))
7714 (setq beg (point))
7715 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7716 (insert-before-markers txt)
7717 (unless (string-match "\n\\'" txt) (insert "\n"))
7718 (setq newend (point))
7719 (org-reinstall-markers-in-region beg)
7720 (setq end (point))
7721 (goto-char beg)
7722 (skip-chars-forward " \t\n\r")
7723 (setq beg (point))
7724 (if (and (outline-invisible-p) visp)
7725 (save-excursion (outline-show-heading)))
7726 ;; Shift if necessary
7727 (unless (= shift 0)
7728 (save-restriction
7729 (narrow-to-region beg end)
7730 (while (not (= shift 0))
7731 (org-map-region func (point-min) (point-max))
7732 (setq shift (+ delta shift)))
7733 (goto-char (point-min))
7734 (setq newend (point-max))))
7735 (when (or (org-called-interactively-p 'interactive) for-yank)
7736 (message "Clipboard pasted as level %d subtree" new-level))
7737 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7738 kill-ring
7739 (eq org-subtree-clip (current-kill 0))
7740 org-subtree-clip-folded)
7741 ;; The tree was folded before it was killed/copied
7742 (hide-subtree))
7743 (and for-yank (goto-char newend)))))
7745 (defun org-kill-is-subtree-p (&optional txt)
7746 "Check if the current kill is an outline subtree, or a set of trees.
7747 Returns nil if kill does not start with a headline, or if the first
7748 headline level is not the largest headline level in the tree.
7749 So this will actually accept several entries of equal levels as well,
7750 which is OK for `org-paste-subtree'.
7751 If optional TXT is given, check this string instead of the current kill."
7752 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7753 (re (org-get-limited-outline-regexp))
7754 (^re (concat "^" re))
7755 (start-level (and kill
7756 (string-match
7757 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7758 kill)
7759 (- (match-end 2) (match-beginning 2) 1)))
7760 (start (1+ (or (match-beginning 2) -1))))
7761 (if (not start-level)
7762 (progn
7763 nil) ;; does not even start with a heading
7764 (catch 'exit
7765 (while (setq start (string-match ^re kill (1+ start)))
7766 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7767 (throw 'exit nil)))
7768 t))))
7770 (defvar org-markers-to-move nil
7771 "Markers that should be moved with a cut-and-paste operation.
7772 Those markers are stored together with their positions relative to
7773 the start of the region.")
7775 (defun org-save-markers-in-region (beg end)
7776 "Check markers in region.
7777 If these markers are between BEG and END, record their position relative
7778 to BEG, so that after moving the block of text, we can put the markers back
7779 into place.
7780 This function gets called just before an entry or tree gets cut from the
7781 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7782 called immediately, to move the markers with the entries."
7783 (setq org-markers-to-move nil)
7784 (when (featurep 'org-clock)
7785 (org-clock-save-markers-for-cut-and-paste beg end))
7786 (when (featurep 'org-agenda)
7787 (org-agenda-save-markers-for-cut-and-paste beg end)))
7789 (defun org-check-and-save-marker (marker beg end)
7790 "Check if MARKER is between BEG and END.
7791 If yes, remember the marker and the distance to BEG."
7792 (when (and (marker-buffer marker)
7793 (equal (marker-buffer marker) (current-buffer)))
7794 (if (and (>= marker beg) (< marker end))
7795 (push (cons marker (- marker beg)) org-markers-to-move))))
7797 (defun org-reinstall-markers-in-region (beg)
7798 "Move all remembered markers to their position relative to BEG."
7799 (mapc (lambda (x)
7800 (move-marker (car x) (+ beg (cdr x))))
7801 org-markers-to-move)
7802 (setq org-markers-to-move nil))
7804 (defun org-narrow-to-subtree ()
7805 "Narrow buffer to the current subtree."
7806 (interactive)
7807 (save-excursion
7808 (save-match-data
7809 (org-with-limited-levels
7810 (narrow-to-region
7811 (progn (org-back-to-heading t) (point))
7812 (progn (org-end-of-subtree t t)
7813 (if (and (org-on-heading-p) (not (eobp))) (backward-char 1))
7814 (point)))))))
7816 (defun org-narrow-to-block ()
7817 "Narrow buffer to the current block."
7818 (interactive)
7819 (let* ((case-fold-search t)
7820 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7821 "^[ \t]*#\\+end_.*")))
7822 (if blockp
7823 (narrow-to-region (car blockp) (cdr blockp))
7824 (error "Not in a block"))))
7826 (eval-when-compile
7827 (defvar org-property-drawer-re))
7829 (defvar org-property-start-re) ;; defined below
7830 (defun org-clone-subtree-with-time-shift (n &optional shift)
7831 "Clone the task (subtree) at point N times.
7832 The clones will be inserted as siblings.
7834 In interactive use, the user will be prompted for the number of
7835 clones to be produced, and for a time SHIFT, which may be a
7836 repeater as used in time stamps, for example `+3d'.
7838 When a valid repeater is given and the entry contains any time
7839 stamps, the clones will become a sequence in time, with time
7840 stamps in the subtree shifted for each clone produced. If SHIFT
7841 is nil or the empty string, time stamps will be left alone. The
7842 ID property of the original subtree is removed.
7844 If the original subtree did contain time stamps with a repeater,
7845 the following will happen:
7846 - the repeater will be removed in each clone
7847 - an additional clone will be produced, with the current, unshifted
7848 date(s) in the entry.
7849 - the original entry will be placed *after* all the clones, with
7850 repeater intact.
7851 - the start days in the repeater in the original entry will be shifted
7852 to past the last clone.
7853 I this way you can spell out a number of instances of a repeating task,
7854 and still retain the repeater to cover future instances of the task."
7855 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7856 (let (beg end template task idprop
7857 shift-n shift-what doshift nmin nmax (n-no-remove -1))
7858 (if (not (and (integerp n) (> n 0)))
7859 (error "Invalid number of replications %s" n))
7860 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7861 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
7862 shift)))
7863 (error "Invalid shift specification %s" shift))
7864 (when doshift
7865 (setq shift-n (string-to-number (match-string 1 shift))
7866 shift-what (cdr (assoc (match-string 2 shift)
7867 '(("d" . day) ("w" . week)
7868 ("m" . month) ("y" . year))))))
7869 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7870 (setq nmin 1 nmax n)
7871 (org-back-to-heading t)
7872 (setq beg (point))
7873 (setq idprop (org-entry-get nil "ID"))
7874 (org-end-of-subtree t t)
7875 (or (bolp) (insert "\n"))
7876 (setq end (point))
7877 (setq template (buffer-substring beg end))
7878 ;; Remove clocks and empty drawers
7879 (with-temp-buffer
7880 (insert template)
7881 (goto-char (point-min))
7882 (while (re-search-forward
7883 "^[ \t]*CLOCK:.*$" (save-excursion (org-end-of-subtree t t)) t)
7884 (replace-match "")
7885 (kill-whole-line))
7886 (goto-char (point-min))
7887 (while (re-search-forward
7888 (concat "^[ \t]*:" (regexp-opt org-drawers) ":[ \t]*$") nil t)
7889 (mapc (lambda(d) (org-remove-empty-drawer-at d (point))) org-drawers))
7890 (setq template (buffer-substring (point-min) (point-max))))
7891 (when (and doshift
7892 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
7893 (delete-region beg end)
7894 (setq end beg)
7895 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7896 (goto-char end)
7897 (loop for n from nmin to nmax do
7898 ;; prepare clone
7899 (with-temp-buffer
7900 (insert template)
7901 (org-mode)
7902 (goto-char (point-min))
7903 (and idprop (if org-clone-delete-id
7904 (org-entry-delete nil "ID")
7905 (org-id-get-create t)))
7906 (while (re-search-forward org-property-start-re nil t)
7907 (org-remove-empty-drawer-at "PROPERTIES" (point)))
7908 (goto-char (point-min))
7909 (when doshift
7910 (while (re-search-forward org-ts-regexp-both nil t)
7911 (org-timestamp-change (* n shift-n) shift-what))
7912 (unless (= n n-no-remove)
7913 (goto-char (point-min))
7914 (while (re-search-forward org-ts-regexp nil t)
7915 (save-excursion
7916 (goto-char (match-beginning 0))
7917 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
7918 (delete-region (match-beginning 1) (match-end 1)))))))
7919 (setq task (buffer-string)))
7920 (insert task))
7921 (goto-char beg)))
7923 ;;; Outline Sorting
7925 (defun org-sort (with-case)
7926 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
7927 Optional argument WITH-CASE means sort case-sensitively.
7928 With a double prefix argument, also remove duplicate entries."
7929 (interactive "P")
7930 (cond
7931 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
7932 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
7934 (org-call-with-arg 'org-sort-entries with-case))))
7936 (defun org-sort-remove-invisible (s)
7937 (remove-text-properties 0 (length s) org-rm-props s)
7938 (while (string-match org-bracket-link-regexp s)
7939 (setq s (replace-match (if (match-end 2)
7940 (match-string 3 s)
7941 (match-string 1 s)) t t s)))
7944 (defvar org-priority-regexp) ; defined later in the file
7946 (defvar org-after-sorting-entries-or-items-hook nil
7947 "Hook that is run after a bunch of entries or items have been sorted.
7948 When children are sorted, the cursor is in the parent line when this
7949 hook gets called. When a region or a plain list is sorted, the cursor
7950 will be in the first entry of the sorted region/list.")
7952 (defun org-sort-entries
7953 (&optional with-case sorting-type getkey-func compare-func property)
7954 "Sort entries on a certain level of an outline tree.
7955 If there is an active region, the entries in the region are sorted.
7956 Else, if the cursor is before the first entry, sort the top-level items.
7957 Else, the children of the entry at point are sorted.
7959 Sorting can be alphabetically, numerically, by date/time as given by
7960 a time stamp, by a property or by priority.
7962 The command prompts for the sorting type unless it has been given to the
7963 function through the SORTING-TYPE argument, which needs to be a character,
7964 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
7965 precise meaning of each character:
7967 n Numerically, by converting the beginning of the entry/item to a number.
7968 a Alphabetically, ignoring the TODO keyword and the priority, if any.
7969 t By date/time, either the first active time stamp in the entry, or, if
7970 none exist, by the first inactive one.
7971 s By the scheduled date/time.
7972 d By deadline date/time.
7973 c By creation time, which is assumed to be the first inactive time stamp
7974 at the beginning of a line.
7975 p By priority according to the cookie.
7976 r By the value of a property.
7978 Capital letters will reverse the sort order.
7980 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
7981 called with point at the beginning of the record. It must return either
7982 a string or a number that should serve as the sorting key for that record.
7984 Comparing entries ignores case by default. However, with an optional argument
7985 WITH-CASE, the sorting considers case as well."
7986 (interactive "P")
7987 (let ((case-func (if with-case 'identity 'downcase))
7988 start beg end stars re re2
7989 txt what tmp)
7990 ;; Find beginning and end of region to sort
7991 (cond
7992 ((org-region-active-p)
7993 ;; we will sort the region
7994 (setq end (region-end)
7995 what "region")
7996 (goto-char (region-beginning))
7997 (if (not (org-on-heading-p)) (outline-next-heading))
7998 (setq start (point)))
7999 ((or (org-on-heading-p)
8000 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8001 ;; we will sort the children of the current headline
8002 (org-back-to-heading)
8003 (setq start (point)
8004 end (progn (org-end-of-subtree t t)
8005 (or (bolp) (insert "\n"))
8006 (org-back-over-empty-lines)
8007 (point))
8008 what "children")
8009 (goto-char start)
8010 (show-subtree)
8011 (outline-next-heading))
8013 ;; we will sort the top-level entries in this file
8014 (goto-char (point-min))
8015 (or (org-on-heading-p) (outline-next-heading))
8016 (setq start (point))
8017 (goto-char (point-max))
8018 (beginning-of-line 1)
8019 (when (looking-at ".*?\\S-")
8020 ;; File ends in a non-white line
8021 (end-of-line 1)
8022 (insert "\n"))
8023 (setq end (point-max))
8024 (setq what "top-level")
8025 (goto-char start)
8026 (show-all)))
8028 (setq beg (point))
8029 (if (>= beg end) (error "Nothing to sort"))
8031 (looking-at "\\(\\*+\\)")
8032 (setq stars (match-string 1)
8033 re (concat "^" (regexp-quote stars) " +")
8034 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8035 txt (buffer-substring beg end))
8036 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8037 (if (and (not (equal stars "*")) (string-match re2 txt))
8038 (error "Region to sort contains a level above the first entry"))
8040 (unless sorting-type
8041 (message
8042 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8043 [t]ime [s]cheduled [d]eadline [c]reated
8044 A/N/T/S/D/C/P/O/F means reversed:"
8045 what)
8046 (setq sorting-type (read-char-exclusive))
8048 (and (= (downcase sorting-type) ?f)
8049 (setq getkey-func
8050 (org-icompleting-read "Sort using function: "
8051 obarray 'fboundp t nil nil))
8052 (setq getkey-func (intern getkey-func)))
8054 (and (= (downcase sorting-type) ?r)
8055 (setq property
8056 (org-icompleting-read "Property: "
8057 (mapcar 'list (org-buffer-property-keys t))
8058 nil t))))
8060 (message "Sorting entries...")
8062 (save-restriction
8063 (narrow-to-region start end)
8064 (let ((dcst (downcase sorting-type))
8065 (case-fold-search nil)
8066 (now (current-time)))
8067 (sort-subr
8068 (/= dcst sorting-type)
8069 ;; This function moves to the beginning character of the "record" to
8070 ;; be sorted.
8071 (lambda nil
8072 (if (re-search-forward re nil t)
8073 (goto-char (match-beginning 0))
8074 (goto-char (point-max))))
8075 ;; This function moves to the last character of the "record" being
8076 ;; sorted.
8077 (lambda nil
8078 (save-match-data
8079 (condition-case nil
8080 (outline-forward-same-level 1)
8081 (error
8082 (goto-char (point-max))))))
8083 ;; This function returns the value that gets sorted against.
8084 (lambda nil
8085 (cond
8086 ((= dcst ?n)
8087 (if (looking-at org-complex-heading-regexp)
8088 (string-to-number (match-string 4))
8089 nil))
8090 ((= dcst ?a)
8091 (if (looking-at org-complex-heading-regexp)
8092 (funcall case-func (match-string 4))
8093 nil))
8094 ((= dcst ?t)
8095 (let ((end (save-excursion (outline-next-heading) (point))))
8096 (if (or (re-search-forward org-ts-regexp end t)
8097 (re-search-forward org-ts-regexp-both end t))
8098 (org-time-string-to-seconds (match-string 0))
8099 (org-float-time now))))
8100 ((= dcst ?c)
8101 (let ((end (save-excursion (outline-next-heading) (point))))
8102 (if (re-search-forward
8103 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8104 end t)
8105 (org-time-string-to-seconds (match-string 0))
8106 (org-float-time now))))
8107 ((= dcst ?s)
8108 (let ((end (save-excursion (outline-next-heading) (point))))
8109 (if (re-search-forward org-scheduled-time-regexp end t)
8110 (org-time-string-to-seconds (match-string 1))
8111 (org-float-time now))))
8112 ((= dcst ?d)
8113 (let ((end (save-excursion (outline-next-heading) (point))))
8114 (if (re-search-forward org-deadline-time-regexp end t)
8115 (org-time-string-to-seconds (match-string 1))
8116 (org-float-time now))))
8117 ((= dcst ?p)
8118 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8119 (string-to-char (match-string 2))
8120 org-default-priority))
8121 ((= dcst ?r)
8122 (or (org-entry-get nil property) ""))
8123 ((= dcst ?o)
8124 (if (looking-at org-complex-heading-regexp)
8125 (- 9999 (length (member (match-string 2)
8126 org-todo-keywords-1)))))
8127 ((= dcst ?f)
8128 (if getkey-func
8129 (progn
8130 (setq tmp (funcall getkey-func))
8131 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8132 tmp)
8133 (error "Invalid key function `%s'" getkey-func)))
8134 (t (error "Invalid sorting type `%c'" sorting-type))))
8136 (cond
8137 ((= dcst ?a) 'string<)
8138 ((= dcst ?f) compare-func)
8139 ((member dcst '(?p ?t ?s ?d ?c)) '<)
8140 (t nil)))))
8141 (run-hooks 'org-after-sorting-entries-or-items-hook)
8142 (message "Sorting entries...done")))
8144 (defun org-do-sort (table what &optional with-case sorting-type)
8145 "Sort TABLE of WHAT according to SORTING-TYPE.
8146 The user will be prompted for the SORTING-TYPE if the call to this
8147 function does not specify it. WHAT is only for the prompt, to indicate
8148 what is being sorted. The sorting key will be extracted from
8149 the car of the elements of the table.
8150 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8151 (unless sorting-type
8152 (message
8153 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8154 what)
8155 (setq sorting-type (read-char-exclusive)))
8156 (let ((dcst (downcase sorting-type))
8157 extractfun comparefun)
8158 ;; Define the appropriate functions
8159 (cond
8160 ((= dcst ?n)
8161 (setq extractfun 'string-to-number
8162 comparefun (if (= dcst sorting-type) '< '>)))
8163 ((= dcst ?a)
8164 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8165 (lambda(x) (downcase (org-sort-remove-invisible x))))
8166 comparefun (if (= dcst sorting-type)
8167 'string<
8168 (lambda (a b) (and (not (string< a b))
8169 (not (string= a b)))))))
8170 ((= dcst ?t)
8171 (setq extractfun
8172 (lambda (x)
8173 (if (or (string-match org-ts-regexp x)
8174 (string-match org-ts-regexp-both x))
8175 (org-float-time
8176 (org-time-string-to-time (match-string 0 x)))
8178 comparefun (if (= dcst sorting-type) '< '>)))
8179 (t (error "Invalid sorting type `%c'" sorting-type)))
8181 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8182 table)
8183 (lambda (a b) (funcall comparefun (car a) (car b))))))
8186 ;;; The orgstruct minor mode
8188 ;; Define a minor mode which can be used in other modes in order to
8189 ;; integrate the org-mode structure editing commands.
8191 ;; This is really a hack, because the org-mode structure commands use
8192 ;; keys which normally belong to the major mode. Here is how it
8193 ;; works: The minor mode defines all the keys necessary to operate the
8194 ;; structure commands, but wraps the commands into a function which
8195 ;; tests if the cursor is currently at a headline or a plain list
8196 ;; item. If that is the case, the structure command is used,
8197 ;; temporarily setting many Org-mode variables like regular
8198 ;; expressions for filling etc. However, when any of those keys is
8199 ;; used at a different location, function uses `key-binding' to look
8200 ;; up if the key has an associated command in another currently active
8201 ;; keymap (minor modes, major mode, global), and executes that
8202 ;; command. There might be problems if any of the keys is otherwise
8203 ;; used as a prefix key.
8205 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8206 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8207 ;; addresses this by checking explicitly for both bindings.
8209 (defvar orgstruct-mode-map (make-sparse-keymap)
8210 "Keymap for the minor `orgstruct-mode'.")
8212 (defvar org-local-vars nil
8213 "List of local variables, for use by `orgstruct-mode'.")
8215 ;;;###autoload
8216 (define-minor-mode orgstruct-mode
8217 "Toggle the minor mode `orgstruct-mode'.
8218 This mode is for using Org-mode structure commands in other
8219 modes. The following keys behave as if Org-mode were active, if
8220 the cursor is on a headline, or on a plain list item (both as
8221 defined by Org-mode).
8223 M-up Move entry/item up
8224 M-down Move entry/item down
8225 M-left Promote
8226 M-right Demote
8227 M-S-up Move entry/item up
8228 M-S-down Move entry/item down
8229 M-S-left Promote subtree
8230 M-S-right Demote subtree
8231 M-q Fill paragraph and items like in Org-mode
8232 C-c ^ Sort entries
8233 C-c - Cycle list bullet
8234 TAB Cycle item visibility
8235 M-RET Insert new heading/item
8236 S-M-RET Insert new TODO heading / Checkbox item
8237 C-c C-c Set tags / toggle checkbox"
8238 nil " OrgStruct" nil
8239 (org-load-modules-maybe)
8240 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8242 ;;;###autoload
8243 (defun turn-on-orgstruct ()
8244 "Unconditionally turn on `orgstruct-mode'."
8245 (orgstruct-mode 1))
8247 (defun orgstruct++-mode (&optional arg)
8248 "Toggle `orgstruct-mode', the enhanced version of it.
8249 In addition to setting orgstruct-mode, this also exports all indentation
8250 and autofilling variables from org-mode into the buffer. It will also
8251 recognize item context in multiline items.
8252 Note that turning off orgstruct-mode will *not* remove the
8253 indentation/paragraph settings. This can only be done by refreshing the
8254 major mode, for example with \\[normal-mode]."
8255 (interactive "P")
8256 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8257 (if (< arg 1)
8258 (orgstruct-mode -1)
8259 (orgstruct-mode 1)
8260 (let (var val)
8261 (mapc
8262 (lambda (x)
8263 (when (string-match
8264 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8265 (symbol-name (car x)))
8266 (setq var (car x) val (nth 1 x))
8267 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8268 org-local-vars)
8269 (org-set-local 'orgstruct-is-++ t))))
8271 (defvar orgstruct-is-++ nil
8272 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8273 (make-variable-buffer-local 'orgstruct-is-++)
8275 ;;;###autoload
8276 (defun turn-on-orgstruct++ ()
8277 "Unconditionally turn on `orgstruct++-mode'."
8278 (orgstruct++-mode 1))
8280 (defun orgstruct-error ()
8281 "Error when there is no default binding for a structure key."
8282 (interactive)
8283 (error "This key has no function outside structure elements"))
8285 (defun orgstruct-setup ()
8286 "Setup orgstruct keymaps."
8287 (let ((nfunc 0)
8288 (bindings
8289 (list
8290 '([(meta up)] org-metaup)
8291 '([(meta down)] org-metadown)
8292 '([(meta left)] org-metaleft)
8293 '([(meta right)] org-metaright)
8294 '([(meta shift up)] org-shiftmetaup)
8295 '([(meta shift down)] org-shiftmetadown)
8296 '([(meta shift left)] org-shiftmetaleft)
8297 '([(meta shift right)] org-shiftmetaright)
8298 '([?\e (up)] org-metaup)
8299 '([?\e (down)] org-metadown)
8300 '([?\e (left)] org-metaleft)
8301 '([?\e (right)] org-metaright)
8302 '([?\e (shift up)] org-shiftmetaup)
8303 '([?\e (shift down)] org-shiftmetadown)
8304 '([?\e (shift left)] org-shiftmetaleft)
8305 '([?\e (shift right)] org-shiftmetaright)
8306 '([(shift up)] org-shiftup)
8307 '([(shift down)] org-shiftdown)
8308 '([(shift left)] org-shiftleft)
8309 '([(shift right)] org-shiftright)
8310 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8311 '("\M-q" fill-paragraph)
8312 '("\C-c^" org-sort)
8313 '("\C-c-" org-cycle-list-bullet)))
8314 elt key fun cmd)
8315 (while (setq elt (pop bindings))
8316 (setq nfunc (1+ nfunc))
8317 (setq key (org-key (car elt))
8318 fun (nth 1 elt)
8319 cmd (orgstruct-make-binding fun nfunc key))
8320 (org-defkey orgstruct-mode-map key cmd))
8322 ;; Special treatment needed for TAB and RET
8323 (org-defkey orgstruct-mode-map [(tab)]
8324 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8325 (org-defkey orgstruct-mode-map "\C-i"
8326 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8328 (org-defkey orgstruct-mode-map "\M-\C-m"
8329 (orgstruct-make-binding 'org-insert-heading 105
8330 "\M-\C-m" [(meta return)]))
8331 (org-defkey orgstruct-mode-map [(meta return)]
8332 (orgstruct-make-binding 'org-insert-heading 106
8333 [(meta return)] "\M-\C-m"))
8335 (org-defkey orgstruct-mode-map [(shift meta return)]
8336 (orgstruct-make-binding 'org-insert-todo-heading 107
8337 [(meta return)] "\M-\C-m"))
8339 (org-defkey orgstruct-mode-map "\e\C-m"
8340 (orgstruct-make-binding 'org-insert-heading 108
8341 "\e\C-m" [?\e (return)]))
8342 (org-defkey orgstruct-mode-map [?\e (return)]
8343 (orgstruct-make-binding 'org-insert-heading 109
8344 [?\e (return)] "\e\C-m"))
8345 (org-defkey orgstruct-mode-map [?\e (shift return)]
8346 (orgstruct-make-binding 'org-insert-todo-heading 110
8347 [?\e (return)] "\e\C-m"))
8349 (unless org-local-vars
8350 (setq org-local-vars (org-get-local-variables)))
8354 (defun orgstruct-make-binding (fun n &rest keys)
8355 "Create a function for binding in the structure minor mode.
8356 FUN is the command to call inside a table. N is used to create a unique
8357 command name. KEYS are keys that should be checked in for a command
8358 to execute outside of tables."
8359 (eval
8360 (list 'defun
8361 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8362 '(arg)
8363 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8364 "Outside of structure, run the binding of `"
8365 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8366 "'.")
8367 '(interactive "p")
8368 (list 'if
8369 `(org-context-p 'headline 'item
8370 (and orgstruct-is-++
8371 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8372 'item-body))
8373 (list 'org-run-like-in-org-mode (list 'quote fun))
8374 (list 'let '(orgstruct-mode)
8375 (list 'call-interactively
8376 (append '(or)
8377 (mapcar (lambda (k)
8378 (list 'key-binding k))
8379 keys)
8380 '('orgstruct-error))))))))
8382 (defun org-context-p (&rest contexts)
8383 "Check if local context is any of CONTEXTS.
8384 Possible values in the list of contexts are `table', `headline', and `item'."
8385 (let ((pos (point)))
8386 (goto-char (point-at-bol))
8387 (prog1 (or (and (memq 'table contexts)
8388 (looking-at "[ \t]*|"))
8389 (and (memq 'headline contexts)
8390 (looking-at org-outline-regexp))
8391 (and (memq 'item contexts)
8392 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8393 (and (memq 'item-body contexts)
8394 (org-in-item-p)))
8395 (goto-char pos))))
8397 (defun org-get-local-variables ()
8398 "Return a list of all local variables in an org-mode buffer."
8399 (let (varlist)
8400 (with-current-buffer (get-buffer-create "*Org tmp*")
8401 (erase-buffer)
8402 (org-mode)
8403 (setq varlist (buffer-local-variables)))
8404 (kill-buffer "*Org tmp*")
8405 (delq nil
8406 (mapcar
8407 (lambda (x)
8408 (setq x
8409 (if (symbolp x)
8410 (list x)
8411 (list (car x) (list 'quote (cdr x)))))
8412 (if (string-match
8413 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8414 (symbol-name (car x)))
8415 x nil))
8416 varlist))))
8418 (defun org-clone-local-variables (from-buffer &optional regexp)
8419 "Clone local variables from FROM-BUFFER.
8420 Optional argument REGEXP selects variables to clone."
8421 (mapc
8422 (lambda (pair)
8423 (and (symbolp (car pair))
8424 (or (null regexp)
8425 (string-match regexp (symbol-name (car pair))))
8426 (set (make-local-variable (car pair))
8427 (cdr pair))))
8428 (buffer-local-variables from-buffer)))
8430 ;;;###autoload
8431 (defun org-run-like-in-org-mode (cmd)
8432 "Run a command, pretending that the current buffer is in Org-mode.
8433 This will temporarily bind local variables that are typically bound in
8434 Org-mode to the values they have in Org-mode, and then interactively
8435 call CMD."
8436 (org-load-modules-maybe)
8437 (unless org-local-vars
8438 (setq org-local-vars (org-get-local-variables)))
8439 (eval (list 'let org-local-vars
8440 (list 'call-interactively (list 'quote cmd)))))
8442 ;;;; Archiving
8444 (defun org-get-category (&optional pos force-refresh)
8445 "Get the category applying to position POS."
8446 (if force-refresh (org-refresh-category-properties))
8447 (let ((pos (or pos (point))))
8448 (or (get-text-property pos 'org-category)
8449 (progn (org-refresh-category-properties)
8450 (get-text-property pos 'org-category)))))
8452 (defun org-refresh-category-properties ()
8453 "Refresh category text properties in the buffer."
8454 (let ((def-cat (cond
8455 ((null org-category)
8456 (if buffer-file-name
8457 (file-name-sans-extension
8458 (file-name-nondirectory buffer-file-name))
8459 "???"))
8460 ((symbolp org-category) (symbol-name org-category))
8461 (t org-category)))
8462 beg end cat pos optionp)
8463 (org-unmodified
8464 (save-excursion
8465 (save-restriction
8466 (widen)
8467 (goto-char (point-min))
8468 (put-text-property (point) (point-max) 'org-category def-cat)
8469 (while (re-search-forward
8470 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8471 (setq pos (match-end 0)
8472 optionp (equal (char-after (match-beginning 0)) ?#)
8473 cat (org-trim (match-string 2)))
8474 (if optionp
8475 (setq beg (point-at-bol) end (point-max))
8476 (org-back-to-heading t)
8477 (setq beg (point) end (org-end-of-subtree t t)))
8478 (put-text-property beg end 'org-category cat)
8479 (put-text-property beg end 'org-category-position beg)
8480 (goto-char pos)))))))
8483 ;;;; Link Stuff
8485 ;;; Link abbreviations
8487 (defun org-link-expand-abbrev (link)
8488 "Apply replacements as defined in `org-link-abbrev-alist."
8489 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8490 (let* ((key (match-string 1 link))
8491 (as (or (assoc key org-link-abbrev-alist-local)
8492 (assoc key org-link-abbrev-alist)))
8493 (tag (and (match-end 2) (match-string 3 link)))
8494 rpl)
8495 (if (not as)
8496 link
8497 (setq rpl (cdr as))
8498 (cond
8499 ((symbolp rpl) (funcall rpl tag))
8500 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8501 ((string-match "%h" rpl)
8502 (replace-match (url-hexify-string (or tag "")) t t rpl))
8503 (t (concat rpl tag)))))
8504 link))
8506 ;;; Storing and inserting links
8508 (defvar org-insert-link-history nil
8509 "Minibuffer history for links inserted with `org-insert-link'.")
8511 (defvar org-stored-links nil
8512 "Contains the links stored with `org-store-link'.")
8514 (defvar org-store-link-plist nil
8515 "Plist with info about the most recently link created with `org-store-link'.")
8517 (defvar org-link-protocols nil
8518 "Link protocols added to Org-mode using `org-add-link-type'.")
8520 (defvar org-store-link-functions nil
8521 "List of functions that are called to create and store a link.
8522 Each function will be called in turn until one returns a non-nil
8523 value. Each function should check if it is responsible for creating
8524 this link (for example by looking at the major mode).
8525 If not, it must exit and return nil.
8526 If yes, it should return a non-nil value after a calling
8527 `org-store-link-props' with a list of properties and values.
8528 Special properties are:
8530 :type The link prefix, like \"http\". This must be given.
8531 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8532 This is obligatory as well.
8533 :description Optional default description for the second pair
8534 of brackets in an Org-mode link. The user can still change
8535 this when inserting this link into an Org-mode buffer.
8537 In addition to these, any additional properties can be specified
8538 and then used in remember templates.")
8540 (defun org-add-link-type (type &optional follow export)
8541 "Add TYPE to the list of `org-link-types'.
8542 Re-compute all regular expressions depending on `org-link-types'
8544 FOLLOW and EXPORT are two functions.
8546 FOLLOW should take the link path as the single argument and do whatever
8547 is necessary to follow the link, for example find a file or display
8548 a mail message.
8550 EXPORT should format the link path for export to one of the export formats.
8551 It should be a function accepting three arguments:
8553 path the path of the link, the text after the prefix (like \"http:\")
8554 desc the description of the link, if any, or a description added by
8555 org-export-normalize-links if there is none
8556 format the export format, a symbol like `html' or `latex' or `ascii'..
8558 The function may use the FORMAT information to return different values
8559 depending on the format. The return value will be put literally into
8560 the exported file. If the return value is nil, this means Org should
8561 do what it normally does with links which do not have EXPORT defined.
8563 Org-mode has a built-in default for exporting links. If you are happy with
8564 this default, there is no need to define an export function for the link
8565 type. For a simple example of an export function, see `org-bbdb.el'."
8566 (add-to-list 'org-link-types type t)
8567 (org-make-link-regexps)
8568 (if (assoc type org-link-protocols)
8569 (setcdr (assoc type org-link-protocols) (list follow export))
8570 (push (list type follow export) org-link-protocols)))
8572 (defvar org-agenda-buffer-name)
8574 ;;;###autoload
8575 (defun org-store-link (arg)
8576 "\\<org-mode-map>Store an org-link to the current location.
8577 This link is added to `org-stored-links' and can later be inserted
8578 into an org-buffer with \\[org-insert-link].
8580 For some link types, a prefix arg is interpreted:
8581 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8582 For file links, arg negates `org-context-in-file-links'."
8583 (interactive "P")
8584 (org-load-modules-maybe)
8585 (setq org-store-link-plist nil) ; reset
8586 (org-with-limited-levels
8587 (let (link cpltxt desc description search txt custom-id agenda-link)
8588 (cond
8590 ((run-hook-with-args-until-success 'org-store-link-functions)
8591 (setq link (plist-get org-store-link-plist :link)
8592 desc (or (plist-get org-store-link-plist :description) link)))
8594 ((equal (buffer-name) "*Org Edit Src Example*")
8595 (let (label gc)
8596 (while (or (not label)
8597 (save-excursion
8598 (save-restriction
8599 (widen)
8600 (goto-char (point-min))
8601 (re-search-forward
8602 (regexp-quote (format org-coderef-label-format label))
8603 nil t))))
8604 (when label (message "Label exists already") (sit-for 2))
8605 (setq label (read-string "Code line label: " label)))
8606 (end-of-line 1)
8607 (setq link (format org-coderef-label-format label))
8608 (setq gc (- 79 (length link)))
8609 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8610 (insert link)
8611 (setq link (concat "(" label ")") desc nil)))
8613 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8614 ;; We are in the agenda, link to referenced location
8615 (let ((m (or (get-text-property (point) 'org-hd-marker)
8616 (get-text-property (point) 'org-marker))))
8617 (when m
8618 (org-with-point-at m
8619 (setq agenda-link
8620 (if (org-called-interactively-p 'any)
8621 (call-interactively 'org-store-link)
8622 (org-store-link nil)))))))
8624 ((eq major-mode 'calendar-mode)
8625 (let ((cd (calendar-cursor-to-date)))
8626 (setq link
8627 (format-time-string
8628 (car org-time-stamp-formats)
8629 (apply 'encode-time
8630 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8631 nil nil nil))))
8632 (org-store-link-props :type "calendar" :date cd)))
8634 ((eq major-mode 'w3-mode)
8635 (setq cpltxt (if (and (buffer-name)
8636 (not (string-match "Untitled" (buffer-name))))
8637 (buffer-name)
8638 (url-view-url t))
8639 link (org-make-link (url-view-url t)))
8640 (org-store-link-props :type "w3" :url (url-view-url t)))
8642 ((eq major-mode 'w3m-mode)
8643 (setq cpltxt (or w3m-current-title w3m-current-url)
8644 link (org-make-link w3m-current-url))
8645 (org-store-link-props :type "w3m" :url (url-view-url t)))
8647 ((setq search (run-hook-with-args-until-success
8648 'org-create-file-search-functions))
8649 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8650 "::" search))
8651 (setq cpltxt (or description link)))
8653 ((eq major-mode 'image-mode)
8654 (setq cpltxt (concat "file:"
8655 (abbreviate-file-name buffer-file-name))
8656 link (org-make-link cpltxt))
8657 (org-store-link-props :type "image" :file buffer-file-name))
8659 ((eq major-mode 'dired-mode)
8660 ;; link to the file in the current line
8661 (let ((file (dired-get-filename nil t)))
8662 (setq file (if file
8663 (abbreviate-file-name
8664 (expand-file-name (dired-get-filename nil t)))
8665 ;; otherwise, no file so use current directory.
8666 default-directory))
8667 (setq cpltxt (concat "file:" file)
8668 link (org-make-link cpltxt))))
8670 ((and (buffer-file-name (buffer-base-buffer)) (eq major-mode 'org-mode))
8671 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8672 (cond
8673 ((org-in-regexp "<<\\(.*?\\)>>")
8674 (setq cpltxt
8675 (concat "file:"
8676 (abbreviate-file-name
8677 (buffer-file-name (buffer-base-buffer)))
8678 "::" (match-string 1))
8679 link (org-make-link cpltxt)))
8680 ((and (featurep 'org-id)
8681 (or (eq org-link-to-org-use-id t)
8682 (and (eq org-link-to-org-use-id 'create-if-interactive)
8683 (org-called-interactively-p 'any))
8684 (and (eq org-link-to-org-use-id
8685 'create-if-interactive-and-no-custom-id)
8686 (org-called-interactively-p 'any)
8687 (not custom-id))
8688 (and org-link-to-org-use-id
8689 (org-entry-get nil "ID"))))
8690 ;; We can make a link using the ID.
8691 (setq link (condition-case nil
8692 (prog1 (org-id-store-link)
8693 (setq desc (plist-get org-store-link-plist
8694 :description)))
8695 (error
8696 ;; probably before first headline, link to file only
8697 (concat "file:"
8698 (abbreviate-file-name
8699 (buffer-file-name (buffer-base-buffer))))))))
8701 ;; Just link to current headline
8702 (setq cpltxt (concat "file:"
8703 (abbreviate-file-name
8704 (buffer-file-name (buffer-base-buffer)))))
8705 ;; Add a context search string
8706 (when (org-xor org-context-in-file-links arg)
8707 (setq txt (cond
8708 ((org-on-heading-p) nil)
8709 ((org-region-active-p)
8710 (buffer-substring (region-beginning) (region-end)))
8711 (t nil)))
8712 (when (or (null txt) (string-match "\\S-" txt))
8713 (setq cpltxt
8714 (concat cpltxt "::"
8715 (condition-case nil
8716 (org-make-org-heading-search-string txt)
8717 (error "")))
8718 desc (or (nth 4 (ignore-errors
8719 (org-heading-components))) "NONE"))))
8720 (if (string-match "::\\'" cpltxt)
8721 (setq cpltxt (substring cpltxt 0 -2)))
8722 (setq link (org-make-link cpltxt)))))
8724 ((buffer-file-name (buffer-base-buffer))
8725 ;; Just link to this file here.
8726 (setq cpltxt (concat "file:"
8727 (abbreviate-file-name
8728 (buffer-file-name (buffer-base-buffer)))))
8729 ;; Add a context string
8730 (when (org-xor org-context-in-file-links arg)
8731 (setq txt (if (org-region-active-p)
8732 (buffer-substring (region-beginning) (region-end))
8733 (buffer-substring (point-at-bol) (point-at-eol))))
8734 ;; Only use search option if there is some text.
8735 (when (string-match "\\S-" txt)
8736 (setq cpltxt
8737 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8738 desc "NONE")))
8739 (setq link (org-make-link cpltxt)))
8741 ((org-called-interactively-p 'interactive)
8742 (error "Cannot link to a buffer which is not visiting a file"))
8744 (t (setq link nil)))
8746 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8747 (setq link (or link cpltxt)
8748 desc (or desc cpltxt))
8749 (if (equal desc "NONE") (setq desc nil))
8751 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8752 (progn
8753 (setq org-stored-links
8754 (cons (list link desc) org-stored-links))
8755 (message "Stored: %s" (or desc link))
8756 (when custom-id
8757 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8758 "::#" custom-id))
8759 (setq org-stored-links
8760 (cons (list link desc) org-stored-links))))
8761 (or agenda-link (and link (org-make-link-string link desc)))))))
8763 (defun org-store-link-props (&rest plist)
8764 "Store link properties, extract names and addresses."
8765 (let (x adr)
8766 (when (setq x (plist-get plist :from))
8767 (setq adr (mail-extract-address-components x))
8768 (setq plist (plist-put plist :fromname (car adr)))
8769 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8770 (when (setq x (plist-get plist :to))
8771 (setq adr (mail-extract-address-components x))
8772 (setq plist (plist-put plist :toname (car adr)))
8773 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8774 (let ((from (plist-get plist :from))
8775 (to (plist-get plist :to)))
8776 (when (and from to org-from-is-user-regexp)
8777 (setq plist
8778 (plist-put plist :fromto
8779 (if (string-match org-from-is-user-regexp from)
8780 (concat "to %t")
8781 (concat "from %f"))))))
8782 (setq org-store-link-plist plist))
8784 (defun org-add-link-props (&rest plist)
8785 "Add these properties to the link property list."
8786 (let (key value)
8787 (while plist
8788 (setq key (pop plist) value (pop plist))
8789 (setq org-store-link-plist
8790 (plist-put org-store-link-plist key value)))))
8792 (defun org-email-link-description (&optional fmt)
8793 "Return the description part of an email link.
8794 This takes information from `org-store-link-plist' and formats it
8795 according to FMT (default from `org-email-link-description-format')."
8796 (setq fmt (or fmt org-email-link-description-format))
8797 (let* ((p org-store-link-plist)
8798 (to (plist-get p :toaddress))
8799 (from (plist-get p :fromaddress))
8800 (table
8801 (list
8802 (cons "%c" (plist-get p :fromto))
8803 (cons "%F" (plist-get p :from))
8804 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8805 (cons "%T" (plist-get p :to))
8806 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8807 (cons "%s" (plist-get p :subject))
8808 (cons "%d" (plist-get p :date))
8809 (cons "%m" (plist-get p :message-id)))))
8810 (when (string-match "%c" fmt)
8811 ;; Check if the user wrote this message
8812 (if (and org-from-is-user-regexp from to
8813 (save-match-data (string-match org-from-is-user-regexp from)))
8814 (setq fmt (replace-match "to %t" t t fmt))
8815 (setq fmt (replace-match "from %f" t t fmt))))
8816 (org-replace-escapes fmt table)))
8818 (defun org-make-org-heading-search-string (&optional string heading)
8819 "Make search string for STRING or current headline."
8820 (interactive)
8821 (let ((s (or string (org-get-heading)))
8822 (lines org-context-in-file-links))
8823 (unless (and string (not heading))
8824 ;; We are using a headline, clean up garbage in there.
8825 (if (string-match org-todo-regexp s)
8826 (setq s (replace-match "" t t s)))
8827 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8828 (setq s (replace-match "" t t s)))
8829 (setq s (org-trim s))
8830 (if (string-match (concat "^\\(" org-quote-string "\\|"
8831 org-comment-string "\\)") s)
8832 (setq s (replace-match "" t t s)))
8833 (while (string-match org-ts-regexp s)
8834 (setq s (replace-match "" t t s))))
8835 (or string (setq s (concat "*" s))) ; Add * for headlines
8836 (when (and string (integerp lines) (> lines 0))
8837 (let ((slines (org-split-string s "\n")))
8838 (when (< lines (length slines))
8839 (setq s (mapconcat
8840 'identity
8841 (reverse (nthcdr (- (length slines) lines)
8842 (reverse slines))) "\n")))))
8843 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8845 (defun org-make-link (&rest strings)
8846 "Concatenate STRINGS."
8847 (apply 'concat strings))
8849 (defun org-make-link-string (link &optional description)
8850 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8851 (unless (string-match "\\S-" link)
8852 (error "Empty link"))
8853 (when (and description
8854 (stringp description)
8855 (not (string-match "\\S-" description)))
8856 (setq description nil))
8857 (when (stringp description)
8858 ;; Remove brackets from the description, they are fatal.
8859 (while (string-match "\\[" description)
8860 (setq description (replace-match "{" t t description)))
8861 (while (string-match "\\]" description)
8862 (setq description (replace-match "}" t t description))))
8863 (when (equal link description)
8864 ;; No description needed, it is identical
8865 (setq description nil))
8866 (when (and (not description)
8867 (not (string-match (org-image-file-name-regexp) link))
8868 (not (equal link (org-link-escape link))))
8869 (setq description (org-extract-attributes link)))
8870 (setq link
8871 (cond ((string-match (org-image-file-name-regexp) link) link)
8872 ((string-match org-link-types-re link)
8873 (concat (match-string 1 link)
8874 (org-link-escape (substring link (match-end 1)))))
8875 (t (org-link-escape link))))
8876 (concat "[[" link "]"
8877 (if description (concat "[" description "]") "")
8878 "]"))
8880 (defconst org-link-escape-chars
8881 '(?\ ?\[ ?\] ?\; ?\= ?\+)
8882 "List of characters that should be escaped in link.
8883 This is the list that is used for internal purposes.")
8885 (defvar org-url-encoding-use-url-hexify nil)
8887 (defconst org-link-escape-chars-browser
8888 '(?\ )
8889 "List of escapes for characters that are problematic in links.
8890 This is the list that is used before handing over to the browser.")
8892 (defun org-link-escape (text &optional table merge)
8893 "Return percent escaped representation of TEXT.
8894 TEXT is a string with the text to escape.
8895 Optional argument TABLE is a list with characters that should be
8896 escaped. When nil, `org-link-escape-chars' is used.
8897 If optional argument MERGE is set, merge TABLE into
8898 `org-link-escape-chars'."
8899 (if (and org-url-encoding-use-url-hexify (not table))
8900 (url-hexify-string text)
8901 (cond
8902 ((and table merge)
8903 (mapc (lambda (defchr)
8904 (unless (member defchr table)
8905 (setq table (cons defchr table)))) org-link-escape-chars))
8906 ((null table)
8907 (setq table org-link-escape-chars)))
8908 (mapconcat
8909 (lambda (char)
8910 (if (or (member char table)
8911 (< char 32) (= char 37) (> char 126))
8912 (mapconcat (lambda (sequence-element)
8913 (format "%%%.2X" sequence-element))
8914 (or (encode-coding-char char 'utf-8)
8915 (error "Unable to percent escape character: %s"
8916 (char-to-string char))) "")
8917 (char-to-string char))) text "")))
8919 (defun org-link-unescape (str)
8920 "Unhex hexified unicode strings as returned from the JavaScript function
8921 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
8922 (unless (and (null str) (string= "" str))
8923 (let ((pos 0) (case-fold-search t) unhexed)
8924 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
8925 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
8926 (setq str (replace-match unhexed t t str))
8927 (setq pos (+ pos (length unhexed))))))
8928 str)
8930 (defun org-link-unescape-compound (hex)
8931 "Unhexify unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
8932 Note: this function also decodes single byte encodings like
8933 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
8934 (save-match-data
8935 (let* ((bytes (cdr (split-string hex "%")))
8936 (ret "")
8937 (eat 0)
8938 (sum 0))
8939 (while bytes
8940 (let* ((val (string-to-number (pop bytes) 16))
8941 (shift-xor
8942 (if (= 0 eat)
8943 (cond
8944 ((>= val 252) (cons 6 252))
8945 ((>= val 248) (cons 5 248))
8946 ((>= val 240) (cons 4 240))
8947 ((>= val 224) (cons 3 224))
8948 ((>= val 192) (cons 2 192))
8949 (t (cons 0 0)))
8950 (cons 6 128))))
8951 (if (>= val 192) (setq eat (car shift-xor)))
8952 (setq val (logxor val (cdr shift-xor)))
8953 (setq sum (+ (lsh sum (car shift-xor)) val))
8954 (if (> eat 0) (setq eat (- eat 1)))
8955 (cond
8956 ((= 0 eat) ;multi byte
8957 (setq ret (concat ret (org-char-to-string sum)))
8958 (setq sum 0))
8959 ((not bytes) ; single byte(s)
8960 (setq ret (org-link-unescape-single-byte-sequence hex))))
8961 )) ;; end (while bytes
8962 ret )))
8964 (defun org-link-unescape-single-byte-sequence (hex)
8965 "Unhexify hex-encoded single byte character sequences."
8966 (mapconcat (lambda (byte)
8967 (char-to-string (string-to-number byte 16)))
8968 (cdr (split-string hex "%")) ""))
8970 (defun org-xor (a b)
8971 "Exclusive or."
8972 (if a (not b) b))
8974 (defun org-fixup-message-id-for-http (s)
8975 "Replace special characters in a message id, so it can be used in an http query."
8976 (when (string-match "%" s)
8977 (setq s (mapconcat (lambda (c)
8978 (if (eq c ?%)
8979 "%25"
8980 (char-to-string c)))
8981 s "")))
8982 (while (string-match "<" s)
8983 (setq s (replace-match "%3C" t t s)))
8984 (while (string-match ">" s)
8985 (setq s (replace-match "%3E" t t s)))
8986 (while (string-match "@" s)
8987 (setq s (replace-match "%40" t t s)))
8990 ;;;###autoload
8991 (defun org-insert-link-global ()
8992 "Insert a link like Org-mode does.
8993 This command can be called in any mode to insert a link in Org-mode syntax."
8994 (interactive)
8995 (org-load-modules-maybe)
8996 (org-run-like-in-org-mode 'org-insert-link))
8998 (defun org-insert-link (&optional complete-file link-location)
8999 "Insert a link. At the prompt, enter the link.
9001 Completion can be used to insert any of the link protocol prefixes like
9002 http or ftp in use.
9004 The history can be used to select a link previously stored with
9005 `org-store-link'. When the empty string is entered (i.e. if you just
9006 press RET at the prompt), the link defaults to the most recently
9007 stored link. As SPC triggers completion in the minibuffer, you need to
9008 use M-SPC or C-q SPC to force the insertion of a space character.
9010 You will also be prompted for a description, and if one is given, it will
9011 be displayed in the buffer instead of the link.
9013 If there is already a link at point, this command will allow you to edit link
9014 and description parts.
9016 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9017 be selected using completion. The path to the file will be relative to the
9018 current directory if the file is in the current directory or a subdirectory.
9019 Otherwise, the link will be the absolute path as completed in the minibuffer
9020 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9021 option `org-link-file-path-type'.
9023 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9024 the current directory or below.
9026 With three \\[universal-argument] prefixes, negate the meaning of
9027 `org-keep-stored-link-after-insertion'.
9029 If `org-make-link-description-function' is non-nil, this function will be
9030 called with the link target, and the result will be the default
9031 link description.
9033 If the LINK-LOCATION parameter is non-nil, this value will be
9034 used as the link location instead of reading one interactively."
9035 (interactive "P")
9036 (let* ((wcf (current-window-configuration))
9037 (region (if (org-region-active-p)
9038 (buffer-substring (region-beginning) (region-end))))
9039 (remove (and region (list (region-beginning) (region-end))))
9040 (desc region)
9041 tmphist ; byte-compile incorrectly complains about this
9042 (link link-location)
9043 entry file all-prefixes)
9044 (cond
9045 (link-location) ; specified by arg, just use it.
9046 ((org-in-regexp org-bracket-link-regexp 1)
9047 ;; We do have a link at point, and we are going to edit it.
9048 (setq remove (list (match-beginning 0) (match-end 0)))
9049 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9050 (setq link (read-string "Link: "
9051 (org-link-unescape
9052 (org-match-string-no-properties 1)))))
9053 ((or (org-in-regexp org-angle-link-re)
9054 (org-in-regexp org-plain-link-re))
9055 ;; Convert to bracket link
9056 (setq remove (list (match-beginning 0) (match-end 0))
9057 link (read-string "Link: "
9058 (org-remove-angle-brackets (match-string 0)))))
9059 ((member complete-file '((4) (16)))
9060 ;; Completing read for file names.
9061 (setq link (org-file-complete-link complete-file)))
9063 ;; Read link, with completion for stored links.
9064 (with-output-to-temp-buffer "*Org Links*"
9065 (princ "Insert a link.
9066 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9067 (when org-stored-links
9068 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9069 (princ (mapconcat
9070 (lambda (x)
9071 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
9072 (reverse org-stored-links) "\n"))))
9073 (let ((cw (selected-window)))
9074 (select-window (get-buffer-window "*Org Links*" 'visible))
9075 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9076 (unless (pos-visible-in-window-p (point-max))
9077 (org-fit-window-to-buffer))
9078 (and (window-live-p cw) (select-window cw)))
9079 ;; Fake a link history, containing the stored links.
9080 (setq tmphist (append (mapcar 'car org-stored-links)
9081 org-insert-link-history))
9082 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
9083 (mapcar 'car org-link-abbrev-alist)
9084 org-link-types))
9085 (unwind-protect
9086 (progn
9087 (setq link
9088 (let ((org-completion-use-ido nil)
9089 (org-completion-use-iswitchb nil))
9090 (org-completing-read
9091 "Link: "
9092 (append
9093 (mapcar (lambda (x) (list (concat x ":")))
9094 all-prefixes)
9095 (mapcar 'car org-stored-links))
9096 nil nil nil
9097 'tmphist
9098 (car (car org-stored-links)))))
9099 (if (not (string-match "\\S-" link))
9100 (error "No link selected"))
9101 (if (or (member link all-prefixes)
9102 (and (equal ":" (substring link -1))
9103 (member (substring link 0 -1) all-prefixes)
9104 (setq link (substring link 0 -1))))
9105 (setq link (org-link-try-special-completion link))))
9106 (set-window-configuration wcf)
9107 (kill-buffer "*Org Links*"))
9108 (setq entry (assoc link org-stored-links))
9109 (or entry (push link org-insert-link-history))
9110 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9111 (not org-keep-stored-link-after-insertion))
9112 (setq org-stored-links (delq (assoc link org-stored-links)
9113 org-stored-links)))
9114 (setq desc (or desc (nth 1 entry)))))
9116 (if (string-match org-plain-link-re link)
9117 ;; URL-like link, normalize the use of angular brackets.
9118 (setq link (org-make-link (org-remove-angle-brackets link))))
9120 ;; Check if we are linking to the current file with a search option
9121 ;; If yes, simplify the link by using only the search option.
9122 (when (and buffer-file-name
9123 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9124 (let* ((path (match-string 1 link))
9125 (case-fold-search nil)
9126 (search (match-string 2 link)))
9127 (save-match-data
9128 (if (equal (file-truename buffer-file-name) (file-truename path))
9129 ;; We are linking to this same file, with a search option
9130 (setq link search)))))
9132 ;; Check if we can/should use a relative path. If yes, simplify the link
9133 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9134 (let* ((type (match-string 1 link))
9135 (path (match-string 2 link))
9136 (origpath path)
9137 (case-fold-search nil))
9138 (cond
9139 ((or (eq org-link-file-path-type 'absolute)
9140 (equal complete-file '(16)))
9141 (setq path (abbreviate-file-name (expand-file-name path))))
9142 ((eq org-link-file-path-type 'noabbrev)
9143 (setq path (expand-file-name path)))
9144 ((eq org-link-file-path-type 'relative)
9145 (setq path (file-relative-name path)))
9147 (save-match-data
9148 (if (string-match (concat "^" (regexp-quote
9149 (expand-file-name
9150 (file-name-as-directory
9151 default-directory))))
9152 (expand-file-name path))
9153 ;; We are linking a file with relative path name.
9154 (setq path (substring (expand-file-name path)
9155 (match-end 0)))
9156 (setq path (abbreviate-file-name (expand-file-name path)))))))
9157 (setq link (concat type path))
9158 (if (equal desc origpath)
9159 (setq desc path))))
9161 (if org-make-link-description-function
9162 (setq desc (funcall org-make-link-description-function link desc)))
9164 (setq desc (read-string "Description: " desc))
9165 (unless (string-match "\\S-" desc) (setq desc nil))
9166 (if remove (apply 'delete-region remove))
9167 (insert (org-make-link-string link desc))))
9169 (defun org-link-try-special-completion (type)
9170 "If there is completion support for link type TYPE, offer it."
9171 (let ((fun (intern (concat "org-" type "-complete-link"))))
9172 (if (functionp fun)
9173 (funcall fun)
9174 (read-string "Link (no completion support): " (concat type ":")))))
9176 (defun org-file-complete-link (&optional arg)
9177 "Create a file link using completion."
9178 (let (file link)
9179 (setq file (read-file-name "File: "))
9180 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9181 (pwd1 (file-name-as-directory (abbreviate-file-name
9182 (expand-file-name ".")))))
9183 (cond
9184 ((equal arg '(16))
9185 (setq link (org-make-link
9186 "file:"
9187 (abbreviate-file-name (expand-file-name file)))))
9188 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9189 (setq link (org-make-link "file:" (match-string 1 file))))
9190 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9191 (expand-file-name file))
9192 (setq link (org-make-link
9193 "file:" (match-string 1 (expand-file-name file)))))
9194 (t (setq link (org-make-link "file:" file)))))
9195 link))
9197 (defun org-completing-read (&rest args)
9198 "Completing-read with SPACE being a normal character."
9199 (let ((enable-recursive-minibuffers t)
9200 (minibuffer-local-completion-map
9201 (copy-keymap minibuffer-local-completion-map)))
9202 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9203 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9204 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9205 (apply 'org-icompleting-read args)))
9207 (defun org-completing-read-no-i (&rest args)
9208 (let (org-completion-use-ido org-completion-use-iswitchb)
9209 (apply 'org-completing-read args)))
9211 (defun org-iswitchb-completing-read (prompt choices &rest args)
9212 "Use iswitch as a completing-read replacement to choose from choices.
9213 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9214 from."
9215 (let* ((iswitchb-use-virtual-buffers nil)
9216 (iswitchb-make-buflist-hook
9217 (lambda ()
9218 (setq iswitchb-temp-buflist choices))))
9219 (iswitchb-read-buffer prompt)))
9221 (defun org-icompleting-read (&rest args)
9222 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9223 (org-without-partial-completion
9224 (if (and org-completion-use-ido
9225 (fboundp 'ido-completing-read)
9226 (boundp 'ido-mode) ido-mode
9227 (listp (second args)))
9228 (let ((ido-enter-matching-directory nil))
9229 (apply 'ido-completing-read (concat (car args))
9230 (if (consp (car (nth 1 args)))
9231 (mapcar 'car (nth 1 args))
9232 (nth 1 args))
9233 (cddr args)))
9234 (if (and org-completion-use-iswitchb
9235 (boundp 'iswitchb-mode) iswitchb-mode
9236 (listp (second args)))
9237 (apply 'org-iswitchb-completing-read (concat (car args))
9238 (if (consp (car (nth 1 args)))
9239 (mapcar 'car (nth 1 args))
9240 (nth 1 args))
9241 (cddr args))
9242 (apply 'completing-read args)))))
9244 (defun org-extract-attributes (s)
9245 "Extract the attributes cookie from a string and set as text property."
9246 (let (a attr (start 0) key value)
9247 (save-match-data
9248 (when (string-match "{{\\([^}]+\\)}}$" s)
9249 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9250 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9251 (setq key (match-string 1 a) value (match-string 2 a)
9252 start (match-end 0)
9253 attr (plist-put attr (intern key) value))))
9254 (org-add-props s nil 'org-attr attr))
9257 (defun org-extract-attributes-from-string (tag)
9258 (let (key value attr)
9259 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9260 (setq key (match-string 1 tag) value (match-string 2 tag)
9261 tag (replace-match "" t t tag)
9262 attr (plist-put attr (intern key) value)))
9263 (cons tag attr)))
9265 (defun org-attributes-to-string (plist)
9266 "Format a property list into an HTML attribute list."
9267 (let ((s "") key value)
9268 (while plist
9269 (setq key (pop plist) value (pop plist))
9270 (and value
9271 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9274 ;;; Opening/following a link
9276 (defvar org-link-search-failed nil)
9278 (defvar org-open-link-functions nil
9279 "Hook for functions finding a plain text link.
9280 These functions must take a single argument, the link content.
9281 They will be called for links that look like [[link text][description]]
9282 when LINK TEXT does not have a protocol like \"http:\" and does not look
9283 like a filename (e.g. \"./blue.png\").
9285 These functions will be called *before* Org attempts to resolve the
9286 link by doing text searches in the current buffer - so if you want a
9287 link \"[[target]]\" to still find \"<<target>>\", your function should
9288 handle this as a special case.
9290 When the function does handle the link, it must return a non-nil value.
9291 If it decides that it is not responsible for this link, it must return
9292 nil to indicate that that Org-mode can continue with other options
9293 like exact and fuzzy text search.")
9295 (defun org-next-link ()
9296 "Move forward to the next link.
9297 If the link is in hidden text, expose it."
9298 (interactive)
9299 (when (and org-link-search-failed (eq this-command last-command))
9300 (goto-char (point-min))
9301 (message "Link search wrapped back to beginning of buffer"))
9302 (setq org-link-search-failed nil)
9303 (let* ((pos (point))
9304 (ct (org-context))
9305 (a (assoc :link ct)))
9306 (if a (goto-char (nth 2 a)))
9307 (if (re-search-forward org-any-link-re nil t)
9308 (progn
9309 (goto-char (match-beginning 0))
9310 (if (outline-invisible-p) (org-show-context)))
9311 (goto-char pos)
9312 (setq org-link-search-failed t)
9313 (error "No further link found"))))
9315 (defun org-previous-link ()
9316 "Move backward to the previous link.
9317 If the link is in hidden text, expose it."
9318 (interactive)
9319 (when (and org-link-search-failed (eq this-command last-command))
9320 (goto-char (point-max))
9321 (message "Link search wrapped back to end of buffer"))
9322 (setq org-link-search-failed nil)
9323 (let* ((pos (point))
9324 (ct (org-context))
9325 (a (assoc :link ct)))
9326 (if a (goto-char (nth 1 a)))
9327 (if (re-search-backward org-any-link-re nil t)
9328 (progn
9329 (goto-char (match-beginning 0))
9330 (if (outline-invisible-p) (org-show-context)))
9331 (goto-char pos)
9332 (setq org-link-search-failed t)
9333 (error "No further link found"))))
9335 (defun org-translate-link (s)
9336 "Translate a link string if a translation function has been defined."
9337 (if (and org-link-translation-function
9338 (fboundp org-link-translation-function)
9339 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9340 (progn
9341 (setq s (funcall org-link-translation-function
9342 (match-string 1) (match-string 2)))
9343 (concat (car s) ":" (cdr s)))
9346 (defun org-translate-link-from-planner (type path)
9347 "Translate a link from Emacs Planner syntax so that Org can follow it.
9348 This is still an experimental function, your mileage may vary."
9349 (cond
9350 ((member type '("http" "https" "news" "ftp"))
9351 ;; standard Internet links are the same.
9352 nil)
9353 ((and (equal type "irc") (string-match "^//" path))
9354 ;; Planner has two / at the beginning of an irc link, we have 1.
9355 ;; We should have zero, actually....
9356 (setq path (substring path 1)))
9357 ((and (equal type "lisp") (string-match "^/" path))
9358 ;; Planner has a slash, we do not.
9359 (setq type "elisp" path (substring path 1)))
9360 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9361 ;; A typical message link. Planner has the id after the final slash,
9362 ;; we separate it with a hash mark
9363 (setq path (concat (match-string 1 path) "#"
9364 (org-remove-angle-brackets (match-string 2 path)))))
9366 (cons type path))
9368 (defun org-find-file-at-mouse (ev)
9369 "Open file link or URL at mouse."
9370 (interactive "e")
9371 (mouse-set-point ev)
9372 (org-open-at-point 'in-emacs))
9374 (defun org-open-at-mouse (ev)
9375 "Open file link or URL at mouse.
9376 See the docstring of `org-open-file' for details."
9377 (interactive "e")
9378 (mouse-set-point ev)
9379 (if (eq major-mode 'org-agenda-mode)
9380 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9381 (org-open-at-point))
9383 (defvar org-window-config-before-follow-link nil
9384 "The window configuration before following a link.
9385 This is saved in case the need arises to restore it.")
9387 (defvar org-open-link-marker (make-marker)
9388 "Marker pointing to the location where `org-open-at-point; was called.")
9390 ;;;###autoload
9391 (defun org-open-at-point-global ()
9392 "Follow a link like Org-mode does.
9393 This command can be called in any mode to follow a link that has
9394 Org-mode syntax."
9395 (interactive)
9396 (org-run-like-in-org-mode 'org-open-at-point))
9398 ;;;###autoload
9399 (defun org-open-link-from-string (s &optional arg reference-buffer)
9400 "Open a link in the string S, as if it was in Org-mode."
9401 (interactive "sLink: \nP")
9402 (let ((reference-buffer (or reference-buffer (current-buffer))))
9403 (with-temp-buffer
9404 (let ((org-inhibit-startup t))
9405 (org-mode)
9406 (insert s)
9407 (goto-char (point-min))
9408 (when reference-buffer
9409 (setq org-link-abbrev-alist-local
9410 (with-current-buffer reference-buffer
9411 org-link-abbrev-alist-local)))
9412 (org-open-at-point arg reference-buffer)))))
9414 (defvar org-open-at-point-functions nil
9415 "Hook that is run when following a link at point.
9417 Functions in this hook must return t if they identify and follow
9418 a link at point. If they don't find anything interesting at point,
9419 they must return nil.")
9421 (defun org-open-at-point (&optional arg reference-buffer)
9422 "Open link at or after point.
9423 If there is no link at point, this function will search forward up to
9424 the end of the current line.
9425 Normally, files will be opened by an appropriate application. If the
9426 optional prefix argument ARG is non-nil, Emacs will visit the file.
9427 With a double prefix argument, try to open outside of Emacs, in the
9428 application the system uses for this file type."
9429 (interactive "P")
9430 ;; if in a code block, then open the block's results
9431 (unless (call-interactively #'org-babel-open-src-block-result)
9432 (org-load-modules-maybe)
9433 (move-marker org-open-link-marker (point))
9434 (setq org-window-config-before-follow-link (current-window-configuration))
9435 (org-remove-occur-highlights nil nil t)
9436 (cond
9437 ((and (org-on-heading-p)
9438 (not (org-in-regexp
9439 (concat org-plain-link-re "\\|"
9440 org-bracket-link-regexp "\\|"
9441 org-angle-link-re "\\|"
9442 "[ \t]:[^ \t\n]+:[ \t]*$")))
9443 (not (get-text-property (point) 'org-linked-text)))
9444 (or (org-offer-links-in-entry arg)
9445 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9446 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9447 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9448 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9449 (not (org-in-regexp org-bracket-link-regexp)))
9450 (org-footnote-action))
9452 (let (type path link line search (pos (point)))
9453 (catch 'match
9454 (save-excursion
9455 (skip-chars-forward "^]\n\r")
9456 (when (org-in-regexp org-bracket-link-regexp 1)
9457 (setq link (org-extract-attributes
9458 (org-link-unescape (org-match-string-no-properties 1))))
9459 (while (string-match " *\n *" link)
9460 (setq link (replace-match " " t t link)))
9461 (setq link (org-link-expand-abbrev link))
9462 (cond
9463 ((or (file-name-absolute-p link)
9464 (string-match "^\\.\\.?/" link))
9465 (setq type "file" path link))
9466 ((string-match org-link-re-with-space3 link)
9467 (setq type (match-string 1 link) path (match-string 2 link)))
9468 (t (setq type "thisfile" path link)))
9469 (throw 'match t)))
9471 (when (get-text-property (point) 'org-linked-text)
9472 (setq type "thisfile"
9473 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9474 (1+ (point)) (point))
9475 path (buffer-substring
9476 (or (previous-single-property-change pos 'org-linked-text)
9477 (point-min))
9478 (or (next-single-property-change pos 'org-linked-text)
9479 (point-max))))
9480 (throw 'match t))
9482 (save-excursion
9483 (when (or (org-in-regexp org-angle-link-re)
9484 (org-in-regexp org-plain-link-re))
9485 (setq type (match-string 1)
9486 path (org-link-unescape (match-string 2)))
9487 (throw 'match t)))
9488 (save-excursion
9489 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9490 (setq type "tags"
9491 path (match-string 1))
9492 (while (string-match ":" path)
9493 (setq path (replace-match "+" t t path)))
9494 (throw 'match t)))
9495 (when (org-in-regexp "<\\([^><\n]+\\)>")
9496 (setq type "tree-match"
9497 path (match-string 1))
9498 (throw 'match t)))
9499 (unless path
9500 (error "No link found"))
9502 ;; switch back to reference buffer
9503 ;; needed when if called in a temporary buffer through
9504 ;; org-open-link-from-string
9505 (with-current-buffer (or reference-buffer (current-buffer))
9507 ;; Remove any trailing spaces in path
9508 (if (string-match " +\\'" path)
9509 (setq path (replace-match "" t t path)))
9510 (if (and org-link-translation-function
9511 (fboundp org-link-translation-function))
9512 ;; Check if we need to translate the link
9513 (let ((tmp (funcall org-link-translation-function type path)))
9514 (setq type (car tmp) path (cdr tmp))))
9516 (cond
9518 ((assoc type org-link-protocols)
9519 (funcall (nth 1 (assoc type org-link-protocols)) path))
9521 ((equal type "mailto")
9522 (let ((cmd (car org-link-mailto-program))
9523 (args (cdr org-link-mailto-program)) args1
9524 (address path) (subject "") a)
9525 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9526 (setq address (match-string 1 path)
9527 subject (org-link-escape (match-string 2 path))))
9528 (while args
9529 (cond
9530 ((not (stringp (car args))) (push (pop args) args1))
9531 (t (setq a (pop args))
9532 (if (string-match "%a" a)
9533 (setq a (replace-match address t t a)))
9534 (if (string-match "%s" a)
9535 (setq a (replace-match subject t t a)))
9536 (push a args1))))
9537 (apply cmd (nreverse args1))))
9539 ((member type '("http" "https" "ftp" "news"))
9540 (browse-url (concat type ":" (org-link-escape
9541 path org-link-escape-chars-browser))))
9543 ((string= type "doi")
9544 (browse-url (concat "http://dx.doi.org/"
9545 (org-link-escape
9546 path org-link-escape-chars-browser))))
9548 ((member type '("message"))
9549 (browse-url (concat type ":" path)))
9551 ((string= type "tags")
9552 (org-tags-view arg path))
9554 ((string= type "tree-match")
9555 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9557 ((string= type "file")
9558 (if (string-match "::\\([0-9]+\\)\\'" path)
9559 (setq line (string-to-number (match-string 1 path))
9560 path (substring path 0 (match-beginning 0)))
9561 (if (string-match "::\\(.+\\)\\'" path)
9562 (setq search (match-string 1 path)
9563 path (substring path 0 (match-beginning 0)))))
9564 (if (string-match "[*?{]" (file-name-nondirectory path))
9565 (dired path)
9566 (org-open-file path arg line search)))
9568 ((string= type "shell")
9569 (let ((cmd path))
9570 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9571 (string-match org-confirm-shell-link-not-regexp cmd))
9572 (not org-confirm-shell-link-function)
9573 (funcall org-confirm-shell-link-function
9574 (format "Execute \"%s\" in shell? "
9575 (org-add-props cmd nil
9576 'face 'org-warning))))
9577 (progn
9578 (message "Executing %s" cmd)
9579 (shell-command cmd))
9580 (error "Abort"))))
9582 ((string= type "elisp")
9583 (let ((cmd path))
9584 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9585 (string-match org-confirm-elisp-link-not-regexp cmd))
9586 (not org-confirm-elisp-link-function)
9587 (funcall org-confirm-elisp-link-function
9588 (format "Execute \"%s\" as elisp? "
9589 (org-add-props cmd nil
9590 'face 'org-warning))))
9591 (message "%s => %s" cmd
9592 (if (equal (string-to-char cmd) ?\()
9593 (eval (read cmd))
9594 (call-interactively (read cmd))))
9595 (error "Abort"))))
9597 ((and (string= type "thisfile")
9598 (run-hook-with-args-until-success
9599 'org-open-link-functions path)))
9601 ((string= type "thisfile")
9602 (if arg
9603 (switch-to-buffer-other-window
9604 (org-get-buffer-for-internal-link (current-buffer)))
9605 (org-mark-ring-push))
9606 (let ((cmd `(org-link-search
9607 ,path
9608 ,(cond ((equal arg '(4)) ''occur)
9609 ((equal arg '(16)) ''org-occur)
9610 (t nil))
9611 ,pos)))
9612 (condition-case nil (let ((org-link-search-inhibit-query t))
9613 (eval cmd))
9614 (error (progn (widen) (eval cmd))))))
9617 (browse-url-at-point)))))))
9618 (move-marker org-open-link-marker nil)
9619 (run-hook-with-args 'org-follow-link-hook)))
9621 (defun org-offer-links-in-entry (&optional nth zero)
9622 "Offer links in the current entry and follow the selected link.
9623 If there is only one link, follow it immediately as well.
9624 If NTH is an integer, immediately pick the NTH link found.
9625 If ZERO is a string, check also this string for a link, and if
9626 there is one, offer it as link number zero."
9627 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9628 "\\(" org-angle-link-re "\\)\\|"
9629 "\\(" org-plain-link-re "\\)"))
9630 (cnt ?0)
9631 (in-emacs (if (integerp nth) nil nth))
9632 have-zero end links link c)
9633 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9634 (push (match-string 0 zero) links)
9635 (setq cnt (1- cnt) have-zero t))
9636 (save-excursion
9637 (org-back-to-heading t)
9638 (setq end (save-excursion (outline-next-heading) (point)))
9639 (while (re-search-forward re end t)
9640 (push (match-string 0) links))
9641 (setq links (org-uniquify (reverse links))))
9643 (cond
9644 ((null links)
9645 (message "No links"))
9646 ((equal (length links) 1)
9647 (setq link (list (car links))))
9648 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9649 (setq link (nth (if have-zero nth (1- nth)) links)))
9650 (t ; we have to select a link
9651 (save-excursion
9652 (save-window-excursion
9653 (delete-other-windows)
9654 (with-output-to-temp-buffer "*Select Link*"
9655 (mapc (lambda (l)
9656 (if (not (string-match org-bracket-link-regexp l))
9657 (princ (format "[%c] %s\n" (incf cnt)
9658 (org-remove-angle-brackets l)))
9659 (if (match-end 3)
9660 (princ (format "[%c] %s (%s)\n" (incf cnt)
9661 (match-string 3 l) (match-string 1 l)))
9662 (princ (format "[%c] %s\n" (incf cnt)
9663 (match-string 1 l))))))
9664 links))
9665 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9666 (message "Select link to open, RET to open all:")
9667 (setq c (read-char-exclusive))
9668 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9669 (when (equal c ?q) (error "Abort"))
9670 (if (equal c ?\C-m)
9671 (setq link links)
9672 (setq nth (- c ?0))
9673 (if have-zero (setq nth (1+ nth)))
9674 (unless (and (integerp nth) (>= (length links) nth))
9675 (error "Invalid link selection"))
9676 (setq link (list (nth (1- nth) links))))))
9677 (if link
9678 (let ((buf (current-buffer)))
9679 (dolist (l link)
9680 (org-open-link-from-string l in-emacs buf))
9682 nil)))
9684 ;; Add special file links that specify the way of opening
9686 (org-add-link-type "file+sys" 'org-open-file-with-system)
9687 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9688 (defun org-open-file-with-system (path)
9689 "Open file at PATH using the system way of opening it."
9690 (org-open-file path 'system))
9691 (defun org-open-file-with-emacs (path)
9692 "Open file at PATH in Emacs."
9693 (org-open-file path 'emacs))
9694 (defun org-remove-file-link-modifiers ()
9695 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9696 (goto-char (point-min))
9697 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9698 (org-if-unprotected
9699 (replace-match "file:" t t))))
9700 (eval-after-load "org-exp"
9701 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9702 'org-remove-file-link-modifiers))
9704 ;;;; Time estimates
9706 (defun org-get-effort (&optional pom)
9707 "Get the effort estimate for the current entry."
9708 (org-entry-get pom org-effort-property))
9710 ;;; File search
9712 (defvar org-create-file-search-functions nil
9713 "List of functions to construct the right search string for a file link.
9714 These functions are called in turn with point at the location to
9715 which the link should point.
9717 A function in the hook should first test if it would like to
9718 handle this file type, for example by checking the `major-mode'
9719 or the file extension. If it decides not to handle this file, it
9720 should just return nil to give other functions a chance. If it
9721 does handle the file, it must return the search string to be used
9722 when following the link. The search string will be part of the
9723 file link, given after a double colon, and `org-open-at-point'
9724 will automatically search for it. If special measures must be
9725 taken to make the search successful, another function should be
9726 added to the companion hook `org-execute-file-search-functions',
9727 which see.
9729 A function in this hook may also use `setq' to set the variable
9730 `description' to provide a suggestion for the descriptive text to
9731 be used for this link when it gets inserted into an Org-mode
9732 buffer with \\[org-insert-link].")
9734 (defvar org-execute-file-search-functions nil
9735 "List of functions to execute a file search triggered by a link.
9737 Functions added to this hook must accept a single argument, the
9738 search string that was part of the file link, the part after the
9739 double colon. The function must first check if it would like to
9740 handle this search, for example by checking the `major-mode' or
9741 the file extension. If it decides not to handle this search, it
9742 should just return nil to give other functions a chance. If it
9743 does handle the search, it must return a non-nil value to keep
9744 other functions from trying.
9746 Each function can access the current prefix argument through the
9747 variable `current-prefix-argument'. Note that a single prefix is
9748 used to force opening a link in Emacs, so it may be good to only
9749 use a numeric or double prefix to guide the search function.
9751 In case this is needed, a function in this hook can also restore
9752 the window configuration before `org-open-at-point' was called using:
9754 (set-window-configuration org-window-config-before-follow-link)")
9756 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9757 (defun org-link-search (s &optional type avoid-pos)
9758 "Search for a link search option.
9759 If S is surrounded by forward slashes, it is interpreted as a
9760 regular expression. In org-mode files, this will create an `org-occur'
9761 sparse tree. In ordinary files, `occur' will be used to list matches.
9762 If the current buffer is in `dired-mode', grep will be used to search
9763 in all files. If AVOID-POS is given, ignore matches near that position."
9764 (let ((case-fold-search t)
9765 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9766 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9767 (append '(("") (" ") ("\t") ("\n"))
9768 org-emphasis-alist)
9769 "\\|") "\\)"))
9770 (pos (point))
9771 (pre nil) (post nil)
9772 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9773 (cond
9774 ;; First check if there are any special search functions
9775 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9776 ;; Now try the builtin stuff
9777 ((and (equal (string-to-char s0) ?#)
9778 (> (length s0) 1)
9779 (save-excursion
9780 (goto-char (point-min))
9781 (and
9782 (re-search-forward
9783 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9784 (setq type 'dedicated
9785 pos (match-beginning 0))))
9786 ;; There is an exact target for this
9787 (goto-char pos)
9788 (org-back-to-heading t)))
9789 ((save-excursion
9790 (goto-char (point-min))
9791 (and
9792 (re-search-forward
9793 (concat "<<" (regexp-quote s0) ">>") nil t)
9794 (setq type 'dedicated
9795 pos (match-beginning 0))))
9796 ;; There is an exact target for this
9797 (goto-char pos))
9798 ((and (string-match "^(\\(.*\\))$" s0)
9799 (save-excursion
9800 (goto-char (point-min))
9801 (and
9802 (re-search-forward
9803 (concat "[^[]" (regexp-quote
9804 (format org-coderef-label-format
9805 (match-string 1 s0))))
9806 nil t)
9807 (setq type 'dedicated
9808 pos (1+ (match-beginning 0))))))
9809 ;; There is a coderef target for this
9810 (goto-char pos))
9811 ((string-match "^/\\(.*\\)/$" s)
9812 ;; A regular expression
9813 (cond
9814 ((eq major-mode 'org-mode)
9815 (org-occur (match-string 1 s)))
9816 ;;((eq major-mode 'dired-mode)
9817 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9818 (t (org-do-occur (match-string 1 s)))))
9819 ((and (eq major-mode 'org-mode) org-link-search-must-match-exact-headline)
9820 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
9821 (goto-char (point-min))
9822 (cond
9823 ((let (case-fold-search)
9824 (re-search-forward (format org-complex-heading-regexp-format
9825 (regexp-quote s))
9826 nil t))
9827 ;; OK, found a match
9828 (setq type 'dedicated)
9829 (goto-char (match-beginning 0)))
9830 ((and (not org-link-search-inhibit-query)
9831 (eq org-link-search-must-match-exact-headline 'query-to-create)
9832 (y-or-n-p "No match - create this as a new heading? "))
9833 (goto-char (point-max))
9834 (or (bolp) (newline))
9835 (insert "* " s "\n")
9836 (beginning-of-line 0))
9838 (goto-char pos)
9839 (error "No match"))))
9841 ;; A normal search string
9842 (when (equal (string-to-char s) ?*)
9843 ;; Anchor on headlines, post may include tags.
9844 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
9845 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
9846 s (substring s 1)))
9847 (remove-text-properties
9848 0 (length s)
9849 '(face nil mouse-face nil keymap nil fontified nil) s)
9850 ;; Make a series of regular expressions to find a match
9851 (setq words (org-split-string s "[ \n\r\t]+")
9853 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9854 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
9855 "\\)" markers)
9856 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9857 re2a (concat "[ \t\r\n]" re2a_)
9858 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9859 re4 (concat "[^a-zA-Z_]" re4_)
9861 re1 (concat pre re2 post)
9862 re3 (concat pre (if pre re4_ re4) post)
9863 re5 (concat pre ".*" re4)
9864 re2 (concat pre re2)
9865 re2a (concat pre (if pre re2a_ re2a))
9866 re4 (concat pre (if pre re4_ re4))
9867 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9868 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9869 re5 "\\)"
9871 (cond
9872 ((eq type 'org-occur) (org-occur reall))
9873 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9874 (t (goto-char (point-min))
9875 (setq type 'fuzzy)
9876 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
9877 (org-search-not-self 1 re1 nil t)
9878 (org-search-not-self 1 re2 nil t)
9879 (org-search-not-self 1 re2a nil t)
9880 (org-search-not-self 1 re3 nil t)
9881 (org-search-not-self 1 re4 nil t)
9882 (org-search-not-self 1 re5 nil t)
9884 (goto-char (match-beginning 1))
9885 (goto-char pos)
9886 (error "No match"))))))
9887 (and (eq major-mode 'org-mode) (org-show-context 'link-search))
9888 type))
9890 (defun org-search-not-self (group &rest args)
9891 "Execute `re-search-forward', but only accept matches that do not
9892 enclose the position of `org-open-link-marker'."
9893 (let ((m org-open-link-marker))
9894 (catch 'exit
9895 (while (apply 're-search-forward args)
9896 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
9897 (goto-char (match-end group))
9898 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
9899 (> (match-beginning 0) (marker-position m))
9900 (< (match-end 0) (marker-position m)))
9901 (save-match-data
9902 (or (not (org-in-regexp
9903 org-bracket-link-analytic-regexp 1))
9904 (not (match-end 4)) ; no description
9905 (and (<= (match-beginning 4) (point))
9906 (>= (match-end 4) (point))))))
9907 (throw 'exit (point))))))))
9909 (defun org-get-buffer-for-internal-link (buffer)
9910 "Return a buffer to be used for displaying the link target of internal links."
9911 (cond
9912 ((not org-display-internal-link-with-indirect-buffer)
9913 buffer)
9914 ((string-match "(Clone)$" (buffer-name buffer))
9915 (message "Buffer is already a clone, not making another one")
9916 ;; we also do not modify visibility in this case
9917 buffer)
9918 (t ; make a new indirect buffer for displaying the link
9919 (let* ((bn (buffer-name buffer))
9920 (ibn (concat bn "(Clone)"))
9921 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
9922 (with-current-buffer ib (org-overview))
9923 ib))))
9925 (defun org-do-occur (regexp &optional cleanup)
9926 "Call the Emacs command `occur'.
9927 If CLEANUP is non-nil, remove the printout of the regular expression
9928 in the *Occur* buffer. This is useful if the regex is long and not useful
9929 to read."
9930 (occur regexp)
9931 (when cleanup
9932 (let ((cwin (selected-window)) win beg end)
9933 (when (setq win (get-buffer-window "*Occur*"))
9934 (select-window win))
9935 (goto-char (point-min))
9936 (when (re-search-forward "match[a-z]+" nil t)
9937 (setq beg (match-end 0))
9938 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9939 (setq end (1- (match-beginning 0)))))
9940 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
9941 (goto-char (point-min))
9942 (select-window cwin))))
9944 ;;; The mark ring for links jumps
9946 (defvar org-mark-ring nil
9947 "Mark ring for positions before jumps in Org-mode.")
9948 (defvar org-mark-ring-last-goto nil
9949 "Last position in the mark ring used to go back.")
9950 ;; Fill and close the ring
9951 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9952 (loop for i from 1 to org-mark-ring-length do
9953 (push (make-marker) org-mark-ring))
9954 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
9955 org-mark-ring)
9957 (defun org-mark-ring-push (&optional pos buffer)
9958 "Put the current position or POS into the mark ring and rotate it."
9959 (interactive)
9960 (setq pos (or pos (point)))
9961 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
9962 (move-marker (car org-mark-ring)
9963 (or pos (point))
9964 (or buffer (current-buffer)))
9965 (message "%s"
9966 (substitute-command-keys
9967 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
9969 (defun org-mark-ring-goto (&optional n)
9970 "Jump to the previous position in the mark ring.
9971 With prefix arg N, jump back that many stored positions. When
9972 called several times in succession, walk through the entire ring.
9973 Org-mode commands jumping to a different position in the current file,
9974 or to another Org-mode file, automatically push the old position
9975 onto the ring."
9976 (interactive "p")
9977 (let (p m)
9978 (if (eq last-command this-command)
9979 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
9980 (setq p org-mark-ring))
9981 (setq org-mark-ring-last-goto p)
9982 (setq m (car p))
9983 (org-pop-to-buffer-same-window (marker-buffer m))
9984 (goto-char m)
9985 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
9987 (defun org-remove-angle-brackets (s)
9988 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
9989 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
9991 (defun org-add-angle-brackets (s)
9992 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
9993 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
9995 (defun org-remove-double-quotes (s)
9996 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
9997 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10000 ;;; Following specific links
10002 (defun org-follow-timestamp-link ()
10003 (cond
10004 ((org-at-date-range-p t)
10005 (let ((org-agenda-start-on-weekday)
10006 (t1 (match-string 1))
10007 (t2 (match-string 2)))
10008 (setq t1 (time-to-days (org-time-string-to-time t1))
10009 t2 (time-to-days (org-time-string-to-time t2)))
10010 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10011 ((org-at-timestamp-p t)
10012 (org-agenda-list nil (time-to-days (org-time-string-to-time
10013 (substring (match-string 1) 0 10)))
10015 (t (error "This should not happen"))))
10018 ;;; Following file links
10019 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10020 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10021 (declare-function mailcap-mime-info
10022 "mailcap" (string &optional request no-decode))
10023 (defvar org-wait nil)
10024 (defun org-open-file (path &optional in-emacs line search)
10025 "Open the file at PATH.
10026 First, this expands any special file name abbreviations. Then the
10027 configuration variable `org-file-apps' is checked if it contains an
10028 entry for this file type, and if yes, the corresponding command is launched.
10030 If no application is found, Emacs simply visits the file.
10032 With optional prefix argument IN-EMACS, Emacs will visit the file.
10033 With a double \\[universal-argument] \\[universal-argument] \
10034 prefix arg, Org tries to avoid opening in Emacs
10035 and to use an external application to visit the file.
10037 Optional LINE specifies a line to go to, optional SEARCH a string
10038 to search for. If LINE or SEARCH is given, the file will be
10039 opened in Emacs, unless an entry from org-file-apps that makes
10040 use of groups in a regexp matches.
10042 If you want to change the way frames are used when following a
10043 link, please customize `org-link-frame-setup'.
10045 If the file does not exist, an error is thrown."
10046 (let* ((file (if (equal path "")
10047 buffer-file-name
10048 (substitute-in-file-name (expand-file-name path))))
10049 (file-apps (append org-file-apps (org-default-apps)))
10050 (apps (org-remove-if
10051 'org-file-apps-entry-match-against-dlink-p file-apps))
10052 (apps-dlink (org-remove-if-not
10053 'org-file-apps-entry-match-against-dlink-p file-apps))
10054 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10055 (dirp (if remp nil (file-directory-p file)))
10056 (file (if (and dirp org-open-directory-means-index-dot-org)
10057 (concat (file-name-as-directory file) "index.org")
10058 file))
10059 (a-m-a-p (assq 'auto-mode apps))
10060 (dfile (downcase file))
10061 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10062 (link (cond ((and (eq line nil)
10063 (eq search nil))
10064 file)
10065 (line
10066 (concat file "::" (number-to-string line)))
10067 (search
10068 (concat file "::" search))))
10069 (dlink (downcase link))
10070 (old-buffer (current-buffer))
10071 (old-pos (point))
10072 (old-mode major-mode)
10073 ext cmd link-match-data)
10074 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10075 (setq ext (match-string 1 dfile))
10076 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10077 (setq ext (match-string 1 dfile))))
10078 (cond
10079 ((member in-emacs '((16) system))
10080 (setq cmd (cdr (assoc 'system apps))))
10081 (in-emacs (setq cmd 'emacs))
10083 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10084 (and dirp (cdr (assoc 'directory apps)))
10085 ; first, try matching against apps-dlink
10086 ; if we get a match here, store the match data for later
10087 (let ((match (assoc-default dlink apps-dlink
10088 'string-match)))
10089 (if match
10090 (progn (setq link-match-data (match-data))
10091 match)
10092 (progn (setq in-emacs (or in-emacs line search))
10093 nil))) ; if we have no match in apps-dlink,
10094 ; always open the file in emacs if line or search
10095 ; is given (for backwards compatibility)
10096 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10097 'string-match)
10098 (cdr (assoc ext apps))
10099 (cdr (assoc t apps))))))
10100 (when (eq cmd 'system)
10101 (setq cmd (cdr (assoc 'system apps))))
10102 (when (eq cmd 'default)
10103 (setq cmd (cdr (assoc t apps))))
10104 (when (eq cmd 'mailcap)
10105 (require 'mailcap)
10106 (mailcap-parse-mailcaps)
10107 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10108 (command (mailcap-mime-info mime-type)))
10109 (if (stringp command)
10110 (setq cmd command)
10111 (setq cmd 'emacs))))
10112 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10113 (not (file-exists-p file))
10114 (not org-open-non-existing-files))
10115 (error "No such file: %s" file))
10116 (cond
10117 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10118 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10119 (while (string-match "['\"]%s['\"]" cmd)
10120 (setq cmd (replace-match "%s" t t cmd)))
10121 (while (string-match "%s" cmd)
10122 (setq cmd (replace-match
10123 (save-match-data
10124 (shell-quote-argument
10125 (convert-standard-filename file)))
10126 t t cmd)))
10128 ;; Replace "%1", "%2" etc. in command with group matches from regex
10129 (save-match-data
10130 (let ((match-index 1)
10131 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10132 (set-match-data link-match-data)
10133 (while (<= match-index number-of-groups)
10134 (let ((regex (concat "%" (number-to-string match-index)))
10135 (replace-with (match-string match-index dlink)))
10136 (while (string-match regex cmd)
10137 (setq cmd (replace-match replace-with t t cmd))))
10138 (setq match-index (+ match-index 1)))))
10140 (save-window-excursion
10141 (start-process-shell-command cmd nil cmd)
10142 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10144 ((or (stringp cmd)
10145 (eq cmd 'emacs))
10146 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10147 (widen)
10148 (if line (org-goto-line line)
10149 (if search (org-link-search search))))
10150 ((consp cmd)
10151 (let ((file (convert-standard-filename file)))
10152 (save-match-data
10153 (set-match-data link-match-data)
10154 (eval cmd))))
10155 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10156 (and (eq major-mode 'org-mode) (eq old-mode 'org-mode)
10157 (or (not (equal old-buffer (current-buffer)))
10158 (not (equal old-pos (point))))
10159 (org-mark-ring-push old-pos old-buffer))))
10161 (defun org-file-apps-entry-match-against-dlink-p (entry)
10162 "This function returns non-nil if `entry' uses a regular
10163 expression which should be matched against the whole link by
10164 org-open-file.
10166 It assumes that is the case when the entry uses a regular
10167 expression which has at least one grouping construct and the
10168 action is either a lisp form or a command string containing
10169 '%1', i.e. using at least one subexpression match as a
10170 parameter."
10171 (let ((selector (car entry))
10172 (action (cdr entry)))
10173 (if (stringp selector)
10174 (and (> (regexp-opt-depth selector) 0)
10175 (or (and (stringp action)
10176 (string-match "%[0-9]" action))
10177 (consp action)))
10178 nil)))
10180 (defun org-default-apps ()
10181 "Return the default applications for this operating system."
10182 (cond
10183 ((eq system-type 'darwin)
10184 org-file-apps-defaults-macosx)
10185 ((eq system-type 'windows-nt)
10186 org-file-apps-defaults-windowsnt)
10187 (t org-file-apps-defaults-gnu)))
10189 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10190 "Convert extensions to regular expressions in the cars of LIST.
10191 Also, weed out any non-string entries, because the return value is used
10192 only for regexp matching.
10193 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10194 point to the symbol `emacs', indicating that the file should
10195 be opened in Emacs."
10196 (append
10197 (delq nil
10198 (mapcar (lambda (x)
10199 (if (not (stringp (car x)))
10201 (if (string-match "\\W" (car x))
10203 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10204 list))
10205 (if add-auto-mode
10206 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10208 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10209 (defun org-file-remote-p (file)
10210 "Test whether FILE specifies a location on a remote system.
10211 Return non-nil if the location is indeed remote.
10213 For example, the filename \"/user@host:/foo\" specifies a location
10214 on the system \"/user@host:\"."
10215 (cond ((fboundp 'file-remote-p)
10216 (file-remote-p file))
10217 ((fboundp 'tramp-handle-file-remote-p)
10218 (tramp-handle-file-remote-p file))
10219 ((and (boundp 'ange-ftp-name-format)
10220 (string-match (car ange-ftp-name-format) file))
10222 (t nil)))
10225 ;;;; Refiling
10227 (defun org-get-org-file ()
10228 "Read a filename, with default directory `org-directory'."
10229 (let ((default (or org-default-notes-file remember-data-file)))
10230 (read-file-name (format "File name [%s]: " default)
10231 (file-name-as-directory org-directory)
10232 default)))
10234 (defun org-notes-order-reversed-p ()
10235 "Check if the current file should receive notes in reversed order."
10236 (cond
10237 ((not org-reverse-note-order) nil)
10238 ((eq t org-reverse-note-order) t)
10239 ((not (listp org-reverse-note-order)) nil)
10240 (t (catch 'exit
10241 (let ((all org-reverse-note-order)
10242 entry)
10243 (while (setq entry (pop all))
10244 (if (string-match (car entry) buffer-file-name)
10245 (throw 'exit (cdr entry))))
10246 nil)))))
10248 (defvar org-refile-target-table nil
10249 "The list of refile targets, created by `org-refile'.")
10251 (defvar org-agenda-new-buffers nil
10252 "Buffers created to visit agenda files.")
10254 (defvar org-refile-cache nil
10255 "Cache for refile targets.")
10257 (defvar org-refile-markers nil
10258 "All the markers used for caching refile locations.")
10260 (defun org-refile-marker (pos)
10261 "Get a new refile marker, but only if caching is in use."
10262 (if (not org-refile-use-cache)
10264 (let ((m (make-marker)))
10265 (move-marker m pos)
10266 (push m org-refile-markers)
10267 m)))
10269 (defun org-refile-cache-clear ()
10270 "Clear the refile cache and disable all the markers."
10271 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10272 (setq org-refile-markers nil)
10273 (setq org-refile-cache nil)
10274 (message "Refile cache has been cleared"))
10276 (defun org-refile-cache-check-set (set)
10277 "Check if all the markers in the cache still have live buffers."
10278 (let (marker)
10279 (catch 'exit
10280 (while (and set (setq marker (nth 3 (pop set))))
10281 ;; if org-refile-use-outline-path is 'file, marker may be nil
10282 (when (and marker (null (marker-buffer marker)))
10283 (message "not found") (sit-for 3)
10284 (throw 'exit nil)))
10285 t)))
10287 (defun org-refile-cache-put (set &rest identifiers)
10288 "Push the refile targets SET into the cache, under IDENTIFIERS."
10289 (let* ((key (sha1 (prin1-to-string identifiers)))
10290 (entry (assoc key org-refile-cache)))
10291 (if entry
10292 (setcdr entry set)
10293 (push (cons key set) org-refile-cache))))
10295 (defun org-refile-cache-get (&rest identifiers)
10296 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10297 (cond
10298 ((not org-refile-cache) nil)
10299 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10301 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10302 org-refile-cache))))
10303 (and set (org-refile-cache-check-set set) set)))))
10305 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10306 "Produce a table with refile targets."
10307 (let ((case-fold-search nil)
10308 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10309 (entries (or org-refile-targets '((nil . (:level . 1)))))
10310 targets tgs txt re files f desc descre fast-path-p level pos0)
10311 (message "Getting targets...")
10312 (with-current-buffer (or default-buffer (current-buffer))
10313 (while (setq entry (pop entries))
10314 (setq files (car entry) desc (cdr entry))
10315 (setq fast-path-p nil)
10316 (cond
10317 ((null files) (setq files (list (current-buffer))))
10318 ((eq files 'org-agenda-files)
10319 (setq files (org-agenda-files 'unrestricted)))
10320 ((and (symbolp files) (fboundp files))
10321 (setq files (funcall files)))
10322 ((and (symbolp files) (boundp files))
10323 (setq files (symbol-value files))))
10324 (if (stringp files) (setq files (list files)))
10325 (cond
10326 ((eq (car desc) :tag)
10327 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10328 ((eq (car desc) :todo)
10329 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10330 ((eq (car desc) :regexp)
10331 (setq descre (cdr desc)))
10332 ((eq (car desc) :level)
10333 (setq descre (concat "^\\*\\{" (number-to-string
10334 (if org-odd-levels-only
10335 (1- (* 2 (cdr desc)))
10336 (cdr desc)))
10337 "\\}[ \t]")))
10338 ((eq (car desc) :maxlevel)
10339 (setq fast-path-p t)
10340 (setq descre (concat "^\\*\\{1," (number-to-string
10341 (if org-odd-levels-only
10342 (1- (* 2 (cdr desc)))
10343 (cdr desc)))
10344 "\\}[ \t]")))
10345 (t (error "Bad refiling target description %s" desc)))
10346 (while (setq f (pop files))
10347 (with-current-buffer
10348 (if (bufferp f) f (org-get-agenda-file-buffer f))
10350 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10351 (progn
10352 (if (bufferp f) (setq f (buffer-file-name
10353 (buffer-base-buffer f))))
10354 (setq f (and f (expand-file-name f)))
10355 (if (eq org-refile-use-outline-path 'file)
10356 (push (list (file-name-nondirectory f) f nil nil) tgs))
10357 (save-excursion
10358 (save-restriction
10359 (widen)
10360 (goto-char (point-min))
10361 (while (re-search-forward descre nil t)
10362 (goto-char (setq pos0 (point-at-bol)))
10363 (catch 'next
10364 (when org-refile-target-verify-function
10365 (save-match-data
10366 (or (funcall org-refile-target-verify-function)
10367 (throw 'next t))))
10368 (when (and (looking-at org-complex-heading-regexp)
10369 (not (member (match-string 4) excluded-entries)))
10370 (setq level (org-reduced-level
10371 (- (match-end 1) (match-beginning 1)))
10372 txt (org-link-display-format (match-string 4))
10373 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10374 re (format org-complex-heading-regexp-format
10375 (regexp-quote (match-string 4))))
10376 (when org-refile-use-outline-path
10377 (setq txt (mapconcat
10378 'org-protect-slash
10379 (append
10380 (if (eq org-refile-use-outline-path
10381 'file)
10382 (list (file-name-nondirectory
10383 (buffer-file-name
10384 (buffer-base-buffer))))
10385 (if (eq org-refile-use-outline-path
10386 'full-file-path)
10387 (list (buffer-file-name
10388 (buffer-base-buffer)))))
10389 (org-get-outline-path fast-path-p
10390 level txt)
10391 (list txt))
10392 "/")))
10393 (push (list txt f re (org-refile-marker (point)))
10394 tgs)))
10395 (when (= (point) pos0)
10396 ;; verification function has not moved point
10397 (goto-char (point-at-eol))))))))
10398 (when org-refile-use-cache
10399 (org-refile-cache-put tgs (buffer-file-name) descre))
10400 (setq targets (append tgs targets))
10401 ))))
10402 (message "Getting targets...done")
10403 (nreverse targets)))
10405 (defun org-protect-slash (s)
10406 (while (string-match "/" s)
10407 (setq s (replace-match "\\" t t s)))
10410 (defvar org-olpa (make-vector 20 nil))
10412 (defun org-get-outline-path (&optional fastp level heading)
10413 "Return the outline path to the current entry, as a list.
10415 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10416 routine which makes outline path derivations for an entire file,
10417 avoiding backtracing. Refile target collection makes use of that."
10418 (if fastp
10419 (progn
10420 (if (> level 19)
10421 (error "Outline path failure, more than 19 levels"))
10422 (loop for i from level upto 19 do
10423 (aset org-olpa i nil))
10424 (prog1
10425 (delq nil (append org-olpa nil))
10426 (aset org-olpa level heading)))
10427 (let (rtn case-fold-search)
10428 (save-excursion
10429 (save-restriction
10430 (widen)
10431 (while (org-up-heading-safe)
10432 (when (looking-at org-complex-heading-regexp)
10433 (push (org-match-string-no-properties 4) rtn)))
10434 rtn)))))
10436 (defun org-format-outline-path (path &optional width prefix)
10437 "Format the outline path PATH for display.
10438 Width is the maximum number of characters that is available.
10439 Prefix is a prefix to be included in the returned string,
10440 such as the file name."
10441 (setq width (or width 79))
10442 (if prefix (setq width (- width (length prefix))))
10443 (if (not path)
10444 (or prefix "")
10445 (let* ((nsteps (length path))
10446 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10447 (maxwidth (if (<= total-width width)
10448 10000 ;; everything fits
10449 ;; we need to shorten the level headings
10450 (/ (- width nsteps) nsteps)))
10451 (org-odd-levels-only nil)
10452 (n 0)
10453 (total (1+ (length prefix))))
10454 (setq maxwidth (max maxwidth 10))
10455 (concat prefix
10456 (mapconcat
10457 (lambda (h)
10458 (setq n (1+ n))
10459 (if (and (= n nsteps) (< maxwidth 10000))
10460 (setq maxwidth (- total-width total)))
10461 (if (< (length h) maxwidth)
10462 (progn (setq total (+ total (length h) 1)) h)
10463 (setq h (substring h 0 (- maxwidth 2))
10464 total (+ total maxwidth 1))
10465 (if (string-match "[ \t]+\\'" h)
10466 (setq h (substring h 0 (match-beginning 0))))
10467 (setq h (concat h "..")))
10468 (org-add-props h nil 'face
10469 (nth (% (1- n) org-n-level-faces)
10470 org-level-faces))
10472 path "/")))))
10474 (defun org-display-outline-path (&optional file current)
10475 "Display the current outline path in the echo area."
10476 (interactive "P")
10477 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10478 (case-fold-search nil)
10479 (path (and (eq major-mode 'org-mode) (org-get-outline-path))))
10480 (if current (setq path (append path
10481 (save-excursion
10482 (org-back-to-heading t)
10483 (if (looking-at org-complex-heading-regexp)
10484 (list (match-string 4)))))))
10485 (message "%s"
10486 (org-format-outline-path
10487 path
10488 (1- (frame-width))
10489 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10491 (defvar org-refile-history nil
10492 "History for refiling operations.")
10494 (defvar org-after-refile-insert-hook nil
10495 "Hook run after `org-refile' has inserted its stuff at the new location.
10496 Note that this is still *before* the stuff will be removed from
10497 the *old* location.")
10499 (defvar org-capture-last-stored-marker)
10500 (defun org-refile (&optional goto default-buffer rfloc)
10501 "Move the entry or entries at point to another heading.
10502 The list of target headings is compiled using the information in
10503 `org-refile-targets', which see.
10505 At the target location, the entry is filed as a subitem of the target
10506 heading. Depending on `org-reverse-note-order', the new subitem will
10507 either be the first or the last subitem.
10509 If there is an active region, all entries in that region will be moved.
10510 However, the region must fulfill the requirement that the first heading
10511 is the first one sets the top-level of the moved text - at most siblings
10512 below it are allowed.
10514 With prefix arg GOTO, the command will only visit the target location
10515 and not actually move anything.
10517 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10518 go to the location where the last refiling operation has put the subtree.
10519 With a prefix argument of `2', refile to the running clock.
10521 RFLOC can be a refile location obtained in a different way.
10523 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10525 If you are using target caching (see `org-refile-use-cache'),
10526 You have to clear the target cache in order to find new targets.
10527 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10528 prefix argument (`C-u C-u C-u C-c C-w')."
10530 (interactive "P")
10531 (if (member goto '(0 (64)))
10532 (org-refile-cache-clear)
10533 (let* ((cbuf (current-buffer))
10534 (regionp (org-region-active-p))
10535 (region-start (and regionp (region-beginning)))
10536 (region-end (and regionp (region-end)))
10537 (region-length (and regionp (- region-end region-start)))
10538 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10539 pos it nbuf file re level reversed)
10540 (setq last-command nil)
10541 (when regionp
10542 (goto-char region-start)
10543 (or (bolp) (goto-char (point-at-bol)))
10544 (setq region-start (point))
10545 (unless (or (org-kill-is-subtree-p
10546 (buffer-substring region-start region-end))
10547 (prog1 org-refile-active-region-within-subtree
10548 (org-toggle-heading)))
10549 (error "The region is not a (sequence of) subtree(s)")))
10550 (if (equal goto '(16))
10551 (org-refile-goto-last-stored)
10552 (when (or
10553 (and (equal goto 2)
10554 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10555 (prog1
10556 (setq it (list (or org-clock-heading "running clock")
10557 (buffer-file-name
10558 (marker-buffer org-clock-hd-marker))
10560 (marker-position org-clock-hd-marker)))
10561 (setq goto nil)))
10562 (setq it (or rfloc
10563 (let (heading-text)
10564 (save-excursion
10565 (unless goto
10566 (org-back-to-heading t)
10567 (setq heading-text
10568 (nth 4 (org-heading-components))))
10569 (org-refile-get-location
10570 (cond (goto "Goto")
10571 (regionp "Refile region to")
10572 (t (concat "Refile subtree \""
10573 heading-text "\" to")))
10574 default-buffer
10575 org-refile-allow-creating-parent-nodes
10576 goto))))))
10577 (setq file (nth 1 it)
10578 re (nth 2 it)
10579 pos (nth 3 it))
10580 (if (and (not goto)
10582 (equal (buffer-file-name) file)
10583 (if regionp
10584 (and (>= pos region-start)
10585 (<= pos region-end))
10586 (and (>= pos (point))
10587 (< pos (save-excursion
10588 (org-end-of-subtree t t))))))
10589 (error "Cannot refile to position inside the tree or region"))
10591 (setq nbuf (or (find-buffer-visiting file)
10592 (find-file-noselect file)))
10593 (if goto
10594 (progn
10595 (org-pop-to-buffer-same-window nbuf)
10596 (goto-char pos)
10597 (org-show-context 'org-goto))
10598 (if regionp
10599 (progn
10600 (org-kill-new (buffer-substring region-start region-end))
10601 (org-save-markers-in-region region-start region-end))
10602 (org-copy-subtree 1 nil t))
10603 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10604 (find-file-noselect file)))
10605 (setq reversed (org-notes-order-reversed-p))
10606 (save-excursion
10607 (save-restriction
10608 (widen)
10609 (if pos
10610 (progn
10611 (goto-char pos)
10612 (looking-at org-outline-regexp)
10613 (setq level (org-get-valid-level (funcall outline-level) 1))
10614 (goto-char
10615 (if reversed
10616 (or (outline-next-heading) (point-max))
10617 (or (save-excursion (org-get-next-sibling))
10618 (org-end-of-subtree t t)
10619 (point-max)))))
10620 (setq level 1)
10621 (if (not reversed)
10622 (goto-char (point-max))
10623 (goto-char (point-min))
10624 (or (outline-next-heading) (goto-char (point-max)))))
10625 (if (not (bolp)) (newline))
10626 (org-paste-subtree level)
10627 (when org-log-refile
10628 (org-add-log-setup 'refile nil nil 'findpos
10629 org-log-refile)
10630 (unless (eq org-log-refile 'note)
10631 (save-excursion (org-add-log-note))))
10632 (and org-auto-align-tags (org-set-tags nil t))
10633 (bookmark-set "org-refile-last-stored")
10634 ;; If we are refiling for capture, make sure that the
10635 ;; last-capture pointers point here
10636 (when (org-bound-and-true-p org-refile-for-capture)
10637 (bookmark-set "org-capture-last-stored-marker")
10638 (move-marker org-capture-last-stored-marker (point)))
10639 (if (fboundp 'deactivate-mark) (deactivate-mark))
10640 (run-hooks 'org-after-refile-insert-hook))))
10641 (if regionp
10642 (delete-region (point) (+ (point) region-length))
10643 (org-cut-subtree))
10644 (when (featurep 'org-inlinetask)
10645 (org-inlinetask-remove-END-maybe))
10646 (setq org-markers-to-move nil)
10647 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10649 (defun org-refile-goto-last-stored ()
10650 "Go to the location where the last refile was stored."
10651 (interactive)
10652 (bookmark-jump "org-refile-last-stored")
10653 (message "This is the location of the last refile"))
10655 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10656 no-exclude)
10657 "Prompt the user for a refile location, using PROMPT.
10658 PROMPT should not be suffixed with a colon and a space, because
10659 this function appends the default value from
10660 `org-refile-history' automatically, if that is not empty.
10661 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10662 this is used for the GOTO interface."
10663 (let ((org-refile-targets org-refile-targets)
10664 (org-refile-use-outline-path org-refile-use-outline-path)
10665 excluded-entries)
10666 (when (and (eq major-mode 'org-mode)
10667 (not org-refile-use-cache)
10668 (not no-exclude))
10669 (org-map-tree
10670 (lambda()
10671 (setq excluded-entries
10672 (append excluded-entries (list (org-get-heading t t)))))))
10673 (setq org-refile-target-table
10674 (org-refile-get-targets default-buffer excluded-entries)))
10675 (unless org-refile-target-table
10676 (error "No refile targets"))
10677 (let* ((prompt (concat prompt
10678 (and (car org-refile-history)
10679 (concat " (default " (car org-refile-history) ")"))
10680 ": "))
10681 (cbuf (current-buffer))
10682 (partial-completion-mode nil)
10683 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10684 (cfunc (if (and org-refile-use-outline-path
10685 org-outline-path-complete-in-steps)
10686 'org-olpath-completing-read
10687 'org-icompleting-read))
10688 (extra (if org-refile-use-outline-path "/" ""))
10689 (filename (and cfn (expand-file-name cfn)))
10690 (tbl (mapcar
10691 (lambda (x)
10692 (if (and (not (member org-refile-use-outline-path
10693 '(file full-file-path)))
10694 (not (equal filename (nth 1 x))))
10695 (cons (concat (car x) extra " ("
10696 (file-name-nondirectory (nth 1 x)) ")")
10697 (cdr x))
10698 (cons (concat (car x) extra) (cdr x))))
10699 org-refile-target-table))
10700 (completion-ignore-case t)
10701 pa answ parent-target child parent old-hist)
10702 (setq old-hist org-refile-history)
10703 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10704 nil 'org-refile-history (car org-refile-history)))
10705 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10706 (org-refile-check-position pa)
10707 (if pa
10708 (progn
10709 (when (or (not org-refile-history)
10710 (not (eq old-hist org-refile-history))
10711 (not (equal (car pa) (car org-refile-history))))
10712 (setq org-refile-history
10713 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10714 org-refile-history
10715 (cdr org-refile-history))))
10716 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10717 (pop org-refile-history)))
10719 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10720 (progn
10721 (setq parent (match-string 1 answ)
10722 child (match-string 2 answ))
10723 (setq parent-target (or (assoc parent tbl)
10724 (assoc (concat parent "/") tbl)))
10725 (when (and parent-target
10726 (or (eq new-nodes t)
10727 (and (eq new-nodes 'confirm)
10728 (y-or-n-p (format "Create new node \"%s\"? "
10729 child)))))
10730 (org-refile-new-child parent-target child)))
10731 (error "Invalid target location")))))
10733 (defun org-refile-check-position (refile-pointer)
10734 "Check if the refile pointer matches the readline to which it points."
10735 (let* ((file (nth 1 refile-pointer))
10736 (re (nth 2 refile-pointer))
10737 (pos (nth 3 refile-pointer))
10738 buffer)
10739 (when (org-string-nw-p re)
10740 (setq buffer (if (markerp pos)
10741 (marker-buffer pos)
10742 (or (find-buffer-visiting file)
10743 (find-file-noselect file))))
10744 (with-current-buffer buffer
10745 (save-excursion
10746 (save-restriction
10747 (widen)
10748 (goto-char pos)
10749 (beginning-of-line 1)
10750 (unless (org-looking-at-p re)
10751 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
10753 (defun org-refile-new-child (parent-target child)
10754 "Use refile target PARENT-TARGET to add new CHILD below it."
10755 (unless parent-target
10756 (error "Cannot find parent for new node"))
10757 (let ((file (nth 1 parent-target))
10758 (pos (nth 3 parent-target))
10759 level)
10760 (with-current-buffer (or (find-buffer-visiting file)
10761 (find-file-noselect file))
10762 (save-excursion
10763 (save-restriction
10764 (widen)
10765 (if pos
10766 (goto-char pos)
10767 (goto-char (point-max))
10768 (if (not (bolp)) (newline)))
10769 (when (looking-at org-outline-regexp)
10770 (setq level (funcall outline-level))
10771 (org-end-of-subtree t t))
10772 (org-back-over-empty-lines)
10773 (insert "\n" (make-string
10774 (if pos (org-get-valid-level level 1) 1) ?*)
10775 " " child "\n")
10776 (beginning-of-line 0)
10777 (list (concat (car parent-target) "/" child) file "" (point)))))))
10779 (defun org-olpath-completing-read (prompt collection &rest args)
10780 "Read an outline path like a file name."
10781 (let ((thetable collection)
10782 (org-completion-use-ido nil) ; does not work with ido.
10783 (org-completion-use-iswitchb nil)) ; or iswitchb
10784 (apply
10785 'org-icompleting-read prompt
10786 (lambda (string predicate &optional flag)
10787 (let (rtn r f (l (length string)))
10788 (cond
10789 ((eq flag nil)
10790 ;; try completion
10791 (try-completion string thetable))
10792 ((eq flag t)
10793 ;; all-completions
10794 (setq rtn (all-completions string thetable predicate))
10795 (mapcar
10796 (lambda (x)
10797 (setq r (substring x l))
10798 (if (string-match " ([^)]*)$" x)
10799 (setq f (match-string 0 x))
10800 (setq f ""))
10801 (if (string-match "/" r)
10802 (concat string (substring r 0 (match-end 0)) f)
10804 rtn))
10805 ((eq flag 'lambda)
10806 ;; exact match?
10807 (assoc string thetable)))
10809 args)))
10811 ;;;; Dynamic blocks
10813 (defun org-find-dblock (name)
10814 "Find the first dynamic block with name NAME in the buffer.
10815 If not found, stay at current position and return nil."
10816 (let (pos)
10817 (save-excursion
10818 (goto-char (point-min))
10819 (setq pos (and (re-search-forward (concat "^[ \t]*#\\+BEGIN:[ \t]+" name "\\>")
10820 nil t)
10821 (match-beginning 0))))
10822 (if pos (goto-char pos))
10823 pos))
10825 (defconst org-dblock-start-re
10826 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10827 "Matches the start line of a dynamic block, with parameters.")
10829 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
10830 "Matches the end of a dynamic block.")
10832 (defun org-create-dblock (plist)
10833 "Create a dynamic block section, with parameters taken from PLIST.
10834 PLIST must contain a :name entry which is used as name of the block."
10835 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
10836 (end-of-line 1)
10837 (newline))
10838 (let ((col (current-column))
10839 (name (plist-get plist :name)))
10840 (insert "#+BEGIN: " name)
10841 (while plist
10842 (if (eq (car plist) :name)
10843 (setq plist (cddr plist))
10844 (insert " " (prin1-to-string (pop plist)))))
10845 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
10846 (beginning-of-line -2)))
10848 (defun org-prepare-dblock ()
10849 "Prepare dynamic block for refresh.
10850 This empties the block, puts the cursor at the insert position and returns
10851 the property list including an extra property :name with the block name."
10852 (unless (looking-at org-dblock-start-re)
10853 (error "Not at a dynamic block"))
10854 (let* ((begdel (1+ (match-end 0)))
10855 (name (org-no-properties (match-string 1)))
10856 (params (append (list :name name)
10857 (read (concat "(" (match-string 3) ")")))))
10858 (save-excursion
10859 (beginning-of-line 1)
10860 (skip-chars-forward " \t")
10861 (setq params (plist-put params :indentation-column (current-column))))
10862 (unless (re-search-forward org-dblock-end-re nil t)
10863 (error "Dynamic block not terminated"))
10864 (setq params
10865 (append params
10866 (list :content (buffer-substring
10867 begdel (match-beginning 0)))))
10868 (delete-region begdel (match-beginning 0))
10869 (goto-char begdel)
10870 (open-line 1)
10871 params))
10873 (defun org-map-dblocks (&optional command)
10874 "Apply COMMAND to all dynamic blocks in the current buffer.
10875 If COMMAND is not given, use `org-update-dblock'."
10876 (let ((cmd (or command 'org-update-dblock)))
10877 (save-excursion
10878 (goto-char (point-min))
10879 (while (re-search-forward org-dblock-start-re nil t)
10880 (goto-char (match-beginning 0))
10881 (save-excursion
10882 (condition-case nil
10883 (funcall cmd)
10884 (error (message "Error during update of dynamic block"))))
10885 (unless (re-search-forward org-dblock-end-re nil t)
10886 (error "Dynamic block not terminated"))))))
10888 (defun org-dblock-update (&optional arg)
10889 "User command for updating dynamic blocks.
10890 Update the dynamic block at point. With prefix ARG, update all dynamic
10891 blocks in the buffer."
10892 (interactive "P")
10893 (if arg
10894 (org-update-all-dblocks)
10895 (or (looking-at org-dblock-start-re)
10896 (org-beginning-of-dblock))
10897 (org-update-dblock)))
10899 (defun org-update-dblock ()
10900 "Update the dynamic block at point.
10901 This means to empty the block, parse for parameters and then call
10902 the correct writing function."
10903 (interactive)
10904 (save-window-excursion
10905 (let* ((pos (point))
10906 (line (org-current-line))
10907 (params (org-prepare-dblock))
10908 (name (plist-get params :name))
10909 (indent (plist-get params :indentation-column))
10910 (cmd (intern (concat "org-dblock-write:" name))))
10911 (message "Updating dynamic block `%s' at line %d..." name line)
10912 (funcall cmd params)
10913 (message "Updating dynamic block `%s' at line %d...done" name line)
10914 (goto-char pos)
10915 (when (and indent (> indent 0))
10916 (setq indent (make-string indent ?\ ))
10917 (save-excursion
10918 (org-beginning-of-dblock)
10919 (forward-line 1)
10920 (while (not (looking-at org-dblock-end-re))
10921 (insert indent)
10922 (beginning-of-line 2))
10923 (when (looking-at org-dblock-end-re)
10924 (and (looking-at "[ \t]+")
10925 (replace-match ""))
10926 (insert indent)))))))
10928 (defun org-beginning-of-dblock ()
10929 "Find the beginning of the dynamic block at point.
10930 Error if there is no such block at point."
10931 (let ((pos (point))
10932 beg)
10933 (end-of-line 1)
10934 (if (and (re-search-backward org-dblock-start-re nil t)
10935 (setq beg (match-beginning 0))
10936 (re-search-forward org-dblock-end-re nil t)
10937 (> (match-end 0) pos))
10938 (goto-char beg)
10939 (goto-char pos)
10940 (error "Not in a dynamic block"))))
10942 (defun org-update-all-dblocks ()
10943 "Update all dynamic blocks in the buffer.
10944 This function can be used in a hook."
10945 (interactive)
10946 (when (eq major-mode 'org-mode)
10947 (org-map-dblocks 'org-update-dblock)))
10950 ;;;; Completion
10952 (defconst org-additional-option-like-keywords
10953 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
10954 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
10955 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
10956 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
10957 "BEGIN:" "END:"
10958 "ORGTBL" "TBLFM:" "TBLNAME:"
10959 "BEGIN_EXAMPLE" "END_EXAMPLE"
10960 "BEGIN_QUOTE" "END_QUOTE"
10961 "BEGIN_VERSE" "END_VERSE"
10962 "BEGIN_CENTER" "END_CENTER"
10963 "BEGIN_SRC" "END_SRC"
10964 "BEGIN_RESULT" "END_RESULT"
10965 "SOURCE:" "SRCNAME:" "FUNCTION:"
10966 "RESULTS:" "DATA:"
10967 "HEADER:" "HEADERS:"
10968 "BABEL:"
10969 "CATEGORY:" "COLUMNS:" "PROPERTY:"
10970 "CAPTION:" "LABEL:"
10971 "SETUPFILE:"
10972 "INCLUDE:"
10973 "BIND:"
10974 "MACRO:"))
10976 (defcustom org-structure-template-alist
10978 ("s" "#+begin_src ?\n\n#+end_src"
10979 "<src lang=\"?\">\n\n</src>")
10980 ("e" "#+begin_example\n?\n#+end_example"
10981 "<example>\n?\n</example>")
10982 ("q" "#+begin_quote\n?\n#+end_quote"
10983 "<quote>\n?\n</quote>")
10984 ("v" "#+begin_verse\n?\n#+end_verse"
10985 "<verse>\n?\n/verse>")
10986 ("c" "#+begin_center\n?\n#+end_center"
10987 "<center>\n?\n/center>")
10988 ("l" "#+begin_latex\n?\n#+end_latex"
10989 "<literal style=\"latex\">\n?\n</literal>")
10990 ("L" "#+latex: "
10991 "<literal style=\"latex\">?</literal>")
10992 ("h" "#+begin_html\n?\n#+end_html"
10993 "<literal style=\"html\">\n?\n</literal>")
10994 ("H" "#+html: "
10995 "<literal style=\"html\">?</literal>")
10996 ("a" "#+begin_ascii\n?\n#+end_ascii")
10997 ("A" "#+ascii: ")
10998 ("i" "#+index: ?"
10999 "#+index: ?")
11000 ("I" "#+include %file ?"
11001 "<include file=%file markup=\"?\">")
11003 "Structure completion elements.
11004 This is a list of abbreviation keys and values. The value gets inserted
11005 if you type `<' followed by the key and then press the completion key,
11006 usually `M-TAB'. %file will be replaced by a file name after prompting
11007 for the file using completion. The cursor will be placed at the position
11008 of the `?` in the template.
11009 There are two templates for each key, the first uses the original Org syntax,
11010 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11011 the default when the /org-mtags.el/ module has been loaded. See also the
11012 variable `org-mtags-prefer-muse-templates'.
11013 This is an experimental feature, it is undecided if it is going to stay in."
11014 :group 'org-completion
11015 :type '(repeat
11016 (string :tag "Key")
11017 (string :tag "Template")
11018 (string :tag "Muse Template")))
11020 (defun org-try-structure-completion ()
11021 "Try to complete a structure template before point.
11022 This looks for strings like \"<e\" on an otherwise empty line and
11023 expands them."
11024 (let ((l (buffer-substring (point-at-bol) (point)))
11026 (when (and (looking-at "[ \t]*$")
11027 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11028 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11029 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11030 (match-beginning 1)) a)
11031 t)))
11033 (defun org-complete-expand-structure-template (start cell)
11034 "Expand a structure template."
11035 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11036 (rpl (nth (if musep 2 1) cell))
11037 (ind ""))
11038 (delete-region start (point))
11039 (when (string-match "\\`#\\+" rpl)
11040 (cond
11041 ((bolp))
11042 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11043 (setq ind (buffer-substring (point-at-bol) (point))))
11044 (t (newline))))
11045 (setq start (point))
11046 (if (string-match "%file" rpl)
11047 (setq rpl (replace-match
11048 (concat
11049 "\""
11050 (save-match-data
11051 (abbreviate-file-name (read-file-name "Include file: ")))
11052 "\"")
11053 t t rpl)))
11054 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11055 (concat "\n" ind)))
11056 (insert rpl)
11057 (if (re-search-backward "\\?" start t) (delete-char 1))))
11059 ;;;; TODO, DEADLINE, Comments
11061 (defun org-toggle-comment ()
11062 "Change the COMMENT state of an entry."
11063 (interactive)
11064 (save-excursion
11065 (org-back-to-heading)
11066 (let (case-fold-search)
11067 (cond
11068 ((looking-at (format org-heading-keyword-regexp-format
11069 org-comment-string))
11070 (goto-char (match-end 1))
11071 (looking-at (concat " +" org-comment-string))
11072 (replace-match "" t t)
11073 (when (eolp) (insert " ")))
11074 ((looking-at org-outline-regexp)
11075 (goto-char (match-end 0))
11076 (insert org-comment-string " "))))))
11078 (defvar org-last-todo-state-is-todo nil
11079 "This is non-nil when the last TODO state change led to a TODO state.
11080 If the last change removed the TODO tag or switched to DONE, then
11081 this is nil.")
11083 (defvar org-setting-tags nil) ; dynamically skipped
11085 (defvar org-todo-setup-filter-hook nil
11086 "Hook for functions that pre-filter todo specs.
11087 Each function takes a todo spec and returns either nil or the spec
11088 transformed into canonical form." )
11090 (defvar org-todo-get-default-hook nil
11091 "Hook for functions that get a default item for todo.
11092 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11093 nil or a string to be used for the todo mark." )
11095 (defvar org-agenda-headline-snapshot-before-repeat)
11097 (defun org-current-effective-time ()
11098 "Return current time adjusted for `org-extend-today-until' variable"
11099 (let* ((ct (org-current-time))
11100 (dct (decode-time ct))
11101 (ct1
11102 (if (and org-use-effective-time
11103 (< (nth 2 dct) org-extend-today-until))
11104 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11105 ct)))
11106 ct1))
11108 (defun org-todo-yesterday (&optional arg)
11109 "Like `org-todo' but the time of change will be 23:59 of yesterday"
11110 (interactive "P")
11111 (let* ((hour (third (decode-time
11112 (org-current-time))))
11113 (org-extend-today-until (1+ hour)))
11114 (org-todo arg)))
11116 (defun org-todo (&optional arg)
11117 "Change the TODO state of an item.
11118 The state of an item is given by a keyword at the start of the heading,
11119 like
11120 *** TODO Write paper
11121 *** DONE Call mom
11123 The different keywords are specified in the variable `org-todo-keywords'.
11124 By default the available states are \"TODO\" and \"DONE\".
11125 So for this example: when the item starts with TODO, it is changed to DONE.
11126 When it starts with DONE, the DONE is removed. And when neither TODO nor
11127 DONE are present, add TODO at the beginning of the heading.
11129 With \\[universal-argument] prefix arg, use completion to determine the new \
11130 state.
11131 With numeric prefix arg, switch to that state.
11132 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11133 keywords (nextset).
11134 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11136 For calling through lisp, arg is also interpreted in the following way:
11137 'none -> empty state
11138 \"\"(empty string) -> switch to empty state
11139 'done -> switch to DONE
11140 'nextset -> switch to the next set of keywords
11141 'previousset -> switch to the previous set of keywords
11142 \"WAITING\" -> switch to the specified keyword, but only if it
11143 really is a member of `org-todo-keywords'."
11144 (interactive "P")
11145 (if (equal arg '(16)) (setq arg 'nextset))
11146 (let ((org-blocker-hook org-blocker-hook)
11147 (case-fold-search nil))
11148 (when (equal arg '(64))
11149 (setq arg nil org-blocker-hook nil))
11150 (when (and org-blocker-hook
11151 (or org-inhibit-blocking
11152 (org-entry-get nil "NOBLOCKING")))
11153 (setq org-blocker-hook nil))
11154 (save-excursion
11155 (catch 'exit
11156 (org-back-to-heading t)
11157 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11158 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11159 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11160 (let* ((match-data (match-data))
11161 (startpos (point-at-bol))
11162 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11163 (org-log-done org-log-done)
11164 (org-log-repeat org-log-repeat)
11165 (org-todo-log-states org-todo-log-states)
11166 (this (match-string 1))
11167 (hl-pos (match-beginning 0))
11168 (head (org-get-todo-sequence-head this))
11169 (ass (assoc head org-todo-kwd-alist))
11170 (interpret (nth 1 ass))
11171 (done-word (nth 3 ass))
11172 (final-done-word (nth 4 ass))
11173 (last-state (or this ""))
11174 (completion-ignore-case t)
11175 (member (member this org-todo-keywords-1))
11176 (tail (cdr member))
11177 (state (cond
11178 ((and org-todo-key-trigger
11179 (or (and (equal arg '(4))
11180 (eq org-use-fast-todo-selection 'prefix))
11181 (and (not arg) org-use-fast-todo-selection
11182 (not (eq org-use-fast-todo-selection
11183 'prefix)))))
11184 ;; Use fast selection
11185 (org-fast-todo-selection))
11186 ((and (equal arg '(4))
11187 (or (not org-use-fast-todo-selection)
11188 (not org-todo-key-trigger)))
11189 ;; Read a state with completion
11190 (org-icompleting-read
11191 "State: " (mapcar (lambda(x) (list x))
11192 org-todo-keywords-1)
11193 nil t))
11194 ((eq arg 'right)
11195 (if this
11196 (if tail (car tail) nil)
11197 (car org-todo-keywords-1)))
11198 ((eq arg 'left)
11199 (if (equal member org-todo-keywords-1)
11201 (if this
11202 (nth (- (length org-todo-keywords-1)
11203 (length tail) 2)
11204 org-todo-keywords-1)
11205 (org-last org-todo-keywords-1))))
11206 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11207 (setq arg nil))) ; hack to fall back to cycling
11208 (arg
11209 ;; user or caller requests a specific state
11210 (cond
11211 ((equal arg "") nil)
11212 ((eq arg 'none) nil)
11213 ((eq arg 'done) (or done-word (car org-done-keywords)))
11214 ((eq arg 'nextset)
11215 (or (car (cdr (member head org-todo-heads)))
11216 (car org-todo-heads)))
11217 ((eq arg 'previousset)
11218 (let ((org-todo-heads (reverse org-todo-heads)))
11219 (or (car (cdr (member head org-todo-heads)))
11220 (car org-todo-heads))))
11221 ((car (member arg org-todo-keywords-1)))
11222 ((stringp arg)
11223 (error "State `%s' not valid in this file" arg))
11224 ((nth (1- (prefix-numeric-value arg))
11225 org-todo-keywords-1))))
11226 ((null member) (or head (car org-todo-keywords-1)))
11227 ((equal this final-done-word) nil) ;; -> make empty
11228 ((null tail) nil) ;; -> first entry
11229 ((memq interpret '(type priority))
11230 (if (eq this-command last-command)
11231 (car tail)
11232 (if (> (length tail) 0)
11233 (or done-word (car org-done-keywords))
11234 nil)))
11236 (car tail))))
11237 (state (or
11238 (run-hook-with-args-until-success
11239 'org-todo-get-default-hook state last-state)
11240 state))
11241 (next (if state (concat " " state " ") " "))
11242 (change-plist (list :type 'todo-state-change :from this :to state
11243 :position startpos))
11244 dolog now-done-p)
11245 (when org-blocker-hook
11246 (setq org-last-todo-state-is-todo
11247 (not (member this org-done-keywords)))
11248 (unless (save-excursion
11249 (save-match-data
11250 (org-with-wide-buffer
11251 (run-hook-with-args-until-failure
11252 'org-blocker-hook change-plist))))
11253 (if (org-called-interactively-p 'interactive)
11254 (error "TODO state change from %s to %s blocked" this state)
11255 ;; fail silently
11256 (message "TODO state change from %s to %s blocked" this state)
11257 (throw 'exit nil))))
11258 (store-match-data match-data)
11259 (replace-match next t t)
11260 (unless (pos-visible-in-window-p hl-pos)
11261 (message "TODO state changed to %s" (org-trim next)))
11262 (unless head
11263 (setq head (org-get-todo-sequence-head state)
11264 ass (assoc head org-todo-kwd-alist)
11265 interpret (nth 1 ass)
11266 done-word (nth 3 ass)
11267 final-done-word (nth 4 ass)))
11268 (when (memq arg '(nextset previousset))
11269 (message "Keyword-Set %d/%d: %s"
11270 (- (length org-todo-sets) -1
11271 (length (memq (assoc state org-todo-sets) org-todo-sets)))
11272 (length org-todo-sets)
11273 (mapconcat 'identity (assoc state org-todo-sets) " ")))
11274 (setq org-last-todo-state-is-todo
11275 (not (member state org-done-keywords)))
11276 (setq now-done-p (and (member state org-done-keywords)
11277 (not (member this org-done-keywords))))
11278 (and logging (org-local-logging logging))
11279 (when (and (or org-todo-log-states org-log-done)
11280 (not (eq org-inhibit-logging t))
11281 (not (memq arg '(nextset previousset))))
11282 ;; we need to look at recording a time and note
11283 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
11284 (nth 2 (assoc this org-todo-log-states))))
11285 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11286 (setq dolog 'time))
11287 (when (and state
11288 (member state org-not-done-keywords)
11289 (not (member this org-not-done-keywords)))
11290 ;; This is now a todo state and was not one before
11291 ;; If there was a CLOSED time stamp, get rid of it.
11292 (org-add-planning-info nil nil 'closed))
11293 (when (and now-done-p org-log-done)
11294 ;; It is now done, and it was not done before
11295 (org-add-planning-info 'closed (org-current-effective-time))
11296 (if (and (not dolog) (eq 'note org-log-done))
11297 (org-add-log-setup 'done state this 'findpos 'note)))
11298 (when (and state dolog)
11299 ;; This is a non-nil state, and we need to log it
11300 (org-add-log-setup 'state state this 'findpos dolog)))
11301 ;; Fixup tag positioning
11302 (org-todo-trigger-tag-changes state)
11303 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11304 (when org-provide-todo-statistics
11305 (org-update-parent-todo-statistics))
11306 (run-hooks 'org-after-todo-state-change-hook)
11307 (if (and arg (not (member state org-done-keywords)))
11308 (setq head (org-get-todo-sequence-head state)))
11309 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11310 ;; Do we need to trigger a repeat?
11311 (when now-done-p
11312 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11313 ;; This is for the agenda, take a snapshot of the headline.
11314 (save-match-data
11315 (setq org-agenda-headline-snapshot-before-repeat
11316 (org-get-heading))))
11317 (org-auto-repeat-maybe state))
11318 ;; Fixup cursor location if close to the keyword
11319 (if (and (outline-on-heading-p)
11320 (not (bolp))
11321 (save-excursion (beginning-of-line 1)
11322 (looking-at org-todo-line-regexp))
11323 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11324 (progn
11325 (goto-char (or (match-end 2) (match-end 1)))
11326 (and (looking-at " ") (just-one-space))))
11327 (when org-trigger-hook
11328 (save-excursion
11329 (run-hook-with-args 'org-trigger-hook change-plist))))))))
11331 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11332 "Block turning an entry into a TODO, using the hierarchy.
11333 This checks whether the current task should be blocked from state
11334 changes. Such blocking occurs when:
11336 1. The task has children which are not all in a completed state.
11338 2. A task has a parent with the property :ORDERED:, and there
11339 are siblings prior to the current task with incomplete
11340 status.
11342 3. The parent of the task is blocked because it has siblings that should
11343 be done first, or is child of a block grandparent TODO entry."
11345 (if (not org-enforce-todo-dependencies)
11346 t ; if locally turned off don't block
11347 (catch 'dont-block
11348 ;; If this is not a todo state change, or if this entry is already DONE,
11349 ;; do not block
11350 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11351 (member (plist-get change-plist :from)
11352 (cons 'done org-done-keywords))
11353 (member (plist-get change-plist :to)
11354 (cons 'todo org-not-done-keywords))
11355 (not (plist-get change-plist :to)))
11356 (throw 'dont-block t))
11357 ;; If this task has children, and any are undone, it's blocked
11358 (save-excursion
11359 (org-back-to-heading t)
11360 (let ((this-level (funcall outline-level)))
11361 (outline-next-heading)
11362 (let ((child-level (funcall outline-level)))
11363 (while (and (not (eobp))
11364 (> child-level this-level))
11365 ;; this todo has children, check whether they are all
11366 ;; completed
11367 (if (and (not (org-entry-is-done-p))
11368 (org-entry-is-todo-p))
11369 (throw 'dont-block nil))
11370 (outline-next-heading)
11371 (setq child-level (funcall outline-level))))))
11372 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11373 ;; any previous siblings are undone, it's blocked
11374 (save-excursion
11375 (org-back-to-heading t)
11376 (let* ((pos (point))
11377 (parent-pos (and (org-up-heading-safe) (point))))
11378 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11379 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11380 (forward-line 1)
11381 (re-search-forward org-not-done-heading-regexp pos t))
11382 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11383 ;; Search further up the hierarchy, to see if an anchestor is blocked
11384 (while t
11385 (goto-char parent-pos)
11386 (if (not (looking-at org-not-done-heading-regexp))
11387 (throw 'dont-block t)) ; do not block, parent is not a TODO
11388 (setq pos (point))
11389 (setq parent-pos (and (org-up-heading-safe) (point)))
11390 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11391 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11392 (forward-line 1)
11393 (re-search-forward org-not-done-heading-regexp pos t))
11394 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11396 (defcustom org-track-ordered-property-with-tag nil
11397 "Should the ORDERED property also be shown as a tag?
11398 The ORDERED property decides if an entry should require subtasks to be
11399 completed in sequence. Since a property is not very visible, setting
11400 this option means that toggling the ORDERED property with the command
11401 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11402 not relevant for the behavior, but it makes things more visible.
11404 Note that toggling the tag with tags commands will not change the property
11405 and therefore not influence behavior!
11407 This can be t, meaning the tag ORDERED should be used, It can also be a
11408 string to select a different tag for this task."
11409 :group 'org-todo
11410 :type '(choice
11411 (const :tag "No tracking" nil)
11412 (const :tag "Track with ORDERED tag" t)
11413 (string :tag "Use other tag")))
11415 (defun org-toggle-ordered-property ()
11416 "Toggle the ORDERED property of the current entry.
11417 For better visibility, you can track the value of this property with a tag.
11418 See variable `org-track-ordered-property-with-tag'."
11419 (interactive)
11420 (let* ((t1 org-track-ordered-property-with-tag)
11421 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11422 (save-excursion
11423 (org-back-to-heading)
11424 (if (org-entry-get nil "ORDERED")
11425 (progn
11426 (org-delete-property "ORDERED")
11427 (and tag (org-toggle-tag tag 'off))
11428 (message "Subtasks can be completed in arbitrary order"))
11429 (org-entry-put nil "ORDERED" "t")
11430 (and tag (org-toggle-tag tag 'on))
11431 (message "Subtasks must be completed in sequence")))))
11433 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11434 (defun org-block-todo-from-checkboxes (change-plist)
11435 "Block turning an entry into a TODO, using checkboxes.
11436 This checks whether the current task should be blocked from state
11437 changes because there are unchecked boxes in this entry."
11438 (if (not org-enforce-todo-checkbox-dependencies)
11439 t ; if locally turned off don't block
11440 (catch 'dont-block
11441 ;; If this is not a todo state change, or if this entry is already DONE,
11442 ;; do not block
11443 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11444 (member (plist-get change-plist :from)
11445 (cons 'done org-done-keywords))
11446 (member (plist-get change-plist :to)
11447 (cons 'todo org-not-done-keywords))
11448 (not (plist-get change-plist :to)))
11449 (throw 'dont-block t))
11450 ;; If this task has checkboxes that are not checked, it's blocked
11451 (save-excursion
11452 (org-back-to-heading t)
11453 (let ((beg (point)) end)
11454 (outline-next-heading)
11455 (setq end (point))
11456 (goto-char beg)
11457 (if (org-list-search-forward
11458 (concat (org-item-beginning-re)
11459 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11460 "\\[[- ]\\]")
11461 end t)
11462 (progn
11463 (if (boundp 'org-blocked-by-checkboxes)
11464 (setq org-blocked-by-checkboxes t))
11465 (throw 'dont-block nil)))))
11466 t))) ; do not block
11468 (defun org-entry-blocked-p ()
11469 "Is the current entry blocked?"
11470 (if (org-entry-get nil "NOBLOCKING")
11471 nil ;; Never block this entry
11472 (not
11473 (run-hook-with-args-until-failure
11474 'org-blocker-hook
11475 (list :type 'todo-state-change
11476 :position (point)
11477 :from 'todo
11478 :to 'done)))))
11480 (defun org-update-statistics-cookies (all)
11481 "Update the statistics cookie, either from TODO or from checkboxes.
11482 This should be called with the cursor in a line with a statistics cookie."
11483 (interactive "P")
11484 (if all
11485 (progn
11486 (org-update-checkbox-count 'all)
11487 (org-map-entries 'org-update-parent-todo-statistics))
11488 (if (not (org-on-heading-p))
11489 (org-update-checkbox-count)
11490 (let ((pos (move-marker (make-marker) (point)))
11491 end l1 l2)
11492 (ignore-errors (org-back-to-heading t))
11493 (if (not (org-on-heading-p))
11494 (org-update-checkbox-count)
11495 (setq l1 (org-outline-level))
11496 (setq end (save-excursion
11497 (outline-next-heading)
11498 (if (org-on-heading-p) (setq l2 (org-outline-level)))
11499 (point)))
11500 (if (and (save-excursion
11501 (re-search-forward
11502 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11503 (not (save-excursion (re-search-forward
11504 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11505 (org-update-checkbox-count)
11506 (if (and l2 (> l2 l1))
11507 (progn
11508 (goto-char end)
11509 (org-update-parent-todo-statistics))
11510 (goto-char pos)
11511 (beginning-of-line 1)
11512 (while (re-search-forward
11513 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11514 (point-at-eol) t)
11515 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11516 (goto-char pos)
11517 (move-marker pos nil)))))
11519 (defvar org-entry-property-inherited-from) ;; defined below
11520 (defun org-update-parent-todo-statistics ()
11521 "Update any statistics cookie in the parent of the current headline.
11522 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11523 the entire subtree and this will travel up the hierarchy and update
11524 statistics everywhere."
11525 (let* ((prop (save-excursion (org-up-heading-safe)
11526 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11527 (recursive (or (not org-hierarchical-todo-statistics)
11528 (and prop (string-match "\\<recursive\\>" prop))))
11529 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11531 (first t)
11532 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11533 level ltoggle l1 new ndel
11534 (cnt-all 0) (cnt-done 0) is-percent kwd
11535 checkbox-beg ov ovs ove cookie-present)
11536 (catch 'exit
11537 (save-excursion
11538 (beginning-of-line 1)
11539 (setq ltoggle (funcall outline-level))
11540 ;; Three situations are to consider:
11542 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11543 ;; to the top-level ancestor on the headline;
11545 ;; 2. If parent has "recursive" property, repeat up to the
11546 ;; headline setting that property, taking inheritance into
11547 ;; account;
11549 ;; 3. Else, move up to direct parent and proceed only once.
11550 (while (and (setq level (org-up-heading-safe))
11551 (or recursive first)
11552 (>= (point) lim))
11553 (setq first nil cookie-present nil)
11554 (unless (and level
11555 (not (string-match
11556 "\\<checkbox\\>"
11557 (downcase (or (org-entry-get nil "COOKIE_DATA")
11558 "")))))
11559 (throw 'exit nil))
11560 (while (re-search-forward box-re (point-at-eol) t)
11561 (setq cnt-all 0 cnt-done 0 cookie-present t)
11562 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11563 (save-match-data
11564 (unless (outline-next-heading) (throw 'exit nil))
11565 (while (and (looking-at org-complex-heading-regexp)
11566 (> (setq l1 (length (match-string 1))) level))
11567 (setq kwd (and (or recursive (= l1 ltoggle))
11568 (match-string 2)))
11569 (if (or (eq org-provide-todo-statistics 'all-headlines)
11570 (and (listp org-provide-todo-statistics)
11571 (or (member kwd org-provide-todo-statistics)
11572 (member kwd org-done-keywords))))
11573 (setq cnt-all (1+ cnt-all))
11574 (if (eq org-provide-todo-statistics t)
11575 (and kwd (setq cnt-all (1+ cnt-all)))))
11576 (and (member kwd org-done-keywords)
11577 (setq cnt-done (1+ cnt-done)))
11578 (outline-next-heading)))
11579 (setq new
11580 (if is-percent
11581 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11582 (format "[%d/%d]" cnt-done cnt-all))
11583 ndel (- (match-end 0) checkbox-beg))
11584 ;; handle overlays when updating cookie from column view
11585 (when (setq ov (car (overlays-at checkbox-beg)))
11586 (setq ovs (overlay-start ov) ove (overlay-end ov))
11587 (delete-overlay ov))
11588 (goto-char checkbox-beg)
11589 (insert new)
11590 (delete-region (point) (+ (point) ndel))
11591 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11592 (when ov (move-overlay ov ovs ove)))
11593 (when cookie-present
11594 (run-hook-with-args 'org-after-todo-statistics-hook
11595 cnt-done (- cnt-all cnt-done))))))
11596 (run-hooks 'org-todo-statistics-hook)))
11598 (defvar org-after-todo-statistics-hook nil
11599 "Hook that is called after a TODO statistics cookie has been updated.
11600 Each function is called with two arguments: the number of not-done entries
11601 and the number of done entries.
11603 For example, the following function, when added to this hook, will switch
11604 an entry to DONE when all children are done, and back to TODO when new
11605 entries are set to a TODO status. Note that this hook is only called
11606 when there is a statistics cookie in the headline!
11608 (defun org-summary-todo (n-done n-not-done)
11609 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11610 (let (org-log-done org-log-states) ; turn off logging
11611 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11614 (defvar org-todo-statistics-hook nil
11615 "Hook that is run whenever Org thinks TODO statistics should be updated.
11616 This hook runs even if there is no statistics cookie present, in which case
11617 `org-after-todo-statistics-hook' would not run.")
11619 (defun org-todo-trigger-tag-changes (state)
11620 "Apply the changes defined in `org-todo-state-tags-triggers'."
11621 (let ((l org-todo-state-tags-triggers)
11622 changes)
11623 (when (or (not state) (equal state ""))
11624 (setq changes (append changes (cdr (assoc "" l)))))
11625 (when (and (stringp state) (> (length state) 0))
11626 (setq changes (append changes (cdr (assoc state l)))))
11627 (when (member state org-not-done-keywords)
11628 (setq changes (append changes (cdr (assoc 'todo l)))))
11629 (when (member state org-done-keywords)
11630 (setq changes (append changes (cdr (assoc 'done l)))))
11631 (dolist (c changes)
11632 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11634 (defun org-local-logging (value)
11635 "Get logging settings from a property VALUE."
11636 (let* (words w a)
11637 ;; directly set the variables, they are already local.
11638 (setq org-log-done nil
11639 org-log-repeat nil
11640 org-todo-log-states nil)
11641 (setq words (org-split-string value))
11642 (while (setq w (pop words))
11643 (cond
11644 ((setq a (assoc w org-startup-options))
11645 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11646 (set (nth 1 a) (nth 2 a))))
11647 ((setq a (org-extract-log-state-settings w))
11648 (and (member (car a) org-todo-keywords-1)
11649 (push a org-todo-log-states)))))))
11651 (defun org-get-todo-sequence-head (kwd)
11652 "Return the head of the TODO sequence to which KWD belongs.
11653 If KWD is not set, check if there is a text property remembering the
11654 right sequence."
11655 (let (p)
11656 (cond
11657 ((not kwd)
11658 (or (get-text-property (point-at-bol) 'org-todo-head)
11659 (progn
11660 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11661 nil (point-at-eol)))
11662 (get-text-property p 'org-todo-head))))
11663 ((not (member kwd org-todo-keywords-1))
11664 (car org-todo-keywords-1))
11665 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11667 (defun org-fast-todo-selection ()
11668 "Fast TODO keyword selection with single keys.
11669 Returns the new TODO keyword, or nil if no state change should occur."
11670 (let* ((fulltable org-todo-key-alist)
11671 (done-keywords org-done-keywords) ;; needed for the faces.
11672 (maxlen (apply 'max (mapcar
11673 (lambda (x)
11674 (if (stringp (car x)) (string-width (car x)) 0))
11675 fulltable)))
11676 (expert nil)
11677 (fwidth (+ maxlen 3 1 3))
11678 (ncol (/ (- (window-width) 4) fwidth))
11679 tg cnt e c tbl
11680 groups ingroup)
11681 (save-excursion
11682 (save-window-excursion
11683 (if expert
11684 (set-buffer (get-buffer-create " *Org todo*"))
11685 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11686 (erase-buffer)
11687 (org-set-local 'org-done-keywords done-keywords)
11688 (setq tbl fulltable cnt 0)
11689 (while (setq e (pop tbl))
11690 (cond
11691 ((equal e '(:startgroup))
11692 (push '() groups) (setq ingroup t)
11693 (when (not (= cnt 0))
11694 (setq cnt 0)
11695 (insert "\n"))
11696 (insert "{ "))
11697 ((equal e '(:endgroup))
11698 (setq ingroup nil cnt 0)
11699 (insert "}\n"))
11700 ((equal e '(:newline))
11701 (when (not (= cnt 0))
11702 (setq cnt 0)
11703 (insert "\n")
11704 (setq e (car tbl))
11705 (while (equal (car tbl) '(:newline))
11706 (insert "\n")
11707 (setq tbl (cdr tbl)))))
11709 (setq tg (car e) c (cdr e))
11710 (if ingroup (push tg (car groups)))
11711 (setq tg (org-add-props tg nil 'face
11712 (org-get-todo-face tg)))
11713 (if (and (= cnt 0) (not ingroup)) (insert " "))
11714 (insert "[" c "] " tg (make-string
11715 (- fwidth 4 (length tg)) ?\ ))
11716 (when (= (setq cnt (1+ cnt)) ncol)
11717 (insert "\n")
11718 (if ingroup (insert " "))
11719 (setq cnt 0)))))
11720 (insert "\n")
11721 (goto-char (point-min))
11722 (if (not expert) (org-fit-window-to-buffer))
11723 (message "[a-z..]:Set [SPC]:clear")
11724 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11725 (cond
11726 ((or (= c ?\C-g)
11727 (and (= c ?q) (not (rassoc c fulltable))))
11728 (setq quit-flag t))
11729 ((= c ?\ ) nil)
11730 ((setq e (rassoc c fulltable) tg (car e))
11732 (t (setq quit-flag t)))))))
11734 (defun org-entry-is-todo-p ()
11735 (member (org-get-todo-state) org-not-done-keywords))
11737 (defun org-entry-is-done-p ()
11738 (member (org-get-todo-state) org-done-keywords))
11740 (defun org-get-todo-state ()
11741 (save-excursion
11742 (org-back-to-heading t)
11743 (and (looking-at org-todo-line-regexp)
11744 (match-end 2)
11745 (match-string 2))))
11747 (defun org-at-date-range-p (&optional inactive-ok)
11748 "Is the cursor inside a date range?"
11749 (interactive)
11750 (save-excursion
11751 (catch 'exit
11752 (let ((pos (point)))
11753 (skip-chars-backward "^[<\r\n")
11754 (skip-chars-backward "<[")
11755 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11756 (>= (match-end 0) pos)
11757 (throw 'exit t))
11758 (skip-chars-backward "^<[\r\n")
11759 (skip-chars-backward "<[")
11760 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11761 (>= (match-end 0) pos)
11762 (throw 'exit t)))
11763 nil)))
11765 (defun org-get-repeat (&optional tagline)
11766 "Check if there is a deadline/schedule with repeater in this entry."
11767 (save-match-data
11768 (save-excursion
11769 (org-back-to-heading t)
11770 (and (re-search-forward (if tagline
11771 (concat tagline "\\s-*" org-repeat-re)
11772 org-repeat-re)
11773 (org-entry-end-position) t)
11774 (match-string-no-properties 1)))))
11776 (defvar org-last-changed-timestamp)
11777 (defvar org-last-inserted-timestamp)
11778 (defvar org-log-post-message)
11779 (defvar org-log-note-purpose)
11780 (defvar org-log-note-how)
11781 (defvar org-log-note-extra)
11782 (defun org-auto-repeat-maybe (done-word)
11783 "Check if the current headline contains a repeated deadline/schedule.
11784 If yes, set TODO state back to what it was and change the base date
11785 of repeating deadline/scheduled time stamps to new date.
11786 This function is run automatically after each state change to a DONE state."
11787 ;; last-state is dynamically scoped into this function
11788 (let* ((repeat (org-get-repeat))
11789 (aa (assoc last-state org-todo-kwd-alist))
11790 (interpret (nth 1 aa))
11791 (head (nth 2 aa))
11792 (whata '(("d" . day) ("m" . month) ("y" . year)))
11793 (msg "Entry repeats: ")
11794 (org-log-done nil)
11795 (org-todo-log-states nil)
11796 re type n what ts time to-state)
11797 (when repeat
11798 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11799 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11800 org-todo-repeat-to-state))
11801 (unless (and to-state (member to-state org-todo-keywords-1))
11802 (setq to-state (if (eq interpret 'type) last-state head)))
11803 (org-todo to-state)
11804 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11805 (org-entry-put nil "LAST_REPEAT" (format-time-string
11806 (org-time-stamp-format t t))))
11807 (when org-log-repeat
11808 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11809 (memq 'org-add-log-note post-command-hook))
11810 ;; OK, we are already setup for some record
11811 (if (eq org-log-repeat 'note)
11812 ;; make sure we take a note, not only a time stamp
11813 (setq org-log-note-how 'note))
11814 ;; Set up for taking a record
11815 (org-add-log-setup 'state (or done-word (car org-done-keywords))
11816 last-state
11817 'findpos org-log-repeat)))
11818 (org-back-to-heading t)
11819 (org-add-planning-info nil nil 'closed)
11820 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11821 org-deadline-time-regexp "\\)\\|\\("
11822 org-ts-regexp "\\)"))
11823 (while (re-search-forward
11824 re (save-excursion (outline-next-heading) (point)) t)
11825 (setq type (if (match-end 1) org-scheduled-string
11826 (if (match-end 3) org-deadline-string "Plain:"))
11827 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
11828 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
11829 (setq n (string-to-number (match-string 2 ts))
11830 what (match-string 3 ts))
11831 (if (equal what "w") (setq n (* n 7) what "d"))
11832 ;; Preparation, see if we need to modify the start date for the change
11833 (when (match-end 1)
11834 (setq time (save-match-data (org-time-string-to-time ts)))
11835 (cond
11836 ((equal (match-string 1 ts) ".")
11837 ;; Shift starting date to today
11838 (org-timestamp-change
11839 (- (org-today) (time-to-days time))
11840 'day))
11841 ((equal (match-string 1 ts) "+")
11842 (let ((nshiftmax 10) (nshift 0))
11843 (while (or (= nshift 0)
11844 (<= (time-to-days time)
11845 (time-to-days (current-time))))
11846 (when (= (incf nshift) nshiftmax)
11847 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
11848 (error "Abort")))
11849 (org-timestamp-change n (cdr (assoc what whata)))
11850 (org-at-timestamp-p t)
11851 (setq ts (match-string 1))
11852 (setq time (save-match-data (org-time-string-to-time ts)))))
11853 (org-timestamp-change (- n) (cdr (assoc what whata)))
11854 ;; rematch, so that we have everything in place for the real shift
11855 (org-at-timestamp-p t)
11856 (setq ts (match-string 1))
11857 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
11858 (org-timestamp-change n (cdr (assoc what whata)))
11859 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
11860 (setq org-log-post-message msg)
11861 (message "%s" msg))))
11863 (defun org-show-todo-tree (arg)
11864 "Make a compact tree which shows all headlines marked with TODO.
11865 The tree will show the lines where the regexp matches, and all higher
11866 headlines above the match.
11867 With a \\[universal-argument] prefix, prompt for a regexp to match.
11868 With a numeric prefix N, construct a sparse tree for the Nth element
11869 of `org-todo-keywords-1'."
11870 (interactive "P")
11871 (let ((case-fold-search nil)
11872 (kwd-re
11873 (cond ((null arg) org-not-done-regexp)
11874 ((equal arg '(4))
11875 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
11876 (mapcar 'list org-todo-keywords-1))))
11877 (concat "\\("
11878 (mapconcat 'identity (org-split-string kwd "|") "\\|")
11879 "\\)\\>")))
11880 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
11881 (regexp-quote (nth (1- (prefix-numeric-value arg))
11882 org-todo-keywords-1)))
11883 (t (error "Invalid prefix argument: %s" arg)))))
11884 (message "%d TODO entries found"
11885 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
11887 (defun org-deadline (&optional remove time)
11888 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
11889 With argument REMOVE, remove any deadline from the item.
11890 With argument TIME, set the deadline at the corresponding date. TIME
11891 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
11892 (interactive "P")
11893 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11894 (let (org-loop-over-headlines-in-active-region)
11895 (org-map-entries
11896 `(org-deadline ',remove ,time) org-loop-over-headlines-in-active-region 'region (if (outline-invisible-p) (org-end-of-subtree nil t))))
11897 (let* ((old-date (org-entry-get nil "DEADLINE"))
11898 (repeater (and old-date
11899 (string-match
11900 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
11901 old-date)
11902 (match-string 1 old-date))))
11903 (if remove
11904 (progn
11905 (when (and old-date org-log-redeadline)
11906 (org-add-log-setup 'deldeadline nil old-date 'findpos
11907 org-log-redeadline))
11908 (org-remove-timestamp-with-keyword org-deadline-string)
11909 (message "Item no longer has a deadline."))
11910 (org-add-planning-info 'deadline time 'closed)
11911 (when (and old-date org-log-redeadline
11912 (not (equal old-date
11913 (substring org-last-inserted-timestamp 1 -1))))
11914 (org-add-log-setup 'redeadline nil old-date 'findpos
11915 org-log-redeadline))
11916 (when repeater
11917 (save-excursion
11918 (org-back-to-heading t)
11919 (when (re-search-forward (concat org-deadline-string " "
11920 org-last-inserted-timestamp)
11921 (save-excursion
11922 (outline-next-heading) (point)) t)
11923 (goto-char (1- (match-end 0)))
11924 (insert " " repeater)
11925 (setq org-last-inserted-timestamp
11926 (concat (substring org-last-inserted-timestamp 0 -1)
11927 " " repeater
11928 (substring org-last-inserted-timestamp -1))))))
11929 (message "Deadline on %s" org-last-inserted-timestamp)))))
11931 (defun org-schedule (&optional remove time)
11932 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
11933 With argument REMOVE, remove any scheduling date from the item.
11934 With argument TIME, scheduled at the corresponding date. TIME can
11935 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
11936 (interactive "P")
11937 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11938 (let (org-loop-over-headlines-in-active-region)
11939 (org-map-entries
11940 `(org-schedule ',remove ,time) org-loop-over-headlines-in-active-region 'region (if (outline-invisible-p) (org-end-of-subtree nil t))))
11941 (let* ((old-date (org-entry-get nil "SCHEDULED"))
11942 (repeater (and old-date
11943 (string-match
11944 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
11945 old-date)
11946 (match-string 1 old-date))))
11947 (if remove
11948 (progn
11949 (when (and old-date org-log-reschedule)
11950 (org-add-log-setup 'delschedule nil old-date 'findpos
11951 org-log-reschedule))
11952 (org-remove-timestamp-with-keyword org-scheduled-string)
11953 (message "Item is no longer scheduled."))
11954 (org-add-planning-info 'scheduled time 'closed)
11955 (when (and old-date org-log-reschedule
11956 (not (equal old-date
11957 (substring org-last-inserted-timestamp 1 -1))))
11958 (org-add-log-setup 'reschedule nil old-date 'findpos
11959 org-log-reschedule))
11960 (when repeater
11961 (save-excursion
11962 (org-back-to-heading t)
11963 (when (re-search-forward (concat org-scheduled-string " "
11964 org-last-inserted-timestamp)
11965 (save-excursion
11966 (outline-next-heading) (point)) t)
11967 (goto-char (1- (match-end 0)))
11968 (insert " " repeater)
11969 (setq org-last-inserted-timestamp
11970 (concat (substring org-last-inserted-timestamp 0 -1)
11971 " " repeater
11972 (substring org-last-inserted-timestamp -1))))))
11973 (message "Scheduled to %s" org-last-inserted-timestamp)))))
11975 (defun org-get-scheduled-time (pom &optional inherit)
11976 "Get the scheduled time as a time tuple, of a format suitable
11977 for calling org-schedule with, or if there is no scheduling,
11978 returns nil."
11979 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
11980 (when time
11981 (apply 'encode-time (org-parse-time-string time)))))
11983 (defun org-get-deadline-time (pom &optional inherit)
11984 "Get the deadline as a time tuple, of a format suitable for
11985 calling org-deadline with, or if there is no scheduling, returns
11986 nil."
11987 (let ((time (org-entry-get pom "DEADLINE" inherit)))
11988 (when time
11989 (apply 'encode-time (org-parse-time-string time)))))
11991 (defun org-remove-timestamp-with-keyword (keyword)
11992 "Remove all time stamps with KEYWORD in the current entry."
11993 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
11994 beg)
11995 (save-excursion
11996 (org-back-to-heading t)
11997 (setq beg (point))
11998 (outline-next-heading)
11999 (while (re-search-backward re beg t)
12000 (replace-match "")
12001 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12002 (equal (char-before) ?\ ))
12003 (backward-delete-char 1)
12004 (if (string-match "^[ \t]*$" (buffer-substring
12005 (point-at-bol) (point-at-eol)))
12006 (delete-region (point-at-bol)
12007 (min (point-max) (1+ (point-at-eol))))))))))
12009 (defun org-add-planning-info (what &optional time &rest remove)
12010 "Insert new timestamp with keyword in the line directly after the headline.
12011 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12012 If non is given, the user is prompted for a date.
12013 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12014 be removed."
12015 (interactive)
12016 (let (org-time-was-given org-end-time-was-given ts
12017 end default-time default-input)
12019 (catch 'exit
12020 (when (and (memq what '(scheduled deadline))
12021 (or (not time)
12022 (and (stringp time)
12023 (string-match "^[-+]+[0-9]" time))))
12024 ;; Try to get a default date/time from existing timestamp
12025 (save-excursion
12026 (org-back-to-heading t)
12027 (setq end (save-excursion (outline-next-heading) (point)))
12028 (when (re-search-forward (if (eq what 'scheduled)
12029 org-scheduled-time-regexp
12030 org-deadline-time-regexp)
12031 end t)
12032 (setq ts (match-string 1)
12033 default-time
12034 (apply 'encode-time (org-parse-time-string ts))
12035 default-input (and ts (org-get-compact-tod ts))))))
12036 (when what
12037 (setq time
12038 (if (and (stringp time)
12039 (string-match "^[-+]+[0-9]" time))
12040 ;; This is a relative time, set the proper date
12041 (apply 'encode-time
12042 (org-read-date-analyze
12043 time default-time (decode-time default-time)))
12044 ;; If necessary, get the time from the user
12045 (or time (org-read-date nil 'to-time nil nil
12046 default-time default-input)))))
12048 (when (and org-insert-labeled-timestamps-at-point
12049 (member what '(scheduled deadline)))
12050 (insert
12051 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12052 (org-insert-time-stamp time org-time-was-given
12053 nil nil nil (list org-end-time-was-given))
12054 (setq what nil))
12055 (save-excursion
12056 (save-restriction
12057 (let (col list elt ts buffer-invisibility-spec)
12058 (org-back-to-heading t)
12059 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12060 (goto-char (match-end 1))
12061 (setq col (current-column))
12062 (goto-char (match-end 0))
12063 (if (eobp) (insert "\n") (forward-char 1))
12064 (when (and (not what)
12065 (not (looking-at
12066 (concat "[ \t]*"
12067 org-keyword-time-not-clock-regexp))))
12068 ;; Nothing to add, nothing to remove...... :-)
12069 (throw 'exit nil))
12070 (if (and (not (looking-at org-outline-regexp))
12071 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12072 "[^\r\n]*"))
12073 (not (equal (match-string 1) org-clock-string)))
12074 (narrow-to-region (match-beginning 0) (match-end 0))
12075 (insert-before-markers "\n")
12076 (backward-char 1)
12077 (narrow-to-region (point) (point))
12078 (and org-adapt-indentation (org-indent-to-column col)))
12079 ;; Check if we have to remove something.
12080 (setq list (cons what remove))
12081 (while list
12082 (setq elt (pop list))
12083 (when (or (and (eq elt 'scheduled)
12084 (re-search-forward org-scheduled-time-regexp nil t))
12085 (and (eq elt 'deadline)
12086 (re-search-forward org-deadline-time-regexp nil t))
12087 (and (eq elt 'closed)
12088 (re-search-forward org-closed-time-regexp nil t)))
12089 (replace-match "")
12090 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12091 (and (looking-at "[ \t]+") (replace-match ""))
12092 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12093 (when what
12094 (insert
12095 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12096 (cond ((eq what 'scheduled) org-scheduled-string)
12097 ((eq what 'deadline) org-deadline-string)
12098 ((eq what 'closed) org-closed-string))
12099 " ")
12100 (setq ts (org-insert-time-stamp
12101 time
12102 (or org-time-was-given
12103 (and (eq what 'closed) org-log-done-with-time))
12104 (eq what 'closed)
12105 nil nil (list org-end-time-was-given)))
12106 (insert
12107 (if (not (or (bolp) (eq (char-before) ?\ )
12108 (memq (char-after) '(32 10))
12109 (eobp))) " " ""))
12110 (end-of-line 1))
12111 (goto-char (point-min))
12112 (widen)
12113 (if (and (looking-at "[ \t]*\n")
12114 (equal (char-before) ?\n))
12115 (delete-region (1- (point)) (point-at-eol)))
12116 ts))))))
12118 (defvar org-log-note-marker (make-marker))
12119 (defvar org-log-note-purpose nil)
12120 (defvar org-log-note-state nil)
12121 (defvar org-log-note-previous-state nil)
12122 (defvar org-log-note-how nil)
12123 (defvar org-log-note-extra nil)
12124 (defvar org-log-note-window-configuration nil)
12125 (defvar org-log-note-return-to (make-marker))
12126 (defvar org-log-note-effective-time nil
12127 "Remembered current time so that dynamically scoped
12128 `org-extend-today-until' affects tha timestamps in state change
12129 log")
12131 (defvar org-log-post-message nil
12132 "Message to be displayed after a log note has been stored.
12133 The auto-repeater uses this.")
12135 (defun org-add-note ()
12136 "Add a note to the current entry.
12137 This is done in the same way as adding a state change note."
12138 (interactive)
12139 (org-add-log-setup 'note nil nil 'findpos nil))
12141 (defvar org-property-end-re)
12142 (defun org-add-log-setup (&optional purpose state prev-state
12143 findpos how extra)
12144 "Set up the post command hook to take a note.
12145 If this is about to TODO state change, the new state is expected in STATE.
12146 When FINDPOS is non-nil, find the correct position for the note in
12147 the current entry. If not, assume that it can be inserted at point.
12148 HOW is an indicator what kind of note should be created.
12149 EXTRA is additional text that will be inserted into the notes buffer."
12150 (let* ((org-log-into-drawer (org-log-into-drawer))
12151 (drawer (cond ((stringp org-log-into-drawer)
12152 org-log-into-drawer)
12153 (org-log-into-drawer "LOGBOOK")
12154 (t nil))))
12155 (save-restriction
12156 (save-excursion
12157 (when findpos
12158 (org-back-to-heading t)
12159 (narrow-to-region (point) (save-excursion
12160 (outline-next-heading) (point)))
12161 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12162 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12163 "[^\r\n]*\\)?"))
12164 (goto-char (match-end 0))
12165 (cond
12166 (drawer
12167 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12168 nil t)
12169 (progn
12170 (goto-char (match-end 0))
12171 (or org-log-states-order-reversed
12172 (and (re-search-forward org-property-end-re nil t)
12173 (goto-char (1- (match-beginning 0))))))
12174 (insert "\n:" drawer ":\n:END:")
12175 (beginning-of-line 0)
12176 (org-indent-line-function)
12177 (beginning-of-line 2)
12178 (org-indent-line-function)
12179 (end-of-line 0)))
12180 ((and org-log-state-notes-insert-after-drawers
12181 (save-excursion
12182 (forward-line) (looking-at org-drawer-regexp)))
12183 (forward-line)
12184 (while (looking-at org-drawer-regexp)
12185 (goto-char (match-end 0))
12186 (re-search-forward org-property-end-re (point-max) t)
12187 (forward-line))
12188 (forward-line -1)))
12189 (unless org-log-states-order-reversed
12190 (and (= (char-after) ?\n) (forward-char 1))
12191 (org-skip-over-state-notes)
12192 (skip-chars-backward " \t\n\r")))
12193 (move-marker org-log-note-marker (point))
12194 (setq org-log-note-purpose purpose
12195 org-log-note-state state
12196 org-log-note-previous-state prev-state
12197 org-log-note-how how
12198 org-log-note-extra extra
12199 org-log-note-effective-time (org-current-effective-time))
12200 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12202 (defun org-skip-over-state-notes ()
12203 "Skip past the list of State notes in an entry."
12204 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12205 (when (ignore-errors (goto-char (org-in-item-p)))
12206 (let* ((struct (org-list-struct))
12207 (prevs (org-list-prevs-alist struct)))
12208 (while (looking-at "[ \t]*- State")
12209 (goto-char (or (org-list-get-next-item (point) struct prevs)
12210 (org-list-get-item-end (point) struct)))))))
12212 (defun org-add-log-note (&optional purpose)
12213 "Pop up a window for taking a note, and add this note later at point."
12214 (remove-hook 'post-command-hook 'org-add-log-note)
12215 (setq org-log-note-window-configuration (current-window-configuration))
12216 (delete-other-windows)
12217 (move-marker org-log-note-return-to (point))
12218 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12219 (goto-char org-log-note-marker)
12220 (org-switch-to-buffer-other-window "*Org Note*")
12221 (erase-buffer)
12222 (if (memq org-log-note-how '(time state))
12223 (let (current-prefix-arg) (org-store-log-note))
12224 (let ((org-inhibit-startup t)) (org-mode))
12225 (insert (format "# Insert note for %s.
12226 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12227 (cond
12228 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12229 ((eq org-log-note-purpose 'done) "closed todo item")
12230 ((eq org-log-note-purpose 'state)
12231 (format "state change from \"%s\" to \"%s\""
12232 (or org-log-note-previous-state "")
12233 (or org-log-note-state "")))
12234 ((eq org-log-note-purpose 'reschedule)
12235 "rescheduling")
12236 ((eq org-log-note-purpose 'delschedule)
12237 "no longer scheduled")
12238 ((eq org-log-note-purpose 'redeadline)
12239 "changing deadline")
12240 ((eq org-log-note-purpose 'deldeadline)
12241 "removing deadline")
12242 ((eq org-log-note-purpose 'refile)
12243 "refiling")
12244 ((eq org-log-note-purpose 'note)
12245 "this entry")
12246 (t (error "This should not happen")))))
12247 (if org-log-note-extra (insert org-log-note-extra))
12248 (org-set-local 'org-finish-function 'org-store-log-note)
12249 (run-hooks 'org-log-buffer-setup-hook)))
12251 (defvar org-note-abort nil) ; dynamically scoped
12252 (defun org-store-log-note ()
12253 "Finish taking a log note, and insert it to where it belongs."
12254 (let ((txt (buffer-string))
12255 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12256 lines ind bul)
12257 (kill-buffer (current-buffer))
12258 (while (string-match "\\`#.*\n[ \t\n]*" txt)
12259 (setq txt (replace-match "" t t txt)))
12260 (if (string-match "\\s-+\\'" txt)
12261 (setq txt (replace-match "" t t txt)))
12262 (setq lines (org-split-string txt "\n"))
12263 (when (and note (string-match "\\S-" note))
12264 (setq note
12265 (org-replace-escapes
12266 note
12267 (list (cons "%u" (user-login-name))
12268 (cons "%U" user-full-name)
12269 (cons "%t" (format-time-string
12270 (org-time-stamp-format 'long 'inactive)
12271 org-log-note-effective-time))
12272 (cons "%T" (format-time-string
12273 (org-time-stamp-format 'long nil)
12274 org-log-note-effective-time))
12275 (cons "%d" (format-time-string
12276 (org-time-stamp-format nil 'inactive)
12277 org-log-note-effective-time))
12278 (cons "%D" (format-time-string
12279 (org-time-stamp-format nil nil)
12280 org-log-note-effective-time))
12281 (cons "%s" (if org-log-note-state
12282 (concat "\"" org-log-note-state "\"")
12283 ""))
12284 (cons "%S" (if org-log-note-previous-state
12285 (concat "\"" org-log-note-previous-state "\"")
12286 "\"\"")))))
12287 (if lines (setq note (concat note " \\\\")))
12288 (push note lines))
12289 (when (or current-prefix-arg org-note-abort)
12290 (when org-log-into-drawer
12291 (org-remove-empty-drawer-at
12292 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12293 org-log-note-marker))
12294 (setq lines nil))
12295 (when lines
12296 (with-current-buffer (marker-buffer org-log-note-marker)
12297 (save-excursion
12298 (goto-char org-log-note-marker)
12299 (move-marker org-log-note-marker nil)
12300 (end-of-line 1)
12301 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12302 (setq ind (save-excursion
12303 (if (ignore-errors (goto-char (org-in-item-p)))
12304 (let ((struct (org-list-struct)))
12305 (org-list-get-ind
12306 (org-list-get-top-point struct) struct))
12307 (skip-chars-backward " \r\t\n")
12308 (cond
12309 ((and (org-at-heading-p)
12310 org-adapt-indentation)
12311 (1+ (org-current-level)))
12312 ((org-at-heading-p) 0)
12313 (t (org-get-indentation))))))
12314 (setq bul (org-list-bullet-string "-"))
12315 (org-indent-line-to ind)
12316 (insert bul (pop lines))
12317 (let ((ind-body (+ (length bul) ind)))
12318 (while lines
12319 (insert "\n")
12320 (org-indent-line-to ind-body)
12321 (insert (pop lines))))
12322 (message "Note stored")
12323 (org-back-to-heading t)
12324 (org-cycle-hide-drawers 'children)))))
12325 (set-window-configuration org-log-note-window-configuration)
12326 (with-current-buffer (marker-buffer org-log-note-return-to)
12327 (goto-char org-log-note-return-to))
12328 (move-marker org-log-note-return-to nil)
12329 (and org-log-post-message (message "%s" org-log-post-message)))
12331 (defun org-remove-empty-drawer-at (drawer pos)
12332 "Remove an empty drawer DRAWER at position POS.
12333 POS may also be a marker."
12334 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12335 (save-excursion
12336 (save-restriction
12337 (widen)
12338 (goto-char pos)
12339 (if (org-in-regexp
12340 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12341 (replace-match ""))))))
12343 (defun org-sparse-tree (&optional arg)
12344 "Create a sparse tree, prompt for the details.
12345 This command can create sparse trees. You first need to select the type
12346 of match used to create the tree:
12348 t Show all TODO entries.
12349 T Show entries with a specific TODO keyword.
12350 m Show entries selected by a tags/property match.
12351 p Enter a property name and its value (both with completion on existing
12352 names/values) and show entries with that property.
12353 r Show entries matching a regular expression (`/' can be used as well)
12354 d Show deadlines due within `org-deadline-warning-days'.
12355 b Show deadlines and scheduled items before a date.
12356 a Show deadlines and scheduled items after a date."
12357 (interactive "P")
12358 (let (ans kwd value)
12359 (message "Sparse tree: [r]egexp [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty\n [d]eadlines [b]efore-date [a]fter-date")
12360 (setq ans (read-char-exclusive))
12361 (cond
12362 ((equal ans ?d)
12363 (call-interactively 'org-check-deadlines))
12364 ((equal ans ?b)
12365 (call-interactively 'org-check-before-date))
12366 ((equal ans ?a)
12367 (call-interactively 'org-check-after-date))
12368 ((equal ans ?t)
12369 (org-show-todo-tree nil))
12370 ((equal ans ?T)
12371 (org-show-todo-tree '(4)))
12372 ((member ans '(?T ?m))
12373 (call-interactively 'org-match-sparse-tree))
12374 ((member ans '(?p ?P))
12375 (setq kwd (org-icompleting-read "Property: "
12376 (mapcar 'list (org-buffer-property-keys))))
12377 (setq value (org-icompleting-read "Value: "
12378 (mapcar 'list (org-property-values kwd))))
12379 (unless (string-match "\\`{.*}\\'" value)
12380 (setq value (concat "\"" value "\"")))
12381 (org-match-sparse-tree arg (concat kwd "=" value)))
12382 ((member ans '(?r ?R ?/))
12383 (call-interactively 'org-occur))
12384 (t (error "No such sparse tree command \"%c\"" ans)))))
12386 (defvar org-occur-highlights nil
12387 "List of overlays used for occur matches.")
12388 (make-variable-buffer-local 'org-occur-highlights)
12389 (defvar org-occur-parameters nil
12390 "Parameters of the active org-occur calls.
12391 This is a list, each call to org-occur pushes as cons cell,
12392 containing the regular expression and the callback, onto the list.
12393 The list can contain several entries if `org-occur' has been called
12394 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12395 will only contain one set of parameters. When the highlights are
12396 removed (for example with `C-c C-c', or with the next edit (depending
12397 on `org-remove-highlights-with-change'), this variable is emptied
12398 as well.")
12399 (make-variable-buffer-local 'org-occur-parameters)
12401 (defun org-occur (regexp &optional keep-previous callback)
12402 "Make a compact tree which shows all matches of REGEXP.
12403 The tree will show the lines where the regexp matches, and all higher
12404 headlines above the match. It will also show the heading after the match,
12405 to make sure editing the matching entry is easy.
12406 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12407 call to `org-occur' will be kept, to allow stacking of calls to this
12408 command.
12409 If CALLBACK is non-nil, it is a function which is called to confirm
12410 that the match should indeed be shown."
12411 (interactive "sRegexp: \nP")
12412 (when (equal regexp "")
12413 (error "Regexp cannot be empty"))
12414 (unless keep-previous
12415 (org-remove-occur-highlights nil nil t))
12416 (push (cons regexp callback) org-occur-parameters)
12417 (let ((cnt 0))
12418 (save-excursion
12419 (goto-char (point-min))
12420 (if (or (not keep-previous) ; do not want to keep
12421 (not org-occur-highlights)) ; no previous matches
12422 ;; hide everything
12423 (org-overview))
12424 (while (re-search-forward regexp nil t)
12425 (when (or (not callback)
12426 (save-match-data (funcall callback)))
12427 (setq cnt (1+ cnt))
12428 (when org-highlight-sparse-tree-matches
12429 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12430 (org-show-context 'occur-tree))))
12431 (when org-remove-highlights-with-change
12432 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12433 nil 'local))
12434 (unless org-sparse-tree-open-archived-trees
12435 (org-hide-archived-subtrees (point-min) (point-max)))
12436 (run-hooks 'org-occur-hook)
12437 (if (org-called-interactively-p 'interactive)
12438 (message "%d match(es) for regexp %s" cnt regexp))
12439 cnt))
12441 (defun org-occur-next-match (&optional n reset)
12442 "Function for `next-error-function' to find sparse tree matches.
12443 N is the number of matches to move, when negative move backwards.
12444 RESET is entirely ignored - this function always goes back to the
12445 starting point when no match is found."
12446 (let* ((limit (if (< n 0) (point-min) (point-max)))
12447 (search-func (if (< n 0)
12448 'previous-single-char-property-change
12449 'next-single-char-property-change))
12450 (n (abs n))
12451 (pos (point))
12453 (catch 'exit
12454 (while (setq p1 (funcall search-func (point) 'org-type))
12455 (when (equal p1 limit)
12456 (goto-char pos)
12457 (error "No more matches"))
12458 (when (equal (get-char-property p1 'org-type) 'org-occur)
12459 (setq n (1- n))
12460 (when (= n 0)
12461 (goto-char p1)
12462 (throw 'exit (point))))
12463 (goto-char p1))
12464 (goto-char p1)
12465 (error "No more matches"))))
12467 (defun org-show-context (&optional key)
12468 "Make sure point and context are visible.
12469 How much context is shown depends upon the variables
12470 `org-show-hierarchy-above', `org-show-following-heading'. and
12471 `org-show-siblings'."
12472 (let ((heading-p (org-on-heading-p t))
12473 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12474 (following-p (org-get-alist-option org-show-following-heading key))
12475 (entry-p (org-get-alist-option org-show-entry-below key))
12476 (siblings-p (org-get-alist-option org-show-siblings key)))
12477 (catch 'exit
12478 ;; Show heading or entry text
12479 (if (and heading-p (not entry-p))
12480 (org-flag-heading nil) ; only show the heading
12481 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12482 (org-show-hidden-entry))) ; show entire entry
12483 (when following-p
12484 ;; Show next sibling, or heading below text
12485 (save-excursion
12486 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12487 (org-flag-heading nil))))
12488 (when siblings-p (org-show-siblings))
12489 (when hierarchy-p
12490 ;; show all higher headings, possibly with siblings
12491 (save-excursion
12492 (while (and (condition-case nil
12493 (progn (org-up-heading-all 1) t)
12494 (error nil))
12495 (not (bobp)))
12496 (org-flag-heading nil)
12497 (when siblings-p (org-show-siblings))))))))
12499 (defvar org-reveal-start-hook nil
12500 "Hook run before revealing a location.")
12502 (defun org-reveal (&optional siblings)
12503 "Show current entry, hierarchy above it, and the following headline.
12504 This can be used to show a consistent set of context around locations
12505 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12506 not t for the search context.
12508 With optional argument SIBLINGS, on each level of the hierarchy all
12509 siblings are shown. This repairs the tree structure to what it would
12510 look like when opened with hierarchical calls to `org-cycle'.
12511 With double optional argument \\[universal-argument] \\[universal-argument], \
12512 go to the parent and show the
12513 entire tree."
12514 (interactive "P")
12515 (run-hooks 'org-reveal-start-hook)
12516 (let ((org-show-hierarchy-above t)
12517 (org-show-following-heading t)
12518 (org-show-siblings (if siblings t org-show-siblings)))
12519 (org-show-context nil))
12520 (when (equal siblings '(16))
12521 (save-excursion
12522 (when (org-up-heading-safe)
12523 (org-show-subtree)
12524 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12526 (defun org-highlight-new-match (beg end)
12527 "Highlight from BEG to END and mark the highlight is an occur headline."
12528 (let ((ov (make-overlay beg end)))
12529 (overlay-put ov 'face 'secondary-selection)
12530 (overlay-put ov 'org-type 'org-occur)
12531 (push ov org-occur-highlights)))
12533 (defun org-remove-occur-highlights (&optional beg end noremove)
12534 "Remove the occur highlights from the buffer.
12535 BEG and END are ignored. If NOREMOVE is nil, remove this function
12536 from the `before-change-functions' in the current buffer."
12537 (interactive)
12538 (unless org-inhibit-highlight-removal
12539 (mapc 'delete-overlay org-occur-highlights)
12540 (setq org-occur-highlights nil)
12541 (setq org-occur-parameters nil)
12542 (unless noremove
12543 (remove-hook 'before-change-functions
12544 'org-remove-occur-highlights 'local))))
12546 ;;;; Priorities
12548 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12549 "Regular expression matching the priority indicator.")
12551 (defvar org-remove-priority-next-time nil)
12553 (defun org-priority-up ()
12554 "Increase the priority of the current item."
12555 (interactive)
12556 (org-priority 'up))
12558 (defun org-priority-down ()
12559 "Decrease the priority of the current item."
12560 (interactive)
12561 (org-priority 'down))
12563 (defun org-priority (&optional action)
12564 "Change the priority of an item by ARG.
12565 ACTION can be `set', `up', `down', or a character."
12566 (interactive)
12567 (unless org-enable-priority-commands
12568 (error "Priority commands are disabled"))
12569 (setq action (or action 'set))
12570 (let (current new news have remove)
12571 (save-excursion
12572 (org-back-to-heading t)
12573 (if (looking-at org-priority-regexp)
12574 (setq current (string-to-char (match-string 2))
12575 have t))
12576 (cond
12577 ((eq action 'remove)
12578 (setq remove t new ?\ ))
12579 ((or (eq action 'set)
12580 (if (featurep 'xemacs) (characterp action) (integerp action)))
12581 (if (not (eq action 'set))
12582 (setq new action)
12583 (message "Priority %c-%c, SPC to remove: "
12584 org-highest-priority org-lowest-priority)
12585 (save-match-data
12586 (setq new (read-char-exclusive))))
12587 (if (and (= (upcase org-highest-priority) org-highest-priority)
12588 (= (upcase org-lowest-priority) org-lowest-priority))
12589 (setq new (upcase new)))
12590 (cond ((equal new ?\ ) (setq remove t))
12591 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12592 (error "Priority must be between `%c' and `%c'"
12593 org-highest-priority org-lowest-priority))))
12594 ((eq action 'up)
12595 (setq new (if have
12596 (1- current) ; normal cycling
12597 ;; last priority was empty
12598 (if (eq last-command this-command)
12599 org-lowest-priority ; wrap around empty to lowest
12600 ;; default
12601 (if org-priority-start-cycle-with-default
12602 org-default-priority
12603 (1- org-default-priority))))))
12604 ((eq action 'down)
12605 (setq new (if have
12606 (1+ current) ; normal cycling
12607 ;; last priority was empty
12608 (if (eq last-command this-command)
12609 org-highest-priority ; wrap around empty to highest
12610 ;; default
12611 (if org-priority-start-cycle-with-default
12612 org-default-priority
12613 (1+ org-default-priority))))))
12614 (t (error "Invalid action")))
12615 (if (or (< (upcase new) org-highest-priority)
12616 (> (upcase new) org-lowest-priority))
12617 (if (and (memq action '(up down))
12618 (not have) (not (eq last-command this-command)))
12619 ;; `new' is from default priority
12620 (error
12621 "The default can not be set, see `org-default-priority' why")
12622 ;; normal cycling: `new' is beyond highest/lowest priority
12623 ;; and is wrapped around to the empty priority
12624 (setq remove t)))
12625 (setq news (format "%c" new))
12626 (if have
12627 (if remove
12628 (replace-match "" t t nil 1)
12629 (replace-match news t t nil 2))
12630 (if remove
12631 (error "No priority cookie found in line")
12632 (let ((case-fold-search nil))
12633 (looking-at org-todo-line-regexp))
12634 (if (match-end 2)
12635 (progn
12636 (goto-char (match-end 2))
12637 (insert " [#" news "]"))
12638 (goto-char (match-beginning 3))
12639 (insert "[#" news "] "))))
12640 (org-preserve-lc (org-set-tags nil 'align)))
12641 (if remove
12642 (message "Priority removed")
12643 (message "Priority of current item set to %s" news))))
12645 (defun org-get-priority (s)
12646 "Find priority cookie and return priority."
12647 (if (functionp org-get-priority-function)
12648 (funcall org-get-priority-function)
12649 (save-match-data
12650 (if (not (string-match org-priority-regexp s))
12651 (* 1000 (- org-lowest-priority org-default-priority))
12652 (* 1000 (- org-lowest-priority
12653 (string-to-char (match-string 2 s))))))))
12655 ;;;; Tags
12657 (defvar org-agenda-archives-mode)
12658 (defvar org-map-continue-from nil
12659 "Position from where mapping should continue.
12660 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
12662 (defvar org-scanner-tags nil
12663 "The current tag list while the tags scanner is running.")
12664 (defvar org-trust-scanner-tags nil
12665 "Should `org-get-tags-at' use the tags for the scanner.
12666 This is for internal dynamical scoping only.
12667 When this is non-nil, the function `org-get-tags-at' will return the value
12668 of `org-scanner-tags' instead of building the list by itself. This
12669 can lead to large speed-ups when the tags scanner is used in a file with
12670 many entries, and when the list of tags is retrieved, for example to
12671 obtain a list of properties. Building the tags list for each entry in such
12672 a file becomes an N^2 operation - but with this variable set, it scales
12673 as N.")
12675 (defun org-scan-tags (action matcher &optional todo-only)
12676 "Scan headline tags with inheritance and produce output ACTION.
12678 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12679 or `agenda' to produce an entry list for an agenda view. It can also be
12680 a Lisp form or a function that should be called at each matched headline, in
12681 this case the return value is a list of all return values from these calls.
12683 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12684 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12685 only lines with a TODO keyword are included in the output."
12686 (require 'org-agenda)
12687 (let* ((re (concat "^" org-outline-regexp " *\\(\\<\\("
12688 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12689 (org-re
12690 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
12691 (props (list 'face 'default
12692 'done-face 'org-agenda-done
12693 'undone-face 'default
12694 'mouse-face 'highlight
12695 'org-not-done-regexp org-not-done-regexp
12696 'org-todo-regexp org-todo-regexp
12697 'help-echo
12698 (format "mouse-2 or RET jump to org file %s"
12699 (abbreviate-file-name
12700 (or (buffer-file-name (buffer-base-buffer))
12701 (buffer-name (buffer-base-buffer)))))))
12702 (case-fold-search nil)
12703 (org-map-continue-from nil)
12704 lspos tags tags-list
12705 (tags-alist (list (cons 0 org-file-tags)))
12706 (llast 0) rtn rtn1 level category i txt
12707 todo marker entry priority)
12708 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12709 (setq action (list 'lambda nil action)))
12710 (save-excursion
12711 (goto-char (point-min))
12712 (when (eq action 'sparse-tree)
12713 (org-overview)
12714 (org-remove-occur-highlights))
12715 (while (re-search-forward re nil t)
12716 (catch :skip
12717 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12718 tags (if (match-end 4) (org-match-string-no-properties 4)))
12719 (goto-char (setq lspos (match-beginning 0)))
12720 (setq level (org-reduced-level (funcall outline-level))
12721 category (org-get-category))
12722 (setq i llast llast level)
12723 ;; remove tag lists from same and sublevels
12724 (while (>= i level)
12725 (when (setq entry (assoc i tags-alist))
12726 (setq tags-alist (delete entry tags-alist)))
12727 (setq i (1- i)))
12728 ;; add the next tags
12729 (when tags
12730 (setq tags (org-split-string tags ":")
12731 tags-alist
12732 (cons (cons level tags) tags-alist)))
12733 ;; compile tags for current headline
12734 (setq tags-list
12735 (if org-use-tag-inheritance
12736 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12737 tags)
12738 org-scanner-tags tags-list)
12739 (when org-use-tag-inheritance
12740 (setcdr (car tags-alist)
12741 (mapcar (lambda (x)
12742 (setq x (copy-sequence x))
12743 (org-add-prop-inherited x))
12744 (cdar tags-alist))))
12745 (when (and tags org-use-tag-inheritance
12746 (or (not (eq t org-use-tag-inheritance))
12747 org-tags-exclude-from-inheritance))
12748 ;; selective inheritance, remove uninherited ones
12749 (setcdr (car tags-alist)
12750 (org-remove-uninherited-tags (cdar tags-alist))))
12751 (when (and
12753 ;; eval matcher only when the todo condition is OK
12754 (and (or (not todo-only) (member todo org-not-done-keywords))
12755 (let ((case-fold-search t)) (eval matcher)))
12757 ;; Call the skipper, but return t if it does not skip,
12758 ;; so that the `and' form continues evaluating
12759 (progn
12760 (unless (eq action 'sparse-tree) (org-agenda-skip))
12763 ;; Check if timestamps are deselecting this entry
12764 (or (not todo-only)
12765 (and (member todo org-not-done-keywords)
12766 (or (not org-agenda-tags-todo-honor-ignore-options)
12767 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
12769 ;; Extra check for the archive tag
12770 ;; FIXME: Does the skipper already do this????
12772 (not (member org-archive-tag tags-list))
12773 ;; we have an archive tag, should we use this anyway?
12774 (or (not org-agenda-skip-archived-trees)
12775 (and (eq action 'agenda) org-agenda-archives-mode))))
12777 ;; select this headline
12779 (cond
12780 ((eq action 'sparse-tree)
12781 (and org-highlight-sparse-tree-matches
12782 (org-get-heading) (match-end 0)
12783 (org-highlight-new-match
12784 (match-beginning 0) (match-beginning 1)))
12785 (org-show-context 'tags-tree))
12786 ((eq action 'agenda)
12787 (setq txt (org-agenda-format-item
12789 (concat
12790 (if (eq org-tags-match-list-sublevels 'indented)
12791 (make-string (1- level) ?.) "")
12792 (org-get-heading))
12793 category
12794 tags-list
12796 priority (org-get-priority txt))
12797 (goto-char lspos)
12798 (setq marker (org-agenda-new-marker))
12799 (org-add-props txt props
12800 'org-marker marker 'org-hd-marker marker 'org-category category
12801 'todo-state todo
12802 'priority priority 'type "tagsmatch")
12803 (push txt rtn))
12804 ((functionp action)
12805 (setq org-map-continue-from nil)
12806 (save-excursion
12807 (setq rtn1 (funcall action))
12808 (push rtn1 rtn)))
12809 (t (error "Invalid action")))
12811 ;; if we are to skip sublevels, jump to end of subtree
12812 (unless org-tags-match-list-sublevels
12813 (org-end-of-subtree t)
12814 (backward-char 1))))
12815 ;; Get the correct position from where to continue
12816 (if org-map-continue-from
12817 (goto-char org-map-continue-from)
12818 (and (= (point) lspos) (end-of-line 1)))))
12819 (when (and (eq action 'sparse-tree)
12820 (not org-sparse-tree-open-archived-trees))
12821 (org-hide-archived-subtrees (point-min) (point-max)))
12822 (nreverse rtn)))
12824 (defun org-remove-uninherited-tags (tags)
12825 "Remove all tags that are not inherited from the list TAGS."
12826 (cond
12827 ((eq org-use-tag-inheritance t)
12828 (if org-tags-exclude-from-inheritance
12829 (org-delete-all org-tags-exclude-from-inheritance tags)
12830 tags))
12831 ((not org-use-tag-inheritance) nil)
12832 ((stringp org-use-tag-inheritance)
12833 (delq nil (mapcar
12834 (lambda (x)
12835 (if (and (string-match org-use-tag-inheritance x)
12836 (not (member x org-tags-exclude-from-inheritance)))
12837 x nil))
12838 tags)))
12839 ((listp org-use-tag-inheritance)
12840 (delq nil (mapcar
12841 (lambda (x)
12842 (if (member x org-use-tag-inheritance) x nil))
12843 tags)))))
12845 (defvar todo-only) ;; dynamically scoped
12847 (defun org-match-sparse-tree (&optional todo-only match)
12848 "Create a sparse tree according to tags string MATCH.
12849 MATCH can contain positive and negative selection of tags, like
12850 \"+WORK+URGENT-WITHBOSS\".
12851 If optional argument TODO-ONLY is non-nil, only select lines that are
12852 also TODO lines."
12853 (interactive "P")
12854 (org-prepare-agenda-buffers (list (current-buffer)))
12855 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
12857 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
12859 (defvar org-cached-props nil)
12860 (defun org-cached-entry-get (pom property)
12861 (if (or (eq t org-use-property-inheritance)
12862 (and (stringp org-use-property-inheritance)
12863 (string-match org-use-property-inheritance property))
12864 (and (listp org-use-property-inheritance)
12865 (member property org-use-property-inheritance)))
12866 ;; Caching is not possible, check it directly
12867 (org-entry-get pom property 'inherit)
12868 ;; Get all properties, so that we can do complicated checks easily
12869 (cdr (assoc property (or org-cached-props
12870 (setq org-cached-props
12871 (org-entry-properties pom)))))))
12873 (defun org-global-tags-completion-table (&optional files)
12874 "Return the list of all tags in all agenda buffer/files.
12875 Optional FILES argument is a list of files to which can be used
12876 instead of the agenda files."
12877 (save-excursion
12878 (org-uniquify
12879 (delq nil
12880 (apply 'append
12881 (mapcar
12882 (lambda (file)
12883 (set-buffer (find-file-noselect file))
12884 (append (org-get-buffer-tags)
12885 (mapcar (lambda (x) (if (stringp (car-safe x))
12886 (list (car-safe x)) nil))
12887 org-tag-alist)))
12888 (if (and files (car files))
12889 files
12890 (org-agenda-files))))))))
12892 (defun org-make-tags-matcher (match)
12893 "Create the TAGS/TODO matcher form for the selection string MATCH."
12894 ;; todo-only is scoped dynamically into this function, and the function
12895 ;; may change it if the matcher asks for it.
12896 (unless match
12897 ;; Get a new match request, with completion
12898 (let ((org-last-tags-completion-table
12899 (org-global-tags-completion-table)))
12900 (setq match (org-completing-read-no-i
12901 "Match: " 'org-tags-completion-function nil nil nil
12902 'org-tags-history))))
12904 ;; Parse the string and create a lisp form
12905 (let ((match0 match)
12906 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
12907 minus tag mm
12908 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
12909 orterms term orlist re-p str-p level-p level-op time-p
12910 prop-p pn pv po gv rest)
12911 (if (string-match "/+" match)
12912 ;; match contains also a todo-matching request
12913 (progn
12914 (setq tagsmatch (substring match 0 (match-beginning 0))
12915 todomatch (substring match (match-end 0)))
12916 (if (string-match "^!" todomatch)
12917 (setq todo-only t todomatch (substring todomatch 1)))
12918 (if (string-match "^\\s-*$" todomatch)
12919 (setq todomatch nil)))
12920 ;; only matching tags
12921 (setq tagsmatch match todomatch nil))
12923 ;; Make the tags matcher
12924 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
12925 (setq tagsmatcher t)
12926 (setq orterms (org-split-string tagsmatch "|") orlist nil)
12927 (while (setq term (pop orterms))
12928 (while (and (equal (substring term -1) "\\") orterms)
12929 (setq term (concat term "|" (pop orterms)))) ; repair bad split
12930 (while (string-match re term)
12931 (setq rest (substring term (match-end 0))
12932 minus (and (match-end 1)
12933 (equal (match-string 1 term) "-"))
12934 tag (save-match-data (replace-regexp-in-string
12935 "\\\\-" "-"
12936 (match-string 2 term)))
12937 re-p (equal (string-to-char tag) ?{)
12938 level-p (match-end 4)
12939 prop-p (match-end 5)
12940 mm (cond
12941 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
12942 (level-p
12943 (setq level-op (org-op-to-function (match-string 3 term)))
12944 `(,level-op level ,(string-to-number
12945 (match-string 4 term))))
12946 (prop-p
12947 (setq pn (match-string 5 term)
12948 po (match-string 6 term)
12949 pv (match-string 7 term)
12950 re-p (equal (string-to-char pv) ?{)
12951 str-p (equal (string-to-char pv) ?\")
12952 time-p (save-match-data
12953 (string-match "^\"[[<].*[]>]\"$" pv))
12954 pv (if (or re-p str-p) (substring pv 1 -1) pv))
12955 (if time-p (setq pv (org-matcher-time pv)))
12956 (setq po (org-op-to-function po (if time-p 'time str-p)))
12957 (cond
12958 ((equal pn "CATEGORY")
12959 (setq gv '(get-text-property (point) 'org-category)))
12960 ((equal pn "TODO")
12961 (setq gv 'todo))
12963 (setq gv `(org-cached-entry-get nil ,pn))))
12964 (if re-p
12965 (if (eq po 'org<>)
12966 `(not (string-match ,pv (or ,gv "")))
12967 `(string-match ,pv (or ,gv "")))
12968 (if str-p
12969 `(,po (or ,gv "") ,pv)
12970 `(,po (string-to-number (or ,gv ""))
12971 ,(string-to-number pv) ))))
12972 (t `(member ,tag tags-list)))
12973 mm (if minus (list 'not mm) mm)
12974 term rest)
12975 (push mm tagsmatcher))
12976 (push (if (> (length tagsmatcher) 1)
12977 (cons 'and tagsmatcher)
12978 (car tagsmatcher))
12979 orlist)
12980 (setq tagsmatcher nil))
12981 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
12982 (setq tagsmatcher
12983 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
12984 ;; Make the todo matcher
12985 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
12986 (setq todomatcher t)
12987 (setq orterms (org-split-string todomatch "|") orlist nil)
12988 (while (setq term (pop orterms))
12989 (while (string-match re term)
12990 (setq minus (and (match-end 1)
12991 (equal (match-string 1 term) "-"))
12992 kwd (match-string 2 term)
12993 re-p (equal (string-to-char kwd) ?{)
12994 term (substring term (match-end 0))
12995 mm (if re-p
12996 `(string-match ,(substring kwd 1 -1) todo)
12997 (list 'equal 'todo kwd))
12998 mm (if minus (list 'not mm) mm))
12999 (push mm todomatcher))
13000 (push (if (> (length todomatcher) 1)
13001 (cons 'and todomatcher)
13002 (car todomatcher))
13003 orlist)
13004 (setq todomatcher nil))
13005 (setq todomatcher (if (> (length orlist) 1)
13006 (cons 'or orlist) (car orlist))))
13008 ;; Return the string and lisp forms of the matcher
13009 (setq matcher (if todomatcher
13010 (list 'and tagsmatcher todomatcher)
13011 tagsmatcher))
13012 (cons match0 matcher)))
13014 (defun org-op-to-function (op &optional stringp)
13015 "Turn an operator into the appropriate function."
13016 (setq op
13017 (cond
13018 ((equal op "<" ) '(< string< org-time<))
13019 ((equal op ">" ) '(> org-string> org-time>))
13020 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13021 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13022 ((member op '("=" "==")) '(= string= org-time=))
13023 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13024 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13026 (defun org<> (a b) (not (= a b)))
13027 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13028 (defun org-string>= (a b) (not (string< a b)))
13029 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13030 (defun org-string<> (a b) (not (string= a b)))
13031 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13032 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13033 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13034 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13035 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13036 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13037 (defun org-2ft (s)
13038 "Convert S to a floating point time.
13039 If S is already a number, just return it. If it is a string, parse
13040 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13041 (cond
13042 ((numberp s) s)
13043 ((stringp s)
13044 (condition-case nil
13045 (float-time (apply 'encode-time (org-parse-time-string s)))
13046 (error 0.)))
13047 (t 0.)))
13049 (defun org-time-today ()
13050 "Time in seconds today at 0:00.
13051 Returns the float number of seconds since the beginning of the
13052 epoch to the beginning of today (00:00)."
13053 (float-time (apply 'encode-time
13054 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13056 (defun org-matcher-time (s)
13057 "Interpret a time comparison value."
13058 (save-match-data
13059 (cond
13060 ((string= s "<now>") (float-time))
13061 ((string= s "<today>") (org-time-today))
13062 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13063 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13064 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
13065 (+ (org-time-today)
13066 (* (string-to-number (match-string 1 s))
13067 (cdr (assoc (match-string 2 s)
13068 '(("d" . 86400.0) ("w" . 604800.0)
13069 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13070 (t (org-2ft s)))))
13072 (defun org-match-any-p (re list)
13073 "Does re match any element of list?"
13074 (setq list (mapcar (lambda (x) (string-match re x)) list))
13075 (delq nil list))
13077 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13078 (defvar org-tags-overlay (make-overlay 1 1))
13079 (org-detach-overlay org-tags-overlay)
13081 (defun org-get-local-tags-at (&optional pos)
13082 "Get a list of tags defined in the current headline."
13083 (org-get-tags-at pos 'local))
13085 (defun org-get-local-tags ()
13086 "Get a list of tags defined in the current headline."
13087 (org-get-tags-at nil 'local))
13089 (defun org-get-tags-at (&optional pos local)
13090 "Get a list of all headline tags applicable at POS.
13091 POS defaults to point. If tags are inherited, the list contains
13092 the targets in the same sequence as the headlines appear, i.e.
13093 the tags of the current headline come last.
13094 When LOCAL is non-nil, only return tags from the current headline,
13095 ignore inherited ones."
13096 (interactive)
13097 (if (and org-trust-scanner-tags
13098 (or (not pos) (equal pos (point)))
13099 (not local))
13100 org-scanner-tags
13101 (let (tags ltags lastpos parent)
13102 (save-excursion
13103 (save-restriction
13104 (widen)
13105 (goto-char (or pos (point)))
13106 (save-match-data
13107 (catch 'done
13108 (condition-case nil
13109 (progn
13110 (org-back-to-heading t)
13111 (while (not (equal lastpos (point)))
13112 (setq lastpos (point))
13113 (when (looking-at
13114 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13115 (setq ltags (org-split-string
13116 (org-match-string-no-properties 1) ":"))
13117 (when parent
13118 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13119 (setq tags (append
13120 (if parent
13121 (org-remove-uninherited-tags ltags)
13122 ltags)
13123 tags)))
13124 (or org-use-tag-inheritance (throw 'done t))
13125 (if local (throw 'done t))
13126 (or (org-up-heading-safe) (error nil))
13127 (setq parent t)))
13128 (error nil)))))
13129 (if local
13130 tags
13131 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13133 (defun org-add-prop-inherited (s)
13134 (add-text-properties 0 (length s) '(inherited t) s)
13137 (defun org-toggle-tag (tag &optional onoff)
13138 "Toggle the tag TAG for the current line.
13139 If ONOFF is `on' or `off', don't toggle but set to this state."
13140 (let (res current)
13141 (save-excursion
13142 (org-back-to-heading t)
13143 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13144 (point-at-eol) t)
13145 (progn
13146 (setq current (match-string 1))
13147 (replace-match ""))
13148 (setq current ""))
13149 (setq current (nreverse (org-split-string current ":")))
13150 (cond
13151 ((eq onoff 'on)
13152 (setq res t)
13153 (or (member tag current) (push tag current)))
13154 ((eq onoff 'off)
13155 (or (not (member tag current)) (setq current (delete tag current))))
13156 (t (if (member tag current)
13157 (setq current (delete tag current))
13158 (setq res t)
13159 (push tag current))))
13160 (end-of-line 1)
13161 (if current
13162 (progn
13163 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13164 (org-set-tags nil t))
13165 (delete-horizontal-space))
13166 (run-hooks 'org-after-tags-change-hook))
13167 res))
13169 (defun org-align-tags-here (to-col)
13170 ;; Assumes that this is a headline
13171 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13172 (beginning-of-line 1)
13173 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13174 (< pos (match-beginning 2)))
13175 (progn
13176 (setq tags-l (- (match-end 2) (match-beginning 2)))
13177 (goto-char (match-beginning 1))
13178 (insert " ")
13179 (delete-region (point) (1+ (match-beginning 2)))
13180 (setq ncol (max (current-column)
13181 (1+ col)
13182 (if (> to-col 0)
13183 to-col
13184 (- (abs to-col) tags-l))))
13185 (setq p (point))
13186 (insert (make-string (- ncol (current-column)) ?\ ))
13187 (setq ncol (current-column))
13188 (when indent-tabs-mode (tabify p (point-at-eol)))
13189 (org-move-to-column (min ncol col) t))
13190 (goto-char pos))))
13192 (defun org-set-tags-command (&optional arg just-align)
13193 "Call the set-tags command for the current entry."
13194 (interactive "P")
13195 (if (org-on-heading-p)
13196 (org-set-tags arg just-align)
13197 (save-excursion
13198 (org-back-to-heading t)
13199 (org-set-tags arg just-align))))
13201 (defun org-set-tags-to (data)
13202 "Set the tags of the current entry to DATA, replacing the current tags.
13203 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13204 If DATA is nil or the empty string, any tags will be removed."
13205 (interactive "sTags: ")
13206 (setq data
13207 (cond
13208 ((eq data nil) "")
13209 ((equal data "") "")
13210 ((stringp data)
13211 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13212 ":"))
13213 ((listp data)
13214 (concat ":" (mapconcat 'identity data ":") ":"))
13215 (t nil)))
13216 (when data
13217 (save-excursion
13218 (org-back-to-heading t)
13219 (when (looking-at org-complex-heading-regexp)
13220 (if (match-end 5)
13221 (progn
13222 (goto-char (match-beginning 5))
13223 (insert data)
13224 (delete-region (point) (point-at-eol))
13225 (org-set-tags nil 'align))
13226 (goto-char (point-at-eol))
13227 (insert " " data)
13228 (org-set-tags nil 'align)))
13229 (beginning-of-line 1)
13230 (if (looking-at ".*?\\([ \t]+\\)$")
13231 (delete-region (match-beginning 1) (match-end 1))))))
13233 (defun org-align-all-tags ()
13234 "Align the tags i all headings."
13235 (interactive)
13236 (save-excursion
13237 (or (ignore-errors (org-back-to-heading t))
13238 (outline-next-heading))
13239 (if (org-on-heading-p)
13240 (org-set-tags t)
13241 (message "No headings"))))
13243 (defvar org-indent-indentation-per-level)
13244 (defun org-set-tags (&optional arg just-align)
13245 "Set the tags for the current headline.
13246 With prefix ARG, realign all tags in headings in the current buffer."
13247 (interactive "P")
13248 (let* ((re org-outline-regexp-bol)
13249 (current (org-get-tags-string))
13250 (col (current-column))
13251 (org-setting-tags t)
13252 table current-tags inherited-tags ; computed below when needed
13253 tags p0 c0 c1 rpl di tc level)
13254 (if arg
13255 (save-excursion
13256 (goto-char (point-min))
13257 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13258 (while (re-search-forward re nil t)
13259 (org-set-tags nil t)
13260 (end-of-line 1)))
13261 (message "All tags realigned to column %d" org-tags-column))
13262 (if just-align
13263 (setq tags current)
13264 ;; Get a new set of tags from the user
13265 (save-excursion
13266 (setq table (append org-tag-persistent-alist
13267 (or org-tag-alist (org-get-buffer-tags))
13268 (and
13269 org-complete-tags-always-offer-all-agenda-tags
13270 (org-global-tags-completion-table
13271 (org-agenda-files))))
13272 org-last-tags-completion-table table
13273 current-tags (org-split-string current ":")
13274 inherited-tags (nreverse
13275 (nthcdr (length current-tags)
13276 (nreverse (org-get-tags-at))))
13277 tags
13278 (if (or (eq t org-use-fast-tag-selection)
13279 (and org-use-fast-tag-selection
13280 (delq nil (mapcar 'cdr table))))
13281 (org-fast-tag-selection
13282 current-tags inherited-tags table
13283 (if org-fast-tag-selection-include-todo
13284 org-todo-key-alist))
13285 (let ((org-add-colon-after-tag-completion t))
13286 (org-trim
13287 (org-icompleting-read "Tags: "
13288 'org-tags-completion-function
13289 nil nil current 'org-tags-history))))))
13290 (while (string-match "[-+&]+" tags)
13291 ;; No boolean logic, just a list
13292 (setq tags (replace-match ":" t t tags))))
13294 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13296 (if org-tags-sort-function
13297 (setq tags (mapconcat 'identity
13298 (sort (org-split-string
13299 tags (org-re "[^[:alnum:]_@#%]+"))
13300 org-tags-sort-function) ":")))
13302 (if (string-match "\\`[\t ]*\\'" tags)
13303 (setq tags "")
13304 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13305 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13307 ;; Insert new tags at the correct column
13308 (beginning-of-line 1)
13309 (setq level (or (and (looking-at org-outline-regexp)
13310 (- (match-end 0) (point) 1))
13312 (cond
13313 ((and (equal current "") (equal tags "")))
13314 ((re-search-forward
13315 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13316 (point-at-eol) t)
13317 (if (equal tags "")
13318 (setq rpl "")
13319 (goto-char (match-beginning 0))
13320 (setq c0 (current-column)
13321 ;; compute offset for the case of org-indent-mode active
13322 di (if org-indent-mode
13323 (* (1- org-indent-indentation-per-level) (1- level))
13325 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13326 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13327 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13328 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13329 (replace-match rpl t t)
13330 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13331 tags)
13332 (t (error "Tags alignment failed")))
13333 (org-move-to-column col)
13334 (unless just-align
13335 (run-hooks 'org-after-tags-change-hook)))))
13337 (defun org-change-tag-in-region (beg end tag off)
13338 "Add or remove TAG for each entry in the region.
13339 This works in the agenda, and also in an org-mode buffer."
13340 (interactive
13341 (list (region-beginning) (region-end)
13342 (let ((org-last-tags-completion-table
13343 (if (eq major-mode 'org-mode)
13344 (org-get-buffer-tags)
13345 (org-global-tags-completion-table))))
13346 (org-icompleting-read
13347 "Tag: " 'org-tags-completion-function nil nil nil
13348 'org-tags-history))
13349 (progn
13350 (message "[s]et or [r]emove? ")
13351 (equal (read-char-exclusive) ?r))))
13352 (if (fboundp 'deactivate-mark) (deactivate-mark))
13353 (let ((agendap (equal major-mode 'org-agenda-mode))
13354 l1 l2 m buf pos newhead (cnt 0))
13355 (goto-char end)
13356 (setq l2 (1- (org-current-line)))
13357 (goto-char beg)
13358 (setq l1 (org-current-line))
13359 (loop for l from l1 to l2 do
13360 (org-goto-line l)
13361 (setq m (get-text-property (point) 'org-hd-marker))
13362 (when (or (and (eq major-mode 'org-mode) (org-on-heading-p))
13363 (and agendap m))
13364 (setq buf (if agendap (marker-buffer m) (current-buffer))
13365 pos (if agendap m (point)))
13366 (with-current-buffer buf
13367 (save-excursion
13368 (save-restriction
13369 (goto-char pos)
13370 (setq cnt (1+ cnt))
13371 (org-toggle-tag tag (if off 'off 'on))
13372 (setq newhead (org-get-heading)))))
13373 (and agendap (org-agenda-change-all-lines newhead m))))
13374 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13376 (defun org-tags-completion-function (string predicate &optional flag)
13377 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13378 (confirm (lambda (x) (stringp (car x)))))
13379 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13380 (setq s1 (match-string 1 string)
13381 s2 (match-string 2 string))
13382 (setq s1 "" s2 string))
13383 (cond
13384 ((eq flag nil)
13385 ;; try completion
13386 (setq rtn (try-completion s2 ctable confirm))
13387 (if (stringp rtn)
13388 (setq rtn
13389 (concat s1 s2 (substring rtn (length s2))
13390 (if (and org-add-colon-after-tag-completion
13391 (assoc rtn ctable))
13392 ":" ""))))
13393 rtn)
13394 ((eq flag t)
13395 ;; all-completions
13396 (all-completions s2 ctable confirm)
13398 ((eq flag 'lambda)
13399 ;; exact match?
13400 (assoc s2 ctable)))
13403 (defun org-fast-tag-insert (kwd tags face &optional end)
13404 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13405 (insert (format "%-12s" (concat kwd ":"))
13406 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13407 (or end "")))
13409 (defun org-fast-tag-show-exit (flag)
13410 (save-excursion
13411 (org-goto-line 3)
13412 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13413 (replace-match ""))
13414 (when flag
13415 (end-of-line 1)
13416 (org-move-to-column (- (window-width) 19) t)
13417 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13419 (defun org-set-current-tags-overlay (current prefix)
13420 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13421 (if (featurep 'xemacs)
13422 (org-overlay-display org-tags-overlay (concat prefix s)
13423 'secondary-selection)
13424 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13425 (org-overlay-display org-tags-overlay (concat prefix s)))))
13427 (defvar org-last-tag-selection-key nil)
13428 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13429 "Fast tag selection with single keys.
13430 CURRENT is the current list of tags in the headline, INHERITED is the
13431 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13432 possibly with grouping information. TODO-TABLE is a similar table with
13433 TODO keywords, should these have keys assigned to them.
13434 If the keys are nil, a-z are automatically assigned.
13435 Returns the new tags string, or nil to not change the current settings."
13436 (let* ((fulltable (append table todo-table))
13437 (maxlen (apply 'max (mapcar
13438 (lambda (x)
13439 (if (stringp (car x)) (string-width (car x)) 0))
13440 fulltable)))
13441 (buf (current-buffer))
13442 (expert (eq org-fast-tag-selection-single-key 'expert))
13443 (buffer-tags nil)
13444 (fwidth (+ maxlen 3 1 3))
13445 (ncol (/ (- (window-width) 4) fwidth))
13446 (i-face 'org-done)
13447 (c-face 'org-todo)
13448 tg cnt e c char c1 c2 ntable tbl rtn
13449 ov-start ov-end ov-prefix
13450 (exit-after-next org-fast-tag-selection-single-key)
13451 (done-keywords org-done-keywords)
13452 groups ingroup)
13453 (save-excursion
13454 (beginning-of-line 1)
13455 (if (looking-at
13456 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13457 (setq ov-start (match-beginning 1)
13458 ov-end (match-end 1)
13459 ov-prefix "")
13460 (setq ov-start (1- (point-at-eol))
13461 ov-end (1+ ov-start))
13462 (skip-chars-forward "^\n\r")
13463 (setq ov-prefix
13464 (concat
13465 (buffer-substring (1- (point)) (point))
13466 (if (> (current-column) org-tags-column)
13468 (make-string (- org-tags-column (current-column)) ?\ ))))))
13469 (move-overlay org-tags-overlay ov-start ov-end)
13470 (save-window-excursion
13471 (if expert
13472 (set-buffer (get-buffer-create " *Org tags*"))
13473 (delete-other-windows)
13474 (split-window-vertically)
13475 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13476 (erase-buffer)
13477 (org-set-local 'org-done-keywords done-keywords)
13478 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13479 (org-fast-tag-insert "Current" current c-face "\n\n")
13480 (org-fast-tag-show-exit exit-after-next)
13481 (org-set-current-tags-overlay current ov-prefix)
13482 (setq tbl fulltable char ?a cnt 0)
13483 (while (setq e (pop tbl))
13484 (cond
13485 ((equal (car e) :startgroup)
13486 (push '() groups) (setq ingroup t)
13487 (when (not (= cnt 0))
13488 (setq cnt 0)
13489 (insert "\n"))
13490 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13491 ((equal (car e) :endgroup)
13492 (setq ingroup nil cnt 0)
13493 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13494 ((equal e '(:newline))
13495 (when (not (= cnt 0))
13496 (setq cnt 0)
13497 (insert "\n")
13498 (setq e (car tbl))
13499 (while (equal (car tbl) '(:newline))
13500 (insert "\n")
13501 (setq tbl (cdr tbl)))))
13503 (setq tg (copy-sequence (car e)) c2 nil)
13504 (if (cdr e)
13505 (setq c (cdr e))
13506 ;; automatically assign a character.
13507 (setq c1 (string-to-char
13508 (downcase (substring
13509 tg (if (= (string-to-char tg) ?@) 1 0)))))
13510 (if (or (rassoc c1 ntable) (rassoc c1 table))
13511 (while (or (rassoc char ntable) (rassoc char table))
13512 (setq char (1+ char)))
13513 (setq c2 c1))
13514 (setq c (or c2 char)))
13515 (if ingroup (push tg (car groups)))
13516 (setq tg (org-add-props tg nil 'face
13517 (cond
13518 ((not (assoc tg table))
13519 (org-get-todo-face tg))
13520 ((member tg current) c-face)
13521 ((member tg inherited) i-face)
13522 (t nil))))
13523 (if (and (= cnt 0) (not ingroup)) (insert " "))
13524 (insert "[" c "] " tg (make-string
13525 (- fwidth 4 (length tg)) ?\ ))
13526 (push (cons tg c) ntable)
13527 (when (= (setq cnt (1+ cnt)) ncol)
13528 (insert "\n")
13529 (if ingroup (insert " "))
13530 (setq cnt 0)))))
13531 (setq ntable (nreverse ntable))
13532 (insert "\n")
13533 (goto-char (point-min))
13534 (if (not expert) (org-fit-window-to-buffer))
13535 (setq rtn
13536 (catch 'exit
13537 (while t
13538 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13539 (if (not groups) "no " "")
13540 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13541 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13542 (setq org-last-tag-selection-key c)
13543 (cond
13544 ((= c ?\r) (throw 'exit t))
13545 ((= c ?!)
13546 (setq groups (not groups))
13547 (goto-char (point-min))
13548 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13549 ((= c ?\C-c)
13550 (if (not expert)
13551 (org-fast-tag-show-exit
13552 (setq exit-after-next (not exit-after-next)))
13553 (setq expert nil)
13554 (delete-other-windows)
13555 (set-window-buffer (split-window-vertically) " *Org tags*")
13556 (org-switch-to-buffer-other-window " *Org tags*")
13557 (org-fit-window-to-buffer)))
13558 ((or (= c ?\C-g)
13559 (and (= c ?q) (not (rassoc c ntable))))
13560 (org-detach-overlay org-tags-overlay)
13561 (setq quit-flag t))
13562 ((= c ?\ )
13563 (setq current nil)
13564 (if exit-after-next (setq exit-after-next 'now)))
13565 ((= c ?\t)
13566 (condition-case nil
13567 (setq tg (org-icompleting-read
13568 "Tag: "
13569 (or buffer-tags
13570 (with-current-buffer buf
13571 (org-get-buffer-tags)))))
13572 (quit (setq tg "")))
13573 (when (string-match "\\S-" tg)
13574 (add-to-list 'buffer-tags (list tg))
13575 (if (member tg current)
13576 (setq current (delete tg current))
13577 (push tg current)))
13578 (if exit-after-next (setq exit-after-next 'now)))
13579 ((setq e (rassoc c todo-table) tg (car e))
13580 (with-current-buffer buf
13581 (save-excursion (org-todo tg)))
13582 (if exit-after-next (setq exit-after-next 'now)))
13583 ((setq e (rassoc c ntable) tg (car e))
13584 (if (member tg current)
13585 (setq current (delete tg current))
13586 (loop for g in groups do
13587 (if (member tg g)
13588 (mapc (lambda (x)
13589 (setq current (delete x current)))
13590 g)))
13591 (push tg current))
13592 (if exit-after-next (setq exit-after-next 'now))))
13594 ;; Create a sorted list
13595 (setq current
13596 (sort current
13597 (lambda (a b)
13598 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13599 (if (eq exit-after-next 'now) (throw 'exit t))
13600 (goto-char (point-min))
13601 (beginning-of-line 2)
13602 (delete-region (point) (point-at-eol))
13603 (org-fast-tag-insert "Current" current c-face)
13604 (org-set-current-tags-overlay current ov-prefix)
13605 (while (re-search-forward
13606 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13607 (setq tg (match-string 1))
13608 (add-text-properties
13609 (match-beginning 1) (match-end 1)
13610 (list 'face
13611 (cond
13612 ((member tg current) c-face)
13613 ((member tg inherited) i-face)
13614 (t (get-text-property (match-beginning 1) 'face))))))
13615 (goto-char (point-min)))))
13616 (org-detach-overlay org-tags-overlay)
13617 (if rtn
13618 (mapconcat 'identity current ":")
13619 nil))))
13621 (defun org-get-tags-string ()
13622 "Get the TAGS string in the current headline."
13623 (unless (org-on-heading-p t)
13624 (error "Not on a heading"))
13625 (save-excursion
13626 (beginning-of-line 1)
13627 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13628 (org-match-string-no-properties 1)
13629 "")))
13631 (defun org-get-tags ()
13632 "Get the list of tags specified in the current headline."
13633 (org-split-string (org-get-tags-string) ":"))
13635 (defun org-get-buffer-tags ()
13636 "Get a table of all tags used in the buffer, for completion."
13637 (let (tags)
13638 (save-excursion
13639 (goto-char (point-min))
13640 (while (re-search-forward
13641 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13642 (when (equal (char-after (point-at-bol 0)) ?*)
13643 (mapc (lambda (x) (add-to-list 'tags x))
13644 (org-split-string (org-match-string-no-properties 1) ":")))))
13645 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13646 (mapcar 'list tags)))
13648 ;;;; The mapping API
13650 ;;;###autoload
13651 (defun org-map-entries (func &optional match scope &rest skip)
13652 "Call FUNC at each headline selected by MATCH in SCOPE.
13654 FUNC is a function or a lisp form. The function will be called without
13655 arguments, with the cursor positioned at the beginning of the headline.
13656 The return values of all calls to the function will be collected and
13657 returned as a list.
13659 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13660 does not need to preserve point. After evaluation, the cursor will be
13661 moved to the end of the line (presumably of the headline of the
13662 processed entry) and search continues from there. Under some
13663 circumstances, this may not produce the wanted results. For example,
13664 if you have removed (e.g. archived) the current (sub)tree it could
13665 mean that the next entry will be skipped entirely. In such cases, you
13666 can specify the position from where search should continue by making
13667 FUNC set the variable `org-map-continue-from' to the desired buffer
13668 position.
13670 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13671 Only headlines that are matched by this query will be considered during
13672 the iteration. When MATCH is nil or t, all headlines will be
13673 visited by the iteration.
13675 SCOPE determines the scope of this command. It can be any of:
13677 nil The current buffer, respecting the restriction if any
13678 tree The subtree started with the entry at point
13679 region The entries within the active region, if any
13680 file The current buffer, without restriction
13681 file-with-archives
13682 The current buffer, and any archives associated with it
13683 agenda All agenda files
13684 agenda-with-archives
13685 All agenda files with any archive files associated with them
13686 \(file1 file2 ...)
13687 If this is a list, all files in the list will be scanned
13689 The remaining args are treated as settings for the skipping facilities of
13690 the scanner. The following items can be given here:
13692 archive skip trees with the archive tag.
13693 comment skip trees with the COMMENT keyword
13694 function or Emacs Lisp form:
13695 will be used as value for `org-agenda-skip-function', so whenever
13696 the function returns t, FUNC will not be called for that
13697 entry and search will continue from the point where the
13698 function leaves it.
13700 If your function needs to retrieve the tags including inherited tags
13701 at the *current* entry, you can use the value of the variable
13702 `org-scanner-tags' which will be much faster than getting the value
13703 with `org-get-tags-at'. If your function gets properties with
13704 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13705 to t around the call to `org-entry-properties' to get the same speedup.
13706 Note that if your function moves around to retrieve tags and properties at
13707 a *different* entry, you cannot use these techniques."
13708 (unless (and (eq scope 'region) (not (org-region-active-p)))
13709 (let* ((org-agenda-archives-mode nil) ; just to make sure
13710 (org-agenda-skip-archived-trees (memq 'archive skip))
13711 (org-agenda-skip-comment-trees (memq 'comment skip))
13712 (org-agenda-skip-function
13713 (car (org-delete-all '(comment archive) skip)))
13714 (org-tags-match-list-sublevels t)
13715 matcher file res
13716 org-todo-keywords-for-agenda
13717 org-done-keywords-for-agenda
13718 org-todo-keyword-alist-for-agenda
13719 org-drawers-for-agenda
13720 org-tag-alist-for-agenda)
13722 (cond
13723 ((eq match t) (setq matcher t))
13724 ((eq match nil) (setq matcher t))
13725 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13727 (save-excursion
13728 (save-restriction
13729 (cond ((eq scope 'tree)
13730 (org-back-to-heading t)
13731 (org-narrow-to-subtree)
13732 (setq scope nil))
13733 ((and (eq scope 'region) (org-region-active-p))
13734 (narrow-to-region (region-beginning)
13735 (save-excursion
13736 (goto-char (region-end))
13737 (unless (and (bolp) (org-at-heading-p))
13738 (outline-next-heading))
13739 (point)))
13740 (setq scope nil)))
13742 (if (not scope)
13743 (progn
13744 (org-prepare-agenda-buffers
13745 (list (buffer-file-name (current-buffer))))
13746 (setq res (org-scan-tags func matcher)))
13747 ;; Get the right scope
13748 (cond
13749 ((and scope (listp scope) (symbolp (car scope)))
13750 (setq scope (eval scope)))
13751 ((eq scope 'agenda)
13752 (setq scope (org-agenda-files t)))
13753 ((eq scope 'agenda-with-archives)
13754 (setq scope (org-agenda-files t))
13755 (setq scope (org-add-archive-files scope)))
13756 ((eq scope 'file)
13757 (setq scope (list (buffer-file-name))))
13758 ((eq scope 'file-with-archives)
13759 (setq scope (org-add-archive-files (list (buffer-file-name))))))
13760 (org-prepare-agenda-buffers scope)
13761 (while (setq file (pop scope))
13762 (with-current-buffer (org-find-base-buffer-visiting file)
13763 (save-excursion
13764 (save-restriction
13765 (widen)
13766 (goto-char (point-min))
13767 (setq res (append res (org-scan-tags func matcher))))))))))
13768 res)))
13770 ;;;; Properties
13772 ;;; Setting and retrieving properties
13774 (defconst org-special-properties
13775 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
13776 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM")
13777 "The special properties valid in Org-mode.
13779 These are properties that are not defined in the property drawer,
13780 but in some other way.")
13782 (defconst org-default-properties
13783 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
13784 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
13785 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
13786 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
13787 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
13788 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
13789 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
13790 "Some properties that are used by Org-mode for various purposes.
13791 Being in this list makes sure that they are offered for completion.")
13793 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
13794 "Regular expression matching the first line of a property drawer.")
13796 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
13797 "Regular expression matching the last line of a property drawer.")
13799 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
13800 "Regular expression matching the first line of a property drawer.")
13802 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
13803 "Regular expression matching the first line of a property drawer.")
13805 (defconst org-property-drawer-re
13806 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
13807 org-property-end-re "\\)\n?")
13808 "Matches an entire property drawer.")
13810 (defconst org-clock-drawer-re
13811 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
13812 org-property-end-re "\\)\n?")
13813 "Matches an entire clock drawer.")
13815 (defsubst org-re-property (property)
13816 "Return a regexp matching PROPERTY.
13817 Match group 1 will be set to the value "
13818 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
13820 (defun org-property-action ()
13821 "Do an action on properties."
13822 (interactive)
13823 (let (c)
13824 (org-at-property-p)
13825 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
13826 (setq c (read-char-exclusive))
13827 (cond
13828 ((equal c ?s)
13829 (call-interactively 'org-set-property))
13830 ((equal c ?d)
13831 (call-interactively 'org-delete-property))
13832 ((equal c ?D)
13833 (call-interactively 'org-delete-property-globally))
13834 ((equal c ?c)
13835 (call-interactively 'org-compute-property-at-point))
13836 (t (error "No such property action %c" c)))))
13838 (defun org-set-effort (&optional value)
13839 "Set the effort property of the current entry.
13840 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
13841 allowed value."
13842 (interactive "P")
13843 (if (equal value 0) (setq value 10))
13844 (let* ((completion-ignore-case t)
13845 (prop org-effort-property)
13846 (cur (org-entry-get nil prop))
13847 (allowed (org-property-get-allowed-values nil prop 'table))
13848 (existing (mapcar 'list (org-property-values prop)))
13850 (val (cond
13851 ((stringp value) value)
13852 ((and allowed (integerp value))
13853 (or (car (nth (1- value) allowed))
13854 (car (org-last allowed))))
13855 (allowed
13856 (message "Select 1-9,0, [RET%s]: %s"
13857 (if cur (concat "=" cur) "")
13858 (mapconcat 'car allowed " "))
13859 (setq rpl (read-char-exclusive))
13860 (if (equal rpl ?\r)
13862 (setq rpl (- rpl ?0))
13863 (if (equal rpl 0) (setq rpl 10))
13864 (if (and (> rpl 0) (<= rpl (length allowed)))
13865 (car (nth (1- rpl) allowed))
13866 (org-completing-read "Effort: " allowed nil))))
13868 (let (org-completion-use-ido org-completion-use-iswitchb)
13869 (org-completing-read
13870 (concat "Effort " (if (and cur (string-match "\\S-" cur))
13871 (concat "[" cur "]") "")
13872 ": ")
13873 existing nil nil "" nil cur))))))
13874 (unless (equal (org-entry-get nil prop) val)
13875 (org-entry-put nil prop val))
13876 (message "%s is now %s" prop val)))
13878 (defun org-at-property-p ()
13879 "Is cursor inside a property drawer?"
13880 (save-excursion
13881 (beginning-of-line 1)
13882 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
13883 (save-match-data ;; Used by calling procedures
13884 (let ((p (point))
13885 (range (unless (org-before-first-heading-p)
13886 (org-get-property-block))))
13887 (and range (<= (car range) p) (< p (cdr range))))))))
13889 (defun org-get-property-block (&optional beg end force)
13890 "Return the (beg . end) range of the body of the property drawer.
13891 BEG and END can be beginning and end of subtree, if not given
13892 they will be found.
13893 If the drawer does not exist and FORCE is non-nil, create the drawer."
13894 (catch 'exit
13895 (save-excursion
13896 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
13897 (end (or end (progn (outline-next-heading) (point)))))
13898 (goto-char beg)
13899 (if (re-search-forward org-property-start-re end t)
13900 (setq beg (1+ (match-end 0)))
13901 (if force
13902 (save-excursion
13903 (org-insert-property-drawer)
13904 (setq end (progn (outline-next-heading) (point))))
13905 (throw 'exit nil))
13906 (goto-char beg)
13907 (if (re-search-forward org-property-start-re end t)
13908 (setq beg (1+ (match-end 0)))))
13909 (if (re-search-forward org-property-end-re end t)
13910 (setq end (match-beginning 0))
13911 (or force (throw 'exit nil))
13912 (goto-char beg)
13913 (setq end beg)
13914 (org-indent-line-function)
13915 (insert ":END:\n"))
13916 (cons beg end)))))
13918 (defun org-entry-properties (&optional pom which specific)
13919 "Get all properties of the entry at point-or-marker POM.
13920 This includes the TODO keyword, the tags, time strings for deadline,
13921 scheduled, and clocking, and any additional properties defined in the
13922 entry. The return value is an alist, keys may occur multiple times
13923 if the property key was used several times.
13924 POM may also be nil, in which case the current entry is used.
13925 If WHICH is nil or `all', get all properties. If WHICH is
13926 `special' or `standard', only get that subclass. If WHICH
13927 is a string only get exactly this property. SPECIFIC can be a string, the
13928 specific property we are interested in. Specifying it can speed
13929 things up because then unnecessary parsing is avoided."
13930 (setq which (or which 'all))
13931 (org-with-point-at pom
13932 (let ((clockstr (substring org-clock-string 0 -1))
13933 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
13934 (case-fold-search nil)
13935 beg end range props sum-props key key1 value string clocksum)
13936 (save-excursion
13937 (when (condition-case nil
13938 (and (eq major-mode 'org-mode) (org-back-to-heading t))
13939 (error nil))
13940 (setq beg (point))
13941 (setq sum-props (get-text-property (point) 'org-summaries))
13942 (setq clocksum (get-text-property (point) :org-clock-minutes))
13943 (outline-next-heading)
13944 (setq end (point))
13945 (when (memq which '(all special))
13946 ;; Get the special properties, like TODO and tags
13947 (goto-char beg)
13948 (when (and (or (not specific) (string= specific "TODO"))
13949 (looking-at org-todo-line-regexp) (match-end 2))
13950 (push (cons "TODO" (org-match-string-no-properties 2)) props))
13951 (when (and (or (not specific) (string= specific "PRIORITY"))
13952 (looking-at org-priority-regexp))
13953 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
13954 (when (or (not specific) (string= specific "FILE"))
13955 (push (cons "FILE" buffer-file-name) props))
13956 (when (and (or (not specific) (string= specific "TAGS"))
13957 (setq value (org-get-tags-string))
13958 (string-match "\\S-" value))
13959 (push (cons "TAGS" value) props))
13960 (when (and (or (not specific) (string= specific "ALLTAGS"))
13961 (setq value (org-get-tags-at)))
13962 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
13963 ":"))
13964 props))
13965 (when (or (not specific) (string= specific "BLOCKED"))
13966 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
13967 (when (or (not specific)
13968 (member specific
13969 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
13970 "TIMESTAMP" "TIMESTAMP_IA")))
13971 (catch 'match
13972 (while (re-search-forward org-maybe-keyword-time-regexp end t)
13973 (setq key (if (match-end 1)
13974 (substring (org-match-string-no-properties 1)
13975 0 -1))
13976 string (if (equal key clockstr)
13977 (org-no-properties
13978 (org-trim
13979 (buffer-substring
13980 (match-beginning 3) (goto-char
13981 (point-at-eol)))))
13982 (substring (org-match-string-no-properties 3)
13983 1 -1)))
13984 ;; Get the correct property name from the key. This is
13985 ;; necessary if the user has configured time keywords.
13986 (setq key1 (concat key ":"))
13987 (cond
13988 ((not key)
13989 (setq key
13990 (if (= (char-after (match-beginning 3)) ?\[)
13991 "TIMESTAMP_IA" "TIMESTAMP")))
13992 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
13993 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
13994 ((equal key1 org-closed-string) (setq key "CLOSED"))
13995 ((equal key1 org-clock-string) (setq key "CLOCK")))
13996 (if (and specific (equal key specific) (not (equal key "CLOCK")))
13997 (progn
13998 (push (cons key string) props)
13999 ;; no need to search further if match is found
14000 (throw 'match t))
14001 (when (or (equal key "CLOCK") (not (assoc key props)))
14002 (push (cons key string) props))))))
14005 (when (memq which '(all standard))
14006 ;; Get the standard properties, like :PROP: ...
14007 (setq range (org-get-property-block beg end))
14008 (when range
14009 (goto-char (car range))
14010 (while (re-search-forward
14011 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14012 (cdr range) t)
14013 (setq key (org-match-string-no-properties 1)
14014 value (org-trim (or (org-match-string-no-properties 2) "")))
14015 (unless (member key excluded)
14016 (push (cons key (or value "")) props)))))
14017 (if clocksum
14018 (push (cons "CLOCKSUM"
14019 (org-columns-number-to-string (/ (float clocksum) 60.)
14020 'add_times))
14021 props))
14022 (unless (assoc "CATEGORY" props)
14023 (push (cons "CATEGORY" (org-get-category)) props))
14024 (append sum-props (nreverse props)))))))
14026 (defun org-entry-get (pom property &optional inherit literal-nil)
14027 "Get value of PROPERTY for entry at point-or-marker POM.
14028 If INHERIT is non-nil and the entry does not have the property,
14029 then also check higher levels of the hierarchy.
14030 If INHERIT is the symbol `selective', use inheritance only if the setting
14031 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14032 If the property is present but empty, the return value is the empty string.
14033 If the property is not present at all, nil is returned.
14035 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14036 do not interpret it as the list atom nil. This is used for inheritance
14037 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14038 (org-with-point-at pom
14039 (if (and inherit (if (eq inherit 'selective)
14040 (org-property-inherit-p property)
14042 (org-entry-get-with-inheritance property literal-nil)
14043 (if (member property org-special-properties)
14044 ;; We need a special property. Use `org-entry-properties' to
14045 ;; retrieve it, but specify the wanted property
14046 (cdr (assoc property (org-entry-properties nil 'special property)))
14047 (let ((range (unless (org-before-first-heading-p)
14048 (org-get-property-block))))
14049 (if (and range
14050 (goto-char (car range))
14051 (re-search-forward
14052 (org-re-property property)
14053 (cdr range) t))
14054 ;; Found the property, return it.
14055 (if (match-end 1)
14056 (if literal-nil
14057 (org-match-string-no-properties 1)
14058 (org-not-nil (org-match-string-no-properties 1)))
14059 "")))))))
14061 (defun org-property-or-variable-value (var &optional inherit)
14062 "Check if there is a property fixing the value of VAR.
14063 If yes, return this value. If not, return the current value of the variable."
14064 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14065 (if (and prop (stringp prop) (string-match "\\S-" prop))
14066 (read prop)
14067 (symbol-value var))))
14069 (defun org-entry-delete (pom property)
14070 "Delete the property PROPERTY from entry at point-or-marker POM."
14071 (org-with-point-at pom
14072 (if (member property org-special-properties)
14073 nil ; cannot delete these properties.
14074 (let ((range (org-get-property-block)))
14075 (if (and range
14076 (goto-char (car range))
14077 (re-search-forward
14078 (org-re-property property)
14079 (cdr range) t))
14080 (progn
14081 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14083 nil)))))
14085 ;; Multi-values properties are properties that contain multiple values
14086 ;; These values are assumed to be single words, separated by whitespace.
14087 (defun org-entry-add-to-multivalued-property (pom property value)
14088 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14089 (let* ((old (org-entry-get pom property))
14090 (values (and old (org-split-string old "[ \t]"))))
14091 (setq value (org-entry-protect-space value))
14092 (unless (member value values)
14093 (setq values (cons value values))
14094 (org-entry-put pom property
14095 (mapconcat 'identity values " ")))))
14097 (defun org-entry-remove-from-multivalued-property (pom property value)
14098 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14099 (let* ((old (org-entry-get pom property))
14100 (values (and old (org-split-string old "[ \t]"))))
14101 (setq value (org-entry-protect-space value))
14102 (when (member value values)
14103 (setq values (delete value values))
14104 (org-entry-put pom property
14105 (mapconcat 'identity values " ")))))
14107 (defun org-entry-member-in-multivalued-property (pom property value)
14108 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14109 (let* ((old (org-entry-get pom property))
14110 (values (and old (org-split-string old "[ \t]"))))
14111 (setq value (org-entry-protect-space value))
14112 (member value values)))
14114 (defun org-entry-get-multivalued-property (pom property)
14115 "Return a list of values in a multivalued property."
14116 (let* ((value (org-entry-get pom property))
14117 (values (and value (org-split-string value "[ \t]"))))
14118 (mapcar 'org-entry-restore-space values)))
14120 (defun org-entry-put-multivalued-property (pom property &rest values)
14121 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14122 VALUES should be a list of strings. Spaces will be protected."
14123 (org-entry-put pom property
14124 (mapconcat 'org-entry-protect-space values " "))
14125 (let* ((value (org-entry-get pom property))
14126 (values (and value (org-split-string value "[ \t]"))))
14127 (mapcar 'org-entry-restore-space values)))
14129 (defun org-entry-protect-space (s)
14130 "Protect spaces and newline in string S."
14131 (while (string-match " " s)
14132 (setq s (replace-match "%20" t t s)))
14133 (while (string-match "\n" s)
14134 (setq s (replace-match "%0A" t t s)))
14137 (defun org-entry-restore-space (s)
14138 "Restore spaces and newline in string S."
14139 (while (string-match "%20" s)
14140 (setq s (replace-match " " t t s)))
14141 (while (string-match "%0A" s)
14142 (setq s (replace-match "\n" t t s)))
14145 (defvar org-entry-property-inherited-from (make-marker)
14146 "Marker pointing to the entry from where a property was inherited.
14147 Each call to `org-entry-get-with-inheritance' will set this marker to the
14148 location of the entry where the inheritance search matched. If there was
14149 no match, the marker will point nowhere.
14150 Note that also `org-entry-get' calls this function, if the INHERIT flag
14151 is set.")
14153 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14154 "Get entry property, and search higher levels if not present.
14155 The search will stop at the first ancestor which has the property defined.
14156 If the value found is \"nil\", return nil to show that the property
14157 should be considered as undefined (this is the meaning of nil here).
14158 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14159 (move-marker org-entry-property-inherited-from nil)
14160 (let (tmp)
14161 (unless (org-before-first-heading-p)
14162 (save-excursion
14163 (save-restriction
14164 (widen)
14165 (catch 'ex
14166 (while t
14167 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14168 (org-back-to-heading t)
14169 (move-marker org-entry-property-inherited-from (point))
14170 (throw 'ex tmp))
14171 (or (org-up-heading-safe) (throw 'ex nil)))))))
14172 (setq tmp (or tmp
14173 (cdr (assoc property org-file-properties))
14174 (cdr (assoc property org-global-properties))
14175 (cdr (assoc property org-global-properties-fixed))))
14176 (if literal-nil tmp (org-not-nil tmp))))
14178 (defvar org-property-changed-functions nil
14179 "Hook called when the value of a property has changed.
14180 Each hook function should accept two arguments, the name of the property
14181 and the new value.")
14183 (defun org-entry-put (pom property value)
14184 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14185 (org-with-point-at pom
14186 (org-back-to-heading t)
14187 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14188 range)
14189 (cond
14190 ((equal property "TODO")
14191 (when (and (stringp value) (string-match "\\S-" value)
14192 (not (member value org-todo-keywords-1)))
14193 (error "\"%s\" is not a valid TODO state" value))
14194 (if (or (not value)
14195 (not (string-match "\\S-" value)))
14196 (setq value 'none))
14197 (org-todo value)
14198 (org-set-tags nil 'align))
14199 ((equal property "PRIORITY")
14200 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14201 (string-to-char value) ?\ ))
14202 (org-set-tags nil 'align))
14203 ((equal property "SCHEDULED")
14204 (if (re-search-forward org-scheduled-time-regexp end t)
14205 (cond
14206 ((eq value 'earlier) (org-timestamp-change -1 'day))
14207 ((eq value 'later) (org-timestamp-change 1 'day))
14208 (t (call-interactively 'org-schedule)))
14209 (call-interactively 'org-schedule)))
14210 ((equal property "DEADLINE")
14211 (if (re-search-forward org-deadline-time-regexp end t)
14212 (cond
14213 ((eq value 'earlier) (org-timestamp-change -1 'day))
14214 ((eq value 'later) (org-timestamp-change 1 'day))
14215 (t (call-interactively 'org-deadline)))
14216 (call-interactively 'org-deadline)))
14217 ((member property org-special-properties)
14218 (error "The %s property can not yet be set with `org-entry-put'"
14219 property))
14220 (t ; a non-special property
14221 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14222 (setq range (org-get-property-block beg end 'force))
14223 (goto-char (car range))
14224 (if (re-search-forward
14225 (org-re-property property) (cdr range) t)
14226 (progn
14227 (delete-region (match-beginning 0) (match-end 0))
14228 (goto-char (match-beginning 0)))
14229 (goto-char (cdr range))
14230 (insert "\n")
14231 (backward-char 1)
14232 (org-indent-line-function))
14233 (insert ":" property ":")
14234 (and value (insert " " value))
14235 (org-indent-line-function)))))
14236 (run-hook-with-args 'org-property-changed-functions property value)))
14238 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14239 "Get all property keys in the current buffer.
14240 With INCLUDE-SPECIALS, also list the special properties that reflect things
14241 like tags and TODO state.
14242 With INCLUDE-DEFAULTS, also include properties that has special meaning
14243 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14244 and others.
14245 With INCLUDE-COLUMNS, also include property names given in COLUMN
14246 formats in the current buffer."
14247 (let (rtn range cfmt s p)
14248 (save-excursion
14249 (save-restriction
14250 (widen)
14251 (goto-char (point-min))
14252 (while (re-search-forward org-property-start-re nil t)
14253 (setq range (org-get-property-block))
14254 (goto-char (car range))
14255 (while (re-search-forward
14256 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14257 (cdr range) t)
14258 (add-to-list 'rtn (org-match-string-no-properties 1)))
14259 (outline-next-heading))))
14261 (when include-specials
14262 (setq rtn (append org-special-properties rtn)))
14264 (when include-defaults
14265 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14266 (add-to-list 'rtn org-effort-property))
14268 (when include-columns
14269 (save-excursion
14270 (save-restriction
14271 (widen)
14272 (goto-char (point-min))
14273 (while (re-search-forward
14274 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14275 nil t)
14276 (setq cfmt (match-string 2) s 0)
14277 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14278 cfmt s)
14279 (setq s (match-end 0)
14280 p (match-string 1 cfmt))
14281 (unless (or (equal p "ITEM")
14282 (member p org-special-properties))
14283 (add-to-list 'rtn (match-string 1 cfmt))))))))
14285 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14287 (defun org-property-values (key)
14288 "Return a list of all values of property KEY in the current buffer."
14289 (save-excursion
14290 (save-restriction
14291 (widen)
14292 (goto-char (point-min))
14293 (let ((re (org-re-property key))
14294 values)
14295 (while (re-search-forward re nil t)
14296 (add-to-list 'values (org-trim (match-string 1))))
14297 (delete "" values)))))
14299 (defun org-insert-property-drawer ()
14300 "Insert a property drawer into the current entry."
14301 (interactive)
14302 (org-back-to-heading t)
14303 (looking-at org-outline-regexp)
14304 (let ((indent (if org-adapt-indentation
14305 (- (match-end 0)(match-beginning 0))
14307 (beg (point))
14308 (re (concat "^[ \t]*" org-keyword-time-regexp))
14309 end hiddenp)
14310 (outline-next-heading)
14311 (setq end (point))
14312 (goto-char beg)
14313 (while (re-search-forward re end t))
14314 (setq hiddenp (outline-invisible-p))
14315 (end-of-line 1)
14316 (and (equal (char-after) ?\n) (forward-char 1))
14317 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14318 (if (member (match-string 1) '("CLOCK:" ":END:"))
14319 ;; just skip this line
14320 (beginning-of-line 2)
14321 ;; Drawer start, find the end
14322 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14323 (beginning-of-line 1)))
14324 (org-skip-over-state-notes)
14325 (skip-chars-backward " \t\n\r")
14326 (if (eq (char-before) ?*) (forward-char 1))
14327 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14328 (beginning-of-line 0)
14329 (org-indent-to-column indent)
14330 (beginning-of-line 2)
14331 (org-indent-to-column indent)
14332 (beginning-of-line 0)
14333 (if hiddenp
14334 (save-excursion
14335 (org-back-to-heading t)
14336 (hide-entry))
14337 (org-flag-drawer t))))
14339 (defvar org-property-set-functions-alist nil
14340 "Property set function alist.
14341 Each entry should have the following format:
14343 (PROPERTY . READ-FUNCTION)
14345 The read function will be called with the same argument as
14346 `org-completing-read'.")
14348 (defun org-set-property-function (property)
14349 "Get the function that should be used to set PROPERTY.
14350 This is computed according to `org-property-set-functions-alist'."
14351 (or (cdr (assoc property org-property-set-functions-alist))
14352 'org-completing-read))
14354 (defun org-read-property-value (property)
14355 "Read PROPERTY value from user."
14356 (let* ((completion-ignore-case t)
14357 (allowed (org-property-get-allowed-values nil property 'table))
14358 (cur (org-entry-get nil property))
14359 (prompt (concat property " value"
14360 (if (and cur (string-match "\\S-" cur))
14361 (concat " [" cur "]") "") ": "))
14362 (set-function (org-set-property-function property))
14363 (val (if allowed
14364 (funcall set-function prompt allowed nil
14365 (not (get-text-property 0 'org-unrestricted
14366 (caar allowed))))
14367 (let (org-completion-use-ido org-completion-use-iswitchb)
14368 (funcall set-function prompt
14369 (mapcar 'list (org-property-values property))
14370 nil nil "" nil cur)))))
14371 (if (equal val "")
14373 val)))
14375 (defvar org-last-set-property nil)
14376 (defun org-read-property-name ()
14377 "Read a property name."
14378 (let* ((completion-ignore-case t)
14379 (keys (org-buffer-property-keys nil t t))
14380 (default-prop (or (save-excursion
14381 (save-match-data
14382 (beginning-of-line)
14383 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14384 (null (string= (match-string 1) "END"))
14385 (match-string 1))))
14386 org-last-set-property))
14387 (property (org-icompleting-read
14388 (concat "Property"
14389 (if default-prop (concat " [" default-prop "]") "")
14390 ": ")
14391 (mapcar 'list keys)
14392 nil nil nil nil
14393 default-prop
14395 (if (member property keys)
14396 property
14397 (or (cdr (assoc (downcase property)
14398 (mapcar (lambda (x) (cons (downcase x) x))
14399 keys)))
14400 property))))
14402 (defun org-set-property (property value)
14403 "In the current entry, set PROPERTY to VALUE.
14404 When called interactively, this will prompt for a property name, offering
14405 completion on existing and default properties. And then it will prompt
14406 for a value, offering completion either on allowed values (via an inherited
14407 xxx_ALL property) or on existing values in other instances of this property
14408 in the current file."
14409 (interactive (list nil nil))
14410 (let* ((property (or property (org-read-property-name)))
14411 (value (or value (org-read-property-value property)))
14412 (fn (assoc property org-properties-postprocess-alist)))
14413 (setq org-last-set-property property)
14414 ;; Possibly postprocess the inserted value:
14415 (when fn (setq value (funcall (cadr fn) value)))
14416 (unless (equal (org-entry-get nil property) value)
14417 (org-entry-put nil property value))))
14419 (defun org-delete-property (property)
14420 "In the current entry, delete PROPERTY."
14421 (interactive
14422 (let* ((completion-ignore-case t)
14423 (prop (org-icompleting-read "Property: "
14424 (org-entry-properties nil 'standard))))
14425 (list prop)))
14426 (message "Property %s %s" property
14427 (if (org-entry-delete nil property)
14428 "deleted"
14429 "was not present in the entry")))
14431 (defun org-delete-property-globally (property)
14432 "Remove PROPERTY globally, from all entries."
14433 (interactive
14434 (let* ((completion-ignore-case t)
14435 (prop (org-icompleting-read
14436 "Globally remove property: "
14437 (mapcar 'list (org-buffer-property-keys)))))
14438 (list prop)))
14439 (save-excursion
14440 (save-restriction
14441 (widen)
14442 (goto-char (point-min))
14443 (let ((cnt 0))
14444 (while (re-search-forward
14445 (org-re-property property)
14446 nil t)
14447 (setq cnt (1+ cnt))
14448 (replace-match ""))
14449 (message "Property \"%s\" removed from %d entries" property cnt)))))
14451 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14453 (defun org-compute-property-at-point ()
14454 "Compute the property at point.
14455 This looks for an enclosing column format, extracts the operator and
14456 then applies it to the property in the column format's scope."
14457 (interactive)
14458 (unless (org-at-property-p)
14459 (error "Not at a property"))
14460 (let ((prop (org-match-string-no-properties 2)))
14461 (org-columns-get-format-and-top-level)
14462 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14463 (error "No operator defined for property %s" prop))
14464 (org-columns-compute prop)))
14466 (defvar org-property-allowed-value-functions nil
14467 "Hook for functions supplying allowed values for a specific property.
14468 The functions must take a single argument, the name of the property, and
14469 return a flat list of allowed values. If \":ETC\" is one of
14470 the values, this means that these values are intended as defaults for
14471 completion, but that other values should be allowed too.
14472 The functions must return nil if they are not responsible for this
14473 property.")
14475 (defun org-property-get-allowed-values (pom property &optional table)
14476 "Get allowed values for the property PROPERTY.
14477 When TABLE is non-nil, return an alist that can directly be used for
14478 completion."
14479 (let (vals)
14480 (cond
14481 ((equal property "TODO")
14482 (setq vals (org-with-point-at pom
14483 (append org-todo-keywords-1 '("")))))
14484 ((equal property "PRIORITY")
14485 (let ((n org-lowest-priority))
14486 (while (>= n org-highest-priority)
14487 (push (char-to-string n) vals)
14488 (setq n (1- n)))))
14489 ((member property org-special-properties))
14490 ((setq vals (run-hook-with-args-until-success
14491 'org-property-allowed-value-functions property)))
14493 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14494 (when (and vals (string-match "\\S-" vals))
14495 (setq vals (car (read-from-string (concat "(" vals ")"))))
14496 (setq vals (mapcar (lambda (x)
14497 (cond ((stringp x) x)
14498 ((numberp x) (number-to-string x))
14499 ((symbolp x) (symbol-name x))
14500 (t "???")))
14501 vals)))))
14502 (when (member ":ETC" vals)
14503 (setq vals (remove ":ETC" vals))
14504 (org-add-props (car vals) '(org-unrestricted t)))
14505 (if table (mapcar 'list vals) vals)))
14507 (defun org-property-previous-allowed-value (&optional previous)
14508 "Switch to the next allowed value for this property."
14509 (interactive)
14510 (org-property-next-allowed-value t))
14512 (defun org-property-next-allowed-value (&optional previous)
14513 "Switch to the next allowed value for this property."
14514 (interactive)
14515 (unless (org-at-property-p)
14516 (error "Not at a property"))
14517 (let* ((key (match-string 2))
14518 (value (match-string 3))
14519 (allowed (or (org-property-get-allowed-values (point) key)
14520 (and (member value '("[ ]" "[-]" "[X]"))
14521 '("[ ]" "[X]"))))
14522 nval)
14523 (unless allowed
14524 (error "Allowed values for this property have not been defined"))
14525 (if previous (setq allowed (reverse allowed)))
14526 (if (member value allowed)
14527 (setq nval (car (cdr (member value allowed)))))
14528 (setq nval (or nval (car allowed)))
14529 (if (equal nval value)
14530 (error "Only one allowed value for this property"))
14531 (org-at-property-p)
14532 (replace-match (concat " :" key ": " nval) t t)
14533 (org-indent-line-function)
14534 (beginning-of-line 1)
14535 (skip-chars-forward " \t")
14536 (run-hook-with-args 'org-property-changed-functions key nval)))
14538 (defun org-find-olp (path &optional this-buffer)
14539 "Return a marker pointing to the entry at outline path OLP.
14540 If anything goes wrong, throw an error.
14541 You can wrap this call to catch the error like this:
14543 (condition-case msg
14544 (org-mobile-locate-entry (match-string 4))
14545 (error (nth 1 msg)))
14547 The return value will then be either a string with the error message,
14548 or a marker if everything is OK.
14550 If THIS-BUFFER is set, the outline path does not contain a file,
14551 only headings."
14552 (let* ((file (if this-buffer buffer-file-name (pop path)))
14553 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14554 (level 1)
14555 (lmin 1)
14556 (lmax 1)
14557 limit re end found pos heading cnt flevel)
14558 (unless buffer (error "File not found :%s" file))
14559 (with-current-buffer buffer
14560 (save-excursion
14561 (save-restriction
14562 (widen)
14563 (setq limit (point-max))
14564 (goto-char (point-min))
14565 (while (setq heading (pop path))
14566 (setq re (format org-complex-heading-regexp-format
14567 (regexp-quote heading)))
14568 (setq cnt 0 pos (point))
14569 (while (re-search-forward re end t)
14570 (setq level (- (match-end 1) (match-beginning 1)))
14571 (if (and (>= level lmin) (<= level lmax))
14572 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
14573 (when (= cnt 0) (error "Heading not found on level %d: %s"
14574 lmax heading))
14575 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14576 lmax heading))
14577 (goto-char found)
14578 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
14579 (setq end (save-excursion (org-end-of-subtree t t))))
14580 (when (org-on-heading-p)
14581 (move-marker (make-marker) (point))))))))
14583 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14584 "Find node HEADING in BUFFER.
14585 Return a marker to the heading if it was found, or nil if not.
14586 If POS-ONLY is set, return just the position instead of a marker.
14588 The heading text must match exact, but it may have a TODO keyword,
14589 a priority cookie and tags in the standard locations."
14590 (with-current-buffer (or buffer (current-buffer))
14591 (save-excursion
14592 (save-restriction
14593 (widen)
14594 (goto-char (point-min))
14595 (let (case-fold-search)
14596 (if (re-search-forward
14597 (format org-complex-heading-regexp-format
14598 (regexp-quote heading)) nil t)
14599 (if pos-only
14600 (match-beginning 0)
14601 (move-marker (make-marker) (match-beginning 0)))))))))
14603 (defun org-find-exact-heading-in-directory (heading &optional dir)
14604 "Find Org node headline HEADING in all .org files in directory DIR.
14605 When the target headline is found, return a marker to this location."
14606 (let ((files (directory-files (or dir default-directory)
14607 nil "\\`[^.#].*\\.org\\'"))
14608 file visiting m buffer)
14609 (catch 'found
14610 (while (setq file (pop files))
14611 (message "trying %s" file)
14612 (setq visiting (org-find-base-buffer-visiting file))
14613 (setq buffer (or visiting (find-file-noselect file)))
14614 (setq m (org-find-exact-headline-in-buffer
14615 heading buffer))
14616 (when (and (not m) (not visiting)) (kill-buffer buffer))
14617 (and m (throw 'found m))))))
14619 (defun org-find-entry-with-id (ident)
14620 "Locate the entry that contains the ID property with exact value IDENT.
14621 IDENT can be a string, a symbol or a number, this function will search for
14622 the string representation of it.
14623 Return the position where this entry starts, or nil if there is no such entry."
14624 (interactive "sID: ")
14625 (let ((id (cond
14626 ((stringp ident) ident)
14627 ((symbol-name ident) (symbol-name ident))
14628 ((numberp ident) (number-to-string ident))
14629 (t (error "IDENT %s must be a string, symbol or number" ident))))
14630 (case-fold-search nil))
14631 (save-excursion
14632 (save-restriction
14633 (widen)
14634 (goto-char (point-min))
14635 (when (re-search-forward
14636 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
14637 nil t)
14638 (org-back-to-heading t)
14639 (point))))))
14641 ;;;; Timestamps
14643 (defvar org-last-changed-timestamp nil)
14644 (defvar org-last-inserted-timestamp nil
14645 "The last time stamp inserted with `org-insert-time-stamp'.")
14646 (defvar org-time-was-given) ; dynamically scoped parameter
14647 (defvar org-end-time-was-given) ; dynamically scoped parameter
14648 (defvar org-ts-what) ; dynamically scoped parameter
14650 (defun org-time-stamp (arg &optional inactive)
14651 "Prompt for a date/time and insert a time stamp.
14652 If the user specifies a time like HH:MM, or if this command is called
14653 with a prefix argument, the time stamp will contain date and time.
14654 Otherwise, only the date will be included. All parts of a date not
14655 specified by the user will be filled in from the current date/time.
14656 So if you press just return without typing anything, the time stamp
14657 will represent the current date/time. If there is already a timestamp
14658 at the cursor, it will be modified."
14659 (interactive "P")
14660 (let* ((ts nil)
14661 (default-time
14662 ;; Default time is either today, or, when entering a range,
14663 ;; the range start.
14664 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
14665 (save-excursion
14666 (re-search-backward
14667 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
14668 (- (point) 20) t)))
14669 (apply 'encode-time (org-parse-time-string (match-string 1)))
14670 (current-time)))
14671 (default-input (and ts (org-get-compact-tod ts)))
14672 (repeater (save-excursion
14673 (save-match-data
14674 (beginning-of-line)
14675 (when (re-search-forward
14676 "\\([.+-]+[0-9]+[dwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
14677 (save-excursion (progn (end-of-line) (point))) t)
14678 (match-string 0)))))
14679 org-time-was-given org-end-time-was-given time)
14680 (cond
14681 ((and (org-at-timestamp-p t)
14682 (memq last-command '(org-time-stamp org-time-stamp-inactive))
14683 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
14684 (insert "--")
14685 (setq time (let ((this-command this-command))
14686 (org-read-date arg 'totime nil nil
14687 default-time default-input)))
14688 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
14689 ((org-at-timestamp-p t)
14690 (setq time (let ((this-command this-command))
14691 (org-read-date arg 'totime nil nil default-time default-input)))
14692 (when (org-at-timestamp-p t) ; just to get the match data
14693 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
14694 (replace-match "")
14695 (setq org-last-changed-timestamp
14696 (org-insert-time-stamp
14697 time (or org-time-was-given arg)
14698 inactive nil nil (list org-end-time-was-given)))
14699 (when repeater (goto-char (1- (point))) (insert " " repeater)
14700 (setq org-last-changed-timestamp
14701 (concat (substring org-last-inserted-timestamp 0 -1)
14702 " " repeater ">"))))
14703 (message "Timestamp updated"))
14705 (setq time (let ((this-command this-command))
14706 (org-read-date arg 'totime nil nil default-time default-input)))
14707 (org-insert-time-stamp time (or org-time-was-given arg) inactive
14708 nil nil (list org-end-time-was-given))))))
14710 ;; FIXME: can we use this for something else, like computing time differences?
14711 (defun org-get-compact-tod (s)
14712 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
14713 (let* ((t1 (match-string 1 s))
14714 (h1 (string-to-number (match-string 2 s)))
14715 (m1 (string-to-number (match-string 3 s)))
14716 (t2 (and (match-end 4) (match-string 5 s)))
14717 (h2 (and t2 (string-to-number (match-string 6 s))))
14718 (m2 (and t2 (string-to-number (match-string 7 s))))
14719 dh dm)
14720 (if (not t2)
14722 (setq dh (- h2 h1) dm (- m2 m1))
14723 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
14724 (concat t1 "+" (number-to-string dh)
14725 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
14727 (defun org-time-stamp-inactive (&optional arg)
14728 "Insert an inactive time stamp.
14729 An inactive time stamp is enclosed in square brackets instead of angle
14730 brackets. It is inactive in the sense that it does not trigger agenda entries,
14731 does not link to the calendar and cannot be changed with the S-cursor keys.
14732 So these are more for recording a certain time/date."
14733 (interactive "P")
14734 (org-time-stamp arg 'inactive))
14736 (defvar org-date-ovl (make-overlay 1 1))
14737 (overlay-put org-date-ovl 'face 'org-warning)
14738 (org-detach-overlay org-date-ovl)
14740 (defvar org-ans1) ; dynamically scoped parameter
14741 (defvar org-ans2) ; dynamically scoped parameter
14743 (defvar org-plain-time-of-day-regexp) ; defined below
14745 (defvar org-overriding-default-time nil) ; dynamically scoped
14746 (defvar org-read-date-overlay nil)
14747 (defvar org-dcst nil) ; dynamically scoped
14748 (defvar org-read-date-history nil)
14749 (defvar org-read-date-final-answer nil)
14750 (defvar org-read-date-analyze-futurep nil)
14751 (defvar org-read-date-analyze-forced-year nil)
14753 (defun org-read-date (&optional with-time to-time from-string prompt
14754 default-time default-input)
14755 "Read a date, possibly a time, and make things smooth for the user.
14756 The prompt will suggest to enter an ISO date, but you can also enter anything
14757 which will at least partially be understood by `parse-time-string'.
14758 Unrecognized parts of the date will default to the current day, month, year,
14759 hour and minute. If this command is called to replace a timestamp at point,
14760 of to enter the second timestamp of a range, the default time is taken
14761 from the existing stamp. Furthermore, the command prefers the future,
14762 so if you are giving a date where the year is not given, and the day-month
14763 combination is already past in the current year, it will assume you
14764 mean next year. For details, see the manual. A few examples:
14766 3-2-5 --> 2003-02-05
14767 feb 15 --> currentyear-02-15
14768 2/15 --> currentyear-02-15
14769 sep 12 9 --> 2009-09-12
14770 12:45 --> today 12:45
14771 22 sept 0:34 --> currentyear-09-22 0:34
14772 12 --> currentyear-currentmonth-12
14773 Fri --> nearest Friday (today or later)
14774 etc.
14776 Furthermore you can specify a relative date by giving, as the *first* thing
14777 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
14778 change in days weeks, months, years.
14779 With a single plus or minus, the date is relative to today. With a double
14780 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
14781 +4d --> four days from today
14782 +4 --> same as above
14783 +2w --> two weeks from today
14784 ++5 --> five days from default date
14786 The function understands only English month and weekday abbreviations,
14787 but this can be configured with the variables `parse-time-months' and
14788 `parse-time-weekdays'.
14790 While prompting, a calendar is popped up - you can also select the
14791 date with the mouse (button 1). The calendar shows a period of three
14792 months. To scroll it to other months, use the keys `>' and `<'.
14793 If you don't like the calendar, turn it off with
14794 \(setq org-read-date-popup-calendar nil)
14796 With optional argument TO-TIME, the date will immediately be converted
14797 to an internal time.
14798 With an optional argument WITH-TIME, the prompt will suggest to also
14799 insert a time. Note that when WITH-TIME is not set, you can still
14800 enter a time, and this function will inform the calling routine about
14801 this change. The calling routine may then choose to change the format
14802 used to insert the time stamp into the buffer to include the time.
14803 With optional argument FROM-STRING, read from this string instead from
14804 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
14805 the time/date that is used for everything that is not specified by the
14806 user."
14807 (require 'parse-time)
14808 (let* ((org-time-stamp-rounding-minutes
14809 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
14810 (org-dcst org-display-custom-times)
14811 (ct (org-current-time))
14812 (def (or org-overriding-default-time default-time ct))
14813 (defdecode (decode-time def))
14814 (dummy (progn
14815 (when (< (nth 2 defdecode) org-extend-today-until)
14816 (setcar (nthcdr 2 defdecode) -1)
14817 (setcar (nthcdr 1 defdecode) 59)
14818 (setq def (apply 'encode-time defdecode)
14819 defdecode (decode-time def)))))
14820 (calendar-frame-setup nil)
14821 (calendar-setup nil)
14822 (calendar-move-hook nil)
14823 (calendar-view-diary-initially-flag nil)
14824 (calendar-view-holidays-initially-flag nil)
14825 (timestr (format-time-string
14826 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
14827 (prompt (concat (if prompt (concat prompt " ") "")
14828 (format "Date+time [%s]: " timestr)))
14829 ans (org-ans0 "") org-ans1 org-ans2 final)
14831 (cond
14832 (from-string (setq ans from-string))
14833 (org-read-date-popup-calendar
14834 (save-excursion
14835 (save-window-excursion
14836 (calendar)
14837 (unwind-protect
14838 (progn
14839 (calendar-forward-day (- (time-to-days def)
14840 (calendar-absolute-from-gregorian
14841 (calendar-current-date))))
14842 (org-eval-in-calendar nil t)
14843 (let* ((old-map (current-local-map))
14844 (map (copy-keymap calendar-mode-map))
14845 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
14846 (org-defkey map (kbd "RET") 'org-calendar-select)
14847 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
14848 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
14849 (org-defkey minibuffer-local-map [(meta shift left)]
14850 (lambda () (interactive)
14851 (org-eval-in-calendar '(calendar-backward-month 1))))
14852 (org-defkey minibuffer-local-map [(meta shift right)]
14853 (lambda () (interactive)
14854 (org-eval-in-calendar '(calendar-forward-month 1))))
14855 (org-defkey minibuffer-local-map [(meta shift up)]
14856 (lambda () (interactive)
14857 (org-eval-in-calendar '(calendar-backward-year 1))))
14858 (org-defkey minibuffer-local-map [(meta shift down)]
14859 (lambda () (interactive)
14860 (org-eval-in-calendar '(calendar-forward-year 1))))
14861 (org-defkey minibuffer-local-map [?\e (shift left)]
14862 (lambda () (interactive)
14863 (org-eval-in-calendar '(calendar-backward-month 1))))
14864 (org-defkey minibuffer-local-map [?\e (shift right)]
14865 (lambda () (interactive)
14866 (org-eval-in-calendar '(calendar-forward-month 1))))
14867 (org-defkey minibuffer-local-map [?\e (shift up)]
14868 (lambda () (interactive)
14869 (org-eval-in-calendar '(calendar-backward-year 1))))
14870 (org-defkey minibuffer-local-map [?\e (shift down)]
14871 (lambda () (interactive)
14872 (org-eval-in-calendar '(calendar-forward-year 1))))
14873 (org-defkey minibuffer-local-map [(shift up)]
14874 (lambda () (interactive)
14875 (org-eval-in-calendar '(calendar-backward-week 1))))
14876 (org-defkey minibuffer-local-map [(shift down)]
14877 (lambda () (interactive)
14878 (org-eval-in-calendar '(calendar-forward-week 1))))
14879 (org-defkey minibuffer-local-map [(shift left)]
14880 (lambda () (interactive)
14881 (org-eval-in-calendar '(calendar-backward-day 1))))
14882 (org-defkey minibuffer-local-map [(shift right)]
14883 (lambda () (interactive)
14884 (org-eval-in-calendar '(calendar-forward-day 1))))
14885 (org-defkey minibuffer-local-map ">"
14886 (lambda () (interactive)
14887 (org-eval-in-calendar '(scroll-calendar-left 1))))
14888 (org-defkey minibuffer-local-map "<"
14889 (lambda () (interactive)
14890 (org-eval-in-calendar '(scroll-calendar-right 1))))
14891 (org-defkey minibuffer-local-map "\C-v"
14892 (lambda () (interactive)
14893 (org-eval-in-calendar
14894 '(calendar-scroll-left-three-months 1))))
14895 (org-defkey minibuffer-local-map "\M-v"
14896 (lambda () (interactive)
14897 (org-eval-in-calendar
14898 '(calendar-scroll-right-three-months 1))))
14899 (run-hooks 'org-read-date-minibuffer-setup-hook)
14900 (unwind-protect
14901 (progn
14902 (use-local-map map)
14903 (add-hook 'post-command-hook 'org-read-date-display)
14904 (setq org-ans0 (read-string prompt default-input
14905 'org-read-date-history nil))
14906 ;; org-ans0: from prompt
14907 ;; org-ans1: from mouse click
14908 ;; org-ans2: from calendar motion
14909 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
14910 (remove-hook 'post-command-hook 'org-read-date-display)
14911 (use-local-map old-map)
14912 (when org-read-date-overlay
14913 (delete-overlay org-read-date-overlay)
14914 (setq org-read-date-overlay nil)))))
14915 (bury-buffer "*Calendar*")))))
14917 (t ; Naked prompt only
14918 (unwind-protect
14919 (setq ans (read-string prompt default-input
14920 'org-read-date-history timestr))
14921 (when org-read-date-overlay
14922 (delete-overlay org-read-date-overlay)
14923 (setq org-read-date-overlay nil)))))
14925 (setq final (org-read-date-analyze ans def defdecode))
14927 (when org-read-date-analyze-forced-year
14928 (message "Year was forced into %s"
14929 (if org-read-date-force-compatible-dates
14930 "compatible range (1970-2037)"
14931 "range representable on this machine"))
14932 (ding))
14934 ;; One round trip to get rid of 34th of August and stuff like that....
14935 (setq final (decode-time (apply 'encode-time final)))
14937 (setq org-read-date-final-answer ans)
14939 (if to-time
14940 (apply 'encode-time final)
14941 (if (and (boundp 'org-time-was-given) org-time-was-given)
14942 (format "%04d-%02d-%02d %02d:%02d"
14943 (nth 5 final) (nth 4 final) (nth 3 final)
14944 (nth 2 final) (nth 1 final))
14945 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
14947 (defvar def)
14948 (defvar defdecode)
14949 (defvar with-time)
14950 (defun org-read-date-display ()
14951 "Display the current date prompt interpretation in the minibuffer."
14952 (when org-read-date-display-live
14953 (when org-read-date-overlay
14954 (delete-overlay org-read-date-overlay))
14955 (let ((p (point)))
14956 (end-of-line 1)
14957 (while (not (equal (buffer-substring
14958 (max (point-min) (- (point) 4)) (point))
14959 " "))
14960 (insert " "))
14961 (goto-char p))
14962 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
14963 " " (or org-ans1 org-ans2)))
14964 (org-end-time-was-given nil)
14965 (f (org-read-date-analyze ans def defdecode))
14966 (fmts (if org-dcst
14967 org-time-stamp-custom-formats
14968 org-time-stamp-formats))
14969 (fmt (if (or with-time
14970 (and (boundp 'org-time-was-given) org-time-was-given))
14971 (cdr fmts)
14972 (car fmts)))
14973 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
14974 (when (and org-end-time-was-given
14975 (string-match org-plain-time-of-day-regexp txt))
14976 (setq txt (concat (substring txt 0 (match-end 0)) "-"
14977 org-end-time-was-given
14978 (substring txt (match-end 0)))))
14979 (when org-read-date-analyze-futurep
14980 (setq txt (concat txt " (=>F)")))
14981 (setq org-read-date-overlay
14982 (make-overlay (1- (point-at-eol)) (point-at-eol)))
14983 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
14985 (defun org-read-date-analyze (ans def defdecode)
14986 "Analyze the combined answer of the date prompt."
14987 ;; FIXME: cleanup and comment
14988 (let ((nowdecode (decode-time (current-time)))
14989 delta deltan deltaw deltadef year month day
14990 hour minute second wday pm h2 m2 tl wday1
14991 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
14992 (setq org-read-date-analyze-futurep nil
14993 org-read-date-analyze-forced-year nil)
14994 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
14995 (setq ans "+0"))
14997 (when (setq delta (org-read-date-get-relative ans (current-time) def))
14998 (setq ans (replace-match "" t t ans)
14999 deltan (car delta)
15000 deltaw (nth 1 delta)
15001 deltadef (nth 2 delta)))
15003 ;; Check if there is an iso week date in there
15004 ;; If yes, store the info and postpone interpreting it until the rest
15005 ;; of the parsing is done
15006 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15007 (setq iso-year (if (match-end 1)
15008 (org-small-year-to-year
15009 (string-to-number (match-string 1 ans))))
15010 iso-weekday (if (match-end 3)
15011 (string-to-number (match-string 3 ans)))
15012 iso-week (string-to-number (match-string 2 ans)))
15013 (setq ans (replace-match "" t t ans)))
15015 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15016 (when (string-match
15017 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15018 (setq year (if (match-end 2)
15019 (string-to-number (match-string 2 ans))
15020 (progn (setq kill-year t)
15021 (string-to-number (format-time-string "%Y"))))
15022 month (string-to-number (match-string 3 ans))
15023 day (string-to-number (match-string 4 ans)))
15024 (if (< year 100) (setq year (+ 2000 year)))
15025 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15026 t nil ans)))
15028 ;; Help matching dottet european dates
15029 (when (string-match
15030 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15031 (setq year (if (match-end 3)
15032 (string-to-number (match-string 3 ans))
15033 (progn (setq kill-year t)
15034 (string-to-number (format-time-string "%Y"))))
15035 day (string-to-number (match-string 1 ans))
15036 month (string-to-number (match-string 2 ans))
15037 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15038 t nil ans)))
15040 ;; Help matching american dates, like 5/30 or 5/30/7
15041 (when (string-match
15042 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15043 (setq year (if (match-end 4)
15044 (string-to-number (match-string 4 ans))
15045 (progn (setq kill-year t)
15046 (string-to-number (format-time-string "%Y"))))
15047 month (string-to-number (match-string 1 ans))
15048 day (string-to-number (match-string 2 ans)))
15049 (if (< year 100) (setq year (+ 2000 year)))
15050 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15051 t nil ans)))
15052 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15053 ;; If there is a time with am/pm, and *no* time without it, we convert
15054 ;; so that matching will be successful.
15055 (loop for i from 1 to 2 do ; twice, for end time as well
15056 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15057 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15058 (setq hour (string-to-number (match-string 1 ans))
15059 minute (if (match-end 3)
15060 (string-to-number (match-string 3 ans))
15062 pm (equal ?p
15063 (string-to-char (downcase (match-string 4 ans)))))
15064 (if (and (= hour 12) (not pm))
15065 (setq hour 0)
15066 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15067 (setq ans (replace-match (format "%02d:%02d" hour minute)
15068 t t ans))))
15070 ;; Check if a time range is given as a duration
15071 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15072 (setq hour (string-to-number (match-string 1 ans))
15073 h2 (+ hour (string-to-number (match-string 3 ans)))
15074 minute (string-to-number (match-string 2 ans))
15075 m2 (+ minute (if (match-end 5) (string-to-number
15076 (match-string 5 ans))0)))
15077 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15078 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15079 t t ans)))
15081 ;; Check if there is a time range
15082 (when (boundp 'org-end-time-was-given)
15083 (setq org-time-was-given nil)
15084 (when (and (string-match org-plain-time-of-day-regexp ans)
15085 (match-end 8))
15086 (setq org-end-time-was-given (match-string 8 ans))
15087 (setq ans (concat (substring ans 0 (match-beginning 7))
15088 (substring ans (match-end 7))))))
15090 (setq tl (parse-time-string ans)
15091 day (or (nth 3 tl) (nth 3 defdecode))
15092 month (or (nth 4 tl)
15093 (if (and org-read-date-prefer-future
15094 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15095 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15096 (nth 4 defdecode)))
15097 year (or (and (not kill-year) (nth 5 tl))
15098 (if (and org-read-date-prefer-future
15099 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15100 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15101 (nth 5 defdecode)))
15102 hour (or (nth 2 tl) (nth 2 defdecode))
15103 minute (or (nth 1 tl) (nth 1 defdecode))
15104 second (or (nth 0 tl) 0)
15105 wday (nth 6 tl))
15107 (when (and (eq org-read-date-prefer-future 'time)
15108 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15109 (equal day (nth 3 nowdecode))
15110 (equal month (nth 4 nowdecode))
15111 (equal year (nth 5 nowdecode))
15112 (nth 2 tl)
15113 (or (< (nth 2 tl) (nth 2 nowdecode))
15114 (and (= (nth 2 tl) (nth 2 nowdecode))
15115 (nth 1 tl)
15116 (< (nth 1 tl) (nth 1 nowdecode)))))
15117 (setq day (1+ day)
15118 futurep t))
15120 ;; Special date definitions below
15121 (cond
15122 (iso-week
15123 ;; There was an iso week
15124 (require 'cal-iso)
15125 (setq futurep nil)
15126 (setq year (or iso-year year)
15127 day (or iso-weekday wday 1)
15128 wday nil ; to make sure that the trigger below does not match
15129 iso-date (calendar-gregorian-from-absolute
15130 (calendar-absolute-from-iso
15131 (list iso-week day year))))
15132 ; FIXME: Should we also push ISO weeks into the future?
15133 ; (when (and org-read-date-prefer-future
15134 ; (not iso-year)
15135 ; (< (calendar-absolute-from-gregorian iso-date)
15136 ; (time-to-days (current-time))))
15137 ; (setq year (1+ year)
15138 ; iso-date (calendar-gregorian-from-absolute
15139 ; (calendar-absolute-from-iso
15140 ; (list iso-week day year)))))
15141 (setq month (car iso-date)
15142 year (nth 2 iso-date)
15143 day (nth 1 iso-date)))
15144 (deltan
15145 (setq futurep nil)
15146 (unless deltadef
15147 (let ((now (decode-time (current-time))))
15148 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15149 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15150 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15151 ((equal deltaw "m") (setq month (+ month deltan)))
15152 ((equal deltaw "y") (setq year (+ year deltan)))))
15153 ((and wday (not (nth 3 tl)))
15154 (setq futurep nil)
15155 ;; Weekday was given, but no day, so pick that day in the week
15156 ;; on or after the derived date.
15157 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15158 (unless (equal wday wday1)
15159 (setq day (+ day (% (- wday wday1 -7) 7))))))
15160 (if (and (boundp 'org-time-was-given)
15161 (nth 2 tl))
15162 (setq org-time-was-given t))
15163 (if (< year 100) (setq year (+ 2000 year)))
15164 ;; Check of the date is representable
15165 (if org-read-date-force-compatible-dates
15166 (progn
15167 (if (< year 1970)
15168 (setq year 1970 org-read-date-analyze-forced-year t))
15169 (if (> year 2037)
15170 (setq year 2037 org-read-date-analyze-forced-year t)))
15171 (condition-case nil
15172 (ignore (encode-time second minute hour day month year))
15173 (error
15174 (setq year (nth 5 defdecode))
15175 (setq org-read-date-analyze-forced-year t))))
15176 (setq org-read-date-analyze-futurep futurep)
15177 (list second minute hour day month year)))
15179 (defvar parse-time-weekdays)
15181 (defun org-read-date-get-relative (s today default)
15182 "Check string S for special relative date string.
15183 TODAY and DEFAULT are internal times, for today and for a default.
15184 Return shift list (N what def-flag)
15185 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15186 N is the number of WHATs to shift.
15187 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15188 the DEFAULT date rather than TODAY."
15189 (when (and
15190 (string-match
15191 (concat
15192 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15193 "\\([0-9]+\\)?"
15194 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15195 "\\([ \t]\\|$\\)") s)
15196 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15197 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15198 (string-to-char (substring (match-string 1 s) -1))
15199 ?+))
15200 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15201 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15202 (what (if (match-end 3) (match-string 3 s) "d"))
15203 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15204 (date (if rel default today))
15205 (wday (nth 6 (decode-time date)))
15206 delta)
15207 (if wday1
15208 (progn
15209 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15210 (if (= dir ?-) (setq delta (- delta 7)))
15211 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15212 (list delta "d" rel))
15213 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15215 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15216 "Turn a user-specified date into the internal representation.
15217 The internal representation needed by the calendar is (month day year).
15218 This is a wrapper to handle the brain-dead convention in calendar that
15219 user function argument order change dependent on argument order."
15220 (if (boundp 'calendar-date-style)
15221 (cond
15222 ((eq calendar-date-style 'american)
15223 (list arg1 arg2 arg3))
15224 ((eq calendar-date-style 'european)
15225 (list arg2 arg1 arg3))
15226 ((eq calendar-date-style 'iso)
15227 (list arg2 arg3 arg1)))
15228 (with-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15229 (if (org-bound-and-true-p european-calendar-style)
15230 (list arg2 arg1 arg3)
15231 (list arg1 arg2 arg3)))))
15233 (defun org-eval-in-calendar (form &optional keepdate)
15234 "Eval FORM in the calendar window and return to current window.
15235 Also, store the cursor date in variable org-ans2."
15236 (let ((sf (selected-frame))
15237 (sw (selected-window)))
15238 (select-window (get-buffer-window "*Calendar*" t))
15239 (eval form)
15240 (when (and (not keepdate) (calendar-cursor-to-date))
15241 (let* ((date (calendar-cursor-to-date))
15242 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15243 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15244 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15245 (select-window sw)
15246 (org-select-frame-set-input-focus sf)))
15248 (defun org-calendar-select ()
15249 "Return to `org-read-date' with the date currently selected.
15250 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15251 (interactive)
15252 (when (calendar-cursor-to-date)
15253 (let* ((date (calendar-cursor-to-date))
15254 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15255 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15256 (if (active-minibuffer-window) (exit-minibuffer))))
15258 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15259 "Insert a date stamp for the date given by the internal TIME.
15260 WITH-HM means use the stamp format that includes the time of the day.
15261 INACTIVE means use square brackets instead of angular ones, so that the
15262 stamp will not contribute to the agenda.
15263 PRE and POST are optional strings to be inserted before and after the
15264 stamp.
15265 The command returns the inserted time stamp."
15266 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15267 stamp)
15268 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15269 (insert-before-markers (or pre ""))
15270 (when (listp extra)
15271 (setq extra (car extra))
15272 (if (and (stringp extra)
15273 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15274 (setq extra (format "-%02d:%02d"
15275 (string-to-number (match-string 1 extra))
15276 (string-to-number (match-string 2 extra))))
15277 (setq extra nil)))
15278 (when extra
15279 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15280 (insert-before-markers (setq stamp (format-time-string fmt time)))
15281 (insert-before-markers (or post ""))
15282 (setq org-last-inserted-timestamp stamp)))
15284 (defun org-toggle-time-stamp-overlays ()
15285 "Toggle the use of custom time stamp formats."
15286 (interactive)
15287 (setq org-display-custom-times (not org-display-custom-times))
15288 (unless org-display-custom-times
15289 (let ((p (point-min)) (bmp (buffer-modified-p)))
15290 (while (setq p (next-single-property-change p 'display))
15291 (if (and (get-text-property p 'display)
15292 (eq (get-text-property p 'face) 'org-date))
15293 (remove-text-properties
15294 p (setq p (next-single-property-change p 'display))
15295 '(display t))))
15296 (set-buffer-modified-p bmp)))
15297 (if (featurep 'xemacs)
15298 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15299 (org-restart-font-lock)
15300 (setq org-table-may-need-update t)
15301 (if org-display-custom-times
15302 (message "Time stamps are overlayed with custom format")
15303 (message "Time stamp overlays removed")))
15305 (defun org-display-custom-time (beg end)
15306 "Overlay modified time stamp format over timestamp between BEG and END."
15307 (let* ((ts (buffer-substring beg end))
15308 t1 w1 with-hm tf time str w2 (off 0))
15309 (save-match-data
15310 (setq t1 (org-parse-time-string ts t))
15311 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
15312 (setq off (- (match-end 0) (match-beginning 0)))))
15313 (setq end (- end off))
15314 (setq w1 (- end beg)
15315 with-hm (and (nth 1 t1) (nth 2 t1))
15316 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15317 time (org-fix-decoded-time t1)
15318 str (org-add-props
15319 (format-time-string
15320 (substring tf 1 -1) (apply 'encode-time time))
15321 nil 'mouse-face 'highlight)
15322 w2 (length str))
15323 (if (not (= w2 w1))
15324 (add-text-properties (1+ beg) (+ 2 beg)
15325 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15326 (if (featurep 'xemacs)
15327 (progn
15328 (put-text-property beg end 'invisible t)
15329 (put-text-property beg end 'end-glyph (make-glyph str)))
15330 (put-text-property beg end 'display str))))
15332 (defun org-translate-time (string)
15333 "Translate all timestamps in STRING to custom format.
15334 But do this only if the variable `org-display-custom-times' is set."
15335 (when org-display-custom-times
15336 (save-match-data
15337 (let* ((start 0)
15338 (re org-ts-regexp-both)
15339 t1 with-hm inactive tf time str beg end)
15340 (while (setq start (string-match re string start))
15341 (setq beg (match-beginning 0)
15342 end (match-end 0)
15343 t1 (save-match-data
15344 (org-parse-time-string (substring string beg end) t))
15345 with-hm (and (nth 1 t1) (nth 2 t1))
15346 inactive (equal (substring string beg (1+ beg)) "[")
15347 tf (funcall (if with-hm 'cdr 'car)
15348 org-time-stamp-custom-formats)
15349 time (org-fix-decoded-time t1)
15350 str (format-time-string
15351 (concat
15352 (if inactive "[" "<") (substring tf 1 -1)
15353 (if inactive "]" ">"))
15354 (apply 'encode-time time))
15355 string (replace-match str t t string)
15356 start (+ start (length str)))))))
15357 string)
15359 (defun org-fix-decoded-time (time)
15360 "Set 0 instead of nil for the first 6 elements of time.
15361 Don't touch the rest."
15362 (let ((n 0))
15363 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15365 (defun org-days-to-time (timestamp-string)
15366 "Difference between TIMESTAMP-STRING and now in days."
15367 (- (time-to-days (org-time-string-to-time timestamp-string))
15368 (time-to-days (current-time))))
15370 (defun org-deadline-close (timestamp-string &optional ndays)
15371 "Is the time in TIMESTAMP-STRING close to the current date?"
15372 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15373 (and (< (org-days-to-time timestamp-string) ndays)
15374 (not (org-entry-is-done-p))))
15376 (defun org-get-wdays (ts)
15377 "Get the deadline lead time appropriate for timestring TS."
15378 (cond
15379 ((<= org-deadline-warning-days 0)
15380 ;; 0 or negative, enforce this value no matter what
15381 (- org-deadline-warning-days))
15382 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
15383 ;; lead time is specified.
15384 (floor (* (string-to-number (match-string 1 ts))
15385 (cdr (assoc (match-string 2 ts)
15386 '(("d" . 1) ("w" . 7)
15387 ("m" . 30.4) ("y" . 365.25)))))))
15388 ;; go for the default.
15389 (t org-deadline-warning-days)))
15391 (defun org-calendar-select-mouse (ev)
15392 "Return to `org-read-date' with the date currently selected.
15393 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15394 (interactive "e")
15395 (mouse-set-point ev)
15396 (when (calendar-cursor-to-date)
15397 (let* ((date (calendar-cursor-to-date))
15398 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15399 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15400 (if (active-minibuffer-window) (exit-minibuffer))))
15402 (defun org-check-deadlines (ndays)
15403 "Check if there are any deadlines due or past due.
15404 A deadline is considered due if it happens within `org-deadline-warning-days'
15405 days from today's date. If the deadline appears in an entry marked DONE,
15406 it is not shown. The prefix arg NDAYS can be used to test that many
15407 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15408 (interactive "P")
15409 (let* ((org-warn-days
15410 (cond
15411 ((equal ndays '(4)) 100000)
15412 (ndays (prefix-numeric-value ndays))
15413 (t (abs org-deadline-warning-days))))
15414 (case-fold-search nil)
15415 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15416 (callback
15417 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15419 (message "%d deadlines past-due or due within %d days"
15420 (org-occur regexp nil callback)
15421 org-warn-days)))
15423 (defun org-check-before-date (date)
15424 "Check if there are deadlines or scheduled entries before DATE."
15425 (interactive (list (org-read-date)))
15426 (let ((case-fold-search nil)
15427 (regexp (concat "\\<\\(" org-deadline-string
15428 "\\|" org-scheduled-string
15429 "\\) *<\\([^>]+\\)>"))
15430 (callback
15431 (lambda () (time-less-p
15432 (org-time-string-to-time (match-string 2))
15433 (org-time-string-to-time date)))))
15434 (message "%d entries before %s"
15435 (org-occur regexp nil callback) date)))
15437 (defun org-check-after-date (date)
15438 "Check if there are deadlines or scheduled entries after DATE."
15439 (interactive (list (org-read-date)))
15440 (let ((case-fold-search nil)
15441 (regexp (concat "\\<\\(" org-deadline-string
15442 "\\|" org-scheduled-string
15443 "\\) *<\\([^>]+\\)>"))
15444 (callback
15445 (lambda () (not
15446 (time-less-p
15447 (org-time-string-to-time (match-string 2))
15448 (org-time-string-to-time date))))))
15449 (message "%d entries after %s"
15450 (org-occur regexp nil callback) date)))
15452 (defun org-evaluate-time-range (&optional to-buffer)
15453 "Evaluate a time range by computing the difference between start and end.
15454 Normally the result is just printed in the echo area, but with prefix arg
15455 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15456 If the time range is actually in a table, the result is inserted into the
15457 next column.
15458 For time difference computation, a year is assumed to be exactly 365
15459 days in order to avoid rounding problems."
15460 (interactive "P")
15462 (org-clock-update-time-maybe)
15463 (save-excursion
15464 (unless (org-at-date-range-p t)
15465 (goto-char (point-at-bol))
15466 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15467 (if (not (org-at-date-range-p t))
15468 (error "Not at a time-stamp range, and none found in current line")))
15469 (let* ((ts1 (match-string 1))
15470 (ts2 (match-string 2))
15471 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15472 (match-end (match-end 0))
15473 (time1 (org-time-string-to-time ts1))
15474 (time2 (org-time-string-to-time ts2))
15475 (t1 (org-float-time time1))
15476 (t2 (org-float-time time2))
15477 (diff (abs (- t2 t1)))
15478 (negative (< (- t2 t1) 0))
15479 ;; (ys (floor (* 365 24 60 60)))
15480 (ds (* 24 60 60))
15481 (hs (* 60 60))
15482 (fy "%dy %dd %02d:%02d")
15483 (fy1 "%dy %dd")
15484 (fd "%dd %02d:%02d")
15485 (fd1 "%dd")
15486 (fh "%02d:%02d")
15487 y d h m align)
15488 (if havetime
15489 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15491 d (floor (/ diff ds)) diff (mod diff ds)
15492 h (floor (/ diff hs)) diff (mod diff hs)
15493 m (floor (/ diff 60)))
15494 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15496 d (floor (+ (/ diff ds) 0.5))
15497 h 0 m 0))
15498 (if (not to-buffer)
15499 (message "%s" (org-make-tdiff-string y d h m))
15500 (if (org-at-table-p)
15501 (progn
15502 (goto-char match-end)
15503 (setq align t)
15504 (and (looking-at " *|") (goto-char (match-end 0))))
15505 (goto-char match-end))
15506 (if (looking-at
15507 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15508 (replace-match ""))
15509 (if negative (insert " -"))
15510 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15511 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15512 (insert " " (format fh h m))))
15513 (if align (org-table-align))
15514 (message "Time difference inserted")))))
15516 (defun org-make-tdiff-string (y d h m)
15517 (let ((fmt "")
15518 (l nil))
15519 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15520 l (push y l)))
15521 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15522 l (push d l)))
15523 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15524 l (push h l)))
15525 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15526 l (push m l)))
15527 (apply 'format fmt (nreverse l))))
15529 (defun org-time-string-to-time (s &optional buffer pos)
15530 (condition-case errdata
15531 (apply 'encode-time (org-parse-time-string s))
15532 (error (error "Bad timestamp `%s'%s\nError was: %s"
15533 s (if (not (and buffer pos))
15535 (format " at %d in buffer `%s'" pos buffer))
15536 (cdr errdata)))))
15538 (defun org-time-string-to-seconds (s)
15539 (org-float-time (org-time-string-to-time s)))
15541 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
15542 "Convert a time stamp to an absolute day number.
15543 If there is a specifier for a cyclic time stamp, get the closest date to
15544 DAYNR.
15545 PREFER and SHOW-ALL are passed through to `org-closest-date'.
15546 The variable date is bound by the calendar when this is called."
15547 (cond
15548 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15549 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15550 daynr
15551 (+ daynr 1000)))
15552 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
15553 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15554 (time-to-days (current-time))) (match-string 0 s)
15555 prefer show-all))
15556 (t (time-to-days
15557 (condition-case errdata
15558 (apply 'encode-time (org-parse-time-string s))
15559 (error (error "Bad timestamp `%s'%s\nError was: %s"
15560 s (if (not (and buffer pos))
15562 (format " at %d in buffer `%s'" pos buffer))
15563 (cdr errdata))))))))
15565 (defun org-days-to-iso-week (days)
15566 "Return the iso week number."
15567 (require 'cal-iso)
15568 (car (calendar-iso-from-absolute days)))
15570 (defun org-small-year-to-year (year)
15571 "Convert 2-digit years into 4-digit years.
15572 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15573 The year 2000 cannot be abbreviated. Any year larger than 99
15574 is returned unchanged."
15575 (if (< year 38)
15576 (setq year (+ 2000 year))
15577 (if (< year 100)
15578 (setq year (+ 1900 year))))
15579 year)
15581 (defun org-time-from-absolute (d)
15582 "Return the time corresponding to date D.
15583 D may be an absolute day number, or a calendar-type list (month day year)."
15584 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15585 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15587 (defun org-calendar-holiday ()
15588 "List of holidays, for Diary display in Org-mode."
15589 (require 'holidays)
15590 (let ((hl (funcall
15591 (if (fboundp 'calendar-check-holidays)
15592 'calendar-check-holidays 'check-calendar-holidays) date)))
15593 (if hl (mapconcat 'identity hl "; "))))
15595 (defun org-diary-sexp-entry (sexp entry date)
15596 "Process a SEXP diary ENTRY for DATE."
15597 (require 'diary-lib)
15598 (let ((result (if calendar-debug-sexp
15599 (let ((stack-trace-on-error t))
15600 (eval (car (read-from-string sexp))))
15601 (condition-case nil
15602 (eval (car (read-from-string sexp)))
15603 (error
15604 (beep)
15605 (message "Bad sexp at line %d in %s: %s"
15606 (org-current-line)
15607 (buffer-file-name) sexp)
15608 (sleep-for 2))))))
15609 (cond ((stringp result) (split-string result "; "))
15610 ((and (consp result)
15611 (not (consp (cdr result)))
15612 (stringp (cdr result))) (cdr result))
15613 ((and (consp result)
15614 (stringp (car result))) result)
15615 (result entry)
15616 (t nil))))
15618 (defun org-diary-to-ical-string (frombuf)
15619 "Get iCalendar entries from diary entries in buffer FROMBUF.
15620 This uses the icalendar.el library."
15621 (let* ((tmpdir (if (featurep 'xemacs)
15622 (temp-directory)
15623 temporary-file-directory))
15624 (tmpfile (make-temp-name
15625 (expand-file-name "orgics" tmpdir)))
15626 buf rtn b e)
15627 (with-current-buffer frombuf
15628 (icalendar-export-region (point-min) (point-max) tmpfile)
15629 (setq buf (find-buffer-visiting tmpfile))
15630 (set-buffer buf)
15631 (goto-char (point-min))
15632 (if (re-search-forward "^BEGIN:VEVENT" nil t)
15633 (setq b (match-beginning 0)))
15634 (goto-char (point-max))
15635 (if (re-search-backward "^END:VEVENT" nil t)
15636 (setq e (match-end 0)))
15637 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
15638 (kill-buffer buf)
15639 (delete-file tmpfile)
15640 rtn))
15642 (defun org-closest-date (start current change prefer show-all)
15643 "Find the date closest to CURRENT that is consistent with START and CHANGE.
15644 When PREFER is `past', return a date that is either CURRENT or past.
15645 When PREFER is `future', return a date that is either CURRENT or future.
15646 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
15647 ;; Make the proper lists from the dates
15648 (catch 'exit
15649 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
15650 dn dw sday cday n1 n2 n0
15651 d m y y1 y2 date1 date2 nmonths nm ny m2)
15653 (setq start (org-date-to-gregorian start)
15654 current (org-date-to-gregorian
15655 (if show-all
15656 current
15657 (time-to-days (current-time))))
15658 sday (calendar-absolute-from-gregorian start)
15659 cday (calendar-absolute-from-gregorian current))
15661 (if (<= cday sday) (throw 'exit sday))
15663 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
15664 (setq dn (string-to-number (match-string 1 change))
15665 dw (cdr (assoc (match-string 2 change) a1)))
15666 (error "Invalid change specifier: %s" change))
15667 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
15668 (cond
15669 ((eq dw 'day)
15670 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
15671 n2 (+ n1 dn)))
15672 ((eq dw 'year)
15673 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
15674 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
15675 (setq date1 (list m d y1)
15676 n1 (calendar-absolute-from-gregorian date1)
15677 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
15678 n2 (calendar-absolute-from-gregorian date2)))
15679 ((eq dw 'month)
15680 ;; approx number of month between the two dates
15681 (setq nmonths (floor (/ (- cday sday) 30.436875)))
15682 ;; How often does dn fit in there?
15683 (setq d (nth 1 start) m (car start) y (nth 2 start)
15684 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
15685 m (+ m nm)
15686 ny (floor (/ m 12))
15687 y (+ y ny)
15688 m (- m (* ny 12)))
15689 (while (> m 12) (setq m (- m 12) y (1+ y)))
15690 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
15691 (setq m2 (+ m dn) y2 y)
15692 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15693 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
15694 (while (<= n2 cday)
15695 (setq n1 n2 m m2 y y2)
15696 (setq m2 (+ m dn) y2 y)
15697 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15698 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
15699 ;; Make sure n1 is the earlier date
15700 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
15701 (if show-all
15702 (cond
15703 ((eq prefer 'past) (if (= cday n2) n2 n1))
15704 ((eq prefer 'future) (if (= cday n1) n1 n2))
15705 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
15706 (cond
15707 ((eq prefer 'past) (if (= cday n2) n2 n1))
15708 ((eq prefer 'future) (if (= cday n1) n1 n2))
15709 (t (if (= cday n1) n1 n2)))))))
15711 (defun org-date-to-gregorian (date)
15712 "Turn any specification of DATE into a Gregorian date for the calendar."
15713 (cond ((integerp date) (calendar-gregorian-from-absolute date))
15714 ((and (listp date) (= (length date) 3)) date)
15715 ((stringp date)
15716 (setq date (org-parse-time-string date))
15717 (list (nth 4 date) (nth 3 date) (nth 5 date)))
15718 ((listp date)
15719 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
15721 (defun org-parse-time-string (s &optional nodefault)
15722 "Parse the standard Org-mode time string.
15723 This should be a lot faster than the normal `parse-time-string'.
15724 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
15725 hour and minute fields will be nil if not given."
15726 (if (string-match org-ts-regexp0 s)
15727 (list 0
15728 (if (or (match-beginning 8) (not nodefault))
15729 (string-to-number (or (match-string 8 s) "0")))
15730 (if (or (match-beginning 7) (not nodefault))
15731 (string-to-number (or (match-string 7 s) "0")))
15732 (string-to-number (match-string 4 s))
15733 (string-to-number (match-string 3 s))
15734 (string-to-number (match-string 2 s))
15735 nil nil nil)
15736 (error "Not a standard Org-mode time string: %s" s)))
15738 (defun org-timestamp-up (&optional arg)
15739 "Increase the date item at the cursor by one.
15740 If the cursor is on the year, change the year. If it is on the month,
15741 the day or the time, change that.
15742 With prefix ARG, change by that many units."
15743 (interactive "p")
15744 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
15746 (defun org-timestamp-down (&optional arg)
15747 "Decrease the date item at the cursor by one.
15748 If the cursor is on the year, change the year. If it is on the month,
15749 the day or the time, change that.
15750 With prefix ARG, change by that many units."
15751 (interactive "p")
15752 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
15754 (defun org-timestamp-up-day (&optional arg)
15755 "Increase the date in the time stamp by one day.
15756 With prefix ARG, change that many days."
15757 (interactive "p")
15758 (if (and (not (org-at-timestamp-p t))
15759 (org-on-heading-p))
15760 (org-todo 'up)
15761 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
15763 (defun org-timestamp-down-day (&optional arg)
15764 "Decrease the date in the time stamp by one day.
15765 With prefix ARG, change that many days."
15766 (interactive "p")
15767 (if (and (not (org-at-timestamp-p t))
15768 (org-on-heading-p))
15769 (org-todo 'down)
15770 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
15772 (defun org-at-timestamp-p (&optional inactive-ok)
15773 "Determine if the cursor is in or at a timestamp."
15774 (interactive)
15775 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
15776 (pos (point))
15777 (ans (or (looking-at tsr)
15778 (save-excursion
15779 (skip-chars-backward "^[<\n\r\t")
15780 (if (> (point) (point-min)) (backward-char 1))
15781 (and (looking-at tsr)
15782 (> (- (match-end 0) pos) -1))))))
15783 (and ans
15784 (boundp 'org-ts-what)
15785 (setq org-ts-what
15786 (cond
15787 ((= pos (match-beginning 0)) 'bracket)
15788 ;; Point is considered to be "on the bracket" whether
15789 ;; it's really on it or right after it.
15790 ((or (= pos (1- (match-end 0)))
15791 (= pos (match-end 0))) 'bracket)
15792 ((org-pos-in-match-range pos 2) 'year)
15793 ((org-pos-in-match-range pos 3) 'month)
15794 ((org-pos-in-match-range pos 7) 'hour)
15795 ((org-pos-in-match-range pos 8) 'minute)
15796 ((or (org-pos-in-match-range pos 4)
15797 (org-pos-in-match-range pos 5)) 'day)
15798 ((and (> pos (or (match-end 8) (match-end 5)))
15799 (< pos (match-end 0)))
15800 (- pos (or (match-end 8) (match-end 5))))
15801 (t 'day))))
15802 ans))
15804 (defun org-toggle-timestamp-type ()
15805 "Toggle the type (<active> or [inactive]) of a time stamp."
15806 (interactive)
15807 (when (org-at-timestamp-p t)
15808 (let ((beg (match-beginning 0)) (end (match-end 0))
15809 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
15810 (save-excursion
15811 (goto-char beg)
15812 (while (re-search-forward "[][<>]" end t)
15813 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
15814 t t)))
15815 (message "Timestamp is now %sactive"
15816 (if (equal (char-after beg) ?<) "" "in")))))
15818 (defun org-timestamp-change (n &optional what updown)
15819 "Change the date in the time stamp at point.
15820 The date will be changed by N times WHAT. WHAT can be `day', `month',
15821 `year', `minute', `second'. If WHAT is not given, the cursor position
15822 in the timestamp determines what will be changed."
15823 (let ((origin (point)) origin-cat
15824 with-hm inactive
15825 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
15826 org-ts-what
15827 extra rem
15828 ts time time0)
15829 (if (not (org-at-timestamp-p t))
15830 (error "Not at a timestamp"))
15831 (if (and (not what) (eq org-ts-what 'bracket))
15832 (org-toggle-timestamp-type)
15833 ;; Point isn't on brackets. Remember the part of the time-stamp
15834 ;; the point was in. Indeed, size of time-stamps may change,
15835 ;; but point must be kept in the same category nonetheless.
15836 (setq origin-cat org-ts-what)
15837 (if (and (not what) (not (eq org-ts-what 'day))
15838 org-display-custom-times
15839 (get-text-property (point) 'display)
15840 (not (get-text-property (1- (point)) 'display)))
15841 (setq org-ts-what 'day))
15842 (setq org-ts-what (or what org-ts-what)
15843 inactive (= (char-after (match-beginning 0)) ?\[)
15844 ts (match-string 0))
15845 (replace-match "")
15846 (if (string-match
15847 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
15849 (setq extra (match-string 1 ts)))
15850 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
15851 (setq with-hm t))
15852 (setq time0 (org-parse-time-string ts))
15853 (when (and updown
15854 (eq org-ts-what 'minute)
15855 (not current-prefix-arg))
15856 ;; This looks like s-up and s-down. Change by one rounding step.
15857 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
15858 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
15859 (setcar (cdr time0) (+ (nth 1 time0)
15860 (if (> n 0) (- rem) (- dm rem))))))
15861 (setq time
15862 (encode-time (or (car time0) 0)
15863 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
15864 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
15865 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
15866 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
15867 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
15868 (nthcdr 6 time0)))
15869 (when (and (member org-ts-what '(hour minute))
15870 extra
15871 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
15872 (setq extra (org-modify-ts-extra
15873 extra
15874 (if (eq org-ts-what 'hour) 2 5)
15875 n dm)))
15876 (when (integerp org-ts-what)
15877 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
15878 (if (eq what 'calendar)
15879 (let ((cal-date (org-get-date-from-calendar)))
15880 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
15881 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
15882 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
15883 (setcar time0 (or (car time0) 0))
15884 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
15885 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
15886 (setq time (apply 'encode-time time0))))
15887 ;; Insert the new time-stamp, and ensure point stays in the same
15888 ;; category as before (i.e. not after the last position in that
15889 ;; category).
15890 (let ((pos (point)))
15891 ;; Stay before inserted string. `save-excursion' is of no use.
15892 (setq org-last-changed-timestamp
15893 (org-insert-time-stamp time with-hm inactive nil nil extra))
15894 (goto-char pos))
15895 (save-match-data
15896 (looking-at org-ts-regexp3)
15897 (goto-char (cond
15898 ;; `day' category ends before `hour' if any, or at
15899 ;; the end of the day name.
15900 ((eq origin-cat 'day)
15901 (min (or (match-beginning 7) (1- (match-end 5))) origin))
15902 ((eq origin-cat 'hour) (min (match-end 7) origin))
15903 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
15904 ((integerp origin-cat) (min (1- (match-end 0)) origin))
15905 ;; `year' and `month' have both fixed size: point
15906 ;; couldn't have moved into another part.
15907 (t origin))))
15908 ;; Update clock if on a CLOCK line.
15909 (org-clock-update-time-maybe)
15910 ;; Try to recenter the calendar window, if any.
15911 (if (and org-calendar-follow-timestamp-change
15912 (get-buffer-window "*Calendar*" t)
15913 (memq org-ts-what '(day month year)))
15914 (org-recenter-calendar (time-to-days time))))))
15916 (defun org-modify-ts-extra (s pos n dm)
15917 "Change the different parts of the lead-time and repeat fields in timestamp."
15918 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
15919 ng h m new rem)
15920 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
15921 (cond
15922 ((or (org-pos-in-match-range pos 2)
15923 (org-pos-in-match-range pos 3))
15924 (setq m (string-to-number (match-string 3 s))
15925 h (string-to-number (match-string 2 s)))
15926 (if (org-pos-in-match-range pos 2)
15927 (setq h (+ h n))
15928 (setq n (* dm (org-no-warnings (signum n))))
15929 (when (not (= 0 (setq rem (% m dm))))
15930 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
15931 (setq m (+ m n)))
15932 (if (< m 0) (setq m (+ m 60) h (1- h)))
15933 (if (> m 59) (setq m (- m 60) h (1+ h)))
15934 (setq h (min 24 (max 0 h)))
15935 (setq ng 1 new (format "-%02d:%02d" h m)))
15936 ((org-pos-in-match-range pos 6)
15937 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
15938 ((org-pos-in-match-range pos 5)
15939 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
15941 ((org-pos-in-match-range pos 9)
15942 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
15943 ((org-pos-in-match-range pos 8)
15944 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
15946 (when ng
15947 (setq s (concat
15948 (substring s 0 (match-beginning ng))
15950 (substring s (match-end ng))))))
15953 (defun org-recenter-calendar (date)
15954 "If the calendar is visible, recenter it to DATE."
15955 (let* ((win (selected-window))
15956 (cwin (get-buffer-window "*Calendar*" t))
15957 (calendar-move-hook nil))
15958 (when cwin
15959 (select-window cwin)
15960 (calendar-goto-date (if (listp date) date
15961 (calendar-gregorian-from-absolute date)))
15962 (select-window win))))
15964 (defun org-goto-calendar (&optional arg)
15965 "Go to the Emacs calendar at the current date.
15966 If there is a time stamp in the current line, go to that date.
15967 A prefix ARG can be used to force the current date."
15968 (interactive "P")
15969 (let ((tsr org-ts-regexp) diff
15970 (calendar-move-hook nil)
15971 (calendar-view-holidays-initially-flag nil)
15972 (calendar-view-diary-initially-flag nil))
15973 (if (or (org-at-timestamp-p)
15974 (save-excursion
15975 (beginning-of-line 1)
15976 (looking-at (concat ".*" tsr))))
15977 (let ((d1 (time-to-days (current-time)))
15978 (d2 (time-to-days
15979 (org-time-string-to-time (match-string 1)))))
15980 (setq diff (- d2 d1))))
15981 (calendar)
15982 (calendar-goto-today)
15983 (if (and diff (not arg)) (calendar-forward-day diff))))
15985 (defun org-get-date-from-calendar ()
15986 "Return a list (month day year) of date at point in calendar."
15987 (with-current-buffer "*Calendar*"
15988 (save-match-data
15989 (calendar-cursor-to-date))))
15991 (defun org-date-from-calendar ()
15992 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
15993 If there is already a time stamp at the cursor position, update it."
15994 (interactive)
15995 (if (org-at-timestamp-p t)
15996 (org-timestamp-change 0 'calendar)
15997 (let ((cal-date (org-get-date-from-calendar)))
15998 (org-insert-time-stamp
15999 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16001 (defun org-minutes-to-hh:mm-string (m)
16002 "Compute H:MM from a number of minutes."
16003 (let ((h (/ m 60)))
16004 (setq m (- m (* 60 h)))
16005 (format org-time-clocksum-format h m)))
16007 (defun org-hh:mm-string-to-minutes (s)
16008 "Convert a string H:MM to a number of minutes.
16009 If the string is just a number, interpret it as minutes.
16010 In fact, the first hh:mm or number in the string will be taken,
16011 there can be extra stuff in the string.
16012 If no number is found, the return value is 0."
16013 (cond
16014 ((integerp s) s)
16015 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16016 (+ (* (string-to-number (match-string 1 s)) 60)
16017 (string-to-number (match-string 2 s))))
16018 ((string-match "\\([0-9]+\\)" s)
16019 (string-to-number (match-string 1 s)))
16020 (t 0)))
16022 (defcustom org-effort-durations
16023 `(("h" . 60)
16024 ("d" . ,(* 60 8))
16025 ("w" . ,(* 60 8 5))
16026 ("m" . ,(* 60 8 5 4))
16027 ("y" . ,(* 60 8 5 40)))
16028 "Conversion factor to minutes for an effort modifier.
16030 Each entry has the form (MODIFIER . MINUTES).
16032 In an effort string, a number followed by MODIFIER is multiplied
16033 by the specified number of MINUTES to obtain an effort in
16034 minutes.
16036 For example, if the value of this variable is ((\"hours\" . 60)), then an
16037 effort string \"2hours\" is equivalent to 120 minutes."
16038 :group 'org-agenda
16039 :type '(alist :key-type (string :tag "Modifier")
16040 :value-type (number :tag "Minutes")))
16042 (defun org-duration-string-to-minutes (s)
16043 "Convert a duration string S to minutes.
16045 A bare number is interpreted as minutes, modifiers can be set by
16046 customizing `org-effort-durations' (which see).
16048 Entries containing a colon are interpreted as H:MM by
16049 `org-hh:mm-string-to-minutes'."
16050 (let ((result 0)
16051 (re (concat "\\([0-9]+\\) *\\("
16052 (regexp-opt (mapcar 'car org-effort-durations))
16053 "\\)")))
16054 (while (string-match re s)
16055 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16056 (string-to-number (match-string 1 s))))
16057 (setq s (replace-match "" nil t s)))
16058 (incf result (org-hh:mm-string-to-minutes s))
16059 result))
16061 ;;;; Files
16063 (defun org-save-all-org-buffers ()
16064 "Save all Org-mode buffers without user confirmation."
16065 (interactive)
16066 (message "Saving all Org-mode buffers...")
16067 (save-some-buffers t (lambda () (eq major-mode 'org-mode)))
16068 (when (featurep 'org-id) (org-id-locations-save))
16069 (message "Saving all Org-mode buffers... done"))
16071 (defun org-revert-all-org-buffers ()
16072 "Revert all Org-mode buffers.
16073 Prompt for confirmation when there are unsaved changes.
16074 Be sure you know what you are doing before letting this function
16075 overwrite your changes.
16077 This function is useful in a setup where one tracks org files
16078 with a version control system, to revert on one machine after pulling
16079 changes from another. I believe the procedure must be like this:
16081 1. M-x org-save-all-org-buffers
16082 2. Pull changes from the other machine, resolve conflicts
16083 3. M-x org-revert-all-org-buffers"
16084 (interactive)
16085 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16086 (error "Abort"))
16087 (save-excursion
16088 (save-window-excursion
16089 (mapc
16090 (lambda (b)
16091 (when (and (with-current-buffer b (eq major-mode 'org-mode))
16092 (with-current-buffer b buffer-file-name))
16093 (org-pop-to-buffer-same-window b)
16094 (revert-buffer t 'no-confirm)))
16095 (buffer-list))
16096 (when (and (featurep 'org-id) org-id-track-globally)
16097 (org-id-locations-load)))))
16099 ;;;; Agenda files
16101 ;;;###autoload
16102 (defun org-switchb (&optional arg)
16103 "Switch between Org buffers.
16104 With one prefix argument, restrict available buffers to files.
16105 With two prefix arguments, restrict available buffers to agenda files.
16107 Defaults to `iswitchb' for buffer name completion.
16108 Set `org-completion-use-ido' to make it use ido instead."
16109 (interactive "P")
16110 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16111 ((equal arg '(16)) (org-buffer-list 'agenda))
16112 (t (org-buffer-list))))
16113 (org-completion-use-iswitchb org-completion-use-iswitchb)
16114 (org-completion-use-ido org-completion-use-ido))
16115 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16116 (setq org-completion-use-iswitchb t))
16117 (org-pop-to-buffer-same-window
16118 (org-icompleting-read "Org buffer: "
16119 (mapcar 'list (mapcar 'buffer-name blist))
16120 nil t))))
16122 ;;; Define some older names previously used for this functionality
16123 ;;;###autoload
16124 (defalias 'org-ido-switchb 'org-switchb)
16125 ;;;###autoload
16126 (defalias 'org-iswitchb 'org-switchb)
16128 (defun org-buffer-list (&optional predicate exclude-tmp)
16129 "Return a list of Org buffers.
16130 PREDICATE can be `export', `files' or `agenda'.
16132 export restrict the list to Export buffers.
16133 files restrict the list to buffers visiting Org files.
16134 agenda restrict the list to buffers visiting agenda files.
16136 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16137 (let* ((bfn nil)
16138 (agenda-files (and (eq predicate 'agenda)
16139 (mapcar 'file-truename (org-agenda-files t))))
16140 (filter
16141 (cond
16142 ((eq predicate 'files)
16143 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
16144 ((eq predicate 'export)
16145 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16146 ((eq predicate 'agenda)
16147 (lambda (b)
16148 (with-current-buffer b
16149 (and (eq major-mode 'org-mode)
16150 (setq bfn (buffer-file-name b))
16151 (member (file-truename bfn) agenda-files)))))
16152 (t (lambda (b) (with-current-buffer b
16153 (or (eq major-mode 'org-mode)
16154 (string-match "\*Org .*Export"
16155 (buffer-name b)))))))))
16156 (delq nil
16157 (mapcar
16158 (lambda(b)
16159 (if (and (funcall filter b)
16160 (or (not exclude-tmp)
16161 (not (string-match "tmp" (buffer-name b)))))
16163 nil))
16164 (buffer-list)))))
16166 (defun org-agenda-files (&optional unrestricted archives)
16167 "Get the list of agenda files.
16168 Optional UNRESTRICTED means return the full list even if a restriction
16169 is currently in place.
16170 When ARCHIVES is t, include all archive files that are really being
16171 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16172 `org-agenda-archives-mode' is t."
16173 (let ((files
16174 (cond
16175 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16176 ((stringp org-agenda-files) (org-read-agenda-file-list))
16177 ((listp org-agenda-files) org-agenda-files)
16178 (t (error "Invalid value of `org-agenda-files'")))))
16179 (setq files (apply 'append
16180 (mapcar (lambda (f)
16181 (if (file-directory-p f)
16182 (directory-files
16183 f t org-agenda-file-regexp)
16184 (list f)))
16185 files)))
16186 (when org-agenda-skip-unavailable-files
16187 (setq files (delq nil
16188 (mapcar (function
16189 (lambda (file)
16190 (and (file-readable-p file) file)))
16191 files))))
16192 (when (or (eq archives t)
16193 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16194 (setq files (org-add-archive-files files)))
16195 files))
16197 (defun org-agenda-file-p (&optional file)
16198 "Return non-nil, if FILE is an agenda file.
16199 If FILE is omitted, use the file associated with the current
16200 buffer."
16201 (member (or file (buffer-file-name))
16202 (org-agenda-files t)))
16204 (defun org-edit-agenda-file-list ()
16205 "Edit the list of agenda files.
16206 Depending on setup, this either uses customize to edit the variable
16207 `org-agenda-files', or it visits the file that is holding the list. In the
16208 latter case, the buffer is set up in a way that saving it automatically kills
16209 the buffer and restores the previous window configuration."
16210 (interactive)
16211 (if (stringp org-agenda-files)
16212 (let ((cw (current-window-configuration)))
16213 (find-file org-agenda-files)
16214 (org-set-local 'org-window-configuration cw)
16215 (org-add-hook 'after-save-hook
16216 (lambda ()
16217 (set-window-configuration
16218 (prog1 org-window-configuration
16219 (kill-buffer (current-buffer))))
16220 (org-install-agenda-files-menu)
16221 (message "New agenda file list installed"))
16222 nil 'local)
16223 (message "%s" (substitute-command-keys
16224 "Edit list and finish with \\[save-buffer]")))
16225 (customize-variable 'org-agenda-files)))
16227 (defun org-store-new-agenda-file-list (list)
16228 "Set new value for the agenda file list and save it correctly."
16229 (if (stringp org-agenda-files)
16230 (let ((fe (org-read-agenda-file-list t)) b u)
16231 (while (setq b (find-buffer-visiting org-agenda-files))
16232 (kill-buffer b))
16233 (with-temp-file org-agenda-files
16234 (insert
16235 (mapconcat
16236 (lambda (f) ;; Keep un-expanded entries.
16237 (if (setq u (assoc f fe))
16238 (cdr u)
16240 list "\n")
16241 "\n")))
16242 (let ((org-mode-hook nil) (org-inhibit-startup t)
16243 (org-insert-mode-line-in-empty-file nil))
16244 (setq org-agenda-files list)
16245 (customize-save-variable 'org-agenda-files org-agenda-files))))
16247 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16248 "Read the list of agenda files from a file.
16249 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16250 filenames, used by `org-store-new-agenda-file-list' to write back
16251 un-expanded file names."
16252 (when (file-directory-p org-agenda-files)
16253 (error "`org-agenda-files' cannot be a single directory"))
16254 (when (stringp org-agenda-files)
16255 (with-temp-buffer
16256 (insert-file-contents org-agenda-files)
16257 (mapcar
16258 (lambda (f)
16259 (let ((e (expand-file-name (substitute-in-file-name f)
16260 org-directory)))
16261 (if pair-with-expansion
16262 (cons e f)
16263 e)))
16264 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16266 ;;;###autoload
16267 (defun org-cycle-agenda-files ()
16268 "Cycle through the files in `org-agenda-files'.
16269 If the current buffer visits an agenda file, find the next one in the list.
16270 If the current buffer does not, find the first agenda file."
16271 (interactive)
16272 (let* ((fs (org-agenda-files t))
16273 (files (append fs (list (car fs))))
16274 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16275 file)
16276 (unless files (error "No agenda files"))
16277 (catch 'exit
16278 (while (setq file (pop files))
16279 (if (equal (file-truename file) tcf)
16280 (when (car files)
16281 (find-file (car files))
16282 (throw 'exit t))))
16283 (find-file (car fs)))
16284 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16286 (defun org-agenda-file-to-front (&optional to-end)
16287 "Move/add the current file to the top of the agenda file list.
16288 If the file is not present in the list, it is added to the front. If it is
16289 present, it is moved there. With optional argument TO-END, add/move to the
16290 end of the list."
16291 (interactive "P")
16292 (let ((org-agenda-skip-unavailable-files nil)
16293 (file-alist (mapcar (lambda (x)
16294 (cons (file-truename x) x))
16295 (org-agenda-files t)))
16296 (ctf (file-truename buffer-file-name))
16297 x had)
16298 (setq x (assoc ctf file-alist) had x)
16300 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16301 (if to-end
16302 (setq file-alist (append (delq x file-alist) (list x)))
16303 (setq file-alist (cons x (delq x file-alist))))
16304 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16305 (org-install-agenda-files-menu)
16306 (message "File %s to %s of agenda file list"
16307 (if had "moved" "added") (if to-end "end" "front"))))
16309 (defun org-remove-file (&optional file)
16310 "Remove current file from the list of files in variable `org-agenda-files'.
16311 These are the files which are being checked for agenda entries.
16312 Optional argument FILE means use this file instead of the current."
16313 (interactive)
16314 (let* ((org-agenda-skip-unavailable-files nil)
16315 (file (or file buffer-file-name))
16316 (true-file (file-truename file))
16317 (afile (abbreviate-file-name file))
16318 (files (delq nil (mapcar
16319 (lambda (x)
16320 (if (equal true-file
16321 (file-truename x))
16322 nil x))
16323 (org-agenda-files t)))))
16324 (if (not (= (length files) (length (org-agenda-files t))))
16325 (progn
16326 (org-store-new-agenda-file-list files)
16327 (org-install-agenda-files-menu)
16328 (message "Removed file: %s" afile))
16329 (message "File was not in list: %s (not removed)" afile))))
16331 (defun org-file-menu-entry (file)
16332 (vector file (list 'find-file file) t))
16334 (defun org-check-agenda-file (file)
16335 "Make sure FILE exists. If not, ask user what to do."
16336 (when (not (file-exists-p file))
16337 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16338 (abbreviate-file-name file))
16339 (let ((r (downcase (read-char-exclusive))))
16340 (cond
16341 ((equal r ?r)
16342 (org-remove-file file)
16343 (throw 'nextfile t))
16344 (t (error "Abort"))))))
16346 (defun org-get-agenda-file-buffer (file)
16347 "Get a buffer visiting FILE. If the buffer needs to be created, add
16348 it to the list of buffers which might be released later."
16349 (let ((buf (org-find-base-buffer-visiting file)))
16350 (if buf
16351 buf ; just return it
16352 ;; Make a new buffer and remember it
16353 (setq buf (find-file-noselect file))
16354 (if buf (push buf org-agenda-new-buffers))
16355 buf)))
16357 (defun org-release-buffers (blist)
16358 "Release all buffers in list, asking the user for confirmation when needed.
16359 When a buffer is unmodified, it is just killed. When modified, it is saved
16360 \(if the user agrees) and then killed."
16361 (let (buf file)
16362 (while (setq buf (pop blist))
16363 (setq file (buffer-file-name buf))
16364 (when (and (buffer-modified-p buf)
16365 file
16366 (y-or-n-p (format "Save file %s? " file)))
16367 (with-current-buffer buf (save-buffer)))
16368 (kill-buffer buf))))
16370 (defun org-prepare-agenda-buffers (files)
16371 "Create buffers for all agenda files, protect archived trees and comments."
16372 (interactive)
16373 (let ((pa '(:org-archived t))
16374 (pc '(:org-comment t))
16375 (pall '(:org-archived t :org-comment t))
16376 (inhibit-read-only t)
16377 (rea (concat ":" org-archive-tag ":"))
16378 bmp file re)
16379 (save-excursion
16380 (save-restriction
16381 (while (setq file (pop files))
16382 (catch 'nextfile
16383 (if (bufferp file)
16384 (set-buffer file)
16385 (org-check-agenda-file file)
16386 (set-buffer (org-get-agenda-file-buffer file)))
16387 (widen)
16388 (setq bmp (buffer-modified-p))
16389 (org-refresh-category-properties)
16390 (setq org-todo-keywords-for-agenda
16391 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16392 (setq org-done-keywords-for-agenda
16393 (append org-done-keywords-for-agenda org-done-keywords))
16394 (setq org-todo-keyword-alist-for-agenda
16395 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16396 (setq org-drawers-for-agenda
16397 (append org-drawers-for-agenda org-drawers))
16398 (setq org-tag-alist-for-agenda
16399 (append org-tag-alist-for-agenda org-tag-alist))
16401 (save-excursion
16402 (remove-text-properties (point-min) (point-max) pall)
16403 (when org-agenda-skip-archived-trees
16404 (goto-char (point-min))
16405 (while (re-search-forward rea nil t)
16406 (if (org-on-heading-p t)
16407 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16408 (goto-char (point-min))
16409 (setq re (format org-heading-keyword-regexp-format
16410 org-comment-string))
16411 (while (re-search-forward re nil t)
16412 (add-text-properties
16413 (match-beginning 0) (org-end-of-subtree t) pc)))
16414 (set-buffer-modified-p bmp)))))
16415 (setq org-todo-keywords-for-agenda
16416 (org-uniquify org-todo-keywords-for-agenda))
16417 (setq org-todo-keyword-alist-for-agenda
16418 (org-uniquify org-todo-keyword-alist-for-agenda)
16419 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16421 ;;;; Embedded LaTeX
16423 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16424 "Keymap for the minor `org-cdlatex-mode'.")
16426 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16427 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16428 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16429 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16430 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16432 (defvar org-cdlatex-texmathp-advice-is-done nil
16433 "Flag remembering if we have applied the advice to texmathp already.")
16435 (define-minor-mode org-cdlatex-mode
16436 "Toggle the minor `org-cdlatex-mode'.
16437 This mode supports entering LaTeX environment and math in LaTeX fragments
16438 in Org-mode.
16439 \\{org-cdlatex-mode-map}"
16440 nil " OCDL" nil
16441 (when org-cdlatex-mode
16442 (require 'cdlatex)
16443 (run-hooks 'cdlatex-mode-hook)
16444 (cdlatex-compute-tables))
16445 (unless org-cdlatex-texmathp-advice-is-done
16446 (setq org-cdlatex-texmathp-advice-is-done t)
16447 (defadvice texmathp (around org-math-always-on activate)
16448 "Always return t in org-mode buffers.
16449 This is because we want to insert math symbols without dollars even outside
16450 the LaTeX math segments. If Orgmode thinks that point is actually inside
16451 an embedded LaTeX fragment, let texmathp do its job.
16452 \\[org-cdlatex-mode-map]"
16453 (interactive)
16454 (let (p)
16455 (cond
16456 ((not (eq major-mode 'org-mode)) ad-do-it)
16457 ((eq this-command 'cdlatex-math-symbol)
16458 (setq ad-return-value t
16459 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16461 (let ((p (org-inside-LaTeX-fragment-p)))
16462 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16463 (setq ad-return-value t
16464 texmathp-why '("Org-mode embedded math" . 0))
16465 (if p ad-do-it)))))))))
16467 (defun turn-on-org-cdlatex ()
16468 "Unconditionally turn on `org-cdlatex-mode'."
16469 (org-cdlatex-mode 1))
16471 (defun org-inside-LaTeX-fragment-p ()
16472 "Test if point is inside a LaTeX fragment.
16473 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16474 sequence appearing also before point.
16475 Even though the matchers for math are configurable, this function assumes
16476 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16477 delimiters are skipped when they have been removed by customization.
16478 The return value is nil, or a cons cell with the delimiter and the
16479 position of this delimiter.
16481 This function does a reasonably good job, but can locally be fooled by
16482 for example currency specifications. For example it will assume being in
16483 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16484 fragments that are properly closed, but during editing, we have to live
16485 with the uncertainty caused by missing closing delimiters. This function
16486 looks only before point, not after."
16487 (catch 'exit
16488 (let ((pos (point))
16489 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16490 (lim (progn
16491 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16492 (point)))
16493 dd-on str (start 0) m re)
16494 (goto-char pos)
16495 (when dodollar
16496 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16497 re (nth 1 (assoc "$" org-latex-regexps)))
16498 (while (string-match re str start)
16499 (cond
16500 ((= (match-end 0) (length str))
16501 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16502 ((= (match-end 0) (- (length str) 5))
16503 (throw 'exit nil))
16504 (t (setq start (match-end 0))))))
16505 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16506 (goto-char pos)
16507 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16508 (and (match-beginning 2) (throw 'exit nil))
16509 ;; count $$
16510 (while (re-search-backward "\\$\\$" lim t)
16511 (setq dd-on (not dd-on)))
16512 (goto-char pos)
16513 (if dd-on (cons "$$" m))))))
16515 (defun org-inside-latex-macro-p ()
16516 "Is point inside a LaTeX macro or its arguments?"
16517 (save-match-data
16518 (org-in-regexp
16519 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16521 (defun org-try-cdlatex-tab ()
16522 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16523 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16524 - inside a LaTeX fragment, or
16525 - after the first word in a line, where an abbreviation expansion could
16526 insert a LaTeX environment."
16527 (when org-cdlatex-mode
16528 (cond
16529 ((save-excursion
16530 (skip-chars-backward "a-zA-Z0-9*")
16531 (skip-chars-backward " \t")
16532 (bolp))
16533 (cdlatex-tab) t)
16534 ((org-inside-LaTeX-fragment-p)
16535 (cdlatex-tab) t)
16536 (t nil))))
16538 (defun org-cdlatex-underscore-caret (&optional arg)
16539 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16540 Revert to the normal definition outside of these fragments."
16541 (interactive "P")
16542 (if (org-inside-LaTeX-fragment-p)
16543 (call-interactively 'cdlatex-sub-superscript)
16544 (let (org-cdlatex-mode)
16545 (call-interactively (key-binding (vector last-input-event))))))
16547 (defun org-cdlatex-math-modify (&optional arg)
16548 "Execute `cdlatex-math-modify' in LaTeX fragments.
16549 Revert to the normal definition outside of these fragments."
16550 (interactive "P")
16551 (if (org-inside-LaTeX-fragment-p)
16552 (call-interactively 'cdlatex-math-modify)
16553 (let (org-cdlatex-mode)
16554 (call-interactively (key-binding (vector last-input-event))))))
16556 (defvar org-latex-fragment-image-overlays nil
16557 "List of overlays carrying the images of latex fragments.")
16558 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16560 (defun org-remove-latex-fragment-image-overlays ()
16561 "Remove all overlays with LaTeX fragment images in current buffer."
16562 (mapc 'delete-overlay org-latex-fragment-image-overlays)
16563 (setq org-latex-fragment-image-overlays nil))
16565 (defun org-preview-latex-fragment (&optional subtree)
16566 "Preview the LaTeX fragment at point, or all locally or globally.
16567 If the cursor is in a LaTeX fragment, create the image and overlay
16568 it over the source code. If there is no fragment at point, display
16569 all fragments in the current text, from one headline to the next. With
16570 prefix SUBTREE, display all fragments in the current subtree. With a
16571 double prefix arg \\[universal-argument] \\[universal-argument], or when \
16572 the cursor is before the first headline,
16573 display all fragments in the buffer.
16574 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16575 (interactive "P")
16576 (org-remove-latex-fragment-image-overlays)
16577 (save-excursion
16578 (save-restriction
16579 (let (beg end at msg)
16580 (cond
16581 ((or (equal subtree '(16))
16582 (not (save-excursion
16583 (re-search-backward org-outline-regexp-bol nil t))))
16584 (setq beg (point-min) end (point-max)
16585 msg "Creating images for buffer...%s"))
16586 ((equal subtree '(4))
16587 (org-back-to-heading)
16588 (setq beg (point) end (org-end-of-subtree t)
16589 msg "Creating images for subtree...%s"))
16591 (if (setq at (org-inside-LaTeX-fragment-p))
16592 (goto-char (max (point-min) (- (cdr at) 2)))
16593 (org-back-to-heading))
16594 (setq beg (point) end (progn (outline-next-heading) (point))
16595 msg (if at "Creating image...%s"
16596 "Creating images for entry...%s"))))
16597 (message msg "")
16598 (narrow-to-region beg end)
16599 (goto-char beg)
16600 (org-format-latex
16601 (concat "ltxpng/" (file-name-sans-extension
16602 (file-name-nondirectory
16603 buffer-file-name)))
16604 default-directory 'overlays msg at 'forbuffer 'dvipng)
16605 (message msg "done. Use `C-c C-c' to remove images.")))))
16607 (defvar org-latex-regexps
16608 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16609 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16610 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16611 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16612 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16613 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16614 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
16615 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
16616 "Regular expressions for matching embedded LaTeX.")
16618 (defvar org-export-have-math nil) ;; dynamic scoping
16619 (defun org-format-latex (prefix &optional dir overlays msg at
16620 forbuffer processing-type)
16621 "Replace LaTeX fragments with links to an image, and produce images.
16622 Some of the options can be changed using the variable
16623 `org-format-latex-options'."
16624 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16625 (let* ((prefixnodir (file-name-nondirectory prefix))
16626 (absprefix (expand-file-name prefix dir))
16627 (todir (file-name-directory absprefix))
16628 (opt org-format-latex-options)
16629 (matchers (plist-get opt :matchers))
16630 (re-list org-latex-regexps)
16631 (org-format-latex-header-extra
16632 (plist-get (org-infile-export-plist) :latex-header-extra))
16633 (cnt 0) txt hash link beg end re e checkdir
16634 executables-checked string
16635 m n block-type block linkfile movefile ov)
16636 ;; Check the different regular expressions
16637 (while (setq e (pop re-list))
16638 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
16639 block (if block-type "\n\n" ""))
16640 (when (member m matchers)
16641 (goto-char (point-min))
16642 (while (re-search-forward re nil t)
16643 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
16644 (not (get-text-property (match-beginning n)
16645 'org-protected))
16646 (or (not overlays)
16647 (not (eq (get-char-property (match-beginning n)
16648 'org-overlay-type)
16649 'org-latex-overlay))))
16650 (setq org-export-have-math t)
16651 (cond
16652 ((eq processing-type 'verbatim)
16653 ;; Leave the text verbatim, just protect it
16654 (add-text-properties (match-beginning n) (match-end n)
16655 '(org-protected t)))
16656 ((eq processing-type 'mathjax)
16657 ;; Prepare for MathJax processing
16658 (setq string (match-string n))
16659 (if (member m '("$" "$1"))
16660 (save-excursion
16661 (delete-region (match-beginning n) (match-end n))
16662 (goto-char (match-beginning n))
16663 (insert (org-add-props (concat "\\(" (substring string 1 -1)
16664 "\\)")
16665 '(org-protected t))))
16666 (add-text-properties (match-beginning n) (match-end n)
16667 '(org-protected t))))
16668 ((eq processing-type 'dvipng)
16669 ;; Process to an image
16670 (setq txt (match-string n)
16671 beg (match-beginning n) end (match-end n)
16672 cnt (1+ cnt))
16673 (let (print-length print-level) ; make sure full list is printed
16674 (setq hash (sha1 (prin1-to-string
16675 (list org-format-latex-header
16676 org-format-latex-header-extra
16677 org-export-latex-default-packages-alist
16678 org-export-latex-packages-alist
16679 org-format-latex-options
16680 forbuffer txt)))
16681 linkfile (format "%s_%s.png" prefix hash)
16682 movefile (format "%s_%s.png" absprefix hash)))
16683 (setq link (concat block "[[file:" linkfile "]]" block))
16684 (if msg (message msg cnt))
16685 (goto-char beg)
16686 (unless checkdir ; make sure the directory exists
16687 (setq checkdir t)
16688 (or (file-directory-p todir) (make-directory todir t)))
16690 (unless executables-checked
16691 (org-check-external-command
16692 "latex" "needed to convert LaTeX fragments to images")
16693 (org-check-external-command
16694 "dvipng" "needed to convert LaTeX fragments to images")
16695 (setq executables-checked t))
16697 (unless (file-exists-p movefile)
16698 (org-create-formula-image
16699 txt movefile opt forbuffer))
16700 (if overlays
16701 (progn
16702 (mapc (lambda (o)
16703 (if (eq (overlay-get o 'org-overlay-type)
16704 'org-latex-overlay)
16705 (delete-overlay o)))
16706 (overlays-in beg end))
16707 (setq ov (make-overlay beg end))
16708 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
16709 (if (featurep 'xemacs)
16710 (progn
16711 (overlay-put ov 'invisible t)
16712 (overlay-put
16713 ov 'end-glyph
16714 (make-glyph (vector 'png :file movefile))))
16715 (overlay-put
16716 ov 'display
16717 (list 'image :type 'png :file movefile :ascent 'center)))
16718 (push ov org-latex-fragment-image-overlays)
16719 (goto-char end))
16720 (delete-region beg end)
16721 (insert (org-add-props link
16722 (list 'org-latex-src
16723 (replace-regexp-in-string
16724 "\"" "" txt)
16725 'org-latex-src-embed-type
16726 (if block-type 'paragraph 'character))))))
16727 ((eq processing-type 'mathml)
16728 ;; Process to MathML
16729 (unless executables-checked
16730 (unless (save-match-data (org-format-latex-mathml-available-p))
16731 (error "LaTeX to MathML converter not configured"))
16732 (setq executables-checked t))
16733 (setq txt (match-string n)
16734 beg (match-beginning n) end (match-end n)
16735 cnt (1+ cnt))
16736 (if msg (message msg cnt))
16737 (goto-char beg)
16738 (delete-region beg end)
16739 (insert (org-format-latex-as-mathml
16740 txt block-type prefix dir)))
16742 (error "Unknown conversion type %s for latex fragments"
16743 processing-type)))))))))
16745 (defun org-create-math-formula (latex-frag &optional mathml-file)
16746 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
16747 Use `org-latex-to-mathml-convert-command'. If the conversion is
16748 sucessful, return the portion between \"<math...> </math>\"
16749 elements otherwise return nil. When MATHML-FILE is specified,
16750 write the results in to that file. When invoked as an
16751 interactive command, prompt for LATEX-FRAG, with initial value
16752 set to the current active region and echo the results for user
16753 inspection."
16754 (interactive (list (let ((frag (when (region-active-p)
16755 (buffer-substring-no-properties
16756 (region-beginning) (region-end)))))
16757 (read-string "LaTeX Fragment: " frag nil frag))))
16758 (unless latex-frag (error "Invalid latex-frag"))
16759 (let* ((tmp-in-file (file-relative-name
16760 (make-temp-name (expand-file-name "ltxmathml-in"))))
16761 (ignore (write-region latex-frag nil tmp-in-file))
16762 (tmp-out-file (file-relative-name
16763 (make-temp-name (expand-file-name "ltxmathml-out"))))
16764 (cmd (format-spec
16765 org-latex-to-mathml-convert-command
16766 `((?j . ,(shell-quote-argument
16767 (expand-file-name org-latex-to-mathml-jar-file)))
16768 (?I . ,(shell-quote-argument tmp-in-file))
16769 (?o . ,(shell-quote-argument tmp-out-file)))))
16770 mathml shell-command-output)
16771 (when (org-called-interactively-p 'any)
16772 (unless (org-format-latex-mathml-available-p)
16773 (error "LaTeX to MathML converter not configured")))
16774 (message "Running %s" cmd)
16775 (setq shell-command-output (shell-command-to-string cmd))
16776 (setq mathml
16777 (when (file-readable-p tmp-out-file)
16778 (with-current-buffer (find-file-noselect tmp-out-file t)
16779 (goto-char (point-min))
16780 (when (re-search-forward
16781 (concat
16782 (regexp-quote
16783 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
16784 "\\(.\\|\n\\)*"
16785 (regexp-quote "</math>")) nil t)
16786 (prog1 (match-string 0) (kill-buffer))))))
16787 (cond
16788 (mathml
16789 (setq mathml
16790 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
16791 (when mathml-file
16792 (write-region mathml nil mathml-file))
16793 (when (org-called-interactively-p 'any)
16794 (message mathml)))
16795 ((message "LaTeX to MathML conversion failed")
16796 (message shell-command-output)))
16797 (delete-file tmp-in-file)
16798 (when (file-exists-p tmp-out-file)
16799 (delete-file tmp-out-file))
16800 mathml))
16802 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
16803 prefix &optional dir)
16804 "Use `org-create-math-formula' but check local cache first."
16805 (let* ((absprefix (expand-file-name prefix dir))
16806 (print-length nil) (print-level nil)
16807 (formula-id (concat
16808 "formula-"
16809 (sha1
16810 (prin1-to-string
16811 (list latex-frag
16812 org-latex-to-mathml-convert-command)))))
16813 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
16814 (formula-cache-dir (file-name-directory formula-cache)))
16816 (unless (file-directory-p formula-cache-dir)
16817 (make-directory formula-cache-dir t))
16819 (unless (file-exists-p formula-cache)
16820 (org-create-math-formula latex-frag formula-cache))
16822 (if (file-exists-p formula-cache)
16823 ;; Successful conversion. Return the link to MathML file.
16824 (org-add-props
16825 (format "[[file:%s]]" (file-relative-name formula-cache dir))
16826 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
16827 'org-latex-src-embed-type (if latex-frag-type
16828 'paragraph 'character)))
16829 ;; Failed conversion. Return the LaTeX fragment verbatim
16830 (add-text-properties
16831 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
16832 latex-frag)))
16834 ;; This function borrows from Ganesh Swami's latex2png.el
16835 (defun org-create-formula-image (string tofile options buffer)
16836 "This calls dvipng."
16837 (require 'org-latex)
16838 (let* ((tmpdir (if (featurep 'xemacs)
16839 (temp-directory)
16840 temporary-file-directory))
16841 (texfilebase (make-temp-name
16842 (expand-file-name "orgtex" tmpdir)))
16843 (texfile (concat texfilebase ".tex"))
16844 (dvifile (concat texfilebase ".dvi"))
16845 (pngfile (concat texfilebase ".png"))
16846 (fnh (if (featurep 'xemacs)
16847 (font-height (get-face-font 'default))
16848 (face-attribute 'default :height nil)))
16849 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
16850 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
16851 (fg (or (plist-get options (if buffer :foreground :html-foreground))
16852 "Black"))
16853 (bg (or (plist-get options (if buffer :background :html-background))
16854 "Transparent")))
16855 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
16856 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
16857 (with-temp-file texfile
16858 (insert (org-splice-latex-header
16859 org-format-latex-header
16860 org-export-latex-default-packages-alist
16861 org-export-latex-packages-alist t
16862 org-format-latex-header-extra))
16863 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
16864 (require 'org-latex)
16865 (org-export-latex-fix-inputenc))
16866 (let ((dir default-directory))
16867 (condition-case nil
16868 (progn
16869 (cd tmpdir)
16870 (call-process "latex" nil nil nil texfile))
16871 (error nil))
16872 (cd dir))
16873 (if (not (file-exists-p dvifile))
16874 (progn (message "Failed to create dvi file from %s" texfile) nil)
16875 (condition-case nil
16876 (call-process "dvipng" nil nil nil
16877 "-fg" fg "-bg" bg
16878 "-D" dpi
16879 ;;"-x" scale "-y" scale
16880 "-T" "tight"
16881 "-o" pngfile
16882 dvifile)
16883 (error nil))
16884 (if (not (file-exists-p pngfile))
16885 (if org-format-latex-signal-error
16886 (error "Failed to create png file from %s" texfile)
16887 (message "Failed to create png file from %s" texfile)
16888 nil)
16889 ;; Use the requested file name and clean up
16890 (copy-file pngfile tofile 'replace)
16891 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
16892 (delete-file (concat texfilebase e)))
16893 pngfile))))
16895 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
16896 "Fill a LaTeX header template TPL.
16897 In the template, the following place holders will be recognized:
16899 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
16900 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
16901 [PACKAGES] \\usepackage statements for PKG
16902 [NO-PACKAGES] do not include PKG
16903 [EXTRA] the string EXTRA
16904 [NO-EXTRA] do not include EXTRA
16906 For backward compatibility, if both the positive and the negative place
16907 holder is missing, the positive one (without the \"NO-\") will be
16908 assumed to be present at the end of the template.
16909 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
16910 EXTRA is a string.
16911 SNIPPETS-P indicates if this is run to create snippet images for HTML."
16912 (let (rpl (end ""))
16913 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
16914 (setq rpl (if (or (match-end 1) (not def-pkg))
16915 "" (org-latex-packages-to-string def-pkg snippets-p t))
16916 tpl (replace-match rpl t t tpl))
16917 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
16919 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
16920 (setq rpl (if (or (match-end 1) (not pkg))
16921 "" (org-latex-packages-to-string pkg snippets-p t))
16922 tpl (replace-match rpl t t tpl))
16923 (if pkg (setq end
16924 (concat end "\n"
16925 (org-latex-packages-to-string pkg snippets-p)))))
16927 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
16928 (setq rpl (if (or (match-end 1) (not extra))
16929 "" (concat extra "\n"))
16930 tpl (replace-match rpl t t tpl))
16931 (if (and extra (string-match "\\S-" extra))
16932 (setq end (concat end "\n" extra))))
16934 (if (string-match "\\S-" end)
16935 (concat tpl "\n" end)
16936 tpl)))
16938 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
16939 "Turn an alist of packages into a string with the \\usepackage macros."
16940 (setq pkg (mapconcat (lambda(p)
16941 (cond
16942 ((stringp p) p)
16943 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
16944 (format "%% Package %s omitted" (cadr p)))
16945 ((equal "" (car p))
16946 (format "\\usepackage{%s}" (cadr p)))
16948 (format "\\usepackage[%s]{%s}"
16949 (car p) (cadr p)))))
16951 "\n"))
16952 (if newline (concat pkg "\n") pkg))
16954 (defun org-dvipng-color (attr)
16955 "Return an rgb color specification for dvipng."
16956 (apply 'format "rgb %s %s %s"
16957 (mapcar 'org-normalize-color
16958 (color-values (face-attribute 'default attr nil)))))
16960 (defun org-normalize-color (value)
16961 "Return string to be used as color value for an RGB component."
16962 (format "%g" (/ value 65535.0)))
16964 ;; Image display
16967 (defvar org-inline-image-overlays nil)
16968 (make-variable-buffer-local 'org-inline-image-overlays)
16970 (defun org-toggle-inline-images (&optional include-linked)
16971 "Toggle the display of inline images.
16972 INCLUDE-LINKED is passed to `org-display-inline-images'."
16973 (interactive "P")
16974 (if org-inline-image-overlays
16975 (progn
16976 (org-remove-inline-images)
16977 (message "Inline image display turned off"))
16978 (org-display-inline-images include-linked)
16979 (if org-inline-image-overlays
16980 (message "%d images displayed inline"
16981 (length org-inline-image-overlays))
16982 (message "No images to display inline"))))
16984 (defun org-display-inline-images (&optional include-linked refresh beg end)
16985 "Display inline images.
16986 Normally only links without a description part are inlined, because this
16987 is how it will work for export. When INCLUDE-LINKED is set, also links
16988 with a description part will be inlined. This can be nice for a quick
16989 look at those images, but it does not reflect what exported files will look
16990 like.
16991 When REFRESH is set, refresh existing images between BEG and END.
16992 This will create new image displays only if necessary.
16993 BEG and END default to the buffer boundaries."
16994 (interactive "P")
16995 (unless refresh
16996 (org-remove-inline-images)
16997 (if (fboundp 'clear-image-cache) (clear-image-cache)))
16998 (save-excursion
16999 (save-restriction
17000 (widen)
17001 (setq beg (or beg (point-min)) end (or end (point-max)))
17002 (goto-char (point-min))
17003 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17004 (substring (org-image-file-name-regexp) 0 -2)
17005 "\\)\\]" (if include-linked "" "\\]")))
17006 old file ov img)
17007 (while (re-search-forward re end t)
17008 (setq old (get-char-property-and-overlay (match-beginning 1)
17009 'org-image-overlay))
17010 (setq file (expand-file-name
17011 (concat (or (match-string 3) "") (match-string 4))))
17012 (when (file-exists-p file)
17013 (if (and (car-safe old) refresh)
17014 (image-refresh (overlay-get (cdr old) 'display))
17015 (setq img (save-match-data (create-image file)))
17016 (when img
17017 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17018 (overlay-put ov 'display img)
17019 (overlay-put ov 'face 'default)
17020 (overlay-put ov 'org-image-overlay t)
17021 (overlay-put ov 'modification-hooks
17022 (list 'org-display-inline-modification-hook))
17023 (push ov org-inline-image-overlays)))))))))
17025 (defun org-display-inline-modification-hook (ov after beg end &optional len)
17026 "Remove inline-display overlay if a corresponding region is modified."
17027 (let ((inhibit-modification-hooks t))
17028 (when (and ov after)
17029 (delete ov org-inline-image-overlays)
17030 (delete-overlay ov))))
17032 (defun org-remove-inline-images ()
17033 "Remove inline display of images."
17034 (interactive)
17035 (mapc 'delete-overlay org-inline-image-overlays)
17036 (setq org-inline-image-overlays nil))
17038 ;;;; Key bindings
17040 ;; Remap outline keys
17041 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17042 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17044 ;; Make `C-c C-x' a prefix key
17045 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17047 ;; TAB key with modifiers
17048 (org-defkey org-mode-map "\C-i" 'org-cycle)
17049 (org-defkey org-mode-map [(tab)] 'org-cycle)
17050 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17051 (org-defkey org-mode-map [(meta tab)] 'pcomplete)
17052 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17053 (org-defkey org-mode-map "\M-\C-i" 'pcomplete)
17054 ;; The following line is necessary under Suse GNU/Linux
17055 (unless (featurep 'xemacs)
17056 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17057 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17058 (define-key org-mode-map [backtab] 'org-shifttab)
17060 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17061 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17062 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17064 ;; Cursor keys with modifiers
17065 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17066 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17067 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17068 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17070 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17071 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17072 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17073 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17075 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17076 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17077 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17078 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17080 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17081 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17082 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17083 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17085 ;; Babel keys
17086 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17087 (mapc (lambda (pair)
17088 (define-key org-babel-map (car pair) (cdr pair)))
17089 org-babel-key-bindings)
17091 ;;; Extra keys for tty access.
17092 ;; We only set them when really needed because otherwise the
17093 ;; menus don't show the simple keys
17095 (when (or org-use-extra-keys
17096 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17097 (not window-system))
17098 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17099 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17100 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17101 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17102 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17103 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17104 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17105 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17106 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17107 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17108 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17109 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17110 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17111 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17112 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17113 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17114 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17115 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17116 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17117 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17118 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17119 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17120 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17121 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17122 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17123 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17124 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17125 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17127 ;; All the other keys
17129 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17130 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17131 (if (boundp 'narrow-map)
17132 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17133 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17134 (if (boundp 'narrow-map)
17135 (org-defkey narrow-map "b" 'org-narrow-to-block)
17136 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17137 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
17138 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
17139 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17140 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17141 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17142 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17143 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17144 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17145 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17146 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17147 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17148 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17149 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17150 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17151 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17152 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17153 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17154 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17155 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17156 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17157 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17158 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17159 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
17160 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
17161 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
17162 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
17163 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
17164 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
17165 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
17166 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
17167 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17168 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17169 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17170 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17171 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
17172 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
17173 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17174 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
17175 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
17176 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
17177 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
17178 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17179 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
17180 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
17181 (org-defkey org-mode-map "\C-c^" 'org-sort)
17182 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
17183 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
17184 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
17185 (org-defkey org-mode-map "\C-m" 'org-return)
17186 (org-defkey org-mode-map "\C-j" 'org-return-indent)
17187 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
17188 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
17189 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
17190 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
17191 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
17192 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
17193 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
17194 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
17195 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
17196 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
17197 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
17198 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
17199 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
17200 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
17201 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
17202 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
17203 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
17204 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
17205 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
17206 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
17207 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
17209 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
17210 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
17211 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
17212 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
17214 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
17215 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
17216 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
17217 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
17218 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
17219 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
17220 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
17221 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
17222 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
17223 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
17224 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
17225 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
17226 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
17227 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
17228 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
17229 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
17230 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
17231 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
17233 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
17234 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
17235 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
17236 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
17237 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
17239 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
17241 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
17243 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
17244 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
17246 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
17249 (when (featurep 'xemacs)
17250 (org-defkey org-mode-map 'button3 'popup-mode-menu))
17253 (defconst org-speed-commands-default
17255 ("Outline Navigation")
17256 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
17257 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
17258 ("f" . (org-speed-move-safe 'org-forward-same-level))
17259 ("b" . (org-speed-move-safe 'org-backward-same-level))
17260 ("u" . (org-speed-move-safe 'outline-up-heading))
17261 ("j" . org-goto)
17262 ("g" . (org-refile t))
17263 ("Outline Visibility")
17264 ("c" . org-cycle)
17265 ("C" . org-shifttab)
17266 (" " . org-display-outline-path)
17267 ("Outline Structure Editing")
17268 ("U" . org-shiftmetaup)
17269 ("D" . org-shiftmetadown)
17270 ("r" . org-metaright)
17271 ("l" . org-metaleft)
17272 ("R" . org-shiftmetaright)
17273 ("L" . org-shiftmetaleft)
17274 ("i" . (progn (forward-char 1) (call-interactively
17275 'org-insert-heading-respect-content)))
17276 ("^" . org-sort)
17277 ("w" . org-refile)
17278 ("a" . org-archive-subtree-default-with-confirmation)
17279 ("." . org-mark-subtree)
17280 ("Clock Commands")
17281 ("I" . org-clock-in)
17282 ("O" . org-clock-out)
17283 ("Meta Data Editing")
17284 ("t" . org-todo)
17285 ("0" . (org-priority ?\ ))
17286 ("1" . (org-priority ?A))
17287 ("2" . (org-priority ?B))
17288 ("3" . (org-priority ?C))
17289 (";" . org-set-tags-command)
17290 ("e" . org-set-effort)
17291 ("Agenda Views etc")
17292 ("v" . org-agenda)
17293 ("/" . org-sparse-tree)
17294 ("Misc")
17295 ("o" . org-open-at-point)
17296 ("?" . org-speed-command-help)
17297 ("<" . (org-agenda-set-restriction-lock 'subtree))
17298 (">" . (org-agenda-remove-restriction-lock))
17300 "The default speed commands.")
17302 (defun org-print-speed-command (e)
17303 (if (> (length (car e)) 1)
17304 (progn
17305 (princ "\n")
17306 (princ (car e))
17307 (princ "\n")
17308 (princ (make-string (length (car e)) ?-))
17309 (princ "\n"))
17310 (princ (car e))
17311 (princ " ")
17312 (if (symbolp (cdr e))
17313 (princ (symbol-name (cdr e)))
17314 (prin1 (cdr e)))
17315 (princ "\n")))
17317 (defun org-speed-command-help ()
17318 "Show the available speed commands."
17319 (interactive)
17320 (if (not org-use-speed-commands)
17321 (error "Speed commands are not activated, customize `org-use-speed-commands'")
17322 (with-output-to-temp-buffer "*Help*"
17323 (princ "User-defined Speed commands\n===========================\n")
17324 (mapc 'org-print-speed-command org-speed-commands-user)
17325 (princ "\n")
17326 (princ "Built-in Speed commands\n=======================\n")
17327 (mapc 'org-print-speed-command org-speed-commands-default))
17328 (with-current-buffer "*Help*"
17329 (setq truncate-lines t))))
17331 (defun org-speed-move-safe (cmd)
17332 "Execute CMD, but make sure that the cursor always ends up in a headline.
17333 If not, return to the original position and throw an error."
17334 (interactive)
17335 (let ((pos (point)))
17336 (call-interactively cmd)
17337 (unless (and (bolp) (org-on-heading-p))
17338 (goto-char pos)
17339 (error "Boundary reached while executing %s" cmd))))
17341 (defvar org-self-insert-command-undo-counter 0)
17343 (defvar org-table-auto-blank-field) ; defined in org-table.el
17344 (defvar org-speed-command nil)
17346 (defun org-speed-command-default-hook (keys)
17347 "Hook for activating single-letter speed commands.
17348 `org-speed-commands-default' specifies a minimal command set.
17349 Use `org-speed-commands-user' for further customization."
17350 (when (or (and (bolp) (looking-at org-outline-regexp))
17351 (and (functionp org-use-speed-commands)
17352 (funcall org-use-speed-commands)))
17353 (cdr (assoc keys (append org-speed-commands-user
17354 org-speed-commands-default)))))
17356 (defun org-babel-speed-command-hook (keys)
17357 "Hook for activating single-letter code block commands."
17358 (when (and (bolp) (looking-at org-babel-src-block-regexp))
17359 (cdr (assoc keys org-babel-key-bindings))))
17361 (defcustom org-speed-command-hook
17362 '(org-speed-command-default-hook org-babel-speed-command-hook)
17363 "Hook for activating speed commands at strategic locations.
17364 Hook functions are called in sequence until a valid handler is
17365 found.
17367 Each hook takes a single argument, a user-pressed command key
17368 which is also a `self-insert-command' from the global map.
17370 Within the hook, examine the cursor position and the command key
17371 and return nil or a valid handler as appropriate. Handler could
17372 be one of an interactive command, a function, or a form.
17374 Set `org-use-speed-commands' to non-nil value to enable this
17375 hook. The default setting is `org-speed-command-default-hook'."
17376 :group 'org-structure
17377 :type 'hook)
17379 (defun org-self-insert-command (N)
17380 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
17381 If the cursor is in a table looking at whitespace, the whitespace is
17382 overwritten, and the table is not marked as requiring realignment."
17383 (interactive "p")
17384 (cond
17385 ((and org-use-speed-commands
17386 (setq org-speed-command
17387 (run-hook-with-args-until-success
17388 'org-speed-command-hook (this-command-keys))))
17389 (cond
17390 ((commandp org-speed-command)
17391 (setq this-command org-speed-command)
17392 (call-interactively org-speed-command))
17393 ((functionp org-speed-command)
17394 (funcall org-speed-command))
17395 ((and org-speed-command (listp org-speed-command))
17396 (eval org-speed-command))
17397 (t (let (org-use-speed-commands)
17398 (call-interactively 'org-self-insert-command)))))
17399 ((and
17400 (org-table-p)
17401 (progn
17402 ;; check if we blank the field, and if that triggers align
17403 (and (featurep 'org-table) org-table-auto-blank-field
17404 (member last-command
17405 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
17406 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
17407 ;; got extra space, this field does not determine column width
17408 (let (org-table-may-need-update) (org-table-blank-field))
17409 ;; no extra space, this field may determine column width
17410 (org-table-blank-field)))
17412 (eq N 1)
17413 (looking-at "[^|\n]* |"))
17414 (let (org-table-may-need-update)
17415 (goto-char (1- (match-end 0)))
17416 (delete-char -1)
17417 (goto-char (match-beginning 0))
17418 (self-insert-command N)))
17420 (setq org-table-may-need-update t)
17421 (self-insert-command N)
17422 (org-fix-tags-on-the-fly)
17423 (if org-self-insert-cluster-for-undo
17424 (if (not (eq last-command 'org-self-insert-command))
17425 (setq org-self-insert-command-undo-counter 1)
17426 (if (>= org-self-insert-command-undo-counter 20)
17427 (setq org-self-insert-command-undo-counter 1)
17428 (and (> org-self-insert-command-undo-counter 0)
17429 buffer-undo-list (listp buffer-undo-list)
17430 (not (cadr buffer-undo-list)) ; remove nil entry
17431 (setcdr buffer-undo-list (cddr buffer-undo-list)))
17432 (setq org-self-insert-command-undo-counter
17433 (1+ org-self-insert-command-undo-counter))))))))
17435 (defun org-fix-tags-on-the-fly ()
17436 (when (and (equal (char-after (point-at-bol)) ?*)
17437 (org-on-heading-p))
17438 (org-align-tags-here org-tags-column)))
17440 (defun org-delete-backward-char (N)
17441 "Like `delete-backward-char', insert whitespace at field end in tables.
17442 When deleting backwards, in tables this function will insert whitespace in
17443 front of the next \"|\" separator, to keep the table aligned. The table will
17444 still be marked for re-alignment if the field did fill the entire column,
17445 because, in this case the deletion might narrow the column."
17446 (interactive "p")
17447 (if (and (org-table-p)
17448 (eq N 1)
17449 (string-match "|" (buffer-substring (point-at-bol) (point)))
17450 (looking-at ".*?|"))
17451 (let ((pos (point))
17452 (noalign (looking-at "[^|\n\r]* |"))
17453 (c org-table-may-need-update))
17454 (backward-delete-char N)
17455 (if (not overwrite-mode)
17456 (progn
17457 (skip-chars-forward "^|")
17458 (insert " ")
17459 (goto-char (1- pos))))
17460 ;; noalign: if there were two spaces at the end, this field
17461 ;; does not determine the width of the column.
17462 (if noalign (setq org-table-may-need-update c)))
17463 (backward-delete-char N)
17464 (org-fix-tags-on-the-fly)))
17466 (defun org-delete-char (N)
17467 "Like `delete-char', but insert whitespace at field end in tables.
17468 When deleting characters, in tables this function will insert whitespace in
17469 front of the next \"|\" separator, to keep the table aligned. The table will
17470 still be marked for re-alignment if the field did fill the entire column,
17471 because, in this case the deletion might narrow the column."
17472 (interactive "p")
17473 (if (and (org-table-p)
17474 (not (bolp))
17475 (not (= (char-after) ?|))
17476 (eq N 1))
17477 (if (looking-at ".*?|")
17478 (let ((pos (point))
17479 (noalign (looking-at "[^|\n\r]* |"))
17480 (c org-table-may-need-update))
17481 (replace-match (concat
17482 (substring (match-string 0) 1 -1)
17483 " |"))
17484 (goto-char pos)
17485 ;; noalign: if there were two spaces at the end, this field
17486 ;; does not determine the width of the column.
17487 (if noalign (setq org-table-may-need-update c)))
17488 (delete-char N))
17489 (delete-char N)
17490 (org-fix-tags-on-the-fly)))
17492 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
17493 (put 'org-self-insert-command 'delete-selection t)
17494 (put 'orgtbl-self-insert-command 'delete-selection t)
17495 (put 'org-delete-char 'delete-selection 'supersede)
17496 (put 'org-delete-backward-char 'delete-selection 'supersede)
17497 (put 'org-yank 'delete-selection 'yank)
17499 ;; Make `flyspell-mode' delay after some commands
17500 (put 'org-self-insert-command 'flyspell-delayed t)
17501 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
17502 (put 'org-delete-char 'flyspell-delayed t)
17503 (put 'org-delete-backward-char 'flyspell-delayed t)
17505 ;; Make pabbrev-mode expand after org-mode commands
17506 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
17507 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
17509 ;; How to do this: Measure non-white length of current string
17510 ;; If equal to column width, we should realign.
17512 (defun org-remap (map &rest commands)
17513 "In MAP, remap the functions given in COMMANDS.
17514 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
17515 (let (new old)
17516 (while commands
17517 (setq old (pop commands) new (pop commands))
17518 (if (fboundp 'command-remapping)
17519 (org-defkey map (vector 'remap old) new)
17520 (substitute-key-definition old new map global-map)))))
17522 (when (eq org-enable-table-editor 'optimized)
17523 ;; If the user wants maximum table support, we need to hijack
17524 ;; some standard editing functions
17525 (org-remap org-mode-map
17526 'self-insert-command 'org-self-insert-command
17527 'delete-char 'org-delete-char
17528 'delete-backward-char 'org-delete-backward-char)
17529 (org-defkey org-mode-map "|" 'org-force-self-insert))
17531 (defvar org-ctrl-c-ctrl-c-hook nil
17532 "Hook for functions attaching themselves to `C-c C-c'.
17534 This can be used to add additional functionality to the C-c C-c
17535 key which executes context-dependent commands. This hook is run
17536 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
17537 run after the last test.
17539 Each function will be called with no arguments. The function
17540 must check if the context is appropriate for it to act. If yes,
17541 it should do its thing and then return a non-nil value. If the
17542 context is wrong, just do nothing and return nil.")
17544 (defvar org-ctrl-c-ctrl-c-final-hook nil
17545 "Hook for functions attaching themselves to `C-c C-c'.
17547 This can be used to add additional functionality to the C-c C-c
17548 key which executes context-dependent commands. This hook is run
17549 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
17550 before the first test.
17552 Each function will be called with no arguments. The function
17553 must check if the context is appropriate for it to act. If yes,
17554 it should do its thing and then return a non-nil value. If the
17555 context is wrong, just do nothing and return nil.")
17557 (defvar org-tab-first-hook nil
17558 "Hook for functions to attach themselves to TAB.
17559 See `org-ctrl-c-ctrl-c-hook' for more information.
17560 This hook runs as the first action when TAB is pressed, even before
17561 `org-cycle' messes around with the `outline-regexp' to cater for
17562 inline tasks and plain list item folding.
17563 If any function in this hook returns t, any other actions that
17564 would have been caused by TAB (such as table field motion or visibility
17565 cycling) will not occur.")
17567 (defvar org-tab-after-check-for-table-hook nil
17568 "Hook for functions to attach themselves to TAB.
17569 See `org-ctrl-c-ctrl-c-hook' for more information.
17570 This hook runs after it has been established that the cursor is not in a
17571 table, but before checking if the cursor is in a headline or if global cycling
17572 should be done.
17573 If any function in this hook returns t, not other actions like visibility
17574 cycling will be done.")
17576 (defvar org-tab-after-check-for-cycling-hook nil
17577 "Hook for functions to attach themselves to TAB.
17578 See `org-ctrl-c-ctrl-c-hook' for more information.
17579 This hook runs after it has been established that not table field motion and
17580 not visibility should be done because of current context. This is probably
17581 the place where a package like yasnippets can hook in.")
17583 (defvar org-tab-before-tab-emulation-hook nil
17584 "Hook for functions to attach themselves to TAB.
17585 See `org-ctrl-c-ctrl-c-hook' for more information.
17586 This hook runs after every other options for TAB have been exhausted, but
17587 before indentation and \t insertion takes place.")
17589 (defvar org-metaleft-hook nil
17590 "Hook for functions attaching themselves to `M-left'.
17591 See `org-ctrl-c-ctrl-c-hook' for more information.")
17592 (defvar org-metaright-hook nil
17593 "Hook for functions attaching themselves to `M-right'.
17594 See `org-ctrl-c-ctrl-c-hook' for more information.")
17595 (defvar org-metaup-hook nil
17596 "Hook for functions attaching themselves to `M-up'.
17597 See `org-ctrl-c-ctrl-c-hook' for more information.")
17598 (defvar org-metadown-hook nil
17599 "Hook for functions attaching themselves to `M-down'.
17600 See `org-ctrl-c-ctrl-c-hook' for more information.")
17601 (defvar org-shiftmetaleft-hook nil
17602 "Hook for functions attaching themselves to `M-S-left'.
17603 See `org-ctrl-c-ctrl-c-hook' for more information.")
17604 (defvar org-shiftmetaright-hook nil
17605 "Hook for functions attaching themselves to `M-S-right'.
17606 See `org-ctrl-c-ctrl-c-hook' for more information.")
17607 (defvar org-shiftmetaup-hook nil
17608 "Hook for functions attaching themselves to `M-S-up'.
17609 See `org-ctrl-c-ctrl-c-hook' for more information.")
17610 (defvar org-shiftmetadown-hook nil
17611 "Hook for functions attaching themselves to `M-S-down'.
17612 See `org-ctrl-c-ctrl-c-hook' for more information.")
17613 (defvar org-metareturn-hook nil
17614 "Hook for functions attaching themselves to `M-RET'.
17615 See `org-ctrl-c-ctrl-c-hook' for more information.")
17616 (defvar org-shiftup-hook nil
17617 "Hook for functions attaching themselves to `S-up'.
17618 See `org-ctrl-c-ctrl-c-hook' for more information.")
17619 (defvar org-shiftup-final-hook nil
17620 "Hook for functions attaching themselves to `S-up'.
17621 This one runs after all other options except shift-select have been excluded.
17622 See `org-ctrl-c-ctrl-c-hook' for more information.")
17623 (defvar org-shiftdown-hook nil
17624 "Hook for functions attaching themselves to `S-down'.
17625 See `org-ctrl-c-ctrl-c-hook' for more information.")
17626 (defvar org-shiftdown-final-hook nil
17627 "Hook for functions attaching themselves to `S-down'.
17628 This one runs after all other options except shift-select have been excluded.
17629 See `org-ctrl-c-ctrl-c-hook' for more information.")
17630 (defvar org-shiftleft-hook nil
17631 "Hook for functions attaching themselves to `S-left'.
17632 See `org-ctrl-c-ctrl-c-hook' for more information.")
17633 (defvar org-shiftleft-final-hook nil
17634 "Hook for functions attaching themselves to `S-left'.
17635 This one runs after all other options except shift-select have been excluded.
17636 See `org-ctrl-c-ctrl-c-hook' for more information.")
17637 (defvar org-shiftright-hook nil
17638 "Hook for functions attaching themselves to `S-right'.
17639 See `org-ctrl-c-ctrl-c-hook' for more information.")
17640 (defvar org-shiftright-final-hook nil
17641 "Hook for functions attaching themselves to `S-right'.
17642 This one runs after all other options except shift-select have been excluded.
17643 See `org-ctrl-c-ctrl-c-hook' for more information.")
17645 (defun org-modifier-cursor-error ()
17646 "Throw an error, a modified cursor command was applied in wrong context."
17647 (error "This command is active in special context like tables, headlines or items"))
17649 (defun org-shiftselect-error ()
17650 "Throw an error because Shift-Cursor command was applied in wrong context."
17651 (if (and (boundp 'shift-select-mode) shift-select-mode)
17652 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
17653 (error "This command works only in special context like headlines or timestamps")))
17655 (defun org-call-for-shift-select (cmd)
17656 (let ((this-command-keys-shift-translated t))
17657 (call-interactively cmd)))
17659 (defun org-shifttab (&optional arg)
17660 "Global visibility cycling or move to previous table field.
17661 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
17662 on context.
17663 See the individual commands for more information."
17664 (interactive "P")
17665 (cond
17666 ((org-at-table-p) (call-interactively 'org-table-previous-field))
17667 ((integerp arg)
17668 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
17669 (message "Content view to level: %d" arg)
17670 (org-content (prefix-numeric-value arg2))
17671 (setq org-cycle-global-status 'overview)))
17672 (t (call-interactively 'org-global-cycle))))
17674 (defun org-shiftmetaleft ()
17675 "Promote subtree or delete table column.
17676 Calls `org-promote-subtree', `org-outdent-item',
17677 or `org-table-delete-column', depending on context.
17678 See the individual commands for more information."
17679 (interactive)
17680 (cond
17681 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
17682 ((org-at-table-p) (call-interactively 'org-table-delete-column))
17683 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
17684 ((org-at-item-p) (call-interactively 'org-outdent-item-tree))
17685 (t (org-modifier-cursor-error))))
17687 (defun org-shiftmetaright ()
17688 "Demote subtree or insert table column.
17689 Calls `org-demote-subtree', `org-indent-item',
17690 or `org-table-insert-column', depending on context.
17691 See the individual commands for more information."
17692 (interactive)
17693 (cond
17694 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
17695 ((org-at-table-p) (call-interactively 'org-table-insert-column))
17696 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
17697 ((org-at-item-p) (call-interactively 'org-indent-item-tree))
17698 (t (org-modifier-cursor-error))))
17700 (defun org-shiftmetaup (&optional arg)
17701 "Move subtree up or kill table row.
17702 Calls `org-move-subtree-up' or `org-table-kill-row' or
17703 `org-move-item-up' depending on context. See the individual commands
17704 for more information."
17705 (interactive "P")
17706 (cond
17707 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
17708 ((org-at-table-p) (call-interactively 'org-table-kill-row))
17709 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17710 ((org-at-item-p) (call-interactively 'org-move-item-up))
17711 (t (org-modifier-cursor-error))))
17713 (defun org-shiftmetadown (&optional arg)
17714 "Move subtree down or insert table row.
17715 Calls `org-move-subtree-down' or `org-table-insert-row' or
17716 `org-move-item-down', depending on context. See the individual
17717 commands for more information."
17718 (interactive "P")
17719 (cond
17720 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
17721 ((org-at-table-p) (call-interactively 'org-table-insert-row))
17722 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17723 ((org-at-item-p) (call-interactively 'org-move-item-down))
17724 (t (org-modifier-cursor-error))))
17726 (defsubst org-hidden-tree-error ()
17727 (error
17728 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
17730 (defun org-metaleft (&optional arg)
17731 "Promote heading or move table column to left.
17732 Calls `org-do-promote' or `org-table-move-column', depending on context.
17733 With no specific context, calls the Emacs default `backward-word'.
17734 See the individual commands for more information."
17735 (interactive "P")
17736 (cond
17737 ((run-hook-with-args-until-success 'org-metaleft-hook))
17738 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
17739 ((org-with-limited-levels
17740 (or (org-on-heading-p)
17741 (and (org-region-active-p)
17742 (save-excursion
17743 (goto-char (region-beginning))
17744 (org-on-heading-p)))))
17745 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17746 (call-interactively 'org-do-promote))
17747 ;; At an inline task.
17748 ((org-on-heading-p)
17749 (call-interactively 'org-inlinetask-promote))
17750 ((or (org-at-item-p)
17751 (and (org-region-active-p)
17752 (save-excursion
17753 (goto-char (region-beginning))
17754 (org-at-item-p))))
17755 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17756 (call-interactively 'org-outdent-item))
17757 (t (call-interactively 'backward-word))))
17759 (defun org-metaright (&optional arg)
17760 "Demote subtree or move table column to right.
17761 Calls `org-do-demote' or `org-table-move-column', depending on context.
17762 With no specific context, calls the Emacs default `forward-word'.
17763 See the individual commands for more information."
17764 (interactive "P")
17765 (cond
17766 ((run-hook-with-args-until-success 'org-metaright-hook))
17767 ((org-at-table-p) (call-interactively 'org-table-move-column))
17768 ((org-with-limited-levels
17769 (or (org-on-heading-p)
17770 (and (org-region-active-p)
17771 (save-excursion
17772 (goto-char (region-beginning))
17773 (org-on-heading-p)))))
17774 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17775 (call-interactively 'org-do-demote))
17776 ;; At an inline task.
17777 ((org-on-heading-p)
17778 (call-interactively 'org-inlinetask-demote))
17779 ((or (org-at-item-p)
17780 (and (org-region-active-p)
17781 (save-excursion
17782 (goto-char (region-beginning))
17783 (org-at-item-p))))
17784 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17785 (call-interactively 'org-indent-item))
17786 (t (call-interactively 'forward-word))))
17788 (defun org-check-for-hidden (what)
17789 "Check if there are hidden headlines/items in the current visual line.
17790 WHAT can be either `headlines' or `items'. If the current line is
17791 an outline or item heading and it has a folded subtree below it,
17792 this function returns t, nil otherwise."
17793 (let ((re (cond
17794 ((eq what 'headlines) org-outline-regexp-bol)
17795 ((eq what 'items) (org-item-beginning-re))
17796 (t (error "This should not happen"))))
17797 beg end)
17798 (save-excursion
17799 (catch 'exit
17800 (unless (org-region-active-p)
17801 (setq beg (point-at-bol))
17802 (beginning-of-line 2)
17803 (while (and (not (eobp)) ;; this is like `next-line'
17804 (get-char-property (1- (point)) 'invisible))
17805 (beginning-of-line 2))
17806 (setq end (point))
17807 (goto-char beg)
17808 (goto-char (point-at-eol))
17809 (setq end (max end (point)))
17810 (while (re-search-forward re end t)
17811 (if (get-char-property (match-beginning 0) 'invisible)
17812 (throw 'exit t))))
17813 nil))))
17815 (defun org-metaup (&optional arg)
17816 "Move subtree up or move table row up.
17817 Calls `org-move-subtree-up' or `org-table-move-row' or
17818 `org-move-item-up', depending on context. See the individual commands
17819 for more information."
17820 (interactive "P")
17821 (cond
17822 ((run-hook-with-args-until-success 'org-metaup-hook))
17823 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
17824 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17825 ((org-at-item-p) (call-interactively 'org-move-item-up))
17826 (t (transpose-lines 1) (beginning-of-line -1))))
17828 (defun org-metadown (&optional arg)
17829 "Move subtree down or move table row down.
17830 Calls `org-move-subtree-down' or `org-table-move-row' or
17831 `org-move-item-down', depending on context. See the individual
17832 commands for more information."
17833 (interactive "P")
17834 (cond
17835 ((run-hook-with-args-until-success 'org-metadown-hook))
17836 ((org-at-table-p) (call-interactively 'org-table-move-row))
17837 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17838 ((org-at-item-p) (call-interactively 'org-move-item-down))
17839 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
17841 (defun org-shiftup (&optional arg)
17842 "Increase item in timestamp or increase priority of current headline.
17843 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
17844 depending on context. See the individual commands for more information."
17845 (interactive "P")
17846 (cond
17847 ((run-hook-with-args-until-success 'org-shiftup-hook))
17848 ((and org-support-shift-select (org-region-active-p))
17849 (org-call-for-shift-select 'previous-line))
17850 ((org-at-timestamp-p t)
17851 (call-interactively (if org-edit-timestamp-down-means-later
17852 'org-timestamp-down 'org-timestamp-up)))
17853 ((and (not (eq org-support-shift-select 'always))
17854 org-enable-priority-commands
17855 (org-on-heading-p))
17856 (call-interactively 'org-priority-up))
17857 ((and (not org-support-shift-select) (org-at-item-p))
17858 (call-interactively 'org-previous-item))
17859 ((org-clocktable-try-shift 'up arg))
17860 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
17861 (org-support-shift-select
17862 (org-call-for-shift-select 'previous-line))
17863 (t (org-shiftselect-error))))
17865 (defun org-shiftdown (&optional arg)
17866 "Decrease item in timestamp or decrease priority of current headline.
17867 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
17868 depending on context. See the individual commands for more information."
17869 (interactive "P")
17870 (cond
17871 ((run-hook-with-args-until-success 'org-shiftdown-hook))
17872 ((and org-support-shift-select (org-region-active-p))
17873 (org-call-for-shift-select 'next-line))
17874 ((org-at-timestamp-p t)
17875 (call-interactively (if org-edit-timestamp-down-means-later
17876 'org-timestamp-up 'org-timestamp-down)))
17877 ((and (not (eq org-support-shift-select 'always))
17878 org-enable-priority-commands
17879 (org-on-heading-p))
17880 (call-interactively 'org-priority-down))
17881 ((and (not org-support-shift-select) (org-at-item-p))
17882 (call-interactively 'org-next-item))
17883 ((org-clocktable-try-shift 'down arg))
17884 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
17885 (org-support-shift-select
17886 (org-call-for-shift-select 'next-line))
17887 (t (org-shiftselect-error))))
17889 (defun org-shiftright (&optional arg)
17890 "Cycle the thing at point or in the current line, depending on context.
17891 Depending on context, this does one of the following:
17893 - switch a timestamp at point one day into the future
17894 - on a headline, switch to the next TODO keyword.
17895 - on an item, switch entire list to the next bullet type
17896 - on a property line, switch to the next allowed value
17897 - on a clocktable definition line, move time block into the future"
17898 (interactive "P")
17899 (cond
17900 ((run-hook-with-args-until-success 'org-shiftright-hook))
17901 ((and org-support-shift-select (org-region-active-p))
17902 (org-call-for-shift-select 'forward-char))
17903 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
17904 ((and (not (eq org-support-shift-select 'always))
17905 (org-on-heading-p))
17906 (let ((org-inhibit-logging
17907 (not org-treat-S-cursor-todo-selection-as-state-change))
17908 (org-inhibit-blocking
17909 (not org-treat-S-cursor-todo-selection-as-state-change)))
17910 (org-call-with-arg 'org-todo 'right)))
17911 ((or (and org-support-shift-select
17912 (not (eq org-support-shift-select 'always))
17913 (org-at-item-bullet-p))
17914 (and (not org-support-shift-select) (org-at-item-p)))
17915 (org-call-with-arg 'org-cycle-list-bullet nil))
17916 ((and (not (eq org-support-shift-select 'always))
17917 (org-at-property-p))
17918 (call-interactively 'org-property-next-allowed-value))
17919 ((org-clocktable-try-shift 'right arg))
17920 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
17921 (org-support-shift-select
17922 (org-call-for-shift-select 'forward-char))
17923 (t (org-shiftselect-error))))
17925 (defun org-shiftleft (&optional arg)
17926 "Cycle the thing at point or in the current line, depending on context.
17927 Depending on context, this does one of the following:
17929 - switch a timestamp at point one day into the past
17930 - on a headline, switch to the previous TODO keyword.
17931 - on an item, switch entire list to the previous bullet type
17932 - on a property line, switch to the previous allowed value
17933 - on a clocktable definition line, move time block into the past"
17934 (interactive "P")
17935 (cond
17936 ((run-hook-with-args-until-success 'org-shiftleft-hook))
17937 ((and org-support-shift-select (org-region-active-p))
17938 (org-call-for-shift-select 'backward-char))
17939 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
17940 ((and (not (eq org-support-shift-select 'always))
17941 (org-on-heading-p))
17942 (let ((org-inhibit-logging
17943 (not org-treat-S-cursor-todo-selection-as-state-change))
17944 (org-inhibit-blocking
17945 (not org-treat-S-cursor-todo-selection-as-state-change)))
17946 (org-call-with-arg 'org-todo 'left)))
17947 ((or (and org-support-shift-select
17948 (not (eq org-support-shift-select 'always))
17949 (org-at-item-bullet-p))
17950 (and (not org-support-shift-select) (org-at-item-p)))
17951 (org-call-with-arg 'org-cycle-list-bullet 'previous))
17952 ((and (not (eq org-support-shift-select 'always))
17953 (org-at-property-p))
17954 (call-interactively 'org-property-previous-allowed-value))
17955 ((org-clocktable-try-shift 'left arg))
17956 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
17957 (org-support-shift-select
17958 (org-call-for-shift-select 'backward-char))
17959 (t (org-shiftselect-error))))
17961 (defun org-shiftcontrolright ()
17962 "Switch to next TODO set."
17963 (interactive)
17964 (cond
17965 ((and org-support-shift-select (org-region-active-p))
17966 (org-call-for-shift-select 'forward-word))
17967 ((and (not (eq org-support-shift-select 'always))
17968 (org-on-heading-p))
17969 (org-call-with-arg 'org-todo 'nextset))
17970 (org-support-shift-select
17971 (org-call-for-shift-select 'forward-word))
17972 (t (org-shiftselect-error))))
17974 (defun org-shiftcontrolleft ()
17975 "Switch to previous TODO set."
17976 (interactive)
17977 (cond
17978 ((and org-support-shift-select (org-region-active-p))
17979 (org-call-for-shift-select 'backward-word))
17980 ((and (not (eq org-support-shift-select 'always))
17981 (org-on-heading-p))
17982 (org-call-with-arg 'org-todo 'previousset))
17983 (org-support-shift-select
17984 (org-call-for-shift-select 'backward-word))
17985 (t (org-shiftselect-error))))
17987 (defun org-shiftcontrolup ()
17988 "Change timestamps synchronously up in CLOCK log lines."
17989 (interactive)
17990 (cond ((and (not org-support-shift-select)
17991 (org-at-clock-log-p)
17992 (org-at-timestamp-p t))
17993 (org-clock-timestamps-up))
17994 (t (org-shiftselect-error))))
17996 (defun org-shiftcontroldown ()
17997 "Change timestamps synchronously down in CLOCK log lines."
17998 (interactive)
17999 (cond ((and (not org-support-shift-select)
18000 (org-at-clock-log-p)
18001 (org-at-timestamp-p t))
18002 (org-clock-timestamps-down))
18003 (t (org-shiftselect-error))))
18005 (defun org-ctrl-c-ret ()
18006 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18007 (interactive)
18008 (cond
18009 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18010 (t (call-interactively 'org-insert-heading))))
18012 (defun org-find-visible ()
18013 (let ((s (point)))
18014 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18015 (get-char-property s 'invisible)))
18017 (defun org-find-invisible ()
18018 (let ((s (point)))
18019 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18020 (not (get-char-property s 'invisible))))
18023 (defun org-copy-visible (beg end)
18024 "Copy the visible parts of the region."
18025 (interactive "r")
18026 (let (snippets s)
18027 (save-excursion
18028 (save-restriction
18029 (narrow-to-region beg end)
18030 (setq s (goto-char (point-min)))
18031 (while (not (= (point) (point-max)))
18032 (goto-char (org-find-invisible))
18033 (push (buffer-substring s (point)) snippets)
18034 (setq s (goto-char (org-find-visible))))))
18035 (kill-new (apply 'concat (nreverse snippets)))))
18037 (defun org-copy-special ()
18038 "Copy region in table or copy current subtree.
18039 Calls `org-table-copy' or `org-copy-subtree', depending on context.
18040 See the individual commands for more information."
18041 (interactive)
18042 (call-interactively
18043 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
18045 (defun org-cut-special ()
18046 "Cut region in table or cut current subtree.
18047 Calls `org-table-copy' or `org-cut-subtree', depending on context.
18048 See the individual commands for more information."
18049 (interactive)
18050 (call-interactively
18051 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
18053 (defun org-paste-special (arg)
18054 "Paste rectangular region into table, or past subtree relative to level.
18055 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
18056 See the individual commands for more information."
18057 (interactive "P")
18058 (if (org-at-table-p)
18059 (org-table-paste-rectangle)
18060 (org-paste-subtree arg)))
18062 (defun org-edit-special (&optional arg)
18063 "Call a special editor for the stuff at point.
18064 When at a table, call the formula editor with `org-table-edit-formulas'.
18065 When at the first line of an src example, call `org-edit-src-code'.
18066 When in an #+include line, visit the include file. Otherwise call
18067 `ffap' to visit the file at point."
18068 (interactive)
18069 ;; possibly prep session before editing source
18070 (when arg
18071 (let* ((info (org-babel-get-src-block-info))
18072 (lang (nth 0 info))
18073 (params (nth 2 info))
18074 (session (cdr (assoc :session params))))
18075 (when (and info session) ;; we are in a source-code block with a session
18076 (funcall
18077 (intern (concat "org-babel-prep-session:" lang)) session params))))
18078 (cond ;; proceed with `org-edit-special'
18079 ((save-excursion
18080 (beginning-of-line 1)
18081 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
18082 (find-file (org-trim (match-string 1))))
18083 ((org-edit-src-code))
18084 ((org-edit-fixed-width-region))
18085 ((org-at-table.el-p)
18086 (org-edit-src-code))
18087 ((or (org-at-table-p)
18088 (save-excursion
18089 (beginning-of-line 1)
18090 (looking-at "[ \t]*#\\+TBLFM:")))
18091 (call-interactively 'org-table-edit-formulas))
18092 (t (call-interactively 'ffap))))
18094 (defvar org-table-coordinate-overlays) ; defined in org-table.el
18095 (defun org-ctrl-c-ctrl-c (&optional arg)
18096 "Set tags in headline, or update according to changed information at point.
18098 This command does many different things, depending on context:
18100 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
18101 this is what we do.
18103 - If the cursor is on a statistics cookie, update it.
18105 - If the cursor is in a headline, prompt for tags and insert them
18106 into the current line, aligned to `org-tags-column'. When called
18107 with prefix arg, realign all tags in the current buffer.
18109 - If the cursor is in one of the special #+KEYWORD lines, this
18110 triggers scanning the buffer for these lines and updating the
18111 information.
18113 - If the cursor is inside a table, realign the table. This command
18114 works even if the automatic table editor has been turned off.
18116 - If the cursor is on a #+TBLFM line, re-apply the formulas to
18117 the entire table.
18119 - If the cursor is at a footnote reference or definition, jump to
18120 the corresponding definition or references, respectively.
18122 - If the cursor is a the beginning of a dynamic block, update it.
18124 - If the current buffer is a capture buffer, close note and file it.
18126 - If the cursor is on a <<<target>>>, update radio targets and
18127 corresponding links in this buffer.
18129 - If the cursor is on a numbered item in a plain list, renumber the
18130 ordered list.
18132 - If the cursor is on a checkbox, toggle it.
18134 - If the cursor is on a code block, evaluate it. The variable
18135 `org-confirm-babel-evaluate' can be used to control prompting
18136 before code block evaluation, by default every code block
18137 evaluation requires confirmation. Code block evaluation can be
18138 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
18139 (interactive "P")
18140 (let ((org-enable-table-editor t))
18141 (cond
18142 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
18143 org-occur-highlights
18144 org-latex-fragment-image-overlays)
18145 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
18146 (org-remove-occur-highlights)
18147 (org-remove-latex-fragment-image-overlays)
18148 (message "Temporary highlights/overlays removed from current buffer"))
18149 ((and (local-variable-p 'org-finish-function (current-buffer))
18150 (fboundp org-finish-function))
18151 (funcall org-finish-function))
18152 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
18153 ((or (looking-at org-property-start-re)
18154 (org-at-property-p))
18155 (call-interactively 'org-property-action))
18156 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
18157 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
18158 (or (org-on-heading-p) (org-at-item-p)))
18159 (call-interactively 'org-update-statistics-cookies))
18160 ((org-on-heading-p) (call-interactively 'org-set-tags))
18161 ((org-at-table.el-p)
18162 (message "Use C-c ' to edit table.el tables"))
18163 ((org-at-table-p)
18164 (org-table-maybe-eval-formula)
18165 (if arg
18166 (call-interactively 'org-table-recalculate)
18167 (org-table-maybe-recalculate-line))
18168 (call-interactively 'org-table-align)
18169 (orgtbl-send-table 'maybe))
18170 ((or (org-footnote-at-reference-p)
18171 (org-footnote-at-definition-p))
18172 (call-interactively 'org-footnote-action))
18173 ((org-at-item-checkbox-p)
18174 ;; Cursor at a checkbox: repair list and update checkboxes. Send
18175 ;; list only if at top item.
18176 (let* ((cbox (match-string 1))
18177 (struct (org-list-struct))
18178 (old-struct (copy-tree struct))
18179 (parents (org-list-parents-alist struct))
18180 (orderedp (org-entry-get nil "ORDERED"))
18181 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18182 block-item)
18183 ;; Use a light version of `org-toggle-checkbox' to avoid
18184 ;; computing list structure twice.
18185 (org-list-set-checkbox (point-at-bol) struct
18186 (cond
18187 ((equal arg '(16)) "[-]")
18188 ((equal arg '(4)) nil)
18189 ((equal "[X]" cbox) "[ ]")
18190 (t "[X]")))
18191 ;; Replicate `org-list-write-struct', while grabbing a return
18192 ;; value from `org-list-struct-fix-box'.
18193 (org-list-struct-fix-ind struct parents 2)
18194 (org-list-struct-fix-item-end struct)
18195 (let ((prevs (org-list-prevs-alist struct)))
18196 (org-list-struct-fix-bul struct prevs)
18197 (org-list-struct-fix-ind struct parents)
18198 (setq block-item
18199 (org-list-struct-fix-box struct parents prevs orderedp)))
18200 (org-list-struct-apply-struct struct old-struct)
18201 (org-update-checkbox-count-maybe)
18202 (when block-item
18203 (message
18204 "Checkboxes were removed due to unchecked box at line %d"
18205 (org-current-line block-item)))
18206 (when firstp (org-list-send-list 'maybe))))
18207 ((org-at-item-p)
18208 ;; Cursor at an item: repair list. Do checkbox related actions
18209 ;; only if function was called with an argument. Send list only
18210 ;; if at top item.
18211 (let* ((struct (org-list-struct))
18212 (firstp (= (org-list-get-top-point struct) (point-at-bol))))
18213 (when arg (org-list-set-checkbox (point-at-bol) struct "[ ]"))
18214 (org-list-write-struct struct (org-list-parents-alist struct))
18215 (when arg (org-update-checkbox-count-maybe))
18216 (when firstp (org-list-send-list 'maybe))))
18217 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
18218 ;; Dynamic block
18219 (beginning-of-line 1)
18220 (save-excursion (org-update-dblock)))
18221 ((save-excursion
18222 (beginning-of-line 1)
18223 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
18224 (cond
18225 ((equal (match-string 1) "TBLFM")
18226 ;; Recalculate the table before this line
18227 (save-excursion
18228 (beginning-of-line 1)
18229 (skip-chars-backward " \r\n\t")
18230 (if (org-at-table-p)
18231 (org-call-with-arg 'org-table-recalculate (or arg t)))))
18233 (let ((org-inhibit-startup-visibility-stuff t)
18234 (org-startup-align-all-tables nil))
18235 (when (boundp 'org-table-coordinate-overlays)
18236 (mapc 'delete-overlay org-table-coordinate-overlays)
18237 (setq org-table-coordinate-overlays nil))
18238 (org-save-outline-visibility 'use-markers (org-mode-restart)))
18239 (message "Local setup has been refreshed"))))
18240 ((org-clock-update-time-maybe))
18242 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
18243 (error "C-c C-c can do nothing useful at this location"))))))
18245 (defun org-mode-restart ()
18246 "Restart Org-mode, to scan again for special lines.
18247 Also updates the keyword regular expressions."
18248 (interactive)
18249 (org-mode)
18250 (message "Org-mode restarted"))
18252 (defun org-kill-note-or-show-branches ()
18253 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
18254 (interactive)
18255 (if (not org-finish-function)
18256 (progn
18257 (hide-subtree)
18258 (call-interactively 'show-branches))
18259 (let ((org-note-abort t))
18260 (funcall org-finish-function))))
18262 (defun org-return (&optional indent)
18263 "Goto next table row or insert a newline.
18264 Calls `org-table-next-row' or `newline', depending on context.
18265 See the individual commands for more information."
18266 (interactive)
18267 (cond
18268 ((bobp) (if indent (newline-and-indent) (newline)))
18269 ((org-at-table-p)
18270 (org-table-justify-field-maybe)
18271 (call-interactively 'org-table-next-row))
18272 ;; when `newline-and-indent' is called within a list, make sure
18273 ;; text moved stays inside the item.
18274 ((and (org-in-item-p) indent)
18275 (if (and (org-at-item-p) (>= (point) (match-end 0)))
18276 (progn
18277 (save-match-data (newline))
18278 (org-indent-line-to (length (match-string 0))))
18279 (let ((ind (org-get-indentation)))
18280 (newline)
18281 (if (org-looking-back org-list-end-re)
18282 (org-indent-line-function)
18283 (org-indent-line-to ind)))))
18284 ((and org-return-follows-link
18285 (eq (get-text-property (point) 'face) 'org-link))
18286 (call-interactively 'org-open-at-point))
18287 ((and (org-at-heading-p)
18288 (looking-at
18289 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
18290 (org-show-entry)
18291 (end-of-line 1)
18292 (newline))
18293 (t (if indent (newline-and-indent) (newline)))))
18295 (defun org-return-indent ()
18296 "Goto next table row or insert a newline and indent.
18297 Calls `org-table-next-row' or `newline-and-indent', depending on
18298 context. See the individual commands for more information."
18299 (interactive)
18300 (org-return t))
18302 (defun org-ctrl-c-star ()
18303 "Compute table, or change heading status of lines.
18304 Calls `org-table-recalculate' or `org-toggle-heading',
18305 depending on context."
18306 (interactive)
18307 (cond
18308 ((org-at-table-p)
18309 (call-interactively 'org-table-recalculate))
18311 ;; Convert all lines in region to list items
18312 (call-interactively 'org-toggle-heading))))
18314 (defun org-ctrl-c-minus ()
18315 "Insert separator line in table or modify bullet status of line.
18316 Also turns a plain line or a region of lines into list items.
18317 Calls `org-table-insert-hline', `org-toggle-item', or
18318 `org-cycle-list-bullet', depending on context."
18319 (interactive)
18320 (cond
18321 ((org-at-table-p)
18322 (call-interactively 'org-table-insert-hline))
18323 ((org-region-active-p)
18324 (call-interactively 'org-toggle-item))
18325 ((org-in-item-p)
18326 (call-interactively 'org-cycle-list-bullet))
18328 (call-interactively 'org-toggle-item))))
18330 (defun org-toggle-item (arg)
18331 "Convert headings or normal lines to items, items to normal lines.
18332 If there is no active region, only the current line is considered.
18334 If the first non blank line in the region is an headline, convert
18335 all headlines to items, shifting text accordingly.
18337 If it is an item, convert all items to normal lines.
18339 If it is normal text, change region into an item. With a prefix
18340 argument ARG, change each line in region into an item."
18341 (interactive "P")
18342 (let ((shift-text
18343 (function
18344 ;; Shift text in current section to IND, from point to END.
18345 ;; The function leaves point to END line.
18346 (lambda (ind end)
18347 (let ((min-i 1000) (end (copy-marker end)))
18348 ;; First determine the minimum indentation (MIN-I) of
18349 ;; the text.
18350 (save-excursion
18351 (catch 'exit
18352 (while (< (point) end)
18353 (let ((i (org-get-indentation)))
18354 (cond
18355 ;; Skip blank lines and inline tasks.
18356 ((looking-at "^[ \t]*$"))
18357 ((looking-at org-outline-regexp-bol))
18358 ;; We can't find less than 0 indentation.
18359 ((zerop i) (throw 'exit (setq min-i 0)))
18360 ((< i min-i) (setq min-i i))))
18361 (forward-line))))
18362 ;; Then indent each line so that a line indented to
18363 ;; MIN-I becomes indented to IND. Ignore blank lines
18364 ;; and inline tasks in the process.
18365 (let ((delta (- ind min-i)))
18366 (while (< (point) end)
18367 (unless (or (looking-at "^[ \t]*$")
18368 (looking-at org-outline-regexp-bol))
18369 (org-indent-line-to (+ (org-get-indentation) delta)))
18370 (forward-line)))))))
18371 (skip-blanks
18372 (function
18373 ;; Return beginning of first non-blank line, starting from
18374 ;; line at POS.
18375 (lambda (pos)
18376 (save-excursion
18377 (goto-char pos)
18378 (skip-chars-forward " \r\t\n")
18379 (point-at-bol)))))
18380 beg end)
18381 ;; Determine boundaries of changes.
18382 (if (org-region-active-p)
18383 (setq beg (funcall skip-blanks (region-beginning))
18384 end (copy-marker (region-end)))
18385 (setq beg (funcall skip-blanks (point-at-bol))
18386 end (copy-marker (point-at-eol))))
18387 ;; Depending on the starting line, choose an action on the text
18388 ;; between BEG and END.
18389 (org-with-limited-levels
18390 (save-excursion
18391 (goto-char beg)
18392 (cond
18393 ;; Case 1. Start at an item: de-itemize. Note that it only
18394 ;; happens when a region is active: `org-ctrl-c-minus'
18395 ;; would call `org-cycle-list-bullet' otherwise.
18396 ((org-at-item-p)
18397 (while (< (point) end)
18398 (when (org-at-item-p)
18399 (skip-chars-forward " \t")
18400 (delete-region (point) (match-end 0)))
18401 (forward-line)))
18402 ;; Case 2. Start at an heading: convert to items.
18403 ((org-on-heading-p)
18404 (let* ((bul (org-list-bullet-string "-"))
18405 (bul-len (length bul))
18406 ;; Indentation of the first heading. It should be
18407 ;; relative to the indentation of its parent, if any.
18408 (start-ind (save-excursion
18409 (cond
18410 ((not org-adapt-indentation) 0)
18411 ((not (outline-previous-heading)) 0)
18412 (t (length (match-string 0))))))
18413 ;; Level of first heading. Further headings will be
18414 ;; compared to it to determine hierarchy in the list.
18415 (ref-level (org-reduced-level (org-outline-level))))
18416 (while (< (point) end)
18417 (let* ((level (org-reduced-level (org-outline-level)))
18418 (delta (max 0 (- level ref-level))))
18419 ;; If current headline is less indented than the first
18420 ;; one, set it as reference, in order to preserve
18421 ;; subtrees.
18422 (when (< level ref-level) (setq ref-level level))
18423 (replace-match bul t t)
18424 (org-indent-line-to (+ start-ind (* delta bul-len)))
18425 ;; Ensure all text down to END (or SECTION-END) belongs
18426 ;; to the newly created item.
18427 (let ((section-end (save-excursion
18428 (or (outline-next-heading) (point)))))
18429 (forward-line)
18430 (funcall shift-text
18431 (+ start-ind (* (1+ delta) bul-len))
18432 (min end section-end)))))))
18433 ;; Case 3. Normal line with ARG: turn each non-item line into
18434 ;; an item.
18435 (arg
18436 (while (< (point) end)
18437 (unless (or (org-on-heading-p) (org-at-item-p))
18438 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
18439 (replace-match
18440 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
18441 (forward-line)))
18442 ;; Case 4. Normal line without ARG: make the first line of
18443 ;; region an item, and shift indentation of others
18444 ;; lines to set them as item's body.
18445 (t (let* ((bul (org-list-bullet-string "-"))
18446 (bul-len (length bul))
18447 (ref-ind (org-get-indentation)))
18448 (skip-chars-forward " \t")
18449 (insert bul)
18450 (forward-line)
18451 (while (< (point) end)
18452 ;; Ensure that lines less indented than first one
18453 ;; still get included in item body.
18454 (funcall shift-text
18455 (+ ref-ind bul-len)
18456 (min end (save-excursion (or (outline-next-heading)
18457 (point)))))
18458 (forward-line)))))))))
18460 (defun org-toggle-heading (&optional nstars)
18461 "Convert headings to normal text, or items or text to headings.
18462 If there is no active region, only the current line is considered.
18464 If the first non blank line is an headline, remove the stars from
18465 all headlines in the region.
18467 If it is a plain list item, turn all plain list items into headings.
18469 If it is a normal line, turn each and every normal line (i.e. not
18470 an heading or an item) in the region into a heading.
18472 When converting a line into a heading, the number of stars is chosen
18473 such that the lines become children of the current entry. However,
18474 when a prefix argument is given, its value determines the number of
18475 stars to add."
18476 (interactive "P")
18477 (let ((skip-blanks
18478 (function
18479 ;; Return beginning of first non-blank line, starting from
18480 ;; line at POS.
18481 (lambda (pos)
18482 (save-excursion
18483 (goto-char pos)
18484 (skip-chars-forward " \r\t\n")
18485 (point-at-bol)))))
18486 beg end)
18487 ;; Determine boundaries of changes. If region ends at a bol, do
18488 ;; not consider the last line to be in the region.
18489 (if (org-region-active-p)
18490 (setq beg (funcall skip-blanks (region-beginning))
18491 end (copy-marker (save-excursion
18492 (goto-char (region-end))
18493 (if (bolp) (point) (point-at-eol)))))
18494 (setq beg (funcall skip-blanks (point-at-bol))
18495 end (copy-marker (point-at-eol))))
18496 ;; Ensure inline tasks don't count as headings.
18497 (org-with-limited-levels
18498 (save-excursion
18499 (goto-char beg)
18500 (cond
18501 ;; Case 1. Started at an heading: de-star headings.
18502 ((org-on-heading-p)
18503 (while (< (point) end)
18504 (when (org-on-heading-p t)
18505 (looking-at org-outline-regexp) (replace-match ""))
18506 (forward-line)))
18507 ;; Case 2. Started at an item: change items into headlines.
18508 ;; One star will be added by `org-list-to-subtree'.
18509 ((org-at-item-p)
18510 (let* ((stars (make-string
18511 (if nstars
18512 ;; subtract the star that will be added again by
18513 ;; `org-list-to-subtree'
18514 (1- (prefix-numeric-value current-prefix-arg))
18515 (or (org-current-level) 0))
18516 ?*))
18517 (add-stars
18518 (cond (nstars "") ; stars from prefix only
18519 ((equal stars "") "") ; before first heading
18520 (org-odd-levels-only "*") ; inside heading, odd
18521 (t "")))) ; inside heading, oddeven
18522 (while (< (point) end)
18523 (when (org-at-item-p)
18524 ;; Pay attention to cases when region ends before list.
18525 (let* ((struct (org-list-struct))
18526 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
18527 (save-restriction
18528 (narrow-to-region (point) list-end)
18529 (insert
18530 (org-list-to-subtree
18531 (org-list-parse-list t)
18532 '(:istart (concat stars add-stars (funcall get-stars depth))
18533 :icount (concat stars add-stars (funcall get-stars depth))))))))
18534 (forward-line))))
18535 ;; Case 3. Started at normal text: make every line an heading,
18536 ;; skipping headlines and items.
18537 (t (let* ((stars (make-string
18538 (if nstars
18539 (prefix-numeric-value current-prefix-arg)
18540 (or (org-current-level) 0))
18541 ?*))
18542 (add-stars
18543 (cond (nstars "") ; stars from prefix only
18544 ((equal stars "") "*") ; before first heading
18545 (org-odd-levels-only "**") ; inside heading, odd
18546 (t "*"))) ; inside heading, oddeven
18547 (rpl (concat stars add-stars " ")))
18548 (while (< (point) end)
18549 (when (and (not (org-on-heading-p)) (not (org-at-item-p))
18550 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
18551 (replace-match (concat rpl (match-string 2))))
18552 (forward-line)))))))))
18554 (defun org-meta-return (&optional arg)
18555 "Insert a new heading or wrap a region in a table.
18556 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
18557 See the individual commands for more information."
18558 (interactive "P")
18559 (cond
18560 ((run-hook-with-args-until-success 'org-metareturn-hook))
18561 ((org-at-table-p)
18562 (call-interactively 'org-table-wrap-region))
18563 (t (call-interactively 'org-insert-heading))))
18565 ;;; Menu entries
18567 ;; Define the Org-mode menus
18568 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
18569 '("Tbl"
18570 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
18571 ["Next Field" org-cycle (org-at-table-p)]
18572 ["Previous Field" org-shifttab (org-at-table-p)]
18573 ["Next Row" org-return (org-at-table-p)]
18574 "--"
18575 ["Blank Field" org-table-blank-field (org-at-table-p)]
18576 ["Edit Field" org-table-edit-field (org-at-table-p)]
18577 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
18578 "--"
18579 ("Column"
18580 ["Move Column Left" org-metaleft (org-at-table-p)]
18581 ["Move Column Right" org-metaright (org-at-table-p)]
18582 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
18583 ["Insert Column" org-shiftmetaright (org-at-table-p)])
18584 ("Row"
18585 ["Move Row Up" org-metaup (org-at-table-p)]
18586 ["Move Row Down" org-metadown (org-at-table-p)]
18587 ["Delete Row" org-shiftmetaup (org-at-table-p)]
18588 ["Insert Row" org-shiftmetadown (org-at-table-p)]
18589 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
18590 "--"
18591 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
18592 ("Rectangle"
18593 ["Copy Rectangle" org-copy-special (org-at-table-p)]
18594 ["Cut Rectangle" org-cut-special (org-at-table-p)]
18595 ["Paste Rectangle" org-paste-special (org-at-table-p)]
18596 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
18597 "--"
18598 ("Calculate"
18599 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
18600 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
18601 ["Edit Formulas" org-edit-special (org-at-table-p)]
18602 "--"
18603 ["Recalculate line" org-table-recalculate (org-at-table-p)]
18604 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
18605 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
18606 "--"
18607 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
18608 "--"
18609 ["Sum Column/Rectangle" org-table-sum
18610 (or (org-at-table-p) (org-region-active-p))]
18611 ["Which Column?" org-table-current-column (org-at-table-p)])
18612 ["Debug Formulas"
18613 org-table-toggle-formula-debugger
18614 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
18615 ["Show Col/Row Numbers"
18616 org-table-toggle-coordinate-overlays
18617 :style toggle
18618 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
18619 "--"
18620 ["Create" org-table-create (and (not (org-at-table-p))
18621 org-enable-table-editor)]
18622 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
18623 ["Import from File" org-table-import (not (org-at-table-p))]
18624 ["Export to File" org-table-export (org-at-table-p)]
18625 "--"
18626 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
18628 (easy-menu-define org-org-menu org-mode-map "Org menu"
18629 '("Org"
18630 ("Show/Hide"
18631 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
18632 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
18633 ["Sparse Tree..." org-sparse-tree t]
18634 ["Reveal Context" org-reveal t]
18635 ["Show All" show-all t]
18636 "--"
18637 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
18638 "--"
18639 ["New Heading" org-insert-heading t]
18640 ("Navigate Headings"
18641 ["Up" outline-up-heading t]
18642 ["Next" outline-next-visible-heading t]
18643 ["Previous" outline-previous-visible-heading t]
18644 ["Next Same Level" outline-forward-same-level t]
18645 ["Previous Same Level" outline-backward-same-level t]
18646 "--"
18647 ["Jump" org-goto t])
18648 ("Edit Structure"
18649 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
18650 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
18651 "--"
18652 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
18653 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
18654 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
18655 "--"
18656 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
18657 "--"
18658 ["Copy visible text" org-copy-visible t]
18659 "--"
18660 ["Promote Heading" org-metaleft (not (org-at-table-p))]
18661 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
18662 ["Demote Heading" org-metaright (not (org-at-table-p))]
18663 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
18664 "--"
18665 ["Sort Region/Children" org-sort (not (org-at-table-p))]
18666 "--"
18667 ["Convert to odd levels" org-convert-to-odd-levels t]
18668 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
18669 ("Editing"
18670 ["Emphasis..." org-emphasize t]
18671 ["Edit Source Example" org-edit-special t]
18672 "--"
18673 ["Footnote new/jump" org-footnote-action t]
18674 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
18675 ("Archive"
18676 ["Archive (default method)" org-archive-subtree-default t]
18677 "--"
18678 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
18679 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
18680 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
18682 "--"
18683 ("Hyperlinks"
18684 ["Store Link (Global)" org-store-link t]
18685 ["Find existing link to here" org-occur-link-in-agenda-files t]
18686 ["Insert Link" org-insert-link t]
18687 ["Follow Link" org-open-at-point t]
18688 "--"
18689 ["Next link" org-next-link t]
18690 ["Previous link" org-previous-link t]
18691 "--"
18692 ["Descriptive Links"
18693 org-toggle-link-display
18694 :style radio
18695 :selected org-descriptive-links
18697 ["Literal Links"
18698 org-toggle-link-display
18699 :style radio
18700 :selected (not org-descriptive-links)])
18701 "--"
18702 ("TODO Lists"
18703 ["TODO/DONE/-" org-todo t]
18704 ("Select keyword"
18705 ["Next keyword" org-shiftright (org-on-heading-p)]
18706 ["Previous keyword" org-shiftleft (org-on-heading-p)]
18707 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
18708 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
18709 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
18710 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
18711 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
18712 "--"
18713 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
18714 :selected org-enforce-todo-dependencies :style toggle :active t]
18715 "Settings for tree at point"
18716 ["Do Children sequentially" org-toggle-ordered-property :style radio
18717 :selected (org-entry-get nil "ORDERED")
18718 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
18719 ["Do Children parallel" org-toggle-ordered-property :style radio
18720 :selected (not (org-entry-get nil "ORDERED"))
18721 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
18722 "--"
18723 ["Set Priority" org-priority t]
18724 ["Priority Up" org-shiftup t]
18725 ["Priority Down" org-shiftdown t]
18726 "--"
18727 ["Get news from all feeds" org-feed-update-all t]
18728 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
18729 ["Customize feeds" (customize-variable 'org-feed-alist) t])
18730 ("TAGS and Properties"
18731 ["Set Tags" org-set-tags-command t]
18732 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
18733 "--"
18734 ["Set property" org-set-property t]
18735 ["Column view of properties" org-columns t]
18736 ["Insert Column View DBlock" org-insert-columns-dblock t])
18737 ("Dates and Scheduling"
18738 ["Timestamp" org-time-stamp t]
18739 ["Timestamp (inactive)" org-time-stamp-inactive t]
18740 ("Change Date"
18741 ["1 Day Later" org-shiftright t]
18742 ["1 Day Earlier" org-shiftleft t]
18743 ["1 ... Later" org-shiftup t]
18744 ["1 ... Earlier" org-shiftdown t])
18745 ["Compute Time Range" org-evaluate-time-range t]
18746 ["Schedule Item" org-schedule t]
18747 ["Deadline" org-deadline t]
18748 "--"
18749 ["Custom time format" org-toggle-time-stamp-overlays
18750 :style radio :selected org-display-custom-times]
18751 "--"
18752 ["Goto Calendar" org-goto-calendar t]
18753 ["Date from Calendar" org-date-from-calendar t]
18754 "--"
18755 ["Start/Restart Timer" org-timer-start t]
18756 ["Pause/Continue Timer" org-timer-pause-or-continue t]
18757 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
18758 ["Insert Timer String" org-timer t]
18759 ["Insert Timer Item" org-timer-item t])
18760 ("Logging work"
18761 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
18762 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
18763 ["Clock out" org-clock-out t]
18764 ["Clock cancel" org-clock-cancel t]
18765 "--"
18766 ["Mark as default task" org-clock-mark-default-task t]
18767 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
18768 ["Goto running clock" org-clock-goto t]
18769 "--"
18770 ["Display times" org-clock-display t]
18771 ["Create clock table" org-clock-report t]
18772 "--"
18773 ["Record DONE time"
18774 (progn (setq org-log-done (not org-log-done))
18775 (message "Switching to %s will %s record a timestamp"
18776 (car org-done-keywords)
18777 (if org-log-done "automatically" "not")))
18778 :style toggle :selected org-log-done])
18779 "--"
18780 ["Agenda Command..." org-agenda t]
18781 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
18782 ("File List for Agenda")
18783 ("Special views current file"
18784 ["TODO Tree" org-show-todo-tree t]
18785 ["Check Deadlines" org-check-deadlines t]
18786 ["Timeline" org-timeline t]
18787 ["Tags/Property tree" org-match-sparse-tree t])
18788 "--"
18789 ["Export/Publish..." org-export t]
18790 ("LaTeX"
18791 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
18792 :selected org-cdlatex-mode]
18793 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
18794 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
18795 ["Modify math symbol" org-cdlatex-math-modify
18796 (org-inside-LaTeX-fragment-p)]
18797 ["Insert citation" org-reftex-citation t]
18798 "--"
18799 ["Template for BEAMER" org-insert-beamer-options-template t])
18800 "--"
18801 ("MobileOrg"
18802 ["Push Files and Views" org-mobile-push t]
18803 ["Get Captured and Flagged" org-mobile-pull t]
18804 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
18805 "--"
18806 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
18807 "--"
18808 ("Documentation"
18809 ["Show Version" org-version t]
18810 ["Info Documentation" org-info t])
18811 ("Customize"
18812 ["Browse Org Group" org-customize t]
18813 "--"
18814 ["Expand This Menu" org-create-customize-menu
18815 (fboundp 'customize-menu-create)])
18816 ["Send bug report" org-submit-bug-report t]
18817 "--"
18818 ("Refresh/Reload"
18819 ["Refresh setup current buffer" org-mode-restart t]
18820 ["Reload Org (after update)" org-reload t]
18821 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
18824 (defun org-info (&optional node)
18825 "Read documentation for Org-mode in the info system.
18826 With optional NODE, go directly to that node."
18827 (interactive)
18828 (info (format "(org)%s" (or node ""))))
18830 ;;;###autoload
18831 (defun org-submit-bug-report ()
18832 "Submit a bug report on Org-mode via mail.
18834 Don't hesitate to report any problems or inaccurate documentation.
18836 If you don't have setup sending mail from (X)Emacs, please copy the
18837 output buffer into your mail program, as it gives us important
18838 information about your Org-mode version and configuration."
18839 (interactive)
18840 (require 'reporter)
18841 (org-load-modules-maybe)
18842 (org-require-autoloaded-modules)
18843 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
18844 (reporter-submit-bug-report
18845 "emacs-orgmode@gnu.org"
18846 (org-version)
18847 (let (list)
18848 (save-window-excursion
18849 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
18850 (delete-other-windows)
18851 (erase-buffer)
18852 (insert "You are about to submit a bug report to the Org-mode mailing list.
18854 We would like to add your full Org-mode and Outline configuration to the
18855 bug report. This greatly simplifies the work of the maintainer and
18856 other experts on the mailing list.
18858 HOWEVER, some variables you have customized may contain private
18859 information. The names of customers, colleagues, or friends, might
18860 appear in the form of file names, tags, todo states, or search strings.
18861 If you answer yes to the prompt, you might want to check and remove
18862 such private information before sending the email.")
18863 (add-text-properties (point-min) (point-max) '(face org-warning))
18864 (when (yes-or-no-p "Include your Org-mode configuration ")
18865 (mapatoms
18866 (lambda (v)
18867 (and (boundp v)
18868 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
18869 (or (and (symbol-value v)
18870 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
18871 (and
18872 (get v 'custom-type) (get v 'standard-value)
18873 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
18874 (push v list)))))
18875 (kill-buffer (get-buffer "*Warn about privacy*"))
18876 list))
18877 nil nil
18878 "Remember to cover the basics, that is, what you expected to happen and
18879 what in fact did happen. You don't know how to make a good report? See
18881 http://orgmode.org/manual/Feedback.html#Feedback
18883 Your bug report will be posted to the Org-mode mailing list.
18884 ------------------------------------------------------------------------")
18885 (save-excursion
18886 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
18887 (replace-match "\\1Bug: \\3 [\\2]")))))
18890 (defun org-install-agenda-files-menu ()
18891 (let ((bl (buffer-list)))
18892 (save-excursion
18893 (while bl
18894 (set-buffer (pop bl))
18895 (if (eq major-mode 'org-mode) (setq bl nil)))
18896 (when (eq major-mode 'org-mode)
18897 (easy-menu-change
18898 '("Org") "File List for Agenda"
18899 (append
18900 (list
18901 ["Edit File List" (org-edit-agenda-file-list) t]
18902 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
18903 ["Remove Current File from List" org-remove-file t]
18904 ["Cycle through agenda files" org-cycle-agenda-files t]
18905 ["Occur in all agenda files" org-occur-in-agenda-files t]
18906 "--")
18907 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
18909 ;;;; Documentation
18911 ;;;###autoload
18912 (defun org-require-autoloaded-modules ()
18913 (interactive)
18914 (mapc 'require
18915 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
18916 org-docbook org-exp org-html org-icalendar
18917 org-id org-latex
18918 org-publish org-remember org-table
18919 org-timer org-xoxo)))
18921 ;;;###autoload
18922 (defun org-reload (&optional uncompiled)
18923 "Reload all org lisp files.
18924 With prefix arg UNCOMPILED, load the uncompiled versions."
18925 (interactive "P")
18926 (require 'find-func)
18927 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
18928 (dir-org (file-name-directory (org-find-library-name "org")))
18929 (dir-org-contrib (ignore-errors
18930 (file-name-directory
18931 (org-find-library-name "org-contribdir"))))
18932 (babel-files
18933 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
18934 (append (list nil "comint" "eval" "exp" "keys"
18935 "lob" "ref" "table" "tangle")
18936 (delq nil
18937 (mapcar
18938 (lambda (lang)
18939 (when (cdr lang) (symbol-name (car lang))))
18940 org-babel-load-languages)))))
18941 (files
18942 (append (directory-files dir-org t file-re)
18943 babel-files
18944 (and dir-org-contrib
18945 (directory-files dir-org-contrib t file-re))))
18946 (remove-re (concat (if (featurep 'xemacs)
18947 "org-colview" "org-colview-xemacs")
18948 "\\'")))
18949 (setq files (mapcar 'file-name-sans-extension files))
18950 (setq files (mapcar
18951 (lambda (x) (if (string-match remove-re x) nil x))
18952 files))
18953 (setq files (delq nil files))
18954 (mapc
18955 (lambda (f)
18956 (when (featurep (intern (file-name-nondirectory f)))
18957 (if (and (not uncompiled)
18958 (file-exists-p (concat f ".elc")))
18959 (load (concat f ".elc") nil nil t)
18960 (load (concat f ".el") nil nil t))))
18961 files))
18962 (org-version))
18964 ;;;###autoload
18965 (defun org-customize ()
18966 "Call the customize function with org as argument."
18967 (interactive)
18968 (org-load-modules-maybe)
18969 (org-require-autoloaded-modules)
18970 (customize-browse 'org))
18972 (defun org-create-customize-menu ()
18973 "Create a full customization menu for Org-mode, insert it into the menu."
18974 (interactive)
18975 (org-load-modules-maybe)
18976 (org-require-autoloaded-modules)
18977 (if (fboundp 'customize-menu-create)
18978 (progn
18979 (easy-menu-change
18980 '("Org") "Customize"
18981 `(["Browse Org group" org-customize t]
18982 "--"
18983 ,(customize-menu-create 'org)
18984 ["Set" Custom-set t]
18985 ["Save" Custom-save t]
18986 ["Reset to Current" Custom-reset-current t]
18987 ["Reset to Saved" Custom-reset-saved t]
18988 ["Reset to Standard Settings" Custom-reset-standard t]))
18989 (message "\"Org\"-menu now contains full customization menu"))
18990 (error "Cannot expand menu (outdated version of cus-edit.el)")))
18992 ;;;; Miscellaneous stuff
18994 ;;; Generally useful functions
18996 (defun org-get-at-bol (property)
18997 "Get text property PROPERTY at beginning of line."
18998 (get-text-property (point-at-bol) property))
19000 (defun org-find-text-property-in-string (prop s)
19001 "Return the first non-nil value of property PROP in string S."
19002 (or (get-text-property 0 prop s)
19003 (get-text-property (or (next-single-property-change 0 prop s) 0)
19004 prop s)))
19006 (defun org-display-warning (message) ;; Copied from Emacs-Muse
19007 "Display the given MESSAGE as a warning."
19008 (if (fboundp 'display-warning)
19009 (display-warning 'org message
19010 (if (featurep 'xemacs) 'warning :warning))
19011 (let ((buf (get-buffer-create "*Org warnings*")))
19012 (with-current-buffer buf
19013 (goto-char (point-max))
19014 (insert "Warning (Org): " message)
19015 (unless (bolp)
19016 (newline)))
19017 (display-buffer buf)
19018 (sit-for 0))))
19020 (defun org-eval (form)
19021 "Eval FORM and return result."
19022 (condition-case error
19023 (eval form)
19024 (error (format "%%![Error: %s]" error))))
19026 (defun org-in-commented-line ()
19027 "Is point in a line starting with `#'?"
19028 (equal (char-after (point-at-bol)) ?#))
19030 (defun org-in-indented-comment-line ()
19031 "Is point in a line starting with `#' after some white space?"
19032 (save-excursion
19033 (save-match-data
19034 (goto-char (point-at-bol))
19035 (looking-at "[ \t]*#"))))
19037 (defun org-in-verbatim-emphasis ()
19038 (save-match-data
19039 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
19041 (defun org-goto-marker-or-bmk (marker &optional bookmark)
19042 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
19043 (if (and marker (marker-buffer marker)
19044 (buffer-live-p (marker-buffer marker)))
19045 (progn
19046 (org-pop-to-buffer-same-window (marker-buffer marker))
19047 (if (or (> marker (point-max)) (< marker (point-min)))
19048 (widen))
19049 (goto-char marker)
19050 (org-show-context 'org-goto))
19051 (if bookmark
19052 (bookmark-jump bookmark)
19053 (error "Cannot find location"))))
19055 (defun org-quote-csv-field (s)
19056 "Quote field for inclusion in CSV material."
19057 (if (string-match "[\",]" s)
19058 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
19061 (defun org-force-self-insert (N)
19062 "Needed to enforce self-insert under remapping."
19063 (interactive "p")
19064 (self-insert-command N))
19066 (defun org-string-width (s)
19067 "Compute width of string, ignoring invisible characters.
19068 This ignores character with invisibility property `org-link', and also
19069 characters with property `org-cwidth', because these will become invisible
19070 upon the next fontification round."
19071 (let (b l)
19072 (when (or (eq t buffer-invisibility-spec)
19073 (assq 'org-link buffer-invisibility-spec))
19074 (while (setq b (text-property-any 0 (length s)
19075 'invisible 'org-link s))
19076 (setq s (concat (substring s 0 b)
19077 (substring s (or (next-single-property-change
19078 b 'invisible s) (length s)))))))
19079 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
19080 (setq s (concat (substring s 0 b)
19081 (substring s (or (next-single-property-change
19082 b 'org-cwidth s) (length s))))))
19083 (setq l (string-width s) b -1)
19084 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
19085 (setq l (- l (get-text-property b 'org-dwidth-n s))))
19088 (defun org-shorten-string (s maxlength)
19089 "Shorten string S so tht it is no longer than MAXLENGTH characters.
19090 If the string is shorter or has length MAXLENGTH, just return the
19091 original string. If it is longer, the functions finds a space in the
19092 string, breaks this string off at that locations and adds three dots
19093 as ellipsis. Including the ellipsis, the string will not be longer
19094 than MAXLENGTH. If finding a good breaking point in the string does
19095 not work, the string is just chopped off in the middle of a word
19096 if necessary."
19097 (if (<= (length s) maxlength)
19099 (let* ((n (max (- maxlength 4) 1))
19100 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
19101 (if (string-match re s)
19102 (concat (match-string 1 s) "...")
19103 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
19105 (defun org-get-indentation (&optional line)
19106 "Get the indentation of the current line, interpreting tabs.
19107 When LINE is given, assume it represents a line and compute its indentation."
19108 (if line
19109 (if (string-match "^ *" (org-remove-tabs line))
19110 (match-end 0))
19111 (save-excursion
19112 (beginning-of-line 1)
19113 (skip-chars-forward " \t")
19114 (current-column))))
19116 (defun org-get-string-indentation (s)
19117 "What indentation has S due to SPACE and TAB at the beginning of the string?"
19118 (let ((n -1) (i 0) (w tab-width) c)
19119 (catch 'exit
19120 (while (< (setq n (1+ n)) (length s))
19121 (setq c (aref s n))
19122 (cond ((= c ?\ ) (setq i (1+ i)))
19123 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
19124 (t (throw 'exit t)))))
19127 (defun org-remove-tabs (s &optional width)
19128 "Replace tabulators in S with spaces.
19129 Assumes that s is a single line, starting in column 0."
19130 (setq width (or width tab-width))
19131 (while (string-match "\t" s)
19132 (setq s (replace-match
19133 (make-string
19134 (- (* width (/ (+ (match-beginning 0) width) width))
19135 (match-beginning 0)) ?\ )
19136 t t s)))
19139 (defun org-fix-indentation (line ind)
19140 "Fix indentation in LINE.
19141 IND is a cons cell with target and minimum indentation.
19142 If the current indentation in LINE is smaller than the minimum,
19143 leave it alone. If it is larger than ind, set it to the target."
19144 (let* ((l (org-remove-tabs line))
19145 (i (org-get-indentation l))
19146 (i1 (car ind)) (i2 (cdr ind)))
19147 (if (>= i i2) (setq l (substring line i2)))
19148 (if (> i1 0)
19149 (concat (make-string i1 ?\ ) l)
19150 l)))
19152 (defun org-remove-indentation (code &optional n)
19153 "Remove the maximum common indentation from the lines in CODE.
19154 N may optionally be the number of spaces to remove."
19155 (with-temp-buffer
19156 (insert code)
19157 (org-do-remove-indentation n)
19158 (buffer-string)))
19160 (defun org-do-remove-indentation (&optional n)
19161 "Remove the maximum common indentation from the buffer."
19162 (untabify (point-min) (point-max))
19163 (let ((min 10000) re)
19164 (if n
19165 (setq min n)
19166 (goto-char (point-min))
19167 (while (re-search-forward "^ *[^ \n]" nil t)
19168 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
19169 (unless (or (= min 0) (= min 10000))
19170 (setq re (format "^ \\{%d\\}" min))
19171 (goto-char (point-min))
19172 (while (re-search-forward re nil t)
19173 (replace-match "")
19174 (end-of-line 1))
19175 min)))
19177 (defun org-fill-template (template alist)
19178 "Find each %key of ALIST in TEMPLATE and replace it."
19179 (let ((case-fold-search nil)
19180 entry key value)
19181 (setq alist (sort (copy-sequence alist)
19182 (lambda (a b) (< (length (car a)) (length (car b))))))
19183 (while (setq entry (pop alist))
19184 (setq template
19185 (replace-regexp-in-string
19186 (concat "%" (regexp-quote (car entry)))
19187 (cdr entry) template t t)))
19188 template))
19190 (defun org-base-buffer (buffer)
19191 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
19192 (if (not buffer)
19193 buffer
19194 (or (buffer-base-buffer buffer)
19195 buffer)))
19197 (defun org-trim (s)
19198 "Remove whitespace at beginning and end of string."
19199 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
19200 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
19203 (defun org-wrap (string &optional width lines)
19204 "Wrap string to either a number of lines, or a width in characters.
19205 If WIDTH is non-nil, the string is wrapped to that width, however many lines
19206 that costs. If there is a word longer than WIDTH, the text is actually
19207 wrapped to the length of that word.
19208 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
19209 many lines, whatever width that takes.
19210 The return value is a list of lines, without newlines at the end."
19211 (let* ((words (org-split-string string "[ \t\n]+"))
19212 (maxword (apply 'max (mapcar 'org-string-width words)))
19213 w ll)
19214 (cond (width
19215 (org-do-wrap words (max maxword width)))
19216 (lines
19217 (setq w maxword)
19218 (setq ll (org-do-wrap words maxword))
19219 (if (<= (length ll) lines)
19221 (setq ll words)
19222 (while (> (length ll) lines)
19223 (setq w (1+ w))
19224 (setq ll (org-do-wrap words w)))
19225 ll))
19226 (t (error "Cannot wrap this")))))
19228 (defun org-do-wrap (words width)
19229 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
19230 (let (lines line)
19231 (while words
19232 (setq line (pop words))
19233 (while (and words (< (+ (length line) (length (car words))) width))
19234 (setq line (concat line " " (pop words))))
19235 (setq lines (push line lines)))
19236 (nreverse lines)))
19238 (defun org-split-string (string &optional separators)
19239 "Splits STRING into substrings at SEPARATORS.
19240 No empty strings are returned if there are matches at the beginning
19241 and end of string."
19242 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
19243 (start 0)
19244 notfirst
19245 (list nil))
19246 (while (and (string-match rexp string
19247 (if (and notfirst
19248 (= start (match-beginning 0))
19249 (< start (length string)))
19250 (1+ start) start))
19251 (< (match-beginning 0) (length string)))
19252 (setq notfirst t)
19253 (or (eq (match-beginning 0) 0)
19254 (and (eq (match-beginning 0) (match-end 0))
19255 (eq (match-beginning 0) start))
19256 (setq list
19257 (cons (substring string start (match-beginning 0))
19258 list)))
19259 (setq start (match-end 0)))
19260 (or (eq start (length string))
19261 (setq list
19262 (cons (substring string start)
19263 list)))
19264 (nreverse list)))
19266 (defun org-quote-vert (s)
19267 "Replace \"|\" with \"\\vert\"."
19268 (while (string-match "|" s)
19269 (setq s (replace-match "\\vert" t t s)))
19272 (defun org-uuidgen-p (s)
19273 "Is S an ID created by UUIDGEN?"
19274 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
19276 (defun org-context ()
19277 "Return a list of contexts of the current cursor position.
19278 If several contexts apply, all are returned.
19279 Each context entry is a list with a symbol naming the context, and
19280 two positions indicating start and end of the context. Possible
19281 contexts are:
19283 :headline anywhere in a headline
19284 :headline-stars on the leading stars in a headline
19285 :todo-keyword on a TODO keyword (including DONE) in a headline
19286 :tags on the TAGS in a headline
19287 :priority on the priority cookie in a headline
19288 :item on the first line of a plain list item
19289 :item-bullet on the bullet/number of a plain list item
19290 :checkbox on the checkbox in a plain list item
19291 :table in an org-mode table
19292 :table-special on a special filed in a table
19293 :table-table in a table.el table
19294 :link on a hyperlink
19295 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
19296 :target on a <<target>>
19297 :radio-target on a <<<radio-target>>>
19298 :latex-fragment on a LaTeX fragment
19299 :latex-preview on a LaTeX fragment with overlayed preview image
19301 This function expects the position to be visible because it uses font-lock
19302 faces as a help to recognize the following contexts: :table-special, :link,
19303 and :keyword."
19304 (let* ((f (get-text-property (point) 'face))
19305 (faces (if (listp f) f (list f)))
19306 (p (point)) clist o)
19307 ;; First the large context
19308 (cond
19309 ((org-on-heading-p t)
19310 (push (list :headline (point-at-bol) (point-at-eol)) clist)
19311 (when (progn
19312 (beginning-of-line 1)
19313 (looking-at org-todo-line-tags-regexp))
19314 (push (org-point-in-group p 1 :headline-stars) clist)
19315 (push (org-point-in-group p 2 :todo-keyword) clist)
19316 (push (org-point-in-group p 4 :tags) clist))
19317 (goto-char p)
19318 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
19319 (if (looking-at "\\[#[A-Z0-9]\\]")
19320 (push (org-point-in-group p 0 :priority) clist)))
19322 ((org-at-item-p)
19323 (push (org-point-in-group p 2 :item-bullet) clist)
19324 (push (list :item (point-at-bol)
19325 (save-excursion (org-end-of-item) (point)))
19326 clist)
19327 (and (org-at-item-checkbox-p)
19328 (push (org-point-in-group p 0 :checkbox) clist)))
19330 ((org-at-table-p)
19331 (push (list :table (org-table-begin) (org-table-end)) clist)
19332 (if (memq 'org-formula faces)
19333 (push (list :table-special
19334 (previous-single-property-change p 'face)
19335 (next-single-property-change p 'face)) clist)))
19336 ((org-at-table-p 'any)
19337 (push (list :table-table) clist)))
19338 (goto-char p)
19340 ;; Now the small context
19341 (cond
19342 ((org-at-timestamp-p)
19343 (push (org-point-in-group p 0 :timestamp) clist))
19344 ((memq 'org-link faces)
19345 (push (list :link
19346 (previous-single-property-change p 'face)
19347 (next-single-property-change p 'face)) clist))
19348 ((memq 'org-special-keyword faces)
19349 (push (list :keyword
19350 (previous-single-property-change p 'face)
19351 (next-single-property-change p 'face)) clist))
19352 ((org-on-target-p)
19353 (push (org-point-in-group p 0 :target) clist)
19354 (goto-char (1- (match-beginning 0)))
19355 (if (looking-at org-radio-target-regexp)
19356 (push (org-point-in-group p 0 :radio-target) clist))
19357 (goto-char p))
19358 ((setq o (car (delq nil
19359 (mapcar
19360 (lambda (x)
19361 (if (memq x org-latex-fragment-image-overlays) x))
19362 (overlays-at (point))))))
19363 (push (list :latex-fragment
19364 (overlay-start o) (overlay-end o)) clist)
19365 (push (list :latex-preview
19366 (overlay-start o) (overlay-end o)) clist))
19367 ((org-inside-LaTeX-fragment-p)
19368 ;; FIXME: positions wrong.
19369 (push (list :latex-fragment (point) (point)) clist)))
19371 (setq clist (nreverse (delq nil clist)))
19372 clist))
19374 ;; FIXME: Compare with at-regexp-p Do we need both?
19375 (defun org-in-regexp (re &optional nlines visually)
19376 "Check if point is inside a match of regexp.
19377 Normally only the current line is checked, but you can include NLINES extra
19378 lines both before and after point into the search.
19379 If VISUALLY is set, require that the cursor is not after the match but
19380 really on, so that the block visually is on the match."
19381 (catch 'exit
19382 (let ((pos (point))
19383 (eol (point-at-eol (+ 1 (or nlines 0))))
19384 (inc (if visually 1 0)))
19385 (save-excursion
19386 (beginning-of-line (- 1 (or nlines 0)))
19387 (while (re-search-forward re eol t)
19388 (if (and (<= (match-beginning 0) pos)
19389 (>= (+ inc (match-end 0)) pos))
19390 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
19392 (defun org-at-regexp-p (regexp)
19393 "Is point inside a match of REGEXP in the current line?"
19394 (catch 'exit
19395 (save-excursion
19396 (let ((pos (point)) (end (point-at-eol)))
19397 (beginning-of-line 1)
19398 (while (re-search-forward regexp end t)
19399 (if (and (<= (match-beginning 0) pos)
19400 (>= (match-end 0) pos))
19401 (throw 'exit t)))
19402 nil))))
19404 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
19405 "Non-nil when point is between matches of START-RE and END-RE.
19407 Also return a non-nil value when point is on one of the matches.
19409 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
19410 buffer positions. Default values are the positions of headlines
19411 surrounding the point.
19413 The functions returns a cons cell whose car (resp. cdr) is the
19414 position before START-RE (resp. after END-RE)."
19415 (save-match-data
19416 (let ((pos (point))
19417 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
19418 (limit-down (or lim-down (save-excursion (outline-next-heading))))
19419 beg end)
19420 (save-excursion
19421 ;; Point is on a block when on START-RE or if START-RE can be
19422 ;; found before it...
19423 (and (or (org-at-regexp-p start-re)
19424 (re-search-backward start-re limit-up t))
19425 (setq beg (match-beginning 0))
19426 ;; ... and END-RE after it...
19427 (goto-char (match-end 0))
19428 (re-search-forward end-re limit-down t)
19429 (> (setq end (match-end 0)) pos)
19430 ;; ... without another START-RE in-between.
19431 (goto-char (match-beginning 0))
19432 (not (re-search-backward start-re (1+ beg) t))
19433 ;; Return value.
19434 (cons beg end))))))
19436 (defun org-in-block-p (names)
19437 "Is point inside any block whose name belongs to NAMES?
19439 NAMES is a list of strings containing names of blocks."
19440 (save-match-data
19441 (catch 'exit
19442 (let ((case-fold-search t)
19443 (lim-up (save-excursion (outline-previous-heading)))
19444 (lim-down (save-excursion (outline-next-heading))))
19445 (mapc (lambda (name)
19446 (let ((n (regexp-quote name)))
19447 (when (org-between-regexps-p
19448 (concat "^[ \t]*#\\+begin_" n)
19449 (concat "^[ \t]*#\\+end_" n)
19450 lim-up lim-down)
19451 (throw 'exit t))))
19452 names))
19453 nil)))
19455 (defun org-occur-in-agenda-files (regexp &optional nlines)
19456 "Call `multi-occur' with buffers for all agenda files."
19457 (interactive "sOrg-files matching: \np")
19458 (let* ((files (org-agenda-files))
19459 (tnames (mapcar 'file-truename files))
19460 (extra org-agenda-text-search-extra-files)
19462 (when (eq (car extra) 'agenda-archives)
19463 (setq extra (cdr extra))
19464 (setq files (org-add-archive-files files)))
19465 (while (setq f (pop extra))
19466 (unless (member (file-truename f) tnames)
19467 (add-to-list 'files f 'append)
19468 (add-to-list 'tnames (file-truename f) 'append)))
19469 (multi-occur
19470 (mapcar (lambda (x)
19471 (with-current-buffer
19472 (or (get-file-buffer x) (find-file-noselect x))
19473 (widen)
19474 (current-buffer)))
19475 files)
19476 regexp)))
19478 (if (boundp 'occur-mode-find-occurrence-hook)
19479 ;; Emacs 23
19480 (add-hook 'occur-mode-find-occurrence-hook
19481 (lambda ()
19482 (when (eq major-mode 'org-mode)
19483 (org-reveal))))
19484 ;; Emacs 22
19485 (defadvice occur-mode-goto-occurrence
19486 (after org-occur-reveal activate)
19487 (and (eq major-mode 'org-mode) (org-reveal)))
19488 (defadvice occur-mode-goto-occurrence-other-window
19489 (after org-occur-reveal activate)
19490 (and (eq major-mode 'org-mode) (org-reveal)))
19491 (defadvice occur-mode-display-occurrence
19492 (after org-occur-reveal activate)
19493 (when (eq major-mode 'org-mode)
19494 (let ((pos (occur-mode-find-occurrence)))
19495 (with-current-buffer (marker-buffer pos)
19496 (save-excursion
19497 (goto-char pos)
19498 (org-reveal)))))))
19500 (defun org-occur-link-in-agenda-files ()
19501 "Create a link and search for it in the agendas.
19502 The link is not stored in `org-stored-links', it is just created
19503 for the search purpose."
19504 (interactive)
19505 (let ((link (condition-case nil
19506 (org-store-link nil)
19507 (error "Unable to create a link to here"))))
19508 (org-occur-in-agenda-files (regexp-quote link))))
19510 (defun org-uniquify (list)
19511 "Remove duplicate elements from LIST."
19512 (let (res)
19513 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
19514 res))
19516 (defun org-delete-all (elts list)
19517 "Remove all elements in ELTS from LIST."
19518 (while elts
19519 (setq list (delete (pop elts) list)))
19520 list)
19522 (defun org-count (cl-item cl-seq)
19523 "Count the number of occurrences of ITEM in SEQ.
19524 Taken from `count' in cl-seq.el with all keyword arguments removed."
19525 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
19526 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
19527 (while (< cl-start cl-end)
19528 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
19529 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
19530 (setq cl-start (1+ cl-start)))
19531 cl-count))
19533 (defun org-remove-if (predicate seq)
19534 "Remove everything from SEQ that fulfills PREDICATE."
19535 (let (res e)
19536 (while seq
19537 (setq e (pop seq))
19538 (if (not (funcall predicate e)) (push e res)))
19539 (nreverse res)))
19541 (defun org-remove-if-not (predicate seq)
19542 "Remove everything from SEQ that does not fulfill PREDICATE."
19543 (let (res e)
19544 (while seq
19545 (setq e (pop seq))
19546 (if (funcall predicate e) (push e res)))
19547 (nreverse res)))
19549 (defun org-back-over-empty-lines ()
19550 "Move backwards over whitespace, to the beginning of the first empty line.
19551 Returns the number of empty lines passed."
19552 (let ((pos (point)))
19553 (if (cdr (assoc 'heading org-blank-before-new-entry))
19554 (skip-chars-backward " \t\n\r")
19555 (unless (eobp)
19556 (forward-line -1)))
19557 (beginning-of-line 2)
19558 (goto-char (min (point) pos))
19559 (count-lines (point) pos)))
19561 (defun org-skip-whitespace ()
19562 (skip-chars-forward " \t\n\r"))
19564 (defun org-point-in-group (point group &optional context)
19565 "Check if POINT is in match-group GROUP.
19566 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
19567 match. If the match group does not exist or point is not inside it,
19568 return nil."
19569 (and (match-beginning group)
19570 (>= point (match-beginning group))
19571 (<= point (match-end group))
19572 (if context
19573 (list context (match-beginning group) (match-end group))
19574 t)))
19576 (defun org-switch-to-buffer-other-window (&rest args)
19577 "Switch to buffer in a second window on the current frame.
19578 In particular, do not allow pop-up frames.
19579 Returns the newly created buffer."
19580 (let (pop-up-frames special-display-buffer-names special-display-regexps
19581 special-display-function)
19582 (apply 'switch-to-buffer-other-window args)))
19584 (defun org-combine-plists (&rest plists)
19585 "Create a single property list from all plists in PLISTS.
19586 The process starts by copying the first list, and then setting properties
19587 from the other lists. Settings in the last list are the most significant
19588 ones and overrule settings in the other lists."
19589 (let ((rtn (copy-sequence (pop plists)))
19590 p v ls)
19591 (while plists
19592 (setq ls (pop plists))
19593 (while ls
19594 (setq p (pop ls) v (pop ls))
19595 (setq rtn (plist-put rtn p v))))
19596 rtn))
19598 (defun org-move-line-down (arg)
19599 "Move the current line down. With prefix argument, move it past ARG lines."
19600 (interactive "p")
19601 (let ((col (current-column))
19602 beg end pos)
19603 (beginning-of-line 1) (setq beg (point))
19604 (beginning-of-line 2) (setq end (point))
19605 (beginning-of-line (+ 1 arg))
19606 (setq pos (move-marker (make-marker) (point)))
19607 (insert (delete-and-extract-region beg end))
19608 (goto-char pos)
19609 (org-move-to-column col)))
19611 (defun org-move-line-up (arg)
19612 "Move the current line up. With prefix argument, move it past ARG lines."
19613 (interactive "p")
19614 (let ((col (current-column))
19615 beg end pos)
19616 (beginning-of-line 1) (setq beg (point))
19617 (beginning-of-line 2) (setq end (point))
19618 (beginning-of-line (- arg))
19619 (setq pos (move-marker (make-marker) (point)))
19620 (insert (delete-and-extract-region beg end))
19621 (goto-char pos)
19622 (org-move-to-column col)))
19624 (defun org-replace-escapes (string table)
19625 "Replace %-escapes in STRING with values in TABLE.
19626 TABLE is an association list with keys like \"%a\" and string values.
19627 The sequences in STRING may contain normal field width and padding information,
19628 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
19629 so values can contain further %-escapes if they are define later in TABLE."
19630 (let ((tbl (copy-alist table))
19631 (case-fold-search nil)
19632 (pchg 0)
19633 e re rpl)
19634 (while (setq e (pop tbl))
19635 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
19636 (when (and (cdr e) (string-match re (cdr e)))
19637 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
19638 (safe "SREF"))
19639 (add-text-properties 0 3 (list 'sref sref) safe)
19640 (setcdr e (replace-match safe t t (cdr e)))))
19641 (while (string-match re string)
19642 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
19643 (cdr e)))
19644 (setq string (replace-match rpl t t string))))
19645 (while (setq pchg (next-property-change pchg string))
19646 (let ((sref (get-text-property pchg 'sref string)))
19647 (when (and sref (string-match "SREF" string pchg))
19648 (setq string (replace-match sref t t string)))))
19649 string))
19651 (defun org-sublist (list start end)
19652 "Return a section of LIST, from START to END.
19653 Counting starts at 1."
19654 (let (rtn (c start))
19655 (setq list (nthcdr (1- start) list))
19656 (while (and list (<= c end))
19657 (push (pop list) rtn)
19658 (setq c (1+ c)))
19659 (nreverse rtn)))
19661 (defun org-find-base-buffer-visiting (file)
19662 "Like `find-buffer-visiting' but always return the base buffer and
19663 not an indirect buffer."
19664 (let ((buf (or (get-file-buffer file)
19665 (find-buffer-visiting file))))
19666 (if buf
19667 (or (buffer-base-buffer buf) buf)
19668 nil)))
19670 (defun org-image-file-name-regexp (&optional extensions)
19671 "Return regexp matching the file names of images.
19672 If EXTENSIONS is given, only match these."
19673 (if (and (not extensions) (fboundp 'image-file-name-regexp))
19674 (image-file-name-regexp)
19675 (let ((image-file-name-extensions
19676 (or extensions
19677 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
19678 "xbm" "xpm" "pbm" "pgm" "ppm"))))
19679 (concat "\\."
19680 (regexp-opt (nconc (mapcar 'upcase
19681 image-file-name-extensions)
19682 image-file-name-extensions)
19684 "\\'"))))
19686 (defun org-file-image-p (file &optional extensions)
19687 "Return non-nil if FILE is an image."
19688 (save-match-data
19689 (string-match (org-image-file-name-regexp extensions) file)))
19691 (defun org-get-cursor-date ()
19692 "Return the date at cursor in as a time.
19693 This works in the calendar and in the agenda, anywhere else it just
19694 returns the current time."
19695 (let (date day defd)
19696 (cond
19697 ((eq major-mode 'calendar-mode)
19698 (setq date (calendar-cursor-to-date)
19699 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
19700 ((eq major-mode 'org-agenda-mode)
19701 (setq day (get-text-property (point) 'day))
19702 (if day
19703 (setq date (calendar-gregorian-from-absolute day)
19704 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
19705 (nth 2 date))))))
19706 (or defd (current-time))))
19708 (defvar org-agenda-action-marker (make-marker)
19709 "Marker pointing to the entry for the next agenda action.")
19711 (defun org-mark-entry-for-agenda-action ()
19712 "Mark the current entry as target of an agenda action.
19713 Agenda actions are actions executed from the agenda with the key `k',
19714 which make use of the date at the cursor."
19715 (interactive)
19716 (move-marker org-agenda-action-marker
19717 (save-excursion (org-back-to-heading t) (point))
19718 (current-buffer))
19719 (message
19720 "Entry marked for action; press `k' at desired date in agenda or calendar"))
19722 (defun org-mark-subtree ()
19723 "Mark the current subtree.
19724 This puts point at the start of the current subtree, and mark at the end.
19726 If point is in an inline task, mark that task instead."
19727 (interactive)
19728 (let ((inline-task-p
19729 (and (featurep 'org-inlinetask)
19730 (org-inlinetask-in-task-p)))
19731 (beg))
19732 ;; Get beginning of subtree
19733 (cond
19734 (inline-task-p (org-inlinetask-goto-beginning))
19735 ((org-at-heading-p) (beginning-of-line))
19736 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
19737 (setq beg (point))
19738 ;; Get end of it
19739 (if inline-task-p
19740 (org-inlinetask-goto-end)
19741 (org-end-of-subtree))
19742 ;; Mark zone
19743 (push-mark (point) nil t)
19744 (goto-char beg)))
19746 ;;; Paragraph filling stuff.
19747 ;; We want this to be just right, so use the full arsenal.
19749 (defun org-indent-line-function ()
19750 "Indent line depending on context."
19751 (interactive)
19752 (let* ((pos (point))
19753 (itemp (org-at-item-p))
19754 (case-fold-search t)
19755 (org-drawer-regexp (or org-drawer-regexp "\000"))
19756 (inline-task-p (and (featurep 'org-inlinetask)
19757 (org-inlinetask-in-task-p)))
19758 (inline-re (and inline-task-p
19759 (org-inlinetask-outline-regexp)))
19760 column)
19761 (beginning-of-line 1)
19762 (cond
19763 ;; Comments
19764 ((looking-at "# ") (setq column 0))
19765 ;; Headings
19766 ((looking-at org-outline-regexp) (setq column 0))
19767 ;; Included files
19768 ((looking-at "#\\+include:") (setq column 0))
19769 ;; Footnote definition
19770 ((looking-at org-footnote-definition-re) (setq column 0))
19771 ;; Literal examples
19772 ((looking-at "[ \t]*:\\( \\|$\\)")
19773 (setq column (org-get-indentation))) ; do nothing
19774 ;; Lists
19775 ((ignore-errors (goto-char (org-in-item-p)))
19776 (setq column (if itemp
19777 (org-get-indentation)
19778 (org-list-item-body-column (point))))
19779 (goto-char pos))
19780 ;; Drawers
19781 ((and (looking-at "[ \t]*:END:")
19782 (save-excursion (re-search-backward org-drawer-regexp nil t)))
19783 (save-excursion
19784 (goto-char (1- (match-beginning 1)))
19785 (setq column (current-column))))
19786 ;; Special blocks
19787 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
19788 (save-excursion
19789 (re-search-backward
19790 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
19791 (setq column (org-get-indentation (match-string 0))))
19792 ((and (not (looking-at "[ \t]*#\\+begin_"))
19793 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
19794 (save-excursion
19795 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
19796 (setq column
19797 (cond ((equal (downcase (match-string 1)) "src")
19798 ;; src blocks: let `org-edit-src-exit' handle them
19799 (org-get-indentation))
19800 ((equal (downcase (match-string 1)) "example")
19801 (max (org-get-indentation)
19802 (org-get-indentation (match-string 0))))
19804 (org-get-indentation (match-string 0))))))
19805 ;; This line has nothing special, look at the previous relevant
19806 ;; line to compute indentation
19808 (beginning-of-line 0)
19809 (while (and (not (bobp))
19810 (not (looking-at org-drawer-regexp))
19811 ;; When point started in an inline task, do not move
19812 ;; above task starting line.
19813 (not (and inline-task-p (looking-at inline-re)))
19814 ;; Skip drawers, blocks, empty lines, verbatim,
19815 ;; comments, tables, footnotes definitions, lists,
19816 ;; inline tasks.
19817 (or (and (looking-at "[ \t]*:END:")
19818 (re-search-backward org-drawer-regexp nil t))
19819 (and (looking-at "[ \t]*#\\+end_")
19820 (re-search-backward "[ \t]*#\\+begin_"nil t))
19821 (looking-at "[ \t]*[\n:#|]")
19822 (looking-at org-footnote-definition-re)
19823 (and (ignore-errors (goto-char (org-in-item-p)))
19824 (goto-char
19825 (org-list-get-top-point (org-list-struct))))
19826 (and (not inline-task-p)
19827 (featurep 'org-inlinetask)
19828 (org-inlinetask-in-task-p)
19829 (or (org-inlinetask-goto-beginning) t))))
19830 (beginning-of-line 0))
19831 (cond
19832 ;; There was an heading above.
19833 ((looking-at "\\*+[ \t]+")
19834 (if (not org-adapt-indentation)
19835 (setq column 0)
19836 (goto-char (match-end 0))
19837 (setq column (current-column))))
19838 ;; A drawer had started and is unfinished
19839 ((looking-at org-drawer-regexp)
19840 (goto-char (1- (match-beginning 1)))
19841 (setq column (current-column)))
19842 ;; Else, nothing noticeable found: get indentation and go on.
19843 (t (setq column (org-get-indentation))))))
19844 ;; Now apply indentation and move cursor accordingly
19845 (goto-char pos)
19846 (if (<= (current-column) (current-indentation))
19847 (org-indent-line-to column)
19848 (save-excursion (org-indent-line-to column)))
19849 ;; Special polishing for properties, see `org-property-format'
19850 (setq column (current-column))
19851 (beginning-of-line 1)
19852 (if (looking-at
19853 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
19854 (replace-match (concat (match-string 1)
19855 (format org-property-format
19856 (match-string 2) (match-string 3)))
19857 t t))
19858 (org-move-to-column column)))
19860 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
19861 "Variable to store copy of `adaptive-fill-regexp'.
19862 Since `adaptive-fill-regexp' is set to never match, we need to
19863 store a backup of its value before entering `org-mode' so that
19864 the functionality can be provided as a fall-back.")
19866 (defun org-set-autofill-regexps ()
19867 (interactive)
19868 ;; In the paragraph separator we include headlines, because filling
19869 ;; text in a line directly attached to a headline would otherwise
19870 ;; fill the headline as well.
19871 (org-set-local 'comment-start-skip "^#+[ \t]*")
19872 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
19873 ;; The paragraph starter includes hand-formatted lists.
19874 (org-set-local
19875 'paragraph-start
19876 (concat
19877 "\f" "\\|"
19878 "[ ]*$" "\\|"
19879 org-outline-regexp "\\|"
19880 "[ \t]*#" "\\|"
19881 (org-item-re) "\\|"
19882 "[ \t]*[:|]" "\\|"
19883 "\\$\\$" "\\|"
19884 "\\\\\\(begin\\|end\\|[][]\\)"))
19885 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
19886 ;; But only if the user has not turned off tables or fixed-width regions
19887 (org-set-local
19888 'auto-fill-inhibit-regexp
19889 (concat org-outline-regexp
19890 "\\|#\\+"
19891 "\\|[ \t]*" org-keyword-time-regexp
19892 (if (or org-enable-table-editor org-enable-fixed-width-editor)
19893 (concat
19894 "\\|[ \t]*["
19895 (if org-enable-table-editor "|" "")
19896 (if org-enable-fixed-width-editor ":" "")
19897 "]"))))
19898 ;; We use our own fill-paragraph function, to make sure that tables
19899 ;; and fixed-width regions are not wrapped. That function will pass
19900 ;; through to `fill-paragraph' when appropriate.
19901 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
19902 ;; Prevent auto-fill from inserting unwanted new items.
19903 (if (boundp 'fill-nobreak-predicate)
19904 (org-set-local 'fill-nobreak-predicate
19905 (if (memq 'org-fill-item-nobreak-p fill-nobreak-predicate)
19906 fill-nobreak-predicate
19907 (cons 'org-fill-item-nobreak-p fill-nobreak-predicate))))
19908 ;; Adaptive filling: To get full control, first make sure that
19909 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
19910 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
19911 (org-set-local 'org-adaptive-fill-regexp-backup
19912 adaptive-fill-regexp))
19913 (org-set-local 'adaptive-fill-regexp "\000")
19914 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
19915 (org-set-local 'adaptive-fill-function
19916 'org-adaptive-fill-function)
19917 (org-set-local
19918 'align-mode-rules-list
19919 '((org-in-buffer-settings
19920 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
19921 (modes . '(org-mode))))))
19923 (defun org-fill-item-nobreak-p ()
19924 "Non-nil when a line break at point would insert a new item."
19925 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
19927 (defun org-fill-paragraph (&optional justify)
19928 "Re-align a table, pass through to fill-paragraph if no table."
19929 (let ((table-p (org-at-table-p))
19930 (table.el-p (org-at-table.el-p))
19931 (itemp (org-in-item-p)))
19932 (cond ((and (equal (char-after (point-at-bol)) ?*)
19933 (save-excursion (goto-char (point-at-bol))
19934 (looking-at org-outline-regexp)))
19935 t) ; skip headlines
19936 (table.el-p t) ; skip table.el tables
19937 (table-p (org-table-align) t) ; align Org tables
19938 (itemp ; align text in items
19939 (let* ((struct (save-excursion (goto-char itemp)
19940 (org-list-struct)))
19941 (parents (org-list-parents-alist struct))
19942 (children (org-list-get-children itemp struct parents))
19943 beg end prev next prefix)
19944 ;; Determine in which part of item point is: before
19945 ;; first child, after last child, between two
19946 ;; sub-lists, or simply in item if there's no child.
19947 (cond
19948 ((not children)
19949 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
19950 beg itemp
19951 end (org-list-get-item-end itemp struct)))
19952 ((< (point) (setq next (car children)))
19953 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
19954 beg itemp
19955 end next))
19956 ((> (point) (setq prev (car (last children))))
19957 (setq beg (org-list-get-item-end prev struct)
19958 end (org-list-get-item-end itemp struct)
19959 prefix (save-excursion
19960 (goto-char beg)
19961 (skip-chars-forward " \t")
19962 (make-string (current-column) ?\ ))))
19963 (t (catch 'exit
19964 (while (setq next (pop children))
19965 (if (> (point) next)
19966 (setq prev next)
19967 (setq beg (org-list-get-item-end prev struct)
19968 end next
19969 prefix (save-excursion
19970 (goto-char beg)
19971 (skip-chars-forward " \t")
19972 (make-string (current-column) ?\ )))
19973 (throw 'exit nil))))))
19974 ;; Use `fill-paragraph' with buffer narrowed to item
19975 ;; without any child, and with our computed PREFIX.
19976 (flet ((fill-context-prefix (from to &optional flr) prefix))
19977 (save-restriction
19978 (narrow-to-region beg end)
19979 (save-excursion (fill-paragraph justify)))) t))
19980 ;; Special case where point is not in a list but is on
19981 ;; a paragraph adjacent to a list: make sure this paragraph
19982 ;; doesn't get merged with the end of the list by narrowing
19983 ;; buffer first.
19984 ((save-excursion (forward-paragraph -1)
19985 (setq itemp (org-in-item-p)))
19986 (let ((struct (save-excursion (goto-char itemp)
19987 (org-list-struct))))
19988 (save-restriction
19989 (narrow-to-region (org-list-get-bottom-point struct)
19990 (save-excursion (forward-paragraph 1)
19991 (point)))
19992 (fill-paragraph justify) t)))
19993 ;; Else simply call `fill-paragraph'.
19994 (t nil))))
19996 ;; For reference, this is the default value of adaptive-fill-regexp
19997 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
19999 (defun org-adaptive-fill-function ()
20000 "Return a fill prefix for org-mode files."
20001 (let (itemp)
20002 (save-excursion
20003 (cond
20004 ;; Comment line
20005 ((looking-at "#[ \t]+")
20006 (match-string-no-properties 0))
20007 ;; Plain list item
20008 ((org-at-item-p)
20009 (make-string (org-list-item-body-column (point-at-bol)) ?\ ))
20010 ;; Point is in a list after `backward-paragraph': original
20011 ;; point wasn't in the list, or filling would have been taken
20012 ;; care of by `org-auto-fill-function', but the list and the
20013 ;; real paragraph are not separated by a blank line. Thus, move
20014 ;; point after the list to go back to real paragraph and
20015 ;; determine fill-prefix.
20016 ((setq itemp (org-in-item-p))
20017 (goto-char itemp)
20018 (let* ((struct (org-list-struct))
20019 (bottom (org-list-get-bottom-point struct)))
20020 (goto-char bottom)
20021 (make-string (org-get-indentation) ?\ )))
20022 ;; Other text
20023 ((looking-at org-adaptive-fill-regexp-backup)
20024 (match-string-no-properties 0))))))
20026 (defun org-auto-fill-function ()
20027 "Auto-fill function."
20028 (let (itemp prefix)
20029 ;; When in a list, compute an appropriate fill-prefix and make
20030 ;; sure it will be used by `do-auto-fill'.
20031 (if (setq itemp (org-in-item-p))
20032 (progn
20033 (setq prefix (make-string (org-list-item-body-column itemp) ?\ ))
20034 (flet ((fill-context-prefix (from to &optional flr) prefix))
20035 (do-auto-fill)))
20036 ;; Else just use `do-auto-fill'.
20037 (do-auto-fill))))
20039 ;;; Other stuff.
20041 (defun org-toggle-fixed-width-section (arg)
20042 "Toggle the fixed-width export.
20043 If there is no active region, the QUOTE keyword at the current headline is
20044 inserted or removed. When present, it causes the text between this headline
20045 and the next to be exported as fixed-width text, and unmodified.
20046 If there is an active region, this command adds or removes a colon as the
20047 first character of this line. If the first character of a line is a colon,
20048 this line is also exported in fixed-width font."
20049 (interactive "P")
20050 (let* ((cc 0)
20051 (regionp (org-region-active-p))
20052 (beg (if regionp (region-beginning) (point)))
20053 (end (if regionp (region-end)))
20054 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
20055 (case-fold-search nil)
20056 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
20057 off)
20058 (if regionp
20059 (save-excursion
20060 (goto-char beg)
20061 (setq cc (current-column))
20062 (beginning-of-line 1)
20063 (setq off (looking-at re))
20064 (while (> nlines 0)
20065 (setq nlines (1- nlines))
20066 (beginning-of-line 1)
20067 (cond
20068 (arg
20069 (org-move-to-column cc t)
20070 (insert ": \n")
20071 (forward-line -1))
20072 ((and off (looking-at re))
20073 (replace-match "" t t nil 1))
20074 ((not off) (org-move-to-column cc t) (insert ": ")))
20075 (forward-line 1)))
20076 (save-excursion
20077 (org-back-to-heading)
20078 (cond
20079 ((looking-at (format org-heading-keyword-regexp-format
20080 org-quote-string))
20081 (goto-char (match-end 1))
20082 (looking-at (concat " +" org-quote-string))
20083 (replace-match "" t t)
20084 (when (eolp) (insert " ")))
20085 ((looking-at org-outline-regexp)
20086 (goto-char (match-end 0))
20087 (insert org-quote-string " ")))))))
20089 (defun org-reftex-citation ()
20090 "Use reftex-citation to insert a citation into the buffer.
20091 This looks for a line like
20093 #+BIBLIOGRAPHY: foo plain option:-d
20095 and derives from it that foo.bib is the bibliography file relevant
20096 for this document. It then installs the necessary environment for RefTeX
20097 to work in this buffer and calls `reftex-citation' to insert a citation
20098 into the buffer.
20100 Export of such citations to both LaTeX and HTML is handled by the contributed
20101 package org-exp-bibtex by Taru Karttunen."
20102 (interactive)
20103 (let ((reftex-docstruct-symbol 'rds)
20104 (reftex-cite-format "\\cite{%l}")
20105 rds bib)
20106 (save-excursion
20107 (save-restriction
20108 (widen)
20109 (let ((case-fold-search t)
20110 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
20111 (if (not (save-excursion
20112 (or (re-search-forward re nil t)
20113 (re-search-backward re nil t))))
20114 (error "No bibliography defined in file")
20115 (setq bib (concat (match-string 1) ".bib")
20116 rds (list (list 'bib bib)))))))
20117 (call-interactively 'reftex-citation)))
20119 ;;;; Functions extending outline functionality
20121 (defun org-beginning-of-line (&optional arg)
20122 "Go to the beginning of the current line. If that is invisible, continue
20123 to a visible line beginning. This makes the function of C-a more intuitive.
20124 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20125 first attempt, and only move to after the tags when the cursor is already
20126 beyond the end of the headline."
20127 (interactive "P")
20128 (let ((pos (point))
20129 (special (if (consp org-special-ctrl-a/e)
20130 (car org-special-ctrl-a/e)
20131 org-special-ctrl-a/e))
20132 refpos)
20133 (if (org-bound-and-true-p line-move-visual)
20134 (beginning-of-visual-line 1)
20135 (beginning-of-line 1))
20136 (if (and arg (fboundp 'move-beginning-of-line))
20137 (call-interactively 'move-beginning-of-line)
20138 (if (bobp)
20140 (backward-char 1)
20141 (if (org-truely-invisible-p)
20142 (while (and (not (bobp)) (org-truely-invisible-p))
20143 (backward-char 1)
20144 (beginning-of-line 1))
20145 (forward-char 1))))
20146 (when special
20147 (cond
20148 ((and (looking-at org-complex-heading-regexp)
20149 (= (char-after (match-end 1)) ?\ ))
20150 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
20151 (point-at-eol)))
20152 (goto-char
20153 (if (eq special t)
20154 (cond ((> pos refpos) refpos)
20155 ((= pos (point)) refpos)
20156 (t (point)))
20157 (cond ((> pos (point)) (point))
20158 ((not (eq last-command this-command)) (point))
20159 (t refpos)))))
20160 ((org-at-item-p)
20161 (goto-char
20162 (if (eq special t)
20163 (cond ((> pos (match-end 0)) (match-end 0))
20164 ((= pos (point)) (match-end 0))
20165 (t (point)))
20166 (cond ((> pos (point)) (point))
20167 ((not (eq last-command this-command)) (point))
20168 (t (match-end 0))))))))
20169 (org-no-warnings
20170 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20172 (defun org-end-of-line (&optional arg)
20173 "Go to the end of the line.
20174 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20175 first attempt, and only move to after the tags when the cursor is already
20176 beyond the end of the headline."
20177 (interactive "P")
20178 (let ((special (if (consp org-special-ctrl-a/e)
20179 (cdr org-special-ctrl-a/e)
20180 org-special-ctrl-a/e)))
20181 (cond
20182 ((or (not special) arg
20183 (not (or (org-on-heading-p) (org-at-item-p))))
20184 (call-interactively
20185 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
20186 ((fboundp 'move-end-of-line) 'move-end-of-line)
20187 (t 'end-of-line))))
20188 ((org-on-heading-p)
20189 (let ((pos (point)))
20190 (beginning-of-line 1)
20191 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
20192 (if (eq special t)
20193 (if (or (< pos (match-beginning 1))
20194 (= pos (match-end 0)))
20195 (goto-char (match-beginning 1))
20196 (goto-char (match-end 0)))
20197 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
20198 (goto-char (match-end 0))
20199 (goto-char (match-beginning 1))))
20200 (call-interactively (if (fboundp 'move-end-of-line)
20201 'move-end-of-line
20202 'end-of-line)))))
20203 ;; At an item: Move before any hidden text.
20204 (t (call-interactively 'end-of-line)))
20205 (org-no-warnings
20206 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20208 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
20209 (define-key org-mode-map "\C-e" 'org-end-of-line)
20211 (defun org-backward-sentence (&optional arg)
20212 "Go to beginning of sentence, or beginning of table field.
20213 This will call `backward-sentence' or `org-table-beginning-of-field',
20214 depending on context."
20215 (interactive "P")
20216 (cond
20217 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
20218 (t (call-interactively 'backward-sentence))))
20220 (defun org-forward-sentence (&optional arg)
20221 "Go to end of sentence, or end of table field.
20222 This will call `forward-sentence' or `org-table-end-of-field',
20223 depending on context."
20224 (interactive "P")
20225 (cond
20226 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
20227 (t (call-interactively 'forward-sentence))))
20229 (define-key org-mode-map "\M-a" 'org-backward-sentence)
20230 (define-key org-mode-map "\M-e" 'org-forward-sentence)
20232 (defun org-kill-line (&optional arg)
20233 "Kill line, to tags or end of line."
20234 (interactive "P")
20235 (cond
20236 ((or (not org-special-ctrl-k)
20237 (bolp)
20238 (not (org-on-heading-p)))
20239 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
20240 org-ctrl-k-protect-subtree)
20241 (if (or (eq org-ctrl-k-protect-subtree 'error)
20242 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
20243 (error "C-k aborted - would kill hidden subtree")))
20244 (call-interactively 'kill-line))
20245 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
20246 (kill-region (point) (match-beginning 1))
20247 (org-set-tags nil t))
20248 (t (kill-region (point) (point-at-eol)))))
20250 (define-key org-mode-map "\C-k" 'org-kill-line)
20252 (defun org-yank (&optional arg)
20253 "Yank. If the kill is a subtree, treat it specially.
20254 This command will look at the current kill and check if is a single
20255 subtree, or a series of subtrees[1]. If it passes the test, and if the
20256 cursor is at the beginning of a line or after the stars of a currently
20257 empty headline, then the yank is handled specially. How exactly depends
20258 on the value of the following variables, both set by default.
20260 org-yank-folded-subtrees
20261 When set, the subtree(s) will be folded after insertion, but only
20262 if doing so would now swallow text after the yanked text.
20264 org-yank-adjusted-subtrees
20265 When set, the subtree will be promoted or demoted in order to
20266 fit into the local outline tree structure, which means that the level
20267 will be adjusted so that it becomes the smaller one of the two
20268 *visible* surrounding headings.
20270 Any prefix to this command will cause `yank' to be called directly with
20271 no special treatment. In particular, a simple \\[universal-argument] prefix \
20272 will just
20273 plainly yank the text as it is.
20275 \[1] The test checks if the first non-white line is a heading
20276 and if there are no other headings with fewer stars."
20277 (interactive "P")
20278 (org-yank-generic 'yank arg))
20280 (defun org-yank-generic (command arg)
20281 "Perform some yank-like command.
20283 This function implements the behavior described in the `org-yank'
20284 documentation. However, it has been generalized to work for any
20285 interactive command with similar behavior."
20287 ;; pretend to be command COMMAND
20288 (setq this-command command)
20290 (if arg
20291 (call-interactively command)
20293 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
20294 (and (org-kill-is-subtree-p)
20295 (or (bolp)
20296 (and (looking-at "[ \t]*$")
20297 (string-match
20298 "\\`\\*+\\'"
20299 (buffer-substring (point-at-bol) (point)))))))
20300 swallowp)
20301 (cond
20302 ((and subtreep org-yank-folded-subtrees)
20303 (let ((beg (point))
20304 end)
20305 (if (and subtreep org-yank-adjusted-subtrees)
20306 (org-paste-subtree nil nil 'for-yank)
20307 (call-interactively command))
20309 (setq end (point))
20310 (goto-char beg)
20311 (when (and (bolp) subtreep
20312 (not (setq swallowp
20313 (org-yank-folding-would-swallow-text beg end))))
20314 (org-with-limited-levels
20315 (or (looking-at org-outline-regexp)
20316 (re-search-forward org-outline-regexp-bol end t))
20317 (while (and (< (point) end) (looking-at org-outline-regexp))
20318 (hide-subtree)
20319 (org-cycle-show-empty-lines 'folded)
20320 (condition-case nil
20321 (outline-forward-same-level 1)
20322 (error (goto-char end))))))
20323 (when swallowp
20324 (message
20325 "Inserted text not folded because that would swallow text"))
20327 (goto-char end)
20328 (skip-chars-forward " \t\n\r")
20329 (beginning-of-line 1)
20330 (push-mark beg 'nomsg)))
20331 ((and subtreep org-yank-adjusted-subtrees)
20332 (let ((beg (point-at-bol)))
20333 (org-paste-subtree nil nil 'for-yank)
20334 (push-mark beg 'nomsg)))
20336 (call-interactively command))))))
20338 (defun org-yank-folding-would-swallow-text (beg end)
20339 "Would hide-subtree at BEG swallow any text after END?"
20340 (let (level)
20341 (org-with-limited-levels
20342 (save-excursion
20343 (goto-char beg)
20344 (when (or (looking-at org-outline-regexp)
20345 (re-search-forward org-outline-regexp-bol end t))
20346 (setq level (org-outline-level)))
20347 (goto-char end)
20348 (skip-chars-forward " \t\r\n\v\f")
20349 (if (or (eobp)
20350 (and (bolp) (looking-at org-outline-regexp)
20351 (<= (org-outline-level) level)))
20352 nil ; Nothing would be swallowed
20353 t))))) ; something would swallow
20355 (define-key org-mode-map "\C-y" 'org-yank)
20357 (defun org-truely-invisible-p ()
20358 "Check if point is at a character currently not visible.
20359 This version does not only check the character property, but also
20360 `visible-mode'."
20361 ;; Early versions of noutline don't have `outline-invisible-p'.
20362 (if (org-bound-and-true-p visible-mode)
20364 (outline-invisible-p)))
20366 (defun org-invisible-p2 ()
20367 "Check if point is at a character currently not visible."
20368 (save-excursion
20369 (if (and (eolp) (not (bobp))) (backward-char 1))
20370 ;; Early versions of noutline don't have `outline-invisible-p'.
20371 (outline-invisible-p)))
20373 (defun org-back-to-heading (&optional invisible-ok)
20374 "Call `outline-back-to-heading', but provide a better error message."
20375 (condition-case nil
20376 (outline-back-to-heading invisible-ok)
20377 (error (error "Before first headline at position %d in buffer %s"
20378 (point) (current-buffer)))))
20380 (defun org-beginning-of-defun ()
20381 "Go to the beginning of the subtree, i.e. back to the heading."
20382 (org-back-to-heading))
20383 (defun org-end-of-defun ()
20384 "Go to the end of the subtree."
20385 (org-end-of-subtree nil t))
20387 (defun org-before-first-heading-p ()
20388 "Before first heading?"
20389 (save-excursion
20390 (end-of-line)
20391 (null (re-search-backward org-outline-regexp-bol nil t))))
20393 (defun org-on-heading-p (&optional ignored)
20394 (outline-on-heading-p t))
20395 (defun org-at-heading-p (&optional ignored)
20396 (outline-on-heading-p t))
20398 (defun org-point-at-end-of-empty-headline ()
20399 "If point is at the end of an empty headline, return t, else nil.
20400 If the heading only contains a TODO keyword, it is still still considered
20401 empty."
20402 (and (looking-at "[ \t]*$")
20403 (save-excursion
20404 (beginning-of-line 1)
20405 (let ((case-fold-search nil))
20406 (looking-at org-todo-line-regexp)))
20407 (string= (match-string 3) "")))
20409 (defun org-at-heading-or-item-p ()
20410 (or (org-on-heading-p) (org-at-item-p)))
20412 (defun org-on-target-p ()
20413 (or (org-in-regexp org-radio-target-regexp)
20414 (org-in-regexp org-target-regexp)))
20416 (defun org-up-heading-all (arg)
20417 "Move to the heading line of which the present line is a subheading.
20418 This function considers both visible and invisible heading lines.
20419 With argument, move up ARG levels."
20420 (if (fboundp 'outline-up-heading-all)
20421 (outline-up-heading-all arg) ; emacs 21 version of outline.el
20422 (outline-up-heading arg t))) ; emacs 22 version of outline.el
20424 (defun org-up-heading-safe ()
20425 "Move to the heading line of which the present line is a subheading.
20426 This version will not throw an error. It will return the level of the
20427 headline found, or nil if no higher level is found.
20429 Also, this function will be a lot faster than `outline-up-heading',
20430 because it relies on stars being the outline starters. This can really
20431 make a significant difference in outlines with very many siblings."
20432 (let (start-level re)
20433 (org-back-to-heading t)
20434 (setq start-level (funcall outline-level))
20435 (if (equal start-level 1)
20437 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
20438 (if (re-search-backward re nil t)
20439 (funcall outline-level)))))
20441 (defun org-first-sibling-p ()
20442 "Is this heading the first child of its parents?"
20443 (interactive)
20444 (let ((re org-outline-regexp-bol)
20445 level l)
20446 (unless (org-at-heading-p t)
20447 (error "Not at a heading"))
20448 (setq level (funcall outline-level))
20449 (save-excursion
20450 (if (not (re-search-backward re nil t))
20452 (setq l (funcall outline-level))
20453 (< l level)))))
20455 (defun org-goto-sibling (&optional previous)
20456 "Goto the next sibling, even if it is invisible.
20457 When PREVIOUS is set, go to the previous sibling instead. Returns t
20458 when a sibling was found. When none is found, return nil and don't
20459 move point."
20460 (let ((fun (if previous 're-search-backward 're-search-forward))
20461 (pos (point))
20462 (re org-outline-regexp-bol)
20463 level l)
20464 (when (condition-case nil (org-back-to-heading t) (error nil))
20465 (setq level (funcall outline-level))
20466 (catch 'exit
20467 (or previous (forward-char 1))
20468 (while (funcall fun re nil t)
20469 (setq l (funcall outline-level))
20470 (when (< l level) (goto-char pos) (throw 'exit nil))
20471 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
20472 (goto-char pos)
20473 nil))))
20475 (defun org-show-siblings ()
20476 "Show all siblings of the current headline."
20477 (save-excursion
20478 (while (org-goto-sibling) (org-flag-heading nil)))
20479 (save-excursion
20480 (while (org-goto-sibling 'previous)
20481 (org-flag-heading nil))))
20483 (defun org-goto-first-child ()
20484 "Goto the first child, even if it is invisible.
20485 Return t when a child was found. Otherwise don't move point and
20486 return nil."
20487 (let (level (pos (point)) (re org-outline-regexp-bol))
20488 (when (condition-case nil (org-back-to-heading t) (error nil))
20489 (setq level (outline-level))
20490 (forward-char 1)
20491 (if (and (re-search-forward re nil t) (> (outline-level) level))
20492 (progn (goto-char (match-beginning 0)) t)
20493 (goto-char pos) nil))))
20495 (defun org-show-hidden-entry ()
20496 "Show an entry where even the heading is hidden."
20497 (save-excursion
20498 (org-show-entry)))
20500 (defun org-flag-heading (flag &optional entry)
20501 "Flag the current heading. FLAG non-nil means make invisible.
20502 When ENTRY is non-nil, show the entire entry."
20503 (save-excursion
20504 (org-back-to-heading t)
20505 ;; Check if we should show the entire entry
20506 (if entry
20507 (progn
20508 (org-show-entry)
20509 (save-excursion
20510 (and (outline-next-heading)
20511 (org-flag-heading nil))))
20512 (outline-flag-region (max (point-min) (1- (point)))
20513 (save-excursion (outline-end-of-heading) (point))
20514 flag))))
20516 (defun org-get-next-sibling ()
20517 "Move to next heading of the same level, and return point.
20518 If there is no such heading, return nil.
20519 This is like outline-next-sibling, but invisible headings are ok."
20520 (let ((level (funcall outline-level)))
20521 (outline-next-heading)
20522 (while (and (not (eobp)) (> (funcall outline-level) level))
20523 (outline-next-heading))
20524 (if (or (eobp) (< (funcall outline-level) level))
20526 (point))))
20528 (defun org-get-last-sibling ()
20529 "Move to previous heading of the same level, and return point.
20530 If there is no such heading, return nil."
20531 (let ((opoint (point))
20532 (level (funcall outline-level)))
20533 (outline-previous-heading)
20534 (when (and (/= (point) opoint) (outline-on-heading-p t))
20535 (while (and (> (funcall outline-level) level)
20536 (not (bobp)))
20537 (outline-previous-heading))
20538 (if (< (funcall outline-level) level)
20540 (point)))))
20542 (defun org-end-of-subtree (&optional invisible-OK to-heading)
20543 ;; This contains an exact copy of the original function, but it uses
20544 ;; `org-back-to-heading', to make it work also in invisible
20545 ;; trees. And is uses an invisible-OK argument.
20546 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
20547 ;; Furthermore, when used inside Org, finding the end of a large subtree
20548 ;; with many children and grandchildren etc, this can be much faster
20549 ;; than the outline version.
20550 (org-back-to-heading invisible-OK)
20551 (let ((first t)
20552 (level (funcall outline-level)))
20553 (if (and (eq major-mode 'org-mode) (< level 1000))
20554 ;; A true heading (not a plain list item), in Org-mode
20555 ;; This means we can easily find the end by looking
20556 ;; only for the right number of stars. Using a regexp to do
20557 ;; this is so much faster than using a Lisp loop.
20558 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
20559 (forward-char 1)
20560 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
20561 ;; something else, do it the slow way
20562 (while (and (not (eobp))
20563 (or first (> (funcall outline-level) level)))
20564 (setq first nil)
20565 (outline-next-heading)))
20566 (unless to-heading
20567 (if (memq (preceding-char) '(?\n ?\^M))
20568 (progn
20569 ;; Go to end of line before heading
20570 (forward-char -1)
20571 (if (memq (preceding-char) '(?\n ?\^M))
20572 ;; leave blank line before heading
20573 (forward-char -1))))))
20574 (point))
20576 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
20577 "Use Org version in org-mode, for dramatic speed-up."
20578 (if (eq major-mode 'org-mode)
20579 (progn
20580 (org-end-of-subtree nil t)
20581 (unless (eobp) (backward-char 1)))
20582 ad-do-it))
20584 (defun org-end-of-meta-data-and-drawers ()
20585 "Jump to the first text after meta data and drawers in the current entry.
20586 This will move over empty lines, lines with planning time stamps,
20587 clocking lines, and drawers."
20588 (org-back-to-heading t)
20589 (let ((end (save-excursion (outline-next-heading) (point)))
20590 (re (concat "\\(" org-drawer-regexp "\\)"
20591 "\\|" "[ \t]*" org-keyword-time-regexp)))
20592 (forward-line 1)
20593 (while (re-search-forward re end t)
20594 (if (not (match-end 1))
20595 ;; empty or planning line
20596 (forward-line 1)
20597 ;; a drawer, find the end
20598 (re-search-forward "^[ \t]*:END:" end 'move)
20599 (forward-line 1)))
20600 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
20601 (point)))
20603 (defun org-forward-same-level (arg &optional invisible-ok)
20604 "Move forward to the arg'th subheading at same level as this one.
20605 Stop at the first and last subheadings of a superior heading.
20606 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
20607 it wil also look at invisible ones."
20608 (interactive "p")
20609 (org-back-to-heading invisible-ok)
20610 (org-on-heading-p)
20611 (let* ((level (- (match-end 0) (match-beginning 0) 1))
20612 (re (format "^\\*\\{1,%d\\} " level))
20614 (forward-char 1)
20615 (while (> arg 0)
20616 (while (and (re-search-forward re nil 'move)
20617 (setq l (- (match-end 0) (match-beginning 0) 1))
20618 (= l level)
20619 (not invisible-ok)
20620 (progn (backward-char 1) (outline-invisible-p)))
20621 (if (< l level) (setq arg 1)))
20622 (setq arg (1- arg)))
20623 (beginning-of-line 1)))
20625 (defun org-backward-same-level (arg &optional invisible-ok)
20626 "Move backward to the arg'th subheading at same level as this one.
20627 Stop at the first and last subheadings of a superior heading."
20628 (interactive "p")
20629 (org-back-to-heading)
20630 (org-on-heading-p)
20631 (let* ((level (- (match-end 0) (match-beginning 0) 1))
20632 (re (format "^\\*\\{1,%d\\} " level))
20634 (while (> arg 0)
20635 (while (and (re-search-backward re nil 'move)
20636 (setq l (- (match-end 0) (match-beginning 0) 1))
20637 (= l level)
20638 (not invisible-ok)
20639 (outline-invisible-p))
20640 (if (< l level) (setq arg 1)))
20641 (setq arg (1- arg)))))
20643 (defun org-show-subtree ()
20644 "Show everything after this heading at deeper levels."
20645 (outline-flag-region
20646 (point)
20647 (save-excursion
20648 (org-end-of-subtree t t))
20649 nil))
20651 (defun org-show-entry ()
20652 "Show the body directly following this heading.
20653 Show the heading too, if it is currently invisible."
20654 (interactive)
20655 (save-excursion
20656 (condition-case nil
20657 (progn
20658 (org-back-to-heading t)
20659 (outline-flag-region
20660 (max (point-min) (1- (point)))
20661 (save-excursion
20662 (if (re-search-forward
20663 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
20664 (match-beginning 1)
20665 (point-max)))
20666 nil)
20667 (org-cycle-hide-drawers 'children))
20668 (error nil))))
20670 (defun org-make-options-regexp (kwds &optional extra)
20671 "Make a regular expression for keyword lines."
20672 (concat
20674 "#?[ \t]*\\+\\("
20675 (mapconcat 'regexp-quote kwds "\\|")
20676 (if extra (concat "\\|" extra))
20677 "\\):[ \t]*"
20678 "\\(.*\\)"))
20680 ;; Make isearch reveal the necessary context
20681 (defun org-isearch-end ()
20682 "Reveal context after isearch exits."
20683 (when isearch-success ; only if search was successful
20684 (if (featurep 'xemacs)
20685 ;; Under XEmacs, the hook is run in the correct place,
20686 ;; we directly show the context.
20687 (org-show-context 'isearch)
20688 ;; In Emacs the hook runs *before* restoring the overlays.
20689 ;; So we have to use a one-time post-command-hook to do this.
20690 ;; (Emacs 22 has a special variable, see function `org-mode')
20691 (unless (and (boundp 'isearch-mode-end-hook-quit)
20692 isearch-mode-end-hook-quit)
20693 ;; Only when the isearch was not quitted.
20694 (org-add-hook 'post-command-hook 'org-isearch-post-command
20695 'append 'local)))))
20697 (defun org-isearch-post-command ()
20698 "Remove self from hook, and show context."
20699 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
20700 (org-show-context 'isearch))
20703 ;;;; Integration with and fixes for other packages
20705 ;;; Imenu support
20707 (defvar org-imenu-markers nil
20708 "All markers currently used by Imenu.")
20709 (make-variable-buffer-local 'org-imenu-markers)
20711 (defun org-imenu-new-marker (&optional pos)
20712 "Return a new marker for use by Imenu, and remember the marker."
20713 (let ((m (make-marker)))
20714 (move-marker m (or pos (point)))
20715 (push m org-imenu-markers)
20718 (defun org-imenu-get-tree ()
20719 "Produce the index for Imenu."
20720 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
20721 (setq org-imenu-markers nil)
20722 (let* ((n org-imenu-depth)
20723 (re (concat "^" (org-get-limited-outline-regexp)))
20724 (subs (make-vector (1+ n) nil))
20725 (last-level 0)
20726 m level head)
20727 (save-excursion
20728 (save-restriction
20729 (widen)
20730 (goto-char (point-max))
20731 (while (re-search-backward re nil t)
20732 (setq level (org-reduced-level (funcall outline-level)))
20733 (when (<= level n)
20734 (looking-at org-complex-heading-regexp)
20735 (setq head (org-link-display-format
20736 (org-match-string-no-properties 4))
20737 m (org-imenu-new-marker))
20738 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
20739 (if (>= level last-level)
20740 (push (cons head m) (aref subs level))
20741 (push (cons head (aref subs (1+ level))) (aref subs level))
20742 (loop for i from (1+ level) to n do (aset subs i nil)))
20743 (setq last-level level)))))
20744 (aref subs 1)))
20746 (eval-after-load "imenu"
20747 '(progn
20748 (add-hook 'imenu-after-jump-hook
20749 (lambda ()
20750 (if (eq major-mode 'org-mode)
20751 (org-show-context 'org-goto))))))
20753 (defun org-link-display-format (link)
20754 "Replace a link with either the description, or the link target
20755 if no description is present"
20756 (save-match-data
20757 (if (string-match org-bracket-link-analytic-regexp link)
20758 (replace-match (if (match-end 5)
20759 (match-string 5 link)
20760 (concat (match-string 1 link)
20761 (match-string 3 link)))
20762 nil t link)
20763 link)))
20765 (defun org-toggle-link-display ()
20766 "Toggle the literal or descriptive display of links."
20767 (interactive)
20768 (if org-descriptive-links
20769 (progn (org-remove-from-invisibility-spec '(org-link))
20770 (org-restart-font-lock)
20771 (setq org-descriptive-links nil))
20772 (progn (add-to-invisibility-spec '(org-link))
20773 (org-restart-font-lock)
20774 (setq org-descriptive-links t))))
20776 ;; Speedbar support
20778 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
20779 "Overlay marking the agenda restriction line in speedbar.")
20780 (overlay-put org-speedbar-restriction-lock-overlay
20781 'face 'org-agenda-restriction-lock)
20782 (overlay-put org-speedbar-restriction-lock-overlay
20783 'help-echo "Agendas are currently limited to this item.")
20784 (org-detach-overlay org-speedbar-restriction-lock-overlay)
20786 (defun org-speedbar-set-agenda-restriction ()
20787 "Restrict future agenda commands to the location at point in speedbar.
20788 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
20789 (interactive)
20790 (require 'org-agenda)
20791 (let (p m tp np dir txt)
20792 (cond
20793 ((setq p (text-property-any (point-at-bol) (point-at-eol)
20794 'org-imenu t))
20795 (setq m (get-text-property p 'org-imenu-marker))
20796 (with-current-buffer (marker-buffer m)
20797 (goto-char m)
20798 (org-agenda-set-restriction-lock 'subtree)))
20799 ((setq p (text-property-any (point-at-bol) (point-at-eol)
20800 'speedbar-function 'speedbar-find-file))
20801 (setq tp (previous-single-property-change
20802 (1+ p) 'speedbar-function)
20803 np (next-single-property-change
20804 tp 'speedbar-function)
20805 dir (speedbar-line-directory)
20806 txt (buffer-substring-no-properties (or tp (point-min))
20807 (or np (point-max))))
20808 (with-current-buffer (find-file-noselect
20809 (let ((default-directory dir))
20810 (expand-file-name txt)))
20811 (unless (eq major-mode 'org-mode)
20812 (error "Cannot restrict to non-Org-mode file"))
20813 (org-agenda-set-restriction-lock 'file)))
20814 (t (error "Don't know how to restrict Org-mode's agenda")))
20815 (move-overlay org-speedbar-restriction-lock-overlay
20816 (point-at-bol) (point-at-eol))
20817 (setq current-prefix-arg nil)
20818 (org-agenda-maybe-redo)))
20820 (eval-after-load "speedbar"
20821 '(progn
20822 (speedbar-add-supported-extension ".org")
20823 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
20824 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
20825 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
20826 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
20827 (add-hook 'speedbar-visiting-tag-hook
20828 (lambda () (and (eq major-mode 'org-mode) (org-show-context 'org-goto))))))
20830 ;;; Fixes and Hacks for problems with other packages
20832 ;; Make flyspell not check words in links, to not mess up our keymap
20833 (defun org-mode-flyspell-verify ()
20834 "Don't let flyspell put overlays at active buttons, or on
20835 {todo,all-time,additional-option-like}-keywords."
20836 (let ((pos (max (1- (point)) (point-min)))
20837 (word (thing-at-point 'word)))
20838 (and (not (get-text-property pos 'keymap))
20839 (not (get-text-property pos 'org-no-flyspell))
20840 (not (member word org-todo-keywords-1))
20841 (not (member word org-all-time-keywords))
20842 (not (member word org-additional-option-like-keywords)))))
20844 (defun org-remove-flyspell-overlays-in (beg end)
20845 "Remove flyspell overlays in region."
20846 (and (org-bound-and-true-p flyspell-mode)
20847 (fboundp 'flyspell-delete-region-overlays)
20848 (flyspell-delete-region-overlays beg end))
20849 (add-text-properties beg end '(org-no-flyspell t)))
20851 ;; Make `bookmark-jump' shows the jump location if it was hidden.
20852 (eval-after-load "bookmark"
20853 '(if (boundp 'bookmark-after-jump-hook)
20854 ;; We can use the hook
20855 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
20856 ;; Hook not available, use advice
20857 (defadvice bookmark-jump (after org-make-visible activate)
20858 "Make the position visible."
20859 (org-bookmark-jump-unhide))))
20861 ;; Make sure saveplace shows the location if it was hidden
20862 (eval-after-load "saveplace"
20863 '(defadvice save-place-find-file-hook (after org-make-visible activate)
20864 "Make the position visible."
20865 (org-bookmark-jump-unhide)))
20867 ;; Make sure ecb shows the location if it was hidden
20868 (eval-after-load "ecb"
20869 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
20870 "Make hierarchy visible when jumping into location from ECB tree buffer."
20871 (if (eq major-mode 'org-mode)
20872 (org-show-context))))
20874 (defun org-bookmark-jump-unhide ()
20875 "Unhide the current position, to show the bookmark location."
20876 (and (eq major-mode 'org-mode)
20877 (or (outline-invisible-p)
20878 (save-excursion (goto-char (max (point-min) (1- (point))))
20879 (outline-invisible-p)))
20880 (org-show-context 'bookmark-jump)))
20882 ;; Make session.el ignore our circular variable
20883 (eval-after-load "session"
20884 '(add-to-list 'session-globals-exclude 'org-mark-ring))
20886 ;;;; Experimental code
20888 (defun org-closed-in-range ()
20889 "Sparse tree of items closed in a certain time range.
20890 Still experimental, may disappear in the future."
20891 (interactive)
20892 ;; Get the time interval from the user.
20893 (let* ((time1 (org-float-time
20894 (org-read-date nil 'to-time nil "Starting date: ")))
20895 (time2 (org-float-time
20896 (org-read-date nil 'to-time nil "End date:")))
20897 ;; callback function
20898 (callback (lambda ()
20899 (let ((time
20900 (org-float-time
20901 (apply 'encode-time
20902 (org-parse-time-string
20903 (match-string 1))))))
20904 ;; check if time in interval
20905 (and (>= time time1) (<= time time2))))))
20906 ;; make tree, check each match with the callback
20907 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
20909 ;;;; Finish up
20911 (provide 'org)
20913 (run-hooks 'org-load-hook)
20915 ;;; org.el ends here