org-capture.el: improve docstring for `org-capture-before-finalize-hook'.
[org-mode.git] / lisp / org.el
blobfe45cf7de53b7510b7d20c8f0992479d7477f9fb
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 default-description)
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.
9036 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9037 be used as the default description."
9038 (interactive "P")
9039 (let* ((wcf (current-window-configuration))
9040 (region (if (org-region-active-p)
9041 (buffer-substring (region-beginning) (region-end))))
9042 (remove (and region (list (region-beginning) (region-end))))
9043 (desc region)
9044 tmphist ; byte-compile incorrectly complains about this
9045 (link link-location)
9046 entry file all-prefixes)
9047 (cond
9048 (link-location) ; specified by arg, just use it.
9049 ((org-in-regexp org-bracket-link-regexp 1)
9050 ;; We do have a link at point, and we are going to edit it.
9051 (setq remove (list (match-beginning 0) (match-end 0)))
9052 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9053 (setq link (read-string "Link: "
9054 (org-link-unescape
9055 (org-match-string-no-properties 1)))))
9056 ((or (org-in-regexp org-angle-link-re)
9057 (org-in-regexp org-plain-link-re))
9058 ;; Convert to bracket link
9059 (setq remove (list (match-beginning 0) (match-end 0))
9060 link (read-string "Link: "
9061 (org-remove-angle-brackets (match-string 0)))))
9062 ((member complete-file '((4) (16)))
9063 ;; Completing read for file names.
9064 (setq link (org-file-complete-link complete-file)))
9066 ;; Read link, with completion for stored links.
9067 (with-output-to-temp-buffer "*Org Links*"
9068 (princ "Insert a link.
9069 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9070 (when org-stored-links
9071 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9072 (princ (mapconcat
9073 (lambda (x)
9074 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
9075 (reverse org-stored-links) "\n"))))
9076 (let ((cw (selected-window)))
9077 (select-window (get-buffer-window "*Org Links*" 'visible))
9078 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9079 (unless (pos-visible-in-window-p (point-max))
9080 (org-fit-window-to-buffer))
9081 (and (window-live-p cw) (select-window cw)))
9082 ;; Fake a link history, containing the stored links.
9083 (setq tmphist (append (mapcar 'car org-stored-links)
9084 org-insert-link-history))
9085 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
9086 (mapcar 'car org-link-abbrev-alist)
9087 org-link-types))
9088 (unwind-protect
9089 (progn
9090 (setq link
9091 (let ((org-completion-use-ido nil)
9092 (org-completion-use-iswitchb nil))
9093 (org-completing-read
9094 "Link: "
9095 (append
9096 (mapcar (lambda (x) (list (concat x ":")))
9097 all-prefixes)
9098 (mapcar 'car org-stored-links))
9099 nil nil nil
9100 'tmphist
9101 (car (car org-stored-links)))))
9102 (if (not (string-match "\\S-" link))
9103 (error "No link selected"))
9104 (if (or (member link all-prefixes)
9105 (and (equal ":" (substring link -1))
9106 (member (substring link 0 -1) all-prefixes)
9107 (setq link (substring link 0 -1))))
9108 (setq link (org-link-try-special-completion link))))
9109 (set-window-configuration wcf)
9110 (kill-buffer "*Org Links*"))
9111 (setq entry (assoc link org-stored-links))
9112 (or entry (push link org-insert-link-history))
9113 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9114 (not org-keep-stored-link-after-insertion))
9115 (setq org-stored-links (delq (assoc link org-stored-links)
9116 org-stored-links)))
9117 (setq desc (or desc (nth 1 entry)))))
9119 (if (string-match org-plain-link-re link)
9120 ;; URL-like link, normalize the use of angular brackets.
9121 (setq link (org-make-link (org-remove-angle-brackets link))))
9123 ;; Check if we are linking to the current file with a search option
9124 ;; If yes, simplify the link by using only the search option.
9125 (when (and buffer-file-name
9126 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9127 (let* ((path (match-string 1 link))
9128 (case-fold-search nil)
9129 (search (match-string 2 link)))
9130 (save-match-data
9131 (if (equal (file-truename buffer-file-name) (file-truename path))
9132 ;; We are linking to this same file, with a search option
9133 (setq link search)))))
9135 ;; Check if we can/should use a relative path. If yes, simplify the link
9136 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9137 (let* ((type (match-string 1 link))
9138 (path (match-string 2 link))
9139 (origpath path)
9140 (case-fold-search nil))
9141 (cond
9142 ((or (eq org-link-file-path-type 'absolute)
9143 (equal complete-file '(16)))
9144 (setq path (abbreviate-file-name (expand-file-name path))))
9145 ((eq org-link-file-path-type 'noabbrev)
9146 (setq path (expand-file-name path)))
9147 ((eq org-link-file-path-type 'relative)
9148 (setq path (file-relative-name path)))
9150 (save-match-data
9151 (if (string-match (concat "^" (regexp-quote
9152 (expand-file-name
9153 (file-name-as-directory
9154 default-directory))))
9155 (expand-file-name path))
9156 ;; We are linking a file with relative path name.
9157 (setq path (substring (expand-file-name path)
9158 (match-end 0)))
9159 (setq path (abbreviate-file-name (expand-file-name path)))))))
9160 (setq link (concat type path))
9161 (if (equal desc origpath)
9162 (setq desc path))))
9164 (if org-make-link-description-function
9165 (setq desc (funcall org-make-link-description-function link desc)))
9167 (if default-description (setq desc default-description))
9168 (setq desc (read-string "Description: " desc))
9169 (unless (string-match "\\S-" desc) (setq desc nil))
9170 (if remove (apply 'delete-region remove))
9171 (insert (org-make-link-string link desc))))
9173 (defun org-link-try-special-completion (type)
9174 "If there is completion support for link type TYPE, offer it."
9175 (let ((fun (intern (concat "org-" type "-complete-link"))))
9176 (if (functionp fun)
9177 (funcall fun)
9178 (read-string "Link (no completion support): " (concat type ":")))))
9180 (defun org-file-complete-link (&optional arg)
9181 "Create a file link using completion."
9182 (let (file link)
9183 (setq file (read-file-name "File: "))
9184 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9185 (pwd1 (file-name-as-directory (abbreviate-file-name
9186 (expand-file-name ".")))))
9187 (cond
9188 ((equal arg '(16))
9189 (setq link (org-make-link
9190 "file:"
9191 (abbreviate-file-name (expand-file-name file)))))
9192 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9193 (setq link (org-make-link "file:" (match-string 1 file))))
9194 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9195 (expand-file-name file))
9196 (setq link (org-make-link
9197 "file:" (match-string 1 (expand-file-name file)))))
9198 (t (setq link (org-make-link "file:" file)))))
9199 link))
9201 (defun org-completing-read (&rest args)
9202 "Completing-read with SPACE being a normal character."
9203 (let ((enable-recursive-minibuffers t)
9204 (minibuffer-local-completion-map
9205 (copy-keymap minibuffer-local-completion-map)))
9206 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9207 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9208 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9209 (apply 'org-icompleting-read args)))
9211 (defun org-completing-read-no-i (&rest args)
9212 (let (org-completion-use-ido org-completion-use-iswitchb)
9213 (apply 'org-completing-read args)))
9215 (defun org-iswitchb-completing-read (prompt choices &rest args)
9216 "Use iswitch as a completing-read replacement to choose from choices.
9217 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9218 from."
9219 (let* ((iswitchb-use-virtual-buffers nil)
9220 (iswitchb-make-buflist-hook
9221 (lambda ()
9222 (setq iswitchb-temp-buflist choices))))
9223 (iswitchb-read-buffer prompt)))
9225 (defun org-icompleting-read (&rest args)
9226 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9227 (org-without-partial-completion
9228 (if (and org-completion-use-ido
9229 (fboundp 'ido-completing-read)
9230 (boundp 'ido-mode) ido-mode
9231 (listp (second args)))
9232 (let ((ido-enter-matching-directory nil))
9233 (apply 'ido-completing-read (concat (car args))
9234 (if (consp (car (nth 1 args)))
9235 (mapcar 'car (nth 1 args))
9236 (nth 1 args))
9237 (cddr args)))
9238 (if (and org-completion-use-iswitchb
9239 (boundp 'iswitchb-mode) iswitchb-mode
9240 (listp (second args)))
9241 (apply 'org-iswitchb-completing-read (concat (car args))
9242 (if (consp (car (nth 1 args)))
9243 (mapcar 'car (nth 1 args))
9244 (nth 1 args))
9245 (cddr args))
9246 (apply 'completing-read args)))))
9248 (defun org-extract-attributes (s)
9249 "Extract the attributes cookie from a string and set as text property."
9250 (let (a attr (start 0) key value)
9251 (save-match-data
9252 (when (string-match "{{\\([^}]+\\)}}$" s)
9253 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9254 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9255 (setq key (match-string 1 a) value (match-string 2 a)
9256 start (match-end 0)
9257 attr (plist-put attr (intern key) value))))
9258 (org-add-props s nil 'org-attr attr))
9261 (defun org-extract-attributes-from-string (tag)
9262 (let (key value attr)
9263 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9264 (setq key (match-string 1 tag) value (match-string 2 tag)
9265 tag (replace-match "" t t tag)
9266 attr (plist-put attr (intern key) value)))
9267 (cons tag attr)))
9269 (defun org-attributes-to-string (plist)
9270 "Format a property list into an HTML attribute list."
9271 (let ((s "") key value)
9272 (while plist
9273 (setq key (pop plist) value (pop plist))
9274 (and value
9275 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9278 ;;; Opening/following a link
9280 (defvar org-link-search-failed nil)
9282 (defvar org-open-link-functions nil
9283 "Hook for functions finding a plain text link.
9284 These functions must take a single argument, the link content.
9285 They will be called for links that look like [[link text][description]]
9286 when LINK TEXT does not have a protocol like \"http:\" and does not look
9287 like a filename (e.g. \"./blue.png\").
9289 These functions will be called *before* Org attempts to resolve the
9290 link by doing text searches in the current buffer - so if you want a
9291 link \"[[target]]\" to still find \"<<target>>\", your function should
9292 handle this as a special case.
9294 When the function does handle the link, it must return a non-nil value.
9295 If it decides that it is not responsible for this link, it must return
9296 nil to indicate that that Org-mode can continue with other options
9297 like exact and fuzzy text search.")
9299 (defun org-next-link ()
9300 "Move forward to the next link.
9301 If the link is in hidden text, expose it."
9302 (interactive)
9303 (when (and org-link-search-failed (eq this-command last-command))
9304 (goto-char (point-min))
9305 (message "Link search wrapped back to beginning of buffer"))
9306 (setq org-link-search-failed nil)
9307 (let* ((pos (point))
9308 (ct (org-context))
9309 (a (assoc :link ct)))
9310 (if a (goto-char (nth 2 a)))
9311 (if (re-search-forward org-any-link-re nil t)
9312 (progn
9313 (goto-char (match-beginning 0))
9314 (if (outline-invisible-p) (org-show-context)))
9315 (goto-char pos)
9316 (setq org-link-search-failed t)
9317 (error "No further link found"))))
9319 (defun org-previous-link ()
9320 "Move backward to the previous link.
9321 If the link is in hidden text, expose it."
9322 (interactive)
9323 (when (and org-link-search-failed (eq this-command last-command))
9324 (goto-char (point-max))
9325 (message "Link search wrapped back to end of buffer"))
9326 (setq org-link-search-failed nil)
9327 (let* ((pos (point))
9328 (ct (org-context))
9329 (a (assoc :link ct)))
9330 (if a (goto-char (nth 1 a)))
9331 (if (re-search-backward org-any-link-re nil t)
9332 (progn
9333 (goto-char (match-beginning 0))
9334 (if (outline-invisible-p) (org-show-context)))
9335 (goto-char pos)
9336 (setq org-link-search-failed t)
9337 (error "No further link found"))))
9339 (defun org-translate-link (s)
9340 "Translate a link string if a translation function has been defined."
9341 (if (and org-link-translation-function
9342 (fboundp org-link-translation-function)
9343 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9344 (progn
9345 (setq s (funcall org-link-translation-function
9346 (match-string 1) (match-string 2)))
9347 (concat (car s) ":" (cdr s)))
9350 (defun org-translate-link-from-planner (type path)
9351 "Translate a link from Emacs Planner syntax so that Org can follow it.
9352 This is still an experimental function, your mileage may vary."
9353 (cond
9354 ((member type '("http" "https" "news" "ftp"))
9355 ;; standard Internet links are the same.
9356 nil)
9357 ((and (equal type "irc") (string-match "^//" path))
9358 ;; Planner has two / at the beginning of an irc link, we have 1.
9359 ;; We should have zero, actually....
9360 (setq path (substring path 1)))
9361 ((and (equal type "lisp") (string-match "^/" path))
9362 ;; Planner has a slash, we do not.
9363 (setq type "elisp" path (substring path 1)))
9364 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9365 ;; A typical message link. Planner has the id after the final slash,
9366 ;; we separate it with a hash mark
9367 (setq path (concat (match-string 1 path) "#"
9368 (org-remove-angle-brackets (match-string 2 path)))))
9370 (cons type path))
9372 (defun org-find-file-at-mouse (ev)
9373 "Open file link or URL at mouse."
9374 (interactive "e")
9375 (mouse-set-point ev)
9376 (org-open-at-point 'in-emacs))
9378 (defun org-open-at-mouse (ev)
9379 "Open file link or URL at mouse.
9380 See the docstring of `org-open-file' for details."
9381 (interactive "e")
9382 (mouse-set-point ev)
9383 (if (eq major-mode 'org-agenda-mode)
9384 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9385 (org-open-at-point))
9387 (defvar org-window-config-before-follow-link nil
9388 "The window configuration before following a link.
9389 This is saved in case the need arises to restore it.")
9391 (defvar org-open-link-marker (make-marker)
9392 "Marker pointing to the location where `org-open-at-point; was called.")
9394 ;;;###autoload
9395 (defun org-open-at-point-global ()
9396 "Follow a link like Org-mode does.
9397 This command can be called in any mode to follow a link that has
9398 Org-mode syntax."
9399 (interactive)
9400 (org-run-like-in-org-mode 'org-open-at-point))
9402 ;;;###autoload
9403 (defun org-open-link-from-string (s &optional arg reference-buffer)
9404 "Open a link in the string S, as if it was in Org-mode."
9405 (interactive "sLink: \nP")
9406 (let ((reference-buffer (or reference-buffer (current-buffer))))
9407 (with-temp-buffer
9408 (let ((org-inhibit-startup t))
9409 (org-mode)
9410 (insert s)
9411 (goto-char (point-min))
9412 (when reference-buffer
9413 (setq org-link-abbrev-alist-local
9414 (with-current-buffer reference-buffer
9415 org-link-abbrev-alist-local)))
9416 (org-open-at-point arg reference-buffer)))))
9418 (defvar org-open-at-point-functions nil
9419 "Hook that is run when following a link at point.
9421 Functions in this hook must return t if they identify and follow
9422 a link at point. If they don't find anything interesting at point,
9423 they must return nil.")
9425 (defun org-open-at-point (&optional arg reference-buffer)
9426 "Open link at or after point.
9427 If there is no link at point, this function will search forward up to
9428 the end of the current line.
9429 Normally, files will be opened by an appropriate application. If the
9430 optional prefix argument ARG is non-nil, Emacs will visit the file.
9431 With a double prefix argument, try to open outside of Emacs, in the
9432 application the system uses for this file type."
9433 (interactive "P")
9434 ;; if in a code block, then open the block's results
9435 (unless (call-interactively #'org-babel-open-src-block-result)
9436 (org-load-modules-maybe)
9437 (move-marker org-open-link-marker (point))
9438 (setq org-window-config-before-follow-link (current-window-configuration))
9439 (org-remove-occur-highlights nil nil t)
9440 (cond
9441 ((and (org-on-heading-p)
9442 (not (org-in-regexp
9443 (concat org-plain-link-re "\\|"
9444 org-bracket-link-regexp "\\|"
9445 org-angle-link-re "\\|"
9446 "[ \t]:[^ \t\n]+:[ \t]*$")))
9447 (not (get-text-property (point) 'org-linked-text)))
9448 (or (org-offer-links-in-entry arg)
9449 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9450 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9451 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9452 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9453 (not (org-in-regexp org-bracket-link-regexp)))
9454 (org-footnote-action))
9456 (let (type path link line search (pos (point)))
9457 (catch 'match
9458 (save-excursion
9459 (skip-chars-forward "^]\n\r")
9460 (when (org-in-regexp org-bracket-link-regexp 1)
9461 (setq link (org-extract-attributes
9462 (org-link-unescape (org-match-string-no-properties 1))))
9463 (while (string-match " *\n *" link)
9464 (setq link (replace-match " " t t link)))
9465 (setq link (org-link-expand-abbrev link))
9466 (cond
9467 ((or (file-name-absolute-p link)
9468 (string-match "^\\.\\.?/" link))
9469 (setq type "file" path link))
9470 ((string-match org-link-re-with-space3 link)
9471 (setq type (match-string 1 link) path (match-string 2 link)))
9472 (t (setq type "thisfile" path link)))
9473 (throw 'match t)))
9475 (when (get-text-property (point) 'org-linked-text)
9476 (setq type "thisfile"
9477 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9478 (1+ (point)) (point))
9479 path (buffer-substring
9480 (or (previous-single-property-change pos 'org-linked-text)
9481 (point-min))
9482 (or (next-single-property-change pos 'org-linked-text)
9483 (point-max))))
9484 (throw 'match t))
9486 (save-excursion
9487 (when (or (org-in-regexp org-angle-link-re)
9488 (org-in-regexp org-plain-link-re))
9489 (setq type (match-string 1)
9490 path (org-link-unescape (match-string 2)))
9491 (throw 'match t)))
9492 (save-excursion
9493 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9494 (setq type "tags"
9495 path (match-string 1))
9496 (while (string-match ":" path)
9497 (setq path (replace-match "+" t t path)))
9498 (throw 'match t)))
9499 (when (org-in-regexp "<\\([^><\n]+\\)>")
9500 (setq type "tree-match"
9501 path (match-string 1))
9502 (throw 'match t)))
9503 (unless path
9504 (error "No link found"))
9506 ;; switch back to reference buffer
9507 ;; needed when if called in a temporary buffer through
9508 ;; org-open-link-from-string
9509 (with-current-buffer (or reference-buffer (current-buffer))
9511 ;; Remove any trailing spaces in path
9512 (if (string-match " +\\'" path)
9513 (setq path (replace-match "" t t path)))
9514 (if (and org-link-translation-function
9515 (fboundp org-link-translation-function))
9516 ;; Check if we need to translate the link
9517 (let ((tmp (funcall org-link-translation-function type path)))
9518 (setq type (car tmp) path (cdr tmp))))
9520 (cond
9522 ((assoc type org-link-protocols)
9523 (funcall (nth 1 (assoc type org-link-protocols)) path))
9525 ((equal type "mailto")
9526 (let ((cmd (car org-link-mailto-program))
9527 (args (cdr org-link-mailto-program)) args1
9528 (address path) (subject "") a)
9529 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9530 (setq address (match-string 1 path)
9531 subject (org-link-escape (match-string 2 path))))
9532 (while args
9533 (cond
9534 ((not (stringp (car args))) (push (pop args) args1))
9535 (t (setq a (pop args))
9536 (if (string-match "%a" a)
9537 (setq a (replace-match address t t a)))
9538 (if (string-match "%s" a)
9539 (setq a (replace-match subject t t a)))
9540 (push a args1))))
9541 (apply cmd (nreverse args1))))
9543 ((member type '("http" "https" "ftp" "news"))
9544 (browse-url (concat type ":" (org-link-escape
9545 path org-link-escape-chars-browser))))
9547 ((string= type "doi")
9548 (browse-url (concat "http://dx.doi.org/"
9549 (org-link-escape
9550 path org-link-escape-chars-browser))))
9552 ((member type '("message"))
9553 (browse-url (concat type ":" path)))
9555 ((string= type "tags")
9556 (org-tags-view arg path))
9558 ((string= type "tree-match")
9559 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9561 ((string= type "file")
9562 (if (string-match "::\\([0-9]+\\)\\'" path)
9563 (setq line (string-to-number (match-string 1 path))
9564 path (substring path 0 (match-beginning 0)))
9565 (if (string-match "::\\(.+\\)\\'" path)
9566 (setq search (match-string 1 path)
9567 path (substring path 0 (match-beginning 0)))))
9568 (if (string-match "[*?{]" (file-name-nondirectory path))
9569 (dired path)
9570 (org-open-file path arg line search)))
9572 ((string= type "shell")
9573 (let ((cmd path))
9574 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9575 (string-match org-confirm-shell-link-not-regexp cmd))
9576 (not org-confirm-shell-link-function)
9577 (funcall org-confirm-shell-link-function
9578 (format "Execute \"%s\" in shell? "
9579 (org-add-props cmd nil
9580 'face 'org-warning))))
9581 (progn
9582 (message "Executing %s" cmd)
9583 (shell-command cmd))
9584 (error "Abort"))))
9586 ((string= type "elisp")
9587 (let ((cmd path))
9588 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9589 (string-match org-confirm-elisp-link-not-regexp cmd))
9590 (not org-confirm-elisp-link-function)
9591 (funcall org-confirm-elisp-link-function
9592 (format "Execute \"%s\" as elisp? "
9593 (org-add-props cmd nil
9594 'face 'org-warning))))
9595 (message "%s => %s" cmd
9596 (if (equal (string-to-char cmd) ?\()
9597 (eval (read cmd))
9598 (call-interactively (read cmd))))
9599 (error "Abort"))))
9601 ((and (string= type "thisfile")
9602 (run-hook-with-args-until-success
9603 'org-open-link-functions path)))
9605 ((string= type "thisfile")
9606 (if arg
9607 (switch-to-buffer-other-window
9608 (org-get-buffer-for-internal-link (current-buffer)))
9609 (org-mark-ring-push))
9610 (let ((cmd `(org-link-search
9611 ,path
9612 ,(cond ((equal arg '(4)) ''occur)
9613 ((equal arg '(16)) ''org-occur)
9614 (t nil))
9615 ,pos)))
9616 (condition-case nil (let ((org-link-search-inhibit-query t))
9617 (eval cmd))
9618 (error (progn (widen) (eval cmd))))))
9621 (browse-url-at-point)))))))
9622 (move-marker org-open-link-marker nil)
9623 (run-hook-with-args 'org-follow-link-hook)))
9625 (defun org-offer-links-in-entry (&optional nth zero)
9626 "Offer links in the current entry and follow the selected link.
9627 If there is only one link, follow it immediately as well.
9628 If NTH is an integer, immediately pick the NTH link found.
9629 If ZERO is a string, check also this string for a link, and if
9630 there is one, offer it as link number zero."
9631 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9632 "\\(" org-angle-link-re "\\)\\|"
9633 "\\(" org-plain-link-re "\\)"))
9634 (cnt ?0)
9635 (in-emacs (if (integerp nth) nil nth))
9636 have-zero end links link c)
9637 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9638 (push (match-string 0 zero) links)
9639 (setq cnt (1- cnt) have-zero t))
9640 (save-excursion
9641 (org-back-to-heading t)
9642 (setq end (save-excursion (outline-next-heading) (point)))
9643 (while (re-search-forward re end t)
9644 (push (match-string 0) links))
9645 (setq links (org-uniquify (reverse links))))
9647 (cond
9648 ((null links)
9649 (message "No links"))
9650 ((equal (length links) 1)
9651 (setq link (list (car links))))
9652 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9653 (setq link (nth (if have-zero nth (1- nth)) links)))
9654 (t ; we have to select a link
9655 (save-excursion
9656 (save-window-excursion
9657 (delete-other-windows)
9658 (with-output-to-temp-buffer "*Select Link*"
9659 (mapc (lambda (l)
9660 (if (not (string-match org-bracket-link-regexp l))
9661 (princ (format "[%c] %s\n" (incf cnt)
9662 (org-remove-angle-brackets l)))
9663 (if (match-end 3)
9664 (princ (format "[%c] %s (%s)\n" (incf cnt)
9665 (match-string 3 l) (match-string 1 l)))
9666 (princ (format "[%c] %s\n" (incf cnt)
9667 (match-string 1 l))))))
9668 links))
9669 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9670 (message "Select link to open, RET to open all:")
9671 (setq c (read-char-exclusive))
9672 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9673 (when (equal c ?q) (error "Abort"))
9674 (if (equal c ?\C-m)
9675 (setq link links)
9676 (setq nth (- c ?0))
9677 (if have-zero (setq nth (1+ nth)))
9678 (unless (and (integerp nth) (>= (length links) nth))
9679 (error "Invalid link selection"))
9680 (setq link (list (nth (1- nth) links))))))
9681 (if link
9682 (let ((buf (current-buffer)))
9683 (dolist (l link)
9684 (org-open-link-from-string l in-emacs buf))
9686 nil)))
9688 ;; Add special file links that specify the way of opening
9690 (org-add-link-type "file+sys" 'org-open-file-with-system)
9691 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9692 (defun org-open-file-with-system (path)
9693 "Open file at PATH using the system way of opening it."
9694 (org-open-file path 'system))
9695 (defun org-open-file-with-emacs (path)
9696 "Open file at PATH in Emacs."
9697 (org-open-file path 'emacs))
9698 (defun org-remove-file-link-modifiers ()
9699 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9700 (goto-char (point-min))
9701 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9702 (org-if-unprotected
9703 (replace-match "file:" t t))))
9704 (eval-after-load "org-exp"
9705 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9706 'org-remove-file-link-modifiers))
9708 ;;;; Time estimates
9710 (defun org-get-effort (&optional pom)
9711 "Get the effort estimate for the current entry."
9712 (org-entry-get pom org-effort-property))
9714 ;;; File search
9716 (defvar org-create-file-search-functions nil
9717 "List of functions to construct the right search string for a file link.
9718 These functions are called in turn with point at the location to
9719 which the link should point.
9721 A function in the hook should first test if it would like to
9722 handle this file type, for example by checking the `major-mode'
9723 or the file extension. If it decides not to handle this file, it
9724 should just return nil to give other functions a chance. If it
9725 does handle the file, it must return the search string to be used
9726 when following the link. The search string will be part of the
9727 file link, given after a double colon, and `org-open-at-point'
9728 will automatically search for it. If special measures must be
9729 taken to make the search successful, another function should be
9730 added to the companion hook `org-execute-file-search-functions',
9731 which see.
9733 A function in this hook may also use `setq' to set the variable
9734 `description' to provide a suggestion for the descriptive text to
9735 be used for this link when it gets inserted into an Org-mode
9736 buffer with \\[org-insert-link].")
9738 (defvar org-execute-file-search-functions nil
9739 "List of functions to execute a file search triggered by a link.
9741 Functions added to this hook must accept a single argument, the
9742 search string that was part of the file link, the part after the
9743 double colon. The function must first check if it would like to
9744 handle this search, for example by checking the `major-mode' or
9745 the file extension. If it decides not to handle this search, it
9746 should just return nil to give other functions a chance. If it
9747 does handle the search, it must return a non-nil value to keep
9748 other functions from trying.
9750 Each function can access the current prefix argument through the
9751 variable `current-prefix-argument'. Note that a single prefix is
9752 used to force opening a link in Emacs, so it may be good to only
9753 use a numeric or double prefix to guide the search function.
9755 In case this is needed, a function in this hook can also restore
9756 the window configuration before `org-open-at-point' was called using:
9758 (set-window-configuration org-window-config-before-follow-link)")
9760 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9761 (defun org-link-search (s &optional type avoid-pos stealth)
9762 "Search for a link search option.
9763 If S is surrounded by forward slashes, it is interpreted as a
9764 regular expression. In org-mode files, this will create an `org-occur'
9765 sparse tree. In ordinary files, `occur' will be used to list matches.
9766 If the current buffer is in `dired-mode', grep will be used to search
9767 in all files. If AVOID-POS is given, ignore matches near that position.
9769 When optional argument STEALTH is non-nil, do not modify
9770 visibility around point, thus ignoring
9771 `org-show-hierarchy-above', `org-show-following-heading' and
9772 `org-show-siblings' variables."
9773 (let ((case-fold-search t)
9774 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9775 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9776 (append '(("") (" ") ("\t") ("\n"))
9777 org-emphasis-alist)
9778 "\\|") "\\)"))
9779 (pos (point))
9780 (pre nil) (post nil)
9781 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9782 (cond
9783 ;; First check if there are any special search functions
9784 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9785 ;; Now try the builtin stuff
9786 ((and (equal (string-to-char s0) ?#)
9787 (> (length s0) 1)
9788 (save-excursion
9789 (goto-char (point-min))
9790 (and
9791 (re-search-forward
9792 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9793 (setq type 'dedicated
9794 pos (match-beginning 0))))
9795 ;; There is an exact target for this
9796 (goto-char pos)
9797 (org-back-to-heading t)))
9798 ((save-excursion
9799 (goto-char (point-min))
9800 (and
9801 (re-search-forward
9802 (concat "<<" (regexp-quote s0) ">>") nil t)
9803 (setq type 'dedicated
9804 pos (match-beginning 0))))
9805 ;; There is an exact target for this
9806 (goto-char pos))
9807 ((and (string-match "^(\\(.*\\))$" s0)
9808 (save-excursion
9809 (goto-char (point-min))
9810 (and
9811 (re-search-forward
9812 (concat "[^[]" (regexp-quote
9813 (format org-coderef-label-format
9814 (match-string 1 s0))))
9815 nil t)
9816 (setq type 'dedicated
9817 pos (1+ (match-beginning 0))))))
9818 ;; There is a coderef target for this
9819 (goto-char pos))
9820 ((string-match "^/\\(.*\\)/$" s)
9821 ;; A regular expression
9822 (cond
9823 ((eq major-mode 'org-mode)
9824 (org-occur (match-string 1 s)))
9825 ;;((eq major-mode 'dired-mode)
9826 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9827 (t (org-do-occur (match-string 1 s)))))
9828 ((and (eq major-mode 'org-mode) org-link-search-must-match-exact-headline)
9829 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
9830 (goto-char (point-min))
9831 (cond
9832 ((let (case-fold-search)
9833 (re-search-forward (format org-complex-heading-regexp-format
9834 (regexp-quote s))
9835 nil t))
9836 ;; OK, found a match
9837 (setq type 'dedicated)
9838 (goto-char (match-beginning 0)))
9839 ((and (not org-link-search-inhibit-query)
9840 (eq org-link-search-must-match-exact-headline 'query-to-create)
9841 (y-or-n-p "No match - create this as a new heading? "))
9842 (goto-char (point-max))
9843 (or (bolp) (newline))
9844 (insert "* " s "\n")
9845 (beginning-of-line 0))
9847 (goto-char pos)
9848 (error "No match"))))
9850 ;; A normal search string
9851 (when (equal (string-to-char s) ?*)
9852 ;; Anchor on headlines, post may include tags.
9853 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
9854 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
9855 s (substring s 1)))
9856 (remove-text-properties
9857 0 (length s)
9858 '(face nil mouse-face nil keymap nil fontified nil) s)
9859 ;; Make a series of regular expressions to find a match
9860 (setq words (org-split-string s "[ \n\r\t]+")
9862 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9863 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
9864 "\\)" markers)
9865 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9866 re2a (concat "[ \t\r\n]" re2a_)
9867 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9868 re4 (concat "[^a-zA-Z_]" re4_)
9870 re1 (concat pre re2 post)
9871 re3 (concat pre (if pre re4_ re4) post)
9872 re5 (concat pre ".*" re4)
9873 re2 (concat pre re2)
9874 re2a (concat pre (if pre re2a_ re2a))
9875 re4 (concat pre (if pre re4_ re4))
9876 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9877 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9878 re5 "\\)"
9880 (cond
9881 ((eq type 'org-occur) (org-occur reall))
9882 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9883 (t (goto-char (point-min))
9884 (setq type 'fuzzy)
9885 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
9886 (org-search-not-self 1 re1 nil t)
9887 (org-search-not-self 1 re2 nil t)
9888 (org-search-not-self 1 re2a nil t)
9889 (org-search-not-self 1 re3 nil t)
9890 (org-search-not-self 1 re4 nil t)
9891 (org-search-not-self 1 re5 nil t)
9893 (goto-char (match-beginning 1))
9894 (goto-char pos)
9895 (error "No match"))))))
9896 (and (eq major-mode 'org-mode)
9897 (not stealth)
9898 (org-show-context 'link-search))
9899 type))
9901 (defun org-search-not-self (group &rest args)
9902 "Execute `re-search-forward', but only accept matches that do not
9903 enclose the position of `org-open-link-marker'."
9904 (let ((m org-open-link-marker))
9905 (catch 'exit
9906 (while (apply 're-search-forward args)
9907 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
9908 (goto-char (match-end group))
9909 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
9910 (> (match-beginning 0) (marker-position m))
9911 (< (match-end 0) (marker-position m)))
9912 (save-match-data
9913 (or (not (org-in-regexp
9914 org-bracket-link-analytic-regexp 1))
9915 (not (match-end 4)) ; no description
9916 (and (<= (match-beginning 4) (point))
9917 (>= (match-end 4) (point))))))
9918 (throw 'exit (point))))))))
9920 (defun org-get-buffer-for-internal-link (buffer)
9921 "Return a buffer to be used for displaying the link target of internal links."
9922 (cond
9923 ((not org-display-internal-link-with-indirect-buffer)
9924 buffer)
9925 ((string-match "(Clone)$" (buffer-name buffer))
9926 (message "Buffer is already a clone, not making another one")
9927 ;; we also do not modify visibility in this case
9928 buffer)
9929 (t ; make a new indirect buffer for displaying the link
9930 (let* ((bn (buffer-name buffer))
9931 (ibn (concat bn "(Clone)"))
9932 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
9933 (with-current-buffer ib (org-overview))
9934 ib))))
9936 (defun org-do-occur (regexp &optional cleanup)
9937 "Call the Emacs command `occur'.
9938 If CLEANUP is non-nil, remove the printout of the regular expression
9939 in the *Occur* buffer. This is useful if the regex is long and not useful
9940 to read."
9941 (occur regexp)
9942 (when cleanup
9943 (let ((cwin (selected-window)) win beg end)
9944 (when (setq win (get-buffer-window "*Occur*"))
9945 (select-window win))
9946 (goto-char (point-min))
9947 (when (re-search-forward "match[a-z]+" nil t)
9948 (setq beg (match-end 0))
9949 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9950 (setq end (1- (match-beginning 0)))))
9951 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
9952 (goto-char (point-min))
9953 (select-window cwin))))
9955 ;;; The mark ring for links jumps
9957 (defvar org-mark-ring nil
9958 "Mark ring for positions before jumps in Org-mode.")
9959 (defvar org-mark-ring-last-goto nil
9960 "Last position in the mark ring used to go back.")
9961 ;; Fill and close the ring
9962 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9963 (loop for i from 1 to org-mark-ring-length do
9964 (push (make-marker) org-mark-ring))
9965 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
9966 org-mark-ring)
9968 (defun org-mark-ring-push (&optional pos buffer)
9969 "Put the current position or POS into the mark ring and rotate it."
9970 (interactive)
9971 (setq pos (or pos (point)))
9972 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
9973 (move-marker (car org-mark-ring)
9974 (or pos (point))
9975 (or buffer (current-buffer)))
9976 (message "%s"
9977 (substitute-command-keys
9978 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
9980 (defun org-mark-ring-goto (&optional n)
9981 "Jump to the previous position in the mark ring.
9982 With prefix arg N, jump back that many stored positions. When
9983 called several times in succession, walk through the entire ring.
9984 Org-mode commands jumping to a different position in the current file,
9985 or to another Org-mode file, automatically push the old position
9986 onto the ring."
9987 (interactive "p")
9988 (let (p m)
9989 (if (eq last-command this-command)
9990 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
9991 (setq p org-mark-ring))
9992 (setq org-mark-ring-last-goto p)
9993 (setq m (car p))
9994 (org-pop-to-buffer-same-window (marker-buffer m))
9995 (goto-char m)
9996 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
9998 (defun org-remove-angle-brackets (s)
9999 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10000 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10002 (defun org-add-angle-brackets (s)
10003 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10004 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10006 (defun org-remove-double-quotes (s)
10007 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10008 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10011 ;;; Following specific links
10013 (defun org-follow-timestamp-link ()
10014 (cond
10015 ((org-at-date-range-p t)
10016 (let ((org-agenda-start-on-weekday)
10017 (t1 (match-string 1))
10018 (t2 (match-string 2)))
10019 (setq t1 (time-to-days (org-time-string-to-time t1))
10020 t2 (time-to-days (org-time-string-to-time t2)))
10021 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10022 ((org-at-timestamp-p t)
10023 (org-agenda-list nil (time-to-days (org-time-string-to-time
10024 (substring (match-string 1) 0 10)))
10026 (t (error "This should not happen"))))
10029 ;;; Following file links
10030 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10031 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10032 (declare-function mailcap-mime-info
10033 "mailcap" (string &optional request no-decode))
10034 (defvar org-wait nil)
10035 (defun org-open-file (path &optional in-emacs line search)
10036 "Open the file at PATH.
10037 First, this expands any special file name abbreviations. Then the
10038 configuration variable `org-file-apps' is checked if it contains an
10039 entry for this file type, and if yes, the corresponding command is launched.
10041 If no application is found, Emacs simply visits the file.
10043 With optional prefix argument IN-EMACS, Emacs will visit the file.
10044 With a double \\[universal-argument] \\[universal-argument] \
10045 prefix arg, Org tries to avoid opening in Emacs
10046 and to use an external application to visit the file.
10048 Optional LINE specifies a line to go to, optional SEARCH a string
10049 to search for. If LINE or SEARCH is given, the file will be
10050 opened in Emacs, unless an entry from org-file-apps that makes
10051 use of groups in a regexp matches.
10053 If you want to change the way frames are used when following a
10054 link, please customize `org-link-frame-setup'.
10056 If the file does not exist, an error is thrown."
10057 (let* ((file (if (equal path "")
10058 buffer-file-name
10059 (substitute-in-file-name (expand-file-name path))))
10060 (file-apps (append org-file-apps (org-default-apps)))
10061 (apps (org-remove-if
10062 'org-file-apps-entry-match-against-dlink-p file-apps))
10063 (apps-dlink (org-remove-if-not
10064 'org-file-apps-entry-match-against-dlink-p file-apps))
10065 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10066 (dirp (if remp nil (file-directory-p file)))
10067 (file (if (and dirp org-open-directory-means-index-dot-org)
10068 (concat (file-name-as-directory file) "index.org")
10069 file))
10070 (a-m-a-p (assq 'auto-mode apps))
10071 (dfile (downcase file))
10072 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10073 (link (cond ((and (eq line nil)
10074 (eq search nil))
10075 file)
10076 (line
10077 (concat file "::" (number-to-string line)))
10078 (search
10079 (concat file "::" search))))
10080 (dlink (downcase link))
10081 (old-buffer (current-buffer))
10082 (old-pos (point))
10083 (old-mode major-mode)
10084 ext cmd link-match-data)
10085 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10086 (setq ext (match-string 1 dfile))
10087 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10088 (setq ext (match-string 1 dfile))))
10089 (cond
10090 ((member in-emacs '((16) system))
10091 (setq cmd (cdr (assoc 'system apps))))
10092 (in-emacs (setq cmd 'emacs))
10094 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10095 (and dirp (cdr (assoc 'directory apps)))
10096 ; first, try matching against apps-dlink
10097 ; if we get a match here, store the match data for later
10098 (let ((match (assoc-default dlink apps-dlink
10099 'string-match)))
10100 (if match
10101 (progn (setq link-match-data (match-data))
10102 match)
10103 (progn (setq in-emacs (or in-emacs line search))
10104 nil))) ; if we have no match in apps-dlink,
10105 ; always open the file in emacs if line or search
10106 ; is given (for backwards compatibility)
10107 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10108 'string-match)
10109 (cdr (assoc ext apps))
10110 (cdr (assoc t apps))))))
10111 (when (eq cmd 'system)
10112 (setq cmd (cdr (assoc 'system apps))))
10113 (when (eq cmd 'default)
10114 (setq cmd (cdr (assoc t apps))))
10115 (when (eq cmd 'mailcap)
10116 (require 'mailcap)
10117 (mailcap-parse-mailcaps)
10118 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10119 (command (mailcap-mime-info mime-type)))
10120 (if (stringp command)
10121 (setq cmd command)
10122 (setq cmd 'emacs))))
10123 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10124 (not (file-exists-p file))
10125 (not org-open-non-existing-files))
10126 (error "No such file: %s" file))
10127 (cond
10128 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10129 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10130 (while (string-match "['\"]%s['\"]" cmd)
10131 (setq cmd (replace-match "%s" t t cmd)))
10132 (while (string-match "%s" cmd)
10133 (setq cmd (replace-match
10134 (save-match-data
10135 (shell-quote-argument
10136 (convert-standard-filename file)))
10137 t t cmd)))
10139 ;; Replace "%1", "%2" etc. in command with group matches from regex
10140 (save-match-data
10141 (let ((match-index 1)
10142 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10143 (set-match-data link-match-data)
10144 (while (<= match-index number-of-groups)
10145 (let ((regex (concat "%" (number-to-string match-index)))
10146 (replace-with (match-string match-index dlink)))
10147 (while (string-match regex cmd)
10148 (setq cmd (replace-match replace-with t t cmd))))
10149 (setq match-index (+ match-index 1)))))
10151 (save-window-excursion
10152 (start-process-shell-command cmd nil cmd)
10153 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10155 ((or (stringp cmd)
10156 (eq cmd 'emacs))
10157 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10158 (widen)
10159 (if line (org-goto-line line)
10160 (if search (org-link-search search))))
10161 ((consp cmd)
10162 (let ((file (convert-standard-filename file)))
10163 (save-match-data
10164 (set-match-data link-match-data)
10165 (eval cmd))))
10166 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10167 (and (eq major-mode 'org-mode) (eq old-mode 'org-mode)
10168 (or (not (equal old-buffer (current-buffer)))
10169 (not (equal old-pos (point))))
10170 (org-mark-ring-push old-pos old-buffer))))
10172 (defun org-file-apps-entry-match-against-dlink-p (entry)
10173 "This function returns non-nil if `entry' uses a regular
10174 expression which should be matched against the whole link by
10175 org-open-file.
10177 It assumes that is the case when the entry uses a regular
10178 expression which has at least one grouping construct and the
10179 action is either a lisp form or a command string containing
10180 '%1', i.e. using at least one subexpression match as a
10181 parameter."
10182 (let ((selector (car entry))
10183 (action (cdr entry)))
10184 (if (stringp selector)
10185 (and (> (regexp-opt-depth selector) 0)
10186 (or (and (stringp action)
10187 (string-match "%[0-9]" action))
10188 (consp action)))
10189 nil)))
10191 (defun org-default-apps ()
10192 "Return the default applications for this operating system."
10193 (cond
10194 ((eq system-type 'darwin)
10195 org-file-apps-defaults-macosx)
10196 ((eq system-type 'windows-nt)
10197 org-file-apps-defaults-windowsnt)
10198 (t org-file-apps-defaults-gnu)))
10200 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10201 "Convert extensions to regular expressions in the cars of LIST.
10202 Also, weed out any non-string entries, because the return value is used
10203 only for regexp matching.
10204 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10205 point to the symbol `emacs', indicating that the file should
10206 be opened in Emacs."
10207 (append
10208 (delq nil
10209 (mapcar (lambda (x)
10210 (if (not (stringp (car x)))
10212 (if (string-match "\\W" (car x))
10214 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10215 list))
10216 (if add-auto-mode
10217 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10219 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10220 (defun org-file-remote-p (file)
10221 "Test whether FILE specifies a location on a remote system.
10222 Return non-nil if the location is indeed remote.
10224 For example, the filename \"/user@host:/foo\" specifies a location
10225 on the system \"/user@host:\"."
10226 (cond ((fboundp 'file-remote-p)
10227 (file-remote-p file))
10228 ((fboundp 'tramp-handle-file-remote-p)
10229 (tramp-handle-file-remote-p file))
10230 ((and (boundp 'ange-ftp-name-format)
10231 (string-match (car ange-ftp-name-format) file))
10233 (t nil)))
10236 ;;;; Refiling
10238 (defun org-get-org-file ()
10239 "Read a filename, with default directory `org-directory'."
10240 (let ((default (or org-default-notes-file remember-data-file)))
10241 (read-file-name (format "File name [%s]: " default)
10242 (file-name-as-directory org-directory)
10243 default)))
10245 (defun org-notes-order-reversed-p ()
10246 "Check if the current file should receive notes in reversed order."
10247 (cond
10248 ((not org-reverse-note-order) nil)
10249 ((eq t org-reverse-note-order) t)
10250 ((not (listp org-reverse-note-order)) nil)
10251 (t (catch 'exit
10252 (let ((all org-reverse-note-order)
10253 entry)
10254 (while (setq entry (pop all))
10255 (if (string-match (car entry) buffer-file-name)
10256 (throw 'exit (cdr entry))))
10257 nil)))))
10259 (defvar org-refile-target-table nil
10260 "The list of refile targets, created by `org-refile'.")
10262 (defvar org-agenda-new-buffers nil
10263 "Buffers created to visit agenda files.")
10265 (defvar org-refile-cache nil
10266 "Cache for refile targets.")
10268 (defvar org-refile-markers nil
10269 "All the markers used for caching refile locations.")
10271 (defun org-refile-marker (pos)
10272 "Get a new refile marker, but only if caching is in use."
10273 (if (not org-refile-use-cache)
10275 (let ((m (make-marker)))
10276 (move-marker m pos)
10277 (push m org-refile-markers)
10278 m)))
10280 (defun org-refile-cache-clear ()
10281 "Clear the refile cache and disable all the markers."
10282 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10283 (setq org-refile-markers nil)
10284 (setq org-refile-cache nil)
10285 (message "Refile cache has been cleared"))
10287 (defun org-refile-cache-check-set (set)
10288 "Check if all the markers in the cache still have live buffers."
10289 (let (marker)
10290 (catch 'exit
10291 (while (and set (setq marker (nth 3 (pop set))))
10292 ;; if org-refile-use-outline-path is 'file, marker may be nil
10293 (when (and marker (null (marker-buffer marker)))
10294 (message "not found") (sit-for 3)
10295 (throw 'exit nil)))
10296 t)))
10298 (defun org-refile-cache-put (set &rest identifiers)
10299 "Push the refile targets SET into the cache, under IDENTIFIERS."
10300 (let* ((key (sha1 (prin1-to-string identifiers)))
10301 (entry (assoc key org-refile-cache)))
10302 (if entry
10303 (setcdr entry set)
10304 (push (cons key set) org-refile-cache))))
10306 (defun org-refile-cache-get (&rest identifiers)
10307 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10308 (cond
10309 ((not org-refile-cache) nil)
10310 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10312 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10313 org-refile-cache))))
10314 (and set (org-refile-cache-check-set set) set)))))
10316 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10317 "Produce a table with refile targets."
10318 (let ((case-fold-search nil)
10319 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10320 (entries (or org-refile-targets '((nil . (:level . 1)))))
10321 targets tgs txt re files f desc descre fast-path-p level pos0)
10322 (message "Getting targets...")
10323 (with-current-buffer (or default-buffer (current-buffer))
10324 (while (setq entry (pop entries))
10325 (setq files (car entry) desc (cdr entry))
10326 (setq fast-path-p nil)
10327 (cond
10328 ((null files) (setq files (list (current-buffer))))
10329 ((eq files 'org-agenda-files)
10330 (setq files (org-agenda-files 'unrestricted)))
10331 ((and (symbolp files) (fboundp files))
10332 (setq files (funcall files)))
10333 ((and (symbolp files) (boundp files))
10334 (setq files (symbol-value files))))
10335 (if (stringp files) (setq files (list files)))
10336 (cond
10337 ((eq (car desc) :tag)
10338 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10339 ((eq (car desc) :todo)
10340 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10341 ((eq (car desc) :regexp)
10342 (setq descre (cdr desc)))
10343 ((eq (car desc) :level)
10344 (setq descre (concat "^\\*\\{" (number-to-string
10345 (if org-odd-levels-only
10346 (1- (* 2 (cdr desc)))
10347 (cdr desc)))
10348 "\\}[ \t]")))
10349 ((eq (car desc) :maxlevel)
10350 (setq fast-path-p t)
10351 (setq descre (concat "^\\*\\{1," (number-to-string
10352 (if org-odd-levels-only
10353 (1- (* 2 (cdr desc)))
10354 (cdr desc)))
10355 "\\}[ \t]")))
10356 (t (error "Bad refiling target description %s" desc)))
10357 (while (setq f (pop files))
10358 (with-current-buffer
10359 (if (bufferp f) f (org-get-agenda-file-buffer f))
10361 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10362 (progn
10363 (if (bufferp f) (setq f (buffer-file-name
10364 (buffer-base-buffer f))))
10365 (setq f (and f (expand-file-name f)))
10366 (if (eq org-refile-use-outline-path 'file)
10367 (push (list (file-name-nondirectory f) f nil nil) tgs))
10368 (save-excursion
10369 (save-restriction
10370 (widen)
10371 (goto-char (point-min))
10372 (while (re-search-forward descre nil t)
10373 (goto-char (setq pos0 (point-at-bol)))
10374 (catch 'next
10375 (when org-refile-target-verify-function
10376 (save-match-data
10377 (or (funcall org-refile-target-verify-function)
10378 (throw 'next t))))
10379 (when (and (looking-at org-complex-heading-regexp)
10380 (not (member (match-string 4) excluded-entries)))
10381 (setq level (org-reduced-level
10382 (- (match-end 1) (match-beginning 1)))
10383 txt (org-link-display-format (match-string 4))
10384 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10385 re (format org-complex-heading-regexp-format
10386 (regexp-quote (match-string 4))))
10387 (when org-refile-use-outline-path
10388 (setq txt (mapconcat
10389 'org-protect-slash
10390 (append
10391 (if (eq org-refile-use-outline-path
10392 'file)
10393 (list (file-name-nondirectory
10394 (buffer-file-name
10395 (buffer-base-buffer))))
10396 (if (eq org-refile-use-outline-path
10397 'full-file-path)
10398 (list (buffer-file-name
10399 (buffer-base-buffer)))))
10400 (org-get-outline-path fast-path-p
10401 level txt)
10402 (list txt))
10403 "/")))
10404 (push (list txt f re (org-refile-marker (point)))
10405 tgs)))
10406 (when (= (point) pos0)
10407 ;; verification function has not moved point
10408 (goto-char (point-at-eol))))))))
10409 (when org-refile-use-cache
10410 (org-refile-cache-put tgs (buffer-file-name) descre))
10411 (setq targets (append tgs targets))
10412 ))))
10413 (message "Getting targets...done")
10414 (nreverse targets)))
10416 (defun org-protect-slash (s)
10417 (while (string-match "/" s)
10418 (setq s (replace-match "\\" t t s)))
10421 (defvar org-olpa (make-vector 20 nil))
10423 (defun org-get-outline-path (&optional fastp level heading)
10424 "Return the outline path to the current entry, as a list.
10426 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10427 routine which makes outline path derivations for an entire file,
10428 avoiding backtracing. Refile target collection makes use of that."
10429 (if fastp
10430 (progn
10431 (if (> level 19)
10432 (error "Outline path failure, more than 19 levels"))
10433 (loop for i from level upto 19 do
10434 (aset org-olpa i nil))
10435 (prog1
10436 (delq nil (append org-olpa nil))
10437 (aset org-olpa level heading)))
10438 (let (rtn case-fold-search)
10439 (save-excursion
10440 (save-restriction
10441 (widen)
10442 (while (org-up-heading-safe)
10443 (when (looking-at org-complex-heading-regexp)
10444 (push (org-match-string-no-properties 4) rtn)))
10445 rtn)))))
10447 (defun org-format-outline-path (path &optional width prefix)
10448 "Format the outline path PATH for display.
10449 Width is the maximum number of characters that is available.
10450 Prefix is a prefix to be included in the returned string,
10451 such as the file name."
10452 (setq width (or width 79))
10453 (if prefix (setq width (- width (length prefix))))
10454 (if (not path)
10455 (or prefix "")
10456 (let* ((nsteps (length path))
10457 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10458 (maxwidth (if (<= total-width width)
10459 10000 ;; everything fits
10460 ;; we need to shorten the level headings
10461 (/ (- width nsteps) nsteps)))
10462 (org-odd-levels-only nil)
10463 (n 0)
10464 (total (1+ (length prefix))))
10465 (setq maxwidth (max maxwidth 10))
10466 (concat prefix
10467 (mapconcat
10468 (lambda (h)
10469 (setq n (1+ n))
10470 (if (and (= n nsteps) (< maxwidth 10000))
10471 (setq maxwidth (- total-width total)))
10472 (if (< (length h) maxwidth)
10473 (progn (setq total (+ total (length h) 1)) h)
10474 (setq h (substring h 0 (- maxwidth 2))
10475 total (+ total maxwidth 1))
10476 (if (string-match "[ \t]+\\'" h)
10477 (setq h (substring h 0 (match-beginning 0))))
10478 (setq h (concat h "..")))
10479 (org-add-props h nil 'face
10480 (nth (% (1- n) org-n-level-faces)
10481 org-level-faces))
10483 path "/")))))
10485 (defun org-display-outline-path (&optional file current)
10486 "Display the current outline path in the echo area."
10487 (interactive "P")
10488 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10489 (case-fold-search nil)
10490 (path (and (eq major-mode 'org-mode) (org-get-outline-path))))
10491 (if current (setq path (append path
10492 (save-excursion
10493 (org-back-to-heading t)
10494 (if (looking-at org-complex-heading-regexp)
10495 (list (match-string 4)))))))
10496 (message "%s"
10497 (org-format-outline-path
10498 path
10499 (1- (frame-width))
10500 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10502 (defvar org-refile-history nil
10503 "History for refiling operations.")
10505 (defvar org-after-refile-insert-hook nil
10506 "Hook run after `org-refile' has inserted its stuff at the new location.
10507 Note that this is still *before* the stuff will be removed from
10508 the *old* location.")
10510 (defvar org-capture-last-stored-marker)
10511 (defun org-refile (&optional goto default-buffer rfloc)
10512 "Move the entry or entries at point to another heading.
10513 The list of target headings is compiled using the information in
10514 `org-refile-targets', which see.
10516 At the target location, the entry is filed as a subitem of the target
10517 heading. Depending on `org-reverse-note-order', the new subitem will
10518 either be the first or the last subitem.
10520 If there is an active region, all entries in that region will be moved.
10521 However, the region must fulfill the requirement that the first heading
10522 is the first one sets the top-level of the moved text - at most siblings
10523 below it are allowed.
10525 With prefix arg GOTO, the command will only visit the target location
10526 and not actually move anything.
10528 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10529 go to the location where the last refiling operation has put the subtree.
10530 With a prefix argument of `2', refile to the running clock.
10532 RFLOC can be a refile location obtained in a different way.
10534 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10536 If you are using target caching (see `org-refile-use-cache'),
10537 You have to clear the target cache in order to find new targets.
10538 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10539 prefix argument (`C-u C-u C-u C-c C-w')."
10541 (interactive "P")
10542 (if (member goto '(0 (64)))
10543 (org-refile-cache-clear)
10544 (let* ((cbuf (current-buffer))
10545 (regionp (org-region-active-p))
10546 (region-start (and regionp (region-beginning)))
10547 (region-end (and regionp (region-end)))
10548 (region-length (and regionp (- region-end region-start)))
10549 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10550 pos it nbuf file re level reversed)
10551 (setq last-command nil)
10552 (when regionp
10553 (goto-char region-start)
10554 (or (bolp) (goto-char (point-at-bol)))
10555 (setq region-start (point))
10556 (unless (or (org-kill-is-subtree-p
10557 (buffer-substring region-start region-end))
10558 (prog1 org-refile-active-region-within-subtree
10559 (org-toggle-heading)))
10560 (error "The region is not a (sequence of) subtree(s)")))
10561 (if (equal goto '(16))
10562 (org-refile-goto-last-stored)
10563 (when (or
10564 (and (equal goto 2)
10565 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10566 (prog1
10567 (setq it (list (or org-clock-heading "running clock")
10568 (buffer-file-name
10569 (marker-buffer org-clock-hd-marker))
10571 (marker-position org-clock-hd-marker)))
10572 (setq goto nil)))
10573 (setq it (or rfloc
10574 (let (heading-text)
10575 (save-excursion
10576 (unless goto
10577 (org-back-to-heading t)
10578 (setq heading-text
10579 (nth 4 (org-heading-components))))
10580 (org-refile-get-location
10581 (cond (goto "Goto")
10582 (regionp "Refile region to")
10583 (t (concat "Refile subtree \""
10584 heading-text "\" to")))
10585 default-buffer
10586 org-refile-allow-creating-parent-nodes
10587 goto))))))
10588 (setq file (nth 1 it)
10589 re (nth 2 it)
10590 pos (nth 3 it))
10591 (if (and (not goto)
10593 (equal (buffer-file-name) file)
10594 (if regionp
10595 (and (>= pos region-start)
10596 (<= pos region-end))
10597 (and (>= pos (point))
10598 (< pos (save-excursion
10599 (org-end-of-subtree t t))))))
10600 (error "Cannot refile to position inside the tree or region"))
10602 (setq nbuf (or (find-buffer-visiting file)
10603 (find-file-noselect file)))
10604 (if goto
10605 (progn
10606 (org-pop-to-buffer-same-window nbuf)
10607 (goto-char pos)
10608 (org-show-context 'org-goto))
10609 (if regionp
10610 (progn
10611 (org-kill-new (buffer-substring region-start region-end))
10612 (org-save-markers-in-region region-start region-end))
10613 (org-copy-subtree 1 nil t))
10614 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10615 (find-file-noselect file)))
10616 (setq reversed (org-notes-order-reversed-p))
10617 (save-excursion
10618 (save-restriction
10619 (widen)
10620 (if pos
10621 (progn
10622 (goto-char pos)
10623 (looking-at org-outline-regexp)
10624 (setq level (org-get-valid-level (funcall outline-level) 1))
10625 (goto-char
10626 (if reversed
10627 (or (outline-next-heading) (point-max))
10628 (or (save-excursion (org-get-next-sibling))
10629 (org-end-of-subtree t t)
10630 (point-max)))))
10631 (setq level 1)
10632 (if (not reversed)
10633 (goto-char (point-max))
10634 (goto-char (point-min))
10635 (or (outline-next-heading) (goto-char (point-max)))))
10636 (if (not (bolp)) (newline))
10637 (org-paste-subtree level)
10638 (when org-log-refile
10639 (org-add-log-setup 'refile nil nil 'findpos
10640 org-log-refile)
10641 (unless (eq org-log-refile 'note)
10642 (save-excursion (org-add-log-note))))
10643 (and org-auto-align-tags (org-set-tags nil t))
10644 (bookmark-set "org-refile-last-stored")
10645 ;; If we are refiling for capture, make sure that the
10646 ;; last-capture pointers point here
10647 (when (org-bound-and-true-p org-refile-for-capture)
10648 (bookmark-set "org-capture-last-stored-marker")
10649 (move-marker org-capture-last-stored-marker (point)))
10650 (if (fboundp 'deactivate-mark) (deactivate-mark))
10651 (run-hooks 'org-after-refile-insert-hook))))
10652 (if regionp
10653 (delete-region (point) (+ (point) region-length))
10654 (org-cut-subtree))
10655 (when (featurep 'org-inlinetask)
10656 (org-inlinetask-remove-END-maybe))
10657 (setq org-markers-to-move nil)
10658 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10660 (defun org-refile-goto-last-stored ()
10661 "Go to the location where the last refile was stored."
10662 (interactive)
10663 (bookmark-jump "org-refile-last-stored")
10664 (message "This is the location of the last refile"))
10666 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10667 no-exclude)
10668 "Prompt the user for a refile location, using PROMPT.
10669 PROMPT should not be suffixed with a colon and a space, because
10670 this function appends the default value from
10671 `org-refile-history' automatically, if that is not empty.
10672 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10673 this is used for the GOTO interface."
10674 (let ((org-refile-targets org-refile-targets)
10675 (org-refile-use-outline-path org-refile-use-outline-path)
10676 excluded-entries)
10677 (when (and (eq major-mode 'org-mode)
10678 (not org-refile-use-cache)
10679 (not no-exclude))
10680 (org-map-tree
10681 (lambda()
10682 (setq excluded-entries
10683 (append excluded-entries (list (org-get-heading t t)))))))
10684 (setq org-refile-target-table
10685 (org-refile-get-targets default-buffer excluded-entries)))
10686 (unless org-refile-target-table
10687 (error "No refile targets"))
10688 (let* ((prompt (concat prompt
10689 (and (car org-refile-history)
10690 (concat " (default " (car org-refile-history) ")"))
10691 ": "))
10692 (cbuf (current-buffer))
10693 (partial-completion-mode nil)
10694 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10695 (cfunc (if (and org-refile-use-outline-path
10696 org-outline-path-complete-in-steps)
10697 'org-olpath-completing-read
10698 'org-icompleting-read))
10699 (extra (if org-refile-use-outline-path "/" ""))
10700 (filename (and cfn (expand-file-name cfn)))
10701 (tbl (mapcar
10702 (lambda (x)
10703 (if (and (not (member org-refile-use-outline-path
10704 '(file full-file-path)))
10705 (not (equal filename (nth 1 x))))
10706 (cons (concat (car x) extra " ("
10707 (file-name-nondirectory (nth 1 x)) ")")
10708 (cdr x))
10709 (cons (concat (car x) extra) (cdr x))))
10710 org-refile-target-table))
10711 (completion-ignore-case t)
10712 pa answ parent-target child parent old-hist)
10713 (setq old-hist org-refile-history)
10714 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10715 nil 'org-refile-history (car org-refile-history)))
10716 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10717 (org-refile-check-position pa)
10718 (if pa
10719 (progn
10720 (when (or (not org-refile-history)
10721 (not (eq old-hist org-refile-history))
10722 (not (equal (car pa) (car org-refile-history))))
10723 (setq org-refile-history
10724 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10725 org-refile-history
10726 (cdr org-refile-history))))
10727 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10728 (pop org-refile-history)))
10730 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10731 (progn
10732 (setq parent (match-string 1 answ)
10733 child (match-string 2 answ))
10734 (setq parent-target (or (assoc parent tbl)
10735 (assoc (concat parent "/") tbl)))
10736 (when (and parent-target
10737 (or (eq new-nodes t)
10738 (and (eq new-nodes 'confirm)
10739 (y-or-n-p (format "Create new node \"%s\"? "
10740 child)))))
10741 (org-refile-new-child parent-target child)))
10742 (error "Invalid target location")))))
10744 (defun org-refile-check-position (refile-pointer)
10745 "Check if the refile pointer matches the readline to which it points."
10746 (let* ((file (nth 1 refile-pointer))
10747 (re (nth 2 refile-pointer))
10748 (pos (nth 3 refile-pointer))
10749 buffer)
10750 (when (org-string-nw-p re)
10751 (setq buffer (if (markerp pos)
10752 (marker-buffer pos)
10753 (or (find-buffer-visiting file)
10754 (find-file-noselect file))))
10755 (with-current-buffer buffer
10756 (save-excursion
10757 (save-restriction
10758 (widen)
10759 (goto-char pos)
10760 (beginning-of-line 1)
10761 (unless (org-looking-at-p re)
10762 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
10764 (defun org-refile-new-child (parent-target child)
10765 "Use refile target PARENT-TARGET to add new CHILD below it."
10766 (unless parent-target
10767 (error "Cannot find parent for new node"))
10768 (let ((file (nth 1 parent-target))
10769 (pos (nth 3 parent-target))
10770 level)
10771 (with-current-buffer (or (find-buffer-visiting file)
10772 (find-file-noselect file))
10773 (save-excursion
10774 (save-restriction
10775 (widen)
10776 (if pos
10777 (goto-char pos)
10778 (goto-char (point-max))
10779 (if (not (bolp)) (newline)))
10780 (when (looking-at org-outline-regexp)
10781 (setq level (funcall outline-level))
10782 (org-end-of-subtree t t))
10783 (org-back-over-empty-lines)
10784 (insert "\n" (make-string
10785 (if pos (org-get-valid-level level 1) 1) ?*)
10786 " " child "\n")
10787 (beginning-of-line 0)
10788 (list (concat (car parent-target) "/" child) file "" (point)))))))
10790 (defun org-olpath-completing-read (prompt collection &rest args)
10791 "Read an outline path like a file name."
10792 (let ((thetable collection)
10793 (org-completion-use-ido nil) ; does not work with ido.
10794 (org-completion-use-iswitchb nil)) ; or iswitchb
10795 (apply
10796 'org-icompleting-read prompt
10797 (lambda (string predicate &optional flag)
10798 (let (rtn r f (l (length string)))
10799 (cond
10800 ((eq flag nil)
10801 ;; try completion
10802 (try-completion string thetable))
10803 ((eq flag t)
10804 ;; all-completions
10805 (setq rtn (all-completions string thetable predicate))
10806 (mapcar
10807 (lambda (x)
10808 (setq r (substring x l))
10809 (if (string-match " ([^)]*)$" x)
10810 (setq f (match-string 0 x))
10811 (setq f ""))
10812 (if (string-match "/" r)
10813 (concat string (substring r 0 (match-end 0)) f)
10815 rtn))
10816 ((eq flag 'lambda)
10817 ;; exact match?
10818 (assoc string thetable)))
10820 args)))
10822 ;;;; Dynamic blocks
10824 (defun org-find-dblock (name)
10825 "Find the first dynamic block with name NAME in the buffer.
10826 If not found, stay at current position and return nil."
10827 (let (pos)
10828 (save-excursion
10829 (goto-char (point-min))
10830 (setq pos (and (re-search-forward (concat "^[ \t]*#\\+BEGIN:[ \t]+" name "\\>")
10831 nil t)
10832 (match-beginning 0))))
10833 (if pos (goto-char pos))
10834 pos))
10836 (defconst org-dblock-start-re
10837 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10838 "Matches the start line of a dynamic block, with parameters.")
10840 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
10841 "Matches the end of a dynamic block.")
10843 (defun org-create-dblock (plist)
10844 "Create a dynamic block section, with parameters taken from PLIST.
10845 PLIST must contain a :name entry which is used as name of the block."
10846 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
10847 (end-of-line 1)
10848 (newline))
10849 (let ((col (current-column))
10850 (name (plist-get plist :name)))
10851 (insert "#+BEGIN: " name)
10852 (while plist
10853 (if (eq (car plist) :name)
10854 (setq plist (cddr plist))
10855 (insert " " (prin1-to-string (pop plist)))))
10856 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
10857 (beginning-of-line -2)))
10859 (defun org-prepare-dblock ()
10860 "Prepare dynamic block for refresh.
10861 This empties the block, puts the cursor at the insert position and returns
10862 the property list including an extra property :name with the block name."
10863 (unless (looking-at org-dblock-start-re)
10864 (error "Not at a dynamic block"))
10865 (let* ((begdel (1+ (match-end 0)))
10866 (name (org-no-properties (match-string 1)))
10867 (params (append (list :name name)
10868 (read (concat "(" (match-string 3) ")")))))
10869 (save-excursion
10870 (beginning-of-line 1)
10871 (skip-chars-forward " \t")
10872 (setq params (plist-put params :indentation-column (current-column))))
10873 (unless (re-search-forward org-dblock-end-re nil t)
10874 (error "Dynamic block not terminated"))
10875 (setq params
10876 (append params
10877 (list :content (buffer-substring
10878 begdel (match-beginning 0)))))
10879 (delete-region begdel (match-beginning 0))
10880 (goto-char begdel)
10881 (open-line 1)
10882 params))
10884 (defun org-map-dblocks (&optional command)
10885 "Apply COMMAND to all dynamic blocks in the current buffer.
10886 If COMMAND is not given, use `org-update-dblock'."
10887 (let ((cmd (or command 'org-update-dblock)))
10888 (save-excursion
10889 (goto-char (point-min))
10890 (while (re-search-forward org-dblock-start-re nil t)
10891 (goto-char (match-beginning 0))
10892 (save-excursion
10893 (condition-case nil
10894 (funcall cmd)
10895 (error (message "Error during update of dynamic block"))))
10896 (unless (re-search-forward org-dblock-end-re nil t)
10897 (error "Dynamic block not terminated"))))))
10899 (defun org-dblock-update (&optional arg)
10900 "User command for updating dynamic blocks.
10901 Update the dynamic block at point. With prefix ARG, update all dynamic
10902 blocks in the buffer."
10903 (interactive "P")
10904 (if arg
10905 (org-update-all-dblocks)
10906 (or (looking-at org-dblock-start-re)
10907 (org-beginning-of-dblock))
10908 (org-update-dblock)))
10910 (defun org-update-dblock ()
10911 "Update the dynamic block at point.
10912 This means to empty the block, parse for parameters and then call
10913 the correct writing function."
10914 (interactive)
10915 (save-window-excursion
10916 (let* ((pos (point))
10917 (line (org-current-line))
10918 (params (org-prepare-dblock))
10919 (name (plist-get params :name))
10920 (indent (plist-get params :indentation-column))
10921 (cmd (intern (concat "org-dblock-write:" name))))
10922 (message "Updating dynamic block `%s' at line %d..." name line)
10923 (funcall cmd params)
10924 (message "Updating dynamic block `%s' at line %d...done" name line)
10925 (goto-char pos)
10926 (when (and indent (> indent 0))
10927 (setq indent (make-string indent ?\ ))
10928 (save-excursion
10929 (org-beginning-of-dblock)
10930 (forward-line 1)
10931 (while (not (looking-at org-dblock-end-re))
10932 (insert indent)
10933 (beginning-of-line 2))
10934 (when (looking-at org-dblock-end-re)
10935 (and (looking-at "[ \t]+")
10936 (replace-match ""))
10937 (insert indent)))))))
10939 (defun org-beginning-of-dblock ()
10940 "Find the beginning of the dynamic block at point.
10941 Error if there is no such block at point."
10942 (let ((pos (point))
10943 beg)
10944 (end-of-line 1)
10945 (if (and (re-search-backward org-dblock-start-re nil t)
10946 (setq beg (match-beginning 0))
10947 (re-search-forward org-dblock-end-re nil t)
10948 (> (match-end 0) pos))
10949 (goto-char beg)
10950 (goto-char pos)
10951 (error "Not in a dynamic block"))))
10953 (defun org-update-all-dblocks ()
10954 "Update all dynamic blocks in the buffer.
10955 This function can be used in a hook."
10956 (interactive)
10957 (when (eq major-mode 'org-mode)
10958 (org-map-dblocks 'org-update-dblock)))
10961 ;;;; Completion
10963 (defconst org-additional-option-like-keywords
10964 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
10965 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
10966 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
10967 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
10968 "BEGIN:" "END:"
10969 "ORGTBL" "TBLFM:" "TBLNAME:"
10970 "BEGIN_EXAMPLE" "END_EXAMPLE"
10971 "BEGIN_QUOTE" "END_QUOTE"
10972 "BEGIN_VERSE" "END_VERSE"
10973 "BEGIN_CENTER" "END_CENTER"
10974 "BEGIN_SRC" "END_SRC"
10975 "BEGIN_RESULT" "END_RESULT"
10976 "SOURCE:" "SRCNAME:" "FUNCTION:"
10977 "RESULTS:" "DATA:"
10978 "HEADER:" "HEADERS:"
10979 "BABEL:"
10980 "CATEGORY:" "COLUMNS:" "PROPERTY:"
10981 "CAPTION:" "LABEL:"
10982 "SETUPFILE:"
10983 "INCLUDE:"
10984 "BIND:"
10985 "MACRO:"))
10987 (defcustom org-structure-template-alist
10989 ("s" "#+begin_src ?\n\n#+end_src"
10990 "<src lang=\"?\">\n\n</src>")
10991 ("e" "#+begin_example\n?\n#+end_example"
10992 "<example>\n?\n</example>")
10993 ("q" "#+begin_quote\n?\n#+end_quote"
10994 "<quote>\n?\n</quote>")
10995 ("v" "#+begin_verse\n?\n#+end_verse"
10996 "<verse>\n?\n/verse>")
10997 ("c" "#+begin_center\n?\n#+end_center"
10998 "<center>\n?\n/center>")
10999 ("l" "#+begin_latex\n?\n#+end_latex"
11000 "<literal style=\"latex\">\n?\n</literal>")
11001 ("L" "#+latex: "
11002 "<literal style=\"latex\">?</literal>")
11003 ("h" "#+begin_html\n?\n#+end_html"
11004 "<literal style=\"html\">\n?\n</literal>")
11005 ("H" "#+html: "
11006 "<literal style=\"html\">?</literal>")
11007 ("a" "#+begin_ascii\n?\n#+end_ascii")
11008 ("A" "#+ascii: ")
11009 ("i" "#+index: ?"
11010 "#+index: ?")
11011 ("I" "#+include %file ?"
11012 "<include file=%file markup=\"?\">")
11014 "Structure completion elements.
11015 This is a list of abbreviation keys and values. The value gets inserted
11016 if you type `<' followed by the key and then press the completion key,
11017 usually `M-TAB'. %file will be replaced by a file name after prompting
11018 for the file using completion. The cursor will be placed at the position
11019 of the `?` in the template.
11020 There are two templates for each key, the first uses the original Org syntax,
11021 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11022 the default when the /org-mtags.el/ module has been loaded. See also the
11023 variable `org-mtags-prefer-muse-templates'.
11024 This is an experimental feature, it is undecided if it is going to stay in."
11025 :group 'org-completion
11026 :type '(repeat
11027 (string :tag "Key")
11028 (string :tag "Template")
11029 (string :tag "Muse Template")))
11031 (defun org-try-structure-completion ()
11032 "Try to complete a structure template before point.
11033 This looks for strings like \"<e\" on an otherwise empty line and
11034 expands them."
11035 (let ((l (buffer-substring (point-at-bol) (point)))
11037 (when (and (looking-at "[ \t]*$")
11038 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11039 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11040 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11041 (match-beginning 1)) a)
11042 t)))
11044 (defun org-complete-expand-structure-template (start cell)
11045 "Expand a structure template."
11046 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11047 (rpl (nth (if musep 2 1) cell))
11048 (ind ""))
11049 (delete-region start (point))
11050 (when (string-match "\\`#\\+" rpl)
11051 (cond
11052 ((bolp))
11053 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11054 (setq ind (buffer-substring (point-at-bol) (point))))
11055 (t (newline))))
11056 (setq start (point))
11057 (if (string-match "%file" rpl)
11058 (setq rpl (replace-match
11059 (concat
11060 "\""
11061 (save-match-data
11062 (abbreviate-file-name (read-file-name "Include file: ")))
11063 "\"")
11064 t t rpl)))
11065 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11066 (concat "\n" ind)))
11067 (insert rpl)
11068 (if (re-search-backward "\\?" start t) (delete-char 1))))
11070 ;;;; TODO, DEADLINE, Comments
11072 (defun org-toggle-comment ()
11073 "Change the COMMENT state of an entry."
11074 (interactive)
11075 (save-excursion
11076 (org-back-to-heading)
11077 (let (case-fold-search)
11078 (cond
11079 ((looking-at (format org-heading-keyword-regexp-format
11080 org-comment-string))
11081 (goto-char (match-end 1))
11082 (looking-at (concat " +" org-comment-string))
11083 (replace-match "" t t)
11084 (when (eolp) (insert " ")))
11085 ((looking-at org-outline-regexp)
11086 (goto-char (match-end 0))
11087 (insert org-comment-string " "))))))
11089 (defvar org-last-todo-state-is-todo nil
11090 "This is non-nil when the last TODO state change led to a TODO state.
11091 If the last change removed the TODO tag or switched to DONE, then
11092 this is nil.")
11094 (defvar org-setting-tags nil) ; dynamically skipped
11096 (defvar org-todo-setup-filter-hook nil
11097 "Hook for functions that pre-filter todo specs.
11098 Each function takes a todo spec and returns either nil or the spec
11099 transformed into canonical form." )
11101 (defvar org-todo-get-default-hook nil
11102 "Hook for functions that get a default item for todo.
11103 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11104 nil or a string to be used for the todo mark." )
11106 (defvar org-agenda-headline-snapshot-before-repeat)
11108 (defun org-current-effective-time ()
11109 "Return current time adjusted for `org-extend-today-until' variable"
11110 (let* ((ct (org-current-time))
11111 (dct (decode-time ct))
11112 (ct1
11113 (if (and org-use-effective-time
11114 (< (nth 2 dct) org-extend-today-until))
11115 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11116 ct)))
11117 ct1))
11119 (defun org-todo-yesterday (&optional arg)
11120 "Like `org-todo' but the time of change will be 23:59 of yesterday"
11121 (interactive "P")
11122 (let* ((hour (third (decode-time
11123 (org-current-time))))
11124 (org-extend-today-until (1+ hour)))
11125 (org-todo arg)))
11127 (defun org-todo (&optional arg)
11128 "Change the TODO state of an item.
11129 The state of an item is given by a keyword at the start of the heading,
11130 like
11131 *** TODO Write paper
11132 *** DONE Call mom
11134 The different keywords are specified in the variable `org-todo-keywords'.
11135 By default the available states are \"TODO\" and \"DONE\".
11136 So for this example: when the item starts with TODO, it is changed to DONE.
11137 When it starts with DONE, the DONE is removed. And when neither TODO nor
11138 DONE are present, add TODO at the beginning of the heading.
11140 With \\[universal-argument] prefix arg, use completion to determine the new \
11141 state.
11142 With numeric prefix arg, switch to that state.
11143 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11144 keywords (nextset).
11145 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11147 For calling through lisp, arg is also interpreted in the following way:
11148 'none -> empty state
11149 \"\"(empty string) -> switch to empty state
11150 'done -> switch to DONE
11151 'nextset -> switch to the next set of keywords
11152 'previousset -> switch to the previous set of keywords
11153 \"WAITING\" -> switch to the specified keyword, but only if it
11154 really is a member of `org-todo-keywords'."
11155 (interactive "P")
11156 (if (equal arg '(16)) (setq arg 'nextset))
11157 (let ((org-blocker-hook org-blocker-hook)
11158 (case-fold-search nil))
11159 (when (equal arg '(64))
11160 (setq arg nil org-blocker-hook nil))
11161 (when (and org-blocker-hook
11162 (or org-inhibit-blocking
11163 (org-entry-get nil "NOBLOCKING")))
11164 (setq org-blocker-hook nil))
11165 (save-excursion
11166 (catch 'exit
11167 (org-back-to-heading t)
11168 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11169 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11170 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11171 (let* ((match-data (match-data))
11172 (startpos (point-at-bol))
11173 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11174 (org-log-done org-log-done)
11175 (org-log-repeat org-log-repeat)
11176 (org-todo-log-states org-todo-log-states)
11177 (this (match-string 1))
11178 (hl-pos (match-beginning 0))
11179 (head (org-get-todo-sequence-head this))
11180 (ass (assoc head org-todo-kwd-alist))
11181 (interpret (nth 1 ass))
11182 (done-word (nth 3 ass))
11183 (final-done-word (nth 4 ass))
11184 (last-state (or this ""))
11185 (completion-ignore-case t)
11186 (member (member this org-todo-keywords-1))
11187 (tail (cdr member))
11188 (state (cond
11189 ((and org-todo-key-trigger
11190 (or (and (equal arg '(4))
11191 (eq org-use-fast-todo-selection 'prefix))
11192 (and (not arg) org-use-fast-todo-selection
11193 (not (eq org-use-fast-todo-selection
11194 'prefix)))))
11195 ;; Use fast selection
11196 (org-fast-todo-selection))
11197 ((and (equal arg '(4))
11198 (or (not org-use-fast-todo-selection)
11199 (not org-todo-key-trigger)))
11200 ;; Read a state with completion
11201 (org-icompleting-read
11202 "State: " (mapcar (lambda(x) (list x))
11203 org-todo-keywords-1)
11204 nil t))
11205 ((eq arg 'right)
11206 (if this
11207 (if tail (car tail) nil)
11208 (car org-todo-keywords-1)))
11209 ((eq arg 'left)
11210 (if (equal member org-todo-keywords-1)
11212 (if this
11213 (nth (- (length org-todo-keywords-1)
11214 (length tail) 2)
11215 org-todo-keywords-1)
11216 (org-last org-todo-keywords-1))))
11217 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11218 (setq arg nil))) ; hack to fall back to cycling
11219 (arg
11220 ;; user or caller requests a specific state
11221 (cond
11222 ((equal arg "") nil)
11223 ((eq arg 'none) nil)
11224 ((eq arg 'done) (or done-word (car org-done-keywords)))
11225 ((eq arg 'nextset)
11226 (or (car (cdr (member head org-todo-heads)))
11227 (car org-todo-heads)))
11228 ((eq arg 'previousset)
11229 (let ((org-todo-heads (reverse org-todo-heads)))
11230 (or (car (cdr (member head org-todo-heads)))
11231 (car org-todo-heads))))
11232 ((car (member arg org-todo-keywords-1)))
11233 ((stringp arg)
11234 (error "State `%s' not valid in this file" arg))
11235 ((nth (1- (prefix-numeric-value arg))
11236 org-todo-keywords-1))))
11237 ((null member) (or head (car org-todo-keywords-1)))
11238 ((equal this final-done-word) nil) ;; -> make empty
11239 ((null tail) nil) ;; -> first entry
11240 ((memq interpret '(type priority))
11241 (if (eq this-command last-command)
11242 (car tail)
11243 (if (> (length tail) 0)
11244 (or done-word (car org-done-keywords))
11245 nil)))
11247 (car tail))))
11248 (state (or
11249 (run-hook-with-args-until-success
11250 'org-todo-get-default-hook state last-state)
11251 state))
11252 (next (if state (concat " " state " ") " "))
11253 (change-plist (list :type 'todo-state-change :from this :to state
11254 :position startpos))
11255 dolog now-done-p)
11256 (when org-blocker-hook
11257 (setq org-last-todo-state-is-todo
11258 (not (member this org-done-keywords)))
11259 (unless (save-excursion
11260 (save-match-data
11261 (org-with-wide-buffer
11262 (run-hook-with-args-until-failure
11263 'org-blocker-hook change-plist))))
11264 (if (org-called-interactively-p 'interactive)
11265 (error "TODO state change from %s to %s blocked" this state)
11266 ;; fail silently
11267 (message "TODO state change from %s to %s blocked" this state)
11268 (throw 'exit nil))))
11269 (store-match-data match-data)
11270 (replace-match next t t)
11271 (unless (pos-visible-in-window-p hl-pos)
11272 (message "TODO state changed to %s" (org-trim next)))
11273 (unless head
11274 (setq head (org-get-todo-sequence-head state)
11275 ass (assoc head org-todo-kwd-alist)
11276 interpret (nth 1 ass)
11277 done-word (nth 3 ass)
11278 final-done-word (nth 4 ass)))
11279 (when (memq arg '(nextset previousset))
11280 (message "Keyword-Set %d/%d: %s"
11281 (- (length org-todo-sets) -1
11282 (length (memq (assoc state org-todo-sets) org-todo-sets)))
11283 (length org-todo-sets)
11284 (mapconcat 'identity (assoc state org-todo-sets) " ")))
11285 (setq org-last-todo-state-is-todo
11286 (not (member state org-done-keywords)))
11287 (setq now-done-p (and (member state org-done-keywords)
11288 (not (member this org-done-keywords))))
11289 (and logging (org-local-logging logging))
11290 (when (and (or org-todo-log-states org-log-done)
11291 (not (eq org-inhibit-logging t))
11292 (not (memq arg '(nextset previousset))))
11293 ;; we need to look at recording a time and note
11294 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
11295 (nth 2 (assoc this org-todo-log-states))))
11296 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11297 (setq dolog 'time))
11298 (when (and state
11299 (member state org-not-done-keywords)
11300 (not (member this org-not-done-keywords)))
11301 ;; This is now a todo state and was not one before
11302 ;; If there was a CLOSED time stamp, get rid of it.
11303 (org-add-planning-info nil nil 'closed))
11304 (when (and now-done-p org-log-done)
11305 ;; It is now done, and it was not done before
11306 (org-add-planning-info 'closed (org-current-effective-time))
11307 (if (and (not dolog) (eq 'note org-log-done))
11308 (org-add-log-setup 'done state this 'findpos 'note)))
11309 (when (and state dolog)
11310 ;; This is a non-nil state, and we need to log it
11311 (org-add-log-setup 'state state this 'findpos dolog)))
11312 ;; Fixup tag positioning
11313 (org-todo-trigger-tag-changes state)
11314 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11315 (when org-provide-todo-statistics
11316 (org-update-parent-todo-statistics))
11317 (run-hooks 'org-after-todo-state-change-hook)
11318 (if (and arg (not (member state org-done-keywords)))
11319 (setq head (org-get-todo-sequence-head state)))
11320 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11321 ;; Do we need to trigger a repeat?
11322 (when now-done-p
11323 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11324 ;; This is for the agenda, take a snapshot of the headline.
11325 (save-match-data
11326 (setq org-agenda-headline-snapshot-before-repeat
11327 (org-get-heading))))
11328 (org-auto-repeat-maybe state))
11329 ;; Fixup cursor location if close to the keyword
11330 (if (and (outline-on-heading-p)
11331 (not (bolp))
11332 (save-excursion (beginning-of-line 1)
11333 (looking-at org-todo-line-regexp))
11334 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11335 (progn
11336 (goto-char (or (match-end 2) (match-end 1)))
11337 (and (looking-at " ") (just-one-space))))
11338 (when org-trigger-hook
11339 (save-excursion
11340 (run-hook-with-args 'org-trigger-hook change-plist))))))))
11342 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11343 "Block turning an entry into a TODO, using the hierarchy.
11344 This checks whether the current task should be blocked from state
11345 changes. Such blocking occurs when:
11347 1. The task has children which are not all in a completed state.
11349 2. A task has a parent with the property :ORDERED:, and there
11350 are siblings prior to the current task with incomplete
11351 status.
11353 3. The parent of the task is blocked because it has siblings that should
11354 be done first, or is child of a block grandparent TODO entry."
11356 (if (not org-enforce-todo-dependencies)
11357 t ; if locally turned off don't block
11358 (catch 'dont-block
11359 ;; If this is not a todo state change, or if this entry is already DONE,
11360 ;; do not block
11361 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11362 (member (plist-get change-plist :from)
11363 (cons 'done org-done-keywords))
11364 (member (plist-get change-plist :to)
11365 (cons 'todo org-not-done-keywords))
11366 (not (plist-get change-plist :to)))
11367 (throw 'dont-block t))
11368 ;; If this task has children, and any are undone, it's blocked
11369 (save-excursion
11370 (org-back-to-heading t)
11371 (let ((this-level (funcall outline-level)))
11372 (outline-next-heading)
11373 (let ((child-level (funcall outline-level)))
11374 (while (and (not (eobp))
11375 (> child-level this-level))
11376 ;; this todo has children, check whether they are all
11377 ;; completed
11378 (if (and (not (org-entry-is-done-p))
11379 (org-entry-is-todo-p))
11380 (throw 'dont-block nil))
11381 (outline-next-heading)
11382 (setq child-level (funcall outline-level))))))
11383 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11384 ;; any previous siblings are undone, it's blocked
11385 (save-excursion
11386 (org-back-to-heading t)
11387 (let* ((pos (point))
11388 (parent-pos (and (org-up-heading-safe) (point))))
11389 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11390 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11391 (forward-line 1)
11392 (re-search-forward org-not-done-heading-regexp pos t))
11393 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11394 ;; Search further up the hierarchy, to see if an anchestor is blocked
11395 (while t
11396 (goto-char parent-pos)
11397 (if (not (looking-at org-not-done-heading-regexp))
11398 (throw 'dont-block t)) ; do not block, parent is not a TODO
11399 (setq pos (point))
11400 (setq parent-pos (and (org-up-heading-safe) (point)))
11401 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11402 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11403 (forward-line 1)
11404 (re-search-forward org-not-done-heading-regexp pos t))
11405 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11407 (defcustom org-track-ordered-property-with-tag nil
11408 "Should the ORDERED property also be shown as a tag?
11409 The ORDERED property decides if an entry should require subtasks to be
11410 completed in sequence. Since a property is not very visible, setting
11411 this option means that toggling the ORDERED property with the command
11412 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11413 not relevant for the behavior, but it makes things more visible.
11415 Note that toggling the tag with tags commands will not change the property
11416 and therefore not influence behavior!
11418 This can be t, meaning the tag ORDERED should be used, It can also be a
11419 string to select a different tag for this task."
11420 :group 'org-todo
11421 :type '(choice
11422 (const :tag "No tracking" nil)
11423 (const :tag "Track with ORDERED tag" t)
11424 (string :tag "Use other tag")))
11426 (defun org-toggle-ordered-property ()
11427 "Toggle the ORDERED property of the current entry.
11428 For better visibility, you can track the value of this property with a tag.
11429 See variable `org-track-ordered-property-with-tag'."
11430 (interactive)
11431 (let* ((t1 org-track-ordered-property-with-tag)
11432 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11433 (save-excursion
11434 (org-back-to-heading)
11435 (if (org-entry-get nil "ORDERED")
11436 (progn
11437 (org-delete-property "ORDERED")
11438 (and tag (org-toggle-tag tag 'off))
11439 (message "Subtasks can be completed in arbitrary order"))
11440 (org-entry-put nil "ORDERED" "t")
11441 (and tag (org-toggle-tag tag 'on))
11442 (message "Subtasks must be completed in sequence")))))
11444 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11445 (defun org-block-todo-from-checkboxes (change-plist)
11446 "Block turning an entry into a TODO, using checkboxes.
11447 This checks whether the current task should be blocked from state
11448 changes because there are unchecked boxes in this entry."
11449 (if (not org-enforce-todo-checkbox-dependencies)
11450 t ; if locally turned off don't block
11451 (catch 'dont-block
11452 ;; If this is not a todo state change, or if this entry is already DONE,
11453 ;; do not block
11454 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11455 (member (plist-get change-plist :from)
11456 (cons 'done org-done-keywords))
11457 (member (plist-get change-plist :to)
11458 (cons 'todo org-not-done-keywords))
11459 (not (plist-get change-plist :to)))
11460 (throw 'dont-block t))
11461 ;; If this task has checkboxes that are not checked, it's blocked
11462 (save-excursion
11463 (org-back-to-heading t)
11464 (let ((beg (point)) end)
11465 (outline-next-heading)
11466 (setq end (point))
11467 (goto-char beg)
11468 (if (org-list-search-forward
11469 (concat (org-item-beginning-re)
11470 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11471 "\\[[- ]\\]")
11472 end t)
11473 (progn
11474 (if (boundp 'org-blocked-by-checkboxes)
11475 (setq org-blocked-by-checkboxes t))
11476 (throw 'dont-block nil)))))
11477 t))) ; do not block
11479 (defun org-entry-blocked-p ()
11480 "Is the current entry blocked?"
11481 (if (org-entry-get nil "NOBLOCKING")
11482 nil ;; Never block this entry
11483 (not
11484 (run-hook-with-args-until-failure
11485 'org-blocker-hook
11486 (list :type 'todo-state-change
11487 :position (point)
11488 :from 'todo
11489 :to 'done)))))
11491 (defun org-update-statistics-cookies (all)
11492 "Update the statistics cookie, either from TODO or from checkboxes.
11493 This should be called with the cursor in a line with a statistics cookie."
11494 (interactive "P")
11495 (if all
11496 (progn
11497 (org-update-checkbox-count 'all)
11498 (org-map-entries 'org-update-parent-todo-statistics))
11499 (if (not (org-on-heading-p))
11500 (org-update-checkbox-count)
11501 (let ((pos (move-marker (make-marker) (point)))
11502 end l1 l2)
11503 (ignore-errors (org-back-to-heading t))
11504 (if (not (org-on-heading-p))
11505 (org-update-checkbox-count)
11506 (setq l1 (org-outline-level))
11507 (setq end (save-excursion
11508 (outline-next-heading)
11509 (if (org-on-heading-p) (setq l2 (org-outline-level)))
11510 (point)))
11511 (if (and (save-excursion
11512 (re-search-forward
11513 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11514 (not (save-excursion (re-search-forward
11515 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11516 (org-update-checkbox-count)
11517 (if (and l2 (> l2 l1))
11518 (progn
11519 (goto-char end)
11520 (org-update-parent-todo-statistics))
11521 (goto-char pos)
11522 (beginning-of-line 1)
11523 (while (re-search-forward
11524 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11525 (point-at-eol) t)
11526 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11527 (goto-char pos)
11528 (move-marker pos nil)))))
11530 (defvar org-entry-property-inherited-from) ;; defined below
11531 (defun org-update-parent-todo-statistics ()
11532 "Update any statistics cookie in the parent of the current headline.
11533 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11534 the entire subtree and this will travel up the hierarchy and update
11535 statistics everywhere."
11536 (let* ((prop (save-excursion (org-up-heading-safe)
11537 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11538 (recursive (or (not org-hierarchical-todo-statistics)
11539 (and prop (string-match "\\<recursive\\>" prop))))
11540 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11542 (first t)
11543 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11544 level ltoggle l1 new ndel
11545 (cnt-all 0) (cnt-done 0) is-percent kwd
11546 checkbox-beg ov ovs ove cookie-present)
11547 (catch 'exit
11548 (save-excursion
11549 (beginning-of-line 1)
11550 (setq ltoggle (funcall outline-level))
11551 ;; Three situations are to consider:
11553 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11554 ;; to the top-level ancestor on the headline;
11556 ;; 2. If parent has "recursive" property, repeat up to the
11557 ;; headline setting that property, taking inheritance into
11558 ;; account;
11560 ;; 3. Else, move up to direct parent and proceed only once.
11561 (while (and (setq level (org-up-heading-safe))
11562 (or recursive first)
11563 (>= (point) lim))
11564 (setq first nil cookie-present nil)
11565 (unless (and level
11566 (not (string-match
11567 "\\<checkbox\\>"
11568 (downcase (or (org-entry-get nil "COOKIE_DATA")
11569 "")))))
11570 (throw 'exit nil))
11571 (while (re-search-forward box-re (point-at-eol) t)
11572 (setq cnt-all 0 cnt-done 0 cookie-present t)
11573 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11574 (save-match-data
11575 (unless (outline-next-heading) (throw 'exit nil))
11576 (while (and (looking-at org-complex-heading-regexp)
11577 (> (setq l1 (length (match-string 1))) level))
11578 (setq kwd (and (or recursive (= l1 ltoggle))
11579 (match-string 2)))
11580 (if (or (eq org-provide-todo-statistics 'all-headlines)
11581 (and (listp org-provide-todo-statistics)
11582 (or (member kwd org-provide-todo-statistics)
11583 (member kwd org-done-keywords))))
11584 (setq cnt-all (1+ cnt-all))
11585 (if (eq org-provide-todo-statistics t)
11586 (and kwd (setq cnt-all (1+ cnt-all)))))
11587 (and (member kwd org-done-keywords)
11588 (setq cnt-done (1+ cnt-done)))
11589 (outline-next-heading)))
11590 (setq new
11591 (if is-percent
11592 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11593 (format "[%d/%d]" cnt-done cnt-all))
11594 ndel (- (match-end 0) checkbox-beg))
11595 ;; handle overlays when updating cookie from column view
11596 (when (setq ov (car (overlays-at checkbox-beg)))
11597 (setq ovs (overlay-start ov) ove (overlay-end ov))
11598 (delete-overlay ov))
11599 (goto-char checkbox-beg)
11600 (insert new)
11601 (delete-region (point) (+ (point) ndel))
11602 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11603 (when ov (move-overlay ov ovs ove)))
11604 (when cookie-present
11605 (run-hook-with-args 'org-after-todo-statistics-hook
11606 cnt-done (- cnt-all cnt-done))))))
11607 (run-hooks 'org-todo-statistics-hook)))
11609 (defvar org-after-todo-statistics-hook nil
11610 "Hook that is called after a TODO statistics cookie has been updated.
11611 Each function is called with two arguments: the number of not-done entries
11612 and the number of done entries.
11614 For example, the following function, when added to this hook, will switch
11615 an entry to DONE when all children are done, and back to TODO when new
11616 entries are set to a TODO status. Note that this hook is only called
11617 when there is a statistics cookie in the headline!
11619 (defun org-summary-todo (n-done n-not-done)
11620 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11621 (let (org-log-done org-log-states) ; turn off logging
11622 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11625 (defvar org-todo-statistics-hook nil
11626 "Hook that is run whenever Org thinks TODO statistics should be updated.
11627 This hook runs even if there is no statistics cookie present, in which case
11628 `org-after-todo-statistics-hook' would not run.")
11630 (defun org-todo-trigger-tag-changes (state)
11631 "Apply the changes defined in `org-todo-state-tags-triggers'."
11632 (let ((l org-todo-state-tags-triggers)
11633 changes)
11634 (when (or (not state) (equal state ""))
11635 (setq changes (append changes (cdr (assoc "" l)))))
11636 (when (and (stringp state) (> (length state) 0))
11637 (setq changes (append changes (cdr (assoc state l)))))
11638 (when (member state org-not-done-keywords)
11639 (setq changes (append changes (cdr (assoc 'todo l)))))
11640 (when (member state org-done-keywords)
11641 (setq changes (append changes (cdr (assoc 'done l)))))
11642 (dolist (c changes)
11643 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11645 (defun org-local-logging (value)
11646 "Get logging settings from a property VALUE."
11647 (let* (words w a)
11648 ;; directly set the variables, they are already local.
11649 (setq org-log-done nil
11650 org-log-repeat nil
11651 org-todo-log-states nil)
11652 (setq words (org-split-string value))
11653 (while (setq w (pop words))
11654 (cond
11655 ((setq a (assoc w org-startup-options))
11656 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11657 (set (nth 1 a) (nth 2 a))))
11658 ((setq a (org-extract-log-state-settings w))
11659 (and (member (car a) org-todo-keywords-1)
11660 (push a org-todo-log-states)))))))
11662 (defun org-get-todo-sequence-head (kwd)
11663 "Return the head of the TODO sequence to which KWD belongs.
11664 If KWD is not set, check if there is a text property remembering the
11665 right sequence."
11666 (let (p)
11667 (cond
11668 ((not kwd)
11669 (or (get-text-property (point-at-bol) 'org-todo-head)
11670 (progn
11671 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11672 nil (point-at-eol)))
11673 (get-text-property p 'org-todo-head))))
11674 ((not (member kwd org-todo-keywords-1))
11675 (car org-todo-keywords-1))
11676 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11678 (defun org-fast-todo-selection ()
11679 "Fast TODO keyword selection with single keys.
11680 Returns the new TODO keyword, or nil if no state change should occur."
11681 (let* ((fulltable org-todo-key-alist)
11682 (done-keywords org-done-keywords) ;; needed for the faces.
11683 (maxlen (apply 'max (mapcar
11684 (lambda (x)
11685 (if (stringp (car x)) (string-width (car x)) 0))
11686 fulltable)))
11687 (expert nil)
11688 (fwidth (+ maxlen 3 1 3))
11689 (ncol (/ (- (window-width) 4) fwidth))
11690 tg cnt e c tbl
11691 groups ingroup)
11692 (save-excursion
11693 (save-window-excursion
11694 (if expert
11695 (set-buffer (get-buffer-create " *Org todo*"))
11696 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11697 (erase-buffer)
11698 (org-set-local 'org-done-keywords done-keywords)
11699 (setq tbl fulltable cnt 0)
11700 (while (setq e (pop tbl))
11701 (cond
11702 ((equal e '(:startgroup))
11703 (push '() groups) (setq ingroup t)
11704 (when (not (= cnt 0))
11705 (setq cnt 0)
11706 (insert "\n"))
11707 (insert "{ "))
11708 ((equal e '(:endgroup))
11709 (setq ingroup nil cnt 0)
11710 (insert "}\n"))
11711 ((equal e '(:newline))
11712 (when (not (= cnt 0))
11713 (setq cnt 0)
11714 (insert "\n")
11715 (setq e (car tbl))
11716 (while (equal (car tbl) '(:newline))
11717 (insert "\n")
11718 (setq tbl (cdr tbl)))))
11720 (setq tg (car e) c (cdr e))
11721 (if ingroup (push tg (car groups)))
11722 (setq tg (org-add-props tg nil 'face
11723 (org-get-todo-face tg)))
11724 (if (and (= cnt 0) (not ingroup)) (insert " "))
11725 (insert "[" c "] " tg (make-string
11726 (- fwidth 4 (length tg)) ?\ ))
11727 (when (= (setq cnt (1+ cnt)) ncol)
11728 (insert "\n")
11729 (if ingroup (insert " "))
11730 (setq cnt 0)))))
11731 (insert "\n")
11732 (goto-char (point-min))
11733 (if (not expert) (org-fit-window-to-buffer))
11734 (message "[a-z..]:Set [SPC]:clear")
11735 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11736 (cond
11737 ((or (= c ?\C-g)
11738 (and (= c ?q) (not (rassoc c fulltable))))
11739 (setq quit-flag t))
11740 ((= c ?\ ) nil)
11741 ((setq e (rassoc c fulltable) tg (car e))
11743 (t (setq quit-flag t)))))))
11745 (defun org-entry-is-todo-p ()
11746 (member (org-get-todo-state) org-not-done-keywords))
11748 (defun org-entry-is-done-p ()
11749 (member (org-get-todo-state) org-done-keywords))
11751 (defun org-get-todo-state ()
11752 (save-excursion
11753 (org-back-to-heading t)
11754 (and (looking-at org-todo-line-regexp)
11755 (match-end 2)
11756 (match-string 2))))
11758 (defun org-at-date-range-p (&optional inactive-ok)
11759 "Is the cursor inside a date range?"
11760 (interactive)
11761 (save-excursion
11762 (catch 'exit
11763 (let ((pos (point)))
11764 (skip-chars-backward "^[<\r\n")
11765 (skip-chars-backward "<[")
11766 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11767 (>= (match-end 0) pos)
11768 (throw 'exit t))
11769 (skip-chars-backward "^<[\r\n")
11770 (skip-chars-backward "<[")
11771 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11772 (>= (match-end 0) pos)
11773 (throw 'exit t)))
11774 nil)))
11776 (defun org-get-repeat (&optional tagline)
11777 "Check if there is a deadline/schedule with repeater in this entry."
11778 (save-match-data
11779 (save-excursion
11780 (org-back-to-heading t)
11781 (and (re-search-forward (if tagline
11782 (concat tagline "\\s-*" org-repeat-re)
11783 org-repeat-re)
11784 (org-entry-end-position) t)
11785 (match-string-no-properties 1)))))
11787 (defvar org-last-changed-timestamp)
11788 (defvar org-last-inserted-timestamp)
11789 (defvar org-log-post-message)
11790 (defvar org-log-note-purpose)
11791 (defvar org-log-note-how)
11792 (defvar org-log-note-extra)
11793 (defun org-auto-repeat-maybe (done-word)
11794 "Check if the current headline contains a repeated deadline/schedule.
11795 If yes, set TODO state back to what it was and change the base date
11796 of repeating deadline/scheduled time stamps to new date.
11797 This function is run automatically after each state change to a DONE state."
11798 ;; last-state is dynamically scoped into this function
11799 (let* ((repeat (org-get-repeat))
11800 (aa (assoc last-state org-todo-kwd-alist))
11801 (interpret (nth 1 aa))
11802 (head (nth 2 aa))
11803 (whata '(("d" . day) ("m" . month) ("y" . year)))
11804 (msg "Entry repeats: ")
11805 (org-log-done nil)
11806 (org-todo-log-states nil)
11807 re type n what ts time to-state)
11808 (when repeat
11809 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11810 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11811 org-todo-repeat-to-state))
11812 (unless (and to-state (member to-state org-todo-keywords-1))
11813 (setq to-state (if (eq interpret 'type) last-state head)))
11814 (org-todo to-state)
11815 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11816 (org-entry-put nil "LAST_REPEAT" (format-time-string
11817 (org-time-stamp-format t t))))
11818 (when org-log-repeat
11819 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11820 (memq 'org-add-log-note post-command-hook))
11821 ;; OK, we are already setup for some record
11822 (if (eq org-log-repeat 'note)
11823 ;; make sure we take a note, not only a time stamp
11824 (setq org-log-note-how 'note))
11825 ;; Set up for taking a record
11826 (org-add-log-setup 'state (or done-word (car org-done-keywords))
11827 last-state
11828 'findpos org-log-repeat)))
11829 (org-back-to-heading t)
11830 (org-add-planning-info nil nil 'closed)
11831 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11832 org-deadline-time-regexp "\\)\\|\\("
11833 org-ts-regexp "\\)"))
11834 (while (re-search-forward
11835 re (save-excursion (outline-next-heading) (point)) t)
11836 (setq type (if (match-end 1) org-scheduled-string
11837 (if (match-end 3) org-deadline-string "Plain:"))
11838 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
11839 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
11840 (setq n (string-to-number (match-string 2 ts))
11841 what (match-string 3 ts))
11842 (if (equal what "w") (setq n (* n 7) what "d"))
11843 ;; Preparation, see if we need to modify the start date for the change
11844 (when (match-end 1)
11845 (setq time (save-match-data (org-time-string-to-time ts)))
11846 (cond
11847 ((equal (match-string 1 ts) ".")
11848 ;; Shift starting date to today
11849 (org-timestamp-change
11850 (- (org-today) (time-to-days time))
11851 'day))
11852 ((equal (match-string 1 ts) "+")
11853 (let ((nshiftmax 10) (nshift 0))
11854 (while (or (= nshift 0)
11855 (<= (time-to-days time)
11856 (time-to-days (current-time))))
11857 (when (= (incf nshift) nshiftmax)
11858 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
11859 (error "Abort")))
11860 (org-timestamp-change n (cdr (assoc what whata)))
11861 (org-at-timestamp-p t)
11862 (setq ts (match-string 1))
11863 (setq time (save-match-data (org-time-string-to-time ts)))))
11864 (org-timestamp-change (- n) (cdr (assoc what whata)))
11865 ;; rematch, so that we have everything in place for the real shift
11866 (org-at-timestamp-p t)
11867 (setq ts (match-string 1))
11868 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
11869 (org-timestamp-change n (cdr (assoc what whata)))
11870 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
11871 (setq org-log-post-message msg)
11872 (message "%s" msg))))
11874 (defun org-show-todo-tree (arg)
11875 "Make a compact tree which shows all headlines marked with TODO.
11876 The tree will show the lines where the regexp matches, and all higher
11877 headlines above the match.
11878 With a \\[universal-argument] prefix, prompt for a regexp to match.
11879 With a numeric prefix N, construct a sparse tree for the Nth element
11880 of `org-todo-keywords-1'."
11881 (interactive "P")
11882 (let ((case-fold-search nil)
11883 (kwd-re
11884 (cond ((null arg) org-not-done-regexp)
11885 ((equal arg '(4))
11886 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
11887 (mapcar 'list org-todo-keywords-1))))
11888 (concat "\\("
11889 (mapconcat 'identity (org-split-string kwd "|") "\\|")
11890 "\\)\\>")))
11891 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
11892 (regexp-quote (nth (1- (prefix-numeric-value arg))
11893 org-todo-keywords-1)))
11894 (t (error "Invalid prefix argument: %s" arg)))))
11895 (message "%d TODO entries found"
11896 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
11898 (defun org-deadline (&optional remove time)
11899 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
11900 With argument REMOVE, remove any deadline from the item.
11901 With argument TIME, set the deadline at the corresponding date. TIME
11902 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
11903 (interactive "P")
11904 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11905 (let (org-loop-over-headlines-in-active-region)
11906 (org-map-entries
11907 `(org-deadline ',remove ,time) org-loop-over-headlines-in-active-region 'region (if (outline-invisible-p) (org-end-of-subtree nil t))))
11908 (let* ((old-date (org-entry-get nil "DEADLINE"))
11909 (repeater (and old-date
11910 (string-match
11911 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
11912 old-date)
11913 (match-string 1 old-date))))
11914 (if remove
11915 (progn
11916 (when (and old-date org-log-redeadline)
11917 (org-add-log-setup 'deldeadline nil old-date 'findpos
11918 org-log-redeadline))
11919 (org-remove-timestamp-with-keyword org-deadline-string)
11920 (message "Item no longer has a deadline."))
11921 (org-add-planning-info 'deadline time 'closed)
11922 (when (and old-date org-log-redeadline
11923 (not (equal old-date
11924 (substring org-last-inserted-timestamp 1 -1))))
11925 (org-add-log-setup 'redeadline nil old-date 'findpos
11926 org-log-redeadline))
11927 (when repeater
11928 (save-excursion
11929 (org-back-to-heading t)
11930 (when (re-search-forward (concat org-deadline-string " "
11931 org-last-inserted-timestamp)
11932 (save-excursion
11933 (outline-next-heading) (point)) t)
11934 (goto-char (1- (match-end 0)))
11935 (insert " " repeater)
11936 (setq org-last-inserted-timestamp
11937 (concat (substring org-last-inserted-timestamp 0 -1)
11938 " " repeater
11939 (substring org-last-inserted-timestamp -1))))))
11940 (message "Deadline on %s" org-last-inserted-timestamp)))))
11942 (defun org-schedule (&optional remove time)
11943 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
11944 With argument REMOVE, remove any scheduling date from the item.
11945 With argument TIME, scheduled at the corresponding date. TIME can
11946 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
11947 (interactive "P")
11948 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11949 (let (org-loop-over-headlines-in-active-region)
11950 (org-map-entries
11951 `(org-schedule ',remove ,time) org-loop-over-headlines-in-active-region 'region (if (outline-invisible-p) (org-end-of-subtree nil t))))
11952 (let* ((old-date (org-entry-get nil "SCHEDULED"))
11953 (repeater (and old-date
11954 (string-match
11955 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
11956 old-date)
11957 (match-string 1 old-date))))
11958 (if remove
11959 (progn
11960 (when (and old-date org-log-reschedule)
11961 (org-add-log-setup 'delschedule nil old-date 'findpos
11962 org-log-reschedule))
11963 (org-remove-timestamp-with-keyword org-scheduled-string)
11964 (message "Item is no longer scheduled."))
11965 (org-add-planning-info 'scheduled time 'closed)
11966 (when (and old-date org-log-reschedule
11967 (not (equal old-date
11968 (substring org-last-inserted-timestamp 1 -1))))
11969 (org-add-log-setup 'reschedule nil old-date 'findpos
11970 org-log-reschedule))
11971 (when repeater
11972 (save-excursion
11973 (org-back-to-heading t)
11974 (when (re-search-forward (concat org-scheduled-string " "
11975 org-last-inserted-timestamp)
11976 (save-excursion
11977 (outline-next-heading) (point)) t)
11978 (goto-char (1- (match-end 0)))
11979 (insert " " repeater)
11980 (setq org-last-inserted-timestamp
11981 (concat (substring org-last-inserted-timestamp 0 -1)
11982 " " repeater
11983 (substring org-last-inserted-timestamp -1))))))
11984 (message "Scheduled to %s" org-last-inserted-timestamp)))))
11986 (defun org-get-scheduled-time (pom &optional inherit)
11987 "Get the scheduled time as a time tuple, of a format suitable
11988 for calling org-schedule with, or if there is no scheduling,
11989 returns nil."
11990 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
11991 (when time
11992 (apply 'encode-time (org-parse-time-string time)))))
11994 (defun org-get-deadline-time (pom &optional inherit)
11995 "Get the deadline as a time tuple, of a format suitable for
11996 calling org-deadline with, or if there is no scheduling, returns
11997 nil."
11998 (let ((time (org-entry-get pom "DEADLINE" inherit)))
11999 (when time
12000 (apply 'encode-time (org-parse-time-string time)))))
12002 (defun org-remove-timestamp-with-keyword (keyword)
12003 "Remove all time stamps with KEYWORD in the current entry."
12004 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12005 beg)
12006 (save-excursion
12007 (org-back-to-heading t)
12008 (setq beg (point))
12009 (outline-next-heading)
12010 (while (re-search-backward re beg t)
12011 (replace-match "")
12012 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12013 (equal (char-before) ?\ ))
12014 (backward-delete-char 1)
12015 (if (string-match "^[ \t]*$" (buffer-substring
12016 (point-at-bol) (point-at-eol)))
12017 (delete-region (point-at-bol)
12018 (min (point-max) (1+ (point-at-eol))))))))))
12020 (defun org-add-planning-info (what &optional time &rest remove)
12021 "Insert new timestamp with keyword in the line directly after the headline.
12022 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12023 If non is given, the user is prompted for a date.
12024 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12025 be removed."
12026 (interactive)
12027 (let (org-time-was-given org-end-time-was-given ts
12028 end default-time default-input)
12030 (catch 'exit
12031 (when (and (memq what '(scheduled deadline))
12032 (or (not time)
12033 (and (stringp time)
12034 (string-match "^[-+]+[0-9]" time))))
12035 ;; Try to get a default date/time from existing timestamp
12036 (save-excursion
12037 (org-back-to-heading t)
12038 (setq end (save-excursion (outline-next-heading) (point)))
12039 (when (re-search-forward (if (eq what 'scheduled)
12040 org-scheduled-time-regexp
12041 org-deadline-time-regexp)
12042 end t)
12043 (setq ts (match-string 1)
12044 default-time
12045 (apply 'encode-time (org-parse-time-string ts))
12046 default-input (and ts (org-get-compact-tod ts))))))
12047 (when what
12048 (setq time
12049 (if (and (stringp time)
12050 (string-match "^[-+]+[0-9]" time))
12051 ;; This is a relative time, set the proper date
12052 (apply 'encode-time
12053 (org-read-date-analyze
12054 time default-time (decode-time default-time)))
12055 ;; If necessary, get the time from the user
12056 (or time (org-read-date nil 'to-time nil nil
12057 default-time default-input)))))
12059 (when (and org-insert-labeled-timestamps-at-point
12060 (member what '(scheduled deadline)))
12061 (insert
12062 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12063 (org-insert-time-stamp time org-time-was-given
12064 nil nil nil (list org-end-time-was-given))
12065 (setq what nil))
12066 (save-excursion
12067 (save-restriction
12068 (let (col list elt ts buffer-invisibility-spec)
12069 (org-back-to-heading t)
12070 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12071 (goto-char (match-end 1))
12072 (setq col (current-column))
12073 (goto-char (match-end 0))
12074 (if (eobp) (insert "\n") (forward-char 1))
12075 (when (and (not what)
12076 (not (looking-at
12077 (concat "[ \t]*"
12078 org-keyword-time-not-clock-regexp))))
12079 ;; Nothing to add, nothing to remove...... :-)
12080 (throw 'exit nil))
12081 (if (and (not (looking-at org-outline-regexp))
12082 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12083 "[^\r\n]*"))
12084 (not (equal (match-string 1) org-clock-string)))
12085 (narrow-to-region (match-beginning 0) (match-end 0))
12086 (insert-before-markers "\n")
12087 (backward-char 1)
12088 (narrow-to-region (point) (point))
12089 (and org-adapt-indentation (org-indent-to-column col)))
12090 ;; Check if we have to remove something.
12091 (setq list (cons what remove))
12092 (while list
12093 (setq elt (pop list))
12094 (when (or (and (eq elt 'scheduled)
12095 (re-search-forward org-scheduled-time-regexp nil t))
12096 (and (eq elt 'deadline)
12097 (re-search-forward org-deadline-time-regexp nil t))
12098 (and (eq elt 'closed)
12099 (re-search-forward org-closed-time-regexp nil t)))
12100 (replace-match "")
12101 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12102 (and (looking-at "[ \t]+") (replace-match ""))
12103 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12104 (when what
12105 (insert
12106 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12107 (cond ((eq what 'scheduled) org-scheduled-string)
12108 ((eq what 'deadline) org-deadline-string)
12109 ((eq what 'closed) org-closed-string))
12110 " ")
12111 (setq ts (org-insert-time-stamp
12112 time
12113 (or org-time-was-given
12114 (and (eq what 'closed) org-log-done-with-time))
12115 (eq what 'closed)
12116 nil nil (list org-end-time-was-given)))
12117 (insert
12118 (if (not (or (bolp) (eq (char-before) ?\ )
12119 (memq (char-after) '(32 10))
12120 (eobp))) " " ""))
12121 (end-of-line 1))
12122 (goto-char (point-min))
12123 (widen)
12124 (if (and (looking-at "[ \t]*\n")
12125 (equal (char-before) ?\n))
12126 (delete-region (1- (point)) (point-at-eol)))
12127 ts))))))
12129 (defvar org-log-note-marker (make-marker))
12130 (defvar org-log-note-purpose nil)
12131 (defvar org-log-note-state nil)
12132 (defvar org-log-note-previous-state nil)
12133 (defvar org-log-note-how nil)
12134 (defvar org-log-note-extra nil)
12135 (defvar org-log-note-window-configuration nil)
12136 (defvar org-log-note-return-to (make-marker))
12137 (defvar org-log-note-effective-time nil
12138 "Remembered current time so that dynamically scoped
12139 `org-extend-today-until' affects tha timestamps in state change
12140 log")
12142 (defvar org-log-post-message nil
12143 "Message to be displayed after a log note has been stored.
12144 The auto-repeater uses this.")
12146 (defun org-add-note ()
12147 "Add a note to the current entry.
12148 This is done in the same way as adding a state change note."
12149 (interactive)
12150 (org-add-log-setup 'note nil nil 'findpos nil))
12152 (defvar org-property-end-re)
12153 (defun org-add-log-setup (&optional purpose state prev-state
12154 findpos how extra)
12155 "Set up the post command hook to take a note.
12156 If this is about to TODO state change, the new state is expected in STATE.
12157 When FINDPOS is non-nil, find the correct position for the note in
12158 the current entry. If not, assume that it can be inserted at point.
12159 HOW is an indicator what kind of note should be created.
12160 EXTRA is additional text that will be inserted into the notes buffer."
12161 (let* ((org-log-into-drawer (org-log-into-drawer))
12162 (drawer (cond ((stringp org-log-into-drawer)
12163 org-log-into-drawer)
12164 (org-log-into-drawer "LOGBOOK")
12165 (t nil))))
12166 (save-restriction
12167 (save-excursion
12168 (when findpos
12169 (org-back-to-heading t)
12170 (narrow-to-region (point) (save-excursion
12171 (outline-next-heading) (point)))
12172 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12173 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12174 "[^\r\n]*\\)?"))
12175 (goto-char (match-end 0))
12176 (cond
12177 (drawer
12178 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12179 nil t)
12180 (progn
12181 (goto-char (match-end 0))
12182 (or org-log-states-order-reversed
12183 (and (re-search-forward org-property-end-re nil t)
12184 (goto-char (1- (match-beginning 0))))))
12185 (insert "\n:" drawer ":\n:END:")
12186 (beginning-of-line 0)
12187 (org-indent-line-function)
12188 (beginning-of-line 2)
12189 (org-indent-line-function)
12190 (end-of-line 0)))
12191 ((and org-log-state-notes-insert-after-drawers
12192 (save-excursion
12193 (forward-line) (looking-at org-drawer-regexp)))
12194 (forward-line)
12195 (while (looking-at org-drawer-regexp)
12196 (goto-char (match-end 0))
12197 (re-search-forward org-property-end-re (point-max) t)
12198 (forward-line))
12199 (forward-line -1)))
12200 (unless org-log-states-order-reversed
12201 (and (= (char-after) ?\n) (forward-char 1))
12202 (org-skip-over-state-notes)
12203 (skip-chars-backward " \t\n\r")))
12204 (move-marker org-log-note-marker (point))
12205 (setq org-log-note-purpose purpose
12206 org-log-note-state state
12207 org-log-note-previous-state prev-state
12208 org-log-note-how how
12209 org-log-note-extra extra
12210 org-log-note-effective-time (org-current-effective-time))
12211 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12213 (defun org-skip-over-state-notes ()
12214 "Skip past the list of State notes in an entry."
12215 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12216 (when (ignore-errors (goto-char (org-in-item-p)))
12217 (let* ((struct (org-list-struct))
12218 (prevs (org-list-prevs-alist struct)))
12219 (while (looking-at "[ \t]*- State")
12220 (goto-char (or (org-list-get-next-item (point) struct prevs)
12221 (org-list-get-item-end (point) struct)))))))
12223 (defun org-add-log-note (&optional purpose)
12224 "Pop up a window for taking a note, and add this note later at point."
12225 (remove-hook 'post-command-hook 'org-add-log-note)
12226 (setq org-log-note-window-configuration (current-window-configuration))
12227 (delete-other-windows)
12228 (move-marker org-log-note-return-to (point))
12229 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12230 (goto-char org-log-note-marker)
12231 (org-switch-to-buffer-other-window "*Org Note*")
12232 (erase-buffer)
12233 (if (memq org-log-note-how '(time state))
12234 (let (current-prefix-arg) (org-store-log-note))
12235 (let ((org-inhibit-startup t)) (org-mode))
12236 (insert (format "# Insert note for %s.
12237 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12238 (cond
12239 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12240 ((eq org-log-note-purpose 'done) "closed todo item")
12241 ((eq org-log-note-purpose 'state)
12242 (format "state change from \"%s\" to \"%s\""
12243 (or org-log-note-previous-state "")
12244 (or org-log-note-state "")))
12245 ((eq org-log-note-purpose 'reschedule)
12246 "rescheduling")
12247 ((eq org-log-note-purpose 'delschedule)
12248 "no longer scheduled")
12249 ((eq org-log-note-purpose 'redeadline)
12250 "changing deadline")
12251 ((eq org-log-note-purpose 'deldeadline)
12252 "removing deadline")
12253 ((eq org-log-note-purpose 'refile)
12254 "refiling")
12255 ((eq org-log-note-purpose 'note)
12256 "this entry")
12257 (t (error "This should not happen")))))
12258 (if org-log-note-extra (insert org-log-note-extra))
12259 (org-set-local 'org-finish-function 'org-store-log-note)
12260 (run-hooks 'org-log-buffer-setup-hook)))
12262 (defvar org-note-abort nil) ; dynamically scoped
12263 (defun org-store-log-note ()
12264 "Finish taking a log note, and insert it to where it belongs."
12265 (let ((txt (buffer-string))
12266 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12267 lines ind bul)
12268 (kill-buffer (current-buffer))
12269 (while (string-match "\\`#.*\n[ \t\n]*" txt)
12270 (setq txt (replace-match "" t t txt)))
12271 (if (string-match "\\s-+\\'" txt)
12272 (setq txt (replace-match "" t t txt)))
12273 (setq lines (org-split-string txt "\n"))
12274 (when (and note (string-match "\\S-" note))
12275 (setq note
12276 (org-replace-escapes
12277 note
12278 (list (cons "%u" (user-login-name))
12279 (cons "%U" user-full-name)
12280 (cons "%t" (format-time-string
12281 (org-time-stamp-format 'long 'inactive)
12282 org-log-note-effective-time))
12283 (cons "%T" (format-time-string
12284 (org-time-stamp-format 'long nil)
12285 org-log-note-effective-time))
12286 (cons "%d" (format-time-string
12287 (org-time-stamp-format nil 'inactive)
12288 org-log-note-effective-time))
12289 (cons "%D" (format-time-string
12290 (org-time-stamp-format nil nil)
12291 org-log-note-effective-time))
12292 (cons "%s" (if org-log-note-state
12293 (concat "\"" org-log-note-state "\"")
12294 ""))
12295 (cons "%S" (if org-log-note-previous-state
12296 (concat "\"" org-log-note-previous-state "\"")
12297 "\"\"")))))
12298 (if lines (setq note (concat note " \\\\")))
12299 (push note lines))
12300 (when (or current-prefix-arg org-note-abort)
12301 (when org-log-into-drawer
12302 (org-remove-empty-drawer-at
12303 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12304 org-log-note-marker))
12305 (setq lines nil))
12306 (when lines
12307 (with-current-buffer (marker-buffer org-log-note-marker)
12308 (save-excursion
12309 (goto-char org-log-note-marker)
12310 (move-marker org-log-note-marker nil)
12311 (end-of-line 1)
12312 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12313 (setq ind (save-excursion
12314 (if (ignore-errors (goto-char (org-in-item-p)))
12315 (let ((struct (org-list-struct)))
12316 (org-list-get-ind
12317 (org-list-get-top-point struct) struct))
12318 (skip-chars-backward " \r\t\n")
12319 (cond
12320 ((and (org-at-heading-p)
12321 org-adapt-indentation)
12322 (1+ (org-current-level)))
12323 ((org-at-heading-p) 0)
12324 (t (org-get-indentation))))))
12325 (setq bul (org-list-bullet-string "-"))
12326 (org-indent-line-to ind)
12327 (insert bul (pop lines))
12328 (let ((ind-body (+ (length bul) ind)))
12329 (while lines
12330 (insert "\n")
12331 (org-indent-line-to ind-body)
12332 (insert (pop lines))))
12333 (message "Note stored")
12334 (org-back-to-heading t)
12335 (org-cycle-hide-drawers 'children)))))
12336 (set-window-configuration org-log-note-window-configuration)
12337 (with-current-buffer (marker-buffer org-log-note-return-to)
12338 (goto-char org-log-note-return-to))
12339 (move-marker org-log-note-return-to nil)
12340 (and org-log-post-message (message "%s" org-log-post-message)))
12342 (defun org-remove-empty-drawer-at (drawer pos)
12343 "Remove an empty drawer DRAWER at position POS.
12344 POS may also be a marker."
12345 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12346 (save-excursion
12347 (save-restriction
12348 (widen)
12349 (goto-char pos)
12350 (if (org-in-regexp
12351 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12352 (replace-match ""))))))
12354 (defun org-sparse-tree (&optional arg)
12355 "Create a sparse tree, prompt for the details.
12356 This command can create sparse trees. You first need to select the type
12357 of match used to create the tree:
12359 t Show all TODO entries.
12360 T Show entries with a specific TODO keyword.
12361 m Show entries selected by a tags/property match.
12362 p Enter a property name and its value (both with completion on existing
12363 names/values) and show entries with that property.
12364 r Show entries matching a regular expression (`/' can be used as well)
12365 d Show deadlines due within `org-deadline-warning-days'.
12366 b Show deadlines and scheduled items before a date.
12367 a Show deadlines and scheduled items after a date."
12368 (interactive "P")
12369 (let (ans kwd value)
12370 (message "Sparse tree: [r]egexp [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty\n [d]eadlines [b]efore-date [a]fter-date")
12371 (setq ans (read-char-exclusive))
12372 (cond
12373 ((equal ans ?d)
12374 (call-interactively 'org-check-deadlines))
12375 ((equal ans ?b)
12376 (call-interactively 'org-check-before-date))
12377 ((equal ans ?a)
12378 (call-interactively 'org-check-after-date))
12379 ((equal ans ?t)
12380 (org-show-todo-tree nil))
12381 ((equal ans ?T)
12382 (org-show-todo-tree '(4)))
12383 ((member ans '(?T ?m))
12384 (call-interactively 'org-match-sparse-tree))
12385 ((member ans '(?p ?P))
12386 (setq kwd (org-icompleting-read "Property: "
12387 (mapcar 'list (org-buffer-property-keys))))
12388 (setq value (org-icompleting-read "Value: "
12389 (mapcar 'list (org-property-values kwd))))
12390 (unless (string-match "\\`{.*}\\'" value)
12391 (setq value (concat "\"" value "\"")))
12392 (org-match-sparse-tree arg (concat kwd "=" value)))
12393 ((member ans '(?r ?R ?/))
12394 (call-interactively 'org-occur))
12395 (t (error "No such sparse tree command \"%c\"" ans)))))
12397 (defvar org-occur-highlights nil
12398 "List of overlays used for occur matches.")
12399 (make-variable-buffer-local 'org-occur-highlights)
12400 (defvar org-occur-parameters nil
12401 "Parameters of the active org-occur calls.
12402 This is a list, each call to org-occur pushes as cons cell,
12403 containing the regular expression and the callback, onto the list.
12404 The list can contain several entries if `org-occur' has been called
12405 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12406 will only contain one set of parameters. When the highlights are
12407 removed (for example with `C-c C-c', or with the next edit (depending
12408 on `org-remove-highlights-with-change'), this variable is emptied
12409 as well.")
12410 (make-variable-buffer-local 'org-occur-parameters)
12412 (defun org-occur (regexp &optional keep-previous callback)
12413 "Make a compact tree which shows all matches of REGEXP.
12414 The tree will show the lines where the regexp matches, and all higher
12415 headlines above the match. It will also show the heading after the match,
12416 to make sure editing the matching entry is easy.
12417 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12418 call to `org-occur' will be kept, to allow stacking of calls to this
12419 command.
12420 If CALLBACK is non-nil, it is a function which is called to confirm
12421 that the match should indeed be shown."
12422 (interactive "sRegexp: \nP")
12423 (when (equal regexp "")
12424 (error "Regexp cannot be empty"))
12425 (unless keep-previous
12426 (org-remove-occur-highlights nil nil t))
12427 (push (cons regexp callback) org-occur-parameters)
12428 (let ((cnt 0))
12429 (save-excursion
12430 (goto-char (point-min))
12431 (if (or (not keep-previous) ; do not want to keep
12432 (not org-occur-highlights)) ; no previous matches
12433 ;; hide everything
12434 (org-overview))
12435 (while (re-search-forward regexp nil t)
12436 (when (or (not callback)
12437 (save-match-data (funcall callback)))
12438 (setq cnt (1+ cnt))
12439 (when org-highlight-sparse-tree-matches
12440 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12441 (org-show-context 'occur-tree))))
12442 (when org-remove-highlights-with-change
12443 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12444 nil 'local))
12445 (unless org-sparse-tree-open-archived-trees
12446 (org-hide-archived-subtrees (point-min) (point-max)))
12447 (run-hooks 'org-occur-hook)
12448 (if (org-called-interactively-p 'interactive)
12449 (message "%d match(es) for regexp %s" cnt regexp))
12450 cnt))
12452 (defun org-occur-next-match (&optional n reset)
12453 "Function for `next-error-function' to find sparse tree matches.
12454 N is the number of matches to move, when negative move backwards.
12455 RESET is entirely ignored - this function always goes back to the
12456 starting point when no match is found."
12457 (let* ((limit (if (< n 0) (point-min) (point-max)))
12458 (search-func (if (< n 0)
12459 'previous-single-char-property-change
12460 'next-single-char-property-change))
12461 (n (abs n))
12462 (pos (point))
12464 (catch 'exit
12465 (while (setq p1 (funcall search-func (point) 'org-type))
12466 (when (equal p1 limit)
12467 (goto-char pos)
12468 (error "No more matches"))
12469 (when (equal (get-char-property p1 'org-type) 'org-occur)
12470 (setq n (1- n))
12471 (when (= n 0)
12472 (goto-char p1)
12473 (throw 'exit (point))))
12474 (goto-char p1))
12475 (goto-char p1)
12476 (error "No more matches"))))
12478 (defun org-show-context (&optional key)
12479 "Make sure point and context are visible.
12480 How much context is shown depends upon the variables
12481 `org-show-hierarchy-above', `org-show-following-heading'. and
12482 `org-show-siblings'."
12483 (let ((heading-p (org-on-heading-p t))
12484 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12485 (following-p (org-get-alist-option org-show-following-heading key))
12486 (entry-p (org-get-alist-option org-show-entry-below key))
12487 (siblings-p (org-get-alist-option org-show-siblings key)))
12488 (catch 'exit
12489 ;; Show heading or entry text
12490 (if (and heading-p (not entry-p))
12491 (org-flag-heading nil) ; only show the heading
12492 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12493 (org-show-hidden-entry))) ; show entire entry
12494 (when following-p
12495 ;; Show next sibling, or heading below text
12496 (save-excursion
12497 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12498 (org-flag-heading nil))))
12499 (when siblings-p (org-show-siblings))
12500 (when hierarchy-p
12501 ;; show all higher headings, possibly with siblings
12502 (save-excursion
12503 (while (and (condition-case nil
12504 (progn (org-up-heading-all 1) t)
12505 (error nil))
12506 (not (bobp)))
12507 (org-flag-heading nil)
12508 (when siblings-p (org-show-siblings))))))))
12510 (defvar org-reveal-start-hook nil
12511 "Hook run before revealing a location.")
12513 (defun org-reveal (&optional siblings)
12514 "Show current entry, hierarchy above it, and the following headline.
12515 This can be used to show a consistent set of context around locations
12516 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12517 not t for the search context.
12519 With optional argument SIBLINGS, on each level of the hierarchy all
12520 siblings are shown. This repairs the tree structure to what it would
12521 look like when opened with hierarchical calls to `org-cycle'.
12522 With double optional argument \\[universal-argument] \\[universal-argument], \
12523 go to the parent and show the
12524 entire tree."
12525 (interactive "P")
12526 (run-hooks 'org-reveal-start-hook)
12527 (let ((org-show-hierarchy-above t)
12528 (org-show-following-heading t)
12529 (org-show-siblings (if siblings t org-show-siblings)))
12530 (org-show-context nil))
12531 (when (equal siblings '(16))
12532 (save-excursion
12533 (when (org-up-heading-safe)
12534 (org-show-subtree)
12535 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12537 (defun org-highlight-new-match (beg end)
12538 "Highlight from BEG to END and mark the highlight is an occur headline."
12539 (let ((ov (make-overlay beg end)))
12540 (overlay-put ov 'face 'secondary-selection)
12541 (overlay-put ov 'org-type 'org-occur)
12542 (push ov org-occur-highlights)))
12544 (defun org-remove-occur-highlights (&optional beg end noremove)
12545 "Remove the occur highlights from the buffer.
12546 BEG and END are ignored. If NOREMOVE is nil, remove this function
12547 from the `before-change-functions' in the current buffer."
12548 (interactive)
12549 (unless org-inhibit-highlight-removal
12550 (mapc 'delete-overlay org-occur-highlights)
12551 (setq org-occur-highlights nil)
12552 (setq org-occur-parameters nil)
12553 (unless noremove
12554 (remove-hook 'before-change-functions
12555 'org-remove-occur-highlights 'local))))
12557 ;;;; Priorities
12559 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12560 "Regular expression matching the priority indicator.")
12562 (defvar org-remove-priority-next-time nil)
12564 (defun org-priority-up ()
12565 "Increase the priority of the current item."
12566 (interactive)
12567 (org-priority 'up))
12569 (defun org-priority-down ()
12570 "Decrease the priority of the current item."
12571 (interactive)
12572 (org-priority 'down))
12574 (defun org-priority (&optional action)
12575 "Change the priority of an item by ARG.
12576 ACTION can be `set', `up', `down', or a character."
12577 (interactive)
12578 (unless org-enable-priority-commands
12579 (error "Priority commands are disabled"))
12580 (setq action (or action 'set))
12581 (let (current new news have remove)
12582 (save-excursion
12583 (org-back-to-heading t)
12584 (if (looking-at org-priority-regexp)
12585 (setq current (string-to-char (match-string 2))
12586 have t))
12587 (cond
12588 ((eq action 'remove)
12589 (setq remove t new ?\ ))
12590 ((or (eq action 'set)
12591 (if (featurep 'xemacs) (characterp action) (integerp action)))
12592 (if (not (eq action 'set))
12593 (setq new action)
12594 (message "Priority %c-%c, SPC to remove: "
12595 org-highest-priority org-lowest-priority)
12596 (save-match-data
12597 (setq new (read-char-exclusive))))
12598 (if (and (= (upcase org-highest-priority) org-highest-priority)
12599 (= (upcase org-lowest-priority) org-lowest-priority))
12600 (setq new (upcase new)))
12601 (cond ((equal new ?\ ) (setq remove t))
12602 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12603 (error "Priority must be between `%c' and `%c'"
12604 org-highest-priority org-lowest-priority))))
12605 ((eq action 'up)
12606 (setq new (if have
12607 (1- current) ; normal cycling
12608 ;; last priority was empty
12609 (if (eq last-command this-command)
12610 org-lowest-priority ; wrap around empty to lowest
12611 ;; default
12612 (if org-priority-start-cycle-with-default
12613 org-default-priority
12614 (1- org-default-priority))))))
12615 ((eq action 'down)
12616 (setq new (if have
12617 (1+ current) ; normal cycling
12618 ;; last priority was empty
12619 (if (eq last-command this-command)
12620 org-highest-priority ; wrap around empty to highest
12621 ;; default
12622 (if org-priority-start-cycle-with-default
12623 org-default-priority
12624 (1+ org-default-priority))))))
12625 (t (error "Invalid action")))
12626 (if (or (< (upcase new) org-highest-priority)
12627 (> (upcase new) org-lowest-priority))
12628 (if (and (memq action '(up down))
12629 (not have) (not (eq last-command this-command)))
12630 ;; `new' is from default priority
12631 (error
12632 "The default can not be set, see `org-default-priority' why")
12633 ;; normal cycling: `new' is beyond highest/lowest priority
12634 ;; and is wrapped around to the empty priority
12635 (setq remove t)))
12636 (setq news (format "%c" new))
12637 (if have
12638 (if remove
12639 (replace-match "" t t nil 1)
12640 (replace-match news t t nil 2))
12641 (if remove
12642 (error "No priority cookie found in line")
12643 (let ((case-fold-search nil))
12644 (looking-at org-todo-line-regexp))
12645 (if (match-end 2)
12646 (progn
12647 (goto-char (match-end 2))
12648 (insert " [#" news "]"))
12649 (goto-char (match-beginning 3))
12650 (insert "[#" news "] "))))
12651 (org-preserve-lc (org-set-tags nil 'align)))
12652 (if remove
12653 (message "Priority removed")
12654 (message "Priority of current item set to %s" news))))
12656 (defun org-get-priority (s)
12657 "Find priority cookie and return priority."
12658 (if (functionp org-get-priority-function)
12659 (funcall org-get-priority-function)
12660 (save-match-data
12661 (if (not (string-match org-priority-regexp s))
12662 (* 1000 (- org-lowest-priority org-default-priority))
12663 (* 1000 (- org-lowest-priority
12664 (string-to-char (match-string 2 s))))))))
12666 ;;;; Tags
12668 (defvar org-agenda-archives-mode)
12669 (defvar org-map-continue-from nil
12670 "Position from where mapping should continue.
12671 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
12673 (defvar org-scanner-tags nil
12674 "The current tag list while the tags scanner is running.")
12675 (defvar org-trust-scanner-tags nil
12676 "Should `org-get-tags-at' use the tags for the scanner.
12677 This is for internal dynamical scoping only.
12678 When this is non-nil, the function `org-get-tags-at' will return the value
12679 of `org-scanner-tags' instead of building the list by itself. This
12680 can lead to large speed-ups when the tags scanner is used in a file with
12681 many entries, and when the list of tags is retrieved, for example to
12682 obtain a list of properties. Building the tags list for each entry in such
12683 a file becomes an N^2 operation - but with this variable set, it scales
12684 as N.")
12686 (defun org-scan-tags (action matcher &optional todo-only)
12687 "Scan headline tags with inheritance and produce output ACTION.
12689 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12690 or `agenda' to produce an entry list for an agenda view. It can also be
12691 a Lisp form or a function that should be called at each matched headline, in
12692 this case the return value is a list of all return values from these calls.
12694 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12695 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12696 only lines with a TODO keyword are included in the output."
12697 (require 'org-agenda)
12698 (let* ((re (concat "^" org-outline-regexp " *\\(\\<\\("
12699 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12700 (org-re
12701 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
12702 (props (list 'face 'default
12703 'done-face 'org-agenda-done
12704 'undone-face 'default
12705 'mouse-face 'highlight
12706 'org-not-done-regexp org-not-done-regexp
12707 'org-todo-regexp org-todo-regexp
12708 'org-complex-heading-regexp org-complex-heading-regexp
12709 'help-echo
12710 (format "mouse-2 or RET jump to org file %s"
12711 (abbreviate-file-name
12712 (or (buffer-file-name (buffer-base-buffer))
12713 (buffer-name (buffer-base-buffer)))))))
12714 (case-fold-search nil)
12715 (org-map-continue-from nil)
12716 lspos tags tags-list
12717 (tags-alist (list (cons 0 org-file-tags)))
12718 (llast 0) rtn rtn1 level category i txt
12719 todo marker entry priority)
12720 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12721 (setq action (list 'lambda nil action)))
12722 (save-excursion
12723 (goto-char (point-min))
12724 (when (eq action 'sparse-tree)
12725 (org-overview)
12726 (org-remove-occur-highlights))
12727 (while (re-search-forward re nil t)
12728 (catch :skip
12729 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12730 tags (if (match-end 4) (org-match-string-no-properties 4)))
12731 (goto-char (setq lspos (match-beginning 0)))
12732 (setq level (org-reduced-level (funcall outline-level))
12733 category (org-get-category))
12734 (setq i llast llast level)
12735 ;; remove tag lists from same and sublevels
12736 (while (>= i level)
12737 (when (setq entry (assoc i tags-alist))
12738 (setq tags-alist (delete entry tags-alist)))
12739 (setq i (1- i)))
12740 ;; add the next tags
12741 (when tags
12742 (setq tags (org-split-string tags ":")
12743 tags-alist
12744 (cons (cons level tags) tags-alist)))
12745 ;; compile tags for current headline
12746 (setq tags-list
12747 (if org-use-tag-inheritance
12748 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12749 tags)
12750 org-scanner-tags tags-list)
12751 (when org-use-tag-inheritance
12752 (setcdr (car tags-alist)
12753 (mapcar (lambda (x)
12754 (setq x (copy-sequence x))
12755 (org-add-prop-inherited x))
12756 (cdar tags-alist))))
12757 (when (and tags org-use-tag-inheritance
12758 (or (not (eq t org-use-tag-inheritance))
12759 org-tags-exclude-from-inheritance))
12760 ;; selective inheritance, remove uninherited ones
12761 (setcdr (car tags-alist)
12762 (org-remove-uninherited-tags (cdar tags-alist))))
12763 (when (and
12765 ;; eval matcher only when the todo condition is OK
12766 (and (or (not todo-only) (member todo org-not-done-keywords))
12767 (let ((case-fold-search t)) (eval matcher)))
12769 ;; Call the skipper, but return t if it does not skip,
12770 ;; so that the `and' form continues evaluating
12771 (progn
12772 (unless (eq action 'sparse-tree) (org-agenda-skip))
12775 ;; Check if timestamps are deselecting this entry
12776 (or (not todo-only)
12777 (and (member todo org-not-done-keywords)
12778 (or (not org-agenda-tags-todo-honor-ignore-options)
12779 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
12781 ;; Extra check for the archive tag
12782 ;; FIXME: Does the skipper already do this????
12784 (not (member org-archive-tag tags-list))
12785 ;; we have an archive tag, should we use this anyway?
12786 (or (not org-agenda-skip-archived-trees)
12787 (and (eq action 'agenda) org-agenda-archives-mode))))
12789 ;; select this headline
12791 (cond
12792 ((eq action 'sparse-tree)
12793 (and org-highlight-sparse-tree-matches
12794 (org-get-heading) (match-end 0)
12795 (org-highlight-new-match
12796 (match-beginning 0) (match-beginning 1)))
12797 (org-show-context 'tags-tree))
12798 ((eq action 'agenda)
12799 (setq txt (org-agenda-format-item
12801 (concat
12802 (if (eq org-tags-match-list-sublevels 'indented)
12803 (make-string (1- level) ?.) "")
12804 (org-get-heading))
12805 category
12806 tags-list
12808 priority (org-get-priority txt))
12809 (goto-char lspos)
12810 (setq marker (org-agenda-new-marker))
12811 (org-add-props txt props
12812 'org-marker marker 'org-hd-marker marker 'org-category category
12813 'todo-state todo
12814 'priority priority 'type "tagsmatch")
12815 (push txt rtn))
12816 ((functionp action)
12817 (setq org-map-continue-from nil)
12818 (save-excursion
12819 (setq rtn1 (funcall action))
12820 (push rtn1 rtn)))
12821 (t (error "Invalid action")))
12823 ;; if we are to skip sublevels, jump to end of subtree
12824 (unless org-tags-match-list-sublevels
12825 (org-end-of-subtree t)
12826 (backward-char 1))))
12827 ;; Get the correct position from where to continue
12828 (if org-map-continue-from
12829 (goto-char org-map-continue-from)
12830 (and (= (point) lspos) (end-of-line 1)))))
12831 (when (and (eq action 'sparse-tree)
12832 (not org-sparse-tree-open-archived-trees))
12833 (org-hide-archived-subtrees (point-min) (point-max)))
12834 (nreverse rtn)))
12836 (defun org-remove-uninherited-tags (tags)
12837 "Remove all tags that are not inherited from the list TAGS."
12838 (cond
12839 ((eq org-use-tag-inheritance t)
12840 (if org-tags-exclude-from-inheritance
12841 (org-delete-all org-tags-exclude-from-inheritance tags)
12842 tags))
12843 ((not org-use-tag-inheritance) nil)
12844 ((stringp org-use-tag-inheritance)
12845 (delq nil (mapcar
12846 (lambda (x)
12847 (if (and (string-match org-use-tag-inheritance x)
12848 (not (member x org-tags-exclude-from-inheritance)))
12849 x nil))
12850 tags)))
12851 ((listp org-use-tag-inheritance)
12852 (delq nil (mapcar
12853 (lambda (x)
12854 (if (member x org-use-tag-inheritance) x nil))
12855 tags)))))
12857 (defvar todo-only) ;; dynamically scoped
12859 (defun org-match-sparse-tree (&optional todo-only match)
12860 "Create a sparse tree according to tags string MATCH.
12861 MATCH can contain positive and negative selection of tags, like
12862 \"+WORK+URGENT-WITHBOSS\".
12863 If optional argument TODO-ONLY is non-nil, only select lines that are
12864 also TODO lines."
12865 (interactive "P")
12866 (org-prepare-agenda-buffers (list (current-buffer)))
12867 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
12869 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
12871 (defvar org-cached-props nil)
12872 (defun org-cached-entry-get (pom property)
12873 (if (or (eq t org-use-property-inheritance)
12874 (and (stringp org-use-property-inheritance)
12875 (string-match org-use-property-inheritance property))
12876 (and (listp org-use-property-inheritance)
12877 (member property org-use-property-inheritance)))
12878 ;; Caching is not possible, check it directly
12879 (org-entry-get pom property 'inherit)
12880 ;; Get all properties, so that we can do complicated checks easily
12881 (cdr (assoc property (or org-cached-props
12882 (setq org-cached-props
12883 (org-entry-properties pom)))))))
12885 (defun org-global-tags-completion-table (&optional files)
12886 "Return the list of all tags in all agenda buffer/files.
12887 Optional FILES argument is a list of files to which can be used
12888 instead of the agenda files."
12889 (save-excursion
12890 (org-uniquify
12891 (delq nil
12892 (apply 'append
12893 (mapcar
12894 (lambda (file)
12895 (set-buffer (find-file-noselect file))
12896 (append (org-get-buffer-tags)
12897 (mapcar (lambda (x) (if (stringp (car-safe x))
12898 (list (car-safe x)) nil))
12899 org-tag-alist)))
12900 (if (and files (car files))
12901 files
12902 (org-agenda-files))))))))
12904 (defun org-make-tags-matcher (match)
12905 "Create the TAGS/TODO matcher form for the selection string MATCH."
12906 ;; todo-only is scoped dynamically into this function, and the function
12907 ;; may change it if the matcher asks for it.
12908 (unless match
12909 ;; Get a new match request, with completion
12910 (let ((org-last-tags-completion-table
12911 (org-global-tags-completion-table)))
12912 (setq match (org-completing-read-no-i
12913 "Match: " 'org-tags-completion-function nil nil nil
12914 'org-tags-history))))
12916 ;; Parse the string and create a lisp form
12917 (let ((match0 match)
12918 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
12919 minus tag mm
12920 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
12921 orterms term orlist re-p str-p level-p level-op time-p
12922 prop-p pn pv po gv rest)
12923 (if (string-match "/+" match)
12924 ;; match contains also a todo-matching request
12925 (progn
12926 (setq tagsmatch (substring match 0 (match-beginning 0))
12927 todomatch (substring match (match-end 0)))
12928 (if (string-match "^!" todomatch)
12929 (setq todo-only t todomatch (substring todomatch 1)))
12930 (if (string-match "^\\s-*$" todomatch)
12931 (setq todomatch nil)))
12932 ;; only matching tags
12933 (setq tagsmatch match todomatch nil))
12935 ;; Make the tags matcher
12936 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
12937 (setq tagsmatcher t)
12938 (setq orterms (org-split-string tagsmatch "|") orlist nil)
12939 (while (setq term (pop orterms))
12940 (while (and (equal (substring term -1) "\\") orterms)
12941 (setq term (concat term "|" (pop orterms)))) ; repair bad split
12942 (while (string-match re term)
12943 (setq rest (substring term (match-end 0))
12944 minus (and (match-end 1)
12945 (equal (match-string 1 term) "-"))
12946 tag (save-match-data (replace-regexp-in-string
12947 "\\\\-" "-"
12948 (match-string 2 term)))
12949 re-p (equal (string-to-char tag) ?{)
12950 level-p (match-end 4)
12951 prop-p (match-end 5)
12952 mm (cond
12953 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
12954 (level-p
12955 (setq level-op (org-op-to-function (match-string 3 term)))
12956 `(,level-op level ,(string-to-number
12957 (match-string 4 term))))
12958 (prop-p
12959 (setq pn (match-string 5 term)
12960 po (match-string 6 term)
12961 pv (match-string 7 term)
12962 re-p (equal (string-to-char pv) ?{)
12963 str-p (equal (string-to-char pv) ?\")
12964 time-p (save-match-data
12965 (string-match "^\"[[<].*[]>]\"$" pv))
12966 pv (if (or re-p str-p) (substring pv 1 -1) pv))
12967 (if time-p (setq pv (org-matcher-time pv)))
12968 (setq po (org-op-to-function po (if time-p 'time str-p)))
12969 (cond
12970 ((equal pn "CATEGORY")
12971 (setq gv '(get-text-property (point) 'org-category)))
12972 ((equal pn "TODO")
12973 (setq gv 'todo))
12975 (setq gv `(org-cached-entry-get nil ,pn))))
12976 (if re-p
12977 (if (eq po 'org<>)
12978 `(not (string-match ,pv (or ,gv "")))
12979 `(string-match ,pv (or ,gv "")))
12980 (if str-p
12981 `(,po (or ,gv "") ,pv)
12982 `(,po (string-to-number (or ,gv ""))
12983 ,(string-to-number pv) ))))
12984 (t `(member ,tag tags-list)))
12985 mm (if minus (list 'not mm) mm)
12986 term rest)
12987 (push mm tagsmatcher))
12988 (push (if (> (length tagsmatcher) 1)
12989 (cons 'and tagsmatcher)
12990 (car tagsmatcher))
12991 orlist)
12992 (setq tagsmatcher nil))
12993 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
12994 (setq tagsmatcher
12995 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
12996 ;; Make the todo matcher
12997 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
12998 (setq todomatcher t)
12999 (setq orterms (org-split-string todomatch "|") orlist nil)
13000 (while (setq term (pop orterms))
13001 (while (string-match re term)
13002 (setq minus (and (match-end 1)
13003 (equal (match-string 1 term) "-"))
13004 kwd (match-string 2 term)
13005 re-p (equal (string-to-char kwd) ?{)
13006 term (substring term (match-end 0))
13007 mm (if re-p
13008 `(string-match ,(substring kwd 1 -1) todo)
13009 (list 'equal 'todo kwd))
13010 mm (if minus (list 'not mm) mm))
13011 (push mm todomatcher))
13012 (push (if (> (length todomatcher) 1)
13013 (cons 'and todomatcher)
13014 (car todomatcher))
13015 orlist)
13016 (setq todomatcher nil))
13017 (setq todomatcher (if (> (length orlist) 1)
13018 (cons 'or orlist) (car orlist))))
13020 ;; Return the string and lisp forms of the matcher
13021 (setq matcher (if todomatcher
13022 (list 'and tagsmatcher todomatcher)
13023 tagsmatcher))
13024 (cons match0 matcher)))
13026 (defun org-op-to-function (op &optional stringp)
13027 "Turn an operator into the appropriate function."
13028 (setq op
13029 (cond
13030 ((equal op "<" ) '(< string< org-time<))
13031 ((equal op ">" ) '(> org-string> org-time>))
13032 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13033 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13034 ((member op '("=" "==")) '(= string= org-time=))
13035 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13036 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13038 (defun org<> (a b) (not (= a b)))
13039 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13040 (defun org-string>= (a b) (not (string< a b)))
13041 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13042 (defun org-string<> (a b) (not (string= a b)))
13043 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13044 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13045 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13046 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13047 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13048 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13049 (defun org-2ft (s)
13050 "Convert S to a floating point time.
13051 If S is already a number, just return it. If it is a string, parse
13052 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13053 (cond
13054 ((numberp s) s)
13055 ((stringp s)
13056 (condition-case nil
13057 (float-time (apply 'encode-time (org-parse-time-string s)))
13058 (error 0.)))
13059 (t 0.)))
13061 (defun org-time-today ()
13062 "Time in seconds today at 0:00.
13063 Returns the float number of seconds since the beginning of the
13064 epoch to the beginning of today (00:00)."
13065 (float-time (apply 'encode-time
13066 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13068 (defun org-matcher-time (s)
13069 "Interpret a time comparison value."
13070 (save-match-data
13071 (cond
13072 ((string= s "<now>") (float-time))
13073 ((string= s "<today>") (org-time-today))
13074 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13075 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13076 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
13077 (+ (org-time-today)
13078 (* (string-to-number (match-string 1 s))
13079 (cdr (assoc (match-string 2 s)
13080 '(("d" . 86400.0) ("w" . 604800.0)
13081 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13082 (t (org-2ft s)))))
13084 (defun org-match-any-p (re list)
13085 "Does re match any element of list?"
13086 (setq list (mapcar (lambda (x) (string-match re x)) list))
13087 (delq nil list))
13089 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13090 (defvar org-tags-overlay (make-overlay 1 1))
13091 (org-detach-overlay org-tags-overlay)
13093 (defun org-get-local-tags-at (&optional pos)
13094 "Get a list of tags defined in the current headline."
13095 (org-get-tags-at pos 'local))
13097 (defun org-get-local-tags ()
13098 "Get a list of tags defined in the current headline."
13099 (org-get-tags-at nil 'local))
13101 (defun org-get-tags-at (&optional pos local)
13102 "Get a list of all headline tags applicable at POS.
13103 POS defaults to point. If tags are inherited, the list contains
13104 the targets in the same sequence as the headlines appear, i.e.
13105 the tags of the current headline come last.
13106 When LOCAL is non-nil, only return tags from the current headline,
13107 ignore inherited ones."
13108 (interactive)
13109 (if (and org-trust-scanner-tags
13110 (or (not pos) (equal pos (point)))
13111 (not local))
13112 org-scanner-tags
13113 (let (tags ltags lastpos parent)
13114 (save-excursion
13115 (save-restriction
13116 (widen)
13117 (goto-char (or pos (point)))
13118 (save-match-data
13119 (catch 'done
13120 (condition-case nil
13121 (progn
13122 (org-back-to-heading t)
13123 (while (not (equal lastpos (point)))
13124 (setq lastpos (point))
13125 (when (looking-at
13126 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13127 (setq ltags (org-split-string
13128 (org-match-string-no-properties 1) ":"))
13129 (when parent
13130 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13131 (setq tags (append
13132 (if parent
13133 (org-remove-uninherited-tags ltags)
13134 ltags)
13135 tags)))
13136 (or org-use-tag-inheritance (throw 'done t))
13137 (if local (throw 'done t))
13138 (or (org-up-heading-safe) (error nil))
13139 (setq parent t)))
13140 (error nil)))))
13141 (if local
13142 tags
13143 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13145 (defun org-add-prop-inherited (s)
13146 (add-text-properties 0 (length s) '(inherited t) s)
13149 (defun org-toggle-tag (tag &optional onoff)
13150 "Toggle the tag TAG for the current line.
13151 If ONOFF is `on' or `off', don't toggle but set to this state."
13152 (let (res current)
13153 (save-excursion
13154 (org-back-to-heading t)
13155 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13156 (point-at-eol) t)
13157 (progn
13158 (setq current (match-string 1))
13159 (replace-match ""))
13160 (setq current ""))
13161 (setq current (nreverse (org-split-string current ":")))
13162 (cond
13163 ((eq onoff 'on)
13164 (setq res t)
13165 (or (member tag current) (push tag current)))
13166 ((eq onoff 'off)
13167 (or (not (member tag current)) (setq current (delete tag current))))
13168 (t (if (member tag current)
13169 (setq current (delete tag current))
13170 (setq res t)
13171 (push tag current))))
13172 (end-of-line 1)
13173 (if current
13174 (progn
13175 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13176 (org-set-tags nil t))
13177 (delete-horizontal-space))
13178 (run-hooks 'org-after-tags-change-hook))
13179 res))
13181 (defun org-align-tags-here (to-col)
13182 ;; Assumes that this is a headline
13183 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13184 (beginning-of-line 1)
13185 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13186 (< pos (match-beginning 2)))
13187 (progn
13188 (setq tags-l (- (match-end 2) (match-beginning 2)))
13189 (goto-char (match-beginning 1))
13190 (insert " ")
13191 (delete-region (point) (1+ (match-beginning 2)))
13192 (setq ncol (max (current-column)
13193 (1+ col)
13194 (if (> to-col 0)
13195 to-col
13196 (- (abs to-col) tags-l))))
13197 (setq p (point))
13198 (insert (make-string (- ncol (current-column)) ?\ ))
13199 (setq ncol (current-column))
13200 (when indent-tabs-mode (tabify p (point-at-eol)))
13201 (org-move-to-column (min ncol col) t))
13202 (goto-char pos))))
13204 (defun org-set-tags-command (&optional arg just-align)
13205 "Call the set-tags command for the current entry."
13206 (interactive "P")
13207 (if (org-on-heading-p)
13208 (org-set-tags arg just-align)
13209 (save-excursion
13210 (org-back-to-heading t)
13211 (org-set-tags arg just-align))))
13213 (defun org-set-tags-to (data)
13214 "Set the tags of the current entry to DATA, replacing the current tags.
13215 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13216 If DATA is nil or the empty string, any tags will be removed."
13217 (interactive "sTags: ")
13218 (setq data
13219 (cond
13220 ((eq data nil) "")
13221 ((equal data "") "")
13222 ((stringp data)
13223 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13224 ":"))
13225 ((listp data)
13226 (concat ":" (mapconcat 'identity data ":") ":"))
13227 (t nil)))
13228 (when data
13229 (save-excursion
13230 (org-back-to-heading t)
13231 (when (looking-at org-complex-heading-regexp)
13232 (if (match-end 5)
13233 (progn
13234 (goto-char (match-beginning 5))
13235 (insert data)
13236 (delete-region (point) (point-at-eol))
13237 (org-set-tags nil 'align))
13238 (goto-char (point-at-eol))
13239 (insert " " data)
13240 (org-set-tags nil 'align)))
13241 (beginning-of-line 1)
13242 (if (looking-at ".*?\\([ \t]+\\)$")
13243 (delete-region (match-beginning 1) (match-end 1))))))
13245 (defun org-align-all-tags ()
13246 "Align the tags i all headings."
13247 (interactive)
13248 (save-excursion
13249 (or (ignore-errors (org-back-to-heading t))
13250 (outline-next-heading))
13251 (if (org-on-heading-p)
13252 (org-set-tags t)
13253 (message "No headings"))))
13255 (defvar org-indent-indentation-per-level)
13256 (defun org-set-tags (&optional arg just-align)
13257 "Set the tags for the current headline.
13258 With prefix ARG, realign all tags in headings in the current buffer."
13259 (interactive "P")
13260 (let* ((re org-outline-regexp-bol)
13261 (current (org-get-tags-string))
13262 (col (current-column))
13263 (org-setting-tags t)
13264 table current-tags inherited-tags ; computed below when needed
13265 tags p0 c0 c1 rpl di tc level)
13266 (if arg
13267 (save-excursion
13268 (goto-char (point-min))
13269 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13270 (while (re-search-forward re nil t)
13271 (org-set-tags nil t)
13272 (end-of-line 1)))
13273 (message "All tags realigned to column %d" org-tags-column))
13274 (if just-align
13275 (setq tags current)
13276 ;; Get a new set of tags from the user
13277 (save-excursion
13278 (setq table (append org-tag-persistent-alist
13279 (or org-tag-alist (org-get-buffer-tags))
13280 (and
13281 org-complete-tags-always-offer-all-agenda-tags
13282 (org-global-tags-completion-table
13283 (org-agenda-files))))
13284 org-last-tags-completion-table table
13285 current-tags (org-split-string current ":")
13286 inherited-tags (nreverse
13287 (nthcdr (length current-tags)
13288 (nreverse (org-get-tags-at))))
13289 tags
13290 (if (or (eq t org-use-fast-tag-selection)
13291 (and org-use-fast-tag-selection
13292 (delq nil (mapcar 'cdr table))))
13293 (org-fast-tag-selection
13294 current-tags inherited-tags table
13295 (if org-fast-tag-selection-include-todo
13296 org-todo-key-alist))
13297 (let ((org-add-colon-after-tag-completion t))
13298 (org-trim
13299 (org-icompleting-read "Tags: "
13300 'org-tags-completion-function
13301 nil nil current 'org-tags-history))))))
13302 (while (string-match "[-+&]+" tags)
13303 ;; No boolean logic, just a list
13304 (setq tags (replace-match ":" t t tags))))
13306 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13308 (if org-tags-sort-function
13309 (setq tags (mapconcat 'identity
13310 (sort (org-split-string
13311 tags (org-re "[^[:alnum:]_@#%]+"))
13312 org-tags-sort-function) ":")))
13314 (if (string-match "\\`[\t ]*\\'" tags)
13315 (setq tags "")
13316 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13317 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13319 ;; Insert new tags at the correct column
13320 (beginning-of-line 1)
13321 (setq level (or (and (looking-at org-outline-regexp)
13322 (- (match-end 0) (point) 1))
13324 (cond
13325 ((and (equal current "") (equal tags "")))
13326 ((re-search-forward
13327 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13328 (point-at-eol) t)
13329 (if (equal tags "")
13330 (setq rpl "")
13331 (goto-char (match-beginning 0))
13332 (setq c0 (current-column)
13333 ;; compute offset for the case of org-indent-mode active
13334 di (if org-indent-mode
13335 (* (1- org-indent-indentation-per-level) (1- level))
13337 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13338 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13339 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13340 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13341 (replace-match rpl t t)
13342 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13343 tags)
13344 (t (error "Tags alignment failed")))
13345 (org-move-to-column col)
13346 (unless just-align
13347 (run-hooks 'org-after-tags-change-hook)))))
13349 (defun org-change-tag-in-region (beg end tag off)
13350 "Add or remove TAG for each entry in the region.
13351 This works in the agenda, and also in an org-mode buffer."
13352 (interactive
13353 (list (region-beginning) (region-end)
13354 (let ((org-last-tags-completion-table
13355 (if (eq major-mode 'org-mode)
13356 (org-get-buffer-tags)
13357 (org-global-tags-completion-table))))
13358 (org-icompleting-read
13359 "Tag: " 'org-tags-completion-function nil nil nil
13360 'org-tags-history))
13361 (progn
13362 (message "[s]et or [r]emove? ")
13363 (equal (read-char-exclusive) ?r))))
13364 (if (fboundp 'deactivate-mark) (deactivate-mark))
13365 (let ((agendap (equal major-mode 'org-agenda-mode))
13366 l1 l2 m buf pos newhead (cnt 0))
13367 (goto-char end)
13368 (setq l2 (1- (org-current-line)))
13369 (goto-char beg)
13370 (setq l1 (org-current-line))
13371 (loop for l from l1 to l2 do
13372 (org-goto-line l)
13373 (setq m (get-text-property (point) 'org-hd-marker))
13374 (when (or (and (eq major-mode 'org-mode) (org-on-heading-p))
13375 (and agendap m))
13376 (setq buf (if agendap (marker-buffer m) (current-buffer))
13377 pos (if agendap m (point)))
13378 (with-current-buffer buf
13379 (save-excursion
13380 (save-restriction
13381 (goto-char pos)
13382 (setq cnt (1+ cnt))
13383 (org-toggle-tag tag (if off 'off 'on))
13384 (setq newhead (org-get-heading)))))
13385 (and agendap (org-agenda-change-all-lines newhead m))))
13386 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13388 (defun org-tags-completion-function (string predicate &optional flag)
13389 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13390 (confirm (lambda (x) (stringp (car x)))))
13391 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13392 (setq s1 (match-string 1 string)
13393 s2 (match-string 2 string))
13394 (setq s1 "" s2 string))
13395 (cond
13396 ((eq flag nil)
13397 ;; try completion
13398 (setq rtn (try-completion s2 ctable confirm))
13399 (if (stringp rtn)
13400 (setq rtn
13401 (concat s1 s2 (substring rtn (length s2))
13402 (if (and org-add-colon-after-tag-completion
13403 (assoc rtn ctable))
13404 ":" ""))))
13405 rtn)
13406 ((eq flag t)
13407 ;; all-completions
13408 (all-completions s2 ctable confirm)
13410 ((eq flag 'lambda)
13411 ;; exact match?
13412 (assoc s2 ctable)))
13415 (defun org-fast-tag-insert (kwd tags face &optional end)
13416 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13417 (insert (format "%-12s" (concat kwd ":"))
13418 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13419 (or end "")))
13421 (defun org-fast-tag-show-exit (flag)
13422 (save-excursion
13423 (org-goto-line 3)
13424 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13425 (replace-match ""))
13426 (when flag
13427 (end-of-line 1)
13428 (org-move-to-column (- (window-width) 19) t)
13429 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13431 (defun org-set-current-tags-overlay (current prefix)
13432 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13433 (if (featurep 'xemacs)
13434 (org-overlay-display org-tags-overlay (concat prefix s)
13435 'secondary-selection)
13436 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13437 (org-overlay-display org-tags-overlay (concat prefix s)))))
13439 (defvar org-last-tag-selection-key nil)
13440 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13441 "Fast tag selection with single keys.
13442 CURRENT is the current list of tags in the headline, INHERITED is the
13443 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13444 possibly with grouping information. TODO-TABLE is a similar table with
13445 TODO keywords, should these have keys assigned to them.
13446 If the keys are nil, a-z are automatically assigned.
13447 Returns the new tags string, or nil to not change the current settings."
13448 (let* ((fulltable (append table todo-table))
13449 (maxlen (apply 'max (mapcar
13450 (lambda (x)
13451 (if (stringp (car x)) (string-width (car x)) 0))
13452 fulltable)))
13453 (buf (current-buffer))
13454 (expert (eq org-fast-tag-selection-single-key 'expert))
13455 (buffer-tags nil)
13456 (fwidth (+ maxlen 3 1 3))
13457 (ncol (/ (- (window-width) 4) fwidth))
13458 (i-face 'org-done)
13459 (c-face 'org-todo)
13460 tg cnt e c char c1 c2 ntable tbl rtn
13461 ov-start ov-end ov-prefix
13462 (exit-after-next org-fast-tag-selection-single-key)
13463 (done-keywords org-done-keywords)
13464 groups ingroup)
13465 (save-excursion
13466 (beginning-of-line 1)
13467 (if (looking-at
13468 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13469 (setq ov-start (match-beginning 1)
13470 ov-end (match-end 1)
13471 ov-prefix "")
13472 (setq ov-start (1- (point-at-eol))
13473 ov-end (1+ ov-start))
13474 (skip-chars-forward "^\n\r")
13475 (setq ov-prefix
13476 (concat
13477 (buffer-substring (1- (point)) (point))
13478 (if (> (current-column) org-tags-column)
13480 (make-string (- org-tags-column (current-column)) ?\ ))))))
13481 (move-overlay org-tags-overlay ov-start ov-end)
13482 (save-window-excursion
13483 (if expert
13484 (set-buffer (get-buffer-create " *Org tags*"))
13485 (delete-other-windows)
13486 (split-window-vertically)
13487 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13488 (erase-buffer)
13489 (org-set-local 'org-done-keywords done-keywords)
13490 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13491 (org-fast-tag-insert "Current" current c-face "\n\n")
13492 (org-fast-tag-show-exit exit-after-next)
13493 (org-set-current-tags-overlay current ov-prefix)
13494 (setq tbl fulltable char ?a cnt 0)
13495 (while (setq e (pop tbl))
13496 (cond
13497 ((equal (car e) :startgroup)
13498 (push '() groups) (setq ingroup t)
13499 (when (not (= cnt 0))
13500 (setq cnt 0)
13501 (insert "\n"))
13502 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13503 ((equal (car e) :endgroup)
13504 (setq ingroup nil cnt 0)
13505 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13506 ((equal e '(:newline))
13507 (when (not (= cnt 0))
13508 (setq cnt 0)
13509 (insert "\n")
13510 (setq e (car tbl))
13511 (while (equal (car tbl) '(:newline))
13512 (insert "\n")
13513 (setq tbl (cdr tbl)))))
13515 (setq tg (copy-sequence (car e)) c2 nil)
13516 (if (cdr e)
13517 (setq c (cdr e))
13518 ;; automatically assign a character.
13519 (setq c1 (string-to-char
13520 (downcase (substring
13521 tg (if (= (string-to-char tg) ?@) 1 0)))))
13522 (if (or (rassoc c1 ntable) (rassoc c1 table))
13523 (while (or (rassoc char ntable) (rassoc char table))
13524 (setq char (1+ char)))
13525 (setq c2 c1))
13526 (setq c (or c2 char)))
13527 (if ingroup (push tg (car groups)))
13528 (setq tg (org-add-props tg nil 'face
13529 (cond
13530 ((not (assoc tg table))
13531 (org-get-todo-face tg))
13532 ((member tg current) c-face)
13533 ((member tg inherited) i-face)
13534 (t nil))))
13535 (if (and (= cnt 0) (not ingroup)) (insert " "))
13536 (insert "[" c "] " tg (make-string
13537 (- fwidth 4 (length tg)) ?\ ))
13538 (push (cons tg c) ntable)
13539 (when (= (setq cnt (1+ cnt)) ncol)
13540 (insert "\n")
13541 (if ingroup (insert " "))
13542 (setq cnt 0)))))
13543 (setq ntable (nreverse ntable))
13544 (insert "\n")
13545 (goto-char (point-min))
13546 (if (not expert) (org-fit-window-to-buffer))
13547 (setq rtn
13548 (catch 'exit
13549 (while t
13550 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13551 (if (not groups) "no " "")
13552 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13553 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13554 (setq org-last-tag-selection-key c)
13555 (cond
13556 ((= c ?\r) (throw 'exit t))
13557 ((= c ?!)
13558 (setq groups (not groups))
13559 (goto-char (point-min))
13560 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13561 ((= c ?\C-c)
13562 (if (not expert)
13563 (org-fast-tag-show-exit
13564 (setq exit-after-next (not exit-after-next)))
13565 (setq expert nil)
13566 (delete-other-windows)
13567 (set-window-buffer (split-window-vertically) " *Org tags*")
13568 (org-switch-to-buffer-other-window " *Org tags*")
13569 (org-fit-window-to-buffer)))
13570 ((or (= c ?\C-g)
13571 (and (= c ?q) (not (rassoc c ntable))))
13572 (org-detach-overlay org-tags-overlay)
13573 (setq quit-flag t))
13574 ((= c ?\ )
13575 (setq current nil)
13576 (if exit-after-next (setq exit-after-next 'now)))
13577 ((= c ?\t)
13578 (condition-case nil
13579 (setq tg (org-icompleting-read
13580 "Tag: "
13581 (or buffer-tags
13582 (with-current-buffer buf
13583 (org-get-buffer-tags)))))
13584 (quit (setq tg "")))
13585 (when (string-match "\\S-" tg)
13586 (add-to-list 'buffer-tags (list tg))
13587 (if (member tg current)
13588 (setq current (delete tg current))
13589 (push tg current)))
13590 (if exit-after-next (setq exit-after-next 'now)))
13591 ((setq e (rassoc c todo-table) tg (car e))
13592 (with-current-buffer buf
13593 (save-excursion (org-todo tg)))
13594 (if exit-after-next (setq exit-after-next 'now)))
13595 ((setq e (rassoc c ntable) tg (car e))
13596 (if (member tg current)
13597 (setq current (delete tg current))
13598 (loop for g in groups do
13599 (if (member tg g)
13600 (mapc (lambda (x)
13601 (setq current (delete x current)))
13602 g)))
13603 (push tg current))
13604 (if exit-after-next (setq exit-after-next 'now))))
13606 ;; Create a sorted list
13607 (setq current
13608 (sort current
13609 (lambda (a b)
13610 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13611 (if (eq exit-after-next 'now) (throw 'exit t))
13612 (goto-char (point-min))
13613 (beginning-of-line 2)
13614 (delete-region (point) (point-at-eol))
13615 (org-fast-tag-insert "Current" current c-face)
13616 (org-set-current-tags-overlay current ov-prefix)
13617 (while (re-search-forward
13618 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13619 (setq tg (match-string 1))
13620 (add-text-properties
13621 (match-beginning 1) (match-end 1)
13622 (list 'face
13623 (cond
13624 ((member tg current) c-face)
13625 ((member tg inherited) i-face)
13626 (t (get-text-property (match-beginning 1) 'face))))))
13627 (goto-char (point-min)))))
13628 (org-detach-overlay org-tags-overlay)
13629 (if rtn
13630 (mapconcat 'identity current ":")
13631 nil))))
13633 (defun org-get-tags-string ()
13634 "Get the TAGS string in the current headline."
13635 (unless (org-on-heading-p t)
13636 (error "Not on a heading"))
13637 (save-excursion
13638 (beginning-of-line 1)
13639 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13640 (org-match-string-no-properties 1)
13641 "")))
13643 (defun org-get-tags ()
13644 "Get the list of tags specified in the current headline."
13645 (org-split-string (org-get-tags-string) ":"))
13647 (defun org-get-buffer-tags ()
13648 "Get a table of all tags used in the buffer, for completion."
13649 (let (tags)
13650 (save-excursion
13651 (goto-char (point-min))
13652 (while (re-search-forward
13653 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13654 (when (equal (char-after (point-at-bol 0)) ?*)
13655 (mapc (lambda (x) (add-to-list 'tags x))
13656 (org-split-string (org-match-string-no-properties 1) ":")))))
13657 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13658 (mapcar 'list tags)))
13660 ;;;; The mapping API
13662 ;;;###autoload
13663 (defun org-map-entries (func &optional match scope &rest skip)
13664 "Call FUNC at each headline selected by MATCH in SCOPE.
13666 FUNC is a function or a lisp form. The function will be called without
13667 arguments, with the cursor positioned at the beginning of the headline.
13668 The return values of all calls to the function will be collected and
13669 returned as a list.
13671 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13672 does not need to preserve point. After evaluation, the cursor will be
13673 moved to the end of the line (presumably of the headline of the
13674 processed entry) and search continues from there. Under some
13675 circumstances, this may not produce the wanted results. For example,
13676 if you have removed (e.g. archived) the current (sub)tree it could
13677 mean that the next entry will be skipped entirely. In such cases, you
13678 can specify the position from where search should continue by making
13679 FUNC set the variable `org-map-continue-from' to the desired buffer
13680 position.
13682 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13683 Only headlines that are matched by this query will be considered during
13684 the iteration. When MATCH is nil or t, all headlines will be
13685 visited by the iteration.
13687 SCOPE determines the scope of this command. It can be any of:
13689 nil The current buffer, respecting the restriction if any
13690 tree The subtree started with the entry at point
13691 region The entries within the active region, if any
13692 file The current buffer, without restriction
13693 file-with-archives
13694 The current buffer, and any archives associated with it
13695 agenda All agenda files
13696 agenda-with-archives
13697 All agenda files with any archive files associated with them
13698 \(file1 file2 ...)
13699 If this is a list, all files in the list will be scanned
13701 The remaining args are treated as settings for the skipping facilities of
13702 the scanner. The following items can be given here:
13704 archive skip trees with the archive tag.
13705 comment skip trees with the COMMENT keyword
13706 function or Emacs Lisp form:
13707 will be used as value for `org-agenda-skip-function', so whenever
13708 the function returns t, FUNC will not be called for that
13709 entry and search will continue from the point where the
13710 function leaves it.
13712 If your function needs to retrieve the tags including inherited tags
13713 at the *current* entry, you can use the value of the variable
13714 `org-scanner-tags' which will be much faster than getting the value
13715 with `org-get-tags-at'. If your function gets properties with
13716 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13717 to t around the call to `org-entry-properties' to get the same speedup.
13718 Note that if your function moves around to retrieve tags and properties at
13719 a *different* entry, you cannot use these techniques."
13720 (unless (and (eq scope 'region) (not (org-region-active-p)))
13721 (let* ((org-agenda-archives-mode nil) ; just to make sure
13722 (org-agenda-skip-archived-trees (memq 'archive skip))
13723 (org-agenda-skip-comment-trees (memq 'comment skip))
13724 (org-agenda-skip-function
13725 (car (org-delete-all '(comment archive) skip)))
13726 (org-tags-match-list-sublevels t)
13727 matcher file res
13728 org-todo-keywords-for-agenda
13729 org-done-keywords-for-agenda
13730 org-todo-keyword-alist-for-agenda
13731 org-drawers-for-agenda
13732 org-tag-alist-for-agenda)
13734 (cond
13735 ((eq match t) (setq matcher t))
13736 ((eq match nil) (setq matcher t))
13737 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13739 (save-excursion
13740 (save-restriction
13741 (cond ((eq scope 'tree)
13742 (org-back-to-heading t)
13743 (org-narrow-to-subtree)
13744 (setq scope nil))
13745 ((and (eq scope 'region) (org-region-active-p))
13746 (narrow-to-region (region-beginning)
13747 (save-excursion
13748 (goto-char (region-end))
13749 (unless (and (bolp) (org-at-heading-p))
13750 (outline-next-heading))
13751 (point)))
13752 (setq scope nil)))
13754 (if (not scope)
13755 (progn
13756 (org-prepare-agenda-buffers
13757 (list (buffer-file-name (current-buffer))))
13758 (setq res (org-scan-tags func matcher)))
13759 ;; Get the right scope
13760 (cond
13761 ((and scope (listp scope) (symbolp (car scope)))
13762 (setq scope (eval scope)))
13763 ((eq scope 'agenda)
13764 (setq scope (org-agenda-files t)))
13765 ((eq scope 'agenda-with-archives)
13766 (setq scope (org-agenda-files t))
13767 (setq scope (org-add-archive-files scope)))
13768 ((eq scope 'file)
13769 (setq scope (list (buffer-file-name))))
13770 ((eq scope 'file-with-archives)
13771 (setq scope (org-add-archive-files (list (buffer-file-name))))))
13772 (org-prepare-agenda-buffers scope)
13773 (while (setq file (pop scope))
13774 (with-current-buffer (org-find-base-buffer-visiting file)
13775 (save-excursion
13776 (save-restriction
13777 (widen)
13778 (goto-char (point-min))
13779 (setq res (append res (org-scan-tags func matcher))))))))))
13780 res)))
13782 ;;;; Properties
13784 ;;; Setting and retrieving properties
13786 (defconst org-special-properties
13787 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
13788 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM")
13789 "The special properties valid in Org-mode.
13791 These are properties that are not defined in the property drawer,
13792 but in some other way.")
13794 (defconst org-default-properties
13795 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
13796 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
13797 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
13798 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
13799 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
13800 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
13801 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
13802 "Some properties that are used by Org-mode for various purposes.
13803 Being in this list makes sure that they are offered for completion.")
13805 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
13806 "Regular expression matching the first line of a property drawer.")
13808 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
13809 "Regular expression matching the last line of a property drawer.")
13811 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
13812 "Regular expression matching the first line of a property drawer.")
13814 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
13815 "Regular expression matching the first line of a property drawer.")
13817 (defconst org-property-drawer-re
13818 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
13819 org-property-end-re "\\)\n?")
13820 "Matches an entire property drawer.")
13822 (defconst org-clock-drawer-re
13823 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
13824 org-property-end-re "\\)\n?")
13825 "Matches an entire clock drawer.")
13827 (defsubst org-re-property (property)
13828 "Return a regexp matching PROPERTY.
13829 Match group 1 will be set to the value "
13830 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
13832 (defun org-property-action ()
13833 "Do an action on properties."
13834 (interactive)
13835 (let (c)
13836 (org-at-property-p)
13837 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
13838 (setq c (read-char-exclusive))
13839 (cond
13840 ((equal c ?s)
13841 (call-interactively 'org-set-property))
13842 ((equal c ?d)
13843 (call-interactively 'org-delete-property))
13844 ((equal c ?D)
13845 (call-interactively 'org-delete-property-globally))
13846 ((equal c ?c)
13847 (call-interactively 'org-compute-property-at-point))
13848 (t (error "No such property action %c" c)))))
13850 (defun org-set-effort (&optional value)
13851 "Set the effort property of the current entry.
13852 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
13853 allowed value."
13854 (interactive "P")
13855 (if (equal value 0) (setq value 10))
13856 (let* ((completion-ignore-case t)
13857 (prop org-effort-property)
13858 (cur (org-entry-get nil prop))
13859 (allowed (org-property-get-allowed-values nil prop 'table))
13860 (existing (mapcar 'list (org-property-values prop)))
13862 (val (cond
13863 ((stringp value) value)
13864 ((and allowed (integerp value))
13865 (or (car (nth (1- value) allowed))
13866 (car (org-last allowed))))
13867 (allowed
13868 (message "Select 1-9,0, [RET%s]: %s"
13869 (if cur (concat "=" cur) "")
13870 (mapconcat 'car allowed " "))
13871 (setq rpl (read-char-exclusive))
13872 (if (equal rpl ?\r)
13874 (setq rpl (- rpl ?0))
13875 (if (equal rpl 0) (setq rpl 10))
13876 (if (and (> rpl 0) (<= rpl (length allowed)))
13877 (car (nth (1- rpl) allowed))
13878 (org-completing-read "Effort: " allowed nil))))
13880 (let (org-completion-use-ido org-completion-use-iswitchb)
13881 (org-completing-read
13882 (concat "Effort " (if (and cur (string-match "\\S-" cur))
13883 (concat "[" cur "]") "")
13884 ": ")
13885 existing nil nil "" nil cur))))))
13886 (unless (equal (org-entry-get nil prop) val)
13887 (org-entry-put nil prop val))
13888 (message "%s is now %s" prop val)))
13890 (defun org-at-property-p ()
13891 "Is cursor inside a property drawer?"
13892 (save-excursion
13893 (beginning-of-line 1)
13894 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
13895 (save-match-data ;; Used by calling procedures
13896 (let ((p (point))
13897 (range (unless (org-before-first-heading-p)
13898 (org-get-property-block))))
13899 (and range (<= (car range) p) (< p (cdr range))))))))
13901 (defun org-get-property-block (&optional beg end force)
13902 "Return the (beg . end) range of the body of the property drawer.
13903 BEG and END can be beginning and end of subtree, if not given
13904 they will be found.
13905 If the drawer does not exist and FORCE is non-nil, create the drawer."
13906 (catch 'exit
13907 (save-excursion
13908 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
13909 (end (or end (progn (outline-next-heading) (point)))))
13910 (goto-char beg)
13911 (if (re-search-forward org-property-start-re end t)
13912 (setq beg (1+ (match-end 0)))
13913 (if force
13914 (save-excursion
13915 (org-insert-property-drawer)
13916 (setq end (progn (outline-next-heading) (point))))
13917 (throw 'exit nil))
13918 (goto-char beg)
13919 (if (re-search-forward org-property-start-re end t)
13920 (setq beg (1+ (match-end 0)))))
13921 (if (re-search-forward org-property-end-re end t)
13922 (setq end (match-beginning 0))
13923 (or force (throw 'exit nil))
13924 (goto-char beg)
13925 (setq end beg)
13926 (org-indent-line-function)
13927 (insert ":END:\n"))
13928 (cons beg end)))))
13930 (defun org-entry-properties (&optional pom which specific)
13931 "Get all properties of the entry at point-or-marker POM.
13932 This includes the TODO keyword, the tags, time strings for deadline,
13933 scheduled, and clocking, and any additional properties defined in the
13934 entry. The return value is an alist, keys may occur multiple times
13935 if the property key was used several times.
13936 POM may also be nil, in which case the current entry is used.
13937 If WHICH is nil or `all', get all properties. If WHICH is
13938 `special' or `standard', only get that subclass. If WHICH
13939 is a string only get exactly this property. SPECIFIC can be a string, the
13940 specific property we are interested in. Specifying it can speed
13941 things up because then unnecessary parsing is avoided."
13942 (setq which (or which 'all))
13943 (org-with-point-at pom
13944 (let ((clockstr (substring org-clock-string 0 -1))
13945 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
13946 (case-fold-search nil)
13947 beg end range props sum-props key key1 value string clocksum)
13948 (save-excursion
13949 (when (condition-case nil
13950 (and (eq major-mode 'org-mode) (org-back-to-heading t))
13951 (error nil))
13952 (setq beg (point))
13953 (setq sum-props (get-text-property (point) 'org-summaries))
13954 (setq clocksum (get-text-property (point) :org-clock-minutes))
13955 (outline-next-heading)
13956 (setq end (point))
13957 (when (memq which '(all special))
13958 ;; Get the special properties, like TODO and tags
13959 (goto-char beg)
13960 (when (and (or (not specific) (string= specific "TODO"))
13961 (looking-at org-todo-line-regexp) (match-end 2))
13962 (push (cons "TODO" (org-match-string-no-properties 2)) props))
13963 (when (and (or (not specific) (string= specific "PRIORITY"))
13964 (looking-at org-priority-regexp))
13965 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
13966 (when (or (not specific) (string= specific "FILE"))
13967 (push (cons "FILE" buffer-file-name) props))
13968 (when (and (or (not specific) (string= specific "TAGS"))
13969 (setq value (org-get-tags-string))
13970 (string-match "\\S-" value))
13971 (push (cons "TAGS" value) props))
13972 (when (and (or (not specific) (string= specific "ALLTAGS"))
13973 (setq value (org-get-tags-at)))
13974 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
13975 ":"))
13976 props))
13977 (when (or (not specific) (string= specific "BLOCKED"))
13978 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
13979 (when (or (not specific)
13980 (member specific
13981 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
13982 "TIMESTAMP" "TIMESTAMP_IA")))
13983 (catch 'match
13984 (while (re-search-forward org-maybe-keyword-time-regexp end t)
13985 (setq key (if (match-end 1)
13986 (substring (org-match-string-no-properties 1)
13987 0 -1))
13988 string (if (equal key clockstr)
13989 (org-no-properties
13990 (org-trim
13991 (buffer-substring
13992 (match-beginning 3) (goto-char
13993 (point-at-eol)))))
13994 (substring (org-match-string-no-properties 3)
13995 1 -1)))
13996 ;; Get the correct property name from the key. This is
13997 ;; necessary if the user has configured time keywords.
13998 (setq key1 (concat key ":"))
13999 (cond
14000 ((not key)
14001 (setq key
14002 (if (= (char-after (match-beginning 3)) ?\[)
14003 "TIMESTAMP_IA" "TIMESTAMP")))
14004 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14005 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14006 ((equal key1 org-closed-string) (setq key "CLOSED"))
14007 ((equal key1 org-clock-string) (setq key "CLOCK")))
14008 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14009 (progn
14010 (push (cons key string) props)
14011 ;; no need to search further if match is found
14012 (throw 'match t))
14013 (when (or (equal key "CLOCK") (not (assoc key props)))
14014 (push (cons key string) props))))))
14017 (when (memq which '(all standard))
14018 ;; Get the standard properties, like :PROP: ...
14019 (setq range (org-get-property-block beg end))
14020 (when range
14021 (goto-char (car range))
14022 (while (re-search-forward
14023 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14024 (cdr range) t)
14025 (setq key (org-match-string-no-properties 1)
14026 value (org-trim (or (org-match-string-no-properties 2) "")))
14027 (unless (member key excluded)
14028 (push (cons key (or value "")) props)))))
14029 (if clocksum
14030 (push (cons "CLOCKSUM"
14031 (org-columns-number-to-string (/ (float clocksum) 60.)
14032 'add_times))
14033 props))
14034 (unless (assoc "CATEGORY" props)
14035 (push (cons "CATEGORY" (org-get-category)) props))
14036 (append sum-props (nreverse props)))))))
14038 (defun org-entry-get (pom property &optional inherit literal-nil)
14039 "Get value of PROPERTY for entry at point-or-marker POM.
14040 If INHERIT is non-nil and the entry does not have the property,
14041 then also check higher levels of the hierarchy.
14042 If INHERIT is the symbol `selective', use inheritance only if the setting
14043 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14044 If the property is present but empty, the return value is the empty string.
14045 If the property is not present at all, nil is returned.
14047 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14048 do not interpret it as the list atom nil. This is used for inheritance
14049 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14050 (org-with-point-at pom
14051 (if (and inherit (if (eq inherit 'selective)
14052 (org-property-inherit-p property)
14054 (org-entry-get-with-inheritance property literal-nil)
14055 (if (member property org-special-properties)
14056 ;; We need a special property. Use `org-entry-properties' to
14057 ;; retrieve it, but specify the wanted property
14058 (cdr (assoc property (org-entry-properties nil 'special property)))
14059 (let ((range (unless (org-before-first-heading-p)
14060 (org-get-property-block))))
14061 (if (and range
14062 (goto-char (car range))
14063 (re-search-forward
14064 (org-re-property property)
14065 (cdr range) t))
14066 ;; Found the property, return it.
14067 (if (match-end 1)
14068 (if literal-nil
14069 (org-match-string-no-properties 1)
14070 (org-not-nil (org-match-string-no-properties 1)))
14071 "")))))))
14073 (defun org-property-or-variable-value (var &optional inherit)
14074 "Check if there is a property fixing the value of VAR.
14075 If yes, return this value. If not, return the current value of the variable."
14076 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14077 (if (and prop (stringp prop) (string-match "\\S-" prop))
14078 (read prop)
14079 (symbol-value var))))
14081 (defun org-entry-delete (pom property)
14082 "Delete the property PROPERTY from entry at point-or-marker POM."
14083 (org-with-point-at pom
14084 (if (member property org-special-properties)
14085 nil ; cannot delete these properties.
14086 (let ((range (org-get-property-block)))
14087 (if (and range
14088 (goto-char (car range))
14089 (re-search-forward
14090 (org-re-property property)
14091 (cdr range) t))
14092 (progn
14093 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14095 nil)))))
14097 ;; Multi-values properties are properties that contain multiple values
14098 ;; These values are assumed to be single words, separated by whitespace.
14099 (defun org-entry-add-to-multivalued-property (pom property value)
14100 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14101 (let* ((old (org-entry-get pom property))
14102 (values (and old (org-split-string old "[ \t]"))))
14103 (setq value (org-entry-protect-space value))
14104 (unless (member value values)
14105 (setq values (cons value values))
14106 (org-entry-put pom property
14107 (mapconcat 'identity values " ")))))
14109 (defun org-entry-remove-from-multivalued-property (pom property value)
14110 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14111 (let* ((old (org-entry-get pom property))
14112 (values (and old (org-split-string old "[ \t]"))))
14113 (setq value (org-entry-protect-space value))
14114 (when (member value values)
14115 (setq values (delete value values))
14116 (org-entry-put pom property
14117 (mapconcat 'identity values " ")))))
14119 (defun org-entry-member-in-multivalued-property (pom property value)
14120 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14121 (let* ((old (org-entry-get pom property))
14122 (values (and old (org-split-string old "[ \t]"))))
14123 (setq value (org-entry-protect-space value))
14124 (member value values)))
14126 (defun org-entry-get-multivalued-property (pom property)
14127 "Return a list of values in a multivalued property."
14128 (let* ((value (org-entry-get pom property))
14129 (values (and value (org-split-string value "[ \t]"))))
14130 (mapcar 'org-entry-restore-space values)))
14132 (defun org-entry-put-multivalued-property (pom property &rest values)
14133 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14134 VALUES should be a list of strings. Spaces will be protected."
14135 (org-entry-put pom property
14136 (mapconcat 'org-entry-protect-space values " "))
14137 (let* ((value (org-entry-get pom property))
14138 (values (and value (org-split-string value "[ \t]"))))
14139 (mapcar 'org-entry-restore-space values)))
14141 (defun org-entry-protect-space (s)
14142 "Protect spaces and newline in string S."
14143 (while (string-match " " s)
14144 (setq s (replace-match "%20" t t s)))
14145 (while (string-match "\n" s)
14146 (setq s (replace-match "%0A" t t s)))
14149 (defun org-entry-restore-space (s)
14150 "Restore spaces and newline in string S."
14151 (while (string-match "%20" s)
14152 (setq s (replace-match " " t t s)))
14153 (while (string-match "%0A" s)
14154 (setq s (replace-match "\n" t t s)))
14157 (defvar org-entry-property-inherited-from (make-marker)
14158 "Marker pointing to the entry from where a property was inherited.
14159 Each call to `org-entry-get-with-inheritance' will set this marker to the
14160 location of the entry where the inheritance search matched. If there was
14161 no match, the marker will point nowhere.
14162 Note that also `org-entry-get' calls this function, if the INHERIT flag
14163 is set.")
14165 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14166 "Get entry property, and search higher levels if not present.
14167 The search will stop at the first ancestor which has the property defined.
14168 If the value found is \"nil\", return nil to show that the property
14169 should be considered as undefined (this is the meaning of nil here).
14170 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14171 (move-marker org-entry-property-inherited-from nil)
14172 (let (tmp)
14173 (unless (org-before-first-heading-p)
14174 (save-excursion
14175 (save-restriction
14176 (widen)
14177 (catch 'ex
14178 (while t
14179 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14180 (org-back-to-heading t)
14181 (move-marker org-entry-property-inherited-from (point))
14182 (throw 'ex tmp))
14183 (or (org-up-heading-safe) (throw 'ex nil)))))))
14184 (setq tmp (or tmp
14185 (cdr (assoc property org-file-properties))
14186 (cdr (assoc property org-global-properties))
14187 (cdr (assoc property org-global-properties-fixed))))
14188 (if literal-nil tmp (org-not-nil tmp))))
14190 (defvar org-property-changed-functions nil
14191 "Hook called when the value of a property has changed.
14192 Each hook function should accept two arguments, the name of the property
14193 and the new value.")
14195 (defun org-entry-put (pom property value)
14196 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14197 (org-with-point-at pom
14198 (org-back-to-heading t)
14199 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14200 range)
14201 (cond
14202 ((equal property "TODO")
14203 (when (and (stringp value) (string-match "\\S-" value)
14204 (not (member value org-todo-keywords-1)))
14205 (error "\"%s\" is not a valid TODO state" value))
14206 (if (or (not value)
14207 (not (string-match "\\S-" value)))
14208 (setq value 'none))
14209 (org-todo value)
14210 (org-set-tags nil 'align))
14211 ((equal property "PRIORITY")
14212 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14213 (string-to-char value) ?\ ))
14214 (org-set-tags nil 'align))
14215 ((equal property "SCHEDULED")
14216 (if (re-search-forward org-scheduled-time-regexp end t)
14217 (cond
14218 ((eq value 'earlier) (org-timestamp-change -1 'day))
14219 ((eq value 'later) (org-timestamp-change 1 'day))
14220 (t (call-interactively 'org-schedule)))
14221 (call-interactively 'org-schedule)))
14222 ((equal property "DEADLINE")
14223 (if (re-search-forward org-deadline-time-regexp end t)
14224 (cond
14225 ((eq value 'earlier) (org-timestamp-change -1 'day))
14226 ((eq value 'later) (org-timestamp-change 1 'day))
14227 (t (call-interactively 'org-deadline)))
14228 (call-interactively 'org-deadline)))
14229 ((member property org-special-properties)
14230 (error "The %s property can not yet be set with `org-entry-put'"
14231 property))
14232 (t ; a non-special property
14233 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14234 (setq range (org-get-property-block beg end 'force))
14235 (goto-char (car range))
14236 (if (re-search-forward
14237 (org-re-property property) (cdr range) t)
14238 (progn
14239 (delete-region (match-beginning 0) (match-end 0))
14240 (goto-char (match-beginning 0)))
14241 (goto-char (cdr range))
14242 (insert "\n")
14243 (backward-char 1)
14244 (org-indent-line-function))
14245 (insert ":" property ":")
14246 (and value (insert " " value))
14247 (org-indent-line-function)))))
14248 (run-hook-with-args 'org-property-changed-functions property value)))
14250 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14251 "Get all property keys in the current buffer.
14252 With INCLUDE-SPECIALS, also list the special properties that reflect things
14253 like tags and TODO state.
14254 With INCLUDE-DEFAULTS, also include properties that has special meaning
14255 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14256 and others.
14257 With INCLUDE-COLUMNS, also include property names given in COLUMN
14258 formats in the current buffer."
14259 (let (rtn range cfmt s p)
14260 (save-excursion
14261 (save-restriction
14262 (widen)
14263 (goto-char (point-min))
14264 (while (re-search-forward org-property-start-re nil t)
14265 (setq range (org-get-property-block))
14266 (goto-char (car range))
14267 (while (re-search-forward
14268 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14269 (cdr range) t)
14270 (add-to-list 'rtn (org-match-string-no-properties 1)))
14271 (outline-next-heading))))
14273 (when include-specials
14274 (setq rtn (append org-special-properties rtn)))
14276 (when include-defaults
14277 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14278 (add-to-list 'rtn org-effort-property))
14280 (when include-columns
14281 (save-excursion
14282 (save-restriction
14283 (widen)
14284 (goto-char (point-min))
14285 (while (re-search-forward
14286 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14287 nil t)
14288 (setq cfmt (match-string 2) s 0)
14289 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14290 cfmt s)
14291 (setq s (match-end 0)
14292 p (match-string 1 cfmt))
14293 (unless (or (equal p "ITEM")
14294 (member p org-special-properties))
14295 (add-to-list 'rtn (match-string 1 cfmt))))))))
14297 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14299 (defun org-property-values (key)
14300 "Return a list of all values of property KEY in the current buffer."
14301 (save-excursion
14302 (save-restriction
14303 (widen)
14304 (goto-char (point-min))
14305 (let ((re (org-re-property key))
14306 values)
14307 (while (re-search-forward re nil t)
14308 (add-to-list 'values (org-trim (match-string 1))))
14309 (delete "" values)))))
14311 (defun org-insert-property-drawer ()
14312 "Insert a property drawer into the current entry."
14313 (interactive)
14314 (org-back-to-heading t)
14315 (looking-at org-outline-regexp)
14316 (let ((indent (if org-adapt-indentation
14317 (- (match-end 0)(match-beginning 0))
14319 (beg (point))
14320 (re (concat "^[ \t]*" org-keyword-time-regexp))
14321 end hiddenp)
14322 (outline-next-heading)
14323 (setq end (point))
14324 (goto-char beg)
14325 (while (re-search-forward re end t))
14326 (setq hiddenp (outline-invisible-p))
14327 (end-of-line 1)
14328 (and (equal (char-after) ?\n) (forward-char 1))
14329 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14330 (if (member (match-string 1) '("CLOCK:" ":END:"))
14331 ;; just skip this line
14332 (beginning-of-line 2)
14333 ;; Drawer start, find the end
14334 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14335 (beginning-of-line 1)))
14336 (org-skip-over-state-notes)
14337 (skip-chars-backward " \t\n\r")
14338 (if (eq (char-before) ?*) (forward-char 1))
14339 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14340 (beginning-of-line 0)
14341 (org-indent-to-column indent)
14342 (beginning-of-line 2)
14343 (org-indent-to-column indent)
14344 (beginning-of-line 0)
14345 (if hiddenp
14346 (save-excursion
14347 (org-back-to-heading t)
14348 (hide-entry))
14349 (org-flag-drawer t))))
14351 (defvar org-property-set-functions-alist nil
14352 "Property set function alist.
14353 Each entry should have the following format:
14355 (PROPERTY . READ-FUNCTION)
14357 The read function will be called with the same argument as
14358 `org-completing-read'.")
14360 (defun org-set-property-function (property)
14361 "Get the function that should be used to set PROPERTY.
14362 This is computed according to `org-property-set-functions-alist'."
14363 (or (cdr (assoc property org-property-set-functions-alist))
14364 'org-completing-read))
14366 (defun org-read-property-value (property)
14367 "Read PROPERTY value from user."
14368 (let* ((completion-ignore-case t)
14369 (allowed (org-property-get-allowed-values nil property 'table))
14370 (cur (org-entry-get nil property))
14371 (prompt (concat property " value"
14372 (if (and cur (string-match "\\S-" cur))
14373 (concat " [" cur "]") "") ": "))
14374 (set-function (org-set-property-function property))
14375 (val (if allowed
14376 (funcall set-function prompt allowed nil
14377 (not (get-text-property 0 'org-unrestricted
14378 (caar allowed))))
14379 (let (org-completion-use-ido org-completion-use-iswitchb)
14380 (funcall set-function prompt
14381 (mapcar 'list (org-property-values property))
14382 nil nil "" nil cur)))))
14383 (if (equal val "")
14385 val)))
14387 (defvar org-last-set-property nil)
14388 (defun org-read-property-name ()
14389 "Read a property name."
14390 (let* ((completion-ignore-case t)
14391 (keys (org-buffer-property-keys nil t t))
14392 (default-prop (or (save-excursion
14393 (save-match-data
14394 (beginning-of-line)
14395 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14396 (null (string= (match-string 1) "END"))
14397 (match-string 1))))
14398 org-last-set-property))
14399 (property (org-icompleting-read
14400 (concat "Property"
14401 (if default-prop (concat " [" default-prop "]") "")
14402 ": ")
14403 (mapcar 'list keys)
14404 nil nil nil nil
14405 default-prop
14407 (if (member property keys)
14408 property
14409 (or (cdr (assoc (downcase property)
14410 (mapcar (lambda (x) (cons (downcase x) x))
14411 keys)))
14412 property))))
14414 (defun org-set-property (property value)
14415 "In the current entry, set PROPERTY to VALUE.
14416 When called interactively, this will prompt for a property name, offering
14417 completion on existing and default properties. And then it will prompt
14418 for a value, offering completion either on allowed values (via an inherited
14419 xxx_ALL property) or on existing values in other instances of this property
14420 in the current file."
14421 (interactive (list nil nil))
14422 (let* ((property (or property (org-read-property-name)))
14423 (value (or value (org-read-property-value property)))
14424 (fn (assoc property org-properties-postprocess-alist)))
14425 (setq org-last-set-property property)
14426 ;; Possibly postprocess the inserted value:
14427 (when fn (setq value (funcall (cadr fn) value)))
14428 (unless (equal (org-entry-get nil property) value)
14429 (org-entry-put nil property value))))
14431 (defun org-delete-property (property)
14432 "In the current entry, delete PROPERTY."
14433 (interactive
14434 (let* ((completion-ignore-case t)
14435 (prop (org-icompleting-read "Property: "
14436 (org-entry-properties nil 'standard))))
14437 (list prop)))
14438 (message "Property %s %s" property
14439 (if (org-entry-delete nil property)
14440 "deleted"
14441 "was not present in the entry")))
14443 (defun org-delete-property-globally (property)
14444 "Remove PROPERTY globally, from all entries."
14445 (interactive
14446 (let* ((completion-ignore-case t)
14447 (prop (org-icompleting-read
14448 "Globally remove property: "
14449 (mapcar 'list (org-buffer-property-keys)))))
14450 (list prop)))
14451 (save-excursion
14452 (save-restriction
14453 (widen)
14454 (goto-char (point-min))
14455 (let ((cnt 0))
14456 (while (re-search-forward
14457 (org-re-property property)
14458 nil t)
14459 (setq cnt (1+ cnt))
14460 (replace-match ""))
14461 (message "Property \"%s\" removed from %d entries" property cnt)))))
14463 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14465 (defun org-compute-property-at-point ()
14466 "Compute the property at point.
14467 This looks for an enclosing column format, extracts the operator and
14468 then applies it to the property in the column format's scope."
14469 (interactive)
14470 (unless (org-at-property-p)
14471 (error "Not at a property"))
14472 (let ((prop (org-match-string-no-properties 2)))
14473 (org-columns-get-format-and-top-level)
14474 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14475 (error "No operator defined for property %s" prop))
14476 (org-columns-compute prop)))
14478 (defvar org-property-allowed-value-functions nil
14479 "Hook for functions supplying allowed values for a specific property.
14480 The functions must take a single argument, the name of the property, and
14481 return a flat list of allowed values. If \":ETC\" is one of
14482 the values, this means that these values are intended as defaults for
14483 completion, but that other values should be allowed too.
14484 The functions must return nil if they are not responsible for this
14485 property.")
14487 (defun org-property-get-allowed-values (pom property &optional table)
14488 "Get allowed values for the property PROPERTY.
14489 When TABLE is non-nil, return an alist that can directly be used for
14490 completion."
14491 (let (vals)
14492 (cond
14493 ((equal property "TODO")
14494 (setq vals (org-with-point-at pom
14495 (append org-todo-keywords-1 '("")))))
14496 ((equal property "PRIORITY")
14497 (let ((n org-lowest-priority))
14498 (while (>= n org-highest-priority)
14499 (push (char-to-string n) vals)
14500 (setq n (1- n)))))
14501 ((member property org-special-properties))
14502 ((setq vals (run-hook-with-args-until-success
14503 'org-property-allowed-value-functions property)))
14505 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14506 (when (and vals (string-match "\\S-" vals))
14507 (setq vals (car (read-from-string (concat "(" vals ")"))))
14508 (setq vals (mapcar (lambda (x)
14509 (cond ((stringp x) x)
14510 ((numberp x) (number-to-string x))
14511 ((symbolp x) (symbol-name x))
14512 (t "???")))
14513 vals)))))
14514 (when (member ":ETC" vals)
14515 (setq vals (remove ":ETC" vals))
14516 (org-add-props (car vals) '(org-unrestricted t)))
14517 (if table (mapcar 'list vals) vals)))
14519 (defun org-property-previous-allowed-value (&optional previous)
14520 "Switch to the next allowed value for this property."
14521 (interactive)
14522 (org-property-next-allowed-value t))
14524 (defun org-property-next-allowed-value (&optional previous)
14525 "Switch to the next allowed value for this property."
14526 (interactive)
14527 (unless (org-at-property-p)
14528 (error "Not at a property"))
14529 (let* ((key (match-string 2))
14530 (value (match-string 3))
14531 (allowed (or (org-property-get-allowed-values (point) key)
14532 (and (member value '("[ ]" "[-]" "[X]"))
14533 '("[ ]" "[X]"))))
14534 nval)
14535 (unless allowed
14536 (error "Allowed values for this property have not been defined"))
14537 (if previous (setq allowed (reverse allowed)))
14538 (if (member value allowed)
14539 (setq nval (car (cdr (member value allowed)))))
14540 (setq nval (or nval (car allowed)))
14541 (if (equal nval value)
14542 (error "Only one allowed value for this property"))
14543 (org-at-property-p)
14544 (replace-match (concat " :" key ": " nval) t t)
14545 (org-indent-line-function)
14546 (beginning-of-line 1)
14547 (skip-chars-forward " \t")
14548 (run-hook-with-args 'org-property-changed-functions key nval)))
14550 (defun org-find-olp (path &optional this-buffer)
14551 "Return a marker pointing to the entry at outline path OLP.
14552 If anything goes wrong, throw an error.
14553 You can wrap this call to catch the error like this:
14555 (condition-case msg
14556 (org-mobile-locate-entry (match-string 4))
14557 (error (nth 1 msg)))
14559 The return value will then be either a string with the error message,
14560 or a marker if everything is OK.
14562 If THIS-BUFFER is set, the outline path does not contain a file,
14563 only headings."
14564 (let* ((file (if this-buffer buffer-file-name (pop path)))
14565 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14566 (level 1)
14567 (lmin 1)
14568 (lmax 1)
14569 limit re end found pos heading cnt flevel)
14570 (unless buffer (error "File not found :%s" file))
14571 (with-current-buffer buffer
14572 (save-excursion
14573 (save-restriction
14574 (widen)
14575 (setq limit (point-max))
14576 (goto-char (point-min))
14577 (while (setq heading (pop path))
14578 (setq re (format org-complex-heading-regexp-format
14579 (regexp-quote heading)))
14580 (setq cnt 0 pos (point))
14581 (while (re-search-forward re end t)
14582 (setq level (- (match-end 1) (match-beginning 1)))
14583 (if (and (>= level lmin) (<= level lmax))
14584 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
14585 (when (= cnt 0) (error "Heading not found on level %d: %s"
14586 lmax heading))
14587 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14588 lmax heading))
14589 (goto-char found)
14590 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
14591 (setq end (save-excursion (org-end-of-subtree t t))))
14592 (when (org-on-heading-p)
14593 (move-marker (make-marker) (point))))))))
14595 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14596 "Find node HEADING in BUFFER.
14597 Return a marker to the heading if it was found, or nil if not.
14598 If POS-ONLY is set, return just the position instead of a marker.
14600 The heading text must match exact, but it may have a TODO keyword,
14601 a priority cookie and tags in the standard locations."
14602 (with-current-buffer (or buffer (current-buffer))
14603 (save-excursion
14604 (save-restriction
14605 (widen)
14606 (goto-char (point-min))
14607 (let (case-fold-search)
14608 (if (re-search-forward
14609 (format org-complex-heading-regexp-format
14610 (regexp-quote heading)) nil t)
14611 (if pos-only
14612 (match-beginning 0)
14613 (move-marker (make-marker) (match-beginning 0)))))))))
14615 (defun org-find-exact-heading-in-directory (heading &optional dir)
14616 "Find Org node headline HEADING in all .org files in directory DIR.
14617 When the target headline is found, return a marker to this location."
14618 (let ((files (directory-files (or dir default-directory)
14619 nil "\\`[^.#].*\\.org\\'"))
14620 file visiting m buffer)
14621 (catch 'found
14622 (while (setq file (pop files))
14623 (message "trying %s" file)
14624 (setq visiting (org-find-base-buffer-visiting file))
14625 (setq buffer (or visiting (find-file-noselect file)))
14626 (setq m (org-find-exact-headline-in-buffer
14627 heading buffer))
14628 (when (and (not m) (not visiting)) (kill-buffer buffer))
14629 (and m (throw 'found m))))))
14631 (defun org-find-entry-with-id (ident)
14632 "Locate the entry that contains the ID property with exact value IDENT.
14633 IDENT can be a string, a symbol or a number, this function will search for
14634 the string representation of it.
14635 Return the position where this entry starts, or nil if there is no such entry."
14636 (interactive "sID: ")
14637 (let ((id (cond
14638 ((stringp ident) ident)
14639 ((symbol-name ident) (symbol-name ident))
14640 ((numberp ident) (number-to-string ident))
14641 (t (error "IDENT %s must be a string, symbol or number" ident))))
14642 (case-fold-search nil))
14643 (save-excursion
14644 (save-restriction
14645 (widen)
14646 (goto-char (point-min))
14647 (when (re-search-forward
14648 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
14649 nil t)
14650 (org-back-to-heading t)
14651 (point))))))
14653 ;;;; Timestamps
14655 (defvar org-last-changed-timestamp nil)
14656 (defvar org-last-inserted-timestamp nil
14657 "The last time stamp inserted with `org-insert-time-stamp'.")
14658 (defvar org-time-was-given) ; dynamically scoped parameter
14659 (defvar org-end-time-was-given) ; dynamically scoped parameter
14660 (defvar org-ts-what) ; dynamically scoped parameter
14662 (defun org-time-stamp (arg &optional inactive)
14663 "Prompt for a date/time and insert a time stamp.
14664 If the user specifies a time like HH:MM, or if this command is called
14665 with a prefix argument, the time stamp will contain date and time.
14666 Otherwise, only the date will be included. All parts of a date not
14667 specified by the user will be filled in from the current date/time.
14668 So if you press just return without typing anything, the time stamp
14669 will represent the current date/time. If there is already a timestamp
14670 at the cursor, it will be modified."
14671 (interactive "P")
14672 (let* ((ts nil)
14673 (default-time
14674 ;; Default time is either today, or, when entering a range,
14675 ;; the range start.
14676 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
14677 (save-excursion
14678 (re-search-backward
14679 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
14680 (- (point) 20) t)))
14681 (apply 'encode-time (org-parse-time-string (match-string 1)))
14682 (current-time)))
14683 (default-input (and ts (org-get-compact-tod ts)))
14684 (repeater (save-excursion
14685 (save-match-data
14686 (beginning-of-line)
14687 (when (re-search-forward
14688 "\\([.+-]+[0-9]+[dwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
14689 (save-excursion (progn (end-of-line) (point))) t)
14690 (match-string 0)))))
14691 org-time-was-given org-end-time-was-given time)
14692 (cond
14693 ((and (org-at-timestamp-p t)
14694 (memq last-command '(org-time-stamp org-time-stamp-inactive))
14695 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
14696 (insert "--")
14697 (setq time (let ((this-command this-command))
14698 (org-read-date arg 'totime nil nil
14699 default-time default-input)))
14700 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
14701 ((org-at-timestamp-p t)
14702 (setq time (let ((this-command this-command))
14703 (org-read-date arg 'totime nil nil default-time default-input)))
14704 (when (org-at-timestamp-p t) ; just to get the match data
14705 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
14706 (replace-match "")
14707 (setq org-last-changed-timestamp
14708 (org-insert-time-stamp
14709 time (or org-time-was-given arg)
14710 inactive nil nil (list org-end-time-was-given)))
14711 (when repeater (goto-char (1- (point))) (insert " " repeater)
14712 (setq org-last-changed-timestamp
14713 (concat (substring org-last-inserted-timestamp 0 -1)
14714 " " repeater ">"))))
14715 (message "Timestamp updated"))
14717 (setq time (let ((this-command this-command))
14718 (org-read-date arg 'totime nil nil default-time default-input)))
14719 (org-insert-time-stamp time (or org-time-was-given arg) inactive
14720 nil nil (list org-end-time-was-given))))))
14722 ;; FIXME: can we use this for something else, like computing time differences?
14723 (defun org-get-compact-tod (s)
14724 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
14725 (let* ((t1 (match-string 1 s))
14726 (h1 (string-to-number (match-string 2 s)))
14727 (m1 (string-to-number (match-string 3 s)))
14728 (t2 (and (match-end 4) (match-string 5 s)))
14729 (h2 (and t2 (string-to-number (match-string 6 s))))
14730 (m2 (and t2 (string-to-number (match-string 7 s))))
14731 dh dm)
14732 (if (not t2)
14734 (setq dh (- h2 h1) dm (- m2 m1))
14735 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
14736 (concat t1 "+" (number-to-string dh)
14737 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
14739 (defun org-time-stamp-inactive (&optional arg)
14740 "Insert an inactive time stamp.
14741 An inactive time stamp is enclosed in square brackets instead of angle
14742 brackets. It is inactive in the sense that it does not trigger agenda entries,
14743 does not link to the calendar and cannot be changed with the S-cursor keys.
14744 So these are more for recording a certain time/date."
14745 (interactive "P")
14746 (org-time-stamp arg 'inactive))
14748 (defvar org-date-ovl (make-overlay 1 1))
14749 (overlay-put org-date-ovl 'face 'org-warning)
14750 (org-detach-overlay org-date-ovl)
14752 (defvar org-ans1) ; dynamically scoped parameter
14753 (defvar org-ans2) ; dynamically scoped parameter
14755 (defvar org-plain-time-of-day-regexp) ; defined below
14757 (defvar org-overriding-default-time nil) ; dynamically scoped
14758 (defvar org-read-date-overlay nil)
14759 (defvar org-dcst nil) ; dynamically scoped
14760 (defvar org-read-date-history nil)
14761 (defvar org-read-date-final-answer nil)
14762 (defvar org-read-date-analyze-futurep nil)
14763 (defvar org-read-date-analyze-forced-year nil)
14765 (defun org-read-date (&optional with-time to-time from-string prompt
14766 default-time default-input)
14767 "Read a date, possibly a time, and make things smooth for the user.
14768 The prompt will suggest to enter an ISO date, but you can also enter anything
14769 which will at least partially be understood by `parse-time-string'.
14770 Unrecognized parts of the date will default to the current day, month, year,
14771 hour and minute. If this command is called to replace a timestamp at point,
14772 of to enter the second timestamp of a range, the default time is taken
14773 from the existing stamp. Furthermore, the command prefers the future,
14774 so if you are giving a date where the year is not given, and the day-month
14775 combination is already past in the current year, it will assume you
14776 mean next year. For details, see the manual. A few examples:
14778 3-2-5 --> 2003-02-05
14779 feb 15 --> currentyear-02-15
14780 2/15 --> currentyear-02-15
14781 sep 12 9 --> 2009-09-12
14782 12:45 --> today 12:45
14783 22 sept 0:34 --> currentyear-09-22 0:34
14784 12 --> currentyear-currentmonth-12
14785 Fri --> nearest Friday (today or later)
14786 etc.
14788 Furthermore you can specify a relative date by giving, as the *first* thing
14789 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
14790 change in days weeks, months, years.
14791 With a single plus or minus, the date is relative to today. With a double
14792 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
14793 +4d --> four days from today
14794 +4 --> same as above
14795 +2w --> two weeks from today
14796 ++5 --> five days from default date
14798 The function understands only English month and weekday abbreviations,
14799 but this can be configured with the variables `parse-time-months' and
14800 `parse-time-weekdays'.
14802 While prompting, a calendar is popped up - you can also select the
14803 date with the mouse (button 1). The calendar shows a period of three
14804 months. To scroll it to other months, use the keys `>' and `<'.
14805 If you don't like the calendar, turn it off with
14806 \(setq org-read-date-popup-calendar nil)
14808 With optional argument TO-TIME, the date will immediately be converted
14809 to an internal time.
14810 With an optional argument WITH-TIME, the prompt will suggest to also
14811 insert a time. Note that when WITH-TIME is not set, you can still
14812 enter a time, and this function will inform the calling routine about
14813 this change. The calling routine may then choose to change the format
14814 used to insert the time stamp into the buffer to include the time.
14815 With optional argument FROM-STRING, read from this string instead from
14816 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
14817 the time/date that is used for everything that is not specified by the
14818 user."
14819 (require 'parse-time)
14820 (let* ((org-time-stamp-rounding-minutes
14821 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
14822 (org-dcst org-display-custom-times)
14823 (ct (org-current-time))
14824 (def (or org-overriding-default-time default-time ct))
14825 (defdecode (decode-time def))
14826 (dummy (progn
14827 (when (< (nth 2 defdecode) org-extend-today-until)
14828 (setcar (nthcdr 2 defdecode) -1)
14829 (setcar (nthcdr 1 defdecode) 59)
14830 (setq def (apply 'encode-time defdecode)
14831 defdecode (decode-time def)))))
14832 (calendar-frame-setup nil)
14833 (calendar-setup nil)
14834 (calendar-move-hook nil)
14835 (calendar-view-diary-initially-flag nil)
14836 (calendar-view-holidays-initially-flag nil)
14837 (timestr (format-time-string
14838 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
14839 (prompt (concat (if prompt (concat prompt " ") "")
14840 (format "Date+time [%s]: " timestr)))
14841 ans (org-ans0 "") org-ans1 org-ans2 final)
14843 (cond
14844 (from-string (setq ans from-string))
14845 (org-read-date-popup-calendar
14846 (save-excursion
14847 (save-window-excursion
14848 (calendar)
14849 (unwind-protect
14850 (progn
14851 (calendar-forward-day (- (time-to-days def)
14852 (calendar-absolute-from-gregorian
14853 (calendar-current-date))))
14854 (org-eval-in-calendar nil t)
14855 (let* ((old-map (current-local-map))
14856 (map (copy-keymap calendar-mode-map))
14857 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
14858 (org-defkey map (kbd "RET") 'org-calendar-select)
14859 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
14860 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
14861 (org-defkey minibuffer-local-map [(meta shift left)]
14862 (lambda () (interactive)
14863 (org-eval-in-calendar '(calendar-backward-month 1))))
14864 (org-defkey minibuffer-local-map [(meta shift right)]
14865 (lambda () (interactive)
14866 (org-eval-in-calendar '(calendar-forward-month 1))))
14867 (org-defkey minibuffer-local-map [(meta shift up)]
14868 (lambda () (interactive)
14869 (org-eval-in-calendar '(calendar-backward-year 1))))
14870 (org-defkey minibuffer-local-map [(meta shift down)]
14871 (lambda () (interactive)
14872 (org-eval-in-calendar '(calendar-forward-year 1))))
14873 (org-defkey minibuffer-local-map [?\e (shift left)]
14874 (lambda () (interactive)
14875 (org-eval-in-calendar '(calendar-backward-month 1))))
14876 (org-defkey minibuffer-local-map [?\e (shift right)]
14877 (lambda () (interactive)
14878 (org-eval-in-calendar '(calendar-forward-month 1))))
14879 (org-defkey minibuffer-local-map [?\e (shift up)]
14880 (lambda () (interactive)
14881 (org-eval-in-calendar '(calendar-backward-year 1))))
14882 (org-defkey minibuffer-local-map [?\e (shift down)]
14883 (lambda () (interactive)
14884 (org-eval-in-calendar '(calendar-forward-year 1))))
14885 (org-defkey minibuffer-local-map [(shift up)]
14886 (lambda () (interactive)
14887 (org-eval-in-calendar '(calendar-backward-week 1))))
14888 (org-defkey minibuffer-local-map [(shift down)]
14889 (lambda () (interactive)
14890 (org-eval-in-calendar '(calendar-forward-week 1))))
14891 (org-defkey minibuffer-local-map [(shift left)]
14892 (lambda () (interactive)
14893 (org-eval-in-calendar '(calendar-backward-day 1))))
14894 (org-defkey minibuffer-local-map [(shift right)]
14895 (lambda () (interactive)
14896 (org-eval-in-calendar '(calendar-forward-day 1))))
14897 (org-defkey minibuffer-local-map ">"
14898 (lambda () (interactive)
14899 (org-eval-in-calendar '(scroll-calendar-left 1))))
14900 (org-defkey minibuffer-local-map "<"
14901 (lambda () (interactive)
14902 (org-eval-in-calendar '(scroll-calendar-right 1))))
14903 (org-defkey minibuffer-local-map "\C-v"
14904 (lambda () (interactive)
14905 (org-eval-in-calendar
14906 '(calendar-scroll-left-three-months 1))))
14907 (org-defkey minibuffer-local-map "\M-v"
14908 (lambda () (interactive)
14909 (org-eval-in-calendar
14910 '(calendar-scroll-right-three-months 1))))
14911 (run-hooks 'org-read-date-minibuffer-setup-hook)
14912 (unwind-protect
14913 (progn
14914 (use-local-map map)
14915 (add-hook 'post-command-hook 'org-read-date-display)
14916 (setq org-ans0 (read-string prompt default-input
14917 'org-read-date-history nil))
14918 ;; org-ans0: from prompt
14919 ;; org-ans1: from mouse click
14920 ;; org-ans2: from calendar motion
14921 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
14922 (remove-hook 'post-command-hook 'org-read-date-display)
14923 (use-local-map old-map)
14924 (when org-read-date-overlay
14925 (delete-overlay org-read-date-overlay)
14926 (setq org-read-date-overlay nil)))))
14927 (bury-buffer "*Calendar*")))))
14929 (t ; Naked prompt only
14930 (unwind-protect
14931 (setq ans (read-string prompt default-input
14932 'org-read-date-history timestr))
14933 (when org-read-date-overlay
14934 (delete-overlay org-read-date-overlay)
14935 (setq org-read-date-overlay nil)))))
14937 (setq final (org-read-date-analyze ans def defdecode))
14939 (when org-read-date-analyze-forced-year
14940 (message "Year was forced into %s"
14941 (if org-read-date-force-compatible-dates
14942 "compatible range (1970-2037)"
14943 "range representable on this machine"))
14944 (ding))
14946 ;; One round trip to get rid of 34th of August and stuff like that....
14947 (setq final (decode-time (apply 'encode-time final)))
14949 (setq org-read-date-final-answer ans)
14951 (if to-time
14952 (apply 'encode-time final)
14953 (if (and (boundp 'org-time-was-given) org-time-was-given)
14954 (format "%04d-%02d-%02d %02d:%02d"
14955 (nth 5 final) (nth 4 final) (nth 3 final)
14956 (nth 2 final) (nth 1 final))
14957 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
14959 (defvar def)
14960 (defvar defdecode)
14961 (defvar with-time)
14962 (defun org-read-date-display ()
14963 "Display the current date prompt interpretation in the minibuffer."
14964 (when org-read-date-display-live
14965 (when org-read-date-overlay
14966 (delete-overlay org-read-date-overlay))
14967 (let ((p (point)))
14968 (end-of-line 1)
14969 (while (not (equal (buffer-substring
14970 (max (point-min) (- (point) 4)) (point))
14971 " "))
14972 (insert " "))
14973 (goto-char p))
14974 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
14975 " " (or org-ans1 org-ans2)))
14976 (org-end-time-was-given nil)
14977 (f (org-read-date-analyze ans def defdecode))
14978 (fmts (if org-dcst
14979 org-time-stamp-custom-formats
14980 org-time-stamp-formats))
14981 (fmt (if (or with-time
14982 (and (boundp 'org-time-was-given) org-time-was-given))
14983 (cdr fmts)
14984 (car fmts)))
14985 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
14986 (when (and org-end-time-was-given
14987 (string-match org-plain-time-of-day-regexp txt))
14988 (setq txt (concat (substring txt 0 (match-end 0)) "-"
14989 org-end-time-was-given
14990 (substring txt (match-end 0)))))
14991 (when org-read-date-analyze-futurep
14992 (setq txt (concat txt " (=>F)")))
14993 (setq org-read-date-overlay
14994 (make-overlay (1- (point-at-eol)) (point-at-eol)))
14995 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
14997 (defun org-read-date-analyze (ans def defdecode)
14998 "Analyze the combined answer of the date prompt."
14999 ;; FIXME: cleanup and comment
15000 (let ((nowdecode (decode-time (current-time)))
15001 delta deltan deltaw deltadef year month day
15002 hour minute second wday pm h2 m2 tl wday1
15003 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15004 (setq org-read-date-analyze-futurep nil
15005 org-read-date-analyze-forced-year nil)
15006 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15007 (setq ans "+0"))
15009 (when (setq delta (org-read-date-get-relative ans (current-time) def))
15010 (setq ans (replace-match "" t t ans)
15011 deltan (car delta)
15012 deltaw (nth 1 delta)
15013 deltadef (nth 2 delta)))
15015 ;; Check if there is an iso week date in there
15016 ;; If yes, store the info and postpone interpreting it until the rest
15017 ;; of the parsing is done
15018 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15019 (setq iso-year (if (match-end 1)
15020 (org-small-year-to-year
15021 (string-to-number (match-string 1 ans))))
15022 iso-weekday (if (match-end 3)
15023 (string-to-number (match-string 3 ans)))
15024 iso-week (string-to-number (match-string 2 ans)))
15025 (setq ans (replace-match "" t t ans)))
15027 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15028 (when (string-match
15029 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15030 (setq year (if (match-end 2)
15031 (string-to-number (match-string 2 ans))
15032 (progn (setq kill-year t)
15033 (string-to-number (format-time-string "%Y"))))
15034 month (string-to-number (match-string 3 ans))
15035 day (string-to-number (match-string 4 ans)))
15036 (if (< year 100) (setq year (+ 2000 year)))
15037 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15038 t nil ans)))
15040 ;; Help matching dottet european dates
15041 (when (string-match
15042 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15043 (setq year (if (match-end 3)
15044 (string-to-number (match-string 3 ans))
15045 (progn (setq kill-year t)
15046 (string-to-number (format-time-string "%Y"))))
15047 day (string-to-number (match-string 1 ans))
15048 month (string-to-number (match-string 2 ans))
15049 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15050 t nil ans)))
15052 ;; Help matching american dates, like 5/30 or 5/30/7
15053 (when (string-match
15054 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15055 (setq year (if (match-end 4)
15056 (string-to-number (match-string 4 ans))
15057 (progn (setq kill-year t)
15058 (string-to-number (format-time-string "%Y"))))
15059 month (string-to-number (match-string 1 ans))
15060 day (string-to-number (match-string 2 ans)))
15061 (if (< year 100) (setq year (+ 2000 year)))
15062 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15063 t nil ans)))
15064 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15065 ;; If there is a time with am/pm, and *no* time without it, we convert
15066 ;; so that matching will be successful.
15067 (loop for i from 1 to 2 do ; twice, for end time as well
15068 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15069 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15070 (setq hour (string-to-number (match-string 1 ans))
15071 minute (if (match-end 3)
15072 (string-to-number (match-string 3 ans))
15074 pm (equal ?p
15075 (string-to-char (downcase (match-string 4 ans)))))
15076 (if (and (= hour 12) (not pm))
15077 (setq hour 0)
15078 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15079 (setq ans (replace-match (format "%02d:%02d" hour minute)
15080 t t ans))))
15082 ;; Check if a time range is given as a duration
15083 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15084 (setq hour (string-to-number (match-string 1 ans))
15085 h2 (+ hour (string-to-number (match-string 3 ans)))
15086 minute (string-to-number (match-string 2 ans))
15087 m2 (+ minute (if (match-end 5) (string-to-number
15088 (match-string 5 ans))0)))
15089 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15090 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15091 t t ans)))
15093 ;; Check if there is a time range
15094 (when (boundp 'org-end-time-was-given)
15095 (setq org-time-was-given nil)
15096 (when (and (string-match org-plain-time-of-day-regexp ans)
15097 (match-end 8))
15098 (setq org-end-time-was-given (match-string 8 ans))
15099 (setq ans (concat (substring ans 0 (match-beginning 7))
15100 (substring ans (match-end 7))))))
15102 (setq tl (parse-time-string ans)
15103 day (or (nth 3 tl) (nth 3 defdecode))
15104 month (or (nth 4 tl)
15105 (if (and org-read-date-prefer-future
15106 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15107 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15108 (nth 4 defdecode)))
15109 year (or (and (not kill-year) (nth 5 tl))
15110 (if (and org-read-date-prefer-future
15111 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15112 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15113 (nth 5 defdecode)))
15114 hour (or (nth 2 tl) (nth 2 defdecode))
15115 minute (or (nth 1 tl) (nth 1 defdecode))
15116 second (or (nth 0 tl) 0)
15117 wday (nth 6 tl))
15119 (when (and (eq org-read-date-prefer-future 'time)
15120 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15121 (equal day (nth 3 nowdecode))
15122 (equal month (nth 4 nowdecode))
15123 (equal year (nth 5 nowdecode))
15124 (nth 2 tl)
15125 (or (< (nth 2 tl) (nth 2 nowdecode))
15126 (and (= (nth 2 tl) (nth 2 nowdecode))
15127 (nth 1 tl)
15128 (< (nth 1 tl) (nth 1 nowdecode)))))
15129 (setq day (1+ day)
15130 futurep t))
15132 ;; Special date definitions below
15133 (cond
15134 (iso-week
15135 ;; There was an iso week
15136 (require 'cal-iso)
15137 (setq futurep nil)
15138 (setq year (or iso-year year)
15139 day (or iso-weekday wday 1)
15140 wday nil ; to make sure that the trigger below does not match
15141 iso-date (calendar-gregorian-from-absolute
15142 (calendar-absolute-from-iso
15143 (list iso-week day year))))
15144 ; FIXME: Should we also push ISO weeks into the future?
15145 ; (when (and org-read-date-prefer-future
15146 ; (not iso-year)
15147 ; (< (calendar-absolute-from-gregorian iso-date)
15148 ; (time-to-days (current-time))))
15149 ; (setq year (1+ year)
15150 ; iso-date (calendar-gregorian-from-absolute
15151 ; (calendar-absolute-from-iso
15152 ; (list iso-week day year)))))
15153 (setq month (car iso-date)
15154 year (nth 2 iso-date)
15155 day (nth 1 iso-date)))
15156 (deltan
15157 (setq futurep nil)
15158 (unless deltadef
15159 (let ((now (decode-time (current-time))))
15160 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15161 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15162 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15163 ((equal deltaw "m") (setq month (+ month deltan)))
15164 ((equal deltaw "y") (setq year (+ year deltan)))))
15165 ((and wday (not (nth 3 tl)))
15166 (setq futurep nil)
15167 ;; Weekday was given, but no day, so pick that day in the week
15168 ;; on or after the derived date.
15169 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15170 (unless (equal wday wday1)
15171 (setq day (+ day (% (- wday wday1 -7) 7))))))
15172 (if (and (boundp 'org-time-was-given)
15173 (nth 2 tl))
15174 (setq org-time-was-given t))
15175 (if (< year 100) (setq year (+ 2000 year)))
15176 ;; Check of the date is representable
15177 (if org-read-date-force-compatible-dates
15178 (progn
15179 (if (< year 1970)
15180 (setq year 1970 org-read-date-analyze-forced-year t))
15181 (if (> year 2037)
15182 (setq year 2037 org-read-date-analyze-forced-year t)))
15183 (condition-case nil
15184 (ignore (encode-time second minute hour day month year))
15185 (error
15186 (setq year (nth 5 defdecode))
15187 (setq org-read-date-analyze-forced-year t))))
15188 (setq org-read-date-analyze-futurep futurep)
15189 (list second minute hour day month year)))
15191 (defvar parse-time-weekdays)
15193 (defun org-read-date-get-relative (s today default)
15194 "Check string S for special relative date string.
15195 TODAY and DEFAULT are internal times, for today and for a default.
15196 Return shift list (N what def-flag)
15197 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15198 N is the number of WHATs to shift.
15199 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15200 the DEFAULT date rather than TODAY."
15201 (when (and
15202 (string-match
15203 (concat
15204 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15205 "\\([0-9]+\\)?"
15206 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15207 "\\([ \t]\\|$\\)") s)
15208 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15209 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15210 (string-to-char (substring (match-string 1 s) -1))
15211 ?+))
15212 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15213 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15214 (what (if (match-end 3) (match-string 3 s) "d"))
15215 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15216 (date (if rel default today))
15217 (wday (nth 6 (decode-time date)))
15218 delta)
15219 (if wday1
15220 (progn
15221 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15222 (if (= dir ?-) (setq delta (- delta 7)))
15223 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15224 (list delta "d" rel))
15225 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15227 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15228 "Turn a user-specified date into the internal representation.
15229 The internal representation needed by the calendar is (month day year).
15230 This is a wrapper to handle the brain-dead convention in calendar that
15231 user function argument order change dependent on argument order."
15232 (if (boundp 'calendar-date-style)
15233 (cond
15234 ((eq calendar-date-style 'american)
15235 (list arg1 arg2 arg3))
15236 ((eq calendar-date-style 'european)
15237 (list arg2 arg1 arg3))
15238 ((eq calendar-date-style 'iso)
15239 (list arg2 arg3 arg1)))
15240 (with-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15241 (if (org-bound-and-true-p european-calendar-style)
15242 (list arg2 arg1 arg3)
15243 (list arg1 arg2 arg3)))))
15245 (defun org-eval-in-calendar (form &optional keepdate)
15246 "Eval FORM in the calendar window and return to current window.
15247 Also, store the cursor date in variable org-ans2."
15248 (let ((sf (selected-frame))
15249 (sw (selected-window)))
15250 (select-window (get-buffer-window "*Calendar*" t))
15251 (eval form)
15252 (when (and (not keepdate) (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-ans2 (format-time-string "%Y-%m-%d" time))))
15256 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15257 (select-window sw)
15258 (org-select-frame-set-input-focus sf)))
15260 (defun org-calendar-select ()
15261 "Return to `org-read-date' with the date currently selected.
15262 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15263 (interactive)
15264 (when (calendar-cursor-to-date)
15265 (let* ((date (calendar-cursor-to-date))
15266 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15267 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15268 (if (active-minibuffer-window) (exit-minibuffer))))
15270 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15271 "Insert a date stamp for the date given by the internal TIME.
15272 WITH-HM means use the stamp format that includes the time of the day.
15273 INACTIVE means use square brackets instead of angular ones, so that the
15274 stamp will not contribute to the agenda.
15275 PRE and POST are optional strings to be inserted before and after the
15276 stamp.
15277 The command returns the inserted time stamp."
15278 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15279 stamp)
15280 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15281 (insert-before-markers (or pre ""))
15282 (when (listp extra)
15283 (setq extra (car extra))
15284 (if (and (stringp extra)
15285 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15286 (setq extra (format "-%02d:%02d"
15287 (string-to-number (match-string 1 extra))
15288 (string-to-number (match-string 2 extra))))
15289 (setq extra nil)))
15290 (when extra
15291 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15292 (insert-before-markers (setq stamp (format-time-string fmt time)))
15293 (insert-before-markers (or post ""))
15294 (setq org-last-inserted-timestamp stamp)))
15296 (defun org-toggle-time-stamp-overlays ()
15297 "Toggle the use of custom time stamp formats."
15298 (interactive)
15299 (setq org-display-custom-times (not org-display-custom-times))
15300 (unless org-display-custom-times
15301 (let ((p (point-min)) (bmp (buffer-modified-p)))
15302 (while (setq p (next-single-property-change p 'display))
15303 (if (and (get-text-property p 'display)
15304 (eq (get-text-property p 'face) 'org-date))
15305 (remove-text-properties
15306 p (setq p (next-single-property-change p 'display))
15307 '(display t))))
15308 (set-buffer-modified-p bmp)))
15309 (if (featurep 'xemacs)
15310 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15311 (org-restart-font-lock)
15312 (setq org-table-may-need-update t)
15313 (if org-display-custom-times
15314 (message "Time stamps are overlayed with custom format")
15315 (message "Time stamp overlays removed")))
15317 (defun org-display-custom-time (beg end)
15318 "Overlay modified time stamp format over timestamp between BEG and END."
15319 (let* ((ts (buffer-substring beg end))
15320 t1 w1 with-hm tf time str w2 (off 0))
15321 (save-match-data
15322 (setq t1 (org-parse-time-string ts t))
15323 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
15324 (setq off (- (match-end 0) (match-beginning 0)))))
15325 (setq end (- end off))
15326 (setq w1 (- end beg)
15327 with-hm (and (nth 1 t1) (nth 2 t1))
15328 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15329 time (org-fix-decoded-time t1)
15330 str (org-add-props
15331 (format-time-string
15332 (substring tf 1 -1) (apply 'encode-time time))
15333 nil 'mouse-face 'highlight)
15334 w2 (length str))
15335 (if (not (= w2 w1))
15336 (add-text-properties (1+ beg) (+ 2 beg)
15337 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15338 (if (featurep 'xemacs)
15339 (progn
15340 (put-text-property beg end 'invisible t)
15341 (put-text-property beg end 'end-glyph (make-glyph str)))
15342 (put-text-property beg end 'display str))))
15344 (defun org-translate-time (string)
15345 "Translate all timestamps in STRING to custom format.
15346 But do this only if the variable `org-display-custom-times' is set."
15347 (when org-display-custom-times
15348 (save-match-data
15349 (let* ((start 0)
15350 (re org-ts-regexp-both)
15351 t1 with-hm inactive tf time str beg end)
15352 (while (setq start (string-match re string start))
15353 (setq beg (match-beginning 0)
15354 end (match-end 0)
15355 t1 (save-match-data
15356 (org-parse-time-string (substring string beg end) t))
15357 with-hm (and (nth 1 t1) (nth 2 t1))
15358 inactive (equal (substring string beg (1+ beg)) "[")
15359 tf (funcall (if with-hm 'cdr 'car)
15360 org-time-stamp-custom-formats)
15361 time (org-fix-decoded-time t1)
15362 str (format-time-string
15363 (concat
15364 (if inactive "[" "<") (substring tf 1 -1)
15365 (if inactive "]" ">"))
15366 (apply 'encode-time time))
15367 string (replace-match str t t string)
15368 start (+ start (length str)))))))
15369 string)
15371 (defun org-fix-decoded-time (time)
15372 "Set 0 instead of nil for the first 6 elements of time.
15373 Don't touch the rest."
15374 (let ((n 0))
15375 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15377 (defun org-days-to-time (timestamp-string)
15378 "Difference between TIMESTAMP-STRING and now in days."
15379 (- (time-to-days (org-time-string-to-time timestamp-string))
15380 (time-to-days (current-time))))
15382 (defun org-deadline-close (timestamp-string &optional ndays)
15383 "Is the time in TIMESTAMP-STRING close to the current date?"
15384 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15385 (and (< (org-days-to-time timestamp-string) ndays)
15386 (not (org-entry-is-done-p))))
15388 (defun org-get-wdays (ts)
15389 "Get the deadline lead time appropriate for timestring TS."
15390 (cond
15391 ((<= org-deadline-warning-days 0)
15392 ;; 0 or negative, enforce this value no matter what
15393 (- org-deadline-warning-days))
15394 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
15395 ;; lead time is specified.
15396 (floor (* (string-to-number (match-string 1 ts))
15397 (cdr (assoc (match-string 2 ts)
15398 '(("d" . 1) ("w" . 7)
15399 ("m" . 30.4) ("y" . 365.25)))))))
15400 ;; go for the default.
15401 (t org-deadline-warning-days)))
15403 (defun org-calendar-select-mouse (ev)
15404 "Return to `org-read-date' with the date currently selected.
15405 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15406 (interactive "e")
15407 (mouse-set-point ev)
15408 (when (calendar-cursor-to-date)
15409 (let* ((date (calendar-cursor-to-date))
15410 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15411 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15412 (if (active-minibuffer-window) (exit-minibuffer))))
15414 (defun org-check-deadlines (ndays)
15415 "Check if there are any deadlines due or past due.
15416 A deadline is considered due if it happens within `org-deadline-warning-days'
15417 days from today's date. If the deadline appears in an entry marked DONE,
15418 it is not shown. The prefix arg NDAYS can be used to test that many
15419 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15420 (interactive "P")
15421 (let* ((org-warn-days
15422 (cond
15423 ((equal ndays '(4)) 100000)
15424 (ndays (prefix-numeric-value ndays))
15425 (t (abs org-deadline-warning-days))))
15426 (case-fold-search nil)
15427 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15428 (callback
15429 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15431 (message "%d deadlines past-due or due within %d days"
15432 (org-occur regexp nil callback)
15433 org-warn-days)))
15435 (defun org-check-before-date (date)
15436 "Check if there are deadlines or scheduled entries before DATE."
15437 (interactive (list (org-read-date)))
15438 (let ((case-fold-search nil)
15439 (regexp (concat "\\<\\(" org-deadline-string
15440 "\\|" org-scheduled-string
15441 "\\) *<\\([^>]+\\)>"))
15442 (callback
15443 (lambda () (time-less-p
15444 (org-time-string-to-time (match-string 2))
15445 (org-time-string-to-time date)))))
15446 (message "%d entries before %s"
15447 (org-occur regexp nil callback) date)))
15449 (defun org-check-after-date (date)
15450 "Check if there are deadlines or scheduled entries after DATE."
15451 (interactive (list (org-read-date)))
15452 (let ((case-fold-search nil)
15453 (regexp (concat "\\<\\(" org-deadline-string
15454 "\\|" org-scheduled-string
15455 "\\) *<\\([^>]+\\)>"))
15456 (callback
15457 (lambda () (not
15458 (time-less-p
15459 (org-time-string-to-time (match-string 2))
15460 (org-time-string-to-time date))))))
15461 (message "%d entries after %s"
15462 (org-occur regexp nil callback) date)))
15464 (defun org-evaluate-time-range (&optional to-buffer)
15465 "Evaluate a time range by computing the difference between start and end.
15466 Normally the result is just printed in the echo area, but with prefix arg
15467 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15468 If the time range is actually in a table, the result is inserted into the
15469 next column.
15470 For time difference computation, a year is assumed to be exactly 365
15471 days in order to avoid rounding problems."
15472 (interactive "P")
15474 (org-clock-update-time-maybe)
15475 (save-excursion
15476 (unless (org-at-date-range-p t)
15477 (goto-char (point-at-bol))
15478 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15479 (if (not (org-at-date-range-p t))
15480 (error "Not at a time-stamp range, and none found in current line")))
15481 (let* ((ts1 (match-string 1))
15482 (ts2 (match-string 2))
15483 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15484 (match-end (match-end 0))
15485 (time1 (org-time-string-to-time ts1))
15486 (time2 (org-time-string-to-time ts2))
15487 (t1 (org-float-time time1))
15488 (t2 (org-float-time time2))
15489 (diff (abs (- t2 t1)))
15490 (negative (< (- t2 t1) 0))
15491 ;; (ys (floor (* 365 24 60 60)))
15492 (ds (* 24 60 60))
15493 (hs (* 60 60))
15494 (fy "%dy %dd %02d:%02d")
15495 (fy1 "%dy %dd")
15496 (fd "%dd %02d:%02d")
15497 (fd1 "%dd")
15498 (fh "%02d:%02d")
15499 y d h m align)
15500 (if havetime
15501 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15503 d (floor (/ diff ds)) diff (mod diff ds)
15504 h (floor (/ diff hs)) diff (mod diff hs)
15505 m (floor (/ diff 60)))
15506 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15508 d (floor (+ (/ diff ds) 0.5))
15509 h 0 m 0))
15510 (if (not to-buffer)
15511 (message "%s" (org-make-tdiff-string y d h m))
15512 (if (org-at-table-p)
15513 (progn
15514 (goto-char match-end)
15515 (setq align t)
15516 (and (looking-at " *|") (goto-char (match-end 0))))
15517 (goto-char match-end))
15518 (if (looking-at
15519 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15520 (replace-match ""))
15521 (if negative (insert " -"))
15522 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15523 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15524 (insert " " (format fh h m))))
15525 (if align (org-table-align))
15526 (message "Time difference inserted")))))
15528 (defun org-make-tdiff-string (y d h m)
15529 (let ((fmt "")
15530 (l nil))
15531 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15532 l (push y l)))
15533 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15534 l (push d l)))
15535 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15536 l (push h l)))
15537 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15538 l (push m l)))
15539 (apply 'format fmt (nreverse l))))
15541 (defun org-time-string-to-time (s &optional buffer pos)
15542 (condition-case errdata
15543 (apply 'encode-time (org-parse-time-string s))
15544 (error (error "Bad timestamp `%s'%s\nError was: %s"
15545 s (if (not (and buffer pos))
15547 (format " at %d in buffer `%s'" pos buffer))
15548 (cdr errdata)))))
15550 (defun org-time-string-to-seconds (s)
15551 (org-float-time (org-time-string-to-time s)))
15553 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
15554 "Convert a time stamp to an absolute day number.
15555 If there is a specifier for a cyclic time stamp, get the closest date to
15556 DAYNR.
15557 PREFER and SHOW-ALL are passed through to `org-closest-date'.
15558 The variable date is bound by the calendar when this is called."
15559 (cond
15560 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15561 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15562 daynr
15563 (+ daynr 1000)))
15564 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
15565 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15566 (time-to-days (current-time))) (match-string 0 s)
15567 prefer show-all))
15568 (t (time-to-days
15569 (condition-case errdata
15570 (apply 'encode-time (org-parse-time-string s))
15571 (error (error "Bad timestamp `%s'%s\nError was: %s"
15572 s (if (not (and buffer pos))
15574 (format " at %d in buffer `%s'" pos buffer))
15575 (cdr errdata))))))))
15577 (defun org-days-to-iso-week (days)
15578 "Return the iso week number."
15579 (require 'cal-iso)
15580 (car (calendar-iso-from-absolute days)))
15582 (defun org-small-year-to-year (year)
15583 "Convert 2-digit years into 4-digit years.
15584 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15585 The year 2000 cannot be abbreviated. Any year larger than 99
15586 is returned unchanged."
15587 (if (< year 38)
15588 (setq year (+ 2000 year))
15589 (if (< year 100)
15590 (setq year (+ 1900 year))))
15591 year)
15593 (defun org-time-from-absolute (d)
15594 "Return the time corresponding to date D.
15595 D may be an absolute day number, or a calendar-type list (month day year)."
15596 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15597 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15599 (defun org-calendar-holiday ()
15600 "List of holidays, for Diary display in Org-mode."
15601 (require 'holidays)
15602 (let ((hl (funcall
15603 (if (fboundp 'calendar-check-holidays)
15604 'calendar-check-holidays 'check-calendar-holidays) date)))
15605 (if hl (mapconcat 'identity hl "; "))))
15607 (defun org-diary-sexp-entry (sexp entry date)
15608 "Process a SEXP diary ENTRY for DATE."
15609 (require 'diary-lib)
15610 (let ((result (if calendar-debug-sexp
15611 (let ((stack-trace-on-error t))
15612 (eval (car (read-from-string sexp))))
15613 (condition-case nil
15614 (eval (car (read-from-string sexp)))
15615 (error
15616 (beep)
15617 (message "Bad sexp at line %d in %s: %s"
15618 (org-current-line)
15619 (buffer-file-name) sexp)
15620 (sleep-for 2))))))
15621 (cond ((stringp result) (split-string result "; "))
15622 ((and (consp result)
15623 (not (consp (cdr result)))
15624 (stringp (cdr result))) (cdr result))
15625 ((and (consp result)
15626 (stringp (car result))) result)
15627 (result entry)
15628 (t nil))))
15630 (defun org-diary-to-ical-string (frombuf)
15631 "Get iCalendar entries from diary entries in buffer FROMBUF.
15632 This uses the icalendar.el library."
15633 (let* ((tmpdir (if (featurep 'xemacs)
15634 (temp-directory)
15635 temporary-file-directory))
15636 (tmpfile (make-temp-name
15637 (expand-file-name "orgics" tmpdir)))
15638 buf rtn b e)
15639 (with-current-buffer frombuf
15640 (icalendar-export-region (point-min) (point-max) tmpfile)
15641 (setq buf (find-buffer-visiting tmpfile))
15642 (set-buffer buf)
15643 (goto-char (point-min))
15644 (if (re-search-forward "^BEGIN:VEVENT" nil t)
15645 (setq b (match-beginning 0)))
15646 (goto-char (point-max))
15647 (if (re-search-backward "^END:VEVENT" nil t)
15648 (setq e (match-end 0)))
15649 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
15650 (kill-buffer buf)
15651 (delete-file tmpfile)
15652 rtn))
15654 (defun org-closest-date (start current change prefer show-all)
15655 "Find the date closest to CURRENT that is consistent with START and CHANGE.
15656 When PREFER is `past', return a date that is either CURRENT or past.
15657 When PREFER is `future', return a date that is either CURRENT or future.
15658 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
15659 ;; Make the proper lists from the dates
15660 (catch 'exit
15661 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
15662 dn dw sday cday n1 n2 n0
15663 d m y y1 y2 date1 date2 nmonths nm ny m2)
15665 (setq start (org-date-to-gregorian start)
15666 current (org-date-to-gregorian
15667 (if show-all
15668 current
15669 (time-to-days (current-time))))
15670 sday (calendar-absolute-from-gregorian start)
15671 cday (calendar-absolute-from-gregorian current))
15673 (if (<= cday sday) (throw 'exit sday))
15675 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
15676 (setq dn (string-to-number (match-string 1 change))
15677 dw (cdr (assoc (match-string 2 change) a1)))
15678 (error "Invalid change specifier: %s" change))
15679 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
15680 (cond
15681 ((eq dw 'day)
15682 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
15683 n2 (+ n1 dn)))
15684 ((eq dw 'year)
15685 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
15686 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
15687 (setq date1 (list m d y1)
15688 n1 (calendar-absolute-from-gregorian date1)
15689 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
15690 n2 (calendar-absolute-from-gregorian date2)))
15691 ((eq dw 'month)
15692 ;; approx number of month between the two dates
15693 (setq nmonths (floor (/ (- cday sday) 30.436875)))
15694 ;; How often does dn fit in there?
15695 (setq d (nth 1 start) m (car start) y (nth 2 start)
15696 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
15697 m (+ m nm)
15698 ny (floor (/ m 12))
15699 y (+ y ny)
15700 m (- m (* ny 12)))
15701 (while (> m 12) (setq m (- m 12) y (1+ y)))
15702 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
15703 (setq m2 (+ m dn) y2 y)
15704 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15705 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
15706 (while (<= n2 cday)
15707 (setq n1 n2 m m2 y y2)
15708 (setq m2 (+ m dn) y2 y)
15709 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15710 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
15711 ;; Make sure n1 is the earlier date
15712 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
15713 (if show-all
15714 (cond
15715 ((eq prefer 'past) (if (= cday n2) n2 n1))
15716 ((eq prefer 'future) (if (= cday n1) n1 n2))
15717 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
15718 (cond
15719 ((eq prefer 'past) (if (= cday n2) n2 n1))
15720 ((eq prefer 'future) (if (= cday n1) n1 n2))
15721 (t (if (= cday n1) n1 n2)))))))
15723 (defun org-date-to-gregorian (date)
15724 "Turn any specification of DATE into a Gregorian date for the calendar."
15725 (cond ((integerp date) (calendar-gregorian-from-absolute date))
15726 ((and (listp date) (= (length date) 3)) date)
15727 ((stringp date)
15728 (setq date (org-parse-time-string date))
15729 (list (nth 4 date) (nth 3 date) (nth 5 date)))
15730 ((listp date)
15731 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
15733 (defun org-parse-time-string (s &optional nodefault)
15734 "Parse the standard Org-mode time string.
15735 This should be a lot faster than the normal `parse-time-string'.
15736 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
15737 hour and minute fields will be nil if not given."
15738 (if (string-match org-ts-regexp0 s)
15739 (list 0
15740 (if (or (match-beginning 8) (not nodefault))
15741 (string-to-number (or (match-string 8 s) "0")))
15742 (if (or (match-beginning 7) (not nodefault))
15743 (string-to-number (or (match-string 7 s) "0")))
15744 (string-to-number (match-string 4 s))
15745 (string-to-number (match-string 3 s))
15746 (string-to-number (match-string 2 s))
15747 nil nil nil)
15748 (error "Not a standard Org-mode time string: %s" s)))
15750 (defun org-timestamp-up (&optional arg)
15751 "Increase the date item at the cursor by one.
15752 If the cursor is on the year, change the year. If it is on the month,
15753 the day or the time, change that.
15754 With prefix ARG, change by that many units."
15755 (interactive "p")
15756 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
15758 (defun org-timestamp-down (&optional arg)
15759 "Decrease the date item at the cursor by one.
15760 If the cursor is on the year, change the year. If it is on the month,
15761 the day or the time, change that.
15762 With prefix ARG, change by that many units."
15763 (interactive "p")
15764 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
15766 (defun org-timestamp-up-day (&optional arg)
15767 "Increase the date in the time stamp by one day.
15768 With prefix ARG, change that many days."
15769 (interactive "p")
15770 (if (and (not (org-at-timestamp-p t))
15771 (org-on-heading-p))
15772 (org-todo 'up)
15773 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
15775 (defun org-timestamp-down-day (&optional arg)
15776 "Decrease the date in the time stamp by one day.
15777 With prefix ARG, change that many days."
15778 (interactive "p")
15779 (if (and (not (org-at-timestamp-p t))
15780 (org-on-heading-p))
15781 (org-todo 'down)
15782 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
15784 (defun org-at-timestamp-p (&optional inactive-ok)
15785 "Determine if the cursor is in or at a timestamp."
15786 (interactive)
15787 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
15788 (pos (point))
15789 (ans (or (looking-at tsr)
15790 (save-excursion
15791 (skip-chars-backward "^[<\n\r\t")
15792 (if (> (point) (point-min)) (backward-char 1))
15793 (and (looking-at tsr)
15794 (> (- (match-end 0) pos) -1))))))
15795 (and ans
15796 (boundp 'org-ts-what)
15797 (setq org-ts-what
15798 (cond
15799 ((= pos (match-beginning 0)) 'bracket)
15800 ;; Point is considered to be "on the bracket" whether
15801 ;; it's really on it or right after it.
15802 ((or (= pos (1- (match-end 0)))
15803 (= pos (match-end 0))) 'bracket)
15804 ((org-pos-in-match-range pos 2) 'year)
15805 ((org-pos-in-match-range pos 3) 'month)
15806 ((org-pos-in-match-range pos 7) 'hour)
15807 ((org-pos-in-match-range pos 8) 'minute)
15808 ((or (org-pos-in-match-range pos 4)
15809 (org-pos-in-match-range pos 5)) 'day)
15810 ((and (> pos (or (match-end 8) (match-end 5)))
15811 (< pos (match-end 0)))
15812 (- pos (or (match-end 8) (match-end 5))))
15813 (t 'day))))
15814 ans))
15816 (defun org-toggle-timestamp-type ()
15817 "Toggle the type (<active> or [inactive]) of a time stamp."
15818 (interactive)
15819 (when (org-at-timestamp-p t)
15820 (let ((beg (match-beginning 0)) (end (match-end 0))
15821 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
15822 (save-excursion
15823 (goto-char beg)
15824 (while (re-search-forward "[][<>]" end t)
15825 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
15826 t t)))
15827 (message "Timestamp is now %sactive"
15828 (if (equal (char-after beg) ?<) "" "in")))))
15830 (defun org-timestamp-change (n &optional what updown)
15831 "Change the date in the time stamp at point.
15832 The date will be changed by N times WHAT. WHAT can be `day', `month',
15833 `year', `minute', `second'. If WHAT is not given, the cursor position
15834 in the timestamp determines what will be changed."
15835 (let ((origin (point)) origin-cat
15836 with-hm inactive
15837 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
15838 org-ts-what
15839 extra rem
15840 ts time time0)
15841 (if (not (org-at-timestamp-p t))
15842 (error "Not at a timestamp"))
15843 (if (and (not what) (eq org-ts-what 'bracket))
15844 (org-toggle-timestamp-type)
15845 ;; Point isn't on brackets. Remember the part of the time-stamp
15846 ;; the point was in. Indeed, size of time-stamps may change,
15847 ;; but point must be kept in the same category nonetheless.
15848 (setq origin-cat org-ts-what)
15849 (if (and (not what) (not (eq org-ts-what 'day))
15850 org-display-custom-times
15851 (get-text-property (point) 'display)
15852 (not (get-text-property (1- (point)) 'display)))
15853 (setq org-ts-what 'day))
15854 (setq org-ts-what (or what org-ts-what)
15855 inactive (= (char-after (match-beginning 0)) ?\[)
15856 ts (match-string 0))
15857 (replace-match "")
15858 (if (string-match
15859 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
15861 (setq extra (match-string 1 ts)))
15862 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
15863 (setq with-hm t))
15864 (setq time0 (org-parse-time-string ts))
15865 (when (and updown
15866 (eq org-ts-what 'minute)
15867 (not current-prefix-arg))
15868 ;; This looks like s-up and s-down. Change by one rounding step.
15869 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
15870 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
15871 (setcar (cdr time0) (+ (nth 1 time0)
15872 (if (> n 0) (- rem) (- dm rem))))))
15873 (setq time
15874 (encode-time (or (car time0) 0)
15875 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
15876 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
15877 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
15878 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
15879 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
15880 (nthcdr 6 time0)))
15881 (when (and (member org-ts-what '(hour minute))
15882 extra
15883 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
15884 (setq extra (org-modify-ts-extra
15885 extra
15886 (if (eq org-ts-what 'hour) 2 5)
15887 n dm)))
15888 (when (integerp org-ts-what)
15889 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
15890 (if (eq what 'calendar)
15891 (let ((cal-date (org-get-date-from-calendar)))
15892 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
15893 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
15894 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
15895 (setcar time0 (or (car time0) 0))
15896 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
15897 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
15898 (setq time (apply 'encode-time time0))))
15899 ;; Insert the new time-stamp, and ensure point stays in the same
15900 ;; category as before (i.e. not after the last position in that
15901 ;; category).
15902 (let ((pos (point)))
15903 ;; Stay before inserted string. `save-excursion' is of no use.
15904 (setq org-last-changed-timestamp
15905 (org-insert-time-stamp time with-hm inactive nil nil extra))
15906 (goto-char pos))
15907 (save-match-data
15908 (looking-at org-ts-regexp3)
15909 (goto-char (cond
15910 ;; `day' category ends before `hour' if any, or at
15911 ;; the end of the day name.
15912 ((eq origin-cat 'day)
15913 (min (or (match-beginning 7) (1- (match-end 5))) origin))
15914 ((eq origin-cat 'hour) (min (match-end 7) origin))
15915 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
15916 ((integerp origin-cat) (min (1- (match-end 0)) origin))
15917 ;; `year' and `month' have both fixed size: point
15918 ;; couldn't have moved into another part.
15919 (t origin))))
15920 ;; Update clock if on a CLOCK line.
15921 (org-clock-update-time-maybe)
15922 ;; Try to recenter the calendar window, if any.
15923 (if (and org-calendar-follow-timestamp-change
15924 (get-buffer-window "*Calendar*" t)
15925 (memq org-ts-what '(day month year)))
15926 (org-recenter-calendar (time-to-days time))))))
15928 (defun org-modify-ts-extra (s pos n dm)
15929 "Change the different parts of the lead-time and repeat fields in timestamp."
15930 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
15931 ng h m new rem)
15932 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
15933 (cond
15934 ((or (org-pos-in-match-range pos 2)
15935 (org-pos-in-match-range pos 3))
15936 (setq m (string-to-number (match-string 3 s))
15937 h (string-to-number (match-string 2 s)))
15938 (if (org-pos-in-match-range pos 2)
15939 (setq h (+ h n))
15940 (setq n (* dm (org-no-warnings (signum n))))
15941 (when (not (= 0 (setq rem (% m dm))))
15942 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
15943 (setq m (+ m n)))
15944 (if (< m 0) (setq m (+ m 60) h (1- h)))
15945 (if (> m 59) (setq m (- m 60) h (1+ h)))
15946 (setq h (min 24 (max 0 h)))
15947 (setq ng 1 new (format "-%02d:%02d" h m)))
15948 ((org-pos-in-match-range pos 6)
15949 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
15950 ((org-pos-in-match-range pos 5)
15951 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
15953 ((org-pos-in-match-range pos 9)
15954 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
15955 ((org-pos-in-match-range pos 8)
15956 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
15958 (when ng
15959 (setq s (concat
15960 (substring s 0 (match-beginning ng))
15962 (substring s (match-end ng))))))
15965 (defun org-recenter-calendar (date)
15966 "If the calendar is visible, recenter it to DATE."
15967 (let* ((win (selected-window))
15968 (cwin (get-buffer-window "*Calendar*" t))
15969 (calendar-move-hook nil))
15970 (when cwin
15971 (select-window cwin)
15972 (calendar-goto-date (if (listp date) date
15973 (calendar-gregorian-from-absolute date)))
15974 (select-window win))))
15976 (defun org-goto-calendar (&optional arg)
15977 "Go to the Emacs calendar at the current date.
15978 If there is a time stamp in the current line, go to that date.
15979 A prefix ARG can be used to force the current date."
15980 (interactive "P")
15981 (let ((tsr org-ts-regexp) diff
15982 (calendar-move-hook nil)
15983 (calendar-view-holidays-initially-flag nil)
15984 (calendar-view-diary-initially-flag nil))
15985 (if (or (org-at-timestamp-p)
15986 (save-excursion
15987 (beginning-of-line 1)
15988 (looking-at (concat ".*" tsr))))
15989 (let ((d1 (time-to-days (current-time)))
15990 (d2 (time-to-days
15991 (org-time-string-to-time (match-string 1)))))
15992 (setq diff (- d2 d1))))
15993 (calendar)
15994 (calendar-goto-today)
15995 (if (and diff (not arg)) (calendar-forward-day diff))))
15997 (defun org-get-date-from-calendar ()
15998 "Return a list (month day year) of date at point in calendar."
15999 (with-current-buffer "*Calendar*"
16000 (save-match-data
16001 (calendar-cursor-to-date))))
16003 (defun org-date-from-calendar ()
16004 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16005 If there is already a time stamp at the cursor position, update it."
16006 (interactive)
16007 (if (org-at-timestamp-p t)
16008 (org-timestamp-change 0 'calendar)
16009 (let ((cal-date (org-get-date-from-calendar)))
16010 (org-insert-time-stamp
16011 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16013 (defun org-minutes-to-hh:mm-string (m)
16014 "Compute H:MM from a number of minutes."
16015 (let ((h (/ m 60)))
16016 (setq m (- m (* 60 h)))
16017 (format org-time-clocksum-format h m)))
16019 (defun org-hh:mm-string-to-minutes (s)
16020 "Convert a string H:MM to a number of minutes.
16021 If the string is just a number, interpret it as minutes.
16022 In fact, the first hh:mm or number in the string will be taken,
16023 there can be extra stuff in the string.
16024 If no number is found, the return value is 0."
16025 (cond
16026 ((integerp s) s)
16027 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16028 (+ (* (string-to-number (match-string 1 s)) 60)
16029 (string-to-number (match-string 2 s))))
16030 ((string-match "\\([0-9]+\\)" s)
16031 (string-to-number (match-string 1 s)))
16032 (t 0)))
16034 (defcustom org-effort-durations
16035 `(("h" . 60)
16036 ("d" . ,(* 60 8))
16037 ("w" . ,(* 60 8 5))
16038 ("m" . ,(* 60 8 5 4))
16039 ("y" . ,(* 60 8 5 40)))
16040 "Conversion factor to minutes for an effort modifier.
16042 Each entry has the form (MODIFIER . MINUTES).
16044 In an effort string, a number followed by MODIFIER is multiplied
16045 by the specified number of MINUTES to obtain an effort in
16046 minutes.
16048 For example, if the value of this variable is ((\"hours\" . 60)), then an
16049 effort string \"2hours\" is equivalent to 120 minutes."
16050 :group 'org-agenda
16051 :type '(alist :key-type (string :tag "Modifier")
16052 :value-type (number :tag "Minutes")))
16054 (defun org-duration-string-to-minutes (s)
16055 "Convert a duration string S to minutes.
16057 A bare number is interpreted as minutes, modifiers can be set by
16058 customizing `org-effort-durations' (which see).
16060 Entries containing a colon are interpreted as H:MM by
16061 `org-hh:mm-string-to-minutes'."
16062 (let ((result 0)
16063 (re (concat "\\([0-9]+\\) *\\("
16064 (regexp-opt (mapcar 'car org-effort-durations))
16065 "\\)")))
16066 (while (string-match re s)
16067 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16068 (string-to-number (match-string 1 s))))
16069 (setq s (replace-match "" nil t s)))
16070 (incf result (org-hh:mm-string-to-minutes s))
16071 result))
16073 ;;;; Files
16075 (defun org-save-all-org-buffers ()
16076 "Save all Org-mode buffers without user confirmation."
16077 (interactive)
16078 (message "Saving all Org-mode buffers...")
16079 (save-some-buffers t (lambda () (eq major-mode 'org-mode)))
16080 (when (featurep 'org-id) (org-id-locations-save))
16081 (message "Saving all Org-mode buffers... done"))
16083 (defun org-revert-all-org-buffers ()
16084 "Revert all Org-mode buffers.
16085 Prompt for confirmation when there are unsaved changes.
16086 Be sure you know what you are doing before letting this function
16087 overwrite your changes.
16089 This function is useful in a setup where one tracks org files
16090 with a version control system, to revert on one machine after pulling
16091 changes from another. I believe the procedure must be like this:
16093 1. M-x org-save-all-org-buffers
16094 2. Pull changes from the other machine, resolve conflicts
16095 3. M-x org-revert-all-org-buffers"
16096 (interactive)
16097 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16098 (error "Abort"))
16099 (save-excursion
16100 (save-window-excursion
16101 (mapc
16102 (lambda (b)
16103 (when (and (with-current-buffer b (eq major-mode 'org-mode))
16104 (with-current-buffer b buffer-file-name))
16105 (org-pop-to-buffer-same-window b)
16106 (revert-buffer t 'no-confirm)))
16107 (buffer-list))
16108 (when (and (featurep 'org-id) org-id-track-globally)
16109 (org-id-locations-load)))))
16111 ;;;; Agenda files
16113 ;;;###autoload
16114 (defun org-switchb (&optional arg)
16115 "Switch between Org buffers.
16116 With one prefix argument, restrict available buffers to files.
16117 With two prefix arguments, restrict available buffers to agenda files.
16119 Defaults to `iswitchb' for buffer name completion.
16120 Set `org-completion-use-ido' to make it use ido instead."
16121 (interactive "P")
16122 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16123 ((equal arg '(16)) (org-buffer-list 'agenda))
16124 (t (org-buffer-list))))
16125 (org-completion-use-iswitchb org-completion-use-iswitchb)
16126 (org-completion-use-ido org-completion-use-ido))
16127 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16128 (setq org-completion-use-iswitchb t))
16129 (org-pop-to-buffer-same-window
16130 (org-icompleting-read "Org buffer: "
16131 (mapcar 'list (mapcar 'buffer-name blist))
16132 nil t))))
16134 ;;; Define some older names previously used for this functionality
16135 ;;;###autoload
16136 (defalias 'org-ido-switchb 'org-switchb)
16137 ;;;###autoload
16138 (defalias 'org-iswitchb 'org-switchb)
16140 (defun org-buffer-list (&optional predicate exclude-tmp)
16141 "Return a list of Org buffers.
16142 PREDICATE can be `export', `files' or `agenda'.
16144 export restrict the list to Export buffers.
16145 files restrict the list to buffers visiting Org files.
16146 agenda restrict the list to buffers visiting agenda files.
16148 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16149 (let* ((bfn nil)
16150 (agenda-files (and (eq predicate 'agenda)
16151 (mapcar 'file-truename (org-agenda-files t))))
16152 (filter
16153 (cond
16154 ((eq predicate 'files)
16155 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
16156 ((eq predicate 'export)
16157 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16158 ((eq predicate 'agenda)
16159 (lambda (b)
16160 (with-current-buffer b
16161 (and (eq major-mode 'org-mode)
16162 (setq bfn (buffer-file-name b))
16163 (member (file-truename bfn) agenda-files)))))
16164 (t (lambda (b) (with-current-buffer b
16165 (or (eq major-mode 'org-mode)
16166 (string-match "\*Org .*Export"
16167 (buffer-name b)))))))))
16168 (delq nil
16169 (mapcar
16170 (lambda(b)
16171 (if (and (funcall filter b)
16172 (or (not exclude-tmp)
16173 (not (string-match "tmp" (buffer-name b)))))
16175 nil))
16176 (buffer-list)))))
16178 (defun org-agenda-files (&optional unrestricted archives)
16179 "Get the list of agenda files.
16180 Optional UNRESTRICTED means return the full list even if a restriction
16181 is currently in place.
16182 When ARCHIVES is t, include all archive files that are really being
16183 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16184 `org-agenda-archives-mode' is t."
16185 (let ((files
16186 (cond
16187 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16188 ((stringp org-agenda-files) (org-read-agenda-file-list))
16189 ((listp org-agenda-files) org-agenda-files)
16190 (t (error "Invalid value of `org-agenda-files'")))))
16191 (setq files (apply 'append
16192 (mapcar (lambda (f)
16193 (if (file-directory-p f)
16194 (directory-files
16195 f t org-agenda-file-regexp)
16196 (list f)))
16197 files)))
16198 (when org-agenda-skip-unavailable-files
16199 (setq files (delq nil
16200 (mapcar (function
16201 (lambda (file)
16202 (and (file-readable-p file) file)))
16203 files))))
16204 (when (or (eq archives t)
16205 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16206 (setq files (org-add-archive-files files)))
16207 files))
16209 (defun org-agenda-file-p (&optional file)
16210 "Return non-nil, if FILE is an agenda file.
16211 If FILE is omitted, use the file associated with the current
16212 buffer."
16213 (member (or file (buffer-file-name))
16214 (org-agenda-files t)))
16216 (defun org-edit-agenda-file-list ()
16217 "Edit the list of agenda files.
16218 Depending on setup, this either uses customize to edit the variable
16219 `org-agenda-files', or it visits the file that is holding the list. In the
16220 latter case, the buffer is set up in a way that saving it automatically kills
16221 the buffer and restores the previous window configuration."
16222 (interactive)
16223 (if (stringp org-agenda-files)
16224 (let ((cw (current-window-configuration)))
16225 (find-file org-agenda-files)
16226 (org-set-local 'org-window-configuration cw)
16227 (org-add-hook 'after-save-hook
16228 (lambda ()
16229 (set-window-configuration
16230 (prog1 org-window-configuration
16231 (kill-buffer (current-buffer))))
16232 (org-install-agenda-files-menu)
16233 (message "New agenda file list installed"))
16234 nil 'local)
16235 (message "%s" (substitute-command-keys
16236 "Edit list and finish with \\[save-buffer]")))
16237 (customize-variable 'org-agenda-files)))
16239 (defun org-store-new-agenda-file-list (list)
16240 "Set new value for the agenda file list and save it correctly."
16241 (if (stringp org-agenda-files)
16242 (let ((fe (org-read-agenda-file-list t)) b u)
16243 (while (setq b (find-buffer-visiting org-agenda-files))
16244 (kill-buffer b))
16245 (with-temp-file org-agenda-files
16246 (insert
16247 (mapconcat
16248 (lambda (f) ;; Keep un-expanded entries.
16249 (if (setq u (assoc f fe))
16250 (cdr u)
16252 list "\n")
16253 "\n")))
16254 (let ((org-mode-hook nil) (org-inhibit-startup t)
16255 (org-insert-mode-line-in-empty-file nil))
16256 (setq org-agenda-files list)
16257 (customize-save-variable 'org-agenda-files org-agenda-files))))
16259 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16260 "Read the list of agenda files from a file.
16261 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16262 filenames, used by `org-store-new-agenda-file-list' to write back
16263 un-expanded file names."
16264 (when (file-directory-p org-agenda-files)
16265 (error "`org-agenda-files' cannot be a single directory"))
16266 (when (stringp org-agenda-files)
16267 (with-temp-buffer
16268 (insert-file-contents org-agenda-files)
16269 (mapcar
16270 (lambda (f)
16271 (let ((e (expand-file-name (substitute-in-file-name f)
16272 org-directory)))
16273 (if pair-with-expansion
16274 (cons e f)
16275 e)))
16276 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16278 ;;;###autoload
16279 (defun org-cycle-agenda-files ()
16280 "Cycle through the files in `org-agenda-files'.
16281 If the current buffer visits an agenda file, find the next one in the list.
16282 If the current buffer does not, find the first agenda file."
16283 (interactive)
16284 (let* ((fs (org-agenda-files t))
16285 (files (append fs (list (car fs))))
16286 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16287 file)
16288 (unless files (error "No agenda files"))
16289 (catch 'exit
16290 (while (setq file (pop files))
16291 (if (equal (file-truename file) tcf)
16292 (when (car files)
16293 (find-file (car files))
16294 (throw 'exit t))))
16295 (find-file (car fs)))
16296 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16298 (defun org-agenda-file-to-front (&optional to-end)
16299 "Move/add the current file to the top of the agenda file list.
16300 If the file is not present in the list, it is added to the front. If it is
16301 present, it is moved there. With optional argument TO-END, add/move to the
16302 end of the list."
16303 (interactive "P")
16304 (let ((org-agenda-skip-unavailable-files nil)
16305 (file-alist (mapcar (lambda (x)
16306 (cons (file-truename x) x))
16307 (org-agenda-files t)))
16308 (ctf (file-truename buffer-file-name))
16309 x had)
16310 (setq x (assoc ctf file-alist) had x)
16312 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16313 (if to-end
16314 (setq file-alist (append (delq x file-alist) (list x)))
16315 (setq file-alist (cons x (delq x file-alist))))
16316 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16317 (org-install-agenda-files-menu)
16318 (message "File %s to %s of agenda file list"
16319 (if had "moved" "added") (if to-end "end" "front"))))
16321 (defun org-remove-file (&optional file)
16322 "Remove current file from the list of files in variable `org-agenda-files'.
16323 These are the files which are being checked for agenda entries.
16324 Optional argument FILE means use this file instead of the current."
16325 (interactive)
16326 (let* ((org-agenda-skip-unavailable-files nil)
16327 (file (or file buffer-file-name))
16328 (true-file (file-truename file))
16329 (afile (abbreviate-file-name file))
16330 (files (delq nil (mapcar
16331 (lambda (x)
16332 (if (equal true-file
16333 (file-truename x))
16334 nil x))
16335 (org-agenda-files t)))))
16336 (if (not (= (length files) (length (org-agenda-files t))))
16337 (progn
16338 (org-store-new-agenda-file-list files)
16339 (org-install-agenda-files-menu)
16340 (message "Removed file: %s" afile))
16341 (message "File was not in list: %s (not removed)" afile))))
16343 (defun org-file-menu-entry (file)
16344 (vector file (list 'find-file file) t))
16346 (defun org-check-agenda-file (file)
16347 "Make sure FILE exists. If not, ask user what to do."
16348 (when (not (file-exists-p file))
16349 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16350 (abbreviate-file-name file))
16351 (let ((r (downcase (read-char-exclusive))))
16352 (cond
16353 ((equal r ?r)
16354 (org-remove-file file)
16355 (throw 'nextfile t))
16356 (t (error "Abort"))))))
16358 (defun org-get-agenda-file-buffer (file)
16359 "Get a buffer visiting FILE. If the buffer needs to be created, add
16360 it to the list of buffers which might be released later."
16361 (let ((buf (org-find-base-buffer-visiting file)))
16362 (if buf
16363 buf ; just return it
16364 ;; Make a new buffer and remember it
16365 (setq buf (find-file-noselect file))
16366 (if buf (push buf org-agenda-new-buffers))
16367 buf)))
16369 (defun org-release-buffers (blist)
16370 "Release all buffers in list, asking the user for confirmation when needed.
16371 When a buffer is unmodified, it is just killed. When modified, it is saved
16372 \(if the user agrees) and then killed."
16373 (let (buf file)
16374 (while (setq buf (pop blist))
16375 (setq file (buffer-file-name buf))
16376 (when (and (buffer-modified-p buf)
16377 file
16378 (y-or-n-p (format "Save file %s? " file)))
16379 (with-current-buffer buf (save-buffer)))
16380 (kill-buffer buf))))
16382 (defun org-prepare-agenda-buffers (files)
16383 "Create buffers for all agenda files, protect archived trees and comments."
16384 (interactive)
16385 (let ((pa '(:org-archived t))
16386 (pc '(:org-comment t))
16387 (pall '(:org-archived t :org-comment t))
16388 (inhibit-read-only t)
16389 (rea (concat ":" org-archive-tag ":"))
16390 bmp file re)
16391 (save-excursion
16392 (save-restriction
16393 (while (setq file (pop files))
16394 (catch 'nextfile
16395 (if (bufferp file)
16396 (set-buffer file)
16397 (org-check-agenda-file file)
16398 (set-buffer (org-get-agenda-file-buffer file)))
16399 (widen)
16400 (setq bmp (buffer-modified-p))
16401 (org-refresh-category-properties)
16402 (setq org-todo-keywords-for-agenda
16403 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16404 (setq org-done-keywords-for-agenda
16405 (append org-done-keywords-for-agenda org-done-keywords))
16406 (setq org-todo-keyword-alist-for-agenda
16407 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16408 (setq org-drawers-for-agenda
16409 (append org-drawers-for-agenda org-drawers))
16410 (setq org-tag-alist-for-agenda
16411 (append org-tag-alist-for-agenda org-tag-alist))
16413 (save-excursion
16414 (remove-text-properties (point-min) (point-max) pall)
16415 (when org-agenda-skip-archived-trees
16416 (goto-char (point-min))
16417 (while (re-search-forward rea nil t)
16418 (if (org-on-heading-p t)
16419 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16420 (goto-char (point-min))
16421 (setq re (format org-heading-keyword-regexp-format
16422 org-comment-string))
16423 (while (re-search-forward re nil t)
16424 (add-text-properties
16425 (match-beginning 0) (org-end-of-subtree t) pc)))
16426 (set-buffer-modified-p bmp)))))
16427 (setq org-todo-keywords-for-agenda
16428 (org-uniquify org-todo-keywords-for-agenda))
16429 (setq org-todo-keyword-alist-for-agenda
16430 (org-uniquify org-todo-keyword-alist-for-agenda)
16431 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16433 ;;;; Embedded LaTeX
16435 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16436 "Keymap for the minor `org-cdlatex-mode'.")
16438 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16439 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16440 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16441 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16442 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16444 (defvar org-cdlatex-texmathp-advice-is-done nil
16445 "Flag remembering if we have applied the advice to texmathp already.")
16447 (define-minor-mode org-cdlatex-mode
16448 "Toggle the minor `org-cdlatex-mode'.
16449 This mode supports entering LaTeX environment and math in LaTeX fragments
16450 in Org-mode.
16451 \\{org-cdlatex-mode-map}"
16452 nil " OCDL" nil
16453 (when org-cdlatex-mode
16454 (require 'cdlatex)
16455 (run-hooks 'cdlatex-mode-hook)
16456 (cdlatex-compute-tables))
16457 (unless org-cdlatex-texmathp-advice-is-done
16458 (setq org-cdlatex-texmathp-advice-is-done t)
16459 (defadvice texmathp (around org-math-always-on activate)
16460 "Always return t in org-mode buffers.
16461 This is because we want to insert math symbols without dollars even outside
16462 the LaTeX math segments. If Orgmode thinks that point is actually inside
16463 an embedded LaTeX fragment, let texmathp do its job.
16464 \\[org-cdlatex-mode-map]"
16465 (interactive)
16466 (let (p)
16467 (cond
16468 ((not (eq major-mode 'org-mode)) ad-do-it)
16469 ((eq this-command 'cdlatex-math-symbol)
16470 (setq ad-return-value t
16471 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16473 (let ((p (org-inside-LaTeX-fragment-p)))
16474 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16475 (setq ad-return-value t
16476 texmathp-why '("Org-mode embedded math" . 0))
16477 (if p ad-do-it)))))))))
16479 (defun turn-on-org-cdlatex ()
16480 "Unconditionally turn on `org-cdlatex-mode'."
16481 (org-cdlatex-mode 1))
16483 (defun org-inside-LaTeX-fragment-p ()
16484 "Test if point is inside a LaTeX fragment.
16485 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16486 sequence appearing also before point.
16487 Even though the matchers for math are configurable, this function assumes
16488 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16489 delimiters are skipped when they have been removed by customization.
16490 The return value is nil, or a cons cell with the delimiter and the
16491 position of this delimiter.
16493 This function does a reasonably good job, but can locally be fooled by
16494 for example currency specifications. For example it will assume being in
16495 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16496 fragments that are properly closed, but during editing, we have to live
16497 with the uncertainty caused by missing closing delimiters. This function
16498 looks only before point, not after."
16499 (catch 'exit
16500 (let ((pos (point))
16501 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16502 (lim (progn
16503 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16504 (point)))
16505 dd-on str (start 0) m re)
16506 (goto-char pos)
16507 (when dodollar
16508 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16509 re (nth 1 (assoc "$" org-latex-regexps)))
16510 (while (string-match re str start)
16511 (cond
16512 ((= (match-end 0) (length str))
16513 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16514 ((= (match-end 0) (- (length str) 5))
16515 (throw 'exit nil))
16516 (t (setq start (match-end 0))))))
16517 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16518 (goto-char pos)
16519 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16520 (and (match-beginning 2) (throw 'exit nil))
16521 ;; count $$
16522 (while (re-search-backward "\\$\\$" lim t)
16523 (setq dd-on (not dd-on)))
16524 (goto-char pos)
16525 (if dd-on (cons "$$" m))))))
16527 (defun org-inside-latex-macro-p ()
16528 "Is point inside a LaTeX macro or its arguments?"
16529 (save-match-data
16530 (org-in-regexp
16531 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16533 (defun org-try-cdlatex-tab ()
16534 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16535 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16536 - inside a LaTeX fragment, or
16537 - after the first word in a line, where an abbreviation expansion could
16538 insert a LaTeX environment."
16539 (when org-cdlatex-mode
16540 (cond
16541 ((save-excursion
16542 (skip-chars-backward "a-zA-Z0-9*")
16543 (skip-chars-backward " \t")
16544 (bolp))
16545 (cdlatex-tab) t)
16546 ((org-inside-LaTeX-fragment-p)
16547 (cdlatex-tab) t)
16548 (t nil))))
16550 (defun org-cdlatex-underscore-caret (&optional arg)
16551 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16552 Revert to the normal definition outside of these fragments."
16553 (interactive "P")
16554 (if (org-inside-LaTeX-fragment-p)
16555 (call-interactively 'cdlatex-sub-superscript)
16556 (let (org-cdlatex-mode)
16557 (call-interactively (key-binding (vector last-input-event))))))
16559 (defun org-cdlatex-math-modify (&optional arg)
16560 "Execute `cdlatex-math-modify' in LaTeX fragments.
16561 Revert to the normal definition outside of these fragments."
16562 (interactive "P")
16563 (if (org-inside-LaTeX-fragment-p)
16564 (call-interactively 'cdlatex-math-modify)
16565 (let (org-cdlatex-mode)
16566 (call-interactively (key-binding (vector last-input-event))))))
16568 (defvar org-latex-fragment-image-overlays nil
16569 "List of overlays carrying the images of latex fragments.")
16570 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16572 (defun org-remove-latex-fragment-image-overlays ()
16573 "Remove all overlays with LaTeX fragment images in current buffer."
16574 (mapc 'delete-overlay org-latex-fragment-image-overlays)
16575 (setq org-latex-fragment-image-overlays nil))
16577 (defun org-preview-latex-fragment (&optional subtree)
16578 "Preview the LaTeX fragment at point, or all locally or globally.
16579 If the cursor is in a LaTeX fragment, create the image and overlay
16580 it over the source code. If there is no fragment at point, display
16581 all fragments in the current text, from one headline to the next. With
16582 prefix SUBTREE, display all fragments in the current subtree. With a
16583 double prefix arg \\[universal-argument] \\[universal-argument], or when \
16584 the cursor is before the first headline,
16585 display all fragments in the buffer.
16586 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16587 (interactive "P")
16588 (org-remove-latex-fragment-image-overlays)
16589 (save-excursion
16590 (save-restriction
16591 (let (beg end at msg)
16592 (cond
16593 ((or (equal subtree '(16))
16594 (not (save-excursion
16595 (re-search-backward org-outline-regexp-bol nil t))))
16596 (setq beg (point-min) end (point-max)
16597 msg "Creating images for buffer...%s"))
16598 ((equal subtree '(4))
16599 (org-back-to-heading)
16600 (setq beg (point) end (org-end-of-subtree t)
16601 msg "Creating images for subtree...%s"))
16603 (if (setq at (org-inside-LaTeX-fragment-p))
16604 (goto-char (max (point-min) (- (cdr at) 2)))
16605 (org-back-to-heading))
16606 (setq beg (point) end (progn (outline-next-heading) (point))
16607 msg (if at "Creating image...%s"
16608 "Creating images for entry...%s"))))
16609 (message msg "")
16610 (narrow-to-region beg end)
16611 (goto-char beg)
16612 (org-format-latex
16613 (concat "ltxpng/" (file-name-sans-extension
16614 (file-name-nondirectory
16615 buffer-file-name)))
16616 default-directory 'overlays msg at 'forbuffer 'dvipng)
16617 (message msg "done. Use `C-c C-c' to remove images.")))))
16619 (defvar org-latex-regexps
16620 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16621 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16622 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16623 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16624 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16625 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16626 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
16627 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
16628 "Regular expressions for matching embedded LaTeX.")
16630 (defvar org-export-have-math nil) ;; dynamic scoping
16631 (defun org-format-latex (prefix &optional dir overlays msg at
16632 forbuffer processing-type)
16633 "Replace LaTeX fragments with links to an image, and produce images.
16634 Some of the options can be changed using the variable
16635 `org-format-latex-options'."
16636 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16637 (let* ((prefixnodir (file-name-nondirectory prefix))
16638 (absprefix (expand-file-name prefix dir))
16639 (todir (file-name-directory absprefix))
16640 (opt org-format-latex-options)
16641 (matchers (plist-get opt :matchers))
16642 (re-list org-latex-regexps)
16643 (org-format-latex-header-extra
16644 (plist-get (org-infile-export-plist) :latex-header-extra))
16645 (cnt 0) txt hash link beg end re e checkdir
16646 executables-checked string
16647 m n block-type block linkfile movefile ov)
16648 ;; Check the different regular expressions
16649 (while (setq e (pop re-list))
16650 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
16651 block (if block-type "\n\n" ""))
16652 (when (member m matchers)
16653 (goto-char (point-min))
16654 (while (re-search-forward re nil t)
16655 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
16656 (not (get-text-property (match-beginning n)
16657 'org-protected))
16658 (or (not overlays)
16659 (not (eq (get-char-property (match-beginning n)
16660 'org-overlay-type)
16661 'org-latex-overlay))))
16662 (setq org-export-have-math t)
16663 (cond
16664 ((eq processing-type 'verbatim)
16665 ;; Leave the text verbatim, just protect it
16666 (add-text-properties (match-beginning n) (match-end n)
16667 '(org-protected t)))
16668 ((eq processing-type 'mathjax)
16669 ;; Prepare for MathJax processing
16670 (setq string (match-string n))
16671 (if (member m '("$" "$1"))
16672 (save-excursion
16673 (delete-region (match-beginning n) (match-end n))
16674 (goto-char (match-beginning n))
16675 (insert (org-add-props (concat "\\(" (substring string 1 -1)
16676 "\\)")
16677 '(org-protected t))))
16678 (add-text-properties (match-beginning n) (match-end n)
16679 '(org-protected t))))
16680 ((eq processing-type 'dvipng)
16681 ;; Process to an image
16682 (setq txt (match-string n)
16683 beg (match-beginning n) end (match-end n)
16684 cnt (1+ cnt))
16685 (let (print-length print-level) ; make sure full list is printed
16686 (setq hash (sha1 (prin1-to-string
16687 (list org-format-latex-header
16688 org-format-latex-header-extra
16689 org-export-latex-default-packages-alist
16690 org-export-latex-packages-alist
16691 org-format-latex-options
16692 forbuffer txt)))
16693 linkfile (format "%s_%s.png" prefix hash)
16694 movefile (format "%s_%s.png" absprefix hash)))
16695 (setq link (concat block "[[file:" linkfile "]]" block))
16696 (if msg (message msg cnt))
16697 (goto-char beg)
16698 (unless checkdir ; make sure the directory exists
16699 (setq checkdir t)
16700 (or (file-directory-p todir) (make-directory todir t)))
16702 (unless executables-checked
16703 (org-check-external-command
16704 "latex" "needed to convert LaTeX fragments to images")
16705 (org-check-external-command
16706 "dvipng" "needed to convert LaTeX fragments to images")
16707 (setq executables-checked t))
16709 (unless (file-exists-p movefile)
16710 (org-create-formula-image
16711 txt movefile opt forbuffer))
16712 (if overlays
16713 (progn
16714 (mapc (lambda (o)
16715 (if (eq (overlay-get o 'org-overlay-type)
16716 'org-latex-overlay)
16717 (delete-overlay o)))
16718 (overlays-in beg end))
16719 (setq ov (make-overlay beg end))
16720 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
16721 (if (featurep 'xemacs)
16722 (progn
16723 (overlay-put ov 'invisible t)
16724 (overlay-put
16725 ov 'end-glyph
16726 (make-glyph (vector 'png :file movefile))))
16727 (overlay-put
16728 ov 'display
16729 (list 'image :type 'png :file movefile :ascent 'center)))
16730 (push ov org-latex-fragment-image-overlays)
16731 (goto-char end))
16732 (delete-region beg end)
16733 (insert (org-add-props link
16734 (list 'org-latex-src
16735 (replace-regexp-in-string
16736 "\"" "" txt)
16737 'org-latex-src-embed-type
16738 (if block-type 'paragraph 'character))))))
16739 ((eq processing-type 'mathml)
16740 ;; Process to MathML
16741 (unless executables-checked
16742 (unless (save-match-data (org-format-latex-mathml-available-p))
16743 (error "LaTeX to MathML converter not configured"))
16744 (setq executables-checked t))
16745 (setq txt (match-string n)
16746 beg (match-beginning n) end (match-end n)
16747 cnt (1+ cnt))
16748 (if msg (message msg cnt))
16749 (goto-char beg)
16750 (delete-region beg end)
16751 (insert (org-format-latex-as-mathml
16752 txt block-type prefix dir)))
16754 (error "Unknown conversion type %s for latex fragments"
16755 processing-type)))))))))
16757 (defun org-create-math-formula (latex-frag &optional mathml-file)
16758 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
16759 Use `org-latex-to-mathml-convert-command'. If the conversion is
16760 sucessful, return the portion between \"<math...> </math>\"
16761 elements otherwise return nil. When MATHML-FILE is specified,
16762 write the results in to that file. When invoked as an
16763 interactive command, prompt for LATEX-FRAG, with initial value
16764 set to the current active region and echo the results for user
16765 inspection."
16766 (interactive (list (let ((frag (when (region-active-p)
16767 (buffer-substring-no-properties
16768 (region-beginning) (region-end)))))
16769 (read-string "LaTeX Fragment: " frag nil frag))))
16770 (unless latex-frag (error "Invalid latex-frag"))
16771 (let* ((tmp-in-file (file-relative-name
16772 (make-temp-name (expand-file-name "ltxmathml-in"))))
16773 (ignore (write-region latex-frag nil tmp-in-file))
16774 (tmp-out-file (file-relative-name
16775 (make-temp-name (expand-file-name "ltxmathml-out"))))
16776 (cmd (format-spec
16777 org-latex-to-mathml-convert-command
16778 `((?j . ,(shell-quote-argument
16779 (expand-file-name org-latex-to-mathml-jar-file)))
16780 (?I . ,(shell-quote-argument tmp-in-file))
16781 (?o . ,(shell-quote-argument tmp-out-file)))))
16782 mathml shell-command-output)
16783 (when (org-called-interactively-p 'any)
16784 (unless (org-format-latex-mathml-available-p)
16785 (error "LaTeX to MathML converter not configured")))
16786 (message "Running %s" cmd)
16787 (setq shell-command-output (shell-command-to-string cmd))
16788 (setq mathml
16789 (when (file-readable-p tmp-out-file)
16790 (with-current-buffer (find-file-noselect tmp-out-file t)
16791 (goto-char (point-min))
16792 (when (re-search-forward
16793 (concat
16794 (regexp-quote
16795 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
16796 "\\(.\\|\n\\)*"
16797 (regexp-quote "</math>")) nil t)
16798 (prog1 (match-string 0) (kill-buffer))))))
16799 (cond
16800 (mathml
16801 (setq mathml
16802 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
16803 (when mathml-file
16804 (write-region mathml nil mathml-file))
16805 (when (org-called-interactively-p 'any)
16806 (message mathml)))
16807 ((message "LaTeX to MathML conversion failed")
16808 (message shell-command-output)))
16809 (delete-file tmp-in-file)
16810 (when (file-exists-p tmp-out-file)
16811 (delete-file tmp-out-file))
16812 mathml))
16814 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
16815 prefix &optional dir)
16816 "Use `org-create-math-formula' but check local cache first."
16817 (let* ((absprefix (expand-file-name prefix dir))
16818 (print-length nil) (print-level nil)
16819 (formula-id (concat
16820 "formula-"
16821 (sha1
16822 (prin1-to-string
16823 (list latex-frag
16824 org-latex-to-mathml-convert-command)))))
16825 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
16826 (formula-cache-dir (file-name-directory formula-cache)))
16828 (unless (file-directory-p formula-cache-dir)
16829 (make-directory formula-cache-dir t))
16831 (unless (file-exists-p formula-cache)
16832 (org-create-math-formula latex-frag formula-cache))
16834 (if (file-exists-p formula-cache)
16835 ;; Successful conversion. Return the link to MathML file.
16836 (org-add-props
16837 (format "[[file:%s]]" (file-relative-name formula-cache dir))
16838 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
16839 'org-latex-src-embed-type (if latex-frag-type
16840 'paragraph 'character)))
16841 ;; Failed conversion. Return the LaTeX fragment verbatim
16842 (add-text-properties
16843 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
16844 latex-frag)))
16846 ;; This function borrows from Ganesh Swami's latex2png.el
16847 (defun org-create-formula-image (string tofile options buffer)
16848 "This calls dvipng."
16849 (require 'org-latex)
16850 (let* ((tmpdir (if (featurep 'xemacs)
16851 (temp-directory)
16852 temporary-file-directory))
16853 (texfilebase (make-temp-name
16854 (expand-file-name "orgtex" tmpdir)))
16855 (texfile (concat texfilebase ".tex"))
16856 (dvifile (concat texfilebase ".dvi"))
16857 (pngfile (concat texfilebase ".png"))
16858 (fnh (if (featurep 'xemacs)
16859 (font-height (get-face-font 'default))
16860 (face-attribute 'default :height nil)))
16861 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
16862 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
16863 (fg (or (plist-get options (if buffer :foreground :html-foreground))
16864 "Black"))
16865 (bg (or (plist-get options (if buffer :background :html-background))
16866 "Transparent")))
16867 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
16868 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
16869 (with-temp-file texfile
16870 (insert (org-splice-latex-header
16871 org-format-latex-header
16872 org-export-latex-default-packages-alist
16873 org-export-latex-packages-alist t
16874 org-format-latex-header-extra))
16875 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
16876 (require 'org-latex)
16877 (org-export-latex-fix-inputenc))
16878 (let ((dir default-directory))
16879 (condition-case nil
16880 (progn
16881 (cd tmpdir)
16882 (call-process "latex" nil nil nil texfile))
16883 (error nil))
16884 (cd dir))
16885 (if (not (file-exists-p dvifile))
16886 (progn (message "Failed to create dvi file from %s" texfile) nil)
16887 (condition-case nil
16888 (call-process "dvipng" nil nil nil
16889 "-fg" fg "-bg" bg
16890 "-D" dpi
16891 ;;"-x" scale "-y" scale
16892 "-T" "tight"
16893 "-o" pngfile
16894 dvifile)
16895 (error nil))
16896 (if (not (file-exists-p pngfile))
16897 (if org-format-latex-signal-error
16898 (error "Failed to create png file from %s" texfile)
16899 (message "Failed to create png file from %s" texfile)
16900 nil)
16901 ;; Use the requested file name and clean up
16902 (copy-file pngfile tofile 'replace)
16903 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
16904 (delete-file (concat texfilebase e)))
16905 pngfile))))
16907 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
16908 "Fill a LaTeX header template TPL.
16909 In the template, the following place holders will be recognized:
16911 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
16912 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
16913 [PACKAGES] \\usepackage statements for PKG
16914 [NO-PACKAGES] do not include PKG
16915 [EXTRA] the string EXTRA
16916 [NO-EXTRA] do not include EXTRA
16918 For backward compatibility, if both the positive and the negative place
16919 holder is missing, the positive one (without the \"NO-\") will be
16920 assumed to be present at the end of the template.
16921 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
16922 EXTRA is a string.
16923 SNIPPETS-P indicates if this is run to create snippet images for HTML."
16924 (let (rpl (end ""))
16925 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
16926 (setq rpl (if (or (match-end 1) (not def-pkg))
16927 "" (org-latex-packages-to-string def-pkg snippets-p t))
16928 tpl (replace-match rpl t t tpl))
16929 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
16931 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
16932 (setq rpl (if (or (match-end 1) (not pkg))
16933 "" (org-latex-packages-to-string pkg snippets-p t))
16934 tpl (replace-match rpl t t tpl))
16935 (if pkg (setq end
16936 (concat end "\n"
16937 (org-latex-packages-to-string pkg snippets-p)))))
16939 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
16940 (setq rpl (if (or (match-end 1) (not extra))
16941 "" (concat extra "\n"))
16942 tpl (replace-match rpl t t tpl))
16943 (if (and extra (string-match "\\S-" extra))
16944 (setq end (concat end "\n" extra))))
16946 (if (string-match "\\S-" end)
16947 (concat tpl "\n" end)
16948 tpl)))
16950 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
16951 "Turn an alist of packages into a string with the \\usepackage macros."
16952 (setq pkg (mapconcat (lambda(p)
16953 (cond
16954 ((stringp p) p)
16955 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
16956 (format "%% Package %s omitted" (cadr p)))
16957 ((equal "" (car p))
16958 (format "\\usepackage{%s}" (cadr p)))
16960 (format "\\usepackage[%s]{%s}"
16961 (car p) (cadr p)))))
16963 "\n"))
16964 (if newline (concat pkg "\n") pkg))
16966 (defun org-dvipng-color (attr)
16967 "Return an rgb color specification for dvipng."
16968 (apply 'format "rgb %s %s %s"
16969 (mapcar 'org-normalize-color
16970 (color-values (face-attribute 'default attr nil)))))
16972 (defun org-normalize-color (value)
16973 "Return string to be used as color value for an RGB component."
16974 (format "%g" (/ value 65535.0)))
16976 ;; Image display
16979 (defvar org-inline-image-overlays nil)
16980 (make-variable-buffer-local 'org-inline-image-overlays)
16982 (defun org-toggle-inline-images (&optional include-linked)
16983 "Toggle the display of inline images.
16984 INCLUDE-LINKED is passed to `org-display-inline-images'."
16985 (interactive "P")
16986 (if org-inline-image-overlays
16987 (progn
16988 (org-remove-inline-images)
16989 (message "Inline image display turned off"))
16990 (org-display-inline-images include-linked)
16991 (if org-inline-image-overlays
16992 (message "%d images displayed inline"
16993 (length org-inline-image-overlays))
16994 (message "No images to display inline"))))
16996 (defun org-display-inline-images (&optional include-linked refresh beg end)
16997 "Display inline images.
16998 Normally only links without a description part are inlined, because this
16999 is how it will work for export. When INCLUDE-LINKED is set, also links
17000 with a description part will be inlined. This can be nice for a quick
17001 look at those images, but it does not reflect what exported files will look
17002 like.
17003 When REFRESH is set, refresh existing images between BEG and END.
17004 This will create new image displays only if necessary.
17005 BEG and END default to the buffer boundaries."
17006 (interactive "P")
17007 (unless refresh
17008 (org-remove-inline-images)
17009 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17010 (save-excursion
17011 (save-restriction
17012 (widen)
17013 (setq beg (or beg (point-min)) end (or end (point-max)))
17014 (goto-char (point-min))
17015 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17016 (substring (org-image-file-name-regexp) 0 -2)
17017 "\\)\\]" (if include-linked "" "\\]")))
17018 old file ov img)
17019 (while (re-search-forward re end t)
17020 (setq old (get-char-property-and-overlay (match-beginning 1)
17021 'org-image-overlay))
17022 (setq file (expand-file-name
17023 (concat (or (match-string 3) "") (match-string 4))))
17024 (when (file-exists-p file)
17025 (if (and (car-safe old) refresh)
17026 (image-refresh (overlay-get (cdr old) 'display))
17027 (setq img (save-match-data (create-image file)))
17028 (when img
17029 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17030 (overlay-put ov 'display img)
17031 (overlay-put ov 'face 'default)
17032 (overlay-put ov 'org-image-overlay t)
17033 (overlay-put ov 'modification-hooks
17034 (list 'org-display-inline-modification-hook))
17035 (push ov org-inline-image-overlays)))))))))
17037 (defun org-display-inline-modification-hook (ov after beg end &optional len)
17038 "Remove inline-display overlay if a corresponding region is modified."
17039 (let ((inhibit-modification-hooks t))
17040 (when (and ov after)
17041 (delete ov org-inline-image-overlays)
17042 (delete-overlay ov))))
17044 (defun org-remove-inline-images ()
17045 "Remove inline display of images."
17046 (interactive)
17047 (mapc 'delete-overlay org-inline-image-overlays)
17048 (setq org-inline-image-overlays nil))
17050 ;;;; Key bindings
17052 ;; Remap outline keys
17053 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17054 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17056 ;; Make `C-c C-x' a prefix key
17057 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17059 ;; TAB key with modifiers
17060 (org-defkey org-mode-map "\C-i" 'org-cycle)
17061 (org-defkey org-mode-map [(tab)] 'org-cycle)
17062 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17063 (org-defkey org-mode-map [(meta tab)] 'pcomplete)
17064 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17065 (org-defkey org-mode-map "\M-\C-i" 'pcomplete)
17066 ;; The following line is necessary under Suse GNU/Linux
17067 (unless (featurep 'xemacs)
17068 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17069 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17070 (define-key org-mode-map [backtab] 'org-shifttab)
17072 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17073 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17074 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17076 ;; Cursor keys with modifiers
17077 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17078 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17079 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17080 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17082 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17083 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17084 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17085 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17087 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17088 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17089 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17090 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17092 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17093 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17094 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17095 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17097 ;; Babel keys
17098 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17099 (mapc (lambda (pair)
17100 (define-key org-babel-map (car pair) (cdr pair)))
17101 org-babel-key-bindings)
17103 ;;; Extra keys for tty access.
17104 ;; We only set them when really needed because otherwise the
17105 ;; menus don't show the simple keys
17107 (when (or org-use-extra-keys
17108 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17109 (not window-system))
17110 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17111 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17112 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17113 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17114 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17115 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17116 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17117 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17118 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17119 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17120 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17121 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17122 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17123 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17124 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17125 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17126 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17127 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17128 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17129 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17130 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17131 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17132 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17133 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17134 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17135 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17136 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17137 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17139 ;; All the other keys
17141 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17142 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17143 (if (boundp 'narrow-map)
17144 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17145 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17146 (if (boundp 'narrow-map)
17147 (org-defkey narrow-map "b" 'org-narrow-to-block)
17148 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17149 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
17150 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
17151 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17152 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17153 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17154 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17155 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17156 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17157 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17158 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17159 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17160 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17161 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17162 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17163 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17164 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17165 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17166 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17167 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17168 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17169 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17170 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17171 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
17172 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
17173 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
17174 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
17175 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
17176 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
17177 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
17178 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
17179 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17180 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17181 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17182 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17183 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
17184 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
17185 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17186 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
17187 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
17188 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
17189 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
17190 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17191 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
17192 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
17193 (org-defkey org-mode-map "\C-c^" 'org-sort)
17194 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
17195 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
17196 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
17197 (org-defkey org-mode-map "\C-m" 'org-return)
17198 (org-defkey org-mode-map "\C-j" 'org-return-indent)
17199 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
17200 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
17201 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
17202 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
17203 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
17204 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
17205 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
17206 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
17207 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
17208 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
17209 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
17210 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
17211 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
17212 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
17213 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
17214 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
17215 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
17216 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
17217 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
17218 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
17219 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
17221 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
17222 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
17223 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
17224 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
17226 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
17227 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
17228 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
17229 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
17230 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
17231 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
17232 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
17233 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
17234 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
17235 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
17236 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
17237 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
17238 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
17239 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
17240 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
17241 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
17242 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
17243 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
17245 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
17246 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
17247 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
17248 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
17249 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
17251 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
17253 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
17255 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
17256 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
17258 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
17261 (when (featurep 'xemacs)
17262 (org-defkey org-mode-map 'button3 'popup-mode-menu))
17265 (defconst org-speed-commands-default
17267 ("Outline Navigation")
17268 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
17269 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
17270 ("f" . (org-speed-move-safe 'org-forward-same-level))
17271 ("b" . (org-speed-move-safe 'org-backward-same-level))
17272 ("u" . (org-speed-move-safe 'outline-up-heading))
17273 ("j" . org-goto)
17274 ("g" . (org-refile t))
17275 ("Outline Visibility")
17276 ("c" . org-cycle)
17277 ("C" . org-shifttab)
17278 (" " . org-display-outline-path)
17279 ("Outline Structure Editing")
17280 ("U" . org-shiftmetaup)
17281 ("D" . org-shiftmetadown)
17282 ("r" . org-metaright)
17283 ("l" . org-metaleft)
17284 ("R" . org-shiftmetaright)
17285 ("L" . org-shiftmetaleft)
17286 ("i" . (progn (forward-char 1) (call-interactively
17287 'org-insert-heading-respect-content)))
17288 ("^" . org-sort)
17289 ("w" . org-refile)
17290 ("a" . org-archive-subtree-default-with-confirmation)
17291 ("." . org-mark-subtree)
17292 ("Clock Commands")
17293 ("I" . org-clock-in)
17294 ("O" . org-clock-out)
17295 ("Meta Data Editing")
17296 ("t" . org-todo)
17297 ("0" . (org-priority ?\ ))
17298 ("1" . (org-priority ?A))
17299 ("2" . (org-priority ?B))
17300 ("3" . (org-priority ?C))
17301 (";" . org-set-tags-command)
17302 ("e" . org-set-effort)
17303 ("Agenda Views etc")
17304 ("v" . org-agenda)
17305 ("/" . org-sparse-tree)
17306 ("Misc")
17307 ("o" . org-open-at-point)
17308 ("?" . org-speed-command-help)
17309 ("<" . (org-agenda-set-restriction-lock 'subtree))
17310 (">" . (org-agenda-remove-restriction-lock))
17312 "The default speed commands.")
17314 (defun org-print-speed-command (e)
17315 (if (> (length (car e)) 1)
17316 (progn
17317 (princ "\n")
17318 (princ (car e))
17319 (princ "\n")
17320 (princ (make-string (length (car e)) ?-))
17321 (princ "\n"))
17322 (princ (car e))
17323 (princ " ")
17324 (if (symbolp (cdr e))
17325 (princ (symbol-name (cdr e)))
17326 (prin1 (cdr e)))
17327 (princ "\n")))
17329 (defun org-speed-command-help ()
17330 "Show the available speed commands."
17331 (interactive)
17332 (if (not org-use-speed-commands)
17333 (error "Speed commands are not activated, customize `org-use-speed-commands'")
17334 (with-output-to-temp-buffer "*Help*"
17335 (princ "User-defined Speed commands\n===========================\n")
17336 (mapc 'org-print-speed-command org-speed-commands-user)
17337 (princ "\n")
17338 (princ "Built-in Speed commands\n=======================\n")
17339 (mapc 'org-print-speed-command org-speed-commands-default))
17340 (with-current-buffer "*Help*"
17341 (setq truncate-lines t))))
17343 (defun org-speed-move-safe (cmd)
17344 "Execute CMD, but make sure that the cursor always ends up in a headline.
17345 If not, return to the original position and throw an error."
17346 (interactive)
17347 (let ((pos (point)))
17348 (call-interactively cmd)
17349 (unless (and (bolp) (org-on-heading-p))
17350 (goto-char pos)
17351 (error "Boundary reached while executing %s" cmd))))
17353 (defvar org-self-insert-command-undo-counter 0)
17355 (defvar org-table-auto-blank-field) ; defined in org-table.el
17356 (defvar org-speed-command nil)
17358 (defun org-speed-command-default-hook (keys)
17359 "Hook for activating single-letter speed commands.
17360 `org-speed-commands-default' specifies a minimal command set.
17361 Use `org-speed-commands-user' for further customization."
17362 (when (or (and (bolp) (looking-at org-outline-regexp))
17363 (and (functionp org-use-speed-commands)
17364 (funcall org-use-speed-commands)))
17365 (cdr (assoc keys (append org-speed-commands-user
17366 org-speed-commands-default)))))
17368 (defun org-babel-speed-command-hook (keys)
17369 "Hook for activating single-letter code block commands."
17370 (when (and (bolp) (looking-at org-babel-src-block-regexp))
17371 (cdr (assoc keys org-babel-key-bindings))))
17373 (defcustom org-speed-command-hook
17374 '(org-speed-command-default-hook org-babel-speed-command-hook)
17375 "Hook for activating speed commands at strategic locations.
17376 Hook functions are called in sequence until a valid handler is
17377 found.
17379 Each hook takes a single argument, a user-pressed command key
17380 which is also a `self-insert-command' from the global map.
17382 Within the hook, examine the cursor position and the command key
17383 and return nil or a valid handler as appropriate. Handler could
17384 be one of an interactive command, a function, or a form.
17386 Set `org-use-speed-commands' to non-nil value to enable this
17387 hook. The default setting is `org-speed-command-default-hook'."
17388 :group 'org-structure
17389 :type 'hook)
17391 (defun org-self-insert-command (N)
17392 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
17393 If the cursor is in a table looking at whitespace, the whitespace is
17394 overwritten, and the table is not marked as requiring realignment."
17395 (interactive "p")
17396 (cond
17397 ((and org-use-speed-commands
17398 (setq org-speed-command
17399 (run-hook-with-args-until-success
17400 'org-speed-command-hook (this-command-keys))))
17401 (cond
17402 ((commandp org-speed-command)
17403 (setq this-command org-speed-command)
17404 (call-interactively org-speed-command))
17405 ((functionp org-speed-command)
17406 (funcall org-speed-command))
17407 ((and org-speed-command (listp org-speed-command))
17408 (eval org-speed-command))
17409 (t (let (org-use-speed-commands)
17410 (call-interactively 'org-self-insert-command)))))
17411 ((and
17412 (org-table-p)
17413 (progn
17414 ;; check if we blank the field, and if that triggers align
17415 (and (featurep 'org-table) org-table-auto-blank-field
17416 (member last-command
17417 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
17418 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
17419 ;; got extra space, this field does not determine column width
17420 (let (org-table-may-need-update) (org-table-blank-field))
17421 ;; no extra space, this field may determine column width
17422 (org-table-blank-field)))
17424 (eq N 1)
17425 (looking-at "[^|\n]* |"))
17426 (let (org-table-may-need-update)
17427 (goto-char (1- (match-end 0)))
17428 (delete-char -1)
17429 (goto-char (match-beginning 0))
17430 (self-insert-command N)))
17432 (setq org-table-may-need-update t)
17433 (self-insert-command N)
17434 (org-fix-tags-on-the-fly)
17435 (if org-self-insert-cluster-for-undo
17436 (if (not (eq last-command 'org-self-insert-command))
17437 (setq org-self-insert-command-undo-counter 1)
17438 (if (>= org-self-insert-command-undo-counter 20)
17439 (setq org-self-insert-command-undo-counter 1)
17440 (and (> org-self-insert-command-undo-counter 0)
17441 buffer-undo-list (listp buffer-undo-list)
17442 (not (cadr buffer-undo-list)) ; remove nil entry
17443 (setcdr buffer-undo-list (cddr buffer-undo-list)))
17444 (setq org-self-insert-command-undo-counter
17445 (1+ org-self-insert-command-undo-counter))))))))
17447 (defun org-fix-tags-on-the-fly ()
17448 (when (and (equal (char-after (point-at-bol)) ?*)
17449 (org-on-heading-p))
17450 (org-align-tags-here org-tags-column)))
17452 (defun org-delete-backward-char (N)
17453 "Like `delete-backward-char', insert whitespace at field end in tables.
17454 When deleting backwards, in tables this function will insert whitespace in
17455 front of the next \"|\" separator, to keep the table aligned. The table will
17456 still be marked for re-alignment if the field did fill the entire column,
17457 because, in this case the deletion might narrow the column."
17458 (interactive "p")
17459 (if (and (org-table-p)
17460 (eq N 1)
17461 (string-match "|" (buffer-substring (point-at-bol) (point)))
17462 (looking-at ".*?|"))
17463 (let ((pos (point))
17464 (noalign (looking-at "[^|\n\r]* |"))
17465 (c org-table-may-need-update))
17466 (backward-delete-char N)
17467 (if (not overwrite-mode)
17468 (progn
17469 (skip-chars-forward "^|")
17470 (insert " ")
17471 (goto-char (1- pos))))
17472 ;; noalign: if there were two spaces at the end, this field
17473 ;; does not determine the width of the column.
17474 (if noalign (setq org-table-may-need-update c)))
17475 (backward-delete-char N)
17476 (org-fix-tags-on-the-fly)))
17478 (defun org-delete-char (N)
17479 "Like `delete-char', but insert whitespace at field end in tables.
17480 When deleting characters, in tables this function will insert whitespace in
17481 front of the next \"|\" separator, to keep the table aligned. The table will
17482 still be marked for re-alignment if the field did fill the entire column,
17483 because, in this case the deletion might narrow the column."
17484 (interactive "p")
17485 (if (and (org-table-p)
17486 (not (bolp))
17487 (not (= (char-after) ?|))
17488 (eq N 1))
17489 (if (looking-at ".*?|")
17490 (let ((pos (point))
17491 (noalign (looking-at "[^|\n\r]* |"))
17492 (c org-table-may-need-update))
17493 (replace-match (concat
17494 (substring (match-string 0) 1 -1)
17495 " |"))
17496 (goto-char pos)
17497 ;; noalign: if there were two spaces at the end, this field
17498 ;; does not determine the width of the column.
17499 (if noalign (setq org-table-may-need-update c)))
17500 (delete-char N))
17501 (delete-char N)
17502 (org-fix-tags-on-the-fly)))
17504 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
17505 (put 'org-self-insert-command 'delete-selection t)
17506 (put 'orgtbl-self-insert-command 'delete-selection t)
17507 (put 'org-delete-char 'delete-selection 'supersede)
17508 (put 'org-delete-backward-char 'delete-selection 'supersede)
17509 (put 'org-yank 'delete-selection 'yank)
17511 ;; Make `flyspell-mode' delay after some commands
17512 (put 'org-self-insert-command 'flyspell-delayed t)
17513 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
17514 (put 'org-delete-char 'flyspell-delayed t)
17515 (put 'org-delete-backward-char 'flyspell-delayed t)
17517 ;; Make pabbrev-mode expand after org-mode commands
17518 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
17519 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
17521 ;; How to do this: Measure non-white length of current string
17522 ;; If equal to column width, we should realign.
17524 (defun org-remap (map &rest commands)
17525 "In MAP, remap the functions given in COMMANDS.
17526 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
17527 (let (new old)
17528 (while commands
17529 (setq old (pop commands) new (pop commands))
17530 (if (fboundp 'command-remapping)
17531 (org-defkey map (vector 'remap old) new)
17532 (substitute-key-definition old new map global-map)))))
17534 (when (eq org-enable-table-editor 'optimized)
17535 ;; If the user wants maximum table support, we need to hijack
17536 ;; some standard editing functions
17537 (org-remap org-mode-map
17538 'self-insert-command 'org-self-insert-command
17539 'delete-char 'org-delete-char
17540 'delete-backward-char 'org-delete-backward-char)
17541 (org-defkey org-mode-map "|" 'org-force-self-insert))
17543 (defvar org-ctrl-c-ctrl-c-hook nil
17544 "Hook for functions attaching themselves to `C-c C-c'.
17546 This can be used to add additional functionality to the C-c C-c
17547 key which executes context-dependent commands. This hook is run
17548 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
17549 run after the last test.
17551 Each function will be called with no arguments. The function
17552 must check if the context is appropriate for it to act. If yes,
17553 it should do its thing and then return a non-nil value. If the
17554 context is wrong, just do nothing and return nil.")
17556 (defvar org-ctrl-c-ctrl-c-final-hook nil
17557 "Hook for functions attaching themselves to `C-c C-c'.
17559 This can be used to add additional functionality to the C-c C-c
17560 key which executes context-dependent commands. This hook is run
17561 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
17562 before the first test.
17564 Each function will be called with no arguments. The function
17565 must check if the context is appropriate for it to act. If yes,
17566 it should do its thing and then return a non-nil value. If the
17567 context is wrong, just do nothing and return nil.")
17569 (defvar org-tab-first-hook nil
17570 "Hook for functions to attach themselves to TAB.
17571 See `org-ctrl-c-ctrl-c-hook' for more information.
17572 This hook runs as the first action when TAB is pressed, even before
17573 `org-cycle' messes around with the `outline-regexp' to cater for
17574 inline tasks and plain list item folding.
17575 If any function in this hook returns t, any other actions that
17576 would have been caused by TAB (such as table field motion or visibility
17577 cycling) will not occur.")
17579 (defvar org-tab-after-check-for-table-hook nil
17580 "Hook for functions to attach themselves to TAB.
17581 See `org-ctrl-c-ctrl-c-hook' for more information.
17582 This hook runs after it has been established that the cursor is not in a
17583 table, but before checking if the cursor is in a headline or if global cycling
17584 should be done.
17585 If any function in this hook returns t, not other actions like visibility
17586 cycling will be done.")
17588 (defvar org-tab-after-check-for-cycling-hook nil
17589 "Hook for functions to attach themselves to TAB.
17590 See `org-ctrl-c-ctrl-c-hook' for more information.
17591 This hook runs after it has been established that not table field motion and
17592 not visibility should be done because of current context. This is probably
17593 the place where a package like yasnippets can hook in.")
17595 (defvar org-tab-before-tab-emulation-hook nil
17596 "Hook for functions to attach themselves to TAB.
17597 See `org-ctrl-c-ctrl-c-hook' for more information.
17598 This hook runs after every other options for TAB have been exhausted, but
17599 before indentation and \t insertion takes place.")
17601 (defvar org-metaleft-hook nil
17602 "Hook for functions attaching themselves to `M-left'.
17603 See `org-ctrl-c-ctrl-c-hook' for more information.")
17604 (defvar org-metaright-hook nil
17605 "Hook for functions attaching themselves to `M-right'.
17606 See `org-ctrl-c-ctrl-c-hook' for more information.")
17607 (defvar org-metaup-hook nil
17608 "Hook for functions attaching themselves to `M-up'.
17609 See `org-ctrl-c-ctrl-c-hook' for more information.")
17610 (defvar org-metadown-hook nil
17611 "Hook for functions attaching themselves to `M-down'.
17612 See `org-ctrl-c-ctrl-c-hook' for more information.")
17613 (defvar org-shiftmetaleft-hook nil
17614 "Hook for functions attaching themselves to `M-S-left'.
17615 See `org-ctrl-c-ctrl-c-hook' for more information.")
17616 (defvar org-shiftmetaright-hook nil
17617 "Hook for functions attaching themselves to `M-S-right'.
17618 See `org-ctrl-c-ctrl-c-hook' for more information.")
17619 (defvar org-shiftmetaup-hook nil
17620 "Hook for functions attaching themselves to `M-S-up'.
17621 See `org-ctrl-c-ctrl-c-hook' for more information.")
17622 (defvar org-shiftmetadown-hook nil
17623 "Hook for functions attaching themselves to `M-S-down'.
17624 See `org-ctrl-c-ctrl-c-hook' for more information.")
17625 (defvar org-metareturn-hook nil
17626 "Hook for functions attaching themselves to `M-RET'.
17627 See `org-ctrl-c-ctrl-c-hook' for more information.")
17628 (defvar org-shiftup-hook nil
17629 "Hook for functions attaching themselves to `S-up'.
17630 See `org-ctrl-c-ctrl-c-hook' for more information.")
17631 (defvar org-shiftup-final-hook nil
17632 "Hook for functions attaching themselves to `S-up'.
17633 This one runs after all other options except shift-select have been excluded.
17634 See `org-ctrl-c-ctrl-c-hook' for more information.")
17635 (defvar org-shiftdown-hook nil
17636 "Hook for functions attaching themselves to `S-down'.
17637 See `org-ctrl-c-ctrl-c-hook' for more information.")
17638 (defvar org-shiftdown-final-hook nil
17639 "Hook for functions attaching themselves to `S-down'.
17640 This one runs after all other options except shift-select have been excluded.
17641 See `org-ctrl-c-ctrl-c-hook' for more information.")
17642 (defvar org-shiftleft-hook nil
17643 "Hook for functions attaching themselves to `S-left'.
17644 See `org-ctrl-c-ctrl-c-hook' for more information.")
17645 (defvar org-shiftleft-final-hook nil
17646 "Hook for functions attaching themselves to `S-left'.
17647 This one runs after all other options except shift-select have been excluded.
17648 See `org-ctrl-c-ctrl-c-hook' for more information.")
17649 (defvar org-shiftright-hook nil
17650 "Hook for functions attaching themselves to `S-right'.
17651 See `org-ctrl-c-ctrl-c-hook' for more information.")
17652 (defvar org-shiftright-final-hook nil
17653 "Hook for functions attaching themselves to `S-right'.
17654 This one runs after all other options except shift-select have been excluded.
17655 See `org-ctrl-c-ctrl-c-hook' for more information.")
17657 (defun org-modifier-cursor-error ()
17658 "Throw an error, a modified cursor command was applied in wrong context."
17659 (error "This command is active in special context like tables, headlines or items"))
17661 (defun org-shiftselect-error ()
17662 "Throw an error because Shift-Cursor command was applied in wrong context."
17663 (if (and (boundp 'shift-select-mode) shift-select-mode)
17664 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
17665 (error "This command works only in special context like headlines or timestamps")))
17667 (defun org-call-for-shift-select (cmd)
17668 (let ((this-command-keys-shift-translated t))
17669 (call-interactively cmd)))
17671 (defun org-shifttab (&optional arg)
17672 "Global visibility cycling or move to previous table field.
17673 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
17674 on context.
17675 See the individual commands for more information."
17676 (interactive "P")
17677 (cond
17678 ((org-at-table-p) (call-interactively 'org-table-previous-field))
17679 ((integerp arg)
17680 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
17681 (message "Content view to level: %d" arg)
17682 (org-content (prefix-numeric-value arg2))
17683 (setq org-cycle-global-status 'overview)))
17684 (t (call-interactively 'org-global-cycle))))
17686 (defun org-shiftmetaleft ()
17687 "Promote subtree or delete table column.
17688 Calls `org-promote-subtree', `org-outdent-item',
17689 or `org-table-delete-column', depending on context.
17690 See the individual commands for more information."
17691 (interactive)
17692 (cond
17693 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
17694 ((org-at-table-p) (call-interactively 'org-table-delete-column))
17695 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
17696 ((org-at-item-p) (call-interactively 'org-outdent-item-tree))
17697 (t (org-modifier-cursor-error))))
17699 (defun org-shiftmetaright ()
17700 "Demote subtree or insert table column.
17701 Calls `org-demote-subtree', `org-indent-item',
17702 or `org-table-insert-column', depending on context.
17703 See the individual commands for more information."
17704 (interactive)
17705 (cond
17706 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
17707 ((org-at-table-p) (call-interactively 'org-table-insert-column))
17708 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
17709 ((org-at-item-p) (call-interactively 'org-indent-item-tree))
17710 (t (org-modifier-cursor-error))))
17712 (defun org-shiftmetaup (&optional arg)
17713 "Move subtree up or kill table row.
17714 Calls `org-move-subtree-up' or `org-table-kill-row' or
17715 `org-move-item-up' depending on context. See the individual commands
17716 for more information."
17717 (interactive "P")
17718 (cond
17719 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
17720 ((org-at-table-p) (call-interactively 'org-table-kill-row))
17721 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17722 ((org-at-item-p) (call-interactively 'org-move-item-up))
17723 (t (org-modifier-cursor-error))))
17725 (defun org-shiftmetadown (&optional arg)
17726 "Move subtree down or insert table row.
17727 Calls `org-move-subtree-down' or `org-table-insert-row' or
17728 `org-move-item-down', depending on context. See the individual
17729 commands for more information."
17730 (interactive "P")
17731 (cond
17732 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
17733 ((org-at-table-p) (call-interactively 'org-table-insert-row))
17734 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17735 ((org-at-item-p) (call-interactively 'org-move-item-down))
17736 (t (org-modifier-cursor-error))))
17738 (defsubst org-hidden-tree-error ()
17739 (error
17740 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
17742 (defun org-metaleft (&optional arg)
17743 "Promote heading or move table column to left.
17744 Calls `org-do-promote' or `org-table-move-column', depending on context.
17745 With no specific context, calls the Emacs default `backward-word'.
17746 See the individual commands for more information."
17747 (interactive "P")
17748 (cond
17749 ((run-hook-with-args-until-success 'org-metaleft-hook))
17750 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
17751 ((org-with-limited-levels
17752 (or (org-on-heading-p)
17753 (and (org-region-active-p)
17754 (save-excursion
17755 (goto-char (region-beginning))
17756 (org-on-heading-p)))))
17757 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17758 (call-interactively 'org-do-promote))
17759 ;; At an inline task.
17760 ((org-on-heading-p)
17761 (call-interactively 'org-inlinetask-promote))
17762 ((or (org-at-item-p)
17763 (and (org-region-active-p)
17764 (save-excursion
17765 (goto-char (region-beginning))
17766 (org-at-item-p))))
17767 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17768 (call-interactively 'org-outdent-item))
17769 (t (call-interactively 'backward-word))))
17771 (defun org-metaright (&optional arg)
17772 "Demote subtree or move table column to right.
17773 Calls `org-do-demote' or `org-table-move-column', depending on context.
17774 With no specific context, calls the Emacs default `forward-word'.
17775 See the individual commands for more information."
17776 (interactive "P")
17777 (cond
17778 ((run-hook-with-args-until-success 'org-metaright-hook))
17779 ((org-at-table-p) (call-interactively 'org-table-move-column))
17780 ((org-with-limited-levels
17781 (or (org-on-heading-p)
17782 (and (org-region-active-p)
17783 (save-excursion
17784 (goto-char (region-beginning))
17785 (org-on-heading-p)))))
17786 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17787 (call-interactively 'org-do-demote))
17788 ;; At an inline task.
17789 ((org-on-heading-p)
17790 (call-interactively 'org-inlinetask-demote))
17791 ((or (org-at-item-p)
17792 (and (org-region-active-p)
17793 (save-excursion
17794 (goto-char (region-beginning))
17795 (org-at-item-p))))
17796 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17797 (call-interactively 'org-indent-item))
17798 (t (call-interactively 'forward-word))))
17800 (defun org-check-for-hidden (what)
17801 "Check if there are hidden headlines/items in the current visual line.
17802 WHAT can be either `headlines' or `items'. If the current line is
17803 an outline or item heading and it has a folded subtree below it,
17804 this function returns t, nil otherwise."
17805 (let ((re (cond
17806 ((eq what 'headlines) org-outline-regexp-bol)
17807 ((eq what 'items) (org-item-beginning-re))
17808 (t (error "This should not happen"))))
17809 beg end)
17810 (save-excursion
17811 (catch 'exit
17812 (unless (org-region-active-p)
17813 (setq beg (point-at-bol))
17814 (beginning-of-line 2)
17815 (while (and (not (eobp)) ;; this is like `next-line'
17816 (get-char-property (1- (point)) 'invisible))
17817 (beginning-of-line 2))
17818 (setq end (point))
17819 (goto-char beg)
17820 (goto-char (point-at-eol))
17821 (setq end (max end (point)))
17822 (while (re-search-forward re end t)
17823 (if (get-char-property (match-beginning 0) 'invisible)
17824 (throw 'exit t))))
17825 nil))))
17827 (defun org-metaup (&optional arg)
17828 "Move subtree up or move table row up.
17829 Calls `org-move-subtree-up' or `org-table-move-row' or
17830 `org-move-item-up', depending on context. See the individual commands
17831 for more information."
17832 (interactive "P")
17833 (cond
17834 ((run-hook-with-args-until-success 'org-metaup-hook))
17835 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
17836 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17837 ((org-at-item-p) (call-interactively 'org-move-item-up))
17838 (t (transpose-lines 1) (beginning-of-line -1))))
17840 (defun org-metadown (&optional arg)
17841 "Move subtree down or move table row down.
17842 Calls `org-move-subtree-down' or `org-table-move-row' or
17843 `org-move-item-down', depending on context. See the individual
17844 commands for more information."
17845 (interactive "P")
17846 (cond
17847 ((run-hook-with-args-until-success 'org-metadown-hook))
17848 ((org-at-table-p) (call-interactively 'org-table-move-row))
17849 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17850 ((org-at-item-p) (call-interactively 'org-move-item-down))
17851 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
17853 (defun org-shiftup (&optional arg)
17854 "Increase item in timestamp or increase priority of current headline.
17855 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
17856 depending on context. See the individual commands for more information."
17857 (interactive "P")
17858 (cond
17859 ((run-hook-with-args-until-success 'org-shiftup-hook))
17860 ((and org-support-shift-select (org-region-active-p))
17861 (org-call-for-shift-select 'previous-line))
17862 ((org-at-timestamp-p t)
17863 (call-interactively (if org-edit-timestamp-down-means-later
17864 'org-timestamp-down 'org-timestamp-up)))
17865 ((and (not (eq org-support-shift-select 'always))
17866 org-enable-priority-commands
17867 (org-on-heading-p))
17868 (call-interactively 'org-priority-up))
17869 ((and (not org-support-shift-select) (org-at-item-p))
17870 (call-interactively 'org-previous-item))
17871 ((org-clocktable-try-shift 'up arg))
17872 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
17873 (org-support-shift-select
17874 (org-call-for-shift-select 'previous-line))
17875 (t (org-shiftselect-error))))
17877 (defun org-shiftdown (&optional arg)
17878 "Decrease item in timestamp or decrease priority of current headline.
17879 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
17880 depending on context. See the individual commands for more information."
17881 (interactive "P")
17882 (cond
17883 ((run-hook-with-args-until-success 'org-shiftdown-hook))
17884 ((and org-support-shift-select (org-region-active-p))
17885 (org-call-for-shift-select 'next-line))
17886 ((org-at-timestamp-p t)
17887 (call-interactively (if org-edit-timestamp-down-means-later
17888 'org-timestamp-up 'org-timestamp-down)))
17889 ((and (not (eq org-support-shift-select 'always))
17890 org-enable-priority-commands
17891 (org-on-heading-p))
17892 (call-interactively 'org-priority-down))
17893 ((and (not org-support-shift-select) (org-at-item-p))
17894 (call-interactively 'org-next-item))
17895 ((org-clocktable-try-shift 'down arg))
17896 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
17897 (org-support-shift-select
17898 (org-call-for-shift-select 'next-line))
17899 (t (org-shiftselect-error))))
17901 (defun org-shiftright (&optional arg)
17902 "Cycle the thing at point or in the current line, depending on context.
17903 Depending on context, this does one of the following:
17905 - switch a timestamp at point one day into the future
17906 - on a headline, switch to the next TODO keyword.
17907 - on an item, switch entire list to the next bullet type
17908 - on a property line, switch to the next allowed value
17909 - on a clocktable definition line, move time block into the future"
17910 (interactive "P")
17911 (cond
17912 ((run-hook-with-args-until-success 'org-shiftright-hook))
17913 ((and org-support-shift-select (org-region-active-p))
17914 (org-call-for-shift-select 'forward-char))
17915 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
17916 ((and (not (eq org-support-shift-select 'always))
17917 (org-on-heading-p))
17918 (let ((org-inhibit-logging
17919 (not org-treat-S-cursor-todo-selection-as-state-change))
17920 (org-inhibit-blocking
17921 (not org-treat-S-cursor-todo-selection-as-state-change)))
17922 (org-call-with-arg 'org-todo 'right)))
17923 ((or (and org-support-shift-select
17924 (not (eq org-support-shift-select 'always))
17925 (org-at-item-bullet-p))
17926 (and (not org-support-shift-select) (org-at-item-p)))
17927 (org-call-with-arg 'org-cycle-list-bullet nil))
17928 ((and (not (eq org-support-shift-select 'always))
17929 (org-at-property-p))
17930 (call-interactively 'org-property-next-allowed-value))
17931 ((org-clocktable-try-shift 'right arg))
17932 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
17933 (org-support-shift-select
17934 (org-call-for-shift-select 'forward-char))
17935 (t (org-shiftselect-error))))
17937 (defun org-shiftleft (&optional arg)
17938 "Cycle the thing at point or in the current line, depending on context.
17939 Depending on context, this does one of the following:
17941 - switch a timestamp at point one day into the past
17942 - on a headline, switch to the previous TODO keyword.
17943 - on an item, switch entire list to the previous bullet type
17944 - on a property line, switch to the previous allowed value
17945 - on a clocktable definition line, move time block into the past"
17946 (interactive "P")
17947 (cond
17948 ((run-hook-with-args-until-success 'org-shiftleft-hook))
17949 ((and org-support-shift-select (org-region-active-p))
17950 (org-call-for-shift-select 'backward-char))
17951 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
17952 ((and (not (eq org-support-shift-select 'always))
17953 (org-on-heading-p))
17954 (let ((org-inhibit-logging
17955 (not org-treat-S-cursor-todo-selection-as-state-change))
17956 (org-inhibit-blocking
17957 (not org-treat-S-cursor-todo-selection-as-state-change)))
17958 (org-call-with-arg 'org-todo 'left)))
17959 ((or (and org-support-shift-select
17960 (not (eq org-support-shift-select 'always))
17961 (org-at-item-bullet-p))
17962 (and (not org-support-shift-select) (org-at-item-p)))
17963 (org-call-with-arg 'org-cycle-list-bullet 'previous))
17964 ((and (not (eq org-support-shift-select 'always))
17965 (org-at-property-p))
17966 (call-interactively 'org-property-previous-allowed-value))
17967 ((org-clocktable-try-shift 'left arg))
17968 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
17969 (org-support-shift-select
17970 (org-call-for-shift-select 'backward-char))
17971 (t (org-shiftselect-error))))
17973 (defun org-shiftcontrolright ()
17974 "Switch to next TODO set."
17975 (interactive)
17976 (cond
17977 ((and org-support-shift-select (org-region-active-p))
17978 (org-call-for-shift-select 'forward-word))
17979 ((and (not (eq org-support-shift-select 'always))
17980 (org-on-heading-p))
17981 (org-call-with-arg 'org-todo 'nextset))
17982 (org-support-shift-select
17983 (org-call-for-shift-select 'forward-word))
17984 (t (org-shiftselect-error))))
17986 (defun org-shiftcontrolleft ()
17987 "Switch to previous TODO set."
17988 (interactive)
17989 (cond
17990 ((and org-support-shift-select (org-region-active-p))
17991 (org-call-for-shift-select 'backward-word))
17992 ((and (not (eq org-support-shift-select 'always))
17993 (org-on-heading-p))
17994 (org-call-with-arg 'org-todo 'previousset))
17995 (org-support-shift-select
17996 (org-call-for-shift-select 'backward-word))
17997 (t (org-shiftselect-error))))
17999 (defun org-shiftcontrolup ()
18000 "Change timestamps synchronously up in CLOCK log lines."
18001 (interactive)
18002 (cond ((and (not org-support-shift-select)
18003 (org-at-clock-log-p)
18004 (org-at-timestamp-p t))
18005 (org-clock-timestamps-up))
18006 (t (org-shiftselect-error))))
18008 (defun org-shiftcontroldown ()
18009 "Change timestamps synchronously down in CLOCK log lines."
18010 (interactive)
18011 (cond ((and (not org-support-shift-select)
18012 (org-at-clock-log-p)
18013 (org-at-timestamp-p t))
18014 (org-clock-timestamps-down))
18015 (t (org-shiftselect-error))))
18017 (defun org-ctrl-c-ret ()
18018 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18019 (interactive)
18020 (cond
18021 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18022 (t (call-interactively 'org-insert-heading))))
18024 (defun org-find-visible ()
18025 (let ((s (point)))
18026 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18027 (get-char-property s 'invisible)))
18029 (defun org-find-invisible ()
18030 (let ((s (point)))
18031 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18032 (not (get-char-property s 'invisible))))
18035 (defun org-copy-visible (beg end)
18036 "Copy the visible parts of the region."
18037 (interactive "r")
18038 (let (snippets s)
18039 (save-excursion
18040 (save-restriction
18041 (narrow-to-region beg end)
18042 (setq s (goto-char (point-min)))
18043 (while (not (= (point) (point-max)))
18044 (goto-char (org-find-invisible))
18045 (push (buffer-substring s (point)) snippets)
18046 (setq s (goto-char (org-find-visible))))))
18047 (kill-new (apply 'concat (nreverse snippets)))))
18049 (defun org-copy-special ()
18050 "Copy region in table or copy current subtree.
18051 Calls `org-table-copy' or `org-copy-subtree', depending on context.
18052 See the individual commands for more information."
18053 (interactive)
18054 (call-interactively
18055 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
18057 (defun org-cut-special ()
18058 "Cut region in table or cut current subtree.
18059 Calls `org-table-copy' or `org-cut-subtree', depending on context.
18060 See the individual commands for more information."
18061 (interactive)
18062 (call-interactively
18063 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
18065 (defun org-paste-special (arg)
18066 "Paste rectangular region into table, or past subtree relative to level.
18067 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
18068 See the individual commands for more information."
18069 (interactive "P")
18070 (if (org-at-table-p)
18071 (org-table-paste-rectangle)
18072 (org-paste-subtree arg)))
18074 (defun org-edit-special (&optional arg)
18075 "Call a special editor for the stuff at point.
18076 When at a table, call the formula editor with `org-table-edit-formulas'.
18077 When at the first line of an src example, call `org-edit-src-code'.
18078 When in an #+include line, visit the include file. Otherwise call
18079 `ffap' to visit the file at point."
18080 (interactive)
18081 ;; possibly prep session before editing source
18082 (when arg
18083 (let* ((info (org-babel-get-src-block-info))
18084 (lang (nth 0 info))
18085 (params (nth 2 info))
18086 (session (cdr (assoc :session params))))
18087 (when (and info session) ;; we are in a source-code block with a session
18088 (funcall
18089 (intern (concat "org-babel-prep-session:" lang)) session params))))
18090 (cond ;; proceed with `org-edit-special'
18091 ((save-excursion
18092 (beginning-of-line 1)
18093 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
18094 (find-file (org-trim (match-string 1))))
18095 ((org-edit-src-code))
18096 ((org-edit-fixed-width-region))
18097 ((org-at-table.el-p)
18098 (org-edit-src-code))
18099 ((or (org-at-table-p)
18100 (save-excursion
18101 (beginning-of-line 1)
18102 (looking-at "[ \t]*#\\+TBLFM:")))
18103 (call-interactively 'org-table-edit-formulas))
18104 (t (call-interactively 'ffap))))
18106 (defvar org-table-coordinate-overlays) ; defined in org-table.el
18107 (defun org-ctrl-c-ctrl-c (&optional arg)
18108 "Set tags in headline, or update according to changed information at point.
18110 This command does many different things, depending on context:
18112 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
18113 this is what we do.
18115 - If the cursor is on a statistics cookie, update it.
18117 - If the cursor is in a headline, prompt for tags and insert them
18118 into the current line, aligned to `org-tags-column'. When called
18119 with prefix arg, realign all tags in the current buffer.
18121 - If the cursor is in one of the special #+KEYWORD lines, this
18122 triggers scanning the buffer for these lines and updating the
18123 information.
18125 - If the cursor is inside a table, realign the table. This command
18126 works even if the automatic table editor has been turned off.
18128 - If the cursor is on a #+TBLFM line, re-apply the formulas to
18129 the entire table.
18131 - If the cursor is at a footnote reference or definition, jump to
18132 the corresponding definition or references, respectively.
18134 - If the cursor is a the beginning of a dynamic block, update it.
18136 - If the current buffer is a capture buffer, close note and file it.
18138 - If the cursor is on a <<<target>>>, update radio targets and
18139 corresponding links in this buffer.
18141 - If the cursor is on a numbered item in a plain list, renumber the
18142 ordered list.
18144 - If the cursor is on a checkbox, toggle it.
18146 - If the cursor is on a code block, evaluate it. The variable
18147 `org-confirm-babel-evaluate' can be used to control prompting
18148 before code block evaluation, by default every code block
18149 evaluation requires confirmation. Code block evaluation can be
18150 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
18151 (interactive "P")
18152 (let ((org-enable-table-editor t))
18153 (cond
18154 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
18155 org-occur-highlights
18156 org-latex-fragment-image-overlays)
18157 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
18158 (org-remove-occur-highlights)
18159 (org-remove-latex-fragment-image-overlays)
18160 (message "Temporary highlights/overlays removed from current buffer"))
18161 ((and (local-variable-p 'org-finish-function (current-buffer))
18162 (fboundp org-finish-function))
18163 (funcall org-finish-function))
18164 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
18165 ((or (looking-at org-property-start-re)
18166 (org-at-property-p))
18167 (call-interactively 'org-property-action))
18168 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
18169 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
18170 (or (org-on-heading-p) (org-at-item-p)))
18171 (call-interactively 'org-update-statistics-cookies))
18172 ((org-on-heading-p) (call-interactively 'org-set-tags))
18173 ((org-at-table.el-p)
18174 (message "Use C-c ' to edit table.el tables"))
18175 ((org-at-table-p)
18176 (org-table-maybe-eval-formula)
18177 (if arg
18178 (call-interactively 'org-table-recalculate)
18179 (org-table-maybe-recalculate-line))
18180 (call-interactively 'org-table-align)
18181 (orgtbl-send-table 'maybe))
18182 ((or (org-footnote-at-reference-p)
18183 (org-footnote-at-definition-p))
18184 (call-interactively 'org-footnote-action))
18185 ((org-at-item-checkbox-p)
18186 ;; Cursor at a checkbox: repair list and update checkboxes. Send
18187 ;; list only if at top item.
18188 (let* ((cbox (match-string 1))
18189 (struct (org-list-struct))
18190 (old-struct (copy-tree struct))
18191 (parents (org-list-parents-alist struct))
18192 (orderedp (org-entry-get nil "ORDERED"))
18193 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18194 block-item)
18195 ;; Use a light version of `org-toggle-checkbox' to avoid
18196 ;; computing list structure twice.
18197 (org-list-set-checkbox (point-at-bol) struct
18198 (cond
18199 ((equal arg '(16)) "[-]")
18200 ((equal arg '(4)) nil)
18201 ((equal "[X]" cbox) "[ ]")
18202 (t "[X]")))
18203 ;; Replicate `org-list-write-struct', while grabbing a return
18204 ;; value from `org-list-struct-fix-box'.
18205 (org-list-struct-fix-ind struct parents 2)
18206 (org-list-struct-fix-item-end struct)
18207 (let ((prevs (org-list-prevs-alist struct)))
18208 (org-list-struct-fix-bul struct prevs)
18209 (org-list-struct-fix-ind struct parents)
18210 (setq block-item
18211 (org-list-struct-fix-box struct parents prevs orderedp)))
18212 (org-list-struct-apply-struct struct old-struct)
18213 (org-update-checkbox-count-maybe)
18214 (when block-item
18215 (message
18216 "Checkboxes were removed due to unchecked box at line %d"
18217 (org-current-line block-item)))
18218 (when firstp (org-list-send-list 'maybe))))
18219 ((org-at-item-p)
18220 ;; Cursor at an item: repair list. Do checkbox related actions
18221 ;; only if function was called with an argument. Send list only
18222 ;; if at top item.
18223 (let* ((struct (org-list-struct))
18224 (firstp (= (org-list-get-top-point struct) (point-at-bol))))
18225 (when arg (org-list-set-checkbox (point-at-bol) struct "[ ]"))
18226 (org-list-write-struct struct (org-list-parents-alist struct))
18227 (when arg (org-update-checkbox-count-maybe))
18228 (when firstp (org-list-send-list 'maybe))))
18229 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
18230 ;; Dynamic block
18231 (beginning-of-line 1)
18232 (save-excursion (org-update-dblock)))
18233 ((save-excursion
18234 (beginning-of-line 1)
18235 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
18236 (cond
18237 ((equal (match-string 1) "TBLFM")
18238 ;; Recalculate the table before this line
18239 (save-excursion
18240 (beginning-of-line 1)
18241 (skip-chars-backward " \r\n\t")
18242 (if (org-at-table-p)
18243 (org-call-with-arg 'org-table-recalculate (or arg t)))))
18245 (let ((org-inhibit-startup-visibility-stuff t)
18246 (org-startup-align-all-tables nil))
18247 (when (boundp 'org-table-coordinate-overlays)
18248 (mapc 'delete-overlay org-table-coordinate-overlays)
18249 (setq org-table-coordinate-overlays nil))
18250 (org-save-outline-visibility 'use-markers (org-mode-restart)))
18251 (message "Local setup has been refreshed"))))
18252 ((org-clock-update-time-maybe))
18254 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
18255 (error "C-c C-c can do nothing useful at this location"))))))
18257 (defun org-mode-restart ()
18258 "Restart Org-mode, to scan again for special lines.
18259 Also updates the keyword regular expressions."
18260 (interactive)
18261 (org-mode)
18262 (message "Org-mode restarted"))
18264 (defun org-kill-note-or-show-branches ()
18265 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
18266 (interactive)
18267 (if (not org-finish-function)
18268 (progn
18269 (hide-subtree)
18270 (call-interactively 'show-branches))
18271 (let ((org-note-abort t))
18272 (funcall org-finish-function))))
18274 (defun org-return (&optional indent)
18275 "Goto next table row or insert a newline.
18276 Calls `org-table-next-row' or `newline', depending on context.
18277 See the individual commands for more information."
18278 (interactive)
18279 (cond
18280 ((bobp) (if indent (newline-and-indent) (newline)))
18281 ((org-at-table-p)
18282 (org-table-justify-field-maybe)
18283 (call-interactively 'org-table-next-row))
18284 ;; when `newline-and-indent' is called within a list, make sure
18285 ;; text moved stays inside the item.
18286 ((and (org-in-item-p) indent)
18287 (if (and (org-at-item-p) (>= (point) (match-end 0)))
18288 (progn
18289 (save-match-data (newline))
18290 (org-indent-line-to (length (match-string 0))))
18291 (let ((ind (org-get-indentation)))
18292 (newline)
18293 (if (org-looking-back org-list-end-re)
18294 (org-indent-line-function)
18295 (org-indent-line-to ind)))))
18296 ((and org-return-follows-link
18297 (let ((tprop (get-text-property (point) 'face)))
18298 (or (eq tprop 'org-link)
18299 (and (listp tprop) (memq 'org-link tprop)))))
18300 (call-interactively 'org-open-at-point))
18301 ((and (org-at-heading-p)
18302 (looking-at
18303 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
18304 (org-show-entry)
18305 (end-of-line 1)
18306 (newline))
18307 (t (if indent (newline-and-indent) (newline)))))
18309 (defun org-return-indent ()
18310 "Goto next table row or insert a newline and indent.
18311 Calls `org-table-next-row' or `newline-and-indent', depending on
18312 context. See the individual commands for more information."
18313 (interactive)
18314 (org-return t))
18316 (defun org-ctrl-c-star ()
18317 "Compute table, or change heading status of lines.
18318 Calls `org-table-recalculate' or `org-toggle-heading',
18319 depending on context."
18320 (interactive)
18321 (cond
18322 ((org-at-table-p)
18323 (call-interactively 'org-table-recalculate))
18325 ;; Convert all lines in region to list items
18326 (call-interactively 'org-toggle-heading))))
18328 (defun org-ctrl-c-minus ()
18329 "Insert separator line in table or modify bullet status of line.
18330 Also turns a plain line or a region of lines into list items.
18331 Calls `org-table-insert-hline', `org-toggle-item', or
18332 `org-cycle-list-bullet', depending on context."
18333 (interactive)
18334 (cond
18335 ((org-at-table-p)
18336 (call-interactively 'org-table-insert-hline))
18337 ((org-region-active-p)
18338 (call-interactively 'org-toggle-item))
18339 ((org-in-item-p)
18340 (call-interactively 'org-cycle-list-bullet))
18342 (call-interactively 'org-toggle-item))))
18344 (defun org-toggle-item (arg)
18345 "Convert headings or normal lines to items, items to normal lines.
18346 If there is no active region, only the current line is considered.
18348 If the first non blank line in the region is an headline, convert
18349 all headlines to items, shifting text accordingly.
18351 If it is an item, convert all items to normal lines.
18353 If it is normal text, change region into an item. With a prefix
18354 argument ARG, change each line in region into an item."
18355 (interactive "P")
18356 (let ((shift-text
18357 (function
18358 ;; Shift text in current section to IND, from point to END.
18359 ;; The function leaves point to END line.
18360 (lambda (ind end)
18361 (let ((min-i 1000) (end (copy-marker end)))
18362 ;; First determine the minimum indentation (MIN-I) of
18363 ;; the text.
18364 (save-excursion
18365 (catch 'exit
18366 (while (< (point) end)
18367 (let ((i (org-get-indentation)))
18368 (cond
18369 ;; Skip blank lines and inline tasks.
18370 ((looking-at "^[ \t]*$"))
18371 ((looking-at org-outline-regexp-bol))
18372 ;; We can't find less than 0 indentation.
18373 ((zerop i) (throw 'exit (setq min-i 0)))
18374 ((< i min-i) (setq min-i i))))
18375 (forward-line))))
18376 ;; Then indent each line so that a line indented to
18377 ;; MIN-I becomes indented to IND. Ignore blank lines
18378 ;; and inline tasks in the process.
18379 (let ((delta (- ind min-i)))
18380 (while (< (point) end)
18381 (unless (or (looking-at "^[ \t]*$")
18382 (looking-at org-outline-regexp-bol))
18383 (org-indent-line-to (+ (org-get-indentation) delta)))
18384 (forward-line)))))))
18385 (skip-blanks
18386 (function
18387 ;; Return beginning of first non-blank line, starting from
18388 ;; line at POS.
18389 (lambda (pos)
18390 (save-excursion
18391 (goto-char pos)
18392 (skip-chars-forward " \r\t\n")
18393 (point-at-bol)))))
18394 beg end)
18395 ;; Determine boundaries of changes.
18396 (if (org-region-active-p)
18397 (setq beg (funcall skip-blanks (region-beginning))
18398 end (copy-marker (region-end)))
18399 (setq beg (funcall skip-blanks (point-at-bol))
18400 end (copy-marker (point-at-eol))))
18401 ;; Depending on the starting line, choose an action on the text
18402 ;; between BEG and END.
18403 (org-with-limited-levels
18404 (save-excursion
18405 (goto-char beg)
18406 (cond
18407 ;; Case 1. Start at an item: de-itemize. Note that it only
18408 ;; happens when a region is active: `org-ctrl-c-minus'
18409 ;; would call `org-cycle-list-bullet' otherwise.
18410 ((org-at-item-p)
18411 (while (< (point) end)
18412 (when (org-at-item-p)
18413 (skip-chars-forward " \t")
18414 (delete-region (point) (match-end 0)))
18415 (forward-line)))
18416 ;; Case 2. Start at an heading: convert to items.
18417 ((org-on-heading-p)
18418 (let* ((bul (org-list-bullet-string "-"))
18419 (bul-len (length bul))
18420 ;; Indentation of the first heading. It should be
18421 ;; relative to the indentation of its parent, if any.
18422 (start-ind (save-excursion
18423 (cond
18424 ((not org-adapt-indentation) 0)
18425 ((not (outline-previous-heading)) 0)
18426 (t (length (match-string 0))))))
18427 ;; Level of first heading. Further headings will be
18428 ;; compared to it to determine hierarchy in the list.
18429 (ref-level (org-reduced-level (org-outline-level))))
18430 (while (< (point) end)
18431 (let* ((level (org-reduced-level (org-outline-level)))
18432 (delta (max 0 (- level ref-level))))
18433 ;; If current headline is less indented than the first
18434 ;; one, set it as reference, in order to preserve
18435 ;; subtrees.
18436 (when (< level ref-level) (setq ref-level level))
18437 (replace-match bul t t)
18438 (org-indent-line-to (+ start-ind (* delta bul-len)))
18439 ;; Ensure all text down to END (or SECTION-END) belongs
18440 ;; to the newly created item.
18441 (let ((section-end (save-excursion
18442 (or (outline-next-heading) (point)))))
18443 (forward-line)
18444 (funcall shift-text
18445 (+ start-ind (* (1+ delta) bul-len))
18446 (min end section-end)))))))
18447 ;; Case 3. Normal line with ARG: turn each non-item line into
18448 ;; an item.
18449 (arg
18450 (while (< (point) end)
18451 (unless (or (org-on-heading-p) (org-at-item-p))
18452 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
18453 (replace-match
18454 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
18455 (forward-line)))
18456 ;; Case 4. Normal line without ARG: make the first line of
18457 ;; region an item, and shift indentation of others
18458 ;; lines to set them as item's body.
18459 (t (let* ((bul (org-list-bullet-string "-"))
18460 (bul-len (length bul))
18461 (ref-ind (org-get-indentation)))
18462 (skip-chars-forward " \t")
18463 (insert bul)
18464 (forward-line)
18465 (while (< (point) end)
18466 ;; Ensure that lines less indented than first one
18467 ;; still get included in item body.
18468 (funcall shift-text
18469 (+ ref-ind bul-len)
18470 (min end (save-excursion (or (outline-next-heading)
18471 (point)))))
18472 (forward-line)))))))))
18474 (defun org-toggle-heading (&optional nstars)
18475 "Convert headings to normal text, or items or text to headings.
18476 If there is no active region, only the current line is considered.
18478 If the first non blank line is an headline, remove the stars from
18479 all headlines in the region.
18481 If it is a plain list item, turn all plain list items into headings.
18483 If it is a normal line, turn each and every normal line (i.e. not
18484 an heading or an item) in the region into a heading.
18486 When converting a line into a heading, the number of stars is chosen
18487 such that the lines become children of the current entry. However,
18488 when a prefix argument is given, its value determines the number of
18489 stars to add."
18490 (interactive "P")
18491 (let ((skip-blanks
18492 (function
18493 ;; Return beginning of first non-blank line, starting from
18494 ;; line at POS.
18495 (lambda (pos)
18496 (save-excursion
18497 (goto-char pos)
18498 (skip-chars-forward " \r\t\n")
18499 (point-at-bol)))))
18500 beg end)
18501 ;; Determine boundaries of changes. If region ends at a bol, do
18502 ;; not consider the last line to be in the region.
18503 (if (org-region-active-p)
18504 (setq beg (funcall skip-blanks (region-beginning))
18505 end (copy-marker (save-excursion
18506 (goto-char (region-end))
18507 (if (bolp) (point) (point-at-eol)))))
18508 (setq beg (funcall skip-blanks (point-at-bol))
18509 end (copy-marker (point-at-eol))))
18510 ;; Ensure inline tasks don't count as headings.
18511 (org-with-limited-levels
18512 (save-excursion
18513 (goto-char beg)
18514 (cond
18515 ;; Case 1. Started at an heading: de-star headings.
18516 ((org-on-heading-p)
18517 (while (< (point) end)
18518 (when (org-on-heading-p t)
18519 (looking-at org-outline-regexp) (replace-match ""))
18520 (forward-line)))
18521 ;; Case 2. Started at an item: change items into headlines.
18522 ;; One star will be added by `org-list-to-subtree'.
18523 ((org-at-item-p)
18524 (let* ((stars (make-string
18525 (if nstars
18526 ;; subtract the star that will be added again by
18527 ;; `org-list-to-subtree'
18528 (1- (prefix-numeric-value current-prefix-arg))
18529 (or (org-current-level) 0))
18530 ?*))
18531 (add-stars
18532 (cond (nstars "") ; stars from prefix only
18533 ((equal stars "") "") ; before first heading
18534 (org-odd-levels-only "*") ; inside heading, odd
18535 (t "")))) ; inside heading, oddeven
18536 (while (< (point) end)
18537 (when (org-at-item-p)
18538 ;; Pay attention to cases when region ends before list.
18539 (let* ((struct (org-list-struct))
18540 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
18541 (save-restriction
18542 (narrow-to-region (point) list-end)
18543 (insert
18544 (org-list-to-subtree
18545 (org-list-parse-list t)
18546 '(:istart (concat stars add-stars (funcall get-stars depth))
18547 :icount (concat stars add-stars (funcall get-stars depth))))))))
18548 (forward-line))))
18549 ;; Case 3. Started at normal text: make every line an heading,
18550 ;; skipping headlines and items.
18551 (t (let* ((stars (make-string
18552 (if nstars
18553 (prefix-numeric-value current-prefix-arg)
18554 (or (org-current-level) 0))
18555 ?*))
18556 (add-stars
18557 (cond (nstars "") ; stars from prefix only
18558 ((equal stars "") "*") ; before first heading
18559 (org-odd-levels-only "**") ; inside heading, odd
18560 (t "*"))) ; inside heading, oddeven
18561 (rpl (concat stars add-stars " ")))
18562 (while (< (point) end)
18563 (when (and (not (org-on-heading-p)) (not (org-at-item-p))
18564 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
18565 (replace-match (concat rpl (match-string 2))))
18566 (forward-line)))))))))
18568 (defun org-meta-return (&optional arg)
18569 "Insert a new heading or wrap a region in a table.
18570 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
18571 See the individual commands for more information."
18572 (interactive "P")
18573 (cond
18574 ((run-hook-with-args-until-success 'org-metareturn-hook))
18575 ((org-at-table-p)
18576 (call-interactively 'org-table-wrap-region))
18577 (t (call-interactively 'org-insert-heading))))
18579 ;;; Menu entries
18581 ;; Define the Org-mode menus
18582 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
18583 '("Tbl"
18584 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
18585 ["Next Field" org-cycle (org-at-table-p)]
18586 ["Previous Field" org-shifttab (org-at-table-p)]
18587 ["Next Row" org-return (org-at-table-p)]
18588 "--"
18589 ["Blank Field" org-table-blank-field (org-at-table-p)]
18590 ["Edit Field" org-table-edit-field (org-at-table-p)]
18591 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
18592 "--"
18593 ("Column"
18594 ["Move Column Left" org-metaleft (org-at-table-p)]
18595 ["Move Column Right" org-metaright (org-at-table-p)]
18596 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
18597 ["Insert Column" org-shiftmetaright (org-at-table-p)])
18598 ("Row"
18599 ["Move Row Up" org-metaup (org-at-table-p)]
18600 ["Move Row Down" org-metadown (org-at-table-p)]
18601 ["Delete Row" org-shiftmetaup (org-at-table-p)]
18602 ["Insert Row" org-shiftmetadown (org-at-table-p)]
18603 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
18604 "--"
18605 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
18606 ("Rectangle"
18607 ["Copy Rectangle" org-copy-special (org-at-table-p)]
18608 ["Cut Rectangle" org-cut-special (org-at-table-p)]
18609 ["Paste Rectangle" org-paste-special (org-at-table-p)]
18610 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
18611 "--"
18612 ("Calculate"
18613 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
18614 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
18615 ["Edit Formulas" org-edit-special (org-at-table-p)]
18616 "--"
18617 ["Recalculate line" org-table-recalculate (org-at-table-p)]
18618 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
18619 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
18620 "--"
18621 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
18622 "--"
18623 ["Sum Column/Rectangle" org-table-sum
18624 (or (org-at-table-p) (org-region-active-p))]
18625 ["Which Column?" org-table-current-column (org-at-table-p)])
18626 ["Debug Formulas"
18627 org-table-toggle-formula-debugger
18628 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
18629 ["Show Col/Row Numbers"
18630 org-table-toggle-coordinate-overlays
18631 :style toggle
18632 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
18633 "--"
18634 ["Create" org-table-create (and (not (org-at-table-p))
18635 org-enable-table-editor)]
18636 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
18637 ["Import from File" org-table-import (not (org-at-table-p))]
18638 ["Export to File" org-table-export (org-at-table-p)]
18639 "--"
18640 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
18642 (easy-menu-define org-org-menu org-mode-map "Org menu"
18643 '("Org"
18644 ("Show/Hide"
18645 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
18646 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
18647 ["Sparse Tree..." org-sparse-tree t]
18648 ["Reveal Context" org-reveal t]
18649 ["Show All" show-all t]
18650 "--"
18651 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
18652 "--"
18653 ["New Heading" org-insert-heading t]
18654 ("Navigate Headings"
18655 ["Up" outline-up-heading t]
18656 ["Next" outline-next-visible-heading t]
18657 ["Previous" outline-previous-visible-heading t]
18658 ["Next Same Level" outline-forward-same-level t]
18659 ["Previous Same Level" outline-backward-same-level t]
18660 "--"
18661 ["Jump" org-goto t])
18662 ("Edit Structure"
18663 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
18664 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
18665 "--"
18666 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
18667 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
18668 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
18669 "--"
18670 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
18671 "--"
18672 ["Copy visible text" org-copy-visible t]
18673 "--"
18674 ["Promote Heading" org-metaleft (not (org-at-table-p))]
18675 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
18676 ["Demote Heading" org-metaright (not (org-at-table-p))]
18677 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
18678 "--"
18679 ["Sort Region/Children" org-sort (not (org-at-table-p))]
18680 "--"
18681 ["Convert to odd levels" org-convert-to-odd-levels t]
18682 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
18683 ("Editing"
18684 ["Emphasis..." org-emphasize t]
18685 ["Edit Source Example" org-edit-special t]
18686 "--"
18687 ["Footnote new/jump" org-footnote-action t]
18688 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
18689 ("Archive"
18690 ["Archive (default method)" org-archive-subtree-default t]
18691 "--"
18692 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
18693 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
18694 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
18696 "--"
18697 ("Hyperlinks"
18698 ["Store Link (Global)" org-store-link t]
18699 ["Find existing link to here" org-occur-link-in-agenda-files t]
18700 ["Insert Link" org-insert-link t]
18701 ["Follow Link" org-open-at-point t]
18702 "--"
18703 ["Next link" org-next-link t]
18704 ["Previous link" org-previous-link t]
18705 "--"
18706 ["Descriptive Links"
18707 org-toggle-link-display
18708 :style radio
18709 :selected org-descriptive-links
18711 ["Literal Links"
18712 org-toggle-link-display
18713 :style radio
18714 :selected (not org-descriptive-links)])
18715 "--"
18716 ("TODO Lists"
18717 ["TODO/DONE/-" org-todo t]
18718 ("Select keyword"
18719 ["Next keyword" org-shiftright (org-on-heading-p)]
18720 ["Previous keyword" org-shiftleft (org-on-heading-p)]
18721 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
18722 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
18723 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
18724 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
18725 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
18726 "--"
18727 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
18728 :selected org-enforce-todo-dependencies :style toggle :active t]
18729 "Settings for tree at point"
18730 ["Do Children sequentially" org-toggle-ordered-property :style radio
18731 :selected (org-entry-get nil "ORDERED")
18732 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
18733 ["Do Children parallel" org-toggle-ordered-property :style radio
18734 :selected (not (org-entry-get nil "ORDERED"))
18735 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
18736 "--"
18737 ["Set Priority" org-priority t]
18738 ["Priority Up" org-shiftup t]
18739 ["Priority Down" org-shiftdown t]
18740 "--"
18741 ["Get news from all feeds" org-feed-update-all t]
18742 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
18743 ["Customize feeds" (customize-variable 'org-feed-alist) t])
18744 ("TAGS and Properties"
18745 ["Set Tags" org-set-tags-command t]
18746 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
18747 "--"
18748 ["Set property" org-set-property t]
18749 ["Column view of properties" org-columns t]
18750 ["Insert Column View DBlock" org-insert-columns-dblock t])
18751 ("Dates and Scheduling"
18752 ["Timestamp" org-time-stamp t]
18753 ["Timestamp (inactive)" org-time-stamp-inactive t]
18754 ("Change Date"
18755 ["1 Day Later" org-shiftright t]
18756 ["1 Day Earlier" org-shiftleft t]
18757 ["1 ... Later" org-shiftup t]
18758 ["1 ... Earlier" org-shiftdown t])
18759 ["Compute Time Range" org-evaluate-time-range t]
18760 ["Schedule Item" org-schedule t]
18761 ["Deadline" org-deadline t]
18762 "--"
18763 ["Custom time format" org-toggle-time-stamp-overlays
18764 :style radio :selected org-display-custom-times]
18765 "--"
18766 ["Goto Calendar" org-goto-calendar t]
18767 ["Date from Calendar" org-date-from-calendar t]
18768 "--"
18769 ["Start/Restart Timer" org-timer-start t]
18770 ["Pause/Continue Timer" org-timer-pause-or-continue t]
18771 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
18772 ["Insert Timer String" org-timer t]
18773 ["Insert Timer Item" org-timer-item t])
18774 ("Logging work"
18775 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
18776 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
18777 ["Clock out" org-clock-out t]
18778 ["Clock cancel" org-clock-cancel t]
18779 "--"
18780 ["Mark as default task" org-clock-mark-default-task t]
18781 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
18782 ["Goto running clock" org-clock-goto t]
18783 "--"
18784 ["Display times" org-clock-display t]
18785 ["Create clock table" org-clock-report t]
18786 "--"
18787 ["Record DONE time"
18788 (progn (setq org-log-done (not org-log-done))
18789 (message "Switching to %s will %s record a timestamp"
18790 (car org-done-keywords)
18791 (if org-log-done "automatically" "not")))
18792 :style toggle :selected org-log-done])
18793 "--"
18794 ["Agenda Command..." org-agenda t]
18795 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
18796 ("File List for Agenda")
18797 ("Special views current file"
18798 ["TODO Tree" org-show-todo-tree t]
18799 ["Check Deadlines" org-check-deadlines t]
18800 ["Timeline" org-timeline t]
18801 ["Tags/Property tree" org-match-sparse-tree t])
18802 "--"
18803 ["Export/Publish..." org-export t]
18804 ("LaTeX"
18805 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
18806 :selected org-cdlatex-mode]
18807 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
18808 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
18809 ["Modify math symbol" org-cdlatex-math-modify
18810 (org-inside-LaTeX-fragment-p)]
18811 ["Insert citation" org-reftex-citation t]
18812 "--"
18813 ["Template for BEAMER" org-insert-beamer-options-template t])
18814 "--"
18815 ("MobileOrg"
18816 ["Push Files and Views" org-mobile-push t]
18817 ["Get Captured and Flagged" org-mobile-pull t]
18818 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
18819 "--"
18820 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
18821 "--"
18822 ("Documentation"
18823 ["Show Version" org-version t]
18824 ["Info Documentation" org-info t])
18825 ("Customize"
18826 ["Browse Org Group" org-customize t]
18827 "--"
18828 ["Expand This Menu" org-create-customize-menu
18829 (fboundp 'customize-menu-create)])
18830 ["Send bug report" org-submit-bug-report t]
18831 "--"
18832 ("Refresh/Reload"
18833 ["Refresh setup current buffer" org-mode-restart t]
18834 ["Reload Org (after update)" org-reload t]
18835 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
18838 (defun org-info (&optional node)
18839 "Read documentation for Org-mode in the info system.
18840 With optional NODE, go directly to that node."
18841 (interactive)
18842 (info (format "(org)%s" (or node ""))))
18844 ;;;###autoload
18845 (defun org-submit-bug-report ()
18846 "Submit a bug report on Org-mode via mail.
18848 Don't hesitate to report any problems or inaccurate documentation.
18850 If you don't have setup sending mail from (X)Emacs, please copy the
18851 output buffer into your mail program, as it gives us important
18852 information about your Org-mode version and configuration."
18853 (interactive)
18854 (require 'reporter)
18855 (org-load-modules-maybe)
18856 (org-require-autoloaded-modules)
18857 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
18858 (reporter-submit-bug-report
18859 "emacs-orgmode@gnu.org"
18860 (org-version)
18861 (let (list)
18862 (save-window-excursion
18863 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
18864 (delete-other-windows)
18865 (erase-buffer)
18866 (insert "You are about to submit a bug report to the Org-mode mailing list.
18868 We would like to add your full Org-mode and Outline configuration to the
18869 bug report. This greatly simplifies the work of the maintainer and
18870 other experts on the mailing list.
18872 HOWEVER, some variables you have customized may contain private
18873 information. The names of customers, colleagues, or friends, might
18874 appear in the form of file names, tags, todo states, or search strings.
18875 If you answer yes to the prompt, you might want to check and remove
18876 such private information before sending the email.")
18877 (add-text-properties (point-min) (point-max) '(face org-warning))
18878 (when (yes-or-no-p "Include your Org-mode configuration ")
18879 (mapatoms
18880 (lambda (v)
18881 (and (boundp v)
18882 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
18883 (or (and (symbol-value v)
18884 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
18885 (and
18886 (get v 'custom-type) (get v 'standard-value)
18887 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
18888 (push v list)))))
18889 (kill-buffer (get-buffer "*Warn about privacy*"))
18890 list))
18891 nil nil
18892 "Remember to cover the basics, that is, what you expected to happen and
18893 what in fact did happen. You don't know how to make a good report? See
18895 http://orgmode.org/manual/Feedback.html#Feedback
18897 Your bug report will be posted to the Org-mode mailing list.
18898 ------------------------------------------------------------------------")
18899 (save-excursion
18900 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
18901 (replace-match "\\1Bug: \\3 [\\2]")))))
18904 (defun org-install-agenda-files-menu ()
18905 (let ((bl (buffer-list)))
18906 (save-excursion
18907 (while bl
18908 (set-buffer (pop bl))
18909 (if (eq major-mode 'org-mode) (setq bl nil)))
18910 (when (eq major-mode 'org-mode)
18911 (easy-menu-change
18912 '("Org") "File List for Agenda"
18913 (append
18914 (list
18915 ["Edit File List" (org-edit-agenda-file-list) t]
18916 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
18917 ["Remove Current File from List" org-remove-file t]
18918 ["Cycle through agenda files" org-cycle-agenda-files t]
18919 ["Occur in all agenda files" org-occur-in-agenda-files t]
18920 "--")
18921 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
18923 ;;;; Documentation
18925 ;;;###autoload
18926 (defun org-require-autoloaded-modules ()
18927 (interactive)
18928 (mapc 'require
18929 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
18930 org-docbook org-exp org-html org-icalendar
18931 org-id org-latex
18932 org-publish org-remember org-table
18933 org-timer org-xoxo)))
18935 ;;;###autoload
18936 (defun org-reload (&optional uncompiled)
18937 "Reload all org lisp files.
18938 With prefix arg UNCOMPILED, load the uncompiled versions."
18939 (interactive "P")
18940 (require 'find-func)
18941 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
18942 (dir-org (file-name-directory (org-find-library-name "org")))
18943 (dir-org-contrib (ignore-errors
18944 (file-name-directory
18945 (org-find-library-name "org-contribdir"))))
18946 (babel-files
18947 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
18948 (append (list nil "comint" "eval" "exp" "keys"
18949 "lob" "ref" "table" "tangle")
18950 (delq nil
18951 (mapcar
18952 (lambda (lang)
18953 (when (cdr lang) (symbol-name (car lang))))
18954 org-babel-load-languages)))))
18955 (files
18956 (append (directory-files dir-org t file-re)
18957 babel-files
18958 (and dir-org-contrib
18959 (directory-files dir-org-contrib t file-re))))
18960 (remove-re (concat (if (featurep 'xemacs)
18961 "org-colview" "org-colview-xemacs")
18962 "\\'")))
18963 (setq files (mapcar 'file-name-sans-extension files))
18964 (setq files (mapcar
18965 (lambda (x) (if (string-match remove-re x) nil x))
18966 files))
18967 (setq files (delq nil files))
18968 (mapc
18969 (lambda (f)
18970 (when (featurep (intern (file-name-nondirectory f)))
18971 (if (and (not uncompiled)
18972 (file-exists-p (concat f ".elc")))
18973 (load (concat f ".elc") nil nil t)
18974 (load (concat f ".el") nil nil t))))
18975 files))
18976 (org-version))
18978 ;;;###autoload
18979 (defun org-customize ()
18980 "Call the customize function with org as argument."
18981 (interactive)
18982 (org-load-modules-maybe)
18983 (org-require-autoloaded-modules)
18984 (customize-browse 'org))
18986 (defun org-create-customize-menu ()
18987 "Create a full customization menu for Org-mode, insert it into the menu."
18988 (interactive)
18989 (org-load-modules-maybe)
18990 (org-require-autoloaded-modules)
18991 (if (fboundp 'customize-menu-create)
18992 (progn
18993 (easy-menu-change
18994 '("Org") "Customize"
18995 `(["Browse Org group" org-customize t]
18996 "--"
18997 ,(customize-menu-create 'org)
18998 ["Set" Custom-set t]
18999 ["Save" Custom-save t]
19000 ["Reset to Current" Custom-reset-current t]
19001 ["Reset to Saved" Custom-reset-saved t]
19002 ["Reset to Standard Settings" Custom-reset-standard t]))
19003 (message "\"Org\"-menu now contains full customization menu"))
19004 (error "Cannot expand menu (outdated version of cus-edit.el)")))
19006 ;;;; Miscellaneous stuff
19008 ;;; Generally useful functions
19010 (defun org-get-at-bol (property)
19011 "Get text property PROPERTY at beginning of line."
19012 (get-text-property (point-at-bol) property))
19014 (defun org-find-text-property-in-string (prop s)
19015 "Return the first non-nil value of property PROP in string S."
19016 (or (get-text-property 0 prop s)
19017 (get-text-property (or (next-single-property-change 0 prop s) 0)
19018 prop s)))
19020 (defun org-display-warning (message) ;; Copied from Emacs-Muse
19021 "Display the given MESSAGE as a warning."
19022 (if (fboundp 'display-warning)
19023 (display-warning 'org message
19024 (if (featurep 'xemacs) 'warning :warning))
19025 (let ((buf (get-buffer-create "*Org warnings*")))
19026 (with-current-buffer buf
19027 (goto-char (point-max))
19028 (insert "Warning (Org): " message)
19029 (unless (bolp)
19030 (newline)))
19031 (display-buffer buf)
19032 (sit-for 0))))
19034 (defun org-eval (form)
19035 "Eval FORM and return result."
19036 (condition-case error
19037 (eval form)
19038 (error (format "%%![Error: %s]" error))))
19040 (defun org-in-commented-line ()
19041 "Is point in a line starting with `#'?"
19042 (equal (char-after (point-at-bol)) ?#))
19044 (defun org-in-indented-comment-line ()
19045 "Is point in a line starting with `#' after some white space?"
19046 (save-excursion
19047 (save-match-data
19048 (goto-char (point-at-bol))
19049 (looking-at "[ \t]*#"))))
19051 (defun org-in-verbatim-emphasis ()
19052 (save-match-data
19053 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
19055 (defun org-goto-marker-or-bmk (marker &optional bookmark)
19056 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
19057 (if (and marker (marker-buffer marker)
19058 (buffer-live-p (marker-buffer marker)))
19059 (progn
19060 (org-pop-to-buffer-same-window (marker-buffer marker))
19061 (if (or (> marker (point-max)) (< marker (point-min)))
19062 (widen))
19063 (goto-char marker)
19064 (org-show-context 'org-goto))
19065 (if bookmark
19066 (bookmark-jump bookmark)
19067 (error "Cannot find location"))))
19069 (defun org-quote-csv-field (s)
19070 "Quote field for inclusion in CSV material."
19071 (if (string-match "[\",]" s)
19072 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
19075 (defun org-force-self-insert (N)
19076 "Needed to enforce self-insert under remapping."
19077 (interactive "p")
19078 (self-insert-command N))
19080 (defun org-string-width (s)
19081 "Compute width of string, ignoring invisible characters.
19082 This ignores character with invisibility property `org-link', and also
19083 characters with property `org-cwidth', because these will become invisible
19084 upon the next fontification round."
19085 (let (b l)
19086 (when (or (eq t buffer-invisibility-spec)
19087 (assq 'org-link buffer-invisibility-spec))
19088 (while (setq b (text-property-any 0 (length s)
19089 'invisible 'org-link s))
19090 (setq s (concat (substring s 0 b)
19091 (substring s (or (next-single-property-change
19092 b 'invisible s) (length s)))))))
19093 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
19094 (setq s (concat (substring s 0 b)
19095 (substring s (or (next-single-property-change
19096 b 'org-cwidth s) (length s))))))
19097 (setq l (string-width s) b -1)
19098 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
19099 (setq l (- l (get-text-property b 'org-dwidth-n s))))
19102 (defun org-shorten-string (s maxlength)
19103 "Shorten string S so tht it is no longer than MAXLENGTH characters.
19104 If the string is shorter or has length MAXLENGTH, just return the
19105 original string. If it is longer, the functions finds a space in the
19106 string, breaks this string off at that locations and adds three dots
19107 as ellipsis. Including the ellipsis, the string will not be longer
19108 than MAXLENGTH. If finding a good breaking point in the string does
19109 not work, the string is just chopped off in the middle of a word
19110 if necessary."
19111 (if (<= (length s) maxlength)
19113 (let* ((n (max (- maxlength 4) 1))
19114 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
19115 (if (string-match re s)
19116 (concat (match-string 1 s) "...")
19117 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
19119 (defun org-get-indentation (&optional line)
19120 "Get the indentation of the current line, interpreting tabs.
19121 When LINE is given, assume it represents a line and compute its indentation."
19122 (if line
19123 (if (string-match "^ *" (org-remove-tabs line))
19124 (match-end 0))
19125 (save-excursion
19126 (beginning-of-line 1)
19127 (skip-chars-forward " \t")
19128 (current-column))))
19130 (defun org-get-string-indentation (s)
19131 "What indentation has S due to SPACE and TAB at the beginning of the string?"
19132 (let ((n -1) (i 0) (w tab-width) c)
19133 (catch 'exit
19134 (while (< (setq n (1+ n)) (length s))
19135 (setq c (aref s n))
19136 (cond ((= c ?\ ) (setq i (1+ i)))
19137 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
19138 (t (throw 'exit t)))))
19141 (defun org-remove-tabs (s &optional width)
19142 "Replace tabulators in S with spaces.
19143 Assumes that s is a single line, starting in column 0."
19144 (setq width (or width tab-width))
19145 (while (string-match "\t" s)
19146 (setq s (replace-match
19147 (make-string
19148 (- (* width (/ (+ (match-beginning 0) width) width))
19149 (match-beginning 0)) ?\ )
19150 t t s)))
19153 (defun org-fix-indentation (line ind)
19154 "Fix indentation in LINE.
19155 IND is a cons cell with target and minimum indentation.
19156 If the current indentation in LINE is smaller than the minimum,
19157 leave it alone. If it is larger than ind, set it to the target."
19158 (let* ((l (org-remove-tabs line))
19159 (i (org-get-indentation l))
19160 (i1 (car ind)) (i2 (cdr ind)))
19161 (if (>= i i2) (setq l (substring line i2)))
19162 (if (> i1 0)
19163 (concat (make-string i1 ?\ ) l)
19164 l)))
19166 (defun org-remove-indentation (code &optional n)
19167 "Remove the maximum common indentation from the lines in CODE.
19168 N may optionally be the number of spaces to remove."
19169 (with-temp-buffer
19170 (insert code)
19171 (org-do-remove-indentation n)
19172 (buffer-string)))
19174 (defun org-do-remove-indentation (&optional n)
19175 "Remove the maximum common indentation from the buffer."
19176 (untabify (point-min) (point-max))
19177 (let ((min 10000) re)
19178 (if n
19179 (setq min n)
19180 (goto-char (point-min))
19181 (while (re-search-forward "^ *[^ \n]" nil t)
19182 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
19183 (unless (or (= min 0) (= min 10000))
19184 (setq re (format "^ \\{%d\\}" min))
19185 (goto-char (point-min))
19186 (while (re-search-forward re nil t)
19187 (replace-match "")
19188 (end-of-line 1))
19189 min)))
19191 (defun org-fill-template (template alist)
19192 "Find each %key of ALIST in TEMPLATE and replace it."
19193 (let ((case-fold-search nil)
19194 entry key value)
19195 (setq alist (sort (copy-sequence alist)
19196 (lambda (a b) (< (length (car a)) (length (car b))))))
19197 (while (setq entry (pop alist))
19198 (setq template
19199 (replace-regexp-in-string
19200 (concat "%" (regexp-quote (car entry)))
19201 (cdr entry) template t t)))
19202 template))
19204 (defun org-base-buffer (buffer)
19205 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
19206 (if (not buffer)
19207 buffer
19208 (or (buffer-base-buffer buffer)
19209 buffer)))
19211 (defun org-trim (s)
19212 "Remove whitespace at beginning and end of string."
19213 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
19214 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
19217 (defun org-wrap (string &optional width lines)
19218 "Wrap string to either a number of lines, or a width in characters.
19219 If WIDTH is non-nil, the string is wrapped to that width, however many lines
19220 that costs. If there is a word longer than WIDTH, the text is actually
19221 wrapped to the length of that word.
19222 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
19223 many lines, whatever width that takes.
19224 The return value is a list of lines, without newlines at the end."
19225 (let* ((words (org-split-string string "[ \t\n]+"))
19226 (maxword (apply 'max (mapcar 'org-string-width words)))
19227 w ll)
19228 (cond (width
19229 (org-do-wrap words (max maxword width)))
19230 (lines
19231 (setq w maxword)
19232 (setq ll (org-do-wrap words maxword))
19233 (if (<= (length ll) lines)
19235 (setq ll words)
19236 (while (> (length ll) lines)
19237 (setq w (1+ w))
19238 (setq ll (org-do-wrap words w)))
19239 ll))
19240 (t (error "Cannot wrap this")))))
19242 (defun org-do-wrap (words width)
19243 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
19244 (let (lines line)
19245 (while words
19246 (setq line (pop words))
19247 (while (and words (< (+ (length line) (length (car words))) width))
19248 (setq line (concat line " " (pop words))))
19249 (setq lines (push line lines)))
19250 (nreverse lines)))
19252 (defun org-split-string (string &optional separators)
19253 "Splits STRING into substrings at SEPARATORS.
19254 No empty strings are returned if there are matches at the beginning
19255 and end of string."
19256 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
19257 (start 0)
19258 notfirst
19259 (list nil))
19260 (while (and (string-match rexp string
19261 (if (and notfirst
19262 (= start (match-beginning 0))
19263 (< start (length string)))
19264 (1+ start) start))
19265 (< (match-beginning 0) (length string)))
19266 (setq notfirst t)
19267 (or (eq (match-beginning 0) 0)
19268 (and (eq (match-beginning 0) (match-end 0))
19269 (eq (match-beginning 0) start))
19270 (setq list
19271 (cons (substring string start (match-beginning 0))
19272 list)))
19273 (setq start (match-end 0)))
19274 (or (eq start (length string))
19275 (setq list
19276 (cons (substring string start)
19277 list)))
19278 (nreverse list)))
19280 (defun org-quote-vert (s)
19281 "Replace \"|\" with \"\\vert\"."
19282 (while (string-match "|" s)
19283 (setq s (replace-match "\\vert" t t s)))
19286 (defun org-uuidgen-p (s)
19287 "Is S an ID created by UUIDGEN?"
19288 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
19290 (defun org-context ()
19291 "Return a list of contexts of the current cursor position.
19292 If several contexts apply, all are returned.
19293 Each context entry is a list with a symbol naming the context, and
19294 two positions indicating start and end of the context. Possible
19295 contexts are:
19297 :headline anywhere in a headline
19298 :headline-stars on the leading stars in a headline
19299 :todo-keyword on a TODO keyword (including DONE) in a headline
19300 :tags on the TAGS in a headline
19301 :priority on the priority cookie in a headline
19302 :item on the first line of a plain list item
19303 :item-bullet on the bullet/number of a plain list item
19304 :checkbox on the checkbox in a plain list item
19305 :table in an org-mode table
19306 :table-special on a special filed in a table
19307 :table-table in a table.el table
19308 :link on a hyperlink
19309 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
19310 :target on a <<target>>
19311 :radio-target on a <<<radio-target>>>
19312 :latex-fragment on a LaTeX fragment
19313 :latex-preview on a LaTeX fragment with overlayed preview image
19315 This function expects the position to be visible because it uses font-lock
19316 faces as a help to recognize the following contexts: :table-special, :link,
19317 and :keyword."
19318 (let* ((f (get-text-property (point) 'face))
19319 (faces (if (listp f) f (list f)))
19320 (p (point)) clist o)
19321 ;; First the large context
19322 (cond
19323 ((org-on-heading-p t)
19324 (push (list :headline (point-at-bol) (point-at-eol)) clist)
19325 (when (progn
19326 (beginning-of-line 1)
19327 (looking-at org-todo-line-tags-regexp))
19328 (push (org-point-in-group p 1 :headline-stars) clist)
19329 (push (org-point-in-group p 2 :todo-keyword) clist)
19330 (push (org-point-in-group p 4 :tags) clist))
19331 (goto-char p)
19332 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
19333 (if (looking-at "\\[#[A-Z0-9]\\]")
19334 (push (org-point-in-group p 0 :priority) clist)))
19336 ((org-at-item-p)
19337 (push (org-point-in-group p 2 :item-bullet) clist)
19338 (push (list :item (point-at-bol)
19339 (save-excursion (org-end-of-item) (point)))
19340 clist)
19341 (and (org-at-item-checkbox-p)
19342 (push (org-point-in-group p 0 :checkbox) clist)))
19344 ((org-at-table-p)
19345 (push (list :table (org-table-begin) (org-table-end)) clist)
19346 (if (memq 'org-formula faces)
19347 (push (list :table-special
19348 (previous-single-property-change p 'face)
19349 (next-single-property-change p 'face)) clist)))
19350 ((org-at-table-p 'any)
19351 (push (list :table-table) clist)))
19352 (goto-char p)
19354 ;; Now the small context
19355 (cond
19356 ((org-at-timestamp-p)
19357 (push (org-point-in-group p 0 :timestamp) clist))
19358 ((memq 'org-link faces)
19359 (push (list :link
19360 (previous-single-property-change p 'face)
19361 (next-single-property-change p 'face)) clist))
19362 ((memq 'org-special-keyword faces)
19363 (push (list :keyword
19364 (previous-single-property-change p 'face)
19365 (next-single-property-change p 'face)) clist))
19366 ((org-on-target-p)
19367 (push (org-point-in-group p 0 :target) clist)
19368 (goto-char (1- (match-beginning 0)))
19369 (if (looking-at org-radio-target-regexp)
19370 (push (org-point-in-group p 0 :radio-target) clist))
19371 (goto-char p))
19372 ((setq o (car (delq nil
19373 (mapcar
19374 (lambda (x)
19375 (if (memq x org-latex-fragment-image-overlays) x))
19376 (overlays-at (point))))))
19377 (push (list :latex-fragment
19378 (overlay-start o) (overlay-end o)) clist)
19379 (push (list :latex-preview
19380 (overlay-start o) (overlay-end o)) clist))
19381 ((org-inside-LaTeX-fragment-p)
19382 ;; FIXME: positions wrong.
19383 (push (list :latex-fragment (point) (point)) clist)))
19385 (setq clist (nreverse (delq nil clist)))
19386 clist))
19388 ;; FIXME: Compare with at-regexp-p Do we need both?
19389 (defun org-in-regexp (re &optional nlines visually)
19390 "Check if point is inside a match of regexp.
19391 Normally only the current line is checked, but you can include NLINES extra
19392 lines both before and after point into the search.
19393 If VISUALLY is set, require that the cursor is not after the match but
19394 really on, so that the block visually is on the match."
19395 (catch 'exit
19396 (let ((pos (point))
19397 (eol (point-at-eol (+ 1 (or nlines 0))))
19398 (inc (if visually 1 0)))
19399 (save-excursion
19400 (beginning-of-line (- 1 (or nlines 0)))
19401 (while (re-search-forward re eol t)
19402 (if (and (<= (match-beginning 0) pos)
19403 (>= (+ inc (match-end 0)) pos))
19404 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
19406 (defun org-at-regexp-p (regexp)
19407 "Is point inside a match of REGEXP in the current line?"
19408 (catch 'exit
19409 (save-excursion
19410 (let ((pos (point)) (end (point-at-eol)))
19411 (beginning-of-line 1)
19412 (while (re-search-forward regexp end t)
19413 (if (and (<= (match-beginning 0) pos)
19414 (>= (match-end 0) pos))
19415 (throw 'exit t)))
19416 nil))))
19418 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
19419 "Non-nil when point is between matches of START-RE and END-RE.
19421 Also return a non-nil value when point is on one of the matches.
19423 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
19424 buffer positions. Default values are the positions of headlines
19425 surrounding the point.
19427 The functions returns a cons cell whose car (resp. cdr) is the
19428 position before START-RE (resp. after END-RE)."
19429 (save-match-data
19430 (let ((pos (point))
19431 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
19432 (limit-down (or lim-down (save-excursion (outline-next-heading))))
19433 beg end)
19434 (save-excursion
19435 ;; Point is on a block when on START-RE or if START-RE can be
19436 ;; found before it...
19437 (and (or (org-at-regexp-p start-re)
19438 (re-search-backward start-re limit-up t))
19439 (setq beg (match-beginning 0))
19440 ;; ... and END-RE after it...
19441 (goto-char (match-end 0))
19442 (re-search-forward end-re limit-down t)
19443 (> (setq end (match-end 0)) pos)
19444 ;; ... without another START-RE in-between.
19445 (goto-char (match-beginning 0))
19446 (not (re-search-backward start-re (1+ beg) t))
19447 ;; Return value.
19448 (cons beg end))))))
19450 (defun org-in-block-p (names)
19451 "Non-nil when point belongs to a block whose name belongs to NAMES.
19453 NAMES is a list of strings containing names of blocks.
19455 Return first block name matched, or nil. Beware that in case of
19456 nested blocks, the returned name may not belong to the closest
19457 block from point."
19458 (save-match-data
19459 (catch 'exit
19460 (let ((case-fold-search t)
19461 (lim-up (save-excursion (outline-previous-heading)))
19462 (lim-down (save-excursion (outline-next-heading))))
19463 (mapc (lambda (name)
19464 (let ((n (regexp-quote name)))
19465 (when (org-between-regexps-p
19466 (concat "^[ \t]*#\\+begin_" n)
19467 (concat "^[ \t]*#\\+end_" n)
19468 lim-up lim-down)
19469 (throw 'exit n))))
19470 names))
19471 nil)))
19473 (defun org-occur-in-agenda-files (regexp &optional nlines)
19474 "Call `multi-occur' with buffers for all agenda files."
19475 (interactive "sOrg-files matching: \np")
19476 (let* ((files (org-agenda-files))
19477 (tnames (mapcar 'file-truename files))
19478 (extra org-agenda-text-search-extra-files)
19480 (when (eq (car extra) 'agenda-archives)
19481 (setq extra (cdr extra))
19482 (setq files (org-add-archive-files files)))
19483 (while (setq f (pop extra))
19484 (unless (member (file-truename f) tnames)
19485 (add-to-list 'files f 'append)
19486 (add-to-list 'tnames (file-truename f) 'append)))
19487 (multi-occur
19488 (mapcar (lambda (x)
19489 (with-current-buffer
19490 (or (get-file-buffer x) (find-file-noselect x))
19491 (widen)
19492 (current-buffer)))
19493 files)
19494 regexp)))
19496 (if (boundp 'occur-mode-find-occurrence-hook)
19497 ;; Emacs 23
19498 (add-hook 'occur-mode-find-occurrence-hook
19499 (lambda ()
19500 (when (eq major-mode 'org-mode)
19501 (org-reveal))))
19502 ;; Emacs 22
19503 (defadvice occur-mode-goto-occurrence
19504 (after org-occur-reveal activate)
19505 (and (eq major-mode 'org-mode) (org-reveal)))
19506 (defadvice occur-mode-goto-occurrence-other-window
19507 (after org-occur-reveal activate)
19508 (and (eq major-mode 'org-mode) (org-reveal)))
19509 (defadvice occur-mode-display-occurrence
19510 (after org-occur-reveal activate)
19511 (when (eq major-mode 'org-mode)
19512 (let ((pos (occur-mode-find-occurrence)))
19513 (with-current-buffer (marker-buffer pos)
19514 (save-excursion
19515 (goto-char pos)
19516 (org-reveal)))))))
19518 (defun org-occur-link-in-agenda-files ()
19519 "Create a link and search for it in the agendas.
19520 The link is not stored in `org-stored-links', it is just created
19521 for the search purpose."
19522 (interactive)
19523 (let ((link (condition-case nil
19524 (org-store-link nil)
19525 (error "Unable to create a link to here"))))
19526 (org-occur-in-agenda-files (regexp-quote link))))
19528 (defun org-uniquify (list)
19529 "Remove duplicate elements from LIST."
19530 (let (res)
19531 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
19532 res))
19534 (defun org-delete-all (elts list)
19535 "Remove all elements in ELTS from LIST."
19536 (while elts
19537 (setq list (delete (pop elts) list)))
19538 list)
19540 (defun org-count (cl-item cl-seq)
19541 "Count the number of occurrences of ITEM in SEQ.
19542 Taken from `count' in cl-seq.el with all keyword arguments removed."
19543 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
19544 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
19545 (while (< cl-start cl-end)
19546 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
19547 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
19548 (setq cl-start (1+ cl-start)))
19549 cl-count))
19551 (defun org-remove-if (predicate seq)
19552 "Remove everything from SEQ that fulfills PREDICATE."
19553 (let (res e)
19554 (while seq
19555 (setq e (pop seq))
19556 (if (not (funcall predicate e)) (push e res)))
19557 (nreverse res)))
19559 (defun org-remove-if-not (predicate seq)
19560 "Remove everything from SEQ that does not fulfill PREDICATE."
19561 (let (res e)
19562 (while seq
19563 (setq e (pop seq))
19564 (if (funcall predicate e) (push e res)))
19565 (nreverse res)))
19567 (defun org-back-over-empty-lines ()
19568 "Move backwards over whitespace, to the beginning of the first empty line.
19569 Returns the number of empty lines passed."
19570 (let ((pos (point)))
19571 (if (cdr (assoc 'heading org-blank-before-new-entry))
19572 (skip-chars-backward " \t\n\r")
19573 (unless (eobp)
19574 (forward-line -1)))
19575 (beginning-of-line 2)
19576 (goto-char (min (point) pos))
19577 (count-lines (point) pos)))
19579 (defun org-skip-whitespace ()
19580 (skip-chars-forward " \t\n\r"))
19582 (defun org-point-in-group (point group &optional context)
19583 "Check if POINT is in match-group GROUP.
19584 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
19585 match. If the match group does not exist or point is not inside it,
19586 return nil."
19587 (and (match-beginning group)
19588 (>= point (match-beginning group))
19589 (<= point (match-end group))
19590 (if context
19591 (list context (match-beginning group) (match-end group))
19592 t)))
19594 (defun org-switch-to-buffer-other-window (&rest args)
19595 "Switch to buffer in a second window on the current frame.
19596 In particular, do not allow pop-up frames.
19597 Returns the newly created buffer."
19598 (let (pop-up-frames special-display-buffer-names special-display-regexps
19599 special-display-function)
19600 (apply 'switch-to-buffer-other-window args)))
19602 (defun org-combine-plists (&rest plists)
19603 "Create a single property list from all plists in PLISTS.
19604 The process starts by copying the first list, and then setting properties
19605 from the other lists. Settings in the last list are the most significant
19606 ones and overrule settings in the other lists."
19607 (let ((rtn (copy-sequence (pop plists)))
19608 p v ls)
19609 (while plists
19610 (setq ls (pop plists))
19611 (while ls
19612 (setq p (pop ls) v (pop ls))
19613 (setq rtn (plist-put rtn p v))))
19614 rtn))
19616 (defun org-move-line-down (arg)
19617 "Move the current line down. With prefix argument, move it past ARG lines."
19618 (interactive "p")
19619 (let ((col (current-column))
19620 beg end pos)
19621 (beginning-of-line 1) (setq beg (point))
19622 (beginning-of-line 2) (setq end (point))
19623 (beginning-of-line (+ 1 arg))
19624 (setq pos (move-marker (make-marker) (point)))
19625 (insert (delete-and-extract-region beg end))
19626 (goto-char pos)
19627 (org-move-to-column col)))
19629 (defun org-move-line-up (arg)
19630 "Move the current line up. With prefix argument, move it past ARG lines."
19631 (interactive "p")
19632 (let ((col (current-column))
19633 beg end pos)
19634 (beginning-of-line 1) (setq beg (point))
19635 (beginning-of-line 2) (setq end (point))
19636 (beginning-of-line (- arg))
19637 (setq pos (move-marker (make-marker) (point)))
19638 (insert (delete-and-extract-region beg end))
19639 (goto-char pos)
19640 (org-move-to-column col)))
19642 (defun org-replace-escapes (string table)
19643 "Replace %-escapes in STRING with values in TABLE.
19644 TABLE is an association list with keys like \"%a\" and string values.
19645 The sequences in STRING may contain normal field width and padding information,
19646 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
19647 so values can contain further %-escapes if they are define later in TABLE."
19648 (let ((tbl (copy-alist table))
19649 (case-fold-search nil)
19650 (pchg 0)
19651 e re rpl)
19652 (while (setq e (pop tbl))
19653 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
19654 (when (and (cdr e) (string-match re (cdr e)))
19655 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
19656 (safe "SREF"))
19657 (add-text-properties 0 3 (list 'sref sref) safe)
19658 (setcdr e (replace-match safe t t (cdr e)))))
19659 (while (string-match re string)
19660 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
19661 (cdr e)))
19662 (setq string (replace-match rpl t t string))))
19663 (while (setq pchg (next-property-change pchg string))
19664 (let ((sref (get-text-property pchg 'sref string)))
19665 (when (and sref (string-match "SREF" string pchg))
19666 (setq string (replace-match sref t t string)))))
19667 string))
19669 (defun org-sublist (list start end)
19670 "Return a section of LIST, from START to END.
19671 Counting starts at 1."
19672 (let (rtn (c start))
19673 (setq list (nthcdr (1- start) list))
19674 (while (and list (<= c end))
19675 (push (pop list) rtn)
19676 (setq c (1+ c)))
19677 (nreverse rtn)))
19679 (defun org-find-base-buffer-visiting (file)
19680 "Like `find-buffer-visiting' but always return the base buffer and
19681 not an indirect buffer."
19682 (let ((buf (or (get-file-buffer file)
19683 (find-buffer-visiting file))))
19684 (if buf
19685 (or (buffer-base-buffer buf) buf)
19686 nil)))
19688 (defun org-image-file-name-regexp (&optional extensions)
19689 "Return regexp matching the file names of images.
19690 If EXTENSIONS is given, only match these."
19691 (if (and (not extensions) (fboundp 'image-file-name-regexp))
19692 (image-file-name-regexp)
19693 (let ((image-file-name-extensions
19694 (or extensions
19695 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
19696 "xbm" "xpm" "pbm" "pgm" "ppm"))))
19697 (concat "\\."
19698 (regexp-opt (nconc (mapcar 'upcase
19699 image-file-name-extensions)
19700 image-file-name-extensions)
19702 "\\'"))))
19704 (defun org-file-image-p (file &optional extensions)
19705 "Return non-nil if FILE is an image."
19706 (save-match-data
19707 (string-match (org-image-file-name-regexp extensions) file)))
19709 (defun org-get-cursor-date ()
19710 "Return the date at cursor in as a time.
19711 This works in the calendar and in the agenda, anywhere else it just
19712 returns the current time."
19713 (let (date day defd)
19714 (cond
19715 ((eq major-mode 'calendar-mode)
19716 (setq date (calendar-cursor-to-date)
19717 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
19718 ((eq major-mode 'org-agenda-mode)
19719 (setq day (get-text-property (point) 'day))
19720 (if day
19721 (setq date (calendar-gregorian-from-absolute day)
19722 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
19723 (nth 2 date))))))
19724 (or defd (current-time))))
19726 (defvar org-agenda-action-marker (make-marker)
19727 "Marker pointing to the entry for the next agenda action.")
19729 (defun org-mark-entry-for-agenda-action ()
19730 "Mark the current entry as target of an agenda action.
19731 Agenda actions are actions executed from the agenda with the key `k',
19732 which make use of the date at the cursor."
19733 (interactive)
19734 (move-marker org-agenda-action-marker
19735 (save-excursion (org-back-to-heading t) (point))
19736 (current-buffer))
19737 (message
19738 "Entry marked for action; press `k' at desired date in agenda or calendar"))
19740 (defun org-mark-subtree ()
19741 "Mark the current subtree.
19742 This puts point at the start of the current subtree, and mark at the end.
19744 If point is in an inline task, mark that task instead."
19745 (interactive)
19746 (let ((inline-task-p
19747 (and (featurep 'org-inlinetask)
19748 (org-inlinetask-in-task-p)))
19749 (beg))
19750 ;; Get beginning of subtree
19751 (cond
19752 (inline-task-p (org-inlinetask-goto-beginning))
19753 ((org-at-heading-p) (beginning-of-line))
19754 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
19755 (setq beg (point))
19756 ;; Get end of it
19757 (if inline-task-p
19758 (org-inlinetask-goto-end)
19759 (org-end-of-subtree))
19760 ;; Mark zone
19761 (push-mark (point) nil t)
19762 (goto-char beg)))
19764 ;;; Paragraph filling stuff.
19765 ;; We want this to be just right, so use the full arsenal.
19767 (defun org-indent-line-function ()
19768 "Indent line depending on context."
19769 (interactive)
19770 (let* ((pos (point))
19771 (itemp (org-at-item-p))
19772 (case-fold-search t)
19773 (org-drawer-regexp (or org-drawer-regexp "\000"))
19774 (inline-task-p (and (featurep 'org-inlinetask)
19775 (org-inlinetask-in-task-p)))
19776 (inline-re (and inline-task-p
19777 (org-inlinetask-outline-regexp)))
19778 column)
19779 (beginning-of-line 1)
19780 (cond
19781 ;; Comments
19782 ((looking-at "# ") (setq column 0))
19783 ;; Headings
19784 ((looking-at org-outline-regexp) (setq column 0))
19785 ;; Included files
19786 ((looking-at "#\\+include:") (setq column 0))
19787 ;; Footnote definition
19788 ((looking-at org-footnote-definition-re) (setq column 0))
19789 ;; Literal examples
19790 ((looking-at "[ \t]*:\\( \\|$\\)")
19791 (setq column (org-get-indentation))) ; do nothing
19792 ;; Lists
19793 ((ignore-errors (goto-char (org-in-item-p)))
19794 (setq column (if itemp
19795 (org-get-indentation)
19796 (org-list-item-body-column (point))))
19797 (goto-char pos))
19798 ;; Drawers
19799 ((and (looking-at "[ \t]*:END:")
19800 (save-excursion (re-search-backward org-drawer-regexp nil t)))
19801 (save-excursion
19802 (goto-char (1- (match-beginning 1)))
19803 (setq column (current-column))))
19804 ;; Special blocks
19805 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
19806 (save-excursion
19807 (re-search-backward
19808 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
19809 (setq column (org-get-indentation (match-string 0))))
19810 ((and (not (looking-at "[ \t]*#\\+begin_"))
19811 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
19812 (save-excursion
19813 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
19814 (setq column
19815 (cond ((equal (downcase (match-string 1)) "src")
19816 ;; src blocks: let `org-edit-src-exit' handle them
19817 (org-get-indentation))
19818 ((equal (downcase (match-string 1)) "example")
19819 (max (org-get-indentation)
19820 (org-get-indentation (match-string 0))))
19822 (org-get-indentation (match-string 0))))))
19823 ;; This line has nothing special, look at the previous relevant
19824 ;; line to compute indentation
19826 (beginning-of-line 0)
19827 (while (and (not (bobp))
19828 (not (looking-at org-drawer-regexp))
19829 ;; When point started in an inline task, do not move
19830 ;; above task starting line.
19831 (not (and inline-task-p (looking-at inline-re)))
19832 ;; Skip drawers, blocks, empty lines, verbatim,
19833 ;; comments, tables, footnotes definitions, lists,
19834 ;; inline tasks.
19835 (or (and (looking-at "[ \t]*:END:")
19836 (re-search-backward org-drawer-regexp nil t))
19837 (and (looking-at "[ \t]*#\\+end_")
19838 (re-search-backward "[ \t]*#\\+begin_"nil t))
19839 (looking-at "[ \t]*[\n:#|]")
19840 (looking-at org-footnote-definition-re)
19841 (and (ignore-errors (goto-char (org-in-item-p)))
19842 (goto-char
19843 (org-list-get-top-point (org-list-struct))))
19844 (and (not inline-task-p)
19845 (featurep 'org-inlinetask)
19846 (org-inlinetask-in-task-p)
19847 (or (org-inlinetask-goto-beginning) t))))
19848 (beginning-of-line 0))
19849 (cond
19850 ;; There was an heading above.
19851 ((looking-at "\\*+[ \t]+")
19852 (if (not org-adapt-indentation)
19853 (setq column 0)
19854 (goto-char (match-end 0))
19855 (setq column (current-column))))
19856 ;; A drawer had started and is unfinished
19857 ((looking-at org-drawer-regexp)
19858 (goto-char (1- (match-beginning 1)))
19859 (setq column (current-column)))
19860 ;; Else, nothing noticeable found: get indentation and go on.
19861 (t (setq column (org-get-indentation))))))
19862 ;; Now apply indentation and move cursor accordingly
19863 (goto-char pos)
19864 (if (<= (current-column) (current-indentation))
19865 (org-indent-line-to column)
19866 (save-excursion (org-indent-line-to column)))
19867 ;; Special polishing for properties, see `org-property-format'
19868 (setq column (current-column))
19869 (beginning-of-line 1)
19870 (if (looking-at
19871 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
19872 (replace-match (concat (match-string 1)
19873 (format org-property-format
19874 (match-string 2) (match-string 3)))
19875 t t))
19876 (org-move-to-column column)))
19878 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
19879 "Variable to store copy of `adaptive-fill-regexp'.
19880 Since `adaptive-fill-regexp' is set to never match, we need to
19881 store a backup of its value before entering `org-mode' so that
19882 the functionality can be provided as a fall-back.")
19884 (defun org-set-autofill-regexps ()
19885 (interactive)
19886 ;; In the paragraph separator we include headlines, because filling
19887 ;; text in a line directly attached to a headline would otherwise
19888 ;; fill the headline as well.
19889 (org-set-local 'comment-start-skip "^#+[ \t]*")
19890 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
19891 ;; The paragraph starter includes hand-formatted lists.
19892 (org-set-local
19893 'paragraph-start
19894 (concat
19895 "\f" "\\|"
19896 "[ ]*$" "\\|"
19897 org-outline-regexp "\\|"
19898 "[ \t]*#" "\\|"
19899 (org-item-re) "\\|"
19900 "[ \t]*[:|]" "\\|"
19901 "\\$\\$" "\\|"
19902 "\\\\\\(begin\\|end\\|[][]\\)"))
19903 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
19904 ;; But only if the user has not turned off tables or fixed-width regions
19905 (org-set-local
19906 'auto-fill-inhibit-regexp
19907 (concat org-outline-regexp
19908 "\\|#\\+"
19909 "\\|[ \t]*" org-keyword-time-regexp
19910 (if (or org-enable-table-editor org-enable-fixed-width-editor)
19911 (concat
19912 "\\|[ \t]*["
19913 (if org-enable-table-editor "|" "")
19914 (if org-enable-fixed-width-editor ":" "")
19915 "]"))))
19916 ;; We use our own fill-paragraph function, to make sure that tables
19917 ;; and fixed-width regions are not wrapped. That function will pass
19918 ;; through to `fill-paragraph' when appropriate.
19919 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
19920 ;; Prevent auto-fill from inserting unwanted new items.
19921 (if (boundp 'fill-nobreak-predicate)
19922 (org-set-local 'fill-nobreak-predicate
19923 (if (memq 'org-fill-item-nobreak-p fill-nobreak-predicate)
19924 fill-nobreak-predicate
19925 (cons 'org-fill-item-nobreak-p fill-nobreak-predicate))))
19926 ;; Adaptive filling: To get full control, first make sure that
19927 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
19928 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
19929 (org-set-local 'org-adaptive-fill-regexp-backup
19930 adaptive-fill-regexp))
19931 (org-set-local 'adaptive-fill-regexp "\000")
19932 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
19933 (org-set-local 'adaptive-fill-function
19934 'org-adaptive-fill-function)
19935 (org-set-local
19936 'align-mode-rules-list
19937 '((org-in-buffer-settings
19938 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
19939 (modes . '(org-mode))))))
19941 (defun org-fill-item-nobreak-p ()
19942 "Non-nil when a line break at point would insert a new item."
19943 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
19945 (defun org-fill-paragraph (&optional justify)
19946 "Re-align a table, pass through to fill-paragraph if no table."
19947 (let ((table-p (org-at-table-p))
19948 (table.el-p (org-at-table.el-p))
19949 (itemp (org-in-item-p)))
19950 (cond ((and (equal (char-after (point-at-bol)) ?*)
19951 (save-excursion (goto-char (point-at-bol))
19952 (looking-at org-outline-regexp)))
19953 t) ; skip headlines
19954 (table.el-p t) ; skip table.el tables
19955 (table-p (org-table-align) t) ; align Org tables
19956 (itemp ; align text in items
19957 (let* ((struct (save-excursion (goto-char itemp)
19958 (org-list-struct)))
19959 (parents (org-list-parents-alist struct))
19960 (children (org-list-get-children itemp struct parents))
19961 beg end prev next prefix)
19962 ;; Determine in which part of item point is: before
19963 ;; first child, after last child, between two
19964 ;; sub-lists, or simply in item if there's no child.
19965 (cond
19966 ((not children)
19967 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
19968 beg itemp
19969 end (org-list-get-item-end itemp struct)))
19970 ((< (point) (setq next (car children)))
19971 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
19972 beg itemp
19973 end next))
19974 ((> (point) (setq prev (car (last children))))
19975 (setq beg (org-list-get-item-end prev struct)
19976 end (org-list-get-item-end itemp struct)
19977 prefix (save-excursion
19978 (goto-char beg)
19979 (skip-chars-forward " \t")
19980 (make-string (current-column) ?\ ))))
19981 (t (catch 'exit
19982 (while (setq next (pop children))
19983 (if (> (point) next)
19984 (setq prev next)
19985 (setq beg (org-list-get-item-end prev struct)
19986 end next
19987 prefix (save-excursion
19988 (goto-char beg)
19989 (skip-chars-forward " \t")
19990 (make-string (current-column) ?\ )))
19991 (throw 'exit nil))))))
19992 ;; Use `fill-paragraph' with buffer narrowed to item
19993 ;; without any child, and with our computed PREFIX.
19994 (flet ((fill-context-prefix (from to &optional flr) prefix))
19995 (save-restriction
19996 (narrow-to-region beg end)
19997 (save-excursion (fill-paragraph justify)))) t))
19998 ;; Special case where point is not in a list but is on
19999 ;; a paragraph adjacent to a list: make sure this paragraph
20000 ;; doesn't get merged with the end of the list by narrowing
20001 ;; buffer first.
20002 ((save-excursion (forward-paragraph -1)
20003 (setq itemp (org-in-item-p)))
20004 (let ((struct (save-excursion (goto-char itemp)
20005 (org-list-struct))))
20006 (save-restriction
20007 (narrow-to-region (org-list-get-bottom-point struct)
20008 (save-excursion (forward-paragraph 1)
20009 (point)))
20010 (fill-paragraph justify) t)))
20011 ;; Else simply call `fill-paragraph'.
20012 (t nil))))
20014 ;; For reference, this is the default value of adaptive-fill-regexp
20015 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
20017 (defun org-adaptive-fill-function ()
20018 "Return a fill prefix for org-mode files."
20019 (let (itemp)
20020 (save-excursion
20021 (cond
20022 ;; Comment line
20023 ((looking-at "#[ \t]+")
20024 (match-string-no-properties 0))
20025 ;; Plain list item
20026 ((org-at-item-p)
20027 (make-string (org-list-item-body-column (point-at-bol)) ?\ ))
20028 ;; Point is in a list after `backward-paragraph': original
20029 ;; point wasn't in the list, or filling would have been taken
20030 ;; care of by `org-auto-fill-function', but the list and the
20031 ;; real paragraph are not separated by a blank line. Thus, move
20032 ;; point after the list to go back to real paragraph and
20033 ;; determine fill-prefix.
20034 ((setq itemp (org-in-item-p))
20035 (goto-char itemp)
20036 (let* ((struct (org-list-struct))
20037 (bottom (org-list-get-bottom-point struct)))
20038 (goto-char bottom)
20039 (make-string (org-get-indentation) ?\ )))
20040 ;; Other text
20041 ((looking-at org-adaptive-fill-regexp-backup)
20042 (match-string-no-properties 0))))))
20044 (defun org-auto-fill-function ()
20045 "Auto-fill function."
20046 (let (itemp prefix)
20047 ;; When in a list, compute an appropriate fill-prefix and make
20048 ;; sure it will be used by `do-auto-fill'.
20049 (if (setq itemp (org-in-item-p))
20050 (progn
20051 (setq prefix (make-string (org-list-item-body-column itemp) ?\ ))
20052 (flet ((fill-context-prefix (from to &optional flr) prefix))
20053 (do-auto-fill)))
20054 ;; Else just use `do-auto-fill'.
20055 (do-auto-fill))))
20057 ;;; Other stuff.
20059 (defun org-toggle-fixed-width-section (arg)
20060 "Toggle the fixed-width export.
20061 If there is no active region, the QUOTE keyword at the current headline is
20062 inserted or removed. When present, it causes the text between this headline
20063 and the next to be exported as fixed-width text, and unmodified.
20064 If there is an active region, this command adds or removes a colon as the
20065 first character of this line. If the first character of a line is a colon,
20066 this line is also exported in fixed-width font."
20067 (interactive "P")
20068 (let* ((cc 0)
20069 (regionp (org-region-active-p))
20070 (beg (if regionp (region-beginning) (point)))
20071 (end (if regionp (region-end)))
20072 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
20073 (case-fold-search nil)
20074 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
20075 off)
20076 (if regionp
20077 (save-excursion
20078 (goto-char beg)
20079 (setq cc (current-column))
20080 (beginning-of-line 1)
20081 (setq off (looking-at re))
20082 (while (> nlines 0)
20083 (setq nlines (1- nlines))
20084 (beginning-of-line 1)
20085 (cond
20086 (arg
20087 (org-move-to-column cc t)
20088 (insert ": \n")
20089 (forward-line -1))
20090 ((and off (looking-at re))
20091 (replace-match "" t t nil 1))
20092 ((not off) (org-move-to-column cc t) (insert ": ")))
20093 (forward-line 1)))
20094 (save-excursion
20095 (org-back-to-heading)
20096 (cond
20097 ((looking-at (format org-heading-keyword-regexp-format
20098 org-quote-string))
20099 (goto-char (match-end 1))
20100 (looking-at (concat " +" org-quote-string))
20101 (replace-match "" t t)
20102 (when (eolp) (insert " ")))
20103 ((looking-at org-outline-regexp)
20104 (goto-char (match-end 0))
20105 (insert org-quote-string " ")))))))
20107 (defun org-reftex-citation ()
20108 "Use reftex-citation to insert a citation into the buffer.
20109 This looks for a line like
20111 #+BIBLIOGRAPHY: foo plain option:-d
20113 and derives from it that foo.bib is the bibliography file relevant
20114 for this document. It then installs the necessary environment for RefTeX
20115 to work in this buffer and calls `reftex-citation' to insert a citation
20116 into the buffer.
20118 Export of such citations to both LaTeX and HTML is handled by the contributed
20119 package org-exp-bibtex by Taru Karttunen."
20120 (interactive)
20121 (let ((reftex-docstruct-symbol 'rds)
20122 (reftex-cite-format "\\cite{%l}")
20123 rds bib)
20124 (save-excursion
20125 (save-restriction
20126 (widen)
20127 (let ((case-fold-search t)
20128 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
20129 (if (not (save-excursion
20130 (or (re-search-forward re nil t)
20131 (re-search-backward re nil t))))
20132 (error "No bibliography defined in file")
20133 (setq bib (concat (match-string 1) ".bib")
20134 rds (list (list 'bib bib)))))))
20135 (call-interactively 'reftex-citation)))
20137 ;;;; Functions extending outline functionality
20139 (defun org-beginning-of-line (&optional arg)
20140 "Go to the beginning of the current line. If that is invisible, continue
20141 to a visible line beginning. This makes the function of C-a more intuitive.
20142 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20143 first attempt, and only move to after the tags when the cursor is already
20144 beyond the end of the headline."
20145 (interactive "P")
20146 (let ((pos (point))
20147 (special (if (consp org-special-ctrl-a/e)
20148 (car org-special-ctrl-a/e)
20149 org-special-ctrl-a/e))
20150 refpos)
20151 (if (org-bound-and-true-p line-move-visual)
20152 (beginning-of-visual-line 1)
20153 (beginning-of-line 1))
20154 (if (and arg (fboundp 'move-beginning-of-line))
20155 (call-interactively 'move-beginning-of-line)
20156 (if (bobp)
20158 (backward-char 1)
20159 (if (org-truely-invisible-p)
20160 (while (and (not (bobp)) (org-truely-invisible-p))
20161 (backward-char 1)
20162 (beginning-of-line 1))
20163 (forward-char 1))))
20164 (when special
20165 (cond
20166 ((and (looking-at org-complex-heading-regexp)
20167 (= (char-after (match-end 1)) ?\ ))
20168 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
20169 (point-at-eol)))
20170 (goto-char
20171 (if (eq special t)
20172 (cond ((> pos refpos) refpos)
20173 ((= pos (point)) refpos)
20174 (t (point)))
20175 (cond ((> pos (point)) (point))
20176 ((not (eq last-command this-command)) (point))
20177 (t refpos)))))
20178 ((org-at-item-p)
20179 (goto-char
20180 (if (eq special t)
20181 (cond ((> pos (match-end 0)) (match-end 0))
20182 ((= pos (point)) (match-end 0))
20183 (t (point)))
20184 (cond ((> pos (point)) (point))
20185 ((not (eq last-command this-command)) (point))
20186 (t (match-end 0))))))))
20187 (org-no-warnings
20188 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20190 (defun org-end-of-line (&optional arg)
20191 "Go to the end of the line.
20192 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20193 first attempt, and only move to after the tags when the cursor is already
20194 beyond the end of the headline."
20195 (interactive "P")
20196 (let ((special (if (consp org-special-ctrl-a/e)
20197 (cdr org-special-ctrl-a/e)
20198 org-special-ctrl-a/e)))
20199 (cond
20200 ((or (not special) arg
20201 (not (or (org-on-heading-p) (org-at-item-p))))
20202 (call-interactively
20203 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
20204 ((fboundp 'move-end-of-line) 'move-end-of-line)
20205 (t 'end-of-line))))
20206 ((org-on-heading-p)
20207 (let ((pos (point)))
20208 (beginning-of-line 1)
20209 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
20210 (if (eq special t)
20211 (if (or (< pos (match-beginning 1))
20212 (= pos (match-end 0)))
20213 (goto-char (match-beginning 1))
20214 (goto-char (match-end 0)))
20215 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
20216 (goto-char (match-end 0))
20217 (goto-char (match-beginning 1))))
20218 (call-interactively (if (fboundp 'move-end-of-line)
20219 'move-end-of-line
20220 'end-of-line)))))
20221 ;; At an item: Move before any hidden text.
20222 (t (call-interactively 'end-of-line)))
20223 (org-no-warnings
20224 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20226 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
20227 (define-key org-mode-map "\C-e" 'org-end-of-line)
20229 (defun org-backward-sentence (&optional arg)
20230 "Go to beginning of sentence, or beginning of table field.
20231 This will call `backward-sentence' or `org-table-beginning-of-field',
20232 depending on context."
20233 (interactive "P")
20234 (cond
20235 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
20236 (t (call-interactively 'backward-sentence))))
20238 (defun org-forward-sentence (&optional arg)
20239 "Go to end of sentence, or end of table field.
20240 This will call `forward-sentence' or `org-table-end-of-field',
20241 depending on context."
20242 (interactive "P")
20243 (cond
20244 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
20245 (t (call-interactively 'forward-sentence))))
20247 (define-key org-mode-map "\M-a" 'org-backward-sentence)
20248 (define-key org-mode-map "\M-e" 'org-forward-sentence)
20250 (defun org-kill-line (&optional arg)
20251 "Kill line, to tags or end of line."
20252 (interactive "P")
20253 (cond
20254 ((or (not org-special-ctrl-k)
20255 (bolp)
20256 (not (org-on-heading-p)))
20257 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
20258 org-ctrl-k-protect-subtree)
20259 (if (or (eq org-ctrl-k-protect-subtree 'error)
20260 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
20261 (error "C-k aborted - would kill hidden subtree")))
20262 (call-interactively 'kill-line))
20263 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
20264 (kill-region (point) (match-beginning 1))
20265 (org-set-tags nil t))
20266 (t (kill-region (point) (point-at-eol)))))
20268 (define-key org-mode-map "\C-k" 'org-kill-line)
20270 (defun org-yank (&optional arg)
20271 "Yank. If the kill is a subtree, treat it specially.
20272 This command will look at the current kill and check if is a single
20273 subtree, or a series of subtrees[1]. If it passes the test, and if the
20274 cursor is at the beginning of a line or after the stars of a currently
20275 empty headline, then the yank is handled specially. How exactly depends
20276 on the value of the following variables, both set by default.
20278 org-yank-folded-subtrees
20279 When set, the subtree(s) will be folded after insertion, but only
20280 if doing so would now swallow text after the yanked text.
20282 org-yank-adjusted-subtrees
20283 When set, the subtree will be promoted or demoted in order to
20284 fit into the local outline tree structure, which means that the level
20285 will be adjusted so that it becomes the smaller one of the two
20286 *visible* surrounding headings.
20288 Any prefix to this command will cause `yank' to be called directly with
20289 no special treatment. In particular, a simple \\[universal-argument] prefix \
20290 will just
20291 plainly yank the text as it is.
20293 \[1] The test checks if the first non-white line is a heading
20294 and if there are no other headings with fewer stars."
20295 (interactive "P")
20296 (org-yank-generic 'yank arg))
20298 (defun org-yank-generic (command arg)
20299 "Perform some yank-like command.
20301 This function implements the behavior described in the `org-yank'
20302 documentation. However, it has been generalized to work for any
20303 interactive command with similar behavior."
20305 ;; pretend to be command COMMAND
20306 (setq this-command command)
20308 (if arg
20309 (call-interactively command)
20311 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
20312 (and (org-kill-is-subtree-p)
20313 (or (bolp)
20314 (and (looking-at "[ \t]*$")
20315 (string-match
20316 "\\`\\*+\\'"
20317 (buffer-substring (point-at-bol) (point)))))))
20318 swallowp)
20319 (cond
20320 ((and subtreep org-yank-folded-subtrees)
20321 (let ((beg (point))
20322 end)
20323 (if (and subtreep org-yank-adjusted-subtrees)
20324 (org-paste-subtree nil nil 'for-yank)
20325 (call-interactively command))
20327 (setq end (point))
20328 (goto-char beg)
20329 (when (and (bolp) subtreep
20330 (not (setq swallowp
20331 (org-yank-folding-would-swallow-text beg end))))
20332 (org-with-limited-levels
20333 (or (looking-at org-outline-regexp)
20334 (re-search-forward org-outline-regexp-bol end t))
20335 (while (and (< (point) end) (looking-at org-outline-regexp))
20336 (hide-subtree)
20337 (org-cycle-show-empty-lines 'folded)
20338 (condition-case nil
20339 (outline-forward-same-level 1)
20340 (error (goto-char end))))))
20341 (when swallowp
20342 (message
20343 "Inserted text not folded because that would swallow text"))
20345 (goto-char end)
20346 (skip-chars-forward " \t\n\r")
20347 (beginning-of-line 1)
20348 (push-mark beg 'nomsg)))
20349 ((and subtreep org-yank-adjusted-subtrees)
20350 (let ((beg (point-at-bol)))
20351 (org-paste-subtree nil nil 'for-yank)
20352 (push-mark beg 'nomsg)))
20354 (call-interactively command))))))
20356 (defun org-yank-folding-would-swallow-text (beg end)
20357 "Would hide-subtree at BEG swallow any text after END?"
20358 (let (level)
20359 (org-with-limited-levels
20360 (save-excursion
20361 (goto-char beg)
20362 (when (or (looking-at org-outline-regexp)
20363 (re-search-forward org-outline-regexp-bol end t))
20364 (setq level (org-outline-level)))
20365 (goto-char end)
20366 (skip-chars-forward " \t\r\n\v\f")
20367 (if (or (eobp)
20368 (and (bolp) (looking-at org-outline-regexp)
20369 (<= (org-outline-level) level)))
20370 nil ; Nothing would be swallowed
20371 t))))) ; something would swallow
20373 (define-key org-mode-map "\C-y" 'org-yank)
20375 (defun org-truely-invisible-p ()
20376 "Check if point is at a character currently not visible.
20377 This version does not only check the character property, but also
20378 `visible-mode'."
20379 ;; Early versions of noutline don't have `outline-invisible-p'.
20380 (if (org-bound-and-true-p visible-mode)
20382 (outline-invisible-p)))
20384 (defun org-invisible-p2 ()
20385 "Check if point is at a character currently not visible."
20386 (save-excursion
20387 (if (and (eolp) (not (bobp))) (backward-char 1))
20388 ;; Early versions of noutline don't have `outline-invisible-p'.
20389 (outline-invisible-p)))
20391 (defun org-back-to-heading (&optional invisible-ok)
20392 "Call `outline-back-to-heading', but provide a better error message."
20393 (condition-case nil
20394 (outline-back-to-heading invisible-ok)
20395 (error (error "Before first headline at position %d in buffer %s"
20396 (point) (current-buffer)))))
20398 (defun org-beginning-of-defun ()
20399 "Go to the beginning of the subtree, i.e. back to the heading."
20400 (org-back-to-heading))
20401 (defun org-end-of-defun ()
20402 "Go to the end of the subtree."
20403 (org-end-of-subtree nil t))
20405 (defun org-before-first-heading-p ()
20406 "Before first heading?"
20407 (save-excursion
20408 (end-of-line)
20409 (null (re-search-backward org-outline-regexp-bol nil t))))
20411 (defun org-on-heading-p (&optional ignored)
20412 (outline-on-heading-p t))
20413 (defun org-at-heading-p (&optional ignored)
20414 (outline-on-heading-p t))
20416 (defun org-point-at-end-of-empty-headline ()
20417 "If point is at the end of an empty headline, return t, else nil.
20418 If the heading only contains a TODO keyword, it is still still considered
20419 empty."
20420 (and (looking-at "[ \t]*$")
20421 (save-excursion
20422 (beginning-of-line 1)
20423 (let ((case-fold-search nil))
20424 (looking-at org-todo-line-regexp)))
20425 (string= (match-string 3) "")))
20427 (defun org-at-heading-or-item-p ()
20428 (or (org-on-heading-p) (org-at-item-p)))
20430 (defun org-on-target-p ()
20431 (or (org-in-regexp org-radio-target-regexp)
20432 (org-in-regexp org-target-regexp)))
20434 (defun org-up-heading-all (arg)
20435 "Move to the heading line of which the present line is a subheading.
20436 This function considers both visible and invisible heading lines.
20437 With argument, move up ARG levels."
20438 (if (fboundp 'outline-up-heading-all)
20439 (outline-up-heading-all arg) ; emacs 21 version of outline.el
20440 (outline-up-heading arg t))) ; emacs 22 version of outline.el
20442 (defun org-up-heading-safe ()
20443 "Move to the heading line of which the present line is a subheading.
20444 This version will not throw an error. It will return the level of the
20445 headline found, or nil if no higher level is found.
20447 Also, this function will be a lot faster than `outline-up-heading',
20448 because it relies on stars being the outline starters. This can really
20449 make a significant difference in outlines with very many siblings."
20450 (let (start-level re)
20451 (org-back-to-heading t)
20452 (setq start-level (funcall outline-level))
20453 (if (equal start-level 1)
20455 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
20456 (if (re-search-backward re nil t)
20457 (funcall outline-level)))))
20459 (defun org-first-sibling-p ()
20460 "Is this heading the first child of its parents?"
20461 (interactive)
20462 (let ((re org-outline-regexp-bol)
20463 level l)
20464 (unless (org-at-heading-p t)
20465 (error "Not at a heading"))
20466 (setq level (funcall outline-level))
20467 (save-excursion
20468 (if (not (re-search-backward re nil t))
20470 (setq l (funcall outline-level))
20471 (< l level)))))
20473 (defun org-goto-sibling (&optional previous)
20474 "Goto the next sibling, even if it is invisible.
20475 When PREVIOUS is set, go to the previous sibling instead. Returns t
20476 when a sibling was found. When none is found, return nil and don't
20477 move point."
20478 (let ((fun (if previous 're-search-backward 're-search-forward))
20479 (pos (point))
20480 (re org-outline-regexp-bol)
20481 level l)
20482 (when (condition-case nil (org-back-to-heading t) (error nil))
20483 (setq level (funcall outline-level))
20484 (catch 'exit
20485 (or previous (forward-char 1))
20486 (while (funcall fun re nil t)
20487 (setq l (funcall outline-level))
20488 (when (< l level) (goto-char pos) (throw 'exit nil))
20489 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
20490 (goto-char pos)
20491 nil))))
20493 (defun org-show-siblings ()
20494 "Show all siblings of the current headline."
20495 (save-excursion
20496 (while (org-goto-sibling) (org-flag-heading nil)))
20497 (save-excursion
20498 (while (org-goto-sibling 'previous)
20499 (org-flag-heading nil))))
20501 (defun org-goto-first-child ()
20502 "Goto the first child, even if it is invisible.
20503 Return t when a child was found. Otherwise don't move point and
20504 return nil."
20505 (let (level (pos (point)) (re org-outline-regexp-bol))
20506 (when (condition-case nil (org-back-to-heading t) (error nil))
20507 (setq level (outline-level))
20508 (forward-char 1)
20509 (if (and (re-search-forward re nil t) (> (outline-level) level))
20510 (progn (goto-char (match-beginning 0)) t)
20511 (goto-char pos) nil))))
20513 (defun org-show-hidden-entry ()
20514 "Show an entry where even the heading is hidden."
20515 (save-excursion
20516 (org-show-entry)))
20518 (defun org-flag-heading (flag &optional entry)
20519 "Flag the current heading. FLAG non-nil means make invisible.
20520 When ENTRY is non-nil, show the entire entry."
20521 (save-excursion
20522 (org-back-to-heading t)
20523 ;; Check if we should show the entire entry
20524 (if entry
20525 (progn
20526 (org-show-entry)
20527 (save-excursion
20528 (and (outline-next-heading)
20529 (org-flag-heading nil))))
20530 (outline-flag-region (max (point-min) (1- (point)))
20531 (save-excursion (outline-end-of-heading) (point))
20532 flag))))
20534 (defun org-get-next-sibling ()
20535 "Move to next heading of the same level, and return point.
20536 If there is no such heading, return nil.
20537 This is like outline-next-sibling, but invisible headings are ok."
20538 (let ((level (funcall outline-level)))
20539 (outline-next-heading)
20540 (while (and (not (eobp)) (> (funcall outline-level) level))
20541 (outline-next-heading))
20542 (if (or (eobp) (< (funcall outline-level) level))
20544 (point))))
20546 (defun org-get-last-sibling ()
20547 "Move to previous heading of the same level, and return point.
20548 If there is no such heading, return nil."
20549 (let ((opoint (point))
20550 (level (funcall outline-level)))
20551 (outline-previous-heading)
20552 (when (and (/= (point) opoint) (outline-on-heading-p t))
20553 (while (and (> (funcall outline-level) level)
20554 (not (bobp)))
20555 (outline-previous-heading))
20556 (if (< (funcall outline-level) level)
20558 (point)))))
20560 (defun org-end-of-subtree (&optional invisible-OK to-heading)
20561 ;; This contains an exact copy of the original function, but it uses
20562 ;; `org-back-to-heading', to make it work also in invisible
20563 ;; trees. And is uses an invisible-OK argument.
20564 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
20565 ;; Furthermore, when used inside Org, finding the end of a large subtree
20566 ;; with many children and grandchildren etc, this can be much faster
20567 ;; than the outline version.
20568 (org-back-to-heading invisible-OK)
20569 (let ((first t)
20570 (level (funcall outline-level)))
20571 (if (and (eq major-mode 'org-mode) (< level 1000))
20572 ;; A true heading (not a plain list item), in Org-mode
20573 ;; This means we can easily find the end by looking
20574 ;; only for the right number of stars. Using a regexp to do
20575 ;; this is so much faster than using a Lisp loop.
20576 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
20577 (forward-char 1)
20578 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
20579 ;; something else, do it the slow way
20580 (while (and (not (eobp))
20581 (or first (> (funcall outline-level) level)))
20582 (setq first nil)
20583 (outline-next-heading)))
20584 (unless to-heading
20585 (if (memq (preceding-char) '(?\n ?\^M))
20586 (progn
20587 ;; Go to end of line before heading
20588 (forward-char -1)
20589 (if (memq (preceding-char) '(?\n ?\^M))
20590 ;; leave blank line before heading
20591 (forward-char -1))))))
20592 (point))
20594 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
20595 "Use Org version in org-mode, for dramatic speed-up."
20596 (if (eq major-mode 'org-mode)
20597 (progn
20598 (org-end-of-subtree nil t)
20599 (unless (eobp) (backward-char 1)))
20600 ad-do-it))
20602 (defun org-end-of-meta-data-and-drawers ()
20603 "Jump to the first text after meta data and drawers in the current entry.
20604 This will move over empty lines, lines with planning time stamps,
20605 clocking lines, and drawers."
20606 (org-back-to-heading t)
20607 (let ((end (save-excursion (outline-next-heading) (point)))
20608 (re (concat "\\(" org-drawer-regexp "\\)"
20609 "\\|" "[ \t]*" org-keyword-time-regexp)))
20610 (forward-line 1)
20611 (while (re-search-forward re end t)
20612 (if (not (match-end 1))
20613 ;; empty or planning line
20614 (forward-line 1)
20615 ;; a drawer, find the end
20616 (re-search-forward "^[ \t]*:END:" end 'move)
20617 (forward-line 1)))
20618 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
20619 (point)))
20621 (defun org-forward-same-level (arg &optional invisible-ok)
20622 "Move forward to the arg'th subheading at same level as this one.
20623 Stop at the first and last subheadings of a superior heading.
20624 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
20625 it wil also look at invisible ones."
20626 (interactive "p")
20627 (org-back-to-heading invisible-ok)
20628 (org-on-heading-p)
20629 (let* ((level (- (match-end 0) (match-beginning 0) 1))
20630 (re (format "^\\*\\{1,%d\\} " level))
20632 (forward-char 1)
20633 (while (> arg 0)
20634 (while (and (re-search-forward re nil 'move)
20635 (setq l (- (match-end 0) (match-beginning 0) 1))
20636 (= l level)
20637 (not invisible-ok)
20638 (progn (backward-char 1) (outline-invisible-p)))
20639 (if (< l level) (setq arg 1)))
20640 (setq arg (1- arg)))
20641 (beginning-of-line 1)))
20643 (defun org-backward-same-level (arg &optional invisible-ok)
20644 "Move backward to the arg'th subheading at same level as this one.
20645 Stop at the first and last subheadings of a superior heading."
20646 (interactive "p")
20647 (org-back-to-heading)
20648 (org-on-heading-p)
20649 (let* ((level (- (match-end 0) (match-beginning 0) 1))
20650 (re (format "^\\*\\{1,%d\\} " level))
20652 (while (> arg 0)
20653 (while (and (re-search-backward re nil 'move)
20654 (setq l (- (match-end 0) (match-beginning 0) 1))
20655 (= l level)
20656 (not invisible-ok)
20657 (outline-invisible-p))
20658 (if (< l level) (setq arg 1)))
20659 (setq arg (1- arg)))))
20661 (defun org-show-subtree ()
20662 "Show everything after this heading at deeper levels."
20663 (outline-flag-region
20664 (point)
20665 (save-excursion
20666 (org-end-of-subtree t t))
20667 nil))
20669 (defun org-show-entry ()
20670 "Show the body directly following this heading.
20671 Show the heading too, if it is currently invisible."
20672 (interactive)
20673 (save-excursion
20674 (condition-case nil
20675 (progn
20676 (org-back-to-heading t)
20677 (outline-flag-region
20678 (max (point-min) (1- (point)))
20679 (save-excursion
20680 (if (re-search-forward
20681 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
20682 (match-beginning 1)
20683 (point-max)))
20684 nil)
20685 (org-cycle-hide-drawers 'children))
20686 (error nil))))
20688 (defun org-make-options-regexp (kwds &optional extra)
20689 "Make a regular expression for keyword lines."
20690 (concat
20692 "#?[ \t]*\\+\\("
20693 (mapconcat 'regexp-quote kwds "\\|")
20694 (if extra (concat "\\|" extra))
20695 "\\):[ \t]*"
20696 "\\(.*\\)"))
20698 ;; Make isearch reveal the necessary context
20699 (defun org-isearch-end ()
20700 "Reveal context after isearch exits."
20701 (when isearch-success ; only if search was successful
20702 (if (featurep 'xemacs)
20703 ;; Under XEmacs, the hook is run in the correct place,
20704 ;; we directly show the context.
20705 (org-show-context 'isearch)
20706 ;; In Emacs the hook runs *before* restoring the overlays.
20707 ;; So we have to use a one-time post-command-hook to do this.
20708 ;; (Emacs 22 has a special variable, see function `org-mode')
20709 (unless (and (boundp 'isearch-mode-end-hook-quit)
20710 isearch-mode-end-hook-quit)
20711 ;; Only when the isearch was not quitted.
20712 (org-add-hook 'post-command-hook 'org-isearch-post-command
20713 'append 'local)))))
20715 (defun org-isearch-post-command ()
20716 "Remove self from hook, and show context."
20717 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
20718 (org-show-context 'isearch))
20721 ;;;; Integration with and fixes for other packages
20723 ;;; Imenu support
20725 (defvar org-imenu-markers nil
20726 "All markers currently used by Imenu.")
20727 (make-variable-buffer-local 'org-imenu-markers)
20729 (defun org-imenu-new-marker (&optional pos)
20730 "Return a new marker for use by Imenu, and remember the marker."
20731 (let ((m (make-marker)))
20732 (move-marker m (or pos (point)))
20733 (push m org-imenu-markers)
20736 (defun org-imenu-get-tree ()
20737 "Produce the index for Imenu."
20738 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
20739 (setq org-imenu-markers nil)
20740 (let* ((n org-imenu-depth)
20741 (re (concat "^" (org-get-limited-outline-regexp)))
20742 (subs (make-vector (1+ n) nil))
20743 (last-level 0)
20744 m level head)
20745 (save-excursion
20746 (save-restriction
20747 (widen)
20748 (goto-char (point-max))
20749 (while (re-search-backward re nil t)
20750 (setq level (org-reduced-level (funcall outline-level)))
20751 (when (<= level n)
20752 (looking-at org-complex-heading-regexp)
20753 (setq head (org-link-display-format
20754 (org-match-string-no-properties 4))
20755 m (org-imenu-new-marker))
20756 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
20757 (if (>= level last-level)
20758 (push (cons head m) (aref subs level))
20759 (push (cons head (aref subs (1+ level))) (aref subs level))
20760 (loop for i from (1+ level) to n do (aset subs i nil)))
20761 (setq last-level level)))))
20762 (aref subs 1)))
20764 (eval-after-load "imenu"
20765 '(progn
20766 (add-hook 'imenu-after-jump-hook
20767 (lambda ()
20768 (if (eq major-mode 'org-mode)
20769 (org-show-context 'org-goto))))))
20771 (defun org-link-display-format (link)
20772 "Replace a link with either the description, or the link target
20773 if no description is present"
20774 (save-match-data
20775 (if (string-match org-bracket-link-analytic-regexp link)
20776 (replace-match (if (match-end 5)
20777 (match-string 5 link)
20778 (concat (match-string 1 link)
20779 (match-string 3 link)))
20780 nil t link)
20781 link)))
20783 (defun org-toggle-link-display ()
20784 "Toggle the literal or descriptive display of links."
20785 (interactive)
20786 (if org-descriptive-links
20787 (progn (org-remove-from-invisibility-spec '(org-link))
20788 (org-restart-font-lock)
20789 (setq org-descriptive-links nil))
20790 (progn (add-to-invisibility-spec '(org-link))
20791 (org-restart-font-lock)
20792 (setq org-descriptive-links t))))
20794 ;; Speedbar support
20796 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
20797 "Overlay marking the agenda restriction line in speedbar.")
20798 (overlay-put org-speedbar-restriction-lock-overlay
20799 'face 'org-agenda-restriction-lock)
20800 (overlay-put org-speedbar-restriction-lock-overlay
20801 'help-echo "Agendas are currently limited to this item.")
20802 (org-detach-overlay org-speedbar-restriction-lock-overlay)
20804 (defun org-speedbar-set-agenda-restriction ()
20805 "Restrict future agenda commands to the location at point in speedbar.
20806 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
20807 (interactive)
20808 (require 'org-agenda)
20809 (let (p m tp np dir txt)
20810 (cond
20811 ((setq p (text-property-any (point-at-bol) (point-at-eol)
20812 'org-imenu t))
20813 (setq m (get-text-property p 'org-imenu-marker))
20814 (with-current-buffer (marker-buffer m)
20815 (goto-char m)
20816 (org-agenda-set-restriction-lock 'subtree)))
20817 ((setq p (text-property-any (point-at-bol) (point-at-eol)
20818 'speedbar-function 'speedbar-find-file))
20819 (setq tp (previous-single-property-change
20820 (1+ p) 'speedbar-function)
20821 np (next-single-property-change
20822 tp 'speedbar-function)
20823 dir (speedbar-line-directory)
20824 txt (buffer-substring-no-properties (or tp (point-min))
20825 (or np (point-max))))
20826 (with-current-buffer (find-file-noselect
20827 (let ((default-directory dir))
20828 (expand-file-name txt)))
20829 (unless (eq major-mode 'org-mode)
20830 (error "Cannot restrict to non-Org-mode file"))
20831 (org-agenda-set-restriction-lock 'file)))
20832 (t (error "Don't know how to restrict Org-mode's agenda")))
20833 (move-overlay org-speedbar-restriction-lock-overlay
20834 (point-at-bol) (point-at-eol))
20835 (setq current-prefix-arg nil)
20836 (org-agenda-maybe-redo)))
20838 (eval-after-load "speedbar"
20839 '(progn
20840 (speedbar-add-supported-extension ".org")
20841 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
20842 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
20843 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
20844 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
20845 (add-hook 'speedbar-visiting-tag-hook
20846 (lambda () (and (eq major-mode 'org-mode) (org-show-context 'org-goto))))))
20848 ;;; Fixes and Hacks for problems with other packages
20850 ;; Make flyspell not check words in links, to not mess up our keymap
20851 (defun org-mode-flyspell-verify ()
20852 "Don't let flyspell put overlays at active buttons, or on
20853 {todo,all-time,additional-option-like}-keywords."
20854 (let ((pos (max (1- (point)) (point-min)))
20855 (word (thing-at-point 'word)))
20856 (and (not (get-text-property pos 'keymap))
20857 (not (get-text-property pos 'org-no-flyspell))
20858 (not (member word org-todo-keywords-1))
20859 (not (member word org-all-time-keywords))
20860 (not (member word org-additional-option-like-keywords)))))
20862 (defun org-remove-flyspell-overlays-in (beg end)
20863 "Remove flyspell overlays in region."
20864 (and (org-bound-and-true-p flyspell-mode)
20865 (fboundp 'flyspell-delete-region-overlays)
20866 (flyspell-delete-region-overlays beg end))
20867 (add-text-properties beg end '(org-no-flyspell t)))
20869 ;; Make `bookmark-jump' shows the jump location if it was hidden.
20870 (eval-after-load "bookmark"
20871 '(if (boundp 'bookmark-after-jump-hook)
20872 ;; We can use the hook
20873 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
20874 ;; Hook not available, use advice
20875 (defadvice bookmark-jump (after org-make-visible activate)
20876 "Make the position visible."
20877 (org-bookmark-jump-unhide))))
20879 ;; Make sure saveplace shows the location if it was hidden
20880 (eval-after-load "saveplace"
20881 '(defadvice save-place-find-file-hook (after org-make-visible activate)
20882 "Make the position visible."
20883 (org-bookmark-jump-unhide)))
20885 ;; Make sure ecb shows the location if it was hidden
20886 (eval-after-load "ecb"
20887 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
20888 "Make hierarchy visible when jumping into location from ECB tree buffer."
20889 (if (eq major-mode 'org-mode)
20890 (org-show-context))))
20892 (defun org-bookmark-jump-unhide ()
20893 "Unhide the current position, to show the bookmark location."
20894 (and (eq major-mode 'org-mode)
20895 (or (outline-invisible-p)
20896 (save-excursion (goto-char (max (point-min) (1- (point))))
20897 (outline-invisible-p)))
20898 (org-show-context 'bookmark-jump)))
20900 ;; Make session.el ignore our circular variable
20901 (eval-after-load "session"
20902 '(add-to-list 'session-globals-exclude 'org-mark-ring))
20904 ;;;; Experimental code
20906 (defun org-closed-in-range ()
20907 "Sparse tree of items closed in a certain time range.
20908 Still experimental, may disappear in the future."
20909 (interactive)
20910 ;; Get the time interval from the user.
20911 (let* ((time1 (org-float-time
20912 (org-read-date nil 'to-time nil "Starting date: ")))
20913 (time2 (org-float-time
20914 (org-read-date nil 'to-time nil "End date:")))
20915 ;; callback function
20916 (callback (lambda ()
20917 (let ((time
20918 (org-float-time
20919 (apply 'encode-time
20920 (org-parse-time-string
20921 (match-string 1))))))
20922 ;; check if time in interval
20923 (and (>= time time1) (<= time time2))))))
20924 ;; make tree, check each match with the callback
20925 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
20927 ;;;; Finish up
20929 (provide 'org)
20931 (run-hooks 'org-load-hook)
20933 ;;; org.el ends here