Correctly fontify headlines with special keywords
[org-mode/org-tableheadings.git] / lisp / org.el
blob92ced781955a3def3a24c3d9905ee72dff2a9893
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-catch-invisible-edits nil
1069 "Check if in invisible region before inserting or deleting a character.
1070 Valid values are:
1072 nil Do not check, so just do invisible edits.
1073 error Throw an error and do nothing.
1074 show Make point visible, and do the requested edit.
1075 show-and-error Make point visible, then throw an error and abort the edit.
1076 smart Make point visible, and do insertion/deletion if it is
1077 adjacent to visible text and the change feels predictable.
1078 Never delete a previously invisible character or add in the
1079 middle or right after an invisible region. Basically, this
1080 allows insertion and backward-delete right before ellipses.
1081 FIXME: maybe in this case we should not even show?"
1082 :group 'org-edit-structure
1083 :type '(choice
1084 (const :tag "Do not check" nil)
1085 (const :tag "Throw error when trying to edit" error)
1086 (const :tag "Unhide, but do not do the edit" show-and-error)
1087 (const :tag "Show invisible part and do the edit" show)
1088 (const :tag "Be smart and do the right thing" smart)))
1090 (defcustom org-yank-folded-subtrees t
1091 "Non-nil means when yanking subtrees, fold them.
1092 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1093 it starts with a heading and all other headings in it are either children
1094 or siblings, then fold all the subtrees. However, do this only if no
1095 text after the yank would be swallowed into a folded tree by this action."
1096 :group 'org-edit-structure
1097 :type 'boolean)
1099 (defcustom org-yank-adjusted-subtrees nil
1100 "Non-nil means when yanking subtrees, adjust the level.
1101 With this setting, `org-paste-subtree' is used to insert the subtree, see
1102 this function for details."
1103 :group 'org-edit-structure
1104 :type 'boolean)
1106 (defcustom org-M-RET-may-split-line '((default . t))
1107 "Non-nil means M-RET will split the line at the cursor position.
1108 When nil, it will go to the end of the line before making a
1109 new line.
1110 You may also set this option in a different way for different
1111 contexts. Valid contexts are:
1113 headline when creating a new headline
1114 item when creating a new item
1115 table in a table field
1116 default the value to be used for all contexts not explicitly
1117 customized"
1118 :group 'org-structure
1119 :group 'org-table
1120 :type '(choice
1121 (const :tag "Always" t)
1122 (const :tag "Never" nil)
1123 (repeat :greedy t :tag "Individual contexts"
1124 (cons
1125 (choice :tag "Context"
1126 (const headline)
1127 (const item)
1128 (const table)
1129 (const default))
1130 (boolean)))))
1133 (defcustom org-insert-heading-respect-content nil
1134 "Non-nil means insert new headings after the current subtree.
1135 When nil, the new heading is created directly after the current line.
1136 The commands \\[org-insert-heading-respect-content] and
1137 \\[org-insert-todo-heading-respect-content] turn this variable on
1138 for the duration of the command."
1139 :group 'org-structure
1140 :type 'boolean)
1142 (defcustom org-blank-before-new-entry '((heading . auto)
1143 (plain-list-item . auto))
1144 "Should `org-insert-heading' leave a blank line before new heading/item?
1145 The value is an alist, with `heading' and `plain-list-item' as CAR,
1146 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1147 which case Org will look at the surrounding headings/items and try to
1148 make an intelligent decision whether to insert a blank line or not.
1150 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1151 set, the setting here is ignored and no empty line is inserted, to avoid
1152 breaking the list structure."
1153 :group 'org-edit-structure
1154 :type '(list
1155 (cons (const heading)
1156 (choice (const :tag "Never" nil)
1157 (const :tag "Always" t)
1158 (const :tag "Auto" auto)))
1159 (cons (const plain-list-item)
1160 (choice (const :tag "Never" nil)
1161 (const :tag "Always" t)
1162 (const :tag "Auto" auto)))))
1164 (defcustom org-insert-heading-hook nil
1165 "Hook being run after inserting a new heading."
1166 :group 'org-edit-structure
1167 :type 'hook)
1169 (defcustom org-enable-fixed-width-editor t
1170 "Non-nil means lines starting with \":\" are treated as fixed-width.
1171 This currently only means they are never auto-wrapped.
1172 When nil, such lines will be treated like ordinary lines.
1173 See also the QUOTE keyword."
1174 :group 'org-edit-structure
1175 :type 'boolean)
1177 (defcustom org-goto-auto-isearch t
1178 "Non-nil means typing characters in `org-goto' starts incremental search."
1179 :group 'org-edit-structure
1180 :type 'boolean)
1182 (defgroup org-sparse-trees nil
1183 "Options concerning sparse trees in Org-mode."
1184 :tag "Org Sparse Trees"
1185 :group 'org-structure)
1187 (defcustom org-highlight-sparse-tree-matches t
1188 "Non-nil means highlight all matches that define a sparse tree.
1189 The highlights will automatically disappear the next time the buffer is
1190 changed by an edit command."
1191 :group 'org-sparse-trees
1192 :type 'boolean)
1194 (defcustom org-remove-highlights-with-change t
1195 "Non-nil means any change to the buffer will remove temporary highlights.
1196 Such highlights are created by `org-occur' and `org-clock-display'.
1197 When nil, `C-c C-c needs to be used to get rid of the highlights.
1198 The highlights created by `org-preview-latex-fragment' always need
1199 `C-c C-c' to be removed."
1200 :group 'org-sparse-trees
1201 :group 'org-time
1202 :type 'boolean)
1205 (defcustom org-occur-hook '(org-first-headline-recenter)
1206 "Hook that is run after `org-occur' has constructed a sparse tree.
1207 This can be used to recenter the window to show as much of the structure
1208 as possible."
1209 :group 'org-sparse-trees
1210 :type 'hook)
1212 (defgroup org-imenu-and-speedbar nil
1213 "Options concerning imenu and speedbar in Org-mode."
1214 :tag "Org Imenu and Speedbar"
1215 :group 'org-structure)
1217 (defcustom org-imenu-depth 2
1218 "The maximum level for Imenu access to Org-mode headlines.
1219 This also applied for speedbar access."
1220 :group 'org-imenu-and-speedbar
1221 :type 'integer)
1223 (defgroup org-table nil
1224 "Options concerning tables in Org-mode."
1225 :tag "Org Table"
1226 :group 'org)
1228 (defcustom org-enable-table-editor 'optimized
1229 "Non-nil means lines starting with \"|\" are handled by the table editor.
1230 When nil, such lines will be treated like ordinary lines.
1232 When equal to the symbol `optimized', the table editor will be optimized to
1233 do the following:
1234 - Automatic overwrite mode in front of whitespace in table fields.
1235 This makes the structure of the table stay in tact as long as the edited
1236 field does not exceed the column width.
1237 - Minimize the number of realigns. Normally, the table is aligned each time
1238 TAB or RET are pressed to move to another field. With optimization this
1239 happens only if changes to a field might have changed the column width.
1240 Optimization requires replacing the functions `self-insert-command',
1241 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1242 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1243 very good at guessing when a re-align will be necessary, but you can always
1244 force one with \\[org-ctrl-c-ctrl-c].
1246 If you would like to use the optimized version in Org-mode, but the
1247 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1249 This variable can be used to turn on and off the table editor during a session,
1250 but in order to toggle optimization, a restart is required.
1252 See also the variable `org-table-auto-blank-field'."
1253 :group 'org-table
1254 :type '(choice
1255 (const :tag "off" nil)
1256 (const :tag "on" t)
1257 (const :tag "on, optimized" optimized)))
1259 (defcustom org-self-insert-cluster-for-undo t
1260 "Non-nil means cluster self-insert commands for undo when possible.
1261 If this is set, then, like in the Emacs command loop, 20 consecutive
1262 characters will be undone together.
1263 This is configurable, because there is some impact on typing performance."
1264 :group 'org-table
1265 :type 'boolean)
1267 (defcustom org-table-tab-recognizes-table.el t
1268 "Non-nil means TAB will automatically notice a table.el table.
1269 When it sees such a table, it moves point into it and - if necessary -
1270 calls `table-recognize-table'."
1271 :group 'org-table-editing
1272 :type 'boolean)
1274 (defgroup org-link nil
1275 "Options concerning links in Org-mode."
1276 :tag "Org Link"
1277 :group 'org)
1279 (defvar org-link-abbrev-alist-local nil
1280 "Buffer-local version of `org-link-abbrev-alist', which see.
1281 The value of this is taken from the #+LINK lines.")
1282 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1284 (defcustom org-link-abbrev-alist nil
1285 "Alist of link abbreviations.
1286 The car of each element is a string, to be replaced at the start of a link.
1287 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1288 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1290 [[linkkey:tag][description]]
1292 The 'linkkey' must be a word word, starting with a letter, followed
1293 by letters, numbers, '-' or '_'.
1295 If REPLACE is a string, the tag will simply be appended to create the link.
1296 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1297 the placeholder \"%h\" will cause a url-encoded version of the tag to
1298 be inserted at that point (see the function `url-hexify-string').
1300 REPLACE may also be a function that will be called with the tag as the
1301 only argument to create the link, which should be returned as a string.
1303 See the manual for examples."
1304 :group 'org-link
1305 :type '(repeat
1306 (cons
1307 (string :tag "Protocol")
1308 (choice
1309 (string :tag "Format")
1310 (function)))))
1312 (defcustom org-descriptive-links t
1313 "Non-nil means Org will display descriptive links.
1314 E.g. [[http://orgmode.org][Org website]] will be displayed as
1315 \"Org Website\", hiding the link itself and just displaying its
1316 description. When set to `nil', Org will display the full links
1317 literally.
1319 You can interactively set the value of this variable by calling
1320 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1321 :group 'org-link
1322 :type 'boolean)
1324 (defcustom org-link-file-path-type 'adaptive
1325 "How the path name in file links should be stored.
1326 Valid values are:
1328 relative Relative to the current directory, i.e. the directory of the file
1329 into which the link is being inserted.
1330 absolute Absolute path, if possible with ~ for home directory.
1331 noabbrev Absolute path, no abbreviation of home directory.
1332 adaptive Use relative path for files in the current directory and sub-
1333 directories of it. For other files, use an absolute path."
1334 :group 'org-link
1335 :type '(choice
1336 (const relative)
1337 (const absolute)
1338 (const noabbrev)
1339 (const adaptive)))
1341 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1342 "Types of links that should be activated in Org-mode files.
1343 This is a list of symbols, each leading to the activation of a certain link
1344 type. In principle, it does not hurt to turn on most link types - there may
1345 be a small gain when turning off unused link types. The types are:
1347 bracket The recommended [[link][description]] or [[link]] links with hiding.
1348 angle Links in angular brackets that may contain whitespace like
1349 <bbdb:Carsten Dominik>.
1350 plain Plain links in normal text, no whitespace, like http://google.com.
1351 radio Text that is matched by a radio target, see manual for details.
1352 tag Tag settings in a headline (link to tag search).
1353 date Time stamps (link to calendar).
1354 footnote Footnote labels.
1356 Changing this variable requires a restart of Emacs to become effective."
1357 :group 'org-link
1358 :type '(set :greedy t
1359 (const :tag "Double bracket links" bracket)
1360 (const :tag "Angular bracket links" angle)
1361 (const :tag "Plain text links" plain)
1362 (const :tag "Radio target matches" radio)
1363 (const :tag "Tags" tag)
1364 (const :tag "Timestamps" date)
1365 (const :tag "Footnotes" footnote)))
1367 (defcustom org-make-link-description-function nil
1368 "Function to use to generate link descriptions from links.
1369 If nil the link location will be used. This function must take
1370 two parameters; the first is the link and the second the
1371 description `org-insert-link' has generated, and should return the
1372 description to use."
1373 :group 'org-link
1374 :type 'function)
1376 (defgroup org-link-store nil
1377 "Options concerning storing links in Org-mode."
1378 :tag "Org Store Link"
1379 :group 'org-link)
1381 (defcustom org-email-link-description-format "Email %c: %.30s"
1382 "Format of the description part of a link to an email or usenet message.
1383 The following %-escapes will be replaced by corresponding information:
1385 %F full \"From\" field
1386 %f name, taken from \"From\" field, address if no name
1387 %T full \"To\" field
1388 %t first name in \"To\" field, address if no name
1389 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1390 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1391 %s subject
1392 %d date
1393 %m message-id.
1395 You may use normal field width specification between the % and the letter.
1396 This is for example useful to limit the length of the subject.
1398 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1399 :group 'org-link-store
1400 :type 'string)
1402 (defcustom org-from-is-user-regexp
1403 (let (r1 r2)
1404 (when (and user-mail-address (not (string= user-mail-address "")))
1405 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1406 (when (and user-full-name (not (string= user-full-name "")))
1407 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1408 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1409 "Regexp matched against the \"From:\" header of an email or usenet message.
1410 It should match if the message is from the user him/herself."
1411 :group 'org-link-store
1412 :type 'regexp)
1414 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1415 "Non-nil means storing a link to an Org file will use entry IDs.
1417 Note that before this variable is even considered, org-id must be loaded,
1418 so please customize `org-modules' and turn it on.
1420 The variable can have the following values:
1422 t Create an ID if needed to make a link to the current entry.
1424 create-if-interactive
1425 If `org-store-link' is called directly (interactively, as a user
1426 command), do create an ID to support the link. But when doing the
1427 job for remember, only use the ID if it already exists. The
1428 purpose of this setting is to avoid proliferation of unwanted
1429 IDs, just because you happen to be in an Org file when you
1430 call `org-remember' that automatically and preemptively
1431 creates a link. If you do want to get an ID link in a remember
1432 template to an entry not having an ID, create it first by
1433 explicitly creating a link to it, using `C-c C-l' first.
1435 create-if-interactive-and-no-custom-id
1436 Like create-if-interactive, but do not create an ID if there is
1437 a CUSTOM_ID property defined in the entry. This is the default.
1439 use-existing
1440 Use existing ID, do not create one.
1442 nil Never use an ID to make a link, instead link using a text search for
1443 the headline text."
1444 :group 'org-link-store
1445 :type '(choice
1446 (const :tag "Create ID to make link" t)
1447 (const :tag "Create if storing link interactively"
1448 create-if-interactive)
1449 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1450 create-if-interactive-and-no-custom-id)
1451 (const :tag "Only use existing" use-existing)
1452 (const :tag "Do not use ID to create link" nil)))
1454 (defcustom org-context-in-file-links t
1455 "Non-nil means file links from `org-store-link' contain context.
1456 A search string will be added to the file name with :: as separator and
1457 used to find the context when the link is activated by the command
1458 `org-open-at-point'. When this option is t, the entire active region
1459 will be placed in the search string of the file link. If set to a
1460 positive integer, only the first n lines of context will be stored.
1462 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1463 negates this setting for the duration of the command."
1464 :group 'org-link-store
1465 :type '(choice boolean integer))
1467 (defcustom org-keep-stored-link-after-insertion nil
1468 "Non-nil means keep link in list for entire session.
1470 The command `org-store-link' adds a link pointing to the current
1471 location to an internal list. These links accumulate during a session.
1472 The command `org-insert-link' can be used to insert links into any
1473 Org-mode file (offering completion for all stored links). When this
1474 option is nil, every link which has been inserted once using \\[org-insert-link]
1475 will be removed from the list, to make completing the unused links
1476 more efficient."
1477 :group 'org-link-store
1478 :type 'boolean)
1480 (defgroup org-link-follow nil
1481 "Options concerning following links in Org-mode."
1482 :tag "Org Follow Link"
1483 :group 'org-link)
1485 (defcustom org-link-translation-function nil
1486 "Function to translate links with different syntax to Org syntax.
1487 This can be used to translate links created for example by the Planner
1488 or emacs-wiki packages to Org syntax.
1489 The function must accept two parameters, a TYPE containing the link
1490 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1491 which is everything after the link protocol. It should return a cons
1492 with possibly modified values of type and path.
1493 Org contains a function for this, so if you set this variable to
1494 `org-translate-link-from-planner', you should be able follow many
1495 links created by planner."
1496 :group 'org-link-follow
1497 :type 'function)
1499 (defcustom org-follow-link-hook nil
1500 "Hook that is run after a link has been followed."
1501 :group 'org-link-follow
1502 :type 'hook)
1504 (defcustom org-tab-follows-link nil
1505 "Non-nil means on links TAB will follow the link.
1506 Needs to be set before org.el is loaded.
1507 This really should not be used, it does not make sense, and the
1508 implementation is bad."
1509 :group 'org-link-follow
1510 :type 'boolean)
1512 (defcustom org-return-follows-link nil
1513 "Non-nil means on links RET will follow the link."
1514 :group 'org-link-follow
1515 :type 'boolean)
1517 (defcustom org-mouse-1-follows-link
1518 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1519 "Non-nil means mouse-1 on a link will follow the link.
1520 A longer mouse click will still set point. Does not work on XEmacs.
1521 Needs to be set before org.el is loaded."
1522 :group 'org-link-follow
1523 :type 'boolean)
1525 (defcustom org-mark-ring-length 4
1526 "Number of different positions to be recorded in the ring.
1527 Changing this requires a restart of Emacs to work correctly."
1528 :group 'org-link-follow
1529 :type 'integer)
1531 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1532 "Non-nil means internal links in Org files must exactly match a headline.
1533 When nil, the link search tries to match a phrase with all words
1534 in the search text."
1535 :group 'org-link-follow
1536 :type '(choice
1537 (const :tag "Use fuzzy text search" nil)
1538 (const :tag "Match only exact headline" t)
1539 (const :tag "Match exact headline or query to create it"
1540 query-to-create)))
1542 (defcustom org-link-frame-setup
1543 '((vm . vm-visit-folder-other-frame)
1544 (gnus . org-gnus-no-new-news)
1545 (file . find-file-other-window)
1546 (wl . wl-other-frame))
1547 "Setup the frame configuration for following links.
1548 When following a link with Emacs, it may often be useful to display
1549 this link in another window or frame. This variable can be used to
1550 set this up for the different types of links.
1551 For VM, use any of
1552 `vm-visit-folder'
1553 `vm-visit-folder-other-window'
1554 `vm-visit-folder-other-frame'
1555 For Gnus, use any of
1556 `gnus'
1557 `gnus-other-frame'
1558 `org-gnus-no-new-news'
1559 For FILE, use any of
1560 `find-file'
1561 `find-file-other-window'
1562 `find-file-other-frame'
1563 For Wanderlust use any of
1564 `wl'
1565 `wl-other-frame'
1566 For the calendar, use the variable `calendar-setup'.
1567 For BBDB, it is currently only possible to display the matches in
1568 another window."
1569 :group 'org-link-follow
1570 :type '(list
1571 (cons (const vm)
1572 (choice
1573 (const vm-visit-folder)
1574 (const vm-visit-folder-other-window)
1575 (const vm-visit-folder-other-frame)))
1576 (cons (const gnus)
1577 (choice
1578 (const gnus)
1579 (const gnus-other-frame)
1580 (const org-gnus-no-new-news)))
1581 (cons (const file)
1582 (choice
1583 (const find-file)
1584 (const find-file-other-window)
1585 (const find-file-other-frame)))
1586 (cons (const wl)
1587 (choice
1588 (const wl)
1589 (const wl-other-frame)))))
1591 (defcustom org-display-internal-link-with-indirect-buffer nil
1592 "Non-nil means use indirect buffer to display infile links.
1593 Activating internal links (from one location in a file to another location
1594 in the same file) normally just jumps to the location. When the link is
1595 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1596 is displayed in
1597 another window. When this option is set, the other window actually displays
1598 an indirect buffer clone of the current buffer, to avoid any visibility
1599 changes to the current buffer."
1600 :group 'org-link-follow
1601 :type 'boolean)
1603 (defcustom org-open-non-existing-files nil
1604 "Non-nil means `org-open-file' will open non-existing files.
1605 When nil, an error will be generated.
1606 This variable applies only to external applications because they
1607 might choke on non-existing files. If the link is to a file that
1608 will be opened in Emacs, the variable is ignored."
1609 :group 'org-link-follow
1610 :type 'boolean)
1612 (defcustom org-open-directory-means-index-dot-org nil
1613 "Non-nil means a link to a directory really means to index.org.
1614 When nil, following a directory link will run dired or open a finder/explorer
1615 window on that directory."
1616 :group 'org-link-follow
1617 :type 'boolean)
1619 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1620 "Function and arguments to call for following mailto links.
1621 This is a list with the first element being a Lisp function, and the
1622 remaining elements being arguments to the function. In string arguments,
1623 %a will be replaced by the address, and %s will be replaced by the subject
1624 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1625 :group 'org-link-follow
1626 :type '(choice
1627 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1628 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1629 (const :tag "message-mail" (message-mail "%a" "%s"))
1630 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1632 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1633 "Non-nil means ask for confirmation before executing shell links.
1634 Shell links can be dangerous: just think about a link
1636 [[shell:rm -rf ~/*][Google Search]]
1638 This link would show up in your Org-mode document as \"Google Search\",
1639 but really it would remove your entire home directory.
1640 Therefore we advise against setting this variable to nil.
1641 Just change it to `y-or-n-p' if you want to confirm with a
1642 single keystroke rather than having to type \"yes\"."
1643 :group 'org-link-follow
1644 :type '(choice
1645 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1646 (const :tag "with y-or-n (faster)" y-or-n-p)
1647 (const :tag "no confirmation (dangerous)" nil)))
1648 (put 'org-confirm-shell-link-function
1649 'safe-local-variable
1650 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1652 (defcustom org-confirm-shell-link-not-regexp ""
1653 "A regexp to skip confirmation for shell links."
1654 :group 'org-link-follow
1655 :type 'regexp)
1657 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1658 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1659 Elisp links can be dangerous: just think about a link
1661 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1663 This link would show up in your Org-mode document as \"Google Search\",
1664 but really it would remove your entire home directory.
1665 Therefore we advise against setting this variable to nil.
1666 Just change it to `y-or-n-p' if you want to confirm with a
1667 single keystroke rather than having to type \"yes\"."
1668 :group 'org-link-follow
1669 :type '(choice
1670 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1671 (const :tag "with y-or-n (faster)" y-or-n-p)
1672 (const :tag "no confirmation (dangerous)" nil)))
1673 (put 'org-confirm-shell-link-function
1674 'safe-local-variable
1675 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1677 (defcustom org-confirm-elisp-link-not-regexp ""
1678 "A regexp to skip confirmation for Elisp links."
1679 :group 'org-link-follow
1680 :type 'regexp)
1682 (defconst org-file-apps-defaults-gnu
1683 '((remote . emacs)
1684 (system . mailcap)
1685 (t . mailcap))
1686 "Default file applications on a UNIX or GNU/Linux system.
1687 See `org-file-apps'.")
1689 (defconst org-file-apps-defaults-macosx
1690 '((remote . emacs)
1691 (t . "open %s")
1692 (system . "open %s")
1693 ("ps.gz" . "gv %s")
1694 ("eps.gz" . "gv %s")
1695 ("dvi" . "xdvi %s")
1696 ("fig" . "xfig %s"))
1697 "Default file applications on a MacOS X system.
1698 The system \"open\" is known as a default, but we use X11 applications
1699 for some files for which the OS does not have a good default.
1700 See `org-file-apps'.")
1702 (defconst org-file-apps-defaults-windowsnt
1703 (list
1704 '(remote . emacs)
1705 (cons t
1706 (list (if (featurep 'xemacs)
1707 'mswindows-shell-execute
1708 'w32-shell-execute)
1709 "open" 'file))
1710 (cons 'system
1711 (list (if (featurep 'xemacs)
1712 'mswindows-shell-execute
1713 'w32-shell-execute)
1714 "open" 'file)))
1715 "Default file applications on a Windows NT system.
1716 The system \"open\" is used for most files.
1717 See `org-file-apps'.")
1719 (defcustom org-file-apps
1721 (auto-mode . emacs)
1722 ("\\.mm\\'" . default)
1723 ("\\.x?html?\\'" . default)
1724 ("\\.pdf\\'" . default)
1726 "External applications for opening `file:path' items in a document.
1727 Org-mode uses system defaults for different file types, but
1728 you can use this variable to set the application for a given file
1729 extension. The entries in this list are cons cells where the car identifies
1730 files and the cdr the corresponding command. Possible values for the
1731 file identifier are
1732 \"string\" A string as a file identifier can be interpreted in different
1733 ways, depending on its contents:
1735 - Alphanumeric characters only:
1736 Match links with this file extension.
1737 Example: (\"pdf\" . \"evince %s\")
1738 to open PDFs with evince.
1740 - Regular expression: Match links where the
1741 filename matches the regexp. If you want to
1742 use groups here, use shy groups.
1744 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1745 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1746 to open *.html and *.xhtml with firefox.
1748 - Regular expression which contains (non-shy) groups:
1749 Match links where the whole link, including \"::\", and
1750 anything after that, matches the regexp.
1751 In a custom command string, %1, %2, etc. are replaced with
1752 the parts of the link that were matched by the groups.
1753 For backwards compatibility, if a command string is given
1754 that does not use any of the group matches, this case is
1755 handled identically to the second one (i.e. match against
1756 file name only).
1757 In a custom lisp form, you can access the group matches with
1758 (match-string n link).
1760 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1761 to open [[file:document.pdf::5]] with evince at page 5.
1763 `directory' Matches a directory
1764 `remote' Matches a remote file, accessible through tramp or efs.
1765 Remote files most likely should be visited through Emacs
1766 because external applications cannot handle such paths.
1767 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1768 so all files Emacs knows how to handle. Using this with
1769 command `emacs' will open most files in Emacs. Beware that this
1770 will also open html files inside Emacs, unless you add
1771 (\"html\" . default) to the list as well.
1772 t Default for files not matched by any of the other options.
1773 `system' The system command to open files, like `open' on Windows
1774 and Mac OS X, and mailcap under GNU/Linux. This is the command
1775 that will be selected if you call `C-c C-o' with a double
1776 \\[universal-argument] \\[universal-argument] prefix.
1778 Possible values for the command are:
1779 `emacs' The file will be visited by the current Emacs process.
1780 `default' Use the default application for this file type, which is the
1781 association for t in the list, most likely in the system-specific
1782 part.
1783 This can be used to overrule an unwanted setting in the
1784 system-specific variable.
1785 `system' Use the system command for opening files, like \"open\".
1786 This command is specified by the entry whose car is `system'.
1787 Most likely, the system-specific version of this variable
1788 does define this command, but you can overrule/replace it
1789 here.
1790 string A command to be executed by a shell; %s will be replaced
1791 by the path to the file.
1792 sexp A Lisp form which will be evaluated. The file path will
1793 be available in the Lisp variable `file'.
1794 For more examples, see the system specific constants
1795 `org-file-apps-defaults-macosx'
1796 `org-file-apps-defaults-windowsnt'
1797 `org-file-apps-defaults-gnu'."
1798 :group 'org-link-follow
1799 :type '(repeat
1800 (cons (choice :value ""
1801 (string :tag "Extension")
1802 (const :tag "System command to open files" system)
1803 (const :tag "Default for unrecognized files" t)
1804 (const :tag "Remote file" remote)
1805 (const :tag "Links to a directory" directory)
1806 (const :tag "Any files that have Emacs modes"
1807 auto-mode))
1808 (choice :value ""
1809 (const :tag "Visit with Emacs" emacs)
1810 (const :tag "Use default" default)
1811 (const :tag "Use the system command" system)
1812 (string :tag "Command")
1813 (sexp :tag "Lisp form")))))
1817 (defgroup org-refile nil
1818 "Options concerning refiling entries in Org-mode."
1819 :tag "Org Refile"
1820 :group 'org)
1822 (defcustom org-directory "~/org"
1823 "Directory with org files.
1824 This is just a default location to look for Org files. There is no need
1825 at all to put your files into this directory. It is only used in the
1826 following situations:
1828 1. When a remember template specifies a target file that is not an
1829 absolute path. The path will then be interpreted relative to
1830 `org-directory'
1831 2. When a remember note is filed away in an interactive way (when exiting the
1832 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1833 with `org-directory' as the default path."
1834 :group 'org-refile
1835 :group 'org-remember
1836 :type 'directory)
1838 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1839 "Default target for storing notes.
1840 Used as a fall back file for org-remember.el and org-capture.el, for
1841 templates that do not specify a target file."
1842 :group 'org-refile
1843 :group 'org-remember
1844 :type '(choice
1845 (const :tag "Default from remember-data-file" nil)
1846 file))
1848 (defcustom org-goto-interface 'outline
1849 "The default interface to be used for `org-goto'.
1850 Allowed values are:
1851 outline The interface shows an outline of the relevant file
1852 and the correct heading is found by moving through
1853 the outline or by searching with incremental search.
1854 outline-path-completion Headlines in the current buffer are offered via
1855 completion. This is the interface also used by
1856 the refile command."
1857 :group 'org-refile
1858 :type '(choice
1859 (const :tag "Outline" outline)
1860 (const :tag "Outline-path-completion" outline-path-completion)))
1862 (defcustom org-goto-max-level 5
1863 "Maximum target level when running `org-goto' with refile interface."
1864 :group 'org-refile
1865 :type 'integer)
1867 (defcustom org-reverse-note-order nil
1868 "Non-nil means store new notes at the beginning of a file or entry.
1869 When nil, new notes will be filed to the end of a file or entry.
1870 This can also be a list with cons cells of regular expressions that
1871 are matched against file names, and values."
1872 :group 'org-remember
1873 :group 'org-refile
1874 :type '(choice
1875 (const :tag "Reverse always" t)
1876 (const :tag "Reverse never" nil)
1877 (repeat :tag "By file name regexp"
1878 (cons regexp boolean))))
1880 (defcustom org-log-refile nil
1881 "Information to record when a task is refiled.
1883 Possible values are:
1885 nil Don't add anything
1886 time Add a time stamp to the task
1887 note Prompt for a note and add it with template `org-log-note-headings'
1889 This option can also be set with on a per-file-basis with
1891 #+STARTUP: nologrefile
1892 #+STARTUP: logrefile
1893 #+STARTUP: lognoterefile
1895 You can have local logging settings for a subtree by setting the LOGGING
1896 property to one or more of these keywords.
1898 When bulk-refiling from the agenda, the value `note' is forbidden and
1899 will temporarily be changed to `time'."
1900 :group 'org-refile
1901 :group 'org-progress
1902 :type '(choice
1903 (const :tag "No logging" nil)
1904 (const :tag "Record timestamp" time)
1905 (const :tag "Record timestamp with note." note)))
1907 (defcustom org-refile-targets nil
1908 "Targets for refiling entries with \\[org-refile].
1909 This is a list of cons cells. Each cell contains:
1910 - a specification of the files to be considered, either a list of files,
1911 or a symbol whose function or variable value will be used to retrieve
1912 a file name or a list of file names. If you use `org-agenda-files' for
1913 that, all agenda files will be scanned for targets. Nil means consider
1914 headings in the current buffer.
1915 - A specification of how to find candidate refile targets. This may be
1916 any of:
1917 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1918 This tag has to be present in all target headlines, inheritance will
1919 not be considered.
1920 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1921 todo keyword.
1922 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1923 headlines that are refiling targets.
1924 - a cons cell (:level . N). Any headline of level N is considered a target.
1925 Note that, when `org-odd-levels-only' is set, level corresponds to
1926 order in hierarchy, not to the number of stars.
1927 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1928 Note that, when `org-odd-levels-only' is set, level corresponds to
1929 order in hierarchy, not to the number of stars.
1931 Each element of this list generates a set of possible targets.
1932 The union of these sets is presented (with completion) to
1933 the user by `org-refile'.
1935 You can set the variable `org-refile-target-verify-function' to a function
1936 to verify each headline found by the simple criteria above.
1938 When this variable is nil, all top-level headlines in the current buffer
1939 are used, equivalent to the value `((nil . (:level . 1))'."
1940 :group 'org-refile
1941 :type '(repeat
1942 (cons
1943 (choice :value org-agenda-files
1944 (const :tag "All agenda files" org-agenda-files)
1945 (const :tag "Current buffer" nil)
1946 (function) (variable) (file))
1947 (choice :tag "Identify target headline by"
1948 (cons :tag "Specific tag" (const :value :tag) (string))
1949 (cons :tag "TODO keyword" (const :value :todo) (string))
1950 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1951 (cons :tag "Level number" (const :value :level) (integer))
1952 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1954 (defcustom org-refile-target-verify-function nil
1955 "Function to verify if the headline at point should be a refile target.
1956 The function will be called without arguments, with point at the
1957 beginning of the headline. It should return t and leave point
1958 where it is if the headline is a valid target for refiling.
1960 If the target should not be selected, the function must return nil.
1961 In addition to this, it may move point to a place from where the search
1962 should be continued. For example, the function may decide that the entire
1963 subtree of the current entry should be excluded and move point to the end
1964 of the subtree."
1965 :group 'org-refile
1966 :type 'function)
1968 (defcustom org-refile-use-cache nil
1969 "Non-nil means cache refile targets to speed up the process.
1970 The cache for a particular file will be updated automatically when
1971 the buffer has been killed, or when any of the marker used for flagging
1972 refile targets no longer points at a live buffer.
1973 If you have added new entries to a buffer that might themselves be targets,
1974 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
1975 find that easier, `C-u C-u C-u C-c C-w'."
1976 :group 'org-refile
1977 :type 'boolean)
1979 (defcustom org-refile-use-outline-path nil
1980 "Non-nil means provide refile targets as paths.
1981 So a level 3 headline will be available as level1/level2/level3.
1983 When the value is `file', also include the file name (without directory)
1984 into the path. In this case, you can also stop the completion after
1985 the file name, to get entries inserted as top level in the file.
1987 When `full-file-path', include the full file path."
1988 :group 'org-refile
1989 :type '(choice
1990 (const :tag "Not" nil)
1991 (const :tag "Yes" t)
1992 (const :tag "Start with file name" file)
1993 (const :tag "Start with full file path" full-file-path)))
1995 (defcustom org-outline-path-complete-in-steps t
1996 "Non-nil means complete the outline path in hierarchical steps.
1997 When Org-mode uses the refile interface to select an outline path
1998 \(see variable `org-refile-use-outline-path'), the completion of
1999 the path can be done is a single go, or if can be done in steps down
2000 the headline hierarchy. Going in steps is probably the best if you
2001 do not use a special completion package like `ido' or `icicles'.
2002 However, when using these packages, going in one step can be very
2003 fast, while still showing the whole path to the entry."
2004 :group 'org-refile
2005 :type 'boolean)
2007 (defcustom org-refile-allow-creating-parent-nodes nil
2008 "Non-nil means allow to create new nodes as refile targets.
2009 New nodes are then created by adding \"/new node name\" to the completion
2010 of an existing node. When the value of this variable is `confirm',
2011 new node creation must be confirmed by the user (recommended)
2012 When nil, the completion must match an existing entry.
2014 Note that, if the new heading is not seen by the criteria
2015 listed in `org-refile-targets', multiple instances of the same
2016 heading would be created by trying again to file under the new
2017 heading."
2018 :group 'org-refile
2019 :type '(choice
2020 (const :tag "Never" nil)
2021 (const :tag "Always" t)
2022 (const :tag "Prompt for confirmation" confirm)))
2024 (defcustom org-refile-active-region-within-subtree nil
2025 "Non-nil means also refile active region within a subtree.
2027 By default `org-refile' doesn't allow refiling regions if they
2028 don't contain a set of subtrees, but it might be convenient to
2029 do so sometimes: in that case, the first line of the region is
2030 converted to a headline before refiling."
2031 :group 'org-refile
2032 :type 'boolean)
2034 (defgroup org-todo nil
2035 "Options concerning TODO items in Org-mode."
2036 :tag "Org TODO"
2037 :group 'org)
2039 (defgroup org-progress nil
2040 "Options concerning Progress logging in Org-mode."
2041 :tag "Org Progress"
2042 :group 'org-time)
2044 (defvar org-todo-interpretation-widgets
2045 '((:tag "Sequence (cycling hits every state)" sequence)
2046 (:tag "Type (cycling directly to DONE)" type))
2047 "The available interpretation symbols for customizing `org-todo-keywords'.
2048 Interested libraries should add to this list.")
2050 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2051 "List of TODO entry keyword sequences and their interpretation.
2052 \\<org-mode-map>This is a list of sequences.
2054 Each sequence starts with a symbol, either `sequence' or `type',
2055 indicating if the keywords should be interpreted as a sequence of
2056 action steps, or as different types of TODO items. The first
2057 keywords are states requiring action - these states will select a headline
2058 for inclusion into the global TODO list Org-mode produces. If one of
2059 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2060 signify that no further action is necessary. If \"|\" is not found,
2061 the last keyword is treated as the only DONE state of the sequence.
2063 The command \\[org-todo] cycles an entry through these states, and one
2064 additional state where no keyword is present. For details about this
2065 cycling, see the manual.
2067 TODO keywords and interpretation can also be set on a per-file basis with
2068 the special #+SEQ_TODO and #+TYP_TODO lines.
2070 Each keyword can optionally specify a character for fast state selection
2071 \(in combination with the variable `org-use-fast-todo-selection')
2072 and specifiers for state change logging, using the same syntax
2073 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
2074 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2075 indicates to record a time stamp each time this state is selected.
2077 Each keyword may also specify if a timestamp or a note should be
2078 recorded when entering or leaving the state, by adding additional
2079 characters in the parenthesis after the keyword. This looks like this:
2080 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2081 record only the time of the state change. With X and Y being either
2082 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2083 Y when leaving the state if and only if the *target* state does not
2084 define X. You may omit any of the fast-selection key or X or /Y,
2085 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2087 For backward compatibility, this variable may also be just a list
2088 of keywords - in this case the interpretation (sequence or type) will be
2089 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2090 :group 'org-todo
2091 :group 'org-keywords
2092 :type '(choice
2093 (repeat :tag "Old syntax, just keywords"
2094 (string :tag "Keyword"))
2095 (repeat :tag "New syntax"
2096 (cons
2097 (choice
2098 :tag "Interpretation"
2099 ;;Quick and dirty way to see
2100 ;;`org-todo-interpretations'. This takes the
2101 ;;place of item arguments
2102 :convert-widget
2103 (lambda (widget)
2104 (widget-put widget
2105 :args (mapcar
2106 #'(lambda (x)
2107 (widget-convert
2108 (cons 'const x)))
2109 org-todo-interpretation-widgets))
2110 widget))
2111 (repeat
2112 (string :tag "Keyword"))))))
2114 (defvar org-todo-keywords-1 nil
2115 "All TODO and DONE keywords active in a buffer.")
2116 (make-variable-buffer-local 'org-todo-keywords-1)
2117 (defvar org-todo-keywords-for-agenda nil)
2118 (defvar org-done-keywords-for-agenda nil)
2119 (defvar org-drawers-for-agenda nil)
2120 (defvar org-todo-keyword-alist-for-agenda nil)
2121 (defvar org-tag-alist-for-agenda nil)
2122 (defvar org-agenda-contributing-files nil)
2123 (defvar org-not-done-keywords nil)
2124 (make-variable-buffer-local 'org-not-done-keywords)
2125 (defvar org-done-keywords nil)
2126 (make-variable-buffer-local 'org-done-keywords)
2127 (defvar org-todo-heads nil)
2128 (make-variable-buffer-local 'org-todo-heads)
2129 (defvar org-todo-sets nil)
2130 (make-variable-buffer-local 'org-todo-sets)
2131 (defvar org-todo-log-states nil)
2132 (make-variable-buffer-local 'org-todo-log-states)
2133 (defvar org-todo-kwd-alist nil)
2134 (make-variable-buffer-local 'org-todo-kwd-alist)
2135 (defvar org-todo-key-alist nil)
2136 (make-variable-buffer-local 'org-todo-key-alist)
2137 (defvar org-todo-key-trigger nil)
2138 (make-variable-buffer-local 'org-todo-key-trigger)
2140 (defcustom org-todo-interpretation 'sequence
2141 "Controls how TODO keywords are interpreted.
2142 This variable is in principle obsolete and is only used for
2143 backward compatibility, if the interpretation of todo keywords is
2144 not given already in `org-todo-keywords'. See that variable for
2145 more information."
2146 :group 'org-todo
2147 :group 'org-keywords
2148 :type '(choice (const sequence)
2149 (const type)))
2151 (defcustom org-use-fast-todo-selection t
2152 "Non-nil means use the fast todo selection scheme with C-c C-t.
2153 This variable describes if and under what circumstances the cycling
2154 mechanism for TODO keywords will be replaced by a single-key, direct
2155 selection scheme.
2157 When nil, fast selection is never used.
2159 When the symbol `prefix', it will be used when `org-todo' is called with
2160 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
2161 in an agenda buffer.
2163 When t, fast selection is used by default. In this case, the prefix
2164 argument forces cycling instead.
2166 In all cases, the special interface is only used if access keys have actually
2167 been assigned by the user, i.e. if keywords in the configuration are followed
2168 by a letter in parenthesis, like TODO(t)."
2169 :group 'org-todo
2170 :type '(choice
2171 (const :tag "Never" nil)
2172 (const :tag "By default" t)
2173 (const :tag "Only with C-u C-c C-t" prefix)))
2175 (defcustom org-provide-todo-statistics t
2176 "Non-nil means update todo statistics after insert and toggle.
2177 ALL-HEADLINES means update todo statistics by including headlines
2178 with no TODO keyword as well, counting them as not done.
2179 A list of TODO keywords means the same, but skip keywords that are
2180 not in this list.
2182 When this is set, todo statistics is updated in the parent of the
2183 current entry each time a todo state is changed."
2184 :group 'org-todo
2185 :type '(choice
2186 (const :tag "Yes, only for TODO entries" t)
2187 (const :tag "Yes, including all entries" 'all-headlines)
2188 (repeat :tag "Yes, for TODOs in this list"
2189 (string :tag "TODO keyword"))
2190 (other :tag "No TODO statistics" nil)))
2192 (defcustom org-hierarchical-todo-statistics t
2193 "Non-nil means TODO statistics covers just direct children.
2194 When nil, all entries in the subtree are considered.
2195 This has only an effect if `org-provide-todo-statistics' is set.
2196 To set this to nil for only a single subtree, use a COOKIE_DATA
2197 property and include the word \"recursive\" into the value."
2198 :group 'org-todo
2199 :type 'boolean)
2201 (defcustom org-after-todo-state-change-hook nil
2202 "Hook which is run after the state of a TODO item was changed.
2203 The new state (a string with a TODO keyword, or nil) is available in the
2204 Lisp variable `state'."
2205 :group 'org-todo
2206 :type 'hook)
2208 (defvar org-blocker-hook nil
2209 "Hook for functions that are allowed to block a state change.
2211 Each function gets as its single argument a property list, see
2212 `org-trigger-hook' for more information about this list.
2214 If any of the functions in this hook returns nil, the state change
2215 is blocked.")
2217 (defvar org-trigger-hook nil
2218 "Hook for functions that are triggered by a state change.
2220 Each function gets as its single argument a property list with at least
2221 the following elements:
2223 (:type type-of-change :position pos-at-entry-start
2224 :from old-state :to new-state)
2226 Depending on the type, more properties may be present.
2228 This mechanism is currently implemented for:
2230 TODO state changes
2231 ------------------
2232 :type todo-state-change
2233 :from previous state (keyword as a string), or nil, or a symbol
2234 'todo' or 'done', to indicate the general type of state.
2235 :to new state, like in :from")
2237 (defcustom org-enforce-todo-dependencies nil
2238 "Non-nil means undone TODO entries will block switching the parent to DONE.
2239 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2240 be blocked if any prior sibling is not yet done.
2241 Finally, if the parent is blocked because of ordered siblings of its own,
2242 the child will also be blocked.
2243 This variable needs to be set before org.el is loaded, and you need to
2244 restart Emacs after a change to make the change effective. The only way
2245 to change is while Emacs is running is through the customize interface."
2246 :set (lambda (var val)
2247 (set var val)
2248 (if val
2249 (add-hook 'org-blocker-hook
2250 'org-block-todo-from-children-or-siblings-or-parent)
2251 (remove-hook 'org-blocker-hook
2252 'org-block-todo-from-children-or-siblings-or-parent)))
2253 :group 'org-todo
2254 :type 'boolean)
2256 (defcustom org-enforce-todo-checkbox-dependencies nil
2257 "Non-nil means unchecked boxes will block switching the parent to DONE.
2258 When this is nil, checkboxes have no influence on switching TODO states.
2259 When non-nil, you first need to check off all check boxes before the TODO
2260 entry can be switched to DONE.
2261 This variable needs to be set before org.el is loaded, and you need to
2262 restart Emacs after a change to make the change effective. The only way
2263 to change is while Emacs is running is through the customize interface."
2264 :set (lambda (var val)
2265 (set var val)
2266 (if val
2267 (add-hook 'org-blocker-hook
2268 'org-block-todo-from-checkboxes)
2269 (remove-hook 'org-blocker-hook
2270 'org-block-todo-from-checkboxes)))
2271 :group 'org-todo
2272 :type 'boolean)
2274 (defcustom org-treat-insert-todo-heading-as-state-change nil
2275 "Non-nil means inserting a TODO heading is treated as state change.
2276 So when the command \\[org-insert-todo-heading] is used, state change
2277 logging will apply if appropriate. When nil, the new TODO item will
2278 be inserted directly, and no logging will take place."
2279 :group 'org-todo
2280 :type 'boolean)
2282 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2283 "Non-nil means switching TODO states with S-cursor counts as state change.
2284 This is the default behavior. However, setting this to nil allows a
2285 convenient way to select a TODO state and bypass any logging associated
2286 with that."
2287 :group 'org-todo
2288 :type 'boolean)
2290 (defcustom org-todo-state-tags-triggers nil
2291 "Tag changes that should be triggered by TODO state changes.
2292 This is a list. Each entry is
2294 (state-change (tag . flag) .......)
2296 State-change can be a string with a state, and empty string to indicate the
2297 state that has no TODO keyword, or it can be one of the symbols `todo'
2298 or `done', meaning any not-done or done state, respectively."
2299 :group 'org-todo
2300 :group 'org-tags
2301 :type '(repeat
2302 (cons (choice :tag "When changing to"
2303 (const :tag "Not-done state" todo)
2304 (const :tag "Done state" done)
2305 (string :tag "State"))
2306 (repeat
2307 (cons :tag "Tag action"
2308 (string :tag "Tag")
2309 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2311 (defcustom org-log-done nil
2312 "Information to record when a task moves to the DONE state.
2314 Possible values are:
2316 nil Don't add anything, just change the keyword
2317 time Add a time stamp to the task
2318 note Prompt for a note and add it with template `org-log-note-headings'
2320 This option can also be set with on a per-file-basis with
2322 #+STARTUP: nologdone
2323 #+STARTUP: logdone
2324 #+STARTUP: lognotedone
2326 You can have local logging settings for a subtree by setting the LOGGING
2327 property to one or more of these keywords."
2328 :group 'org-todo
2329 :group 'org-progress
2330 :type '(choice
2331 (const :tag "No logging" nil)
2332 (const :tag "Record CLOSED timestamp" time)
2333 (const :tag "Record CLOSED timestamp with note." note)))
2335 ;; Normalize old uses of org-log-done.
2336 (cond
2337 ((eq org-log-done t) (setq org-log-done 'time))
2338 ((and (listp org-log-done) (memq 'done org-log-done))
2339 (setq org-log-done 'note)))
2341 (defcustom org-log-reschedule nil
2342 "Information to record when the scheduling date of a tasks is modified.
2344 Possible values are:
2346 nil Don't add anything, just change the date
2347 time Add a time stamp to the task
2348 note Prompt for a note and add it with template `org-log-note-headings'
2350 This option can also be set with on a per-file-basis with
2352 #+STARTUP: nologreschedule
2353 #+STARTUP: logreschedule
2354 #+STARTUP: lognotereschedule"
2355 :group 'org-todo
2356 :group 'org-progress
2357 :type '(choice
2358 (const :tag "No logging" nil)
2359 (const :tag "Record timestamp" time)
2360 (const :tag "Record timestamp with note." note)))
2362 (defcustom org-log-redeadline nil
2363 "Information to record when the deadline date of a tasks is modified.
2365 Possible values are:
2367 nil Don't add anything, just change the date
2368 time Add a time stamp to the task
2369 note Prompt for a note and add it with template `org-log-note-headings'
2371 This option can also be set with on a per-file-basis with
2373 #+STARTUP: nologredeadline
2374 #+STARTUP: logredeadline
2375 #+STARTUP: lognoteredeadline
2377 You can have local logging settings for a subtree by setting the LOGGING
2378 property to one or more of these keywords."
2379 :group 'org-todo
2380 :group 'org-progress
2381 :type '(choice
2382 (const :tag "No logging" nil)
2383 (const :tag "Record timestamp" time)
2384 (const :tag "Record timestamp with note." note)))
2386 (defcustom org-log-note-clock-out nil
2387 "Non-nil means record a note when clocking out of an item.
2388 This can also be configured on a per-file basis by adding one of
2389 the following lines anywhere in the buffer:
2391 #+STARTUP: lognoteclock-out
2392 #+STARTUP: nolognoteclock-out"
2393 :group 'org-todo
2394 :group 'org-progress
2395 :type 'boolean)
2397 (defcustom org-log-done-with-time t
2398 "Non-nil means the CLOSED time stamp will contain date and time.
2399 When nil, only the date will be recorded."
2400 :group 'org-progress
2401 :type 'boolean)
2403 (defcustom org-log-note-headings
2404 '((done . "CLOSING NOTE %t")
2405 (state . "State %-12s from %-12S %t")
2406 (note . "Note taken on %t")
2407 (reschedule . "Rescheduled from %S on %t")
2408 (delschedule . "Not scheduled, was %S on %t")
2409 (redeadline . "New deadline from %S on %t")
2410 (deldeadline . "Removed deadline, was %S on %t")
2411 (refile . "Refiled on %t")
2412 (clock-out . ""))
2413 "Headings for notes added to entries.
2414 The value is an alist, with the car being a symbol indicating the note
2415 context, and the cdr is the heading to be used. The heading may also be the
2416 empty string.
2417 %t in the heading will be replaced by a time stamp.
2418 %T will be an active time stamp instead the default inactive one
2419 %d will be replaced by a short-format time stamp.
2420 %D will be replaced by an active short-format time stamp.
2421 %s will be replaced by the new TODO state, in double quotes.
2422 %S will be replaced by the old TODO state, in double quotes.
2423 %u will be replaced by the user name.
2424 %U will be replaced by the full user name.
2426 In fact, it is not a good idea to change the `state' entry, because
2427 agenda log mode depends on the format of these entries."
2428 :group 'org-todo
2429 :group 'org-progress
2430 :type '(list :greedy t
2431 (cons (const :tag "Heading when closing an item" done) string)
2432 (cons (const :tag
2433 "Heading when changing todo state (todo sequence only)"
2434 state) string)
2435 (cons (const :tag "Heading when just taking a note" note) string)
2436 (cons (const :tag "Heading when clocking out" clock-out) string)
2437 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2438 (cons (const :tag "Heading when rescheduling" reschedule) string)
2439 (cons (const :tag "Heading when changing deadline" redeadline) string)
2440 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2441 (cons (const :tag "Heading when refiling" refile) string)))
2443 (unless (assq 'note org-log-note-headings)
2444 (push '(note . "%t") org-log-note-headings))
2446 (defcustom org-log-into-drawer nil
2447 "Non-nil means insert state change notes and time stamps into a drawer.
2448 When nil, state changes notes will be inserted after the headline and
2449 any scheduling and clock lines, but not inside a drawer.
2451 The value of this variable should be the name of the drawer to use.
2452 LOGBOOK is proposed as the default drawer for this purpose, you can
2453 also set this to a string to define the drawer of your choice.
2455 A value of t is also allowed, representing \"LOGBOOK\".
2457 If this variable is set, `org-log-state-notes-insert-after-drawers'
2458 will be ignored.
2460 You can set the property LOG_INTO_DRAWER to overrule this setting for
2461 a subtree."
2462 :group 'org-todo
2463 :group 'org-progress
2464 :type '(choice
2465 (const :tag "Not into a drawer" nil)
2466 (const :tag "LOGBOOK" t)
2467 (string :tag "Other")))
2469 (if (fboundp 'defvaralias)
2470 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2472 (defun org-log-into-drawer ()
2473 "Return the value of `org-log-into-drawer', but let properties overrule.
2474 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2475 used instead of the default value."
2476 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2477 (cond
2478 ((or (not p) (equal p "nil")) org-log-into-drawer)
2479 ((equal p "t") "LOGBOOK")
2480 (t p))))
2482 (defcustom org-log-state-notes-insert-after-drawers nil
2483 "Non-nil means insert state change notes after any drawers in entry.
2484 Only the drawers that *immediately* follow the headline and the
2485 deadline/scheduled line are skipped.
2486 When nil, insert notes right after the heading and perhaps the line
2487 with deadline/scheduling if present.
2489 This variable will have no effect if `org-log-into-drawer' is
2490 set."
2491 :group 'org-todo
2492 :group 'org-progress
2493 :type 'boolean)
2495 (defcustom org-log-states-order-reversed t
2496 "Non-nil means the latest state note will be directly after heading.
2497 When nil, the state change notes will be ordered according to time."
2498 :group 'org-todo
2499 :group 'org-progress
2500 :type 'boolean)
2502 (defcustom org-todo-repeat-to-state nil
2503 "The TODO state to which a repeater should return the repeating task.
2504 By default this is the first task in a TODO sequence, or the previous state
2505 in a TODO_TYP set. But you can specify another task here.
2506 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2507 :group 'org-todo
2508 :type '(choice (const :tag "Head of sequence" nil)
2509 (string :tag "Specific state")))
2511 (defcustom org-log-repeat 'time
2512 "Non-nil means record moving through the DONE state when triggering repeat.
2513 An auto-repeating task is immediately switched back to TODO when
2514 marked DONE. If you are not logging state changes (by adding \"@\"
2515 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2516 record a closing note, there will be no record of the task moving
2517 through DONE. This variable forces taking a note anyway.
2519 nil Don't force a record
2520 time Record a time stamp
2521 note Record a note
2523 This option can also be set with on a per-file-basis with
2525 #+STARTUP: logrepeat
2526 #+STARTUP: lognoterepeat
2527 #+STARTUP: nologrepeat
2529 You can have local logging settings for a subtree by setting the LOGGING
2530 property to one or more of these keywords."
2531 :group 'org-todo
2532 :group 'org-progress
2533 :type '(choice
2534 (const :tag "Don't force a record" nil)
2535 (const :tag "Force recording the DONE state" time)
2536 (const :tag "Force recording a note with the DONE state" note)))
2539 (defgroup org-priorities nil
2540 "Priorities in Org-mode."
2541 :tag "Org Priorities"
2542 :group 'org-todo)
2544 (defcustom org-enable-priority-commands t
2545 "Non-nil means priority commands are active.
2546 When nil, these commands will be disabled, so that you never accidentally
2547 set a priority."
2548 :group 'org-priorities
2549 :type 'boolean)
2551 (defcustom org-highest-priority ?A
2552 "The highest priority of TODO items. A character like ?A, ?B etc.
2553 Must have a smaller ASCII number than `org-lowest-priority'."
2554 :group 'org-priorities
2555 :type 'character)
2557 (defcustom org-lowest-priority ?C
2558 "The lowest priority of TODO items. A character like ?A, ?B etc.
2559 Must have a larger ASCII number than `org-highest-priority'."
2560 :group 'org-priorities
2561 :type 'character)
2563 (defcustom org-default-priority ?B
2564 "The default priority of TODO items.
2565 This is the priority an item gets if no explicit priority is given.
2566 When starting to cycle on an empty priority the first step in the cycle
2567 depends on `org-priority-start-cycle-with-default'. The resulting first
2568 step priority must not exceed the range from `org-highest-priority' to
2569 `org-lowest-priority' which means that `org-default-priority' has to be
2570 in this range exclusive or inclusive the range boundaries. Else the
2571 first step refuses to set the default and the second will fall back
2572 to (depending on the command used) the highest or lowest priority."
2573 :group 'org-priorities
2574 :type 'character)
2576 (defcustom org-priority-start-cycle-with-default t
2577 "Non-nil means start with default priority when starting to cycle.
2578 When this is nil, the first step in the cycle will be (depending on the
2579 command used) one higher or lower than the default priority.
2580 See also `org-default-priority'."
2581 :group 'org-priorities
2582 :type 'boolean)
2584 (defcustom org-get-priority-function nil
2585 "Function to extract the priority from a string.
2586 The string is normally the headline. If this is nil Org computes the
2587 priority from the priority cookie like [#A] in the headline. It returns
2588 an integer, increasing by 1000 for each priority level.
2589 The user can set a different function here, which should take a string
2590 as an argument and return the numeric priority."
2591 :group 'org-priorities
2592 :type 'function)
2594 (defgroup org-time nil
2595 "Options concerning time stamps and deadlines in Org-mode."
2596 :tag "Org Time"
2597 :group 'org)
2599 (defcustom org-insert-labeled-timestamps-at-point nil
2600 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2601 When nil, these labeled time stamps are forces into the second line of an
2602 entry, just after the headline. When scheduling from the global TODO list,
2603 the time stamp will always be forced into the second line."
2604 :group 'org-time
2605 :type 'boolean)
2607 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2608 "Formats for `format-time-string' which are used for time stamps.
2609 It is not recommended to change this constant.")
2611 (defcustom org-time-stamp-rounding-minutes '(0 5)
2612 "Number of minutes to round time stamps to.
2613 These are two values, the first applies when first creating a time stamp.
2614 The second applies when changing it with the commands `S-up' and `S-down'.
2615 When changing the time stamp, this means that it will change in steps
2616 of N minutes, as given by the second value.
2618 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2619 numbers should be factors of 60, so for example 5, 10, 15.
2621 When this is larger than 1, you can still force an exact time stamp by using
2622 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2623 and by using a prefix arg to `S-up/down' to specify the exact number
2624 of minutes to shift."
2625 :group 'org-time
2626 :get #'(lambda (var) ; Make sure both elements are there
2627 (if (integerp (default-value var))
2628 (list (default-value var) 5)
2629 (default-value var)))
2630 :type '(list
2631 (integer :tag "when inserting times")
2632 (integer :tag "when modifying times")))
2634 ;; Normalize old customizations of this variable.
2635 (when (integerp org-time-stamp-rounding-minutes)
2636 (setq org-time-stamp-rounding-minutes
2637 (list org-time-stamp-rounding-minutes
2638 org-time-stamp-rounding-minutes)))
2640 (defcustom org-display-custom-times nil
2641 "Non-nil means overlay custom formats over all time stamps.
2642 The formats are defined through the variable `org-time-stamp-custom-formats'.
2643 To turn this on on a per-file basis, insert anywhere in the file:
2644 #+STARTUP: customtime"
2645 :group 'org-time
2646 :set 'set-default
2647 :type 'sexp)
2648 (make-variable-buffer-local 'org-display-custom-times)
2650 (defcustom org-time-stamp-custom-formats
2651 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2652 "Custom formats for time stamps. See `format-time-string' for the syntax.
2653 These are overlayed over the default ISO format if the variable
2654 `org-display-custom-times' is set. Time like %H:%M should be at the
2655 end of the second format. The custom formats are also honored by export
2656 commands, if custom time display is turned on at the time of export."
2657 :group 'org-time
2658 :type 'sexp)
2660 (defun org-time-stamp-format (&optional long inactive)
2661 "Get the right format for a time string."
2662 (let ((f (if long (cdr org-time-stamp-formats)
2663 (car org-time-stamp-formats))))
2664 (if inactive
2665 (concat "[" (substring f 1 -1) "]")
2666 f)))
2668 (defcustom org-time-clocksum-format "%d:%02d"
2669 "The format string used when creating CLOCKSUM lines.
2670 This is also used when org-mode generates a time duration."
2671 :group 'org-time
2672 :type 'string)
2674 (defcustom org-time-clocksum-use-fractional nil
2675 "If non-nil, \\[org-clock-display] uses fractional times.
2676 org-mode generates a time duration."
2677 :group 'org-time
2678 :type 'boolean)
2680 (defcustom org-time-clocksum-fractional-format "%.2f"
2681 "The format string used when creating CLOCKSUM lines, or when
2682 org-mode generates a time duration."
2683 :group 'org-time
2684 :type 'string)
2686 (defcustom org-deadline-warning-days 14
2687 "No. of days before expiration during which a deadline becomes active.
2688 This variable governs the display in sparse trees and in the agenda.
2689 When 0 or negative, it means use this number (the absolute value of it)
2690 even if a deadline has a different individual lead time specified.
2692 Custom commands can set this variable in the options section."
2693 :group 'org-time
2694 :group 'org-agenda-daily/weekly
2695 :type 'integer)
2697 (defcustom org-read-date-prefer-future t
2698 "Non-nil means assume future for incomplete date input from user.
2699 This affects the following situations:
2700 1. The user gives a month but not a year.
2701 For example, if it is April and you enter \"feb 2\", this will be read
2702 as Feb 2, *next* year. \"May 5\", however, will be this year.
2703 2. The user gives a day, but no month.
2704 For example, if today is the 15th, and you enter \"3\", Org-mode will
2705 read this as the third of *next* month. However, if you enter \"17\",
2706 it will be considered as *this* month.
2708 If you set this variable to the symbol `time', then also the following
2709 will work:
2711 3. If the user gives a time, but no day. If the time is before now,
2712 to will be interpreted as tomorrow.
2714 Currently none of this works for ISO week specifications.
2716 When this option is nil, the current day, month and year will always be
2717 used as defaults.
2719 See also `org-agenda-jump-prefer-future'."
2720 :group 'org-time
2721 :type '(choice
2722 (const :tag "Never" nil)
2723 (const :tag "Check month and day" t)
2724 (const :tag "Check month, day, and time" time)))
2726 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2727 "Should the agenda jump command prefer the future for incomplete dates?
2728 The default is to do the same as configured in `org-read-date-prefer-future'.
2729 But you can also set a deviating value here.
2730 This may t or nil, or the symbol `org-read-date-prefer-future'."
2731 :group 'org-agenda
2732 :group 'org-time
2733 :type '(choice
2734 (const :tag "Use org-read-date-prefer-future"
2735 org-read-date-prefer-future)
2736 (const :tag "Never" nil)
2737 (const :tag "Always" t)))
2739 (defcustom org-read-date-force-compatible-dates t
2740 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2742 Depending on the system Emacs is running on, certain dates cannot
2743 be represented with the type used internally to represent time.
2744 Dates between 1970-1-1 and 2038-1-1 can always be represented
2745 correctly. Some systems allow for earlier dates, some for later,
2746 some for both. One way to find out it to insert any date into an
2747 Org buffer, putting the cursor on the year and hitting S-up and
2748 S-down to test the range.
2750 When this variable is set to t, the date/time prompt will not let
2751 you specify dates outside the 1970-2037 range, so it is certain that
2752 these dates will work in whatever version of Emacs you are
2753 running, and also that you can move a file from one Emacs implementation
2754 to another. WHenever Org is forcing the year for you, it will display
2755 a message and beep.
2757 When this variable is nil, Org will check if the date is
2758 representable in the specific Emacs implementation you are using.
2759 If not, it will force a year, usually the current year, and beep
2760 to remind you. Currently this setting is not recommended because
2761 the likelihood that you will open your Org files in an Emacs that
2762 has limited date range is not negligible.
2764 A workaround for this problem is to use diary sexp dates for time
2765 stamps outside of this range."
2766 :group 'org-time
2767 :type 'boolean)
2769 (defcustom org-read-date-display-live t
2770 "Non-nil means display current interpretation of date prompt live.
2771 This display will be in an overlay, in the minibuffer."
2772 :group 'org-time
2773 :type 'boolean)
2775 (defcustom org-read-date-popup-calendar t
2776 "Non-nil means pop up a calendar when prompting for a date.
2777 In the calendar, the date can be selected with mouse-1. However, the
2778 minibuffer will also be active, and you can simply enter the date as well.
2779 When nil, only the minibuffer will be available."
2780 :group 'org-time
2781 :type 'boolean)
2782 (if (fboundp 'defvaralias)
2783 (defvaralias 'org-popup-calendar-for-date-prompt
2784 'org-read-date-popup-calendar))
2786 (defcustom org-read-date-minibuffer-setup-hook nil
2787 "Hook to be used to set up keys for the date/time interface.
2788 Add key definitions to `minibuffer-local-map', which will be a temporary
2789 copy."
2790 :group 'org-time
2791 :type 'hook)
2793 (defcustom org-extend-today-until 0
2794 "The hour when your day really ends. Must be an integer.
2795 This has influence for the following applications:
2796 - When switching the agenda to \"today\". It it is still earlier than
2797 the time given here, the day recognized as TODAY is actually yesterday.
2798 - When a date is read from the user and it is still before the time given
2799 here, the current date and time will be assumed to be yesterday, 23:59.
2800 Also, timestamps inserted in remember templates follow this rule.
2802 IMPORTANT: This is a feature whose implementation is and likely will
2803 remain incomplete. Really, it is only here because past midnight seems to
2804 be the favorite working time of John Wiegley :-)"
2805 :group 'org-time
2806 :type 'integer)
2808 (defcustom org-use-effective-time nil
2809 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2810 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2811 \"effective time\" of any timestamps between midnight and 8am will be
2812 23:59 of the previous day."
2813 :group 'boolean
2814 :type 'integer)
2816 (defcustom org-edit-timestamp-down-means-later nil
2817 "Non-nil means S-down will increase the time in a time stamp.
2818 When nil, S-up will increase."
2819 :group 'org-time
2820 :type 'boolean)
2822 (defcustom org-calendar-follow-timestamp-change t
2823 "Non-nil means make the calendar window follow timestamp changes.
2824 When a timestamp is modified and the calendar window is visible, it will be
2825 moved to the new date."
2826 :group 'org-time
2827 :type 'boolean)
2829 (defgroup org-tags nil
2830 "Options concerning tags in Org-mode."
2831 :tag "Org Tags"
2832 :group 'org)
2834 (defcustom org-tag-alist nil
2835 "List of tags allowed in Org-mode files.
2836 When this list is nil, Org-mode will base TAG input on what is already in the
2837 buffer.
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 :group 'org-tags
2843 :type '(repeat
2844 (choice
2845 (cons (string :tag "Tag name")
2846 (character :tag "Access char"))
2847 (list :tag "Start radio group"
2848 (const :startgroup)
2849 (option (string :tag "Group description")))
2850 (list :tag "End radio group"
2851 (const :endgroup)
2852 (option (string :tag "Group description")))
2853 (const :tag "New line" (:newline)))))
2855 (defcustom org-tag-persistent-alist nil
2856 "List of tags that will always appear in all Org-mode files.
2857 This is in addition to any in buffer settings or customizations
2858 of `org-tag-alist'.
2859 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2860 The value of this variable is an alist, the car of each entry must be a
2861 keyword as a string, the cdr may be a character that is used to select
2862 that tag through the fast-tag-selection interface.
2863 See the manual for details.
2864 To disable these tags on a per-file basis, insert anywhere in the file:
2865 #+STARTUP: noptag"
2866 :group 'org-tags
2867 :type '(repeat
2868 (choice
2869 (cons (string :tag "Tag name")
2870 (character :tag "Access char"))
2871 (const :tag "Start radio group" (:startgroup))
2872 (const :tag "End radio group" (:endgroup))
2873 (const :tag "New line" (:newline)))))
2875 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2876 "If non-nil, always offer completion for all tags of all agenda files.
2877 Instead of customizing this variable directly, you might want to
2878 set it locally for capture buffers, because there no list of
2879 tags in that file can be created dynamically (there are none).
2881 (add-hook 'org-capture-mode-hook
2882 (lambda ()
2883 (set (make-local-variable
2884 'org-complete-tags-always-offer-all-agenda-tags)
2885 t)))"
2886 :group 'org-tags
2887 :type 'boolean)
2889 (defvar org-file-tags nil
2890 "List of tags that can be inherited by all entries in the file.
2891 The tags will be inherited if the variable `org-use-tag-inheritance'
2892 says they should be.
2893 This variable is populated from #+FILETAGS lines.")
2895 (defcustom org-use-fast-tag-selection 'auto
2896 "Non-nil means use fast tag selection scheme.
2897 This is a special interface to select and deselect tags with single keys.
2898 When nil, fast selection is never used.
2899 When the symbol `auto', fast selection is used if and only if selection
2900 characters for tags have been configured, either through the variable
2901 `org-tag-alist' or through a #+TAGS line in the buffer.
2902 When t, fast selection is always used and selection keys are assigned
2903 automatically if necessary."
2904 :group 'org-tags
2905 :type '(choice
2906 (const :tag "Always" t)
2907 (const :tag "Never" nil)
2908 (const :tag "When selection characters are configured" 'auto)))
2910 (defcustom org-fast-tag-selection-single-key nil
2911 "Non-nil means fast tag selection exits after first change.
2912 When nil, you have to press RET to exit it.
2913 During fast tag selection, you can toggle this flag with `C-c'.
2914 This variable can also have the value `expert'. In this case, the window
2915 displaying the tags menu is not even shown, until you press C-c again."
2916 :group 'org-tags
2917 :type '(choice
2918 (const :tag "No" nil)
2919 (const :tag "Yes" t)
2920 (const :tag "Expert" expert)))
2922 (defvar org-fast-tag-selection-include-todo nil
2923 "Non-nil means fast tags selection interface will also offer TODO states.
2924 This is an undocumented feature, you should not rely on it.")
2926 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2927 "The column to which tags should be indented in a headline.
2928 If this number is positive, it specifies the column. If it is negative,
2929 it means that the tags should be flushright to that column. For example,
2930 -80 works well for a normal 80 character screen.
2931 When 0, place tags directly after headline text, with only one space in
2932 between."
2933 :group 'org-tags
2934 :type 'integer)
2936 (defcustom org-auto-align-tags t
2937 "Non-nil keeps tags aligned when modifying headlines.
2938 Some operations (i.e. demoting) change the length of a headline and
2939 therefore shift the tags around. With this option turned on, after
2940 each such operation the tags are again aligned to `org-tags-column'."
2941 :group 'org-tags
2942 :type 'boolean)
2944 (defcustom org-use-tag-inheritance t
2945 "Non-nil means tags in levels apply also for sublevels.
2946 When nil, only the tags directly given in a specific line apply there.
2947 This may also be a list of tags that should be inherited, or a regexp that
2948 matches tags that should be inherited. Additional control is possible
2949 with the variable `org-tags-exclude-from-inheritance' which gives an
2950 explicit list of tags to be excluded from inheritance., even if the value of
2951 `org-use-tag-inheritance' would select it for inheritance.
2953 If this option is t, a match early-on in a tree can lead to a large
2954 number of matches in the subtree when constructing the agenda or creating
2955 a sparse tree. If you only want to see the first match in a tree during
2956 a search, check out the variable `org-tags-match-list-sublevels'."
2957 :group 'org-tags
2958 :type '(choice
2959 (const :tag "Not" nil)
2960 (const :tag "Always" t)
2961 (repeat :tag "Specific tags" (string :tag "Tag"))
2962 (regexp :tag "Tags matched by regexp")))
2964 (defcustom org-tags-exclude-from-inheritance nil
2965 "List of tags that should never be inherited.
2966 This is a way to exclude a few tags from inheritance. For way to do
2967 the opposite, to actively allow inheritance for selected tags,
2968 see the variable `org-use-tag-inheritance'."
2969 :group 'org-tags
2970 :type '(repeat (string :tag "Tag")))
2972 (defun org-tag-inherit-p (tag)
2973 "Check if TAG is one that should be inherited."
2974 (cond
2975 ((member tag org-tags-exclude-from-inheritance) nil)
2976 ((eq org-use-tag-inheritance t) t)
2977 ((not org-use-tag-inheritance) nil)
2978 ((stringp org-use-tag-inheritance)
2979 (string-match org-use-tag-inheritance tag))
2980 ((listp org-use-tag-inheritance)
2981 (member tag org-use-tag-inheritance))
2982 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2984 (defcustom org-tags-match-list-sublevels t
2985 "Non-nil means list also sublevels of headlines matching a search.
2986 This variable applies to tags/property searches, and also to stuck
2987 projects because this search is based on a tags match as well.
2989 When set to the symbol `indented', sublevels are indented with
2990 leading dots.
2992 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2993 the sublevels of a headline matching a tag search often also match
2994 the same search. Listing all of them can create very long lists.
2995 Setting this variable to nil causes subtrees of a match to be skipped.
2997 This variable is semi-obsolete and probably should always be true. It
2998 is better to limit inheritance to certain tags using the variables
2999 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3000 :group 'org-tags
3001 :type '(choice
3002 (const :tag "No, don't list them" nil)
3003 (const :tag "Yes, do list them" t)
3004 (const :tag "List them, indented with leading dots" indented)))
3006 (defcustom org-tags-sort-function nil
3007 "When set, tags are sorted using this function as a comparator."
3008 :group 'org-tags
3009 :type '(choice
3010 (const :tag "No sorting" nil)
3011 (const :tag "Alphabetical" string<)
3012 (const :tag "Reverse alphabetical" string>)
3013 (function :tag "Custom function" nil)))
3015 (defvar org-tags-history nil
3016 "History of minibuffer reads for tags.")
3017 (defvar org-last-tags-completion-table nil
3018 "The last used completion table for tags.")
3019 (defvar org-after-tags-change-hook nil
3020 "Hook that is run after the tags in a line have changed.")
3022 (defgroup org-properties nil
3023 "Options concerning properties in Org-mode."
3024 :tag "Org Properties"
3025 :group 'org)
3027 (defcustom org-property-format "%-10s %s"
3028 "How property key/value pairs should be formatted by `indent-line'.
3029 When `indent-line' hits a property definition, it will format the line
3030 according to this format, mainly to make sure that the values are
3031 lined-up with respect to each other."
3032 :group 'org-properties
3033 :type 'string)
3035 (defcustom org-properties-postprocess-alist nil
3036 "Alist of properties and functions to adjust inserted values.
3037 Elements of this alist must be of the form
3039 ([string] [function])
3041 where [string] must be a property name and [function] must be a
3042 lambda expression: this lambda expression must take one argument,
3043 the value to adjust, and return the new value as a string.
3045 For example, this element will allow the property \"Remaining\"
3046 to be updated wrt the relation between the \"Effort\" property
3047 and the clock summary:
3049 ((\"Remaining\" (lambda(value)
3050 (let ((clocksum (org-clock-sum-current-item))
3051 (effort (org-duration-string-to-minutes
3052 (org-entry-get (point) \"Effort\"))))
3053 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3054 :group 'org-properties
3055 :type 'alist)
3057 (defcustom org-use-property-inheritance nil
3058 "Non-nil means properties apply also for sublevels.
3060 This setting is chiefly used during property searches. Turning it on can
3061 cause significant overhead when doing a search, which is why it is not
3062 on by default.
3064 When nil, only the properties directly given in the current entry count.
3065 When t, every property is inherited. The value may also be a list of
3066 properties that should have inheritance, or a regular expression matching
3067 properties that should be inherited.
3069 However, note that some special properties use inheritance under special
3070 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3071 and the properties ending in \"_ALL\" when they are used as descriptor
3072 for valid values of a property.
3074 Note for programmers:
3075 When querying an entry with `org-entry-get', you can control if inheritance
3076 should be used. By default, `org-entry-get' looks only at the local
3077 properties. You can request inheritance by setting the inherit argument
3078 to t (to force inheritance) or to `selective' (to respect the setting
3079 in this variable)."
3080 :group 'org-properties
3081 :type '(choice
3082 (const :tag "Not" nil)
3083 (const :tag "Always" t)
3084 (repeat :tag "Specific properties" (string :tag "Property"))
3085 (regexp :tag "Properties matched by regexp")))
3087 (defun org-property-inherit-p (property)
3088 "Check if PROPERTY is one that should be inherited."
3089 (cond
3090 ((eq org-use-property-inheritance t) t)
3091 ((not org-use-property-inheritance) nil)
3092 ((stringp org-use-property-inheritance)
3093 (string-match org-use-property-inheritance property))
3094 ((listp org-use-property-inheritance)
3095 (member property org-use-property-inheritance))
3096 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3098 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3099 "The default column format, if no other format has been defined.
3100 This variable can be set on the per-file basis by inserting a line
3102 #+COLUMNS: %25ITEM ....."
3103 :group 'org-properties
3104 :type 'string)
3106 (defcustom org-columns-ellipses ".."
3107 "The ellipses to be used when a field in column view is truncated.
3108 When this is the empty string, as many characters as possible are shown,
3109 but then there will be no visual indication that the field has been truncated.
3110 When this is a string of length N, the last N characters of a truncated
3111 field are replaced by this string. If the column is narrower than the
3112 ellipses string, only part of the ellipses string will be shown."
3113 :group 'org-properties
3114 :type 'string)
3116 (defcustom org-columns-modify-value-for-display-function nil
3117 "Function that modifies values for display in column view.
3118 For example, it can be used to cut out a certain part from a time stamp.
3119 The function must take 2 arguments:
3121 column-title The title of the column (*not* the property name)
3122 value The value that should be modified.
3124 The function should return the value that should be displayed,
3125 or nil if the normal value should be used."
3126 :group 'org-properties
3127 :type 'function)
3129 (defcustom org-effort-property "Effort"
3130 "The property that is being used to keep track of effort estimates.
3131 Effort estimates given in this property need to have the format H:MM."
3132 :group 'org-properties
3133 :group 'org-progress
3134 :type '(string :tag "Property"))
3136 (defconst org-global-properties-fixed
3137 '(("VISIBILITY_ALL" . "folded children content all")
3138 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3139 "List of property/value pairs that can be inherited by any entry.
3141 These are fixed values, for the preset properties. The user variable
3142 that can be used to add to this list is `org-global-properties'.
3144 The entries in this list are cons cells where the car is a property
3145 name and cdr is a string with the value. If the value represents
3146 multiple items like an \"_ALL\" property, separate the items by
3147 spaces.")
3149 (defcustom org-global-properties nil
3150 "List of property/value pairs that can be inherited by any entry.
3152 This list will be combined with the constant `org-global-properties-fixed'.
3154 The entries in this list are cons cells where the car is a property
3155 name and cdr is a string with the value.
3157 You can set buffer-local values for the same purpose in the variable
3158 `org-file-properties' this by adding lines like
3160 #+PROPERTY: NAME VALUE"
3161 :group 'org-properties
3162 :type '(repeat
3163 (cons (string :tag "Property")
3164 (string :tag "Value"))))
3166 (defvar org-file-properties nil
3167 "List of property/value pairs that can be inherited by any entry.
3168 Valid for the current buffer.
3169 This variable is populated from #+PROPERTY lines.")
3170 (make-variable-buffer-local 'org-file-properties)
3172 (defgroup org-agenda nil
3173 "Options concerning agenda views in Org-mode."
3174 :tag "Org Agenda"
3175 :group 'org)
3177 (defvar org-category nil
3178 "Variable used by org files to set a category for agenda display.
3179 Such files should use a file variable to set it, for example
3181 # -*- mode: org; org-category: \"ELisp\"
3183 or contain a special line
3185 #+CATEGORY: ELisp
3187 If the file does not specify a category, then file's base name
3188 is used instead.")
3189 (make-variable-buffer-local 'org-category)
3190 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3192 (defcustom org-agenda-files nil
3193 "The files to be used for agenda display.
3194 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3195 \\[org-remove-file]. You can also use customize to edit the list.
3197 If an entry is a directory, all files in that directory that are matched by
3198 `org-agenda-file-regexp' will be part of the file list.
3200 If the value of the variable is not a list but a single file name, then
3201 the list of agenda files is actually stored and maintained in that file, one
3202 agenda file per line. In this file paths can be given relative to
3203 `org-directory'. Tilde expansion and environment variable substitution
3204 are also made."
3205 :group 'org-agenda
3206 :type '(choice
3207 (repeat :tag "List of files and directories" file)
3208 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3210 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3211 "Regular expression to match files for `org-agenda-files'.
3212 If any element in the list in that variable contains a directory instead
3213 of a normal file, all files in that directory that are matched by this
3214 regular expression will be included."
3215 :group 'org-agenda
3216 :type 'regexp)
3218 (defcustom org-agenda-text-search-extra-files nil
3219 "List of extra files to be searched by text search commands.
3220 These files will be search in addition to the agenda files by the
3221 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3222 Note that these files will only be searched for text search commands,
3223 not for the other agenda views like todo lists, tag searches or the weekly
3224 agenda. This variable is intended to list notes and possibly archive files
3225 that should also be searched by these two commands.
3226 In fact, if the first element in the list is the symbol `agenda-archives',
3227 than all archive files of all agenda files will be added to the search
3228 scope."
3229 :group 'org-agenda
3230 :type '(set :greedy t
3231 (const :tag "Agenda Archives" agenda-archives)
3232 (repeat :inline t (file))))
3234 (if (fboundp 'defvaralias)
3235 (defvaralias 'org-agenda-multi-occur-extra-files
3236 'org-agenda-text-search-extra-files))
3238 (defcustom org-agenda-skip-unavailable-files nil
3239 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3240 A nil value means to remove them, after a query, from the list."
3241 :group 'org-agenda
3242 :type 'boolean)
3244 (defcustom org-calendar-to-agenda-key [?c]
3245 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3246 The command `org-calendar-goto-agenda' will be bound to this key. The
3247 default is the character `c' because then `c' can be used to switch back and
3248 forth between agenda and calendar."
3249 :group 'org-agenda
3250 :type 'sexp)
3252 (defcustom org-calendar-agenda-action-key [?k]
3253 "The key to be installed in `calendar-mode-map' for agenda-action.
3254 The command `org-agenda-action' will be bound to this key. The
3255 default is the character `k' because we use the same key in the agenda."
3256 :group 'org-agenda
3257 :type 'sexp)
3259 (defcustom org-calendar-insert-diary-entry-key [?i]
3260 "The key to be installed in `calendar-mode-map' for adding diary entries.
3261 This option is irrelevant until `org-agenda-diary-file' has been configured
3262 to point to an Org-mode file. When that is the case, the command
3263 `org-agenda-diary-entry' will be bound to the key given here, by default
3264 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3265 if you want to continue doing this, you need to change this to a different
3266 key."
3267 :group 'org-agenda
3268 :type 'sexp)
3270 (defcustom org-agenda-diary-file 'diary-file
3271 "File to which to add new entries with the `i' key in agenda and calendar.
3272 When this is the symbol `diary-file', the functionality in the Emacs
3273 calendar will be used to add entries to the `diary-file'. But when this
3274 points to a file, `org-agenda-diary-entry' will be used instead."
3275 :group 'org-agenda
3276 :type '(choice
3277 (const :tag "The standard Emacs diary file" diary-file)
3278 (file :tag "Special Org file diary entries")))
3280 (eval-after-load "calendar"
3281 '(progn
3282 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3283 'org-calendar-goto-agenda)
3284 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3285 'org-agenda-action)
3286 (add-hook 'calendar-mode-hook
3287 (lambda ()
3288 (unless (eq org-agenda-diary-file 'diary-file)
3289 (define-key calendar-mode-map
3290 org-calendar-insert-diary-entry-key
3291 'org-agenda-diary-entry))))))
3293 (defgroup org-latex nil
3294 "Options for embedding LaTeX code into Org-mode."
3295 :tag "Org LaTeX"
3296 :group 'org)
3298 (defcustom org-format-latex-options
3299 '(:foreground default :background default :scale 1.0
3300 :html-foreground "Black" :html-background "Transparent"
3301 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3302 "Options for creating images from LaTeX fragments.
3303 This is a property list with the following properties:
3304 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3305 `default' means use the foreground of the default face.
3306 :background the background color, or \"Transparent\".
3307 `default' means use the background of the default face.
3308 :scale a scaling factor for the size of the images, to get more pixels
3309 :html-foreground, :html-background, :html-scale
3310 the same numbers for HTML export.
3311 :matchers a list indicating which matchers should be used to
3312 find LaTeX fragments. Valid members of this list are:
3313 \"begin\" find environments
3314 \"$1\" find single characters surrounded by $.$
3315 \"$\" find math expressions surrounded by $...$
3316 \"$$\" find math expressions surrounded by $$....$$
3317 \"\\(\" find math expressions surrounded by \\(...\\)
3318 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3319 :group 'org-latex
3320 :type 'plist)
3322 (defcustom org-format-latex-signal-error t
3323 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3324 When nil, just push out a message."
3325 :group 'org-latex
3326 :type 'boolean)
3327 (defcustom org-latex-to-mathml-jar-file nil
3328 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3329 Use this to specify additional executable file say a jar file.
3331 When using MathToWeb as the converter, specify the full-path to
3332 your mathtoweb.jar file."
3333 :group 'org-latex
3334 :type '(choice
3335 (const :tag "None" nil)
3336 (file :tag "JAR file" :must-match t)))
3338 (defcustom org-latex-to-mathml-convert-command nil
3339 "Command to convert LaTeX fragments to MathML.
3340 Replace format-specifiers in the command as noted below and use
3341 `shell-command' to convert LaTeX to MathML.
3342 %j: Executable file in fully expanded form as specified by
3343 `org-latex-to-mathml-jar-file'.
3344 %I: Input LaTeX file in fully expanded form
3345 %o: Output MathML file
3346 This command is used by `org-create-math-formula'.
3348 When using MathToWeb as the converter, set this to
3349 \"java -jar %j -unicode -force -df %o %I\"."
3350 :group 'org-latex
3351 :type '(choice
3352 (const :tag "None" nil)
3353 (string :tag "\nShell command")))
3355 (defun org-format-latex-mathml-available-p ()
3356 "Return t if `org-latex-to-mathml-convert-command' is usable."
3357 (save-match-data
3358 (when (and (boundp 'org-latex-to-mathml-convert-command)
3359 org-latex-to-mathml-convert-command)
3360 (let ((executable (car (split-string
3361 org-latex-to-mathml-convert-command))))
3362 (when (executable-find executable)
3363 (if (string-match
3364 "%j" org-latex-to-mathml-convert-command)
3365 (file-readable-p org-latex-to-mathml-jar-file)
3366 t))))))
3368 (defcustom org-format-latex-header "\\documentclass{article}
3369 \\usepackage[usenames]{color}
3370 \\usepackage{amsmath}
3371 \\usepackage[mathscr]{eucal}
3372 \\pagestyle{empty} % do not remove
3373 \[PACKAGES]
3374 \[DEFAULT-PACKAGES]
3375 % The settings below are copied from fullpage.sty
3376 \\setlength{\\textwidth}{\\paperwidth}
3377 \\addtolength{\\textwidth}{-3cm}
3378 \\setlength{\\oddsidemargin}{1.5cm}
3379 \\addtolength{\\oddsidemargin}{-2.54cm}
3380 \\setlength{\\evensidemargin}{\\oddsidemargin}
3381 \\setlength{\\textheight}{\\paperheight}
3382 \\addtolength{\\textheight}{-\\headheight}
3383 \\addtolength{\\textheight}{-\\headsep}
3384 \\addtolength{\\textheight}{-\\footskip}
3385 \\addtolength{\\textheight}{-3cm}
3386 \\setlength{\\topmargin}{1.5cm}
3387 \\addtolength{\\topmargin}{-2.54cm}"
3388 "The document header used for processing LaTeX fragments.
3389 It is imperative that this header make sure that no page number
3390 appears on the page. The package defined in the variables
3391 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3392 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3393 will be appended."
3394 :group 'org-latex
3395 :type 'string)
3397 (defvar org-format-latex-header-extra nil)
3399 (defun org-set-packages-alist (var val)
3400 "Set the packages alist and make sure it has 3 elements per entry."
3401 (set var (mapcar (lambda (x)
3402 (if (and (consp x) (= (length x) 2))
3403 (list (car x) (nth 1 x) t)
3405 val)))
3407 (defun org-get-packages-alist (var)
3409 "Get the packages alist and make sure it has 3 elements per entry."
3410 (mapcar (lambda (x)
3411 (if (and (consp x) (= (length x) 2))
3412 (list (car x) (nth 1 x) t)
3414 (default-value var)))
3416 ;; The following variables are defined here because is it also used
3417 ;; when formatting latex fragments. Originally it was part of the
3418 ;; LaTeX exporter, which is why the name includes "export".
3419 (defcustom org-export-latex-default-packages-alist
3420 '(("AUTO" "inputenc" t)
3421 ("T1" "fontenc" t)
3422 ("" "fixltx2e" nil)
3423 ("" "graphicx" t)
3424 ("" "longtable" nil)
3425 ("" "float" nil)
3426 ("" "wrapfig" nil)
3427 ("" "soul" t)
3428 ("" "textcomp" t)
3429 ("" "marvosym" t)
3430 ("" "wasysym" t)
3431 ("" "latexsym" t)
3432 ("" "amssymb" t)
3433 ("" "hyperref" nil)
3434 "\\tolerance=1000"
3436 "Alist of default packages to be inserted in the header.
3437 Change this only if one of the packages here causes an incompatibility
3438 with another package you are using.
3439 The packages in this list are needed by one part or another of Org-mode
3440 to function properly.
3442 - inputenc, fontenc: for basic font and character selection
3443 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3444 for interpreting the entities in `org-entities'. You can skip some of these
3445 packages if you don't use any of the symbols in it.
3446 - graphicx: for including images
3447 - float, wrapfig: for figure placement
3448 - longtable: for long tables
3449 - hyperref: for cross references
3451 Therefore you should not modify this variable unless you know what you
3452 are doing. The one reason to change it anyway is that you might be loading
3453 some other package that conflicts with one of the default packages.
3454 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3455 If SNIPPET-FLAG is t, the package also needs to be included when
3456 compiling LaTeX snippets into images for inclusion into HTML."
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"))))
3468 (defcustom org-export-latex-packages-alist nil
3469 "Alist of packages to be inserted in every LaTeX header.
3470 These will be inserted after `org-export-latex-default-packages-alist'.
3471 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3472 SNIPPET-FLAG, when t, indicates that this package is also needed when
3473 turning LaTeX snippets into images for inclusion into HTML.
3474 Make sure that you only list packages here which:
3475 - you want in every file
3476 - do not conflict with the default packages in
3477 `org-export-latex-default-packages-alist'
3478 - do not conflict with the setup in `org-format-latex-header'."
3479 :group 'org-export-latex
3480 :set 'org-set-packages-alist
3481 :get 'org-get-packages-alist
3482 :type '(repeat
3483 (choice
3484 (list :tag "options/package pair"
3485 (string :tag "options")
3486 (string :tag "package")
3487 (boolean :tag "Snippet"))
3488 (string :tag "A line of LaTeX"))))
3491 (defgroup org-appearance nil
3492 "Settings for Org-mode appearance."
3493 :tag "Org Appearance"
3494 :group 'org)
3496 (defcustom org-level-color-stars-only nil
3497 "Non-nil means fontify only the stars in each headline.
3498 When nil, the entire headline is fontified.
3499 Changing it requires restart of `font-lock-mode' to become effective
3500 also in regions already fontified."
3501 :group 'org-appearance
3502 :type 'boolean)
3504 (defcustom org-hide-leading-stars nil
3505 "Non-nil means hide the first N-1 stars in a headline.
3506 This works by using the face `org-hide' for these stars. This
3507 face is white for a light background, and black for a dark
3508 background. You may have to customize the face `org-hide' to
3509 make this work.
3510 Changing it requires restart of `font-lock-mode' to become effective
3511 also in regions already fontified.
3512 You may also set this on a per-file basis by adding one of the following
3513 lines to the buffer:
3515 #+STARTUP: hidestars
3516 #+STARTUP: showstars"
3517 :group 'org-appearance
3518 :type 'boolean)
3520 (defcustom org-hidden-keywords nil
3521 "List of symbols corresponding to keywords to be hidden the org buffer.
3522 For example, a value '(title) for this list will make the document's title
3523 appear in the buffer without the initial #+TITLE: keyword."
3524 :group 'org-appearance
3525 :type '(set (const :tag "#+AUTHOR" author)
3526 (const :tag "#+DATE" date)
3527 (const :tag "#+EMAIL" email)
3528 (const :tag "#+TITLE" title)))
3530 (defcustom org-fontify-done-headline nil
3531 "Non-nil means change the face of a headline if it is marked DONE.
3532 Normally, only the TODO/DONE keyword indicates the state of a headline.
3533 When this is non-nil, the headline after the keyword is set to the
3534 `org-headline-done' as an additional indication."
3535 :group 'org-appearance
3536 :type 'boolean)
3538 (defcustom org-fontify-emphasized-text t
3539 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3540 Changing this variable requires a restart of Emacs to take effect."
3541 :group 'org-appearance
3542 :type 'boolean)
3544 (defcustom org-fontify-whole-heading-line nil
3545 "Non-nil means fontify the whole line for headings.
3546 This is useful when setting a background color for the
3547 org-level-* faces."
3548 :group 'org-appearance
3549 :type 'boolean)
3551 (defcustom org-highlight-latex-fragments-and-specials nil
3552 "Non-nil means fontify what is treated specially by the exporters."
3553 :group 'org-appearance
3554 :type 'boolean)
3556 (defcustom org-hide-emphasis-markers nil
3557 "Non-nil mean font-lock should hide the emphasis marker characters."
3558 :group 'org-appearance
3559 :type 'boolean)
3561 (defcustom org-pretty-entities nil
3562 "Non-nil means show entities as UTF8 characters.
3563 When nil, the \\name form remains in the buffer."
3564 :group 'org-appearance
3565 :type 'boolean)
3567 (defcustom org-pretty-entities-include-sub-superscripts t
3568 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3569 :group 'org-appearance
3570 :type 'boolean)
3572 (defvar org-emph-re nil
3573 "Regular expression for matching emphasis.
3574 After a match, the match groups contain these elements:
3575 0 The match of the full regular expression, including the characters
3576 before and after the proper match
3577 1 The character before the proper match, or empty at beginning of line
3578 2 The proper match, including the leading and trailing markers
3579 3 The leading marker like * or /, indicating the type of highlighting
3580 4 The text between the emphasis markers, not including the markers
3581 5 The character after the match, empty at the end of a line")
3582 (defvar org-verbatim-re nil
3583 "Regular expression for matching verbatim text.")
3584 (defvar org-emphasis-regexp-components) ; defined just below
3585 (defvar org-emphasis-alist) ; defined just below
3586 (defun org-set-emph-re (var val)
3587 "Set variable and compute the emphasis regular expression."
3588 (set var val)
3589 (when (and (boundp 'org-emphasis-alist)
3590 (boundp 'org-emphasis-regexp-components)
3591 org-emphasis-alist org-emphasis-regexp-components)
3592 (let* ((e org-emphasis-regexp-components)
3593 (pre (car e))
3594 (post (nth 1 e))
3595 (border (nth 2 e))
3596 (body (nth 3 e))
3597 (nl (nth 4 e))
3598 (body1 (concat body "*?"))
3599 (markers (mapconcat 'car org-emphasis-alist ""))
3600 (vmarkers (mapconcat
3601 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3602 org-emphasis-alist "")))
3603 ;; make sure special characters appear at the right position in the class
3604 (if (string-match "\\^" markers)
3605 (setq markers (concat (replace-match "" t t markers) "^")))
3606 (if (string-match "-" markers)
3607 (setq markers (concat (replace-match "" t t markers) "-")))
3608 (if (string-match "\\^" vmarkers)
3609 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3610 (if (string-match "-" vmarkers)
3611 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3612 (if (> nl 0)
3613 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3614 (int-to-string nl) "\\}")))
3615 ;; Make the regexp
3616 (setq org-emph-re
3617 (concat "\\([" pre "]\\|^\\)"
3618 "\\("
3619 "\\([" markers "]\\)"
3620 "\\("
3621 "[^" border "]\\|"
3622 "[^" border "]"
3623 body1
3624 "[^" border "]"
3625 "\\)"
3626 "\\3\\)"
3627 "\\([" post "]\\|$\\)"))
3628 (setq org-verbatim-re
3629 (concat "\\([" pre "]\\|^\\)"
3630 "\\("
3631 "\\([" vmarkers "]\\)"
3632 "\\("
3633 "[^" border "]\\|"
3634 "[^" border "]"
3635 body1
3636 "[^" border "]"
3637 "\\)"
3638 "\\3\\)"
3639 "\\([" post "]\\|$\\)")))))
3641 (defcustom org-emphasis-regexp-components
3642 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3643 "Components used to build the regular expression for emphasis.
3644 This is a list with five entries. Terminology: In an emphasis string
3645 like \" *strong word* \", we call the initial space PREMATCH, the final
3646 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3647 and \"trong wor\" is the body. The different components in this variable
3648 specify what is allowed/forbidden in each part:
3650 pre Chars allowed as prematch. Beginning of line will be allowed too.
3651 post Chars allowed as postmatch. End of line will be allowed too.
3652 border The chars *forbidden* as border characters.
3653 body-regexp A regexp like \".\" to match a body character. Don't use
3654 non-shy groups here, and don't allow newline here.
3655 newline The maximum number of newlines allowed in an emphasis exp.
3657 Use customize to modify this, or restart Emacs after changing it."
3658 :group 'org-appearance
3659 :set 'org-set-emph-re
3660 :type '(list
3661 (sexp :tag "Allowed chars in pre ")
3662 (sexp :tag "Allowed chars in post ")
3663 (sexp :tag "Forbidden chars in border ")
3664 (sexp :tag "Regexp for body ")
3665 (integer :tag "number of newlines allowed")
3666 (option (boolean :tag "Please ignore this button"))))
3668 (defcustom org-emphasis-alist
3669 `(("*" bold "<b>" "</b>")
3670 ("/" italic "<i>" "</i>")
3671 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3672 ("=" org-code "<code>" "</code>" verbatim)
3673 ("~" org-verbatim "<code>" "</code>" verbatim)
3674 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3675 "<del>" "</del>")
3677 "Special syntax for emphasized text.
3678 Text starting and ending with a special character will be emphasized, for
3679 example *bold*, _underlined_ and /italic/. This variable sets the marker
3680 characters, the face to be used by font-lock for highlighting in Org-mode
3681 Emacs buffers, and the HTML tags to be used for this.
3682 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3683 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3684 Use customize to modify this, or restart Emacs after changing it."
3685 :group 'org-appearance
3686 :set 'org-set-emph-re
3687 :type '(repeat
3688 (list
3689 (string :tag "Marker character")
3690 (choice
3691 (face :tag "Font-lock-face")
3692 (plist :tag "Face property list"))
3693 (string :tag "HTML start tag")
3694 (string :tag "HTML end tag")
3695 (option (const verbatim)))))
3697 (defvar org-protecting-blocks
3698 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3699 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3700 This is needed for font-lock setup.")
3702 ;;; Miscellaneous options
3704 (defgroup org-completion nil
3705 "Completion in Org-mode."
3706 :tag "Org Completion"
3707 :group 'org)
3709 (defcustom org-completion-use-ido nil
3710 "Non-nil means use ido completion wherever possible.
3711 Note that `ido-mode' must be active for this variable to be relevant.
3712 If you decide to turn this variable on, you might well want to turn off
3713 `org-outline-path-complete-in-steps'.
3714 See also `org-completion-use-iswitchb'."
3715 :group 'org-completion
3716 :type 'boolean)
3718 (defcustom org-completion-use-iswitchb nil
3719 "Non-nil means use iswitchb completion wherever possible.
3720 Note that `iswitchb-mode' must be active for this variable to be relevant.
3721 If you decide to turn this variable on, you might well want to turn off
3722 `org-outline-path-complete-in-steps'.
3723 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3724 :group 'org-completion
3725 :type 'boolean)
3727 (defcustom org-completion-fallback-command 'hippie-expand
3728 "The expansion command called by \\[pcomplete] in normal context.
3729 Normal means, no org-mode-specific context."
3730 :group 'org-completion
3731 :type 'function)
3733 ;;; Functions and variables from their packages
3734 ;; Declared here to avoid compiler warnings
3736 ;; XEmacs only
3737 (defvar outline-mode-menu-heading)
3738 (defvar outline-mode-menu-show)
3739 (defvar outline-mode-menu-hide)
3740 (defvar zmacs-regions) ; XEmacs regions
3742 ;; Emacs only
3743 (defvar mark-active)
3745 ;; Various packages
3746 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3747 (declare-function calendar-forward-day "cal-move" (arg))
3748 (declare-function calendar-goto-date "cal-move" (date))
3749 (declare-function calendar-goto-today "cal-move" ())
3750 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3751 (defvar calc-embedded-close-formula)
3752 (defvar calc-embedded-open-formula)
3753 (declare-function cdlatex-tab "ext:cdlatex" ())
3754 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3755 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3756 (defvar font-lock-unfontify-region-function)
3757 (declare-function iswitchb-read-buffer "iswitchb"
3758 (prompt &optional default require-match start matches-set))
3759 (defvar iswitchb-temp-buflist)
3760 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3761 (defvar org-agenda-tags-todo-honor-ignore-options)
3762 (declare-function org-agenda-skip "org-agenda" ())
3763 (declare-function
3764 org-agenda-format-item "org-agenda"
3765 (extra txt &optional category tags dotime noprefix remove-re habitp))
3766 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3767 (declare-function org-agenda-change-all-lines "org-agenda"
3768 (newhead hdmarker &optional fixface just-this))
3769 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3770 (declare-function org-agenda-maybe-redo "org-agenda" ())
3771 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3772 (beg end))
3773 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3774 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3775 "org-agenda" (&optional end))
3776 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3777 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3778 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3779 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3780 (declare-function org-indent-mode "org-indent" (&optional arg))
3781 (declare-function parse-time-string "parse-time" (string))
3782 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3783 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3784 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3785 (defvar remember-data-file)
3786 (defvar texmathp-why)
3787 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3788 (declare-function table--at-cell-p "table" (position &optional object at-column))
3790 (defvar w3m-current-url)
3791 (defvar w3m-current-title)
3793 (defvar org-latex-regexps)
3795 ;;; Autoload and prepare some org modules
3797 ;; Some table stuff that needs to be defined here, because it is used
3798 ;; by the functions setting up org-mode or checking for table context.
3800 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3801 "Detect an org-type or table-type table.")
3802 (defconst org-table-line-regexp "^[ \t]*|"
3803 "Detect an org-type table line.")
3804 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3805 "Detect an org-type table line.")
3806 (defconst org-table-hline-regexp "^[ \t]*|-"
3807 "Detect an org-type table hline.")
3808 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3809 "Detect a table-type table hline.")
3810 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3811 "Detect the first line outside a table when searching from within it.
3812 This works for both table types.")
3814 ;; Autoload the functions in org-table.el that are needed by functions here.
3816 (eval-and-compile
3817 (org-autoload "org-table"
3818 '(org-table-align org-table-begin org-table-blank-field
3819 org-table-convert org-table-convert-region org-table-copy-down
3820 org-table-copy-region org-table-create
3821 org-table-create-or-convert-from-region
3822 org-table-create-with-table.el org-table-current-dline
3823 org-table-cut-region org-table-delete-column org-table-edit-field
3824 org-table-edit-formulas org-table-end org-table-eval-formula
3825 org-table-export org-table-field-info
3826 org-table-get-stored-formulas org-table-goto-column
3827 org-table-hline-and-move org-table-import org-table-insert-column
3828 org-table-insert-hline org-table-insert-row org-table-iterate
3829 org-table-justify-field-maybe org-table-kill-row
3830 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3831 org-table-move-column org-table-move-column-left
3832 org-table-move-column-right org-table-move-row
3833 org-table-move-row-down org-table-move-row-up
3834 org-table-next-field org-table-next-row org-table-paste-rectangle
3835 org-table-previous-field org-table-recalculate
3836 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3837 org-table-toggle-coordinate-overlays
3838 org-table-toggle-formula-debugger org-table-wrap-region
3839 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3840 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3841 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3843 (defun org-at-table-p (&optional table-type)
3844 "Return t if the cursor is inside an org-type table.
3845 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3846 (if org-enable-table-editor
3847 (save-excursion
3848 (beginning-of-line 1)
3849 (looking-at (if table-type org-table-any-line-regexp
3850 org-table-line-regexp)))
3851 nil))
3852 (defsubst org-table-p () (org-at-table-p))
3854 (defun org-at-table.el-p ()
3855 "Return t if and only if we are at a table.el table."
3856 (and (org-at-table-p 'any)
3857 (save-excursion
3858 (goto-char (org-table-begin 'any))
3859 (looking-at org-table1-hline-regexp))))
3860 (defun org-table-recognize-table.el ()
3861 "If there is a table.el table nearby, recognize it and move into it."
3862 (if org-table-tab-recognizes-table.el
3863 (if (org-at-table.el-p)
3864 (progn
3865 (beginning-of-line 1)
3866 (if (looking-at org-table-dataline-regexp)
3868 (if (looking-at org-table1-hline-regexp)
3869 (progn
3870 (beginning-of-line 2)
3871 (if (looking-at org-table-any-border-regexp)
3872 (beginning-of-line -1)))))
3873 (if (re-search-forward "|" (org-table-end t) t)
3874 (progn
3875 (require 'table)
3876 (if (table--at-cell-p (point))
3878 (message "recognizing table.el table...")
3879 (table-recognize-table)
3880 (message "recognizing table.el table...done")))
3881 (error "This should not happen"))
3883 nil)
3884 nil))
3886 (defun org-at-table-hline-p ()
3887 "Return t if the cursor is inside a hline in a table."
3888 (if org-enable-table-editor
3889 (save-excursion
3890 (beginning-of-line 1)
3891 (looking-at org-table-hline-regexp))
3892 nil))
3894 (defvar org-table-clean-did-remove-column nil)
3896 (defun org-table-map-tables (function &optional quietly)
3897 "Apply FUNCTION to the start of all tables in the buffer."
3898 (save-excursion
3899 (save-restriction
3900 (widen)
3901 (goto-char (point-min))
3902 (while (re-search-forward org-table-any-line-regexp nil t)
3903 (unless quietly
3904 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3905 (beginning-of-line 1)
3906 (when (looking-at org-table-line-regexp)
3907 (save-excursion (funcall function))
3908 (or (looking-at org-table-line-regexp)
3909 (forward-char 1)))
3910 (re-search-forward org-table-any-border-regexp nil 1))))
3911 (unless quietly (message "Mapping tables: done")))
3913 ;; Declare and autoload functions from org-exp.el & Co
3915 (declare-function org-default-export-plist "org-exp")
3916 (declare-function org-infile-export-plist "org-exp")
3917 (declare-function org-get-current-options "org-exp")
3918 (eval-and-compile
3919 (org-autoload "org-exp"
3920 '(org-export org-export-visible
3921 org-insert-export-options-template
3922 org-table-clean-before-export))
3923 (org-autoload "org-ascii"
3924 '(org-export-as-ascii org-export-ascii-preprocess
3925 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3926 org-export-region-as-ascii))
3927 (org-autoload "org-latex"
3928 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3929 org-replace-region-by-latex org-export-region-as-latex
3930 org-export-as-latex org-export-as-pdf
3931 org-export-as-pdf-and-open))
3932 (org-autoload "org-html"
3933 '(org-export-as-html-and-open
3934 org-export-as-html-batch org-export-as-html-to-buffer
3935 org-replace-region-by-html org-export-region-as-html
3936 org-export-as-html))
3937 (org-autoload "org-docbook"
3938 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3939 org-replace-region-by-docbook org-export-region-as-docbook
3940 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3941 org-export-as-docbook))
3942 (org-autoload "org-icalendar"
3943 '(org-export-icalendar-this-file
3944 org-export-icalendar-all-agenda-files
3945 org-export-icalendar-combine-agenda-files))
3946 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3947 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3949 ;; Declare and autoload functions from org-agenda.el
3951 (eval-and-compile
3952 (org-autoload "org-agenda"
3953 '(org-agenda org-agenda-list org-search-view
3954 org-todo-list org-tags-view org-agenda-list-stuck-projects
3955 org-diary org-agenda-to-appt
3956 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3958 ;; Autoload org-remember
3960 (eval-and-compile
3961 (org-autoload "org-remember"
3962 '(org-remember-insinuate org-remember-annotation
3963 org-remember-apply-template org-remember org-remember-handler)))
3965 (eval-and-compile
3966 (org-autoload "org-capture"
3967 '(org-capture org-capture-insert-template-here
3968 org-capture-import-remember-templates)))
3970 ;; Autoload org-clock.el
3972 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3973 (beg end))
3974 (declare-function org-clock-update-mode-line "org-clock" ())
3975 (declare-function org-resolve-clocks "org-clock"
3976 (&optional also-non-dangling-p prompt last-valid))
3977 (defvar org-clock-start-time)
3978 (defvar org-clock-marker (make-marker)
3979 "Marker recording the last clock-in.")
3980 (defvar org-clock-hd-marker (make-marker)
3981 "Marker recording the last clock-in, but the headline position.")
3982 (defvar org-clock-heading ""
3983 "The heading of the current clock entry.")
3984 (defun org-clock-is-active ()
3985 "Return non-nil if clock is currently running.
3986 The return value is actually the clock marker."
3987 (marker-buffer org-clock-marker))
3989 (eval-and-compile
3990 (org-autoload
3991 "org-clock"
3992 '(org-clock-in org-clock-out org-clock-cancel
3993 org-clock-goto org-clock-sum org-clock-display
3994 org-clock-remove-overlays org-clock-report
3995 org-clocktable-shift org-dblock-write:clocktable
3996 org-get-clocktable org-resolve-clocks)))
3998 (defun org-clock-update-time-maybe ()
3999 "If this is a CLOCK line, update it and return t.
4000 Otherwise, return nil."
4001 (interactive)
4002 (save-excursion
4003 (beginning-of-line 1)
4004 (skip-chars-forward " \t")
4005 (when (looking-at org-clock-string)
4006 (let ((re (concat "[ \t]*" org-clock-string
4007 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
4008 "\\([ \t]*=>.*\\)?\\)?"))
4009 ts te h m s neg)
4010 (cond
4011 ((not (looking-at re))
4012 nil)
4013 ((not (match-end 2))
4014 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4015 (> org-clock-marker (point))
4016 (<= org-clock-marker (point-at-eol)))
4017 ;; The clock is running here
4018 (setq org-clock-start-time
4019 (apply 'encode-time
4020 (org-parse-time-string (match-string 1))))
4021 (org-clock-update-mode-line)))
4023 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
4024 (end-of-line 1)
4025 (setq ts (match-string 1)
4026 te (match-string 3))
4027 (setq s (- (org-float-time
4028 (apply 'encode-time (org-parse-time-string te)))
4029 (org-float-time
4030 (apply 'encode-time (org-parse-time-string ts))))
4031 neg (< s 0)
4032 s (abs s)
4033 h (floor (/ s 3600))
4034 s (- s (* 3600 h))
4035 m (floor (/ s 60))
4036 s (- s (* 60 s)))
4037 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
4038 t))))))
4040 (defun org-check-running-clock ()
4041 "Check if the current buffer contains the running clock.
4042 If yes, offer to stop it and to save the buffer with the changes."
4043 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4044 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4045 (buffer-name))))
4046 (org-clock-out)
4047 (when (y-or-n-p "Save changed buffer?")
4048 (save-buffer))))
4050 (defun org-clocktable-try-shift (dir n)
4051 "Check if this line starts a clock table, if yes, shift the time block."
4052 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4053 (org-clocktable-shift dir n)))
4055 ;; Autoload org-timer.el
4057 (eval-and-compile
4058 (org-autoload
4059 "org-timer"
4060 '(org-timer-start org-timer org-timer-item
4061 org-timer-change-times-in-region
4062 org-timer-set-timer
4063 org-timer-reset-timers
4064 org-timer-show-remaining-time)))
4066 ;; Autoload org-feed.el
4068 (eval-and-compile
4069 (org-autoload
4070 "org-feed"
4071 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
4074 ;; Autoload org-indent.el
4076 ;; Define the variable already here, to make sure we have it.
4077 (defvar org-indent-mode nil
4078 "Non-nil if Org-Indent mode is enabled.
4079 Use the command `org-indent-mode' to change this variable.")
4081 (eval-and-compile
4082 (org-autoload
4083 "org-indent"
4084 '(org-indent-mode)))
4086 ;; Autoload org-mobile.el
4088 (eval-and-compile
4089 (org-autoload
4090 "org-mobile"
4091 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
4093 ;; Autoload archiving code
4094 ;; The stuff that is needed for cycling and tags has to be defined here.
4096 (defgroup org-archive nil
4097 "Options concerning archiving in Org-mode."
4098 :tag "Org Archive"
4099 :group 'org-structure)
4101 (defcustom org-archive-location "%s_archive::"
4102 "The location where subtrees should be archived.
4104 The value of this variable is a string, consisting of two parts,
4105 separated by a double-colon. The first part is a filename and
4106 the second part is a headline.
4108 When the filename is omitted, archiving happens in the same file.
4109 %s in the filename will be replaced by the current file
4110 name (without the directory part). Archiving to a different file
4111 is useful to keep archived entries from contributing to the
4112 Org-mode Agenda.
4114 The archived entries will be filed as subtrees of the specified
4115 headline. When the headline is omitted, the subtrees are simply
4116 filed away at the end of the file, as top-level entries. Also in
4117 the heading you can use %s to represent the file name, this can be
4118 useful when using the same archive for a number of different files.
4120 Here are a few examples:
4121 \"%s_archive::\"
4122 If the current file is Projects.org, archive in file
4123 Projects.org_archive, as top-level trees. This is the default.
4125 \"::* Archived Tasks\"
4126 Archive in the current file, under the top-level headline
4127 \"* Archived Tasks\".
4129 \"~/org/archive.org::\"
4130 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4132 \"~/org/archive.org::* From %s\"
4133 Archive in file ~/org/archive.org (absolute path), under headlines
4134 \"From FILENAME\" where file name is the current file name.
4136 \"basement::** Finished Tasks\"
4137 Archive in file ./basement (relative path), as level 3 trees
4138 below the level 2 heading \"** Finished Tasks\".
4140 You may set this option on a per-file basis by adding to the buffer a
4141 line like
4143 #+ARCHIVE: basement::** Finished Tasks
4145 You may also define it locally for a subtree by setting an ARCHIVE property
4146 in the entry. If such a property is found in an entry, or anywhere up
4147 the hierarchy, it will be used."
4148 :group 'org-archive
4149 :type 'string)
4151 (defcustom org-archive-tag "ARCHIVE"
4152 "The tag that marks a subtree as archived.
4153 An archived subtree does not open during visibility cycling, and does
4154 not contribute to the agenda listings.
4155 After changing this, font-lock must be restarted in the relevant buffers to
4156 get the proper fontification."
4157 :group 'org-archive
4158 :group 'org-keywords
4159 :type 'string)
4161 (defcustom org-agenda-skip-archived-trees t
4162 "Non-nil means the agenda will skip any items located in archived trees.
4163 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4164 variable is no longer recommended, you should leave it at the value t.
4165 Instead, use the key `v' to cycle the archives-mode in the agenda."
4166 :group 'org-archive
4167 :group 'org-agenda-skip
4168 :type 'boolean)
4170 (defcustom org-columns-skip-archived-trees t
4171 "Non-nil means ignore archived trees when creating column view."
4172 :group 'org-archive
4173 :group 'org-properties
4174 :type 'boolean)
4176 (defcustom org-cycle-open-archived-trees nil
4177 "Non-nil means `org-cycle' will open archived trees.
4178 An archived tree is a tree marked with the tag ARCHIVE.
4179 When nil, archived trees will stay folded. You can still open them with
4180 normal outline commands like `show-all', but not with the cycling commands."
4181 :group 'org-archive
4182 :group 'org-cycle
4183 :type 'boolean)
4185 (defcustom org-sparse-tree-open-archived-trees nil
4186 "Non-nil means sparse tree construction shows matches in archived trees.
4187 When nil, matches in these trees are highlighted, but the trees are kept in
4188 collapsed state."
4189 :group 'org-archive
4190 :group 'org-sparse-trees
4191 :type 'boolean)
4193 (defun org-cycle-hide-archived-subtrees (state)
4194 "Re-hide all archived subtrees after a visibility state change."
4195 (when (and (not org-cycle-open-archived-trees)
4196 (not (memq state '(overview folded))))
4197 (save-excursion
4198 (let* ((globalp (memq state '(contents all)))
4199 (beg (if globalp (point-min) (point)))
4200 (end (if globalp (point-max) (org-end-of-subtree t))))
4201 (org-hide-archived-subtrees beg end)
4202 (goto-char beg)
4203 (if (looking-at (concat ".*:" org-archive-tag ":"))
4204 (message "%s" (substitute-command-keys
4205 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4207 (defun org-force-cycle-archived ()
4208 "Cycle subtree even if it is archived."
4209 (interactive)
4210 (setq this-command 'org-cycle)
4211 (let ((org-cycle-open-archived-trees t))
4212 (call-interactively 'org-cycle)))
4214 (defun org-hide-archived-subtrees (beg end)
4215 "Re-hide all archived subtrees after a visibility state change."
4216 (save-excursion
4217 (let* ((re (concat ":" org-archive-tag ":")))
4218 (goto-char beg)
4219 (while (re-search-forward re end t)
4220 (when (org-on-heading-p)
4221 (org-flag-subtree t)
4222 (org-end-of-subtree t))))))
4224 (defun org-flag-subtree (flag)
4225 (save-excursion
4226 (org-back-to-heading t)
4227 (outline-end-of-heading)
4228 (outline-flag-region (point)
4229 (progn (org-end-of-subtree t) (point))
4230 flag)))
4232 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4234 (eval-and-compile
4235 (org-autoload "org-archive"
4236 '(org-add-archive-files org-archive-subtree
4237 org-archive-to-archive-sibling org-toggle-archive-tag
4238 org-archive-subtree-default
4239 org-archive-subtree-default-with-confirmation)))
4241 ;; Autoload Column View Code
4243 (declare-function org-columns-number-to-string "org-colview")
4244 (declare-function org-columns-get-format-and-top-level "org-colview")
4245 (declare-function org-columns-compute "org-colview")
4247 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4248 '(org-columns-number-to-string org-columns-get-format-and-top-level
4249 org-columns-compute org-agenda-columns org-columns-remove-overlays
4250 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4252 ;; Autoload ID code
4254 (declare-function org-id-store-link "org-id")
4255 (declare-function org-id-locations-load "org-id")
4256 (declare-function org-id-locations-save "org-id")
4257 (defvar org-id-track-globally)
4258 (org-autoload "org-id"
4259 '(org-id-get-create org-id-new org-id-copy org-id-get
4260 org-id-get-with-outline-path-completion
4261 org-id-get-with-outline-drilling org-id-store-link
4262 org-id-goto org-id-find org-id-store-link))
4264 ;; Autoload Plotting Code
4266 (org-autoload "org-plot"
4267 '(org-plot/gnuplot))
4269 ;;; Variables for pre-computed regular expressions, all buffer local
4271 (defvar org-drawer-regexp nil
4272 "Matches first line of a hidden block.")
4273 (make-variable-buffer-local 'org-drawer-regexp)
4274 (defvar org-todo-regexp nil
4275 "Matches any of the TODO state keywords.")
4276 (make-variable-buffer-local 'org-todo-regexp)
4277 (defvar org-not-done-regexp nil
4278 "Matches any of the TODO state keywords except the last one.")
4279 (make-variable-buffer-local 'org-not-done-regexp)
4280 (defvar org-not-done-heading-regexp nil
4281 "Matches a TODO headline that is not done.")
4282 (make-variable-buffer-local 'org-not-done-regexp)
4283 (defvar org-todo-line-regexp nil
4284 "Matches a headline and puts TODO state into group 2 if present.")
4285 (make-variable-buffer-local 'org-todo-line-regexp)
4286 (defvar org-complex-heading-regexp nil
4287 "Matches a headline and puts everything into groups:
4288 group 1: the stars
4289 group 2: The todo keyword, maybe
4290 group 3: Priority cookie
4291 group 4: True headline
4292 group 5: Tags")
4293 (make-variable-buffer-local 'org-complex-heading-regexp)
4294 (defvar org-complex-heading-regexp-format nil
4295 "Printf format to make regexp to match an exact headline.
4296 This regexp will match the headline of any node which has the
4297 exact headline text that is put into the format, but may have any
4298 TODO state, priority and tags.")
4299 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4300 (defvar org-todo-line-tags-regexp nil
4301 "Matches a headline and puts TODO state into group 2 if present.
4302 Also put tags into group 4 if tags are present.")
4303 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4304 (defvar org-ds-keyword-length 12
4305 "Maximum length of the Deadline and SCHEDULED keywords.")
4306 (make-variable-buffer-local 'org-ds-keyword-length)
4307 (defvar org-deadline-regexp nil
4308 "Matches the DEADLINE keyword.")
4309 (make-variable-buffer-local 'org-deadline-regexp)
4310 (defvar org-deadline-time-regexp nil
4311 "Matches the DEADLINE keyword together with a time stamp.")
4312 (make-variable-buffer-local 'org-deadline-time-regexp)
4313 (defvar org-deadline-line-regexp nil
4314 "Matches the DEADLINE keyword and the rest of the line.")
4315 (make-variable-buffer-local 'org-deadline-line-regexp)
4316 (defvar org-scheduled-regexp nil
4317 "Matches the SCHEDULED keyword.")
4318 (make-variable-buffer-local 'org-scheduled-regexp)
4319 (defvar org-scheduled-time-regexp nil
4320 "Matches the SCHEDULED keyword together with a time stamp.")
4321 (make-variable-buffer-local 'org-scheduled-time-regexp)
4322 (defvar org-closed-time-regexp nil
4323 "Matches the CLOSED keyword together with a time stamp.")
4324 (make-variable-buffer-local 'org-closed-time-regexp)
4326 (defvar org-keyword-time-regexp nil
4327 "Matches any of the 4 keywords, together with the time stamp.")
4328 (make-variable-buffer-local 'org-keyword-time-regexp)
4329 (defvar org-keyword-time-not-clock-regexp nil
4330 "Matches any of the 3 keywords, together with the time stamp.")
4331 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4332 (defvar org-maybe-keyword-time-regexp nil
4333 "Matches a timestamp, possibly preceded by a keyword.")
4334 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4335 (defvar org-planning-or-clock-line-re nil
4336 "Matches a line with planning or clock info.")
4337 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4338 (defvar org-all-time-keywords nil
4339 "List of time keywords.")
4340 (make-variable-buffer-local 'org-all-time-keywords)
4342 (defconst org-plain-time-of-day-regexp
4343 (concat
4344 "\\(\\<[012]?[0-9]"
4345 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4346 "\\(--?"
4347 "\\(\\<[012]?[0-9]"
4348 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4349 "\\)?")
4350 "Regular expression to match a plain time or time range.
4351 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4352 groups carry important information:
4353 0 the full match
4354 1 the first time, range or not
4355 8 the second time, if it is a range.")
4357 (defconst org-plain-time-extension-regexp
4358 (concat
4359 "\\(\\<[012]?[0-9]"
4360 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4361 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4362 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4363 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4364 groups carry important information:
4365 0 the full match
4366 7 hours of duration
4367 9 minutes of duration")
4369 (defconst org-stamp-time-of-day-regexp
4370 (concat
4371 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4372 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4373 "\\(--?"
4374 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4375 "Regular expression to match a timestamp time or time range.
4376 After a match, the following groups carry important information:
4377 0 the full match
4378 1 date plus weekday, for back referencing to make sure both times are on the same day
4379 2 the first time, range or not
4380 4 the second time, if it is a range.")
4382 (defconst org-startup-options
4383 '(("fold" org-startup-folded t)
4384 ("overview" org-startup-folded t)
4385 ("nofold" org-startup-folded nil)
4386 ("showall" org-startup-folded nil)
4387 ("showeverything" org-startup-folded showeverything)
4388 ("content" org-startup-folded content)
4389 ("indent" org-startup-indented t)
4390 ("noindent" org-startup-indented nil)
4391 ("hidestars" org-hide-leading-stars t)
4392 ("showstars" org-hide-leading-stars nil)
4393 ("odd" org-odd-levels-only t)
4394 ("oddeven" org-odd-levels-only nil)
4395 ("align" org-startup-align-all-tables t)
4396 ("noalign" org-startup-align-all-tables nil)
4397 ("inlineimages" org-startup-with-inline-images t)
4398 ("noinlineimages" org-startup-with-inline-images nil)
4399 ("customtime" org-display-custom-times t)
4400 ("logdone" org-log-done time)
4401 ("lognotedone" org-log-done note)
4402 ("nologdone" org-log-done nil)
4403 ("lognoteclock-out" org-log-note-clock-out t)
4404 ("nolognoteclock-out" org-log-note-clock-out nil)
4405 ("logrepeat" org-log-repeat state)
4406 ("lognoterepeat" org-log-repeat note)
4407 ("nologrepeat" org-log-repeat nil)
4408 ("logreschedule" org-log-reschedule time)
4409 ("lognotereschedule" org-log-reschedule note)
4410 ("nologreschedule" org-log-reschedule nil)
4411 ("logredeadline" org-log-redeadline time)
4412 ("lognoteredeadline" org-log-redeadline note)
4413 ("nologredeadline" org-log-redeadline nil)
4414 ("logrefile" org-log-refile time)
4415 ("lognoterefile" org-log-refile note)
4416 ("nologrefile" org-log-refile nil)
4417 ("fninline" org-footnote-define-inline t)
4418 ("nofninline" org-footnote-define-inline nil)
4419 ("fnlocal" org-footnote-section nil)
4420 ("fnauto" org-footnote-auto-label t)
4421 ("fnprompt" org-footnote-auto-label nil)
4422 ("fnconfirm" org-footnote-auto-label confirm)
4423 ("fnplain" org-footnote-auto-label plain)
4424 ("fnadjust" org-footnote-auto-adjust t)
4425 ("nofnadjust" org-footnote-auto-adjust nil)
4426 ("constcgs" constants-unit-system cgs)
4427 ("constSI" constants-unit-system SI)
4428 ("noptag" org-tag-persistent-alist nil)
4429 ("hideblocks" org-hide-block-startup t)
4430 ("nohideblocks" org-hide-block-startup nil)
4431 ("beamer" org-startup-with-beamer-mode t)
4432 ("entitiespretty" org-pretty-entities t)
4433 ("entitiesplain" org-pretty-entities nil))
4434 "Variable associated with STARTUP options for org-mode.
4435 Each element is a list of three items: The startup options as written
4436 in the #+STARTUP line, the corresponding variable, and the value to
4437 set this variable to if the option is found. An optional forth element PUSH
4438 means to push this value onto the list in the variable.")
4440 (defun org-set-regexps-and-options ()
4441 "Precompute regular expressions for current buffer."
4442 (when (eq major-mode 'org-mode)
4443 (org-set-local 'org-todo-kwd-alist nil)
4444 (org-set-local 'org-todo-key-alist nil)
4445 (org-set-local 'org-todo-key-trigger nil)
4446 (org-set-local 'org-todo-keywords-1 nil)
4447 (org-set-local 'org-done-keywords nil)
4448 (org-set-local 'org-todo-heads nil)
4449 (org-set-local 'org-todo-sets nil)
4450 (org-set-local 'org-todo-log-states nil)
4451 (org-set-local 'org-file-properties nil)
4452 (org-set-local 'org-file-tags nil)
4453 (let ((re (org-make-options-regexp
4454 '("CATEGORY" "TODO" "COLUMNS"
4455 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4456 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4457 "OPTIONS")
4458 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4459 (splitre "[ \t]+")
4460 (scripts org-use-sub-superscripts)
4461 kwds kws0 kwsa key log value cat arch tags const links hw dws
4462 tail sep kws1 prio props ftags drawers beamer-p
4463 ext-setup-or-nil setup-contents (start 0))
4464 (save-excursion
4465 (save-restriction
4466 (widen)
4467 (goto-char (point-min))
4468 (while (or (and ext-setup-or-nil
4469 (string-match re ext-setup-or-nil start)
4470 (setq start (match-end 0)))
4471 (and (setq ext-setup-or-nil nil start 0)
4472 (re-search-forward re nil t)))
4473 (setq key (upcase (match-string 1 ext-setup-or-nil))
4474 value (org-match-string-no-properties 2 ext-setup-or-nil))
4475 (if (stringp value) (setq value (org-trim value)))
4476 (cond
4477 ((equal key "CATEGORY")
4478 (setq cat value))
4479 ((member key '("SEQ_TODO" "TODO"))
4480 (push (cons 'sequence (org-split-string value splitre)) kwds))
4481 ((equal key "TYP_TODO")
4482 (push (cons 'type (org-split-string value splitre)) kwds))
4483 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4484 ;; general TODO-like setup
4485 (push (cons (intern (downcase (match-string 1 key)))
4486 (org-split-string value splitre)) kwds))
4487 ((equal key "TAGS")
4488 (setq tags (append tags (if tags '("\\n") nil)
4489 (org-split-string value splitre))))
4490 ((equal key "COLUMNS")
4491 (org-set-local 'org-columns-default-format value))
4492 ((equal key "LINK")
4493 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4494 (push (cons (match-string 1 value)
4495 (org-trim (match-string 2 value)))
4496 links)))
4497 ((equal key "PRIORITIES")
4498 (setq prio (org-split-string value " +")))
4499 ((equal key "PROPERTY")
4500 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4501 (push (cons (match-string 1 value) (match-string 2 value))
4502 props)))
4503 ((equal key "FILETAGS")
4504 (when (string-match "\\S-" value)
4505 (setq ftags
4506 (append
4507 ftags
4508 (apply 'append
4509 (mapcar (lambda (x) (org-split-string x ":"))
4510 (org-split-string value)))))))
4511 ((equal key "DRAWERS")
4512 (setq drawers (org-split-string value splitre)))
4513 ((equal key "CONSTANTS")
4514 (setq const (append const (org-split-string value splitre))))
4515 ((equal key "STARTUP")
4516 (let ((opts (org-split-string value splitre))
4517 l var val)
4518 (while (setq l (pop opts))
4519 (when (setq l (assoc l org-startup-options))
4520 (setq var (nth 1 l) val (nth 2 l))
4521 (if (not (nth 3 l))
4522 (set (make-local-variable var) val)
4523 (if (not (listp (symbol-value var)))
4524 (set (make-local-variable var) nil))
4525 (set (make-local-variable var) (symbol-value var))
4526 (add-to-list var val))))))
4527 ((equal key "ARCHIVE")
4528 (setq arch value)
4529 (remove-text-properties 0 (length arch)
4530 '(face t fontified t) arch))
4531 ((equal key "LATEX_CLASS")
4532 (setq beamer-p (equal value "beamer")))
4533 ((equal key "OPTIONS")
4534 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4535 (setq scripts (read (match-string 2 value)))))
4536 ((equal key "SETUPFILE")
4537 (setq setup-contents (org-file-contents
4538 (expand-file-name
4539 (org-remove-double-quotes value))
4540 'noerror))
4541 (if (not ext-setup-or-nil)
4542 (setq ext-setup-or-nil setup-contents start 0)
4543 (setq ext-setup-or-nil
4544 (concat (substring ext-setup-or-nil 0 start)
4545 "\n" setup-contents "\n"
4546 (substring ext-setup-or-nil start)))))))
4547 ;; search for property blocks
4548 (goto-char (point-min))
4549 (while (re-search-forward org-block-regexp nil t)
4550 (when (equal "PROPERTY" (upcase (match-string 1)))
4551 (setq value (replace-regexp-in-string
4552 "[\n\r]" " " (match-string 4)))
4553 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4554 (push (cons (match-string 1 value) (match-string 2 value))
4555 props))))))
4556 (org-set-local 'org-use-sub-superscripts scripts)
4557 (when cat
4558 (org-set-local 'org-category (intern cat))
4559 (push (cons "CATEGORY" cat) props))
4560 (when prio
4561 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4562 (setq prio (mapcar 'string-to-char prio))
4563 (org-set-local 'org-highest-priority (nth 0 prio))
4564 (org-set-local 'org-lowest-priority (nth 1 prio))
4565 (org-set-local 'org-default-priority (nth 2 prio)))
4566 (and props (org-set-local 'org-file-properties (nreverse props)))
4567 (and ftags (org-set-local 'org-file-tags
4568 (mapcar 'org-add-prop-inherited ftags)))
4569 (and drawers (org-set-local 'org-drawers drawers))
4570 (and arch (org-set-local 'org-archive-location arch))
4571 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4572 ;; Process the TODO keywords
4573 (unless kwds
4574 ;; Use the global values as if they had been given locally.
4575 (setq kwds (default-value 'org-todo-keywords))
4576 (if (stringp (car kwds))
4577 (setq kwds (list (cons org-todo-interpretation
4578 (default-value 'org-todo-keywords)))))
4579 (setq kwds (reverse kwds)))
4580 (setq kwds (nreverse kwds))
4581 (let (inter kws kw)
4582 (while (setq kws (pop kwds))
4583 (let ((kws (or
4584 (run-hook-with-args-until-success
4585 'org-todo-setup-filter-hook kws)
4586 kws)))
4587 (setq inter (pop kws) sep (member "|" kws)
4588 kws0 (delete "|" (copy-sequence kws))
4589 kwsa nil
4590 kws1 (mapcar
4591 (lambda (x)
4592 ;; 1 2
4593 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4594 (progn
4595 (setq kw (match-string 1 x)
4596 key (and (match-end 2) (match-string 2 x))
4597 log (org-extract-log-state-settings x))
4598 (push (cons kw (and key (string-to-char key))) kwsa)
4599 (and log (push log org-todo-log-states))
4601 (error "Invalid TODO keyword %s" x)))
4602 kws0)
4603 kwsa (if kwsa (append '((:startgroup))
4604 (nreverse kwsa)
4605 '((:endgroup))))
4606 hw (car kws1)
4607 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4608 tail (list inter hw (car dws) (org-last dws))))
4609 (add-to-list 'org-todo-heads hw 'append)
4610 (push kws1 org-todo-sets)
4611 (setq org-done-keywords (append org-done-keywords dws nil))
4612 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4613 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4614 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4615 (setq org-todo-sets (nreverse org-todo-sets)
4616 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4617 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4618 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4619 ;; Process the constants
4620 (when const
4621 (let (e cst)
4622 (while (setq e (pop const))
4623 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4624 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4625 (setq org-table-formula-constants-local cst)))
4627 ;; Process the tags.
4628 (when tags
4629 (let (e tgs)
4630 (while (setq e (pop tags))
4631 (cond
4632 ((equal e "{") (push '(:startgroup) tgs))
4633 ((equal e "}") (push '(:endgroup) tgs))
4634 ((equal e "\\n") (push '(:newline) tgs))
4635 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4636 (push (cons (match-string 1 e)
4637 (string-to-char (match-string 2 e)))
4638 tgs))
4639 (t (push (list e) tgs))))
4640 (org-set-local 'org-tag-alist nil)
4641 (while (setq e (pop tgs))
4642 (or (and (stringp (car e))
4643 (assoc (car e) org-tag-alist))
4644 (push e org-tag-alist)))))
4646 ;; Compute the regular expressions and other local variables.
4647 ;; Using `org-outline-regexp-bol' would complicate them much,
4648 ;; because of the fixed white space at the end of that string.
4649 (if (not org-done-keywords)
4650 (setq org-done-keywords (and org-todo-keywords-1
4651 (list (org-last org-todo-keywords-1)))))
4652 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4653 (length org-scheduled-string)
4654 (length org-clock-string)
4655 (length org-closed-string)))
4656 org-drawer-regexp
4657 (concat "^[ \t]*:\\("
4658 (mapconcat 'regexp-quote org-drawers "\\|")
4659 "\\):[ \t]*$")
4660 org-not-done-keywords
4661 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4662 org-todo-regexp
4663 (concat "\\("
4664 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4665 "\\)")
4666 org-not-done-regexp
4667 (concat "\\("
4668 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4669 "\\)")
4670 org-not-done-heading-regexp
4671 (format org-heading-keyword-regexp-format org-not-done-regexp)
4672 org-todo-line-regexp
4673 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4674 org-complex-heading-regexp
4675 (concat "^\\(\\*+\\)"
4676 "\\(?: +" org-todo-regexp "\\)?"
4677 "\\(?: +\\(\\[#.\\]\\)\\)?"
4678 "\\(?: +\\(.*?\\)\\)?"
4679 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4680 "[ \t]*$")
4681 org-complex-heading-regexp-format
4682 (concat "^\\(\\*+\\)"
4683 "\\(?: +" org-todo-regexp "\\)?"
4684 "\\(?: +\\(\\[#.\\]\\)\\)?"
4685 "\\(?: +"
4686 ;; Stats cookies can be sticked to body.
4687 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4688 "\\(%s\\)"
4689 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4690 "\\)"
4691 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4692 "[ \t]*$")
4693 org-todo-line-tags-regexp
4694 (concat "^\\(\\*+\\)"
4695 "\\(?: +" org-todo-regexp "\\)?"
4696 "\\(?: +\\(.*?\\)\\)?"
4697 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4698 "[ \t]*$")
4699 org-deadline-regexp (concat "\\<" org-deadline-string)
4700 org-deadline-time-regexp
4701 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4702 org-deadline-line-regexp
4703 (concat "\\<\\(" org-deadline-string "\\).*")
4704 org-scheduled-regexp
4705 (concat "\\<" org-scheduled-string)
4706 org-scheduled-time-regexp
4707 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4708 org-closed-time-regexp
4709 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4710 org-keyword-time-regexp
4711 (concat "\\<\\(" org-scheduled-string
4712 "\\|" org-deadline-string
4713 "\\|" org-closed-string
4714 "\\|" org-clock-string "\\)"
4715 " *[[<]\\([^]>]+\\)[]>]")
4716 org-keyword-time-not-clock-regexp
4717 (concat "\\<\\(" org-scheduled-string
4718 "\\|" org-deadline-string
4719 "\\|" org-closed-string
4720 "\\)"
4721 " *[[<]\\([^]>]+\\)[]>]")
4722 org-maybe-keyword-time-regexp
4723 (concat "\\(\\<\\(" org-scheduled-string
4724 "\\|" org-deadline-string
4725 "\\|" org-closed-string
4726 "\\|" org-clock-string "\\)\\)?"
4727 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4728 org-planning-or-clock-line-re
4729 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4730 "\\|" org-deadline-string
4731 "\\|" org-closed-string "\\|" org-clock-string
4732 "\\)\\>\\)")
4733 org-all-time-keywords
4734 (mapcar (lambda (w) (substring w 0 -1))
4735 (list org-scheduled-string org-deadline-string
4736 org-clock-string org-closed-string))
4738 (org-compute-latex-and-specials-regexp)
4739 (org-set-font-lock-defaults))))
4741 (defun org-file-contents (file &optional noerror)
4742 "Return the contents of FILE, as a string."
4743 (if (or (not file)
4744 (not (file-readable-p file)))
4745 (if noerror
4746 (progn
4747 (message "Cannot read file \"%s\"" file)
4748 (ding) (sit-for 2)
4750 (error "Cannot read file \"%s\"" file))
4751 (with-temp-buffer
4752 (insert-file-contents file)
4753 (buffer-string))))
4755 (defun org-extract-log-state-settings (x)
4756 "Extract the log state setting from a TODO keyword string.
4757 This will extract info from a string like \"WAIT(w@/!)\"."
4758 (let (kw key log1 log2)
4759 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4760 (setq kw (match-string 1 x)
4761 key (and (match-end 2) (match-string 2 x))
4762 log1 (and (match-end 3) (match-string 3 x))
4763 log2 (and (match-end 4) (match-string 4 x)))
4764 (and (or log1 log2)
4765 (list kw
4766 (and log1 (if (equal log1 "!") 'time 'note))
4767 (and log2 (if (equal log2 "!") 'time 'note)))))))
4769 (defun org-remove-keyword-keys (list)
4770 "Remove a pair of parenthesis at the end of each string in LIST."
4771 (mapcar (lambda (x)
4772 (if (string-match "(.*)$" x)
4773 (substring x 0 (match-beginning 0))
4775 list))
4777 (defun org-assign-fast-keys (alist)
4778 "Assign fast keys to a keyword-key alist.
4779 Respect keys that are already there."
4780 (let (new e (alt ?0))
4781 (while (setq e (pop alist))
4782 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4783 (cdr e)) ;; Key already assigned.
4784 (push e new)
4785 (let ((clist (string-to-list (downcase (car e))))
4786 (used (append new alist)))
4787 (when (= (car clist) ?@)
4788 (pop clist))
4789 (while (and clist (rassoc (car clist) used))
4790 (pop clist))
4791 (unless clist
4792 (while (rassoc alt used)
4793 (incf alt)))
4794 (push (cons (car e) (or (car clist) alt)) new))))
4795 (nreverse new)))
4797 ;;; Some variables used in various places
4799 (defvar org-window-configuration nil
4800 "Used in various places to store a window configuration.")
4801 (defvar org-selected-window nil
4802 "Used in various places to store a window configuration.")
4803 (defvar org-finish-function nil
4804 "Function to be called when `C-c C-c' is used.
4805 This is for getting out of special buffers like remember.")
4808 ;; FIXME: Occasionally check by commenting these, to make sure
4809 ;; no other functions uses these, forgetting to let-bind them.
4810 (defvar entry)
4811 (defvar last-state)
4812 (defvar date)
4814 ;; Defined somewhere in this file, but used before definition.
4815 (defvar org-entities) ;; defined in org-entities.el
4816 (defvar org-struct-menu)
4817 (defvar org-org-menu)
4818 (defvar org-tbl-menu)
4820 ;;;; Define the Org-mode
4822 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4823 (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"))
4826 ;; We use a before-change function to check if a table might need
4827 ;; an update.
4828 (defvar org-table-may-need-update t
4829 "Indicates that a table might need an update.
4830 This variable is set by `org-before-change-function'.
4831 `org-table-align' sets it back to nil.")
4832 (defun org-before-change-function (beg end)
4833 "Every change indicates that a table might need an update."
4834 (setq org-table-may-need-update t))
4835 (defvar org-mode-map)
4836 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4837 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4838 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4839 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4840 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4841 (defvar org-table-buffer-is-an nil)
4843 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
4844 ;; some places -- e.g. see the macro org-with-limited-levels.
4846 ;; In Org buffers, the value of `outline-regexp' is that of
4847 ;; `org-outline-regexp'. The only function still directly relying on
4848 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
4849 ;; job when `orgstruct-mode' is active.
4850 (defvar org-outline-regexp "\\*+ "
4851 "Regexp to match Org headlines.")
4852 (defconst org-outline-regexp-bol "^\\*+ "
4853 "Regexp to match Org headlines.
4854 This is similar to `org-outline-regexp' but additionally makes
4855 sure that we are at the beginning of the line.")
4857 (defconst org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4858 "Matches an headline, putting stars and text into groups.
4859 Stars are put in group 1 and the trimmed body in group 2.")
4860 (defconst org-heading-keyword-regexp-format
4861 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4862 "Printf format for a regexp matching an headline with some keyword.
4863 This regexp will match the headline of any node which has the
4864 exact keyword that is put into the format. The keyword isn't in
4865 any group by default, but the stars and the body are.")
4866 (defconst org-heading-keyword-maybe-regexp-format
4867 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4868 "Printf format for a regexp matching an headline, possibly with some keyword.
4869 This regexp can match any headline with the specified keyword, or
4870 without a keyword. The keyword isn't in any group by default,
4871 but the stars and the body are.")
4873 ;;;###autoload
4874 (define-derived-mode org-mode outline-mode "Org"
4875 "Outline-based notes management and organizer, alias
4876 \"Carsten's outline-mode for keeping track of everything.\"
4878 Org-mode develops organizational tasks around a NOTES file which
4879 contains information about projects as plain text. Org-mode is
4880 implemented on top of outline-mode, which is ideal to keep the content
4881 of large files well structured. It supports ToDo items, deadlines and
4882 time stamps, which magically appear in the diary listing of the Emacs
4883 calendar. Tables are easily created with a built-in table editor.
4884 Plain text URL-like links connect to websites, emails (VM), Usenet
4885 messages (Gnus), BBDB entries, and any files related to the project.
4886 For printing and sharing of notes, an Org-mode file (or a part of it)
4887 can be exported as a structured ASCII or HTML file.
4889 The following commands are available:
4891 \\{org-mode-map}"
4893 ;; Get rid of Outline menus, they are not needed
4894 ;; Need to do this here because define-derived-mode sets up
4895 ;; the keymap so late. Still, it is a waste to call this each time
4896 ;; we switch another buffer into org-mode.
4897 (if (featurep 'xemacs)
4898 (when (boundp 'outline-mode-menu-heading)
4899 ;; Assume this is Greg's port, it uses easymenu
4900 (easy-menu-remove outline-mode-menu-heading)
4901 (easy-menu-remove outline-mode-menu-show)
4902 (easy-menu-remove outline-mode-menu-hide))
4903 (define-key org-mode-map [menu-bar headings] 'undefined)
4904 (define-key org-mode-map [menu-bar hide] 'undefined)
4905 (define-key org-mode-map [menu-bar show] 'undefined))
4907 (org-load-modules-maybe)
4908 (easy-menu-add org-org-menu)
4909 (easy-menu-add org-tbl-menu)
4910 (org-install-agenda-files-menu)
4911 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4912 (add-to-invisibility-spec '(org-cwidth))
4913 (add-to-invisibility-spec '(org-hide-block . t))
4914 (when (featurep 'xemacs)
4915 (org-set-local 'line-move-ignore-invisible t))
4916 (org-set-local 'outline-regexp org-outline-regexp)
4917 (org-set-local 'outline-level 'org-outline-level)
4918 (setq bidi-paragraph-direction 'left-to-right)
4919 (when (and org-ellipsis
4920 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4921 (fboundp 'make-glyph-code))
4922 (unless org-display-table
4923 (setq org-display-table (make-display-table)))
4924 (set-display-table-slot
4925 org-display-table 4
4926 (vconcat (mapcar
4927 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4928 org-ellipsis)))
4929 (if (stringp org-ellipsis) org-ellipsis "..."))))
4930 (setq buffer-display-table org-display-table))
4931 (org-set-regexps-and-options)
4932 (when (and org-tag-faces (not org-tags-special-faces-re))
4933 ;; tag faces set outside customize.... force initialization.
4934 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4935 ;; Calc embedded
4936 (org-set-local 'calc-embedded-open-mode "# ")
4937 (modify-syntax-entry ?@ "w")
4938 (if org-startup-truncated (setq truncate-lines t))
4939 (org-set-local 'font-lock-unfontify-region-function
4940 'org-unfontify-region)
4941 ;; Activate before-change-function
4942 (org-set-local 'org-table-may-need-update t)
4943 (org-add-hook 'before-change-functions 'org-before-change-function nil
4944 'local)
4945 ;; Check for running clock before killing a buffer
4946 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4947 ;; Paragraphs and auto-filling
4948 (org-set-autofill-regexps)
4949 (setq indent-line-function 'org-indent-line-function)
4950 (org-update-radio-target-regexp)
4951 ;; Beginning/end of defun
4952 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
4953 (org-set-local 'end-of-defun-function 'org-end-of-defun)
4954 ;; Next error for sparse trees
4955 (org-set-local 'next-error-function 'org-occur-next-match)
4956 ;; Make sure dependence stuff works reliably, even for users who set it
4957 ;; too late :-(
4958 (if org-enforce-todo-dependencies
4959 (add-hook 'org-blocker-hook
4960 'org-block-todo-from-children-or-siblings-or-parent)
4961 (remove-hook 'org-blocker-hook
4962 'org-block-todo-from-children-or-siblings-or-parent))
4963 (if org-enforce-todo-checkbox-dependencies
4964 (add-hook 'org-blocker-hook
4965 'org-block-todo-from-checkboxes)
4966 (remove-hook 'org-blocker-hook
4967 'org-block-todo-from-checkboxes))
4969 ;; Comment characters
4970 (org-set-local 'comment-start "#")
4971 (org-set-local 'comment-padding " ")
4973 ;; Align options lines
4974 (org-set-local
4975 'align-mode-rules-list
4976 '((org-in-buffer-settings
4977 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4978 (modes . '(org-mode)))))
4980 ;; Imenu
4981 (org-set-local 'imenu-create-index-function
4982 'org-imenu-get-tree)
4984 ;; Make isearch reveal context
4985 (if (or (featurep 'xemacs)
4986 (not (boundp 'outline-isearch-open-invisible-function)))
4987 ;; Emacs 21 and XEmacs make use of the hook
4988 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4989 ;; Emacs 22 deals with this through a special variable
4990 (org-set-local 'outline-isearch-open-invisible-function
4991 (lambda (&rest ignore) (org-show-context 'isearch))))
4993 ;; Turn on org-beamer-mode?
4994 (and org-startup-with-beamer-mode (org-beamer-mode 1))
4996 ;; Setup the pcomplete hooks
4997 (set (make-local-variable 'pcomplete-command-completion-function)
4998 'org-pcomplete-initial)
4999 (set (make-local-variable 'pcomplete-command-name-function)
5000 'org-command-at-point)
5001 (set (make-local-variable 'pcomplete-default-completion-function)
5002 'ignore)
5003 (set (make-local-variable 'pcomplete-parse-arguments-function)
5004 'org-parse-arguments)
5005 (set (make-local-variable 'pcomplete-termination-string) "")
5006 (set (make-local-variable 'face-remapping-alist)
5007 '((default org-default)))
5009 ;; If empty file that did not turn on org-mode automatically, make it to.
5010 (if (and org-insert-mode-line-in-empty-file
5011 (org-called-interactively-p 'any)
5012 (= (point-min) (point-max)))
5013 (insert "# -*- mode: org -*-\n\n"))
5014 (unless org-inhibit-startup
5015 (when org-startup-align-all-tables
5016 (let ((bmp (buffer-modified-p)))
5017 (org-table-map-tables 'org-table-align 'quietly)
5018 (set-buffer-modified-p bmp)))
5019 (when org-startup-with-inline-images
5020 (org-display-inline-images))
5021 (when org-startup-indented
5022 (require 'org-indent)
5023 (org-indent-mode 1))
5024 (unless org-inhibit-startup-visibility-stuff
5025 (org-set-startup-visibility))))
5027 (when (fboundp 'abbrev-table-put)
5028 (abbrev-table-put org-mode-abbrev-table
5029 :parents (list text-mode-abbrev-table)))
5031 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5033 (defun org-current-time ()
5034 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5035 (if (> (car org-time-stamp-rounding-minutes) 1)
5036 (let ((r (car org-time-stamp-rounding-minutes))
5037 (time (decode-time)))
5038 (apply 'encode-time
5039 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5040 (nthcdr 2 time))))
5041 (current-time)))
5043 (defun org-today ()
5044 "Return today date, considering `org-extend-today-until'."
5045 (time-to-days
5046 (time-subtract (current-time)
5047 (list 0 (* 3600 org-extend-today-until) 0))))
5049 ;;;; Font-Lock stuff, including the activators
5051 (defvar org-mouse-map (make-sparse-keymap))
5052 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5053 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5054 (when org-mouse-1-follows-link
5055 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5056 (when org-tab-follows-link
5057 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5058 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5060 (require 'font-lock)
5062 (defconst org-non-link-chars "]\t\n\r<>")
5063 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5064 "shell" "elisp" "doi" "message"))
5065 (defvar org-link-types-re nil
5066 "Matches a link that has a url-like prefix like \"http:\"")
5067 (defvar org-link-re-with-space nil
5068 "Matches a link with spaces, optional angular brackets around it.")
5069 (defvar org-link-re-with-space2 nil
5070 "Matches a link with spaces, optional angular brackets around it.")
5071 (defvar org-link-re-with-space3 nil
5072 "Matches a link with spaces, only for internal part in bracket links.")
5073 (defvar org-angle-link-re nil
5074 "Matches link with angular brackets, spaces are allowed.")
5075 (defvar org-plain-link-re nil
5076 "Matches plain link, without spaces.")
5077 (defvar org-bracket-link-regexp nil
5078 "Matches a link in double brackets.")
5079 (defvar org-bracket-link-analytic-regexp nil
5080 "Regular expression used to analyze links.
5081 Here is what the match groups contain after a match:
5082 1: http:
5083 2: http
5084 3: path
5085 4: [desc]
5086 5: desc")
5087 (defvar org-bracket-link-analytic-regexp++ nil
5088 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5089 (defvar org-any-link-re nil
5090 "Regular expression matching any link.")
5092 (defcustom org-match-sexp-depth 3
5093 "Number of stacked braces for sub/superscript matching.
5094 This has to be set before loading org.el to be effective."
5095 :group 'org-export-translation ; ??????????????????????????/
5096 :type 'integer)
5098 (defun org-create-multibrace-regexp (left right n)
5099 "Create a regular expression which will match a balanced sexp.
5100 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5101 as single character strings.
5102 The regexp returned will match the entire expression including the
5103 delimiters. It will also define a single group which contains the
5104 match except for the outermost delimiters. The maximum depth of
5105 stacked delimiters is N. Escaping delimiters is not possible."
5106 (let* ((nothing (concat "[^" left right "]*?"))
5107 (or "\\|")
5108 (re nothing)
5109 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5110 (while (> n 1)
5111 (setq n (1- n)
5112 re (concat re or next)
5113 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5114 (concat left "\\(" re "\\)" right)))
5116 (defvar org-match-substring-regexp
5117 (concat
5118 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5119 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5120 "\\|"
5121 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5122 "\\|"
5123 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5124 "The regular expression matching a sub- or superscript.")
5126 (defvar org-match-substring-with-braces-regexp
5127 (concat
5128 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5129 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5130 "\\)")
5131 "The regular expression matching a sub- or superscript, forcing braces.")
5133 (defun org-make-link-regexps ()
5134 "Update the link regular expressions.
5135 This should be called after the variable `org-link-types' has changed."
5136 (setq org-link-types-re
5137 (concat
5138 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5139 org-link-re-with-space
5140 (concat
5141 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5142 "\\([^" org-non-link-chars " ]"
5143 "[^" org-non-link-chars "]*"
5144 "[^" org-non-link-chars " ]\\)>?")
5145 org-link-re-with-space2
5146 (concat
5147 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5148 "\\([^" org-non-link-chars " ]"
5149 "[^\t\n\r]*"
5150 "[^" org-non-link-chars " ]\\)>?")
5151 org-link-re-with-space3
5152 (concat
5153 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5154 "\\([^" org-non-link-chars " ]"
5155 "[^\t\n\r]*\\)")
5156 org-angle-link-re
5157 (concat
5158 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5159 "\\([^" org-non-link-chars " ]"
5160 "[^" org-non-link-chars "]*"
5161 "\\)>")
5162 org-plain-link-re
5163 (concat
5164 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5165 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5166 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5167 org-bracket-link-regexp
5168 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5169 org-bracket-link-analytic-regexp
5170 (concat
5171 "\\[\\["
5172 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5173 "\\([^]]+\\)"
5174 "\\]"
5175 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5176 "\\]")
5177 org-bracket-link-analytic-regexp++
5178 (concat
5179 "\\[\\["
5180 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5181 "\\([^]]+\\)"
5182 "\\]"
5183 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5184 "\\]")
5185 org-any-link-re
5186 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5187 org-angle-link-re "\\)\\|\\("
5188 org-plain-link-re "\\)")))
5190 (org-make-link-regexps)
5192 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
5193 "Regular expression for fast time stamp matching.")
5194 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?\\)[]>]"
5195 "Regular expression for fast time stamp matching.")
5196 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5197 "Regular expression matching time strings for analysis.
5198 This one does not require the space after the date, so it can be used
5199 on a string that terminates immediately after the date.")
5200 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5201 "Regular expression matching time strings for analysis.")
5202 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5203 "Regular expression matching time stamps, with groups.")
5204 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5205 "Regular expression matching time stamps (also [..]), with groups.")
5206 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5207 "Regular expression matching a time stamp range.")
5208 (defconst org-tr-regexp-both
5209 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5210 "Regular expression matching a time stamp range.")
5211 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5212 org-ts-regexp "\\)?")
5213 "Regular expression matching a time stamp or time stamp range.")
5214 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5215 org-ts-regexp-both "\\)?")
5216 "Regular expression matching a time stamp or time stamp range.
5217 The time stamps may be either active or inactive.")
5219 (defvar org-emph-face nil)
5221 (defun org-do-emphasis-faces (limit)
5222 "Run through the buffer and add overlays to emphasised strings."
5223 (let (rtn a)
5224 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5225 (if (not (= (char-after (match-beginning 3))
5226 (char-after (match-beginning 4))))
5227 (progn
5228 (setq rtn t)
5229 (setq a (assoc (match-string 3) org-emphasis-alist))
5230 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5231 'face
5232 (nth 1 a))
5233 (and (nth 4 a)
5234 (org-remove-flyspell-overlays-in
5235 (match-beginning 0) (match-end 0)))
5236 (add-text-properties (match-beginning 2) (match-end 2)
5237 '(font-lock-multiline t org-emphasis t))
5238 (when org-hide-emphasis-markers
5239 (add-text-properties (match-end 4) (match-beginning 5)
5240 '(invisible org-link))
5241 (add-text-properties (match-beginning 3) (match-end 3)
5242 '(invisible org-link)))))
5243 (backward-char 1))
5244 rtn))
5246 (defun org-emphasize (&optional char)
5247 "Insert or change an emphasis, i.e. a font like bold or italic.
5248 If there is an active region, change that region to a new emphasis.
5249 If there is no region, just insert the marker characters and position
5250 the cursor between them.
5251 CHAR should be either the marker character, or the first character of the
5252 HTML tag associated with that emphasis. If CHAR is a space, the means
5253 to remove the emphasis of the selected region.
5254 If char is not given (for example in an interactive call) it
5255 will be prompted for."
5256 (interactive)
5257 (let ((eal org-emphasis-alist) e det
5258 (erc org-emphasis-regexp-components)
5259 (prompt "")
5260 (string "") beg end move tag c s)
5261 (if (org-region-active-p)
5262 (setq beg (region-beginning) end (region-end)
5263 string (buffer-substring beg end))
5264 (setq move t))
5266 (while (setq e (pop eal))
5267 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5268 c (aref tag 0))
5269 (push (cons c (string-to-char (car e))) det)
5270 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5271 (substring tag 1)))))
5272 (setq det (nreverse det))
5273 (unless char
5274 (message "%s" (concat "Emphasis marker or tag:" prompt))
5275 (setq char (read-char-exclusive)))
5276 (setq char (or (cdr (assoc char det)) char))
5277 (if (equal char ?\ )
5278 (setq s "" move nil)
5279 (unless (assoc (char-to-string char) org-emphasis-alist)
5280 (error "No such emphasis marker: \"%c\"" char))
5281 (setq s (char-to-string char)))
5282 (while (and (> (length string) 1)
5283 (equal (substring string 0 1) (substring string -1))
5284 (assoc (substring string 0 1) org-emphasis-alist))
5285 (setq string (substring string 1 -1)))
5286 (setq string (concat s string s))
5287 (if beg (delete-region beg end))
5288 (unless (or (bolp)
5289 (string-match (concat "[" (nth 0 erc) "\n]")
5290 (char-to-string (char-before (point)))))
5291 (insert " "))
5292 (unless (or (eobp)
5293 (string-match (concat "[" (nth 1 erc) "\n]")
5294 (char-to-string (char-after (point)))))
5295 (insert " ") (backward-char 1))
5296 (insert string)
5297 (and move (backward-char 1))))
5299 (defconst org-nonsticky-props
5300 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5302 (defsubst org-rear-nonsticky-at (pos)
5303 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5305 (defun org-activate-plain-links (limit)
5306 "Run through the buffer and add overlays to links."
5307 (catch 'exit
5308 (let (f)
5309 (if (re-search-forward org-plain-link-re limit t)
5310 (progn
5311 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5312 (setq f (get-text-property (match-beginning 0) 'face))
5313 (if (or (eq f 'org-tag)
5314 (and (listp f) (memq 'org-tag f)))
5316 (add-text-properties (match-beginning 0) (match-end 0)
5317 (list 'mouse-face 'highlight
5318 'face 'org-link
5319 'keymap org-mouse-map))
5320 (org-rear-nonsticky-at (match-end 0)))
5321 t)))))
5323 (defun org-activate-code (limit)
5324 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5325 (progn
5326 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5327 (remove-text-properties (match-beginning 0) (match-end 0)
5328 '(display t invisible t intangible t))
5329 t)))
5331 (defcustom org-src-fontify-natively nil
5332 "When non-nil, fontify code in code blocks."
5333 :type 'boolean
5334 :group 'org-appearance
5335 :group 'org-babel)
5337 (defun org-fontify-meta-lines-and-blocks (limit)
5338 (condition-case nil
5339 (org-fontify-meta-lines-and-blocks-1 limit)
5340 (error (message "org-mode fontification error"))))
5342 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5343 "Fontify #+ lines and blocks, in the correct ways."
5344 (let ((case-fold-search t))
5345 (if (re-search-forward
5346 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5347 limit t)
5348 (let ((beg (match-beginning 0))
5349 (block-start (match-end 0))
5350 (block-end nil)
5351 (lang (match-string 7))
5352 (beg1 (line-beginning-position 2))
5353 (dc1 (downcase (match-string 2)))
5354 (dc3 (downcase (match-string 3)))
5355 end end1 quoting block-type ovl)
5356 (cond
5357 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
5358 ;; a single line of backend-specific content
5359 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5360 (remove-text-properties (match-beginning 0) (match-end 0)
5361 '(display t invisible t intangible t))
5362 (add-text-properties (match-beginning 1) (match-end 3)
5363 '(font-lock-fontified t face org-meta-line))
5364 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5365 '(font-lock-fontified t face org-block))
5366 ; for backend-specific code
5368 ((and (match-end 4) (equal dc3 "begin"))
5369 ;; Truly a block
5370 (setq block-type (downcase (match-string 5))
5371 quoting (member block-type org-protecting-blocks))
5372 (when (re-search-forward
5373 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5374 nil t) ;; on purpose, we look further than LIMIT
5375 (setq end (match-end 0) end1 (1- (match-beginning 0)))
5376 (setq block-end (match-beginning 0))
5377 (when quoting
5378 (remove-text-properties beg end
5379 '(display t invisible t intangible t)))
5380 (add-text-properties
5381 beg end
5382 '(font-lock-fontified t font-lock-multiline t))
5383 (add-text-properties beg beg1 '(face org-meta-line))
5384 (add-text-properties end1 (min (point-max) (1+ end))
5385 '(face org-meta-line)) ; for end_src
5386 (cond
5387 ((and lang (not (string= lang "")) org-src-fontify-natively)
5388 (org-src-font-lock-fontify-block lang block-start block-end)
5389 ;; remove old background overlays
5390 (mapc (lambda (ov)
5391 (if (eq (overlay-get ov 'face) 'org-block-background)
5392 (delete-overlay ov)))
5393 (overlays-at (/ (+ beg1 block-end) 2)))
5394 ;; add a background overlay
5395 (setq ovl (make-overlay beg1 block-end))
5396 (overlay-put ovl 'face 'org-block-background)
5397 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5398 (quoting
5399 (add-text-properties beg1 (min (point-max) (1+ end1))
5400 '(face org-block))) ; end of source block
5401 ((not org-fontify-quote-and-verse-blocks))
5402 ((string= block-type "quote")
5403 (add-text-properties beg1 (1+ end1) '(face org-quote)))
5404 ((string= block-type "verse")
5405 (add-text-properties beg1 (1+ end1) '(face org-verse))))
5406 (add-text-properties beg beg1 '(face org-block-begin-line))
5407 (add-text-properties (1+ end) (1+ end1) '(face org-block-end-line))
5409 ((member dc1 '("title:" "author:" "email:" "date:"))
5410 (add-text-properties
5411 beg (match-end 3)
5412 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5413 '(font-lock-fontified t invisible t)
5414 '(font-lock-fontified t face org-document-info-keyword)))
5415 (add-text-properties
5416 (match-beginning 6) (match-end 6)
5417 (if (string-equal dc1 "title:")
5418 '(font-lock-fontified t face org-document-title)
5419 '(font-lock-fontified t face org-document-info))))
5420 ((not (member (char-after beg) '(?\ ?\t)))
5421 ;; just any other in-buffer setting, but not indented
5422 (add-text-properties
5423 beg (1+ (match-end 0))
5424 '(font-lock-fontified t face org-meta-line))
5426 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
5427 "orgtbl:" "tblfm:" "tblname:" "result:"
5428 "results:" "source:" "srcname:" "call:"
5429 "data:" "header:" "headers:"))
5430 (and (match-end 4) (equal dc3 "attr")))
5431 (add-text-properties
5432 beg (match-end 0)
5433 '(font-lock-fontified t face org-meta-line))
5435 ((member dc3 '(" " ""))
5436 (add-text-properties
5437 beg (match-end 0)
5438 '(font-lock-fontified t face font-lock-comment-face)))
5439 (t nil))))))
5441 (defun org-activate-angle-links (limit)
5442 "Run through the buffer and add overlays to links."
5443 (if (re-search-forward org-angle-link-re limit t)
5444 (progn
5445 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5446 (add-text-properties (match-beginning 0) (match-end 0)
5447 (list 'mouse-face 'highlight
5448 'keymap org-mouse-map))
5449 (org-rear-nonsticky-at (match-end 0))
5450 t)))
5452 (defun org-activate-footnote-links (limit)
5453 "Run through the buffer and add overlays to footnotes."
5454 (let ((fn (org-footnote-next-reference-or-definition limit)))
5455 (when fn
5456 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5457 (org-remove-flyspell-overlays-in beg end)
5458 (add-text-properties beg end
5459 (list 'mouse-face 'highlight
5460 'keymap org-mouse-map
5461 'help-echo
5462 (if (= (point-at-bol) beg)
5463 "Footnote definition"
5464 "Footnote reference")
5465 'font-lock-fontified t
5466 'font-lock-multiline t
5467 'face 'org-footnote))))))
5469 (defun org-activate-bracket-links (limit)
5470 "Run through the buffer and add overlays to bracketed links."
5471 (if (re-search-forward org-bracket-link-regexp limit t)
5472 (let* ((help (concat "LINK: "
5473 (org-match-string-no-properties 1)))
5474 ;; FIXME: above we should remove the escapes.
5475 ;; but that requires another match, protecting match data,
5476 ;; a lot of overhead for font-lock.
5477 (ip (org-maybe-intangible
5478 (list 'invisible 'org-link
5479 'keymap org-mouse-map 'mouse-face 'highlight
5480 'font-lock-multiline t 'help-echo help)))
5481 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5482 'font-lock-multiline t 'help-echo help)))
5483 ;; We need to remove the invisible property here. Table narrowing
5484 ;; may have made some of this invisible.
5485 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5486 (remove-text-properties (match-beginning 0) (match-end 0)
5487 '(invisible nil))
5488 (if (match-end 3)
5489 (progn
5490 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5491 (org-rear-nonsticky-at (match-beginning 3))
5492 (add-text-properties (match-beginning 3) (match-end 3) vp)
5493 (org-rear-nonsticky-at (match-end 3))
5494 (add-text-properties (match-end 3) (match-end 0) ip)
5495 (org-rear-nonsticky-at (match-end 0)))
5496 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5497 (org-rear-nonsticky-at (match-beginning 1))
5498 (add-text-properties (match-beginning 1) (match-end 1) vp)
5499 (org-rear-nonsticky-at (match-end 1))
5500 (add-text-properties (match-end 1) (match-end 0) ip)
5501 (org-rear-nonsticky-at (match-end 0)))
5502 t)))
5504 (defun org-activate-dates (limit)
5505 "Run through the buffer and add overlays to dates."
5506 (if (re-search-forward org-tsr-regexp-both limit t)
5507 (progn
5508 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5509 (add-text-properties (match-beginning 0) (match-end 0)
5510 (list 'mouse-face 'highlight
5511 'keymap org-mouse-map))
5512 (org-rear-nonsticky-at (match-end 0))
5513 (when org-display-custom-times
5514 (if (match-end 3)
5515 (org-display-custom-time (match-beginning 3) (match-end 3)))
5516 (org-display-custom-time (match-beginning 1) (match-end 1)))
5517 t)))
5519 (defvar org-target-link-regexp nil
5520 "Regular expression matching radio targets in plain text.")
5521 (make-variable-buffer-local 'org-target-link-regexp)
5522 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5523 "Regular expression matching a link target.")
5524 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5525 "Regular expression matching a radio target.")
5526 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5527 "Regular expression matching any target.")
5529 (defun org-activate-target-links (limit)
5530 "Run through the buffer and add overlays to target matches."
5531 (when org-target-link-regexp
5532 (let ((case-fold-search t))
5533 (if (re-search-forward org-target-link-regexp limit t)
5534 (progn
5535 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5536 (add-text-properties (match-beginning 0) (match-end 0)
5537 (list 'mouse-face 'highlight
5538 'keymap org-mouse-map
5539 'help-echo "Radio target link"
5540 'org-linked-text t))
5541 (org-rear-nonsticky-at (match-end 0))
5542 t)))))
5544 (defun org-update-radio-target-regexp ()
5545 "Find all radio targets in this file and update the regular expression."
5546 (interactive)
5547 (when (memq 'radio org-activate-links)
5548 (setq org-target-link-regexp
5549 (org-make-target-link-regexp (org-all-targets 'radio)))
5550 (org-restart-font-lock)))
5552 (defun org-hide-wide-columns (limit)
5553 (let (s e)
5554 (setq s (text-property-any (point) (or limit (point-max))
5555 'org-cwidth t))
5556 (when s
5557 (setq e (next-single-property-change s 'org-cwidth))
5558 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5559 (goto-char e)
5560 t)))
5562 (defvar org-latex-and-specials-regexp nil
5563 "Regular expression for highlighting export special stuff.")
5564 (defvar org-match-substring-regexp)
5565 (defvar org-match-substring-with-braces-regexp)
5567 ;; This should be with the exporter code, but we also use if for font-locking
5568 (defconst org-export-html-special-string-regexps
5569 '(("\\\\-" . "&shy;")
5570 ("---\\([^-]\\)" . "&mdash;\\1")
5571 ("--\\([^-]\\)" . "&ndash;\\1")
5572 ("\\.\\.\\." . "&hellip;"))
5573 "Regular expressions for special string conversion.")
5576 (defun org-compute-latex-and-specials-regexp ()
5577 "Compute regular expression for stuff treated specially by exporters."
5578 (if (not org-highlight-latex-fragments-and-specials)
5579 (org-set-local 'org-latex-and-specials-regexp nil)
5580 (require 'org-exp)
5581 (let*
5582 ((matchers (plist-get org-format-latex-options :matchers))
5583 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5584 org-latex-regexps)))
5585 (org-export-allow-BIND nil)
5586 (options (org-combine-plists (org-default-export-plist)
5587 (org-infile-export-plist)))
5588 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5589 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5590 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5591 (org-export-html-expand (plist-get options :expand-quoted-html))
5592 (org-export-with-special-strings (plist-get options :special-strings))
5593 (re-sub
5594 (cond
5595 ((equal org-export-with-sub-superscripts '{})
5596 (list org-match-substring-with-braces-regexp))
5597 (org-export-with-sub-superscripts
5598 (list org-match-substring-regexp))
5599 (t nil)))
5600 (re-latex
5601 (if org-export-with-LaTeX-fragments
5602 (mapcar (lambda (x) (nth 1 x)) latexs)))
5603 (re-macros
5604 (if org-export-with-TeX-macros
5605 (list (concat "\\\\"
5606 (regexp-opt
5607 (append
5609 (delq nil
5610 (mapcar 'car-safe
5611 (append org-entities-user
5612 org-entities)))
5613 (if (boundp 'org-latex-entities)
5614 (mapcar (lambda (x)
5615 (or (car-safe x) x))
5616 org-latex-entities)
5617 nil))
5618 'words))) ; FIXME
5620 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5621 (re-special (if org-export-with-special-strings
5622 (mapcar (lambda (x) (car x))
5623 org-export-html-special-string-regexps)))
5624 (re-rest
5625 (delq nil
5626 (list
5627 (if org-export-html-expand "@<[^>\n]+>")
5628 ))))
5629 (org-set-local
5630 'org-latex-and-specials-regexp
5631 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5632 re-rest) "\\|")))))
5634 (defun org-do-latex-and-special-faces (limit)
5635 "Run through the buffer and add overlays to links."
5636 (when org-latex-and-specials-regexp
5637 (let (rtn d)
5638 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5639 limit t))
5640 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5641 'face))
5642 '(org-code org-verbatim underline)))
5643 (progn
5644 (setq rtn t
5645 d (cond ((member (char-after (1+ (match-beginning 0)))
5646 '(?_ ?^)) 1)
5647 (t 0)))
5648 (font-lock-prepend-text-property
5649 (+ d (match-beginning 0)) (match-end 0)
5650 'face 'org-latex-and-export-specials)
5651 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5652 '(font-lock-multiline t)))))
5653 rtn)))
5655 (defun org-restart-font-lock ()
5656 "Restart `font-lock-mode', to force refontification."
5657 (when (and (boundp 'font-lock-mode) font-lock-mode)
5658 (font-lock-mode -1)
5659 (font-lock-mode 1)))
5661 (defun org-all-targets (&optional radio)
5662 "Return a list of all targets in this file.
5663 With optional argument RADIO, only find radio targets."
5664 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5665 rtn)
5666 (save-excursion
5667 (goto-char (point-min))
5668 (while (re-search-forward re nil t)
5669 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5670 rtn)))
5672 (defun org-make-target-link-regexp (targets)
5673 "Make regular expression matching all strings in TARGETS.
5674 The regular expression finds the targets also if there is a line break
5675 between words."
5676 (and targets
5677 (concat
5678 "\\<\\("
5679 (mapconcat
5680 (lambda (x)
5681 (setq x (regexp-quote x))
5682 (while (string-match " +" x)
5683 (setq x (replace-match "\\s-+" t t x)))
5685 targets
5686 "\\|")
5687 "\\)\\>")))
5689 (defun org-activate-tags (limit)
5690 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5691 (progn
5692 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5693 (add-text-properties (match-beginning 1) (match-end 1)
5694 (list 'mouse-face 'highlight
5695 'keymap org-mouse-map))
5696 (org-rear-nonsticky-at (match-end 1))
5697 t)))
5699 (defun org-outline-level ()
5700 "Compute the outline level of the heading at point.
5701 This function assumes that the cursor is at the beginning of a line matched
5702 by `outline-regexp'. Otherwise it returns garbage.
5703 If this is called at a normal headline, the level is the number of stars.
5704 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5705 (save-excursion
5706 (looking-at org-outline-regexp)
5707 (1- (- (match-end 0) (match-beginning 0)))))
5709 (defvar org-font-lock-keywords nil)
5711 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5712 "Regular expression matching a property line.")
5714 (defvar org-font-lock-hook nil
5715 "Functions to be called for special font lock stuff.")
5717 (defvar org-font-lock-set-keywords-hook nil
5718 "Functions that can manipulate `org-font-lock-extra-keywords'.
5719 This is calles after `org-font-lock-extra-keywords' is defined, but before
5720 it is installed to be used by font lock. This can be useful if something
5721 needs to be inserted at a specific position in the font-lock sequence.")
5723 (defun org-font-lock-hook (limit)
5724 (run-hook-with-args 'org-font-lock-hook limit))
5726 (defun org-set-font-lock-defaults ()
5727 (let* ((em org-fontify-emphasized-text)
5728 (lk org-activate-links)
5729 (org-font-lock-extra-keywords
5730 (list
5731 ;; Call the hook
5732 '(org-font-lock-hook)
5733 ;; Headlines
5734 `(,(if org-fontify-whole-heading-line
5735 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5736 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5737 (1 (org-get-level-face 1))
5738 (2 (org-get-level-face 2))
5739 (3 (org-get-level-face 3)))
5740 ;; Table lines
5741 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5742 (1 'org-table t))
5743 ;; Table internals
5744 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5745 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5746 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5747 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5748 ;; Drawers
5749 (list org-drawer-regexp '(0 'org-special-keyword t))
5750 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5751 ;; Properties
5752 (list org-property-re
5753 '(1 'org-special-keyword t)
5754 '(3 'org-property-value t))
5755 ;; Links
5756 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5757 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5758 (if (memq 'plain lk) '(org-activate-plain-links))
5759 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5760 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5761 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5762 (if (memq 'footnote lk) '(org-activate-footnote-links))
5763 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5764 '(org-hide-wide-columns (0 nil append))
5765 ;; TODO keyword
5766 (list (format org-heading-keyword-regexp-format
5767 org-todo-regexp)
5768 '(2 (org-get-todo-face 2) t))
5769 ;; DONE
5770 (if org-fontify-done-headline
5771 (list (format org-heading-keyword-regexp-format
5772 (concat
5773 "\\("
5774 (mapconcat 'regexp-quote org-done-keywords "\\|")
5775 "\\)"))
5776 '(2 'org-headline-done t))
5777 nil)
5778 ;; Priorities
5779 '(org-font-lock-add-priority-faces)
5780 ;; Tags
5781 '(org-font-lock-add-tag-faces)
5782 ;; Special keywords
5783 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5784 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5785 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5786 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5787 ;; Emphasis
5788 (if em
5789 (if (featurep 'xemacs)
5790 '(org-do-emphasis-faces (0 nil append))
5791 '(org-do-emphasis-faces)))
5792 ;; Checkboxes
5793 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5794 1 'org-checkbox prepend)
5795 (if (cdr (assq 'checkbox org-list-automatic-rules))
5796 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5797 (0 (org-get-checkbox-statistics-face) t)))
5798 ;; Description list items
5799 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5800 1 'bold prepend)
5801 ;; ARCHIVEd headings
5802 (list (concat
5803 org-outline-regexp-bol
5804 "\\(.*:" org-archive-tag ":.*\\)")
5805 '(1 'org-archived prepend))
5806 ;; Specials
5807 '(org-do-latex-and-special-faces)
5808 '(org-fontify-entities)
5809 '(org-raise-scripts)
5810 ;; Code
5811 '(org-activate-code (1 'org-code t))
5812 ;; COMMENT
5813 (list (format org-heading-keyword-regexp-format
5814 (concat "\\("
5815 org-comment-string "\\|" org-quote-string
5816 "\\)"))
5817 '(2 'org-special-keyword t))
5818 '("^#.*" (0 'font-lock-comment-face t))
5819 ;; Blocks and meta lines
5820 '(org-fontify-meta-lines-and-blocks)
5822 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5823 (run-hooks 'org-font-lock-set-keywords-hook)
5824 ;; Now set the full font-lock-keywords
5825 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5826 (org-set-local 'font-lock-defaults
5827 '(org-font-lock-keywords t nil nil backward-paragraph))
5828 (kill-local-variable 'font-lock-keywords) nil))
5830 (defun org-toggle-pretty-entities ()
5831 "Toggle the composition display of entities as UTF8 characters."
5832 (interactive)
5833 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5834 (org-restart-font-lock)
5835 (if org-pretty-entities
5836 (message "Entities are displayed as UTF8 characers")
5837 (save-restriction
5838 (widen)
5839 (org-decompose-region (point-min) (point-max))
5840 (message "Entities are displayed plain"))))
5842 (defun org-fontify-entities (limit)
5843 "Find an entity to fontify."
5844 (let (ee)
5845 (when org-pretty-entities
5846 (catch 'match
5847 (while (re-search-forward
5848 "\\\\\\(frac[13][24]\\|[a-zA-Z]+\\)\\($\\|[^[:alpha:]\n]\\)"
5849 limit t)
5850 (if (and (not (org-in-indented-comment-line))
5851 (setq ee (org-entity-get (match-string 1)))
5852 (= (length (nth 6 ee)) 1))
5853 (progn
5854 (add-text-properties
5855 (match-beginning 0) (match-end 1)
5856 (list 'font-lock-fontified t))
5857 (compose-region (match-beginning 0) (match-end 1)
5858 (nth 6 ee) nil)
5859 (backward-char 1)
5860 (throw 'match t))))
5861 nil))))
5863 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5864 "Fontify string S like in Org-mode."
5865 (with-temp-buffer
5866 (insert s)
5867 (let ((org-odd-levels-only odd-levels))
5868 (org-mode)
5869 (font-lock-fontify-buffer)
5870 (buffer-string))))
5872 (defvar org-m nil)
5873 (defvar org-l nil)
5874 (defvar org-f nil)
5875 (defun org-get-level-face (n)
5876 "Get the right face for match N in font-lock matching of headlines."
5877 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5878 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5879 (if org-cycle-level-faces
5880 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5881 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5882 (cond
5883 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5884 ((eq n 2) org-f)
5885 (t (if org-level-color-stars-only nil org-f))))
5888 (defun org-get-todo-face (kwd)
5889 "Get the right face for a TODO keyword KWD.
5890 If KWD is a number, get the corresponding match group."
5891 (if (numberp kwd) (setq kwd (match-string kwd)))
5892 (or (org-face-from-face-or-color
5893 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5894 (and (member kwd org-done-keywords) 'org-done)
5895 'org-todo))
5897 (defun org-face-from-face-or-color (context inherit face-or-color)
5898 "Create a face list that inherits INHERIT, but sets the foreground color.
5899 When FACE-OR-COLOR is not a string, just return it."
5900 (if (stringp face-or-color)
5901 (list :inherit inherit
5902 (cdr (assoc context org-faces-easy-properties))
5903 face-or-color)
5904 face-or-color))
5906 (defun org-font-lock-add-tag-faces (limit)
5907 "Add the special tag faces."
5908 (when (and org-tag-faces org-tags-special-faces-re)
5909 (while (re-search-forward org-tags-special-faces-re limit t)
5910 (add-text-properties (match-beginning 1) (match-end 1)
5911 (list 'face (org-get-tag-face 1)
5912 'font-lock-fontified t))
5913 (backward-char 1))))
5915 (defun org-font-lock-add-priority-faces (limit)
5916 "Add the special priority faces."
5917 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5918 (add-text-properties
5919 (match-beginning 0) (match-end 0)
5920 (list 'face (or (org-face-from-face-or-color
5921 'priority 'org-special-keyword
5922 (cdr (assoc (char-after (match-beginning 1))
5923 org-priority-faces)))
5924 'org-special-keyword)
5925 'font-lock-fontified t))))
5927 (defun org-get-tag-face (kwd)
5928 "Get the right face for a TODO keyword KWD.
5929 If KWD is a number, get the corresponding match group."
5930 (if (numberp kwd) (setq kwd (match-string kwd)))
5931 (or (org-face-from-face-or-color
5932 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5933 'org-tag))
5935 (defun org-unfontify-region (beg end &optional maybe_loudly)
5936 "Remove fontification and activation overlays from links."
5937 (font-lock-default-unfontify-region beg end)
5938 (let* ((buffer-undo-list t)
5939 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5940 (inhibit-modification-hooks t)
5941 deactivate-mark buffer-file-name buffer-file-truename)
5942 (org-decompose-region beg end)
5943 (remove-text-properties beg end
5944 '(mouse-face t keymap t org-linked-text t
5945 invisible t intangible t
5946 org-no-flyspell t org-emphasis t))
5947 (org-remove-font-lock-display-properties beg end)))
5949 (defconst org-script-display '(((raise -0.3) (height 0.7))
5950 ((raise 0.3) (height 0.7))
5951 ((raise -0.5))
5952 ((raise 0.5)))
5953 "Display properties for showing superscripts and subscripts.")
5955 (defun org-remove-font-lock-display-properties (beg end)
5956 "Remove specific display properties that have been added by font lock.
5957 The will remove the raise properties that are used to show superscripts
5958 and subscripts."
5959 (let (next prop)
5960 (while (< beg end)
5961 (setq next (next-single-property-change beg 'display nil end)
5962 prop (get-text-property beg 'display))
5963 (if (member prop org-script-display)
5964 (put-text-property beg next 'display nil))
5965 (setq beg next))))
5967 (defun org-raise-scripts (limit)
5968 "Add raise properties to sub/superscripts."
5969 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
5970 (if (re-search-forward
5971 (if (eq org-use-sub-superscripts t)
5972 org-match-substring-regexp
5973 org-match-substring-with-braces-regexp)
5974 limit t)
5975 (let* ((pos (point)) table-p comment-p
5976 (mpos (match-beginning 3))
5977 (emph-p (get-text-property mpos 'org-emphasis))
5978 (link-p (get-text-property mpos 'mouse-face))
5979 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
5980 (goto-char (point-at-bol))
5981 (setq table-p (org-looking-at-p org-table-dataline-regexp)
5982 comment-p (org-looking-at-p "[ \t]*#"))
5983 (goto-char pos)
5984 ;; FIXME: Should we go back one character here, for a_b^c
5985 ;; (goto-char (1- pos)) ;????????????????????
5986 (if (or comment-p emph-p link-p keyw-p)
5988 (put-text-property (match-beginning 3) (match-end 0)
5989 'display
5990 (if (equal (char-after (match-beginning 2)) ?^)
5991 (nth (if table-p 3 1) org-script-display)
5992 (nth (if table-p 2 0) org-script-display)))
5993 (add-text-properties (match-beginning 2) (match-end 2)
5994 (list 'invisible t
5995 'org-dwidth t 'org-dwidth-n 1))
5996 (if (and (eq (char-after (match-beginning 3)) ?{)
5997 (eq (char-before (match-end 3)) ?}))
5998 (progn
5999 (add-text-properties
6000 (match-beginning 3) (1+ (match-beginning 3))
6001 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6002 (add-text-properties
6003 (1- (match-end 3)) (match-end 3)
6004 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6005 t)))))
6007 ;;;; Visibility cycling, including org-goto and indirect buffer
6009 ;;; Cycling
6011 (defvar org-cycle-global-status nil)
6012 (make-variable-buffer-local 'org-cycle-global-status)
6013 (defvar org-cycle-subtree-status nil)
6014 (make-variable-buffer-local 'org-cycle-subtree-status)
6016 ;;;###autoload
6018 (defvar org-inlinetask-min-level)
6020 (defun org-cycle (&optional arg)
6021 "TAB-action and visibility cycling for Org-mode.
6023 This is the command invoked in Org-mode by the TAB key. Its main purpose
6024 is outline visibility cycling, but it also invokes other actions
6025 in special contexts.
6027 - When this function is called with a prefix argument, rotate the entire
6028 buffer through 3 states (global cycling)
6029 1. OVERVIEW: Show only top-level headlines.
6030 2. CONTENTS: Show all headlines of all levels, but no body text.
6031 3. SHOW ALL: Show everything.
6032 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6033 determined by the variable `org-startup-folded', and by any VISIBILITY
6034 properties in the buffer.
6035 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6036 including any drawers.
6038 - When inside a table, re-align the table and move to the next field.
6040 - When point is at the beginning of a headline, rotate the subtree started
6041 by this line through 3 different states (local cycling)
6042 1. FOLDED: Only the main headline is shown.
6043 2. CHILDREN: The main headline and the direct children are shown.
6044 From this state, you can move to one of the children
6045 and zoom in further.
6046 3. SUBTREE: Show the entire subtree, including body text.
6047 If there is no subtree, switch directly from CHILDREN to FOLDED.
6049 - When point is at the beginning of an empty headline and the variable
6050 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6051 of the headline by demoting and promoting it to likely levels. This
6052 speeds up creation document structure by pressing TAB once or several
6053 times right after creating a new headline.
6055 - When there is a numeric prefix, go up to a heading with level ARG, do
6056 a `show-subtree' and return to the previous cursor position. If ARG
6057 is negative, go up that many levels.
6059 - When point is not at the beginning of a headline, execute the global
6060 binding for TAB, which is re-indenting the line. See the option
6061 `org-cycle-emulate-tab' for details.
6063 - Special case: if point is at the beginning of the buffer and there is
6064 no headline in line 1, this function will act as if called with prefix arg
6065 (C-u TAB, same as S-TAB) also when called without prefix arg.
6066 But only if also the variable `org-cycle-global-at-bob' is t."
6067 (interactive "P")
6068 (org-load-modules-maybe)
6069 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6070 (and org-cycle-level-after-item/entry-creation
6071 (or (org-cycle-level)
6072 (org-cycle-item-indentation))))
6073 (let* ((limit-level
6074 (or org-cycle-max-level
6075 (and (boundp 'org-inlinetask-min-level)
6076 org-inlinetask-min-level
6077 (1- org-inlinetask-min-level))))
6078 (nstars (and limit-level
6079 (if org-odd-levels-only
6080 (and limit-level (1- (* limit-level 2)))
6081 limit-level)))
6082 (org-outline-regexp
6083 (if (not (eq major-mode 'org-mode))
6084 outline-regexp
6085 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6086 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6087 (not (looking-at org-outline-regexp))))
6088 (org-cycle-hook
6089 (if bob-special
6090 (delq 'org-optimize-window-after-visibility-change
6091 (copy-sequence org-cycle-hook))
6092 org-cycle-hook))
6093 (pos (point)))
6095 (if (or bob-special (equal arg '(4)))
6096 ;; special case: use global cycling
6097 (setq arg t))
6099 (cond
6101 ((equal arg '(16))
6102 (setq last-command 'dummy)
6103 (org-set-startup-visibility)
6104 (message "Startup visibility, plus VISIBILITY properties"))
6106 ((equal arg '(64))
6107 (show-all)
6108 (message "Entire buffer visible, including drawers"))
6110 ;; Table: enter it or move to the next field.
6111 ((org-at-table-p 'any)
6112 (if (org-at-table.el-p)
6113 (message "Use C-c ' to edit table.el tables")
6114 (if arg (org-table-edit-field t)
6115 (org-table-justify-field-maybe)
6116 (call-interactively 'org-table-next-field))))
6118 ((run-hook-with-args-until-success
6119 'org-tab-after-check-for-table-hook))
6121 ;; Global cycling: delegate to `org-cycle-internal-global'.
6122 ((eq arg t) (org-cycle-internal-global))
6124 ;; Drawers: delegate to `org-flag-drawer'.
6125 ((and org-drawers org-drawer-regexp
6126 (save-excursion
6127 (beginning-of-line 1)
6128 (looking-at org-drawer-regexp)))
6129 (org-flag-drawer ; toggle block visibility
6130 (not (get-char-property (match-end 0) 'invisible))))
6132 ;; Show-subtree, ARG levels up from here.
6133 ((integerp arg)
6134 (save-excursion
6135 (org-back-to-heading)
6136 (outline-up-heading (if (< arg 0) (- arg)
6137 (- (funcall outline-level) arg)))
6138 (org-show-subtree)))
6140 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6141 ((and (featurep 'org-inlinetask)
6142 (org-inlinetask-at-task-p)
6143 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6144 (org-inlinetask-toggle-visibility))
6146 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6147 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6148 (save-excursion (beginning-of-line 1)
6149 (looking-at org-outline-regexp)))
6150 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6151 (org-cycle-internal-local))
6153 ;; From there: TAB emulation and template completion.
6154 (buffer-read-only (org-back-to-heading))
6156 ((run-hook-with-args-until-success
6157 'org-tab-after-check-for-cycling-hook))
6159 ((org-try-structure-completion))
6161 ((org-try-cdlatex-tab))
6163 ((run-hook-with-args-until-success
6164 'org-tab-before-tab-emulation-hook))
6166 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6167 (or (not (bolp))
6168 (not (looking-at org-outline-regexp))))
6169 (call-interactively (global-key-binding "\t")))
6171 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6172 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6173 (or (and (eq org-cycle-emulate-tab 'white)
6174 (= (match-end 0) (point-at-eol)))
6175 (and (eq org-cycle-emulate-tab 'whitestart)
6176 (>= (match-end 0) pos))))
6178 (eq org-cycle-emulate-tab t))
6179 (call-interactively (global-key-binding "\t")))
6181 (t (save-excursion
6182 (org-back-to-heading)
6183 (org-cycle)))))))
6185 (defun org-cycle-internal-global ()
6186 "Do the global cycling action."
6187 (cond
6188 ((and (eq last-command this-command)
6189 (eq org-cycle-global-status 'overview))
6190 ;; We just created the overview - now do table of contents
6191 ;; This can be slow in very large buffers, so indicate action
6192 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6193 (message "CONTENTS...")
6194 (org-content)
6195 (message "CONTENTS...done")
6196 (setq org-cycle-global-status 'contents)
6197 (run-hook-with-args 'org-cycle-hook 'contents))
6199 ((and (eq last-command this-command)
6200 (eq org-cycle-global-status 'contents))
6201 ;; We just showed the table of contents - now show everything
6202 (run-hook-with-args 'org-pre-cycle-hook 'all)
6203 (show-all)
6204 (message "SHOW ALL")
6205 (setq org-cycle-global-status 'all)
6206 (run-hook-with-args 'org-cycle-hook 'all))
6209 ;; Default action: go to overview
6210 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6211 (org-overview)
6212 (message "OVERVIEW")
6213 (setq org-cycle-global-status 'overview)
6214 (run-hook-with-args 'org-cycle-hook 'overview))))
6216 (defun org-cycle-internal-local ()
6217 "Do the local cycling action."
6218 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6219 ;; First, determine end of headline (EOH), end of subtree or item
6220 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6221 (save-excursion
6222 (if (org-at-item-p)
6223 (progn
6224 (beginning-of-line)
6225 (setq struct (org-list-struct))
6226 (setq eoh (point-at-eol))
6227 (setq eos (org-list-get-item-end-before-blank (point) struct))
6228 (setq has-children (org-list-has-child-p (point) struct)))
6229 (org-back-to-heading)
6230 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6231 (setq eos (save-excursion
6232 (org-end-of-subtree t)
6233 (unless (eobp)
6234 (skip-chars-forward " \t\n"))
6235 (if (eobp) (point) (1- (point)))))
6236 (setq has-children
6237 (or (save-excursion
6238 (let ((level (funcall outline-level)))
6239 (outline-next-heading)
6240 (and (org-at-heading-p t)
6241 (> (funcall outline-level) level))))
6242 (save-excursion
6243 (org-list-search-forward (org-item-beginning-re) eos t)))))
6244 ;; Determine end invisible part of buffer (EOL)
6245 (beginning-of-line 2)
6246 ;; XEmacs doesn't have `next-single-char-property-change'
6247 (if (featurep 'xemacs)
6248 (while (and (not (eobp)) ;; this is like `next-line'
6249 (get-char-property (1- (point)) 'invisible))
6250 (beginning-of-line 2))
6251 (while (and (not (eobp)) ;; this is like `next-line'
6252 (get-char-property (1- (point)) 'invisible))
6253 (goto-char (next-single-char-property-change (point) 'invisible))
6254 (and (eolp) (beginning-of-line 2))))
6255 (setq eol (point)))
6256 ;; Find out what to do next and set `this-command'
6257 (cond
6258 ((= eos eoh)
6259 ;; Nothing is hidden behind this heading
6260 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6261 (message "EMPTY ENTRY")
6262 (setq org-cycle-subtree-status nil)
6263 (save-excursion
6264 (goto-char eos)
6265 (outline-next-heading)
6266 (if (outline-invisible-p) (org-flag-heading nil))))
6267 ((and (or (>= eol eos)
6268 (not (string-match "\\S-" (buffer-substring eol eos))))
6269 (or has-children
6270 (not (setq children-skipped
6271 org-cycle-skip-children-state-if-no-children))))
6272 ;; Entire subtree is hidden in one line: children view
6273 (run-hook-with-args 'org-pre-cycle-hook 'children)
6274 (if (org-at-item-p)
6275 (org-list-set-item-visibility (point-at-bol) struct 'children)
6276 (org-show-entry)
6277 (show-children)
6278 ;; Fold every list in subtree to top-level items.
6279 (when (eq org-cycle-include-plain-lists 'integrate)
6280 (save-excursion
6281 (org-back-to-heading)
6282 (while (org-list-search-forward (org-item-beginning-re) eos t)
6283 (beginning-of-line 1)
6284 (let* ((struct (org-list-struct))
6285 (prevs (org-list-prevs-alist struct))
6286 (end (org-list-get-bottom-point struct)))
6287 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6288 (org-list-get-all-items (point) struct prevs))
6289 (goto-char end))))))
6290 (message "CHILDREN")
6291 (save-excursion
6292 (goto-char eos)
6293 (outline-next-heading)
6294 (if (outline-invisible-p) (org-flag-heading nil)))
6295 (setq org-cycle-subtree-status 'children)
6296 (run-hook-with-args 'org-cycle-hook 'children))
6297 ((or children-skipped
6298 (and (eq last-command this-command)
6299 (eq org-cycle-subtree-status 'children)))
6300 ;; We just showed the children, or no children are there,
6301 ;; now show everything.
6302 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6303 (outline-flag-region eoh eos nil)
6304 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6305 (setq org-cycle-subtree-status 'subtree)
6306 (run-hook-with-args 'org-cycle-hook 'subtree))
6308 ;; Default action: hide the subtree.
6309 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6310 (outline-flag-region eoh eos t)
6311 (message "FOLDED")
6312 (setq org-cycle-subtree-status 'folded)
6313 (run-hook-with-args 'org-cycle-hook 'folded)))))
6315 ;;;###autoload
6316 (defun org-global-cycle (&optional arg)
6317 "Cycle the global visibility. For details see `org-cycle'.
6318 With \\[universal-argument] prefix arg, switch to startup visibility.
6319 With a numeric prefix, show all headlines up to that level."
6320 (interactive "P")
6321 (let ((org-cycle-include-plain-lists
6322 (if (eq major-mode 'org-mode) org-cycle-include-plain-lists nil)))
6323 (cond
6324 ((integerp arg)
6325 (show-all)
6326 (hide-sublevels arg)
6327 (setq org-cycle-global-status 'contents))
6328 ((equal arg '(4))
6329 (org-set-startup-visibility)
6330 (message "Startup visibility, plus VISIBILITY properties."))
6332 (org-cycle '(4))))))
6334 (defun org-set-startup-visibility ()
6335 "Set the visibility required by startup options and properties."
6336 (cond
6337 ((eq org-startup-folded t)
6338 (org-cycle '(4)))
6339 ((eq org-startup-folded 'content)
6340 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6341 (org-cycle '(4)) (org-cycle '(4)))))
6342 (unless (eq org-startup-folded 'showeverything)
6343 (if org-hide-block-startup (org-hide-block-all))
6344 (org-set-visibility-according-to-property 'no-cleanup)
6345 (org-cycle-hide-archived-subtrees 'all)
6346 (org-cycle-hide-drawers 'all)
6347 (org-cycle-show-empty-lines t)))
6349 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6350 "Switch subtree visibilities according to :VISIBILITY: property."
6351 (interactive)
6352 (let (org-show-entry-below state)
6353 (save-excursion
6354 (goto-char (point-min))
6355 (while (re-search-forward
6356 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6357 nil t)
6358 (setq state (match-string 1))
6359 (save-excursion
6360 (org-back-to-heading t)
6361 (hide-subtree)
6362 (org-reveal)
6363 (cond
6364 ((equal state '("fold" "folded"))
6365 (hide-subtree))
6366 ((equal state "children")
6367 (org-show-hidden-entry)
6368 (show-children))
6369 ((equal state "content")
6370 (save-excursion
6371 (save-restriction
6372 (org-narrow-to-subtree)
6373 (org-content))))
6374 ((member state '("all" "showall"))
6375 (show-subtree)))))
6376 (unless no-cleanup
6377 (org-cycle-hide-archived-subtrees 'all)
6378 (org-cycle-hide-drawers 'all)
6379 (org-cycle-show-empty-lines 'all)))))
6381 ;; This function uses outline-regexp instead of the more fundamental
6382 ;; org-outline-regexp so that org-cycle-global works outside of Org
6383 ;; buffers, where outline-regexp is needed.
6384 (defun org-overview ()
6385 "Switch to overview mode, showing only top-level headlines.
6386 Really, this shows all headlines with level equal or greater than the level
6387 of the first headline in the buffer. This is important, because if the
6388 first headline is not level one, then (hide-sublevels 1) gives confusing
6389 results."
6390 (interactive)
6391 (let ((level (save-excursion
6392 (goto-char (point-min))
6393 (if (re-search-forward (concat "^" outline-regexp) nil t)
6394 (progn
6395 (goto-char (match-beginning 0))
6396 (funcall outline-level))))))
6397 (and level (hide-sublevels level))))
6399 (defun org-content (&optional arg)
6400 "Show all headlines in the buffer, like a table of contents.
6401 With numerical argument N, show content up to level N."
6402 (interactive "P")
6403 (save-excursion
6404 ;; Visit all headings and show their offspring
6405 (and (integerp arg) (org-overview))
6406 (goto-char (point-max))
6407 (catch 'exit
6408 (while (and (progn (condition-case nil
6409 (outline-previous-visible-heading 1)
6410 (error (goto-char (point-min))))
6412 (looking-at org-outline-regexp))
6413 (if (integerp arg)
6414 (show-children (1- arg))
6415 (show-branches))
6416 (if (bobp) (throw 'exit nil))))))
6419 (defun org-optimize-window-after-visibility-change (state)
6420 "Adjust the window after a change in outline visibility.
6421 This function is the default value of the hook `org-cycle-hook'."
6422 (when (get-buffer-window (current-buffer))
6423 (cond
6424 ((eq state 'content) nil)
6425 ((eq state 'all) nil)
6426 ((eq state 'folded) nil)
6427 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6428 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6430 (defun org-remove-empty-overlays-at (pos)
6431 "Remove outline overlays that do not contain non-white stuff."
6432 (mapc
6433 (lambda (o)
6434 (and (eq 'outline (overlay-get o 'invisible))
6435 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6436 (overlay-end o))))
6437 (delete-overlay o)))
6438 (overlays-at pos)))
6440 (defun org-clean-visibility-after-subtree-move ()
6441 "Fix visibility issues after moving a subtree."
6442 ;; First, find a reasonable region to look at:
6443 ;; Start two siblings above, end three below
6444 (let* ((beg (save-excursion
6445 (and (org-get-last-sibling)
6446 (org-get-last-sibling))
6447 (point)))
6448 (end (save-excursion
6449 (and (org-get-next-sibling)
6450 (org-get-next-sibling)
6451 (org-get-next-sibling))
6452 (if (org-at-heading-p)
6453 (point-at-eol)
6454 (point))))
6455 (level (looking-at "\\*+"))
6456 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6457 (save-excursion
6458 (save-restriction
6459 (narrow-to-region beg end)
6460 (when re
6461 ;; Properly fold already folded siblings
6462 (goto-char (point-min))
6463 (while (re-search-forward re nil t)
6464 (if (and (not (outline-invisible-p))
6465 (save-excursion
6466 (goto-char (point-at-eol)) (outline-invisible-p)))
6467 (hide-entry))))
6468 (org-cycle-show-empty-lines 'overview)
6469 (org-cycle-hide-drawers 'overview)))))
6471 (defun org-cycle-show-empty-lines (state)
6472 "Show empty lines above all visible headlines.
6473 The region to be covered depends on STATE when called through
6474 `org-cycle-hook'. Lisp program can use t for STATE to get the
6475 entire buffer covered. Note that an empty line is only shown if there
6476 are at least `org-cycle-separator-lines' empty lines before the headline."
6477 (when (not (= org-cycle-separator-lines 0))
6478 (save-excursion
6479 (let* ((n (abs org-cycle-separator-lines))
6480 (re (cond
6481 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6482 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6483 (t (let ((ns (number-to-string (- n 2))))
6484 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6485 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6486 beg end b e)
6487 (cond
6488 ((memq state '(overview contents t))
6489 (setq beg (point-min) end (point-max)))
6490 ((memq state '(children folded))
6491 (setq beg (point) end (progn (org-end-of-subtree t t)
6492 (beginning-of-line 2)
6493 (point)))))
6494 (when beg
6495 (goto-char beg)
6496 (while (re-search-forward re end t)
6497 (unless (get-char-property (match-end 1) 'invisible)
6498 (setq e (match-end 1))
6499 (if (< org-cycle-separator-lines 0)
6500 (setq b (save-excursion
6501 (goto-char (match-beginning 0))
6502 (org-back-over-empty-lines)
6503 (if (save-excursion
6504 (goto-char (max (point-min) (1- (point))))
6505 (org-on-heading-p))
6506 (1- (point))
6507 (point))))
6508 (setq b (match-beginning 1)))
6509 (outline-flag-region b e nil)))))))
6510 ;; Never hide empty lines at the end of the file.
6511 (save-excursion
6512 (goto-char (point-max))
6513 (outline-previous-heading)
6514 (outline-end-of-heading)
6515 (if (and (looking-at "[ \t\n]+")
6516 (= (match-end 0) (point-max)))
6517 (outline-flag-region (point) (match-end 0) nil))))
6519 (defun org-show-empty-lines-in-parent ()
6520 "Move to the parent and re-show empty lines before visible headlines."
6521 (save-excursion
6522 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6523 (org-cycle-show-empty-lines context))))
6525 (defun org-files-list ()
6526 "Return `org-agenda-files' list, plus all open org-mode files.
6527 This is useful for operations that need to scan all of a user's
6528 open and agenda-wise Org files."
6529 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6530 (dolist (buf (buffer-list))
6531 (with-current-buffer buf
6532 (if (and (eq major-mode 'org-mode) (buffer-file-name))
6533 (let ((file (expand-file-name (buffer-file-name))))
6534 (unless (member file files)
6535 (push file files))))))
6536 files))
6538 (defsubst org-entry-beginning-position ()
6539 "Return the beginning position of the current entry."
6540 (save-excursion (outline-back-to-heading t) (point)))
6542 (defsubst org-entry-end-position ()
6543 "Return the end position of the current entry."
6544 (save-excursion (outline-next-heading) (point)))
6546 (defun org-cycle-hide-drawers (state)
6547 "Re-hide all drawers after a visibility state change."
6548 (when (and (eq major-mode 'org-mode)
6549 (not (memq state '(overview folded contents))))
6550 (save-excursion
6551 (let* ((globalp (memq state '(contents all)))
6552 (beg (if globalp (point-min) (point)))
6553 (end (if globalp (point-max)
6554 (if (eq state 'children)
6555 (save-excursion (outline-next-heading) (point))
6556 (org-end-of-subtree t)))))
6557 (goto-char beg)
6558 (while (re-search-forward org-drawer-regexp end t)
6559 (org-flag-drawer t))))))
6561 (defun org-flag-drawer (flag)
6562 (save-excursion
6563 (beginning-of-line 1)
6564 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6565 (let ((b (match-end 0)))
6566 (if (re-search-forward
6567 "^[ \t]*:END:"
6568 (save-excursion (outline-next-heading) (point)) t)
6569 (outline-flag-region b (point-at-eol) flag)
6570 (error ":END: line missing at position %s" b))))))
6572 (defun org-subtree-end-visible-p ()
6573 "Is the end of the current subtree visible?"
6574 (pos-visible-in-window-p
6575 (save-excursion (org-end-of-subtree t) (point))))
6577 (defun org-first-headline-recenter (&optional N)
6578 "Move cursor to the first headline and recenter the headline.
6579 Optional argument N means put the headline into the Nth line of the window."
6580 (goto-char (point-min))
6581 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6582 (beginning-of-line)
6583 (recenter (prefix-numeric-value N))))
6585 ;;; Saving and restoring visibility
6587 (defun org-outline-overlay-data (&optional use-markers)
6588 "Return a list of the locations of all outline overlays.
6589 These are overlays with the `invisible' property value `outline'.
6590 The return value is a list of cons cells, with start and stop
6591 positions for each overlay.
6592 If USE-MARKERS is set, return the positions as markers."
6593 (let (beg end)
6594 (save-excursion
6595 (save-restriction
6596 (widen)
6597 (delq nil
6598 (mapcar (lambda (o)
6599 (when (eq (overlay-get o 'invisible) 'outline)
6600 (setq beg (overlay-start o)
6601 end (overlay-end o))
6602 (and beg end (> end beg)
6603 (if use-markers
6604 (cons (move-marker (make-marker) beg)
6605 (move-marker (make-marker) end))
6606 (cons beg end)))))
6607 (overlays-in (point-min) (point-max))))))))
6609 (defun org-set-outline-overlay-data (data)
6610 "Create visibility overlays for all positions in DATA.
6611 DATA should have been made by `org-outline-overlay-data'."
6612 (let (o)
6613 (save-excursion
6614 (save-restriction
6615 (widen)
6616 (show-all)
6617 (mapc (lambda (c)
6618 (setq o (make-overlay (car c) (cdr c)))
6619 (overlay-put o 'invisible 'outline))
6620 data)))))
6622 ;;; Folding of blocks
6624 (defconst org-block-regexp
6625 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
6626 "Regular expression for hiding blocks.")
6628 (defvar org-hide-block-overlays nil
6629 "Overlays hiding blocks.")
6630 (make-variable-buffer-local 'org-hide-block-overlays)
6632 (defun org-block-map (function &optional start end)
6633 "Call FUNCTION at the head of all source blocks in the current buffer.
6634 Optional arguments START and END can be used to limit the range."
6635 (let ((start (or start (point-min)))
6636 (end (or end (point-max))))
6637 (save-excursion
6638 (goto-char start)
6639 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6640 (save-excursion
6641 (save-match-data
6642 (goto-char (match-beginning 0))
6643 (funcall function)))))))
6645 (defun org-hide-block-toggle-all ()
6646 "Toggle the visibility of all blocks in the current buffer."
6647 (org-block-map #'org-hide-block-toggle))
6649 (defun org-hide-block-all ()
6650 "Fold all blocks in the current buffer."
6651 (interactive)
6652 (org-show-block-all)
6653 (org-block-map #'org-hide-block-toggle-maybe))
6655 (defun org-show-block-all ()
6656 "Unfold all blocks in the current buffer."
6657 (interactive)
6658 (mapc 'delete-overlay org-hide-block-overlays)
6659 (setq org-hide-block-overlays nil))
6661 (defun org-hide-block-toggle-maybe ()
6662 "Toggle visibility of block at point."
6663 (interactive)
6664 (let ((case-fold-search t))
6665 (if (save-excursion
6666 (beginning-of-line 1)
6667 (looking-at org-block-regexp))
6668 (progn (org-hide-block-toggle)
6669 t) ;; to signal that we took action
6670 nil))) ;; to signal that we did not
6672 (defun org-hide-block-toggle (&optional force)
6673 "Toggle the visibility of the current block."
6674 (interactive)
6675 (save-excursion
6676 (beginning-of-line)
6677 (if (re-search-forward org-block-regexp nil t)
6678 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6679 (end (match-end 0)) ;; end of entire body
6681 (if (memq t (mapcar (lambda (overlay)
6682 (eq (overlay-get overlay 'invisible)
6683 'org-hide-block))
6684 (overlays-at start)))
6685 (if (or (not force) (eq force 'off))
6686 (mapc (lambda (ov)
6687 (when (member ov org-hide-block-overlays)
6688 (setq org-hide-block-overlays
6689 (delq ov org-hide-block-overlays)))
6690 (when (eq (overlay-get ov 'invisible)
6691 'org-hide-block)
6692 (delete-overlay ov)))
6693 (overlays-at start)))
6694 (setq ov (make-overlay start end))
6695 (overlay-put ov 'invisible 'org-hide-block)
6696 ;; make the block accessible to isearch
6697 (overlay-put
6698 ov 'isearch-open-invisible
6699 (lambda (ov)
6700 (when (member ov org-hide-block-overlays)
6701 (setq org-hide-block-overlays
6702 (delq ov org-hide-block-overlays)))
6703 (when (eq (overlay-get ov 'invisible)
6704 'org-hide-block)
6705 (delete-overlay ov))))
6706 (push ov org-hide-block-overlays)))
6707 (error "Not looking at a source block"))))
6709 ;; org-tab-after-check-for-cycling-hook
6710 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6711 ;; Remove overlays when changing major mode
6712 (add-hook 'org-mode-hook
6713 (lambda () (org-add-hook 'change-major-mode-hook
6714 'org-show-block-all 'append 'local)))
6716 ;;; Org-goto
6718 (defvar org-goto-window-configuration nil)
6719 (defvar org-goto-marker nil)
6720 (defvar org-goto-map
6721 (let ((map (make-sparse-keymap)))
6722 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6723 (while (setq cmd (pop cmds))
6724 (substitute-key-definition cmd cmd map global-map)))
6725 (suppress-keymap map)
6726 (org-defkey map "\C-m" 'org-goto-ret)
6727 (org-defkey map [(return)] 'org-goto-ret)
6728 (org-defkey map [(left)] 'org-goto-left)
6729 (org-defkey map [(right)] 'org-goto-right)
6730 (org-defkey map [(control ?g)] 'org-goto-quit)
6731 (org-defkey map "\C-i" 'org-cycle)
6732 (org-defkey map [(tab)] 'org-cycle)
6733 (org-defkey map [(down)] 'outline-next-visible-heading)
6734 (org-defkey map [(up)] 'outline-previous-visible-heading)
6735 (if org-goto-auto-isearch
6736 (if (fboundp 'define-key-after)
6737 (define-key-after map [t] 'org-goto-local-auto-isearch)
6738 nil)
6739 (org-defkey map "q" 'org-goto-quit)
6740 (org-defkey map "n" 'outline-next-visible-heading)
6741 (org-defkey map "p" 'outline-previous-visible-heading)
6742 (org-defkey map "f" 'outline-forward-same-level)
6743 (org-defkey map "b" 'outline-backward-same-level)
6744 (org-defkey map "u" 'outline-up-heading))
6745 (org-defkey map "/" 'org-occur)
6746 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6747 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6748 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6749 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6750 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6751 map))
6753 (defconst org-goto-help
6754 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6755 RET=jump to location [Q]uit and return to previous location
6756 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6758 (defvar org-goto-start-pos) ; dynamically scoped parameter
6760 ;; FIXME: Docstring does not mention both interfaces
6761 (defun org-goto (&optional alternative-interface)
6762 "Look up a different location in the current file, keeping current visibility.
6764 When you want look-up or go to a different location in a document, the
6765 fastest way is often to fold the entire buffer and then dive into the tree.
6766 This method has the disadvantage, that the previous location will be folded,
6767 which may not be what you want.
6769 This command works around this by showing a copy of the current buffer
6770 in an indirect buffer, in overview mode. You can dive into the tree in
6771 that copy, use org-occur and incremental search to find a location.
6772 When pressing RET or `Q', the command returns to the original buffer in
6773 which the visibility is still unchanged. After RET is will also jump to
6774 the location selected in the indirect buffer and expose the headline
6775 hierarchy above."
6776 (interactive "P")
6777 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6778 (org-refile-use-outline-path t)
6779 (org-refile-target-verify-function nil)
6780 (interface
6781 (if (not alternative-interface)
6782 org-goto-interface
6783 (if (eq org-goto-interface 'outline)
6784 'outline-path-completion
6785 'outline)))
6786 (org-goto-start-pos (point))
6787 (selected-point
6788 (if (eq interface 'outline)
6789 (car (org-get-location (current-buffer) org-goto-help))
6790 (let ((pa (org-refile-get-location "Goto")))
6791 (org-refile-check-position pa)
6792 (nth 3 pa)))))
6793 (if selected-point
6794 (progn
6795 (org-mark-ring-push org-goto-start-pos)
6796 (goto-char selected-point)
6797 (if (or (outline-invisible-p) (org-invisible-p2))
6798 (org-show-context 'org-goto)))
6799 (message "Quit"))))
6801 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6802 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6803 (defvar org-goto-local-auto-isearch-map) ; defined below
6805 (defun org-get-location (buf help)
6806 "Let the user select a location in the Org-mode buffer BUF.
6807 This function uses a recursive edit. It returns the selected position
6808 or nil."
6809 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6810 (isearch-hide-immediately nil)
6811 (isearch-search-fun-function
6812 (lambda () 'org-goto-local-search-headings))
6813 (org-goto-selected-point org-goto-exit-command)
6814 (pop-up-frames nil)
6815 (special-display-buffer-names nil)
6816 (special-display-regexps nil)
6817 (special-display-function nil))
6818 (save-excursion
6819 (save-window-excursion
6820 (delete-other-windows)
6821 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6822 (org-pop-to-buffer-same-window
6823 (condition-case nil
6824 (make-indirect-buffer (current-buffer) "*org-goto*")
6825 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6826 (with-output-to-temp-buffer "*Help*"
6827 (princ help))
6828 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6829 (setq buffer-read-only nil)
6830 (let ((org-startup-truncated t)
6831 (org-startup-folded nil)
6832 (org-startup-align-all-tables nil))
6833 (org-mode)
6834 (org-overview))
6835 (setq buffer-read-only t)
6836 (if (and (boundp 'org-goto-start-pos)
6837 (integer-or-marker-p org-goto-start-pos))
6838 (let ((org-show-hierarchy-above t)
6839 (org-show-siblings t)
6840 (org-show-following-heading t))
6841 (goto-char org-goto-start-pos)
6842 (and (outline-invisible-p) (org-show-context)))
6843 (goto-char (point-min)))
6844 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6845 (message "Select location and press RET")
6846 (use-local-map org-goto-map)
6847 (recursive-edit)
6849 (kill-buffer "*org-goto*")
6850 (cons org-goto-selected-point org-goto-exit-command)))
6852 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6853 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6854 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6855 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6857 (defun org-goto-local-search-headings (string bound noerror)
6858 "Search and make sure that any matches are in headlines."
6859 (catch 'return
6860 (while (if isearch-forward
6861 (search-forward string bound noerror)
6862 (search-backward string bound noerror))
6863 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6864 (and (member :headline context)
6865 (not (member :tags context))))
6866 (throw 'return (point))))))
6868 (defun org-goto-local-auto-isearch ()
6869 "Start isearch."
6870 (interactive)
6871 (goto-char (point-min))
6872 (let ((keys (this-command-keys)))
6873 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6874 (isearch-mode t)
6875 (isearch-process-search-char (string-to-char keys)))))
6877 (defun org-goto-ret (&optional arg)
6878 "Finish `org-goto' by going to the new location."
6879 (interactive "P")
6880 (setq org-goto-selected-point (point)
6881 org-goto-exit-command 'return)
6882 (throw 'exit nil))
6884 (defun org-goto-left ()
6885 "Finish `org-goto' by going to the new location."
6886 (interactive)
6887 (if (org-on-heading-p)
6888 (progn
6889 (beginning-of-line 1)
6890 (setq org-goto-selected-point (point)
6891 org-goto-exit-command 'left)
6892 (throw 'exit nil))
6893 (error "Not on a heading")))
6895 (defun org-goto-right ()
6896 "Finish `org-goto' by going to the new location."
6897 (interactive)
6898 (if (org-on-heading-p)
6899 (progn
6900 (setq org-goto-selected-point (point)
6901 org-goto-exit-command 'right)
6902 (throw 'exit nil))
6903 (error "Not on a heading")))
6905 (defun org-goto-quit ()
6906 "Finish `org-goto' without cursor motion."
6907 (interactive)
6908 (setq org-goto-selected-point nil)
6909 (setq org-goto-exit-command 'quit)
6910 (throw 'exit nil))
6912 ;;; Indirect buffer display of subtrees
6914 (defvar org-indirect-dedicated-frame nil
6915 "This is the frame being used for indirect tree display.")
6916 (defvar org-last-indirect-buffer nil)
6918 (defun org-tree-to-indirect-buffer (&optional arg)
6919 "Create indirect buffer and narrow it to current subtree.
6920 With numerical prefix ARG, go up to this level and then take that tree.
6921 If ARG is negative, go up that many levels.
6922 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6923 indirect buffer previously made with this command, to avoid proliferation of
6924 indirect buffers. However, when you call the command with a \
6925 \\[universal-argument] prefix, or
6926 when `org-indirect-buffer-display' is `new-frame', the last buffer
6927 is kept so that you can work with several indirect buffers at the same time.
6928 If `org-indirect-buffer-display' is `dedicated-frame', the \
6929 \\[universal-argument] prefix also
6930 requests that a new frame be made for the new buffer, so that the dedicated
6931 frame is not changed."
6932 (interactive "P")
6933 (let ((cbuf (current-buffer))
6934 (cwin (selected-window))
6935 (pos (point))
6936 beg end level heading ibuf)
6937 (save-excursion
6938 (org-back-to-heading t)
6939 (when (numberp arg)
6940 (setq level (org-outline-level))
6941 (if (< arg 0) (setq arg (+ level arg)))
6942 (while (> (setq level (org-outline-level)) arg)
6943 (outline-up-heading 1 t)))
6944 (setq beg (point)
6945 heading (org-get-heading))
6946 (org-end-of-subtree t t)
6947 (if (org-on-heading-p) (backward-char 1))
6948 (setq end (point)))
6949 (if (and (buffer-live-p org-last-indirect-buffer)
6950 (not (eq org-indirect-buffer-display 'new-frame))
6951 (not arg))
6952 (kill-buffer org-last-indirect-buffer))
6953 (setq ibuf (org-get-indirect-buffer cbuf)
6954 org-last-indirect-buffer ibuf)
6955 (cond
6956 ((or (eq org-indirect-buffer-display 'new-frame)
6957 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6958 (select-frame (make-frame))
6959 (delete-other-windows)
6960 (org-pop-to-buffer-same-window ibuf)
6961 (org-set-frame-title heading))
6962 ((eq org-indirect-buffer-display 'dedicated-frame)
6963 (raise-frame
6964 (select-frame (or (and org-indirect-dedicated-frame
6965 (frame-live-p org-indirect-dedicated-frame)
6966 org-indirect-dedicated-frame)
6967 (setq org-indirect-dedicated-frame (make-frame)))))
6968 (delete-other-windows)
6969 (org-pop-to-buffer-same-window ibuf)
6970 (org-set-frame-title (concat "Indirect: " heading)))
6971 ((eq org-indirect-buffer-display 'current-window)
6972 (org-pop-to-buffer-same-window ibuf))
6973 ((eq org-indirect-buffer-display 'other-window)
6974 (pop-to-buffer ibuf))
6975 (t (error "Invalid value")))
6976 (if (featurep 'xemacs)
6977 (save-excursion (org-mode) (turn-on-font-lock)))
6978 (narrow-to-region beg end)
6979 (show-all)
6980 (goto-char pos)
6981 (run-hook-with-args 'org-cycle-hook 'all)
6982 (and (window-live-p cwin) (select-window cwin))))
6984 (defun org-get-indirect-buffer (&optional buffer)
6985 (setq buffer (or buffer (current-buffer)))
6986 (let ((n 1) (base (buffer-name buffer)) bname)
6987 (while (buffer-live-p
6988 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6989 (setq n (1+ n)))
6990 (condition-case nil
6991 (make-indirect-buffer buffer bname 'clone)
6992 (error (make-indirect-buffer buffer bname)))))
6994 (defun org-set-frame-title (title)
6995 "Set the title of the current frame to the string TITLE."
6996 ;; FIXME: how to name a single frame in XEmacs???
6997 (unless (featurep 'xemacs)
6998 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7000 ;;;; Structure editing
7002 ;;; Inserting headlines
7004 (defun org-previous-line-empty-p ()
7005 (save-excursion
7006 (and (not (bobp))
7007 (or (beginning-of-line 0) t)
7008 (save-match-data
7009 (looking-at "[ \t]*$")))))
7011 (defun org-insert-heading (&optional force-heading invisible-ok)
7012 "Insert a new heading or item with same depth at point.
7013 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7014 If point is at the beginning of a headline, insert a sibling before the
7015 current headline. If point is not at the beginning, split the line,
7016 create the new headline with the text in the current line after point
7017 \(but see also the variable `org-M-RET-may-split-line').
7019 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7020 This is important for non-interactive uses of the command."
7021 (interactive "P")
7022 (if (or (= (buffer-size) 0)
7023 (and (not (save-excursion
7024 (and (ignore-errors (org-back-to-heading invisible-ok))
7025 (org-on-heading-p))))
7026 (or force-heading (not (org-in-item-p)))))
7027 (progn
7028 (insert "\n* ")
7029 (run-hooks 'org-insert-heading-hook))
7030 (when (or force-heading (not (org-insert-item)))
7031 (let* ((empty-line-p nil)
7032 (level nil)
7033 (on-heading (org-on-heading-p))
7034 (head (save-excursion
7035 (condition-case nil
7036 (progn
7037 (org-back-to-heading invisible-ok)
7038 (when (and (not on-heading)
7039 (featurep 'org-inlinetask)
7040 (integerp org-inlinetask-min-level)
7041 (>= (length (match-string 0))
7042 org-inlinetask-min-level))
7043 ;; Find a heading level before the inline task
7044 (while (and (setq level (org-up-heading-safe))
7045 (>= level org-inlinetask-min-level)))
7046 (if (org-on-heading-p)
7047 (org-back-to-heading invisible-ok)
7048 (error "This should not happen")))
7049 (setq empty-line-p (org-previous-line-empty-p))
7050 (match-string 0))
7051 (error "*"))))
7052 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7053 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7054 pos hide-previous previous-pos)
7055 (cond
7056 ((and (org-on-heading-p) (bolp)
7057 (or (bobp)
7058 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7059 ;; insert before the current line
7060 (open-line (if blank 2 1)))
7061 ((and (bolp)
7062 (not org-insert-heading-respect-content)
7063 (or (bobp)
7064 (save-excursion
7065 (backward-char 1) (not (outline-invisible-p)))))
7066 ;; insert right here
7067 nil)
7069 ;; somewhere in the line
7070 (save-excursion
7071 (setq previous-pos (point-at-bol))
7072 (end-of-line)
7073 (setq hide-previous (outline-invisible-p)))
7074 (and org-insert-heading-respect-content (org-show-subtree))
7075 (let ((split
7076 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7077 (save-excursion
7078 (let ((p (point)))
7079 (goto-char (point-at-bol))
7080 (and (looking-at org-complex-heading-regexp)
7081 (match-beginning 4)
7082 (> p (match-beginning 4)))))))
7083 tags pos)
7084 (cond
7085 (org-insert-heading-respect-content
7086 (org-end-of-subtree nil t)
7087 (when (featurep 'org-inlinetask)
7088 (while (and (not (eobp))
7089 (looking-at "\\(\\*+\\)[ \t]+")
7090 (>= (length (match-string 1))
7091 org-inlinetask-min-level))
7092 (org-end-of-subtree nil t)))
7093 (or (bolp) (newline))
7094 (or (org-previous-line-empty-p)
7095 (and blank (newline)))
7096 (open-line 1))
7097 ((org-on-heading-p)
7098 (when hide-previous
7099 (show-children)
7100 (org-show-entry))
7101 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7102 (setq tags (and (match-end 2) (match-string 2)))
7103 (and (match-end 1)
7104 (delete-region (match-beginning 1) (match-end 1)))
7105 (setq pos (point-at-bol))
7106 (or split (end-of-line 1))
7107 (delete-horizontal-space)
7108 (if (string-match "\\`\\*+\\'"
7109 (buffer-substring (point-at-bol) (point)))
7110 (insert " "))
7111 (newline (if blank 2 1))
7112 (when tags
7113 (save-excursion
7114 (goto-char pos)
7115 (end-of-line 1)
7116 (insert " " tags)
7117 (org-set-tags nil 'align))))
7119 (or split (end-of-line 1))
7120 (newline (if blank 2 1)))))))
7121 (insert head) (just-one-space)
7122 (setq pos (point))
7123 (end-of-line 1)
7124 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7125 (when (and org-insert-heading-respect-content hide-previous)
7126 (save-excursion
7127 (goto-char previous-pos)
7128 (hide-subtree)))
7129 (run-hooks 'org-insert-heading-hook)))))
7131 (defun org-get-heading (&optional no-tags no-todo)
7132 "Return the heading of the current entry, without the stars.
7133 When NO-TAGS is non-nil, don't include tags.
7134 When NO-TODO is non-nil, don't include TODO keywords."
7135 (save-excursion
7136 (org-back-to-heading t)
7137 (cond
7138 ((and no-tags no-todo)
7139 (looking-at org-complex-heading-regexp)
7140 (match-string 4))
7141 (no-tags
7142 (looking-at (concat org-outline-regexp
7143 "\\(.*?\\)"
7144 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7145 (match-string 1))
7146 (no-todo
7147 (looking-at org-todo-line-regexp)
7148 (match-string 3))
7149 (t (looking-at org-heading-regexp)
7150 (match-string 2)))))
7152 (defun org-heading-components ()
7153 "Return the components of the current heading.
7154 This is a list with the following elements:
7155 - the level as an integer
7156 - the reduced level, different if `org-odd-levels-only' is set.
7157 - the TODO keyword, or nil
7158 - the priority character, like ?A, or nil if no priority is given
7159 - the headline text itself, or the tags string if no headline text
7160 - the tags string, or nil."
7161 (save-excursion
7162 (org-back-to-heading t)
7163 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7164 (list (length (match-string 1))
7165 (org-reduced-level (length (match-string 1)))
7166 (org-match-string-no-properties 2)
7167 (and (match-end 3) (aref (match-string 3) 2))
7168 (org-match-string-no-properties 4)
7169 (org-match-string-no-properties 5)))))
7171 (defun org-get-entry ()
7172 "Get the entry text, after heading, entire subtree."
7173 (save-excursion
7174 (org-back-to-heading t)
7175 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7177 (defun org-insert-heading-after-current ()
7178 "Insert a new heading with same level as current, after current subtree."
7179 (interactive)
7180 (org-back-to-heading)
7181 (org-insert-heading)
7182 (org-move-subtree-down)
7183 (end-of-line 1))
7185 (defun org-insert-heading-respect-content ()
7186 (interactive)
7187 (let ((org-insert-heading-respect-content t))
7188 (org-insert-heading t)))
7190 (defun org-insert-todo-heading-respect-content (&optional force-state)
7191 (interactive "P")
7192 (let ((org-insert-heading-respect-content t))
7193 (org-insert-todo-heading force-state t)))
7195 (defun org-insert-todo-heading (arg &optional force-heading)
7196 "Insert a new heading with the same level and TODO state as current heading.
7197 If the heading has no TODO state, or if the state is DONE, use the first
7198 state (TODO by default). Also with prefix arg, force first state."
7199 (interactive "P")
7200 (when (or force-heading (not (org-insert-item 'checkbox)))
7201 (org-insert-heading force-heading)
7202 (save-excursion
7203 (org-back-to-heading)
7204 (outline-previous-heading)
7205 (looking-at org-todo-line-regexp))
7206 (let*
7207 ((new-mark-x
7208 (if (or arg
7209 (not (match-beginning 2))
7210 (member (match-string 2) org-done-keywords))
7211 (car org-todo-keywords-1)
7212 (match-string 2)))
7213 (new-mark
7215 (run-hook-with-args-until-success
7216 'org-todo-get-default-hook new-mark-x nil)
7217 new-mark-x)))
7218 (beginning-of-line 1)
7219 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7220 (if org-treat-insert-todo-heading-as-state-change
7221 (org-todo new-mark)
7222 (insert new-mark " "))))
7223 (when org-provide-todo-statistics
7224 (org-update-parent-todo-statistics))))
7226 (defun org-insert-subheading (arg)
7227 "Insert a new subheading and demote it.
7228 Works for outline headings and for plain lists alike."
7229 (interactive "P")
7230 (org-insert-heading arg)
7231 (cond
7232 ((org-on-heading-p) (org-do-demote))
7233 ((org-at-item-p) (org-indent-item))))
7235 (defun org-insert-todo-subheading (arg)
7236 "Insert a new subheading with TODO keyword or checkbox and demote it.
7237 Works for outline headings and for plain lists alike."
7238 (interactive "P")
7239 (org-insert-todo-heading arg)
7240 (cond
7241 ((org-on-heading-p) (org-do-demote))
7242 ((org-at-item-p) (org-indent-item))))
7244 ;;; Promotion and Demotion
7246 (defvar org-after-demote-entry-hook nil
7247 "Hook run after an entry has been demoted.
7248 The cursor will be at the beginning of the entry.
7249 When a subtree is being demoted, the hook will be called for each node.")
7251 (defvar org-after-promote-entry-hook nil
7252 "Hook run after an entry has been promoted.
7253 The cursor will be at the beginning of the entry.
7254 When a subtree is being promoted, the hook will be called for each node.")
7256 (defun org-promote-subtree ()
7257 "Promote the entire subtree.
7258 See also `org-promote'."
7259 (interactive)
7260 (save-excursion
7261 (org-with-limited-levels (org-map-tree 'org-promote)))
7262 (org-fix-position-after-promote))
7264 (defun org-demote-subtree ()
7265 "Demote the entire subtree. See `org-demote'.
7266 See also `org-promote'."
7267 (interactive)
7268 (save-excursion
7269 (org-with-limited-levels (org-map-tree 'org-demote)))
7270 (org-fix-position-after-promote))
7273 (defun org-do-promote ()
7274 "Promote the current heading higher up the tree.
7275 If the region is active in `transient-mark-mode', promote all headings
7276 in the region."
7277 (interactive)
7278 (save-excursion
7279 (if (org-region-active-p)
7280 (org-map-region 'org-promote (region-beginning) (region-end))
7281 (org-promote)))
7282 (org-fix-position-after-promote))
7284 (defun org-do-demote ()
7285 "Demote the current heading lower down the tree.
7286 If the region is active in `transient-mark-mode', demote all headings
7287 in the region."
7288 (interactive)
7289 (save-excursion
7290 (if (org-region-active-p)
7291 (org-map-region 'org-demote (region-beginning) (region-end))
7292 (org-demote)))
7293 (org-fix-position-after-promote))
7295 (defun org-fix-position-after-promote ()
7296 "Make sure that after pro/demotion cursor position is right."
7297 (let ((pos (point)))
7298 (when (save-excursion
7299 (beginning-of-line 1)
7300 (looking-at org-todo-line-regexp)
7301 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7302 (cond ((eobp) (insert " "))
7303 ((eolp) (insert " "))
7304 ((equal (char-after) ?\ ) (forward-char 1))))))
7306 (defun org-current-level ()
7307 "Return the level of the current entry, or nil if before the first headline.
7308 The level is the number of stars at the beginning of the headline."
7309 (save-excursion
7310 (org-with-limited-levels
7311 (if (ignore-errors (org-back-to-heading t))
7312 (funcall outline-level)))))
7314 (defun org-get-previous-line-level ()
7315 "Return the outline depth of the last headline before the current line.
7316 Returns 0 for the first headline in the buffer, and nil if before the
7317 first headline."
7318 (let ((current-level (org-current-level))
7319 (prev-level (when (> (line-number-at-pos) 1)
7320 (save-excursion
7321 (beginning-of-line 0)
7322 (org-current-level)))))
7323 (cond ((null current-level) nil) ; Before first headline
7324 ((null prev-level) 0) ; At first headline
7325 (prev-level))))
7327 (defun org-reduced-level (l)
7328 "Compute the effective level of a heading.
7329 This takes into account the setting of `org-odd-levels-only'."
7330 (cond
7331 ((zerop l) 0)
7332 (org-odd-levels-only (1+ (floor (/ l 2))))
7333 (t l)))
7335 (defun org-level-increment ()
7336 "Return the number of stars that will be added or removed at a
7337 time to headlines when structure editing, based on the value of
7338 `org-odd-levels-only'."
7339 (if org-odd-levels-only 2 1))
7341 (defun org-get-valid-level (level &optional change)
7342 "Rectify a level change under the influence of `org-odd-levels-only'
7343 LEVEL is a current level, CHANGE is by how much the level should be
7344 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7345 even level numbers will become the next higher odd number."
7346 (if org-odd-levels-only
7347 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7348 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7349 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7350 (max 1 (+ level (or change 0)))))
7352 (if (boundp 'define-obsolete-function-alias)
7353 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7354 (define-obsolete-function-alias 'org-get-legal-level
7355 'org-get-valid-level)
7356 (define-obsolete-function-alias 'org-get-legal-level
7357 'org-get-valid-level "23.1")))
7359 (defun org-promote ()
7360 "Promote the current heading higher up the tree.
7361 If the region is active in `transient-mark-mode', promote all headings
7362 in the region."
7363 (org-back-to-heading t)
7364 (let* ((level (save-match-data (funcall outline-level)))
7365 (after-change-functions (remove 'flyspell-after-change-function
7366 after-change-functions))
7367 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7368 (diff (abs (- level (length up-head) -1))))
7369 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
7370 (replace-match up-head nil t)
7371 ;; Fixup tag positioning
7372 (and org-auto-align-tags (org-set-tags nil t))
7373 (if org-adapt-indentation (org-fixup-indentation (- diff)))
7374 (run-hooks 'org-after-promote-entry-hook)))
7376 (defun org-demote ()
7377 "Demote the current heading lower down the tree.
7378 If the region is active in `transient-mark-mode', demote all headings
7379 in the region."
7380 (org-back-to-heading t)
7381 (let* ((level (save-match-data (funcall outline-level)))
7382 (after-change-functions (remove 'flyspell-after-change-function
7383 after-change-functions))
7384 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7385 (diff (abs (- level (length down-head) -1))))
7386 (replace-match down-head nil t)
7387 ;; Fixup tag positioning
7388 (and org-auto-align-tags (org-set-tags nil t))
7389 (if org-adapt-indentation (org-fixup-indentation diff))
7390 (run-hooks 'org-after-demote-entry-hook)))
7392 (defun org-cycle-level ()
7393 "Cycle the level of an empty headline through possible states.
7394 This goes first to child, then to parent, level, then up the hierarchy.
7395 After top level, it switches back to sibling level."
7396 (interactive)
7397 (let ((org-adapt-indentation nil))
7398 (when (org-point-at-end-of-empty-headline)
7399 (setq this-command 'org-cycle-level) ; Only needed for caching
7400 (let ((cur-level (org-current-level))
7401 (prev-level (org-get-previous-line-level)))
7402 (cond
7403 ;; If first headline in file, promote to top-level.
7404 ((= prev-level 0)
7405 (loop repeat (/ (- cur-level 1) (org-level-increment))
7406 do (org-do-promote)))
7407 ;; If same level as prev, demote one.
7408 ((= prev-level cur-level)
7409 (org-do-demote))
7410 ;; If parent is top-level, promote to top level if not already.
7411 ((= prev-level 1)
7412 (loop repeat (/ (- cur-level 1) (org-level-increment))
7413 do (org-do-promote)))
7414 ;; If top-level, return to prev-level.
7415 ((= cur-level 1)
7416 (loop repeat (/ (- prev-level 1) (org-level-increment))
7417 do (org-do-demote)))
7418 ;; If less than prev-level, promote one.
7419 ((< cur-level prev-level)
7420 (org-do-promote))
7421 ;; If deeper than prev-level, promote until higher than
7422 ;; prev-level.
7423 ((> cur-level prev-level)
7424 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7425 do (org-do-promote))))
7426 t))))
7428 (defun org-map-tree (fun)
7429 "Call FUN for every heading underneath the current one."
7430 (org-back-to-heading)
7431 (let ((level (funcall outline-level)))
7432 (save-excursion
7433 (funcall fun)
7434 (while (and (progn
7435 (outline-next-heading)
7436 (> (funcall outline-level) level))
7437 (not (eobp)))
7438 (funcall fun)))))
7440 (defun org-map-region (fun beg end)
7441 "Call FUN for every heading between BEG and END."
7442 (let ((org-ignore-region t))
7443 (save-excursion
7444 (setq end (copy-marker end))
7445 (goto-char beg)
7446 (if (and (re-search-forward org-outline-regexp-bol nil t)
7447 (< (point) end))
7448 (funcall fun))
7449 (while (and (progn
7450 (outline-next-heading)
7451 (< (point) end))
7452 (not (eobp)))
7453 (funcall fun)))))
7455 (defvar org-property-end-re) ; silence byte-compiler
7456 (defun org-fixup-indentation (diff)
7457 "Change the indentation in the current entry by DIFF.
7458 However, if any line in the current entry has no indentation, or if it
7459 would end up with no indentation after the change, nothing at all is done."
7460 (save-excursion
7461 (let ((end (save-excursion (outline-next-heading)
7462 (point-marker)))
7463 (prohibit (if (> diff 0)
7464 "^\\S-"
7465 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7466 col)
7467 (unless (save-excursion (end-of-line 1)
7468 (re-search-forward prohibit end t))
7469 (while (and (< (point) end)
7470 (re-search-forward "^[ \t]+" end t))
7471 (goto-char (match-end 0))
7472 (setq col (current-column))
7473 (if (< diff 0) (replace-match ""))
7474 (org-indent-to-column (+ diff col))))
7475 (move-marker end nil))))
7477 (defun org-convert-to-odd-levels ()
7478 "Convert an org-mode file with all levels allowed to one with odd levels.
7479 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7480 level 5 etc."
7481 (interactive)
7482 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7483 (let ((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 (- (length (match-string 0)) 2))
7489 (while (>= (setq n (1- n)) 0)
7490 (org-demote))
7491 (end-of-line 1))))))
7493 (defun org-convert-to-oddeven-levels ()
7494 "Convert an org-mode file with only odd levels to one with odd/even levels.
7495 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7496 file contains a section with an even level, conversion would
7497 destroy the structure of the file. An error is signaled in this
7498 case."
7499 (interactive)
7500 (goto-char (point-min))
7501 ;; First check if there are no even levels
7502 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7503 (org-show-context t)
7504 (error "Not all levels are odd in this file. Conversion not possible"))
7505 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7506 (let ((outline-regexp org-outline-regexp)
7507 (outline-level 'org-outline-level)
7508 (org-odd-levels-only nil) n)
7509 (save-excursion
7510 (goto-char (point-min))
7511 (while (re-search-forward "^\\*\\*+ " nil t)
7512 (setq n (/ (1- (length (match-string 0))) 2))
7513 (while (>= (setq n (1- n)) 0)
7514 (org-promote))
7515 (end-of-line 1))))))
7517 (defun org-tr-level (n)
7518 "Make N odd if required."
7519 (if org-odd-levels-only (1+ (/ n 2)) n))
7521 ;;; Vertical tree motion, cutting and pasting of subtrees
7523 (defun org-move-subtree-up (&optional arg)
7524 "Move the current subtree up past ARG headlines of the same level."
7525 (interactive "p")
7526 (org-move-subtree-down (- (prefix-numeric-value arg))))
7528 (defun org-move-subtree-down (&optional arg)
7529 "Move the current subtree down past ARG headlines of the same level."
7530 (interactive "p")
7531 (setq arg (prefix-numeric-value arg))
7532 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7533 'org-get-last-sibling))
7534 (ins-point (make-marker))
7535 (cnt (abs arg))
7536 (col (current-column))
7537 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7538 ;; Select the tree
7539 (org-back-to-heading)
7540 (setq beg0 (point))
7541 (save-excursion
7542 (setq ne-beg (org-back-over-empty-lines))
7543 (setq beg (point)))
7544 (save-match-data
7545 (save-excursion (outline-end-of-heading)
7546 (setq folded (outline-invisible-p)))
7547 (outline-end-of-subtree))
7548 (outline-next-heading)
7549 (setq ne-end (org-back-over-empty-lines))
7550 (setq end (point))
7551 (goto-char beg0)
7552 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7553 ;; include less whitespace
7554 (save-excursion
7555 (goto-char beg)
7556 (forward-line (- ne-beg ne-end))
7557 (setq beg (point))))
7558 ;; Find insertion point, with error handling
7559 (while (> cnt 0)
7560 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7561 (progn (goto-char beg0)
7562 (error "Cannot move past superior level or buffer limit")))
7563 (setq cnt (1- cnt)))
7564 (if (> arg 0)
7565 ;; Moving forward - still need to move over subtree
7566 (progn (org-end-of-subtree t t)
7567 (save-excursion
7568 (org-back-over-empty-lines)
7569 (or (bolp) (newline)))))
7570 (setq ne-ins (org-back-over-empty-lines))
7571 (move-marker ins-point (point))
7572 (setq txt (buffer-substring beg end))
7573 (org-save-markers-in-region beg end)
7574 (delete-region beg end)
7575 (org-remove-empty-overlays-at beg)
7576 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7577 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7578 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7579 (let ((bbb (point)))
7580 (insert-before-markers txt)
7581 (org-reinstall-markers-in-region bbb)
7582 (move-marker ins-point bbb))
7583 (or (bolp) (insert "\n"))
7584 (setq ins-end (point))
7585 (goto-char ins-point)
7586 (org-skip-whitespace)
7587 (when (and (< arg 0)
7588 (org-first-sibling-p)
7589 (> ne-ins ne-beg))
7590 ;; Move whitespace back to beginning
7591 (save-excursion
7592 (goto-char ins-end)
7593 (let ((kill-whole-line t))
7594 (kill-line (- ne-ins ne-beg)) (point)))
7595 (insert (make-string (- ne-ins ne-beg) ?\n)))
7596 (move-marker ins-point nil)
7597 (if folded
7598 (hide-subtree)
7599 (org-show-entry)
7600 (show-children)
7601 (org-cycle-hide-drawers 'children))
7602 (org-clean-visibility-after-subtree-move)
7603 ;; move back to the initial column we were at
7604 (move-to-column col)))
7606 (defvar org-subtree-clip ""
7607 "Clipboard for cut and paste of subtrees.
7608 This is actually only a copy of the kill, because we use the normal kill
7609 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7611 (defvar org-subtree-clip-folded nil
7612 "Was the last copied subtree folded?
7613 This is used to fold the tree back after pasting.")
7615 (defun org-cut-subtree (&optional n)
7616 "Cut the current subtree into the clipboard.
7617 With prefix arg N, cut this many sequential subtrees.
7618 This is a short-hand for marking the subtree and then cutting it."
7619 (interactive "p")
7620 (org-copy-subtree n 'cut))
7622 (defun org-copy-subtree (&optional n cut force-store-markers)
7623 "Cut the current subtree into the clipboard.
7624 With prefix arg N, cut this many sequential subtrees.
7625 This is a short-hand for marking the subtree and then copying it.
7626 If CUT is non-nil, actually cut the subtree.
7627 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7628 of some markers in the region, even if CUT is non-nil. This is
7629 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7630 (interactive "p")
7631 (let (beg end folded (beg0 (point)))
7632 (if (org-called-interactively-p 'any)
7633 (org-back-to-heading nil) ; take what looks like a subtree
7634 (org-back-to-heading t)) ; take what is really there
7635 (org-back-over-empty-lines)
7636 (setq beg (point))
7637 (skip-chars-forward " \t\r\n")
7638 (save-match-data
7639 (save-excursion (outline-end-of-heading)
7640 (setq folded (outline-invisible-p)))
7641 (condition-case nil
7642 (org-forward-same-level (1- n) t)
7643 (error nil))
7644 (org-end-of-subtree t t))
7645 (org-back-over-empty-lines)
7646 (setq end (point))
7647 (goto-char beg0)
7648 (when (> end beg)
7649 (setq org-subtree-clip-folded folded)
7650 (when (or cut force-store-markers)
7651 (org-save-markers-in-region beg end))
7652 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7653 (setq org-subtree-clip (current-kill 0))
7654 (message "%s: Subtree(s) with %d characters"
7655 (if cut "Cut" "Copied")
7656 (length org-subtree-clip)))))
7658 (defun org-paste-subtree (&optional level tree for-yank)
7659 "Paste the clipboard as a subtree, with modification of headline level.
7660 The entire subtree is promoted or demoted in order to match a new headline
7661 level.
7663 If the cursor is at the beginning of a headline, the same level as
7664 that headline is used to paste the tree
7666 If not, the new level is derived from the *visible* headings
7667 before and after the insertion point, and taken to be the inferior headline
7668 level of the two. So if the previous visible heading is level 3 and the
7669 next is level 4 (or vice versa), level 4 will be used for insertion.
7670 This makes sure that the subtree remains an independent subtree and does
7671 not swallow low level entries.
7673 You can also force a different level, either by using a numeric prefix
7674 argument, or by inserting the heading marker by hand. For example, if the
7675 cursor is after \"*****\", then the tree will be shifted to level 5.
7677 If optional TREE is given, use this text instead of the kill ring.
7679 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7680 move back over whitespace before inserting, and move point to the end of
7681 the inserted text when done."
7682 (interactive "P")
7683 (setq tree (or tree (and kill-ring (current-kill 0))))
7684 (unless (org-kill-is-subtree-p tree)
7685 (error "%s"
7686 (substitute-command-keys
7687 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7688 (org-with-limited-levels
7689 (let* ((visp (not (outline-invisible-p)))
7690 (txt tree)
7691 (^re_ "\\(\\*+\\)[ \t]*")
7692 (old-level (if (string-match org-outline-regexp-bol txt)
7693 (- (match-end 0) (match-beginning 0) 1)
7694 -1))
7695 (force-level (cond (level (prefix-numeric-value level))
7696 ((and (looking-at "[ \t]*$")
7697 (string-match
7698 "^\\*+$" (buffer-substring
7699 (point-at-bol) (point))))
7700 (- (match-end 1) (match-beginning 1)))
7701 ((and (bolp)
7702 (looking-at org-outline-regexp))
7703 (- (match-end 0) (point) 1))
7704 (t nil)))
7705 (previous-level (save-excursion
7706 (condition-case nil
7707 (progn
7708 (outline-previous-visible-heading 1)
7709 (if (looking-at ^re_)
7710 (- (match-end 0) (match-beginning 0) 1)
7712 (error 1))))
7713 (next-level (save-excursion
7714 (condition-case nil
7715 (progn
7716 (or (looking-at org-outline-regexp)
7717 (outline-next-visible-heading 1))
7718 (if (looking-at ^re_)
7719 (- (match-end 0) (match-beginning 0) 1)
7721 (error 1))))
7722 (new-level (or force-level (max previous-level next-level)))
7723 (shift (if (or (= old-level -1)
7724 (= new-level -1)
7725 (= old-level new-level))
7727 (- new-level old-level)))
7728 (delta (if (> shift 0) -1 1))
7729 (func (if (> shift 0) 'org-demote 'org-promote))
7730 (org-odd-levels-only nil)
7731 beg end newend)
7732 ;; Remove the forced level indicator
7733 (if force-level
7734 (delete-region (point-at-bol) (point)))
7735 ;; Paste
7736 (beginning-of-line (if (bolp) 1 2))
7737 (unless for-yank (org-back-over-empty-lines))
7738 (setq beg (point))
7739 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7740 (insert-before-markers txt)
7741 (unless (string-match "\n\\'" txt) (insert "\n"))
7742 (setq newend (point))
7743 (org-reinstall-markers-in-region beg)
7744 (setq end (point))
7745 (goto-char beg)
7746 (skip-chars-forward " \t\n\r")
7747 (setq beg (point))
7748 (if (and (outline-invisible-p) visp)
7749 (save-excursion (outline-show-heading)))
7750 ;; Shift if necessary
7751 (unless (= shift 0)
7752 (save-restriction
7753 (narrow-to-region beg end)
7754 (while (not (= shift 0))
7755 (org-map-region func (point-min) (point-max))
7756 (setq shift (+ delta shift)))
7757 (goto-char (point-min))
7758 (setq newend (point-max))))
7759 (when (or (org-called-interactively-p 'interactive) for-yank)
7760 (message "Clipboard pasted as level %d subtree" new-level))
7761 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7762 kill-ring
7763 (eq org-subtree-clip (current-kill 0))
7764 org-subtree-clip-folded)
7765 ;; The tree was folded before it was killed/copied
7766 (hide-subtree))
7767 (and for-yank (goto-char newend)))))
7769 (defun org-kill-is-subtree-p (&optional txt)
7770 "Check if the current kill is an outline subtree, or a set of trees.
7771 Returns nil if kill does not start with a headline, or if the first
7772 headline level is not the largest headline level in the tree.
7773 So this will actually accept several entries of equal levels as well,
7774 which is OK for `org-paste-subtree'.
7775 If optional TXT is given, check this string instead of the current kill."
7776 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7777 (re (org-get-limited-outline-regexp))
7778 (^re (concat "^" re))
7779 (start-level (and kill
7780 (string-match
7781 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7782 kill)
7783 (- (match-end 2) (match-beginning 2) 1)))
7784 (start (1+ (or (match-beginning 2) -1))))
7785 (if (not start-level)
7786 (progn
7787 nil) ;; does not even start with a heading
7788 (catch 'exit
7789 (while (setq start (string-match ^re kill (1+ start)))
7790 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7791 (throw 'exit nil)))
7792 t))))
7794 (defvar org-markers-to-move nil
7795 "Markers that should be moved with a cut-and-paste operation.
7796 Those markers are stored together with their positions relative to
7797 the start of the region.")
7799 (defun org-save-markers-in-region (beg end)
7800 "Check markers in region.
7801 If these markers are between BEG and END, record their position relative
7802 to BEG, so that after moving the block of text, we can put the markers back
7803 into place.
7804 This function gets called just before an entry or tree gets cut from the
7805 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7806 called immediately, to move the markers with the entries."
7807 (setq org-markers-to-move nil)
7808 (when (featurep 'org-clock)
7809 (org-clock-save-markers-for-cut-and-paste beg end))
7810 (when (featurep 'org-agenda)
7811 (org-agenda-save-markers-for-cut-and-paste beg end)))
7813 (defun org-check-and-save-marker (marker beg end)
7814 "Check if MARKER is between BEG and END.
7815 If yes, remember the marker and the distance to BEG."
7816 (when (and (marker-buffer marker)
7817 (equal (marker-buffer marker) (current-buffer)))
7818 (if (and (>= marker beg) (< marker end))
7819 (push (cons marker (- marker beg)) org-markers-to-move))))
7821 (defun org-reinstall-markers-in-region (beg)
7822 "Move all remembered markers to their position relative to BEG."
7823 (mapc (lambda (x)
7824 (move-marker (car x) (+ beg (cdr x))))
7825 org-markers-to-move)
7826 (setq org-markers-to-move nil))
7828 (defun org-narrow-to-subtree ()
7829 "Narrow buffer to the current subtree."
7830 (interactive)
7831 (save-excursion
7832 (save-match-data
7833 (org-with-limited-levels
7834 (narrow-to-region
7835 (progn (org-back-to-heading t) (point))
7836 (progn (org-end-of-subtree t t)
7837 (if (and (org-on-heading-p) (not (eobp))) (backward-char 1))
7838 (point)))))))
7840 (defun org-narrow-to-block ()
7841 "Narrow buffer to the current block."
7842 (interactive)
7843 (let* ((case-fold-search t)
7844 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7845 "^[ \t]*#\\+end_.*")))
7846 (if blockp
7847 (narrow-to-region (car blockp) (cdr blockp))
7848 (error "Not in a block"))))
7850 (eval-when-compile
7851 (defvar org-property-drawer-re))
7853 (defvar org-property-start-re) ;; defined below
7854 (defun org-clone-subtree-with-time-shift (n &optional shift)
7855 "Clone the task (subtree) at point N times.
7856 The clones will be inserted as siblings.
7858 In interactive use, the user will be prompted for the number of
7859 clones to be produced, and for a time SHIFT, which may be a
7860 repeater as used in time stamps, for example `+3d'.
7862 When a valid repeater is given and the entry contains any time
7863 stamps, the clones will become a sequence in time, with time
7864 stamps in the subtree shifted for each clone produced. If SHIFT
7865 is nil or the empty string, time stamps will be left alone. The
7866 ID property of the original subtree is removed.
7868 If the original subtree did contain time stamps with a repeater,
7869 the following will happen:
7870 - the repeater will be removed in each clone
7871 - an additional clone will be produced, with the current, unshifted
7872 date(s) in the entry.
7873 - the original entry will be placed *after* all the clones, with
7874 repeater intact.
7875 - the start days in the repeater in the original entry will be shifted
7876 to past the last clone.
7877 I this way you can spell out a number of instances of a repeating task,
7878 and still retain the repeater to cover future instances of the task."
7879 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7880 (let (beg end template task idprop
7881 shift-n shift-what doshift nmin nmax (n-no-remove -1))
7882 (if (not (and (integerp n) (> n 0)))
7883 (error "Invalid number of replications %s" n))
7884 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7885 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
7886 shift)))
7887 (error "Invalid shift specification %s" shift))
7888 (when doshift
7889 (setq shift-n (string-to-number (match-string 1 shift))
7890 shift-what (cdr (assoc (match-string 2 shift)
7891 '(("d" . day) ("w" . week)
7892 ("m" . month) ("y" . year))))))
7893 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7894 (setq nmin 1 nmax n)
7895 (org-back-to-heading t)
7896 (setq beg (point))
7897 (setq idprop (org-entry-get nil "ID"))
7898 (org-end-of-subtree t t)
7899 (or (bolp) (insert "\n"))
7900 (setq end (point))
7901 (setq template (buffer-substring beg end))
7902 ;; Remove clocks and empty drawers
7903 (with-temp-buffer
7904 (insert template)
7905 (goto-char (point-min))
7906 (while (re-search-forward
7907 "^[ \t]*CLOCK:.*$" (save-excursion (org-end-of-subtree t t)) t)
7908 (replace-match "")
7909 (kill-whole-line))
7910 (goto-char (point-min))
7911 (while (re-search-forward
7912 (concat "^[ \t]*:" (regexp-opt org-drawers) ":[ \t]*$") nil t)
7913 (mapc (lambda(d) (org-remove-empty-drawer-at d (point))) org-drawers))
7914 (setq template (buffer-substring (point-min) (point-max))))
7915 (when (and doshift
7916 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
7917 (delete-region beg end)
7918 (setq end beg)
7919 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7920 (goto-char end)
7921 (loop for n from nmin to nmax do
7922 ;; prepare clone
7923 (with-temp-buffer
7924 (insert template)
7925 (org-mode)
7926 (goto-char (point-min))
7927 (and idprop (if org-clone-delete-id
7928 (org-entry-delete nil "ID")
7929 (org-id-get-create t)))
7930 (while (re-search-forward org-property-start-re nil t)
7931 (org-remove-empty-drawer-at "PROPERTIES" (point)))
7932 (goto-char (point-min))
7933 (when doshift
7934 (while (re-search-forward org-ts-regexp-both nil t)
7935 (org-timestamp-change (* n shift-n) shift-what))
7936 (unless (= n n-no-remove)
7937 (goto-char (point-min))
7938 (while (re-search-forward org-ts-regexp nil t)
7939 (save-excursion
7940 (goto-char (match-beginning 0))
7941 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
7942 (delete-region (match-beginning 1) (match-end 1)))))))
7943 (setq task (buffer-string)))
7944 (insert task))
7945 (goto-char beg)))
7947 ;;; Outline Sorting
7949 (defun org-sort (with-case)
7950 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
7951 Optional argument WITH-CASE means sort case-sensitively.
7952 With a double prefix argument, also remove duplicate entries."
7953 (interactive "P")
7954 (cond
7955 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
7956 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
7958 (org-call-with-arg 'org-sort-entries with-case))))
7960 (defun org-sort-remove-invisible (s)
7961 (remove-text-properties 0 (length s) org-rm-props s)
7962 (while (string-match org-bracket-link-regexp s)
7963 (setq s (replace-match (if (match-end 2)
7964 (match-string 3 s)
7965 (match-string 1 s)) t t s)))
7968 (defvar org-priority-regexp) ; defined later in the file
7970 (defvar org-after-sorting-entries-or-items-hook nil
7971 "Hook that is run after a bunch of entries or items have been sorted.
7972 When children are sorted, the cursor is in the parent line when this
7973 hook gets called. When a region or a plain list is sorted, the cursor
7974 will be in the first entry of the sorted region/list.")
7976 (defun org-sort-entries
7977 (&optional with-case sorting-type getkey-func compare-func property)
7978 "Sort entries on a certain level of an outline tree.
7979 If there is an active region, the entries in the region are sorted.
7980 Else, if the cursor is before the first entry, sort the top-level items.
7981 Else, the children of the entry at point are sorted.
7983 Sorting can be alphabetically, numerically, by date/time as given by
7984 a time stamp, by a property or by priority.
7986 The command prompts for the sorting type unless it has been given to the
7987 function through the SORTING-TYPE argument, which needs to be a character,
7988 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
7989 precise meaning of each character:
7991 n Numerically, by converting the beginning of the entry/item to a number.
7992 a Alphabetically, ignoring the TODO keyword and the priority, if any.
7993 t By date/time, either the first active time stamp in the entry, or, if
7994 none exist, by the first inactive one.
7995 s By the scheduled date/time.
7996 d By deadline date/time.
7997 c By creation time, which is assumed to be the first inactive time stamp
7998 at the beginning of a line.
7999 p By priority according to the cookie.
8000 r By the value of a property.
8002 Capital letters will reverse the sort order.
8004 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8005 called with point at the beginning of the record. It must return either
8006 a string or a number that should serve as the sorting key for that record.
8008 Comparing entries ignores case by default. However, with an optional argument
8009 WITH-CASE, the sorting considers case as well."
8010 (interactive "P")
8011 (let ((case-func (if with-case 'identity 'downcase))
8012 start beg end stars re re2
8013 txt what tmp)
8014 ;; Find beginning and end of region to sort
8015 (cond
8016 ((org-region-active-p)
8017 ;; we will sort the region
8018 (setq end (region-end)
8019 what "region")
8020 (goto-char (region-beginning))
8021 (if (not (org-on-heading-p)) (outline-next-heading))
8022 (setq start (point)))
8023 ((or (org-on-heading-p)
8024 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8025 ;; we will sort the children of the current headline
8026 (org-back-to-heading)
8027 (setq start (point)
8028 end (progn (org-end-of-subtree t t)
8029 (or (bolp) (insert "\n"))
8030 (org-back-over-empty-lines)
8031 (point))
8032 what "children")
8033 (goto-char start)
8034 (show-subtree)
8035 (outline-next-heading))
8037 ;; we will sort the top-level entries in this file
8038 (goto-char (point-min))
8039 (or (org-on-heading-p) (outline-next-heading))
8040 (setq start (point))
8041 (goto-char (point-max))
8042 (beginning-of-line 1)
8043 (when (looking-at ".*?\\S-")
8044 ;; File ends in a non-white line
8045 (end-of-line 1)
8046 (insert "\n"))
8047 (setq end (point-max))
8048 (setq what "top-level")
8049 (goto-char start)
8050 (show-all)))
8052 (setq beg (point))
8053 (if (>= beg end) (error "Nothing to sort"))
8055 (looking-at "\\(\\*+\\)")
8056 (setq stars (match-string 1)
8057 re (concat "^" (regexp-quote stars) " +")
8058 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8059 txt (buffer-substring beg end))
8060 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8061 (if (and (not (equal stars "*")) (string-match re2 txt))
8062 (error "Region to sort contains a level above the first entry"))
8064 (unless sorting-type
8065 (message
8066 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8067 [t]ime [s]cheduled [d]eadline [c]reated
8068 A/N/T/S/D/C/P/O/F means reversed:"
8069 what)
8070 (setq sorting-type (read-char-exclusive))
8072 (and (= (downcase sorting-type) ?f)
8073 (setq getkey-func
8074 (org-icompleting-read "Sort using function: "
8075 obarray 'fboundp t nil nil))
8076 (setq getkey-func (intern getkey-func)))
8078 (and (= (downcase sorting-type) ?r)
8079 (setq property
8080 (org-icompleting-read "Property: "
8081 (mapcar 'list (org-buffer-property-keys t))
8082 nil t))))
8084 (message "Sorting entries...")
8086 (save-restriction
8087 (narrow-to-region start end)
8088 (let ((dcst (downcase sorting-type))
8089 (case-fold-search nil)
8090 (now (current-time)))
8091 (sort-subr
8092 (/= dcst sorting-type)
8093 ;; This function moves to the beginning character of the "record" to
8094 ;; be sorted.
8095 (lambda nil
8096 (if (re-search-forward re nil t)
8097 (goto-char (match-beginning 0))
8098 (goto-char (point-max))))
8099 ;; This function moves to the last character of the "record" being
8100 ;; sorted.
8101 (lambda nil
8102 (save-match-data
8103 (condition-case nil
8104 (outline-forward-same-level 1)
8105 (error
8106 (goto-char (point-max))))))
8107 ;; This function returns the value that gets sorted against.
8108 (lambda nil
8109 (cond
8110 ((= dcst ?n)
8111 (if (looking-at org-complex-heading-regexp)
8112 (string-to-number (match-string 4))
8113 nil))
8114 ((= dcst ?a)
8115 (if (looking-at org-complex-heading-regexp)
8116 (funcall case-func (match-string 4))
8117 nil))
8118 ((= dcst ?t)
8119 (let ((end (save-excursion (outline-next-heading) (point))))
8120 (if (or (re-search-forward org-ts-regexp end t)
8121 (re-search-forward org-ts-regexp-both end t))
8122 (org-time-string-to-seconds (match-string 0))
8123 (org-float-time now))))
8124 ((= dcst ?c)
8125 (let ((end (save-excursion (outline-next-heading) (point))))
8126 (if (re-search-forward
8127 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8128 end t)
8129 (org-time-string-to-seconds (match-string 0))
8130 (org-float-time now))))
8131 ((= dcst ?s)
8132 (let ((end (save-excursion (outline-next-heading) (point))))
8133 (if (re-search-forward org-scheduled-time-regexp end t)
8134 (org-time-string-to-seconds (match-string 1))
8135 (org-float-time now))))
8136 ((= dcst ?d)
8137 (let ((end (save-excursion (outline-next-heading) (point))))
8138 (if (re-search-forward org-deadline-time-regexp end t)
8139 (org-time-string-to-seconds (match-string 1))
8140 (org-float-time now))))
8141 ((= dcst ?p)
8142 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8143 (string-to-char (match-string 2))
8144 org-default-priority))
8145 ((= dcst ?r)
8146 (or (org-entry-get nil property) ""))
8147 ((= dcst ?o)
8148 (if (looking-at org-complex-heading-regexp)
8149 (- 9999 (length (member (match-string 2)
8150 org-todo-keywords-1)))))
8151 ((= dcst ?f)
8152 (if getkey-func
8153 (progn
8154 (setq tmp (funcall getkey-func))
8155 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8156 tmp)
8157 (error "Invalid key function `%s'" getkey-func)))
8158 (t (error "Invalid sorting type `%c'" sorting-type))))
8160 (cond
8161 ((= dcst ?a) 'string<)
8162 ((= dcst ?f) compare-func)
8163 ((member dcst '(?p ?t ?s ?d ?c)) '<)
8164 (t nil)))))
8165 (run-hooks 'org-after-sorting-entries-or-items-hook)
8166 (message "Sorting entries...done")))
8168 (defun org-do-sort (table what &optional with-case sorting-type)
8169 "Sort TABLE of WHAT according to SORTING-TYPE.
8170 The user will be prompted for the SORTING-TYPE if the call to this
8171 function does not specify it. WHAT is only for the prompt, to indicate
8172 what is being sorted. The sorting key will be extracted from
8173 the car of the elements of the table.
8174 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8175 (unless sorting-type
8176 (message
8177 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8178 what)
8179 (setq sorting-type (read-char-exclusive)))
8180 (let ((dcst (downcase sorting-type))
8181 extractfun comparefun)
8182 ;; Define the appropriate functions
8183 (cond
8184 ((= dcst ?n)
8185 (setq extractfun 'string-to-number
8186 comparefun (if (= dcst sorting-type) '< '>)))
8187 ((= dcst ?a)
8188 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8189 (lambda(x) (downcase (org-sort-remove-invisible x))))
8190 comparefun (if (= dcst sorting-type)
8191 'string<
8192 (lambda (a b) (and (not (string< a b))
8193 (not (string= a b)))))))
8194 ((= dcst ?t)
8195 (setq extractfun
8196 (lambda (x)
8197 (if (or (string-match org-ts-regexp x)
8198 (string-match org-ts-regexp-both x))
8199 (org-float-time
8200 (org-time-string-to-time (match-string 0 x)))
8202 comparefun (if (= dcst sorting-type) '< '>)))
8203 (t (error "Invalid sorting type `%c'" sorting-type)))
8205 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8206 table)
8207 (lambda (a b) (funcall comparefun (car a) (car b))))))
8210 ;;; The orgstruct minor mode
8212 ;; Define a minor mode which can be used in other modes in order to
8213 ;; integrate the org-mode structure editing commands.
8215 ;; This is really a hack, because the org-mode structure commands use
8216 ;; keys which normally belong to the major mode. Here is how it
8217 ;; works: The minor mode defines all the keys necessary to operate the
8218 ;; structure commands, but wraps the commands into a function which
8219 ;; tests if the cursor is currently at a headline or a plain list
8220 ;; item. If that is the case, the structure command is used,
8221 ;; temporarily setting many Org-mode variables like regular
8222 ;; expressions for filling etc. However, when any of those keys is
8223 ;; used at a different location, function uses `key-binding' to look
8224 ;; up if the key has an associated command in another currently active
8225 ;; keymap (minor modes, major mode, global), and executes that
8226 ;; command. There might be problems if any of the keys is otherwise
8227 ;; used as a prefix key.
8229 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8230 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8231 ;; addresses this by checking explicitly for both bindings.
8233 (defvar orgstruct-mode-map (make-sparse-keymap)
8234 "Keymap for the minor `orgstruct-mode'.")
8236 (defvar org-local-vars nil
8237 "List of local variables, for use by `orgstruct-mode'.")
8239 ;;;###autoload
8240 (define-minor-mode orgstruct-mode
8241 "Toggle the minor mode `orgstruct-mode'.
8242 This mode is for using Org-mode structure commands in other
8243 modes. The following keys behave as if Org-mode were active, if
8244 the cursor is on a headline, or on a plain list item (both as
8245 defined by Org-mode).
8247 M-up Move entry/item up
8248 M-down Move entry/item down
8249 M-left Promote
8250 M-right Demote
8251 M-S-up Move entry/item up
8252 M-S-down Move entry/item down
8253 M-S-left Promote subtree
8254 M-S-right Demote subtree
8255 M-q Fill paragraph and items like in Org-mode
8256 C-c ^ Sort entries
8257 C-c - Cycle list bullet
8258 TAB Cycle item visibility
8259 M-RET Insert new heading/item
8260 S-M-RET Insert new TODO heading / Checkbox item
8261 C-c C-c Set tags / toggle checkbox"
8262 nil " OrgStruct" nil
8263 (org-load-modules-maybe)
8264 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8266 ;;;###autoload
8267 (defun turn-on-orgstruct ()
8268 "Unconditionally turn on `orgstruct-mode'."
8269 (orgstruct-mode 1))
8271 (defun orgstruct++-mode (&optional arg)
8272 "Toggle `orgstruct-mode', the enhanced version of it.
8273 In addition to setting orgstruct-mode, this also exports all indentation
8274 and autofilling variables from org-mode into the buffer. It will also
8275 recognize item context in multiline items.
8276 Note that turning off orgstruct-mode will *not* remove the
8277 indentation/paragraph settings. This can only be done by refreshing the
8278 major mode, for example with \\[normal-mode]."
8279 (interactive "P")
8280 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8281 (if (< arg 1)
8282 (orgstruct-mode -1)
8283 (orgstruct-mode 1)
8284 (let (var val)
8285 (mapc
8286 (lambda (x)
8287 (when (string-match
8288 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8289 (symbol-name (car x)))
8290 (setq var (car x) val (nth 1 x))
8291 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8292 org-local-vars)
8293 (org-set-local 'orgstruct-is-++ t))))
8295 (defvar orgstruct-is-++ nil
8296 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8297 (make-variable-buffer-local 'orgstruct-is-++)
8299 ;;;###autoload
8300 (defun turn-on-orgstruct++ ()
8301 "Unconditionally turn on `orgstruct++-mode'."
8302 (orgstruct++-mode 1))
8304 (defun orgstruct-error ()
8305 "Error when there is no default binding for a structure key."
8306 (interactive)
8307 (error "This key has no function outside structure elements"))
8309 (defun orgstruct-setup ()
8310 "Setup orgstruct keymaps."
8311 (let ((nfunc 0)
8312 (bindings
8313 (list
8314 '([(meta up)] org-metaup)
8315 '([(meta down)] org-metadown)
8316 '([(meta left)] org-metaleft)
8317 '([(meta right)] org-metaright)
8318 '([(meta shift up)] org-shiftmetaup)
8319 '([(meta shift down)] org-shiftmetadown)
8320 '([(meta shift left)] org-shiftmetaleft)
8321 '([(meta shift right)] org-shiftmetaright)
8322 '([?\e (up)] org-metaup)
8323 '([?\e (down)] org-metadown)
8324 '([?\e (left)] org-metaleft)
8325 '([?\e (right)] org-metaright)
8326 '([?\e (shift up)] org-shiftmetaup)
8327 '([?\e (shift down)] org-shiftmetadown)
8328 '([?\e (shift left)] org-shiftmetaleft)
8329 '([?\e (shift right)] org-shiftmetaright)
8330 '([(shift up)] org-shiftup)
8331 '([(shift down)] org-shiftdown)
8332 '([(shift left)] org-shiftleft)
8333 '([(shift right)] org-shiftright)
8334 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8335 '("\M-q" fill-paragraph)
8336 '("\C-c^" org-sort)
8337 '("\C-c-" org-cycle-list-bullet)))
8338 elt key fun cmd)
8339 (while (setq elt (pop bindings))
8340 (setq nfunc (1+ nfunc))
8341 (setq key (org-key (car elt))
8342 fun (nth 1 elt)
8343 cmd (orgstruct-make-binding fun nfunc key))
8344 (org-defkey orgstruct-mode-map key cmd))
8346 ;; Special treatment needed for TAB and RET
8347 (org-defkey orgstruct-mode-map [(tab)]
8348 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8349 (org-defkey orgstruct-mode-map "\C-i"
8350 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8352 (org-defkey orgstruct-mode-map "\M-\C-m"
8353 (orgstruct-make-binding 'org-insert-heading 105
8354 "\M-\C-m" [(meta return)]))
8355 (org-defkey orgstruct-mode-map [(meta return)]
8356 (orgstruct-make-binding 'org-insert-heading 106
8357 [(meta return)] "\M-\C-m"))
8359 (org-defkey orgstruct-mode-map [(shift meta return)]
8360 (orgstruct-make-binding 'org-insert-todo-heading 107
8361 [(meta return)] "\M-\C-m"))
8363 (org-defkey orgstruct-mode-map "\e\C-m"
8364 (orgstruct-make-binding 'org-insert-heading 108
8365 "\e\C-m" [?\e (return)]))
8366 (org-defkey orgstruct-mode-map [?\e (return)]
8367 (orgstruct-make-binding 'org-insert-heading 109
8368 [?\e (return)] "\e\C-m"))
8369 (org-defkey orgstruct-mode-map [?\e (shift return)]
8370 (orgstruct-make-binding 'org-insert-todo-heading 110
8371 [?\e (return)] "\e\C-m"))
8373 (unless org-local-vars
8374 (setq org-local-vars (org-get-local-variables)))
8378 (defun orgstruct-make-binding (fun n &rest keys)
8379 "Create a function for binding in the structure minor mode.
8380 FUN is the command to call inside a table. N is used to create a unique
8381 command name. KEYS are keys that should be checked in for a command
8382 to execute outside of tables."
8383 (eval
8384 (list 'defun
8385 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8386 '(arg)
8387 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8388 "Outside of structure, run the binding of `"
8389 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8390 "'.")
8391 '(interactive "p")
8392 (list 'if
8393 `(org-context-p 'headline 'item
8394 (and orgstruct-is-++
8395 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8396 'item-body))
8397 (list 'org-run-like-in-org-mode (list 'quote fun))
8398 (list 'let '(orgstruct-mode)
8399 (list 'call-interactively
8400 (append '(or)
8401 (mapcar (lambda (k)
8402 (list 'key-binding k))
8403 keys)
8404 '('orgstruct-error))))))))
8406 (defun org-context-p (&rest contexts)
8407 "Check if local context is any of CONTEXTS.
8408 Possible values in the list of contexts are `table', `headline', and `item'."
8409 (let ((pos (point)))
8410 (goto-char (point-at-bol))
8411 (prog1 (or (and (memq 'table contexts)
8412 (looking-at "[ \t]*|"))
8413 (and (memq 'headline contexts)
8414 (looking-at org-outline-regexp))
8415 (and (memq 'item contexts)
8416 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8417 (and (memq 'item-body contexts)
8418 (org-in-item-p)))
8419 (goto-char pos))))
8421 (defun org-get-local-variables ()
8422 "Return a list of all local variables in an org-mode buffer."
8423 (let (varlist)
8424 (with-current-buffer (get-buffer-create "*Org tmp*")
8425 (erase-buffer)
8426 (org-mode)
8427 (setq varlist (buffer-local-variables)))
8428 (kill-buffer "*Org tmp*")
8429 (delq nil
8430 (mapcar
8431 (lambda (x)
8432 (setq x
8433 (if (symbolp x)
8434 (list x)
8435 (list (car x) (list 'quote (cdr x)))))
8436 (if (string-match
8437 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8438 (symbol-name (car x)))
8439 x nil))
8440 varlist))))
8442 (defun org-clone-local-variables (from-buffer &optional regexp)
8443 "Clone local variables from FROM-BUFFER.
8444 Optional argument REGEXP selects variables to clone."
8445 (mapc
8446 (lambda (pair)
8447 (and (symbolp (car pair))
8448 (or (null regexp)
8449 (string-match regexp (symbol-name (car pair))))
8450 (set (make-local-variable (car pair))
8451 (cdr pair))))
8452 (buffer-local-variables from-buffer)))
8454 ;;;###autoload
8455 (defun org-run-like-in-org-mode (cmd)
8456 "Run a command, pretending that the current buffer is in Org-mode.
8457 This will temporarily bind local variables that are typically bound in
8458 Org-mode to the values they have in Org-mode, and then interactively
8459 call CMD."
8460 (org-load-modules-maybe)
8461 (unless org-local-vars
8462 (setq org-local-vars (org-get-local-variables)))
8463 (eval (list 'let org-local-vars
8464 (list 'call-interactively (list 'quote cmd)))))
8466 ;;;; Archiving
8468 (defun org-get-category (&optional pos force-refresh)
8469 "Get the category applying to position POS."
8470 (if force-refresh (org-refresh-category-properties))
8471 (let ((pos (or pos (point))))
8472 (or (get-text-property pos 'org-category)
8473 (progn (org-refresh-category-properties)
8474 (get-text-property pos 'org-category)))))
8476 (defun org-refresh-category-properties ()
8477 "Refresh category text properties in the buffer."
8478 (let ((def-cat (cond
8479 ((null org-category)
8480 (if buffer-file-name
8481 (file-name-sans-extension
8482 (file-name-nondirectory buffer-file-name))
8483 "???"))
8484 ((symbolp org-category) (symbol-name org-category))
8485 (t org-category)))
8486 beg end cat pos optionp)
8487 (org-unmodified
8488 (save-excursion
8489 (save-restriction
8490 (widen)
8491 (goto-char (point-min))
8492 (put-text-property (point) (point-max) 'org-category def-cat)
8493 (while (re-search-forward
8494 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8495 (setq pos (match-end 0)
8496 optionp (equal (char-after (match-beginning 0)) ?#)
8497 cat (org-trim (match-string 2)))
8498 (if optionp
8499 (setq beg (point-at-bol) end (point-max))
8500 (org-back-to-heading t)
8501 (setq beg (point) end (org-end-of-subtree t t)))
8502 (put-text-property beg end 'org-category cat)
8503 (put-text-property beg end 'org-category-position beg)
8504 (goto-char pos)))))))
8507 ;;;; Link Stuff
8509 ;;; Link abbreviations
8511 (defun org-link-expand-abbrev (link)
8512 "Apply replacements as defined in `org-link-abbrev-alist."
8513 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8514 (let* ((key (match-string 1 link))
8515 (as (or (assoc key org-link-abbrev-alist-local)
8516 (assoc key org-link-abbrev-alist)))
8517 (tag (and (match-end 2) (match-string 3 link)))
8518 rpl)
8519 (if (not as)
8520 link
8521 (setq rpl (cdr as))
8522 (cond
8523 ((symbolp rpl) (funcall rpl tag))
8524 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8525 ((string-match "%h" rpl)
8526 (replace-match (url-hexify-string (or tag "")) t t rpl))
8527 (t (concat rpl tag)))))
8528 link))
8530 ;;; Storing and inserting links
8532 (defvar org-insert-link-history nil
8533 "Minibuffer history for links inserted with `org-insert-link'.")
8535 (defvar org-stored-links nil
8536 "Contains the links stored with `org-store-link'.")
8538 (defvar org-store-link-plist nil
8539 "Plist with info about the most recently link created with `org-store-link'.")
8541 (defvar org-link-protocols nil
8542 "Link protocols added to Org-mode using `org-add-link-type'.")
8544 (defvar org-store-link-functions nil
8545 "List of functions that are called to create and store a link.
8546 Each function will be called in turn until one returns a non-nil
8547 value. Each function should check if it is responsible for creating
8548 this link (for example by looking at the major mode).
8549 If not, it must exit and return nil.
8550 If yes, it should return a non-nil value after a calling
8551 `org-store-link-props' with a list of properties and values.
8552 Special properties are:
8554 :type The link prefix, like \"http\". This must be given.
8555 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8556 This is obligatory as well.
8557 :description Optional default description for the second pair
8558 of brackets in an Org-mode link. The user can still change
8559 this when inserting this link into an Org-mode buffer.
8561 In addition to these, any additional properties can be specified
8562 and then used in remember templates.")
8564 (defun org-add-link-type (type &optional follow export)
8565 "Add TYPE to the list of `org-link-types'.
8566 Re-compute all regular expressions depending on `org-link-types'
8568 FOLLOW and EXPORT are two functions.
8570 FOLLOW should take the link path as the single argument and do whatever
8571 is necessary to follow the link, for example find a file or display
8572 a mail message.
8574 EXPORT should format the link path for export to one of the export formats.
8575 It should be a function accepting three arguments:
8577 path the path of the link, the text after the prefix (like \"http:\")
8578 desc the description of the link, if any, or a description added by
8579 org-export-normalize-links if there is none
8580 format the export format, a symbol like `html' or `latex' or `ascii'..
8582 The function may use the FORMAT information to return different values
8583 depending on the format. The return value will be put literally into
8584 the exported file. If the return value is nil, this means Org should
8585 do what it normally does with links which do not have EXPORT defined.
8587 Org-mode has a built-in default for exporting links. If you are happy with
8588 this default, there is no need to define an export function for the link
8589 type. For a simple example of an export function, see `org-bbdb.el'."
8590 (add-to-list 'org-link-types type t)
8591 (org-make-link-regexps)
8592 (if (assoc type org-link-protocols)
8593 (setcdr (assoc type org-link-protocols) (list follow export))
8594 (push (list type follow export) org-link-protocols)))
8596 (defvar org-agenda-buffer-name)
8598 ;;;###autoload
8599 (defun org-store-link (arg)
8600 "\\<org-mode-map>Store an org-link to the current location.
8601 This link is added to `org-stored-links' and can later be inserted
8602 into an org-buffer with \\[org-insert-link].
8604 For some link types, a prefix arg is interpreted:
8605 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8606 For file links, arg negates `org-context-in-file-links'."
8607 (interactive "P")
8608 (org-load-modules-maybe)
8609 (setq org-store-link-plist nil) ; reset
8610 (org-with-limited-levels
8611 (let (link cpltxt desc description search txt custom-id agenda-link)
8612 (cond
8614 ((run-hook-with-args-until-success 'org-store-link-functions)
8615 (setq link (plist-get org-store-link-plist :link)
8616 desc (or (plist-get org-store-link-plist :description) link)))
8618 ((equal (buffer-name) "*Org Edit Src Example*")
8619 (let (label gc)
8620 (while (or (not label)
8621 (save-excursion
8622 (save-restriction
8623 (widen)
8624 (goto-char (point-min))
8625 (re-search-forward
8626 (regexp-quote (format org-coderef-label-format label))
8627 nil t))))
8628 (when label (message "Label exists already") (sit-for 2))
8629 (setq label (read-string "Code line label: " label)))
8630 (end-of-line 1)
8631 (setq link (format org-coderef-label-format label))
8632 (setq gc (- 79 (length link)))
8633 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8634 (insert link)
8635 (setq link (concat "(" label ")") desc nil)))
8637 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8638 ;; We are in the agenda, link to referenced location
8639 (let ((m (or (get-text-property (point) 'org-hd-marker)
8640 (get-text-property (point) 'org-marker))))
8641 (when m
8642 (org-with-point-at m
8643 (setq agenda-link
8644 (if (org-called-interactively-p 'any)
8645 (call-interactively 'org-store-link)
8646 (org-store-link nil)))))))
8648 ((eq major-mode 'calendar-mode)
8649 (let ((cd (calendar-cursor-to-date)))
8650 (setq link
8651 (format-time-string
8652 (car org-time-stamp-formats)
8653 (apply 'encode-time
8654 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8655 nil nil nil))))
8656 (org-store-link-props :type "calendar" :date cd)))
8658 ((eq major-mode 'w3-mode)
8659 (setq cpltxt (if (and (buffer-name)
8660 (not (string-match "Untitled" (buffer-name))))
8661 (buffer-name)
8662 (url-view-url t))
8663 link (org-make-link (url-view-url t)))
8664 (org-store-link-props :type "w3" :url (url-view-url t)))
8666 ((eq major-mode 'w3m-mode)
8667 (setq cpltxt (or w3m-current-title w3m-current-url)
8668 link (org-make-link w3m-current-url))
8669 (org-store-link-props :type "w3m" :url (url-view-url t)))
8671 ((setq search (run-hook-with-args-until-success
8672 'org-create-file-search-functions))
8673 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8674 "::" search))
8675 (setq cpltxt (or description link)))
8677 ((eq major-mode 'image-mode)
8678 (setq cpltxt (concat "file:"
8679 (abbreviate-file-name buffer-file-name))
8680 link (org-make-link cpltxt))
8681 (org-store-link-props :type "image" :file buffer-file-name))
8683 ((eq major-mode 'dired-mode)
8684 ;; link to the file in the current line
8685 (let ((file (dired-get-filename nil t)))
8686 (setq file (if file
8687 (abbreviate-file-name
8688 (expand-file-name (dired-get-filename nil t)))
8689 ;; otherwise, no file so use current directory.
8690 default-directory))
8691 (setq cpltxt (concat "file:" file)
8692 link (org-make-link cpltxt))))
8694 ((and (buffer-file-name (buffer-base-buffer)) (eq major-mode 'org-mode))
8695 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8696 (cond
8697 ((org-in-regexp "<<\\(.*?\\)>>")
8698 (setq cpltxt
8699 (concat "file:"
8700 (abbreviate-file-name
8701 (buffer-file-name (buffer-base-buffer)))
8702 "::" (match-string 1))
8703 link (org-make-link cpltxt)))
8704 ((and (featurep 'org-id)
8705 (or (eq org-link-to-org-use-id t)
8706 (and (eq org-link-to-org-use-id 'create-if-interactive)
8707 (org-called-interactively-p 'any))
8708 (and (eq org-link-to-org-use-id
8709 'create-if-interactive-and-no-custom-id)
8710 (org-called-interactively-p 'any)
8711 (not custom-id))
8712 (and org-link-to-org-use-id
8713 (org-entry-get nil "ID"))))
8714 ;; We can make a link using the ID.
8715 (setq link (condition-case nil
8716 (prog1 (org-id-store-link)
8717 (setq desc (plist-get org-store-link-plist
8718 :description)))
8719 (error
8720 ;; probably before first headline, link to file only
8721 (concat "file:"
8722 (abbreviate-file-name
8723 (buffer-file-name (buffer-base-buffer))))))))
8725 ;; Just link to current headline
8726 (setq cpltxt (concat "file:"
8727 (abbreviate-file-name
8728 (buffer-file-name (buffer-base-buffer)))))
8729 ;; Add a context search string
8730 (when (org-xor org-context-in-file-links arg)
8731 (setq txt (cond
8732 ((org-on-heading-p) nil)
8733 ((org-region-active-p)
8734 (buffer-substring (region-beginning) (region-end)))
8735 (t nil)))
8736 (when (or (null txt) (string-match "\\S-" txt))
8737 (setq cpltxt
8738 (concat cpltxt "::"
8739 (condition-case nil
8740 (org-make-org-heading-search-string txt)
8741 (error "")))
8742 desc (or (nth 4 (ignore-errors
8743 (org-heading-components))) "NONE"))))
8744 (if (string-match "::\\'" cpltxt)
8745 (setq cpltxt (substring cpltxt 0 -2)))
8746 (setq link (org-make-link cpltxt)))))
8748 ((buffer-file-name (buffer-base-buffer))
8749 ;; Just link to this file here.
8750 (setq cpltxt (concat "file:"
8751 (abbreviate-file-name
8752 (buffer-file-name (buffer-base-buffer)))))
8753 ;; Add a context string
8754 (when (org-xor org-context-in-file-links arg)
8755 (setq txt (if (org-region-active-p)
8756 (buffer-substring (region-beginning) (region-end))
8757 (buffer-substring (point-at-bol) (point-at-eol))))
8758 ;; Only use search option if there is some text.
8759 (when (string-match "\\S-" txt)
8760 (setq cpltxt
8761 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8762 desc "NONE")))
8763 (setq link (org-make-link cpltxt)))
8765 ((org-called-interactively-p 'interactive)
8766 (error "Cannot link to a buffer which is not visiting a file"))
8768 (t (setq link nil)))
8770 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8771 (setq link (or link cpltxt)
8772 desc (or desc cpltxt))
8773 (if (equal desc "NONE") (setq desc nil))
8775 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8776 (progn
8777 (setq org-stored-links
8778 (cons (list link desc) org-stored-links))
8779 (message "Stored: %s" (or desc link))
8780 (when custom-id
8781 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8782 "::#" custom-id))
8783 (setq org-stored-links
8784 (cons (list link desc) org-stored-links))))
8785 (or agenda-link (and link (org-make-link-string link desc)))))))
8787 (defun org-store-link-props (&rest plist)
8788 "Store link properties, extract names and addresses."
8789 (let (x adr)
8790 (when (setq x (plist-get plist :from))
8791 (setq adr (mail-extract-address-components x))
8792 (setq plist (plist-put plist :fromname (car adr)))
8793 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8794 (when (setq x (plist-get plist :to))
8795 (setq adr (mail-extract-address-components x))
8796 (setq plist (plist-put plist :toname (car adr)))
8797 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8798 (let ((from (plist-get plist :from))
8799 (to (plist-get plist :to)))
8800 (when (and from to org-from-is-user-regexp)
8801 (setq plist
8802 (plist-put plist :fromto
8803 (if (string-match org-from-is-user-regexp from)
8804 (concat "to %t")
8805 (concat "from %f"))))))
8806 (setq org-store-link-plist plist))
8808 (defun org-add-link-props (&rest plist)
8809 "Add these properties to the link property list."
8810 (let (key value)
8811 (while plist
8812 (setq key (pop plist) value (pop plist))
8813 (setq org-store-link-plist
8814 (plist-put org-store-link-plist key value)))))
8816 (defun org-email-link-description (&optional fmt)
8817 "Return the description part of an email link.
8818 This takes information from `org-store-link-plist' and formats it
8819 according to FMT (default from `org-email-link-description-format')."
8820 (setq fmt (or fmt org-email-link-description-format))
8821 (let* ((p org-store-link-plist)
8822 (to (plist-get p :toaddress))
8823 (from (plist-get p :fromaddress))
8824 (table
8825 (list
8826 (cons "%c" (plist-get p :fromto))
8827 (cons "%F" (plist-get p :from))
8828 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8829 (cons "%T" (plist-get p :to))
8830 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8831 (cons "%s" (plist-get p :subject))
8832 (cons "%d" (plist-get p :date))
8833 (cons "%m" (plist-get p :message-id)))))
8834 (when (string-match "%c" fmt)
8835 ;; Check if the user wrote this message
8836 (if (and org-from-is-user-regexp from to
8837 (save-match-data (string-match org-from-is-user-regexp from)))
8838 (setq fmt (replace-match "to %t" t t fmt))
8839 (setq fmt (replace-match "from %f" t t fmt))))
8840 (org-replace-escapes fmt table)))
8842 (defun org-make-org-heading-search-string (&optional string heading)
8843 "Make search string for STRING or current headline."
8844 (interactive)
8845 (let ((s (or string (org-get-heading)))
8846 (lines org-context-in-file-links))
8847 (unless (and string (not heading))
8848 ;; We are using a headline, clean up garbage in there.
8849 (if (string-match org-todo-regexp s)
8850 (setq s (replace-match "" t t s)))
8851 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8852 (setq s (replace-match "" t t s)))
8853 (setq s (org-trim s))
8854 (if (string-match (concat "^\\(" org-quote-string "\\|"
8855 org-comment-string "\\)") s)
8856 (setq s (replace-match "" t t s)))
8857 (while (string-match org-ts-regexp s)
8858 (setq s (replace-match "" t t s))))
8859 (or string (setq s (concat "*" s))) ; Add * for headlines
8860 (when (and string (integerp lines) (> lines 0))
8861 (let ((slines (org-split-string s "\n")))
8862 (when (< lines (length slines))
8863 (setq s (mapconcat
8864 'identity
8865 (reverse (nthcdr (- (length slines) lines)
8866 (reverse slines))) "\n")))))
8867 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8869 (defun org-make-link (&rest strings)
8870 "Concatenate STRINGS."
8871 (apply 'concat strings))
8873 (defun org-make-link-string (link &optional description)
8874 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8875 (unless (string-match "\\S-" link)
8876 (error "Empty link"))
8877 (when (and description
8878 (stringp description)
8879 (not (string-match "\\S-" description)))
8880 (setq description nil))
8881 (when (stringp description)
8882 ;; Remove brackets from the description, they are fatal.
8883 (while (string-match "\\[" description)
8884 (setq description (replace-match "{" t t description)))
8885 (while (string-match "\\]" description)
8886 (setq description (replace-match "}" t t description))))
8887 (when (equal link description)
8888 ;; No description needed, it is identical
8889 (setq description nil))
8890 (when (and (not description)
8891 (not (string-match (org-image-file-name-regexp) link))
8892 (not (equal link (org-link-escape link))))
8893 (setq description (org-extract-attributes link)))
8894 (setq link
8895 (cond ((string-match (org-image-file-name-regexp) link) link)
8896 ((string-match org-link-types-re link)
8897 (concat (match-string 1 link)
8898 (org-link-escape (substring link (match-end 1)))))
8899 (t (org-link-escape link))))
8900 (concat "[[" link "]"
8901 (if description (concat "[" description "]") "")
8902 "]"))
8904 (defconst org-link-escape-chars
8905 '(?\ ?\[ ?\] ?\; ?\= ?\+)
8906 "List of characters that should be escaped in link.
8907 This is the list that is used for internal purposes.")
8909 (defvar org-url-encoding-use-url-hexify nil)
8911 (defconst org-link-escape-chars-browser
8912 '(?\ )
8913 "List of escapes for characters that are problematic in links.
8914 This is the list that is used before handing over to the browser.")
8916 (defun org-link-escape (text &optional table merge)
8917 "Return percent escaped representation of TEXT.
8918 TEXT is a string with the text to escape.
8919 Optional argument TABLE is a list with characters that should be
8920 escaped. When nil, `org-link-escape-chars' is used.
8921 If optional argument MERGE is set, merge TABLE into
8922 `org-link-escape-chars'."
8923 (if (and org-url-encoding-use-url-hexify (not table))
8924 (url-hexify-string text)
8925 (cond
8926 ((and table merge)
8927 (mapc (lambda (defchr)
8928 (unless (member defchr table)
8929 (setq table (cons defchr table)))) org-link-escape-chars))
8930 ((null table)
8931 (setq table org-link-escape-chars)))
8932 (mapconcat
8933 (lambda (char)
8934 (if (or (member char table)
8935 (< char 32) (= char 37) (> char 126))
8936 (mapconcat (lambda (sequence-element)
8937 (format "%%%.2X" sequence-element))
8938 (or (encode-coding-char char 'utf-8)
8939 (error "Unable to percent escape character: %s"
8940 (char-to-string char))) "")
8941 (char-to-string char))) text "")))
8943 (defun org-link-unescape (str)
8944 "Unhex hexified unicode strings as returned from the JavaScript function
8945 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
8946 (unless (and (null str) (string= "" str))
8947 (let ((pos 0) (case-fold-search t) unhexed)
8948 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
8949 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
8950 (setq str (replace-match unhexed t t str))
8951 (setq pos (+ pos (length unhexed))))))
8952 str)
8954 (defun org-link-unescape-compound (hex)
8955 "Unhexify unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
8956 Note: this function also decodes single byte encodings like
8957 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
8958 (save-match-data
8959 (let* ((bytes (cdr (split-string hex "%")))
8960 (ret "")
8961 (eat 0)
8962 (sum 0))
8963 (while bytes
8964 (let* ((val (string-to-number (pop bytes) 16))
8965 (shift-xor
8966 (if (= 0 eat)
8967 (cond
8968 ((>= val 252) (cons 6 252))
8969 ((>= val 248) (cons 5 248))
8970 ((>= val 240) (cons 4 240))
8971 ((>= val 224) (cons 3 224))
8972 ((>= val 192) (cons 2 192))
8973 (t (cons 0 0)))
8974 (cons 6 128))))
8975 (if (>= val 192) (setq eat (car shift-xor)))
8976 (setq val (logxor val (cdr shift-xor)))
8977 (setq sum (+ (lsh sum (car shift-xor)) val))
8978 (if (> eat 0) (setq eat (- eat 1)))
8979 (cond
8980 ((= 0 eat) ;multi byte
8981 (setq ret (concat ret (org-char-to-string sum)))
8982 (setq sum 0))
8983 ((not bytes) ; single byte(s)
8984 (setq ret (org-link-unescape-single-byte-sequence hex))))
8985 )) ;; end (while bytes
8986 ret )))
8988 (defun org-link-unescape-single-byte-sequence (hex)
8989 "Unhexify hex-encoded single byte character sequences."
8990 (mapconcat (lambda (byte)
8991 (char-to-string (string-to-number byte 16)))
8992 (cdr (split-string hex "%")) ""))
8994 (defun org-xor (a b)
8995 "Exclusive or."
8996 (if a (not b) b))
8998 (defun org-fixup-message-id-for-http (s)
8999 "Replace special characters in a message id, so it can be used in an http query."
9000 (when (string-match "%" s)
9001 (setq s (mapconcat (lambda (c)
9002 (if (eq c ?%)
9003 "%25"
9004 (char-to-string c)))
9005 s "")))
9006 (while (string-match "<" s)
9007 (setq s (replace-match "%3C" t t s)))
9008 (while (string-match ">" s)
9009 (setq s (replace-match "%3E" t t s)))
9010 (while (string-match "@" s)
9011 (setq s (replace-match "%40" t t s)))
9014 ;;;###autoload
9015 (defun org-insert-link-global ()
9016 "Insert a link like Org-mode does.
9017 This command can be called in any mode to insert a link in Org-mode syntax."
9018 (interactive)
9019 (org-load-modules-maybe)
9020 (org-run-like-in-org-mode 'org-insert-link))
9022 (defun org-insert-link (&optional complete-file link-location default-description)
9023 "Insert a link. At the prompt, enter the link.
9025 Completion can be used to insert any of the link protocol prefixes like
9026 http or ftp in use.
9028 The history can be used to select a link previously stored with
9029 `org-store-link'. When the empty string is entered (i.e. if you just
9030 press RET at the prompt), the link defaults to the most recently
9031 stored link. As SPC triggers completion in the minibuffer, you need to
9032 use M-SPC or C-q SPC to force the insertion of a space character.
9034 You will also be prompted for a description, and if one is given, it will
9035 be displayed in the buffer instead of the link.
9037 If there is already a link at point, this command will allow you to edit link
9038 and description parts.
9040 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9041 be selected using completion. The path to the file will be relative to the
9042 current directory if the file is in the current directory or a subdirectory.
9043 Otherwise, the link will be the absolute path as completed in the minibuffer
9044 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9045 option `org-link-file-path-type'.
9047 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9048 the current directory or below.
9050 With three \\[universal-argument] prefixes, negate the meaning of
9051 `org-keep-stored-link-after-insertion'.
9053 If `org-make-link-description-function' is non-nil, this function will be
9054 called with the link target, and the result will be the default
9055 link description.
9057 If the LINK-LOCATION parameter is non-nil, this value will be
9058 used as the link location instead of reading one interactively.
9060 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9061 be used as the default description."
9062 (interactive "P")
9063 (let* ((wcf (current-window-configuration))
9064 (region (if (org-region-active-p)
9065 (buffer-substring (region-beginning) (region-end))))
9066 (remove (and region (list (region-beginning) (region-end))))
9067 (desc region)
9068 tmphist ; byte-compile incorrectly complains about this
9069 (link link-location)
9070 entry file all-prefixes)
9071 (cond
9072 (link-location) ; specified by arg, just use it.
9073 ((org-in-regexp org-bracket-link-regexp 1)
9074 ;; We do have a link at point, and we are going to edit it.
9075 (setq remove (list (match-beginning 0) (match-end 0)))
9076 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9077 (setq link (read-string "Link: "
9078 (org-link-unescape
9079 (org-match-string-no-properties 1)))))
9080 ((or (org-in-regexp org-angle-link-re)
9081 (org-in-regexp org-plain-link-re))
9082 ;; Convert to bracket link
9083 (setq remove (list (match-beginning 0) (match-end 0))
9084 link (read-string "Link: "
9085 (org-remove-angle-brackets (match-string 0)))))
9086 ((member complete-file '((4) (16)))
9087 ;; Completing read for file names.
9088 (setq link (org-file-complete-link complete-file)))
9090 ;; Read link, with completion for stored links.
9091 (with-output-to-temp-buffer "*Org Links*"
9092 (princ "Insert a link.
9093 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9094 (when org-stored-links
9095 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9096 (princ (mapconcat
9097 (lambda (x)
9098 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
9099 (reverse org-stored-links) "\n"))))
9100 (let ((cw (selected-window)))
9101 (select-window (get-buffer-window "*Org Links*" 'visible))
9102 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9103 (unless (pos-visible-in-window-p (point-max))
9104 (org-fit-window-to-buffer))
9105 (and (window-live-p cw) (select-window cw)))
9106 ;; Fake a link history, containing the stored links.
9107 (setq tmphist (append (mapcar 'car org-stored-links)
9108 org-insert-link-history))
9109 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
9110 (mapcar 'car org-link-abbrev-alist)
9111 org-link-types))
9112 (unwind-protect
9113 (progn
9114 (setq link
9115 (let ((org-completion-use-ido nil)
9116 (org-completion-use-iswitchb nil))
9117 (org-completing-read
9118 "Link: "
9119 (append
9120 (mapcar (lambda (x) (list (concat x ":")))
9121 all-prefixes)
9122 (mapcar 'car org-stored-links))
9123 nil nil nil
9124 'tmphist
9125 (car (car org-stored-links)))))
9126 (if (not (string-match "\\S-" link))
9127 (error "No link selected"))
9128 (if (or (member link all-prefixes)
9129 (and (equal ":" (substring link -1))
9130 (member (substring link 0 -1) all-prefixes)
9131 (setq link (substring link 0 -1))))
9132 (setq link (org-link-try-special-completion link))))
9133 (set-window-configuration wcf)
9134 (kill-buffer "*Org Links*"))
9135 (setq entry (assoc link org-stored-links))
9136 (or entry (push link org-insert-link-history))
9137 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9138 (not org-keep-stored-link-after-insertion))
9139 (setq org-stored-links (delq (assoc link org-stored-links)
9140 org-stored-links)))
9141 (setq desc (or desc (nth 1 entry)))))
9143 (if (string-match org-plain-link-re link)
9144 ;; URL-like link, normalize the use of angular brackets.
9145 (setq link (org-make-link (org-remove-angle-brackets link))))
9147 ;; Check if we are linking to the current file with a search option
9148 ;; If yes, simplify the link by using only the search option.
9149 (when (and buffer-file-name
9150 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9151 (let* ((path (match-string 1 link))
9152 (case-fold-search nil)
9153 (search (match-string 2 link)))
9154 (save-match-data
9155 (if (equal (file-truename buffer-file-name) (file-truename path))
9156 ;; We are linking to this same file, with a search option
9157 (setq link search)))))
9159 ;; Check if we can/should use a relative path. If yes, simplify the link
9160 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9161 (let* ((type (match-string 1 link))
9162 (path (match-string 2 link))
9163 (origpath path)
9164 (case-fold-search nil))
9165 (cond
9166 ((or (eq org-link-file-path-type 'absolute)
9167 (equal complete-file '(16)))
9168 (setq path (abbreviate-file-name (expand-file-name path))))
9169 ((eq org-link-file-path-type 'noabbrev)
9170 (setq path (expand-file-name path)))
9171 ((eq org-link-file-path-type 'relative)
9172 (setq path (file-relative-name path)))
9174 (save-match-data
9175 (if (string-match (concat "^" (regexp-quote
9176 (expand-file-name
9177 (file-name-as-directory
9178 default-directory))))
9179 (expand-file-name path))
9180 ;; We are linking a file with relative path name.
9181 (setq path (substring (expand-file-name path)
9182 (match-end 0)))
9183 (setq path (abbreviate-file-name (expand-file-name path)))))))
9184 (setq link (concat type path))
9185 (if (equal desc origpath)
9186 (setq desc path))))
9188 (if org-make-link-description-function
9189 (setq desc (funcall org-make-link-description-function link desc))
9190 (if default-description (setq desc default-description)))
9192 (setq desc (read-string "Description: " desc))
9193 (unless (string-match "\\S-" desc) (setq desc nil))
9194 (if remove (apply 'delete-region remove))
9195 (insert (org-make-link-string link desc))))
9197 (defun org-link-try-special-completion (type)
9198 "If there is completion support for link type TYPE, offer it."
9199 (let ((fun (intern (concat "org-" type "-complete-link"))))
9200 (if (functionp fun)
9201 (funcall fun)
9202 (read-string "Link (no completion support): " (concat type ":")))))
9204 (defun org-file-complete-link (&optional arg)
9205 "Create a file link using completion."
9206 (let (file link)
9207 (setq file (read-file-name "File: "))
9208 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9209 (pwd1 (file-name-as-directory (abbreviate-file-name
9210 (expand-file-name ".")))))
9211 (cond
9212 ((equal arg '(16))
9213 (setq link (org-make-link
9214 "file:"
9215 (abbreviate-file-name (expand-file-name file)))))
9216 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9217 (setq link (org-make-link "file:" (match-string 1 file))))
9218 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9219 (expand-file-name file))
9220 (setq link (org-make-link
9221 "file:" (match-string 1 (expand-file-name file)))))
9222 (t (setq link (org-make-link "file:" file)))))
9223 link))
9225 (defun org-completing-read (&rest args)
9226 "Completing-read with SPACE being a normal character."
9227 (let ((enable-recursive-minibuffers t)
9228 (minibuffer-local-completion-map
9229 (copy-keymap minibuffer-local-completion-map)))
9230 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9231 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9232 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9233 (apply 'org-icompleting-read args)))
9235 (defun org-completing-read-no-i (&rest args)
9236 (let (org-completion-use-ido org-completion-use-iswitchb)
9237 (apply 'org-completing-read args)))
9239 (defun org-iswitchb-completing-read (prompt choices &rest args)
9240 "Use iswitch as a completing-read replacement to choose from choices.
9241 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9242 from."
9243 (let* ((iswitchb-use-virtual-buffers nil)
9244 (iswitchb-make-buflist-hook
9245 (lambda ()
9246 (setq iswitchb-temp-buflist choices))))
9247 (iswitchb-read-buffer prompt)))
9249 (defun org-icompleting-read (&rest args)
9250 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9251 (org-without-partial-completion
9252 (if (and org-completion-use-ido
9253 (fboundp 'ido-completing-read)
9254 (boundp 'ido-mode) ido-mode
9255 (listp (second args)))
9256 (let ((ido-enter-matching-directory nil))
9257 (apply 'ido-completing-read (concat (car args))
9258 (if (consp (car (nth 1 args)))
9259 (mapcar 'car (nth 1 args))
9260 (nth 1 args))
9261 (cddr args)))
9262 (if (and org-completion-use-iswitchb
9263 (boundp 'iswitchb-mode) iswitchb-mode
9264 (listp (second args)))
9265 (apply 'org-iswitchb-completing-read (concat (car args))
9266 (if (consp (car (nth 1 args)))
9267 (mapcar 'car (nth 1 args))
9268 (nth 1 args))
9269 (cddr args))
9270 (apply 'completing-read args)))))
9272 (defun org-extract-attributes (s)
9273 "Extract the attributes cookie from a string and set as text property."
9274 (let (a attr (start 0) key value)
9275 (save-match-data
9276 (when (string-match "{{\\([^}]+\\)}}$" s)
9277 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9278 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9279 (setq key (match-string 1 a) value (match-string 2 a)
9280 start (match-end 0)
9281 attr (plist-put attr (intern key) value))))
9282 (org-add-props s nil 'org-attr attr))
9285 (defun org-extract-attributes-from-string (tag)
9286 (let (key value attr)
9287 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9288 (setq key (match-string 1 tag) value (match-string 2 tag)
9289 tag (replace-match "" t t tag)
9290 attr (plist-put attr (intern key) value)))
9291 (cons tag attr)))
9293 (defun org-attributes-to-string (plist)
9294 "Format a property list into an HTML attribute list."
9295 (let ((s "") key value)
9296 (while plist
9297 (setq key (pop plist) value (pop plist))
9298 (and value
9299 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9302 ;;; Opening/following a link
9304 (defvar org-link-search-failed nil)
9306 (defvar org-open-link-functions nil
9307 "Hook for functions finding a plain text link.
9308 These functions must take a single argument, the link content.
9309 They will be called for links that look like [[link text][description]]
9310 when LINK TEXT does not have a protocol like \"http:\" and does not look
9311 like a filename (e.g. \"./blue.png\").
9313 These functions will be called *before* Org attempts to resolve the
9314 link by doing text searches in the current buffer - so if you want a
9315 link \"[[target]]\" to still find \"<<target>>\", your function should
9316 handle this as a special case.
9318 When the function does handle the link, it must return a non-nil value.
9319 If it decides that it is not responsible for this link, it must return
9320 nil to indicate that that Org-mode can continue with other options
9321 like exact and fuzzy text search.")
9323 (defun org-next-link ()
9324 "Move forward to the next link.
9325 If the link is in hidden text, expose it."
9326 (interactive)
9327 (when (and org-link-search-failed (eq this-command last-command))
9328 (goto-char (point-min))
9329 (message "Link search wrapped back to beginning of buffer"))
9330 (setq org-link-search-failed nil)
9331 (let* ((pos (point))
9332 (ct (org-context))
9333 (a (assoc :link ct)))
9334 (if a (goto-char (nth 2 a)))
9335 (if (re-search-forward org-any-link-re nil t)
9336 (progn
9337 (goto-char (match-beginning 0))
9338 (if (outline-invisible-p) (org-show-context)))
9339 (goto-char pos)
9340 (setq org-link-search-failed t)
9341 (error "No further link found"))))
9343 (defun org-previous-link ()
9344 "Move backward to the previous link.
9345 If the link is in hidden text, expose it."
9346 (interactive)
9347 (when (and org-link-search-failed (eq this-command last-command))
9348 (goto-char (point-max))
9349 (message "Link search wrapped back to end of buffer"))
9350 (setq org-link-search-failed nil)
9351 (let* ((pos (point))
9352 (ct (org-context))
9353 (a (assoc :link ct)))
9354 (if a (goto-char (nth 1 a)))
9355 (if (re-search-backward org-any-link-re nil t)
9356 (progn
9357 (goto-char (match-beginning 0))
9358 (if (outline-invisible-p) (org-show-context)))
9359 (goto-char pos)
9360 (setq org-link-search-failed t)
9361 (error "No further link found"))))
9363 (defun org-translate-link (s)
9364 "Translate a link string if a translation function has been defined."
9365 (if (and org-link-translation-function
9366 (fboundp org-link-translation-function)
9367 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9368 (progn
9369 (setq s (funcall org-link-translation-function
9370 (match-string 1) (match-string 2)))
9371 (concat (car s) ":" (cdr s)))
9374 (defun org-translate-link-from-planner (type path)
9375 "Translate a link from Emacs Planner syntax so that Org can follow it.
9376 This is still an experimental function, your mileage may vary."
9377 (cond
9378 ((member type '("http" "https" "news" "ftp"))
9379 ;; standard Internet links are the same.
9380 nil)
9381 ((and (equal type "irc") (string-match "^//" path))
9382 ;; Planner has two / at the beginning of an irc link, we have 1.
9383 ;; We should have zero, actually....
9384 (setq path (substring path 1)))
9385 ((and (equal type "lisp") (string-match "^/" path))
9386 ;; Planner has a slash, we do not.
9387 (setq type "elisp" path (substring path 1)))
9388 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9389 ;; A typical message link. Planner has the id after the final slash,
9390 ;; we separate it with a hash mark
9391 (setq path (concat (match-string 1 path) "#"
9392 (org-remove-angle-brackets (match-string 2 path)))))
9394 (cons type path))
9396 (defun org-find-file-at-mouse (ev)
9397 "Open file link or URL at mouse."
9398 (interactive "e")
9399 (mouse-set-point ev)
9400 (org-open-at-point 'in-emacs))
9402 (defun org-open-at-mouse (ev)
9403 "Open file link or URL at mouse.
9404 See the docstring of `org-open-file' for details."
9405 (interactive "e")
9406 (mouse-set-point ev)
9407 (if (eq major-mode 'org-agenda-mode)
9408 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9409 (org-open-at-point))
9411 (defvar org-window-config-before-follow-link nil
9412 "The window configuration before following a link.
9413 This is saved in case the need arises to restore it.")
9415 (defvar org-open-link-marker (make-marker)
9416 "Marker pointing to the location where `org-open-at-point; was called.")
9418 ;;;###autoload
9419 (defun org-open-at-point-global ()
9420 "Follow a link like Org-mode does.
9421 This command can be called in any mode to follow a link that has
9422 Org-mode syntax."
9423 (interactive)
9424 (org-run-like-in-org-mode 'org-open-at-point))
9426 ;;;###autoload
9427 (defun org-open-link-from-string (s &optional arg reference-buffer)
9428 "Open a link in the string S, as if it was in Org-mode."
9429 (interactive "sLink: \nP")
9430 (let ((reference-buffer (or reference-buffer (current-buffer))))
9431 (with-temp-buffer
9432 (let ((org-inhibit-startup t))
9433 (org-mode)
9434 (insert s)
9435 (goto-char (point-min))
9436 (when reference-buffer
9437 (setq org-link-abbrev-alist-local
9438 (with-current-buffer reference-buffer
9439 org-link-abbrev-alist-local)))
9440 (org-open-at-point arg reference-buffer)))))
9442 (defvar org-open-at-point-functions nil
9443 "Hook that is run when following a link at point.
9445 Functions in this hook must return t if they identify and follow
9446 a link at point. If they don't find anything interesting at point,
9447 they must return nil.")
9449 (defun org-open-at-point (&optional arg reference-buffer)
9450 "Open link at or after point.
9451 If there is no link at point, this function will search forward up to
9452 the end of the current line.
9453 Normally, files will be opened by an appropriate application. If the
9454 optional prefix argument ARG is non-nil, Emacs will visit the file.
9455 With a double prefix argument, try to open outside of Emacs, in the
9456 application the system uses for this file type."
9457 (interactive "P")
9458 ;; if in a code block, then open the block's results
9459 (unless (call-interactively #'org-babel-open-src-block-result)
9460 (org-load-modules-maybe)
9461 (move-marker org-open-link-marker (point))
9462 (setq org-window-config-before-follow-link (current-window-configuration))
9463 (org-remove-occur-highlights nil nil t)
9464 (cond
9465 ((and (org-on-heading-p)
9466 (not (org-in-regexp
9467 (concat org-plain-link-re "\\|"
9468 org-bracket-link-regexp "\\|"
9469 org-angle-link-re "\\|"
9470 "[ \t]:[^ \t\n]+:[ \t]*$")))
9471 (not (get-text-property (point) 'org-linked-text)))
9472 (or (org-offer-links-in-entry arg)
9473 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9474 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9475 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9476 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9477 (not (org-in-regexp org-bracket-link-regexp)))
9478 (org-footnote-action))
9480 (let (type path link line search (pos (point)))
9481 (catch 'match
9482 (save-excursion
9483 (skip-chars-forward "^]\n\r")
9484 (when (org-in-regexp org-bracket-link-regexp 1)
9485 (setq link (org-extract-attributes
9486 (org-link-unescape (org-match-string-no-properties 1))))
9487 (while (string-match " *\n *" link)
9488 (setq link (replace-match " " t t link)))
9489 (setq link (org-link-expand-abbrev link))
9490 (cond
9491 ((or (file-name-absolute-p link)
9492 (string-match "^\\.\\.?/" link))
9493 (setq type "file" path link))
9494 ((string-match org-link-re-with-space3 link)
9495 (setq type (match-string 1 link) path (match-string 2 link)))
9496 (t (setq type "thisfile" path link)))
9497 (throw 'match t)))
9499 (when (get-text-property (point) 'org-linked-text)
9500 (setq type "thisfile"
9501 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9502 (1+ (point)) (point))
9503 path (buffer-substring
9504 (or (previous-single-property-change pos 'org-linked-text)
9505 (point-min))
9506 (or (next-single-property-change pos 'org-linked-text)
9507 (point-max))))
9508 (throw 'match t))
9510 (save-excursion
9511 (when (or (org-in-regexp org-angle-link-re)
9512 (org-in-regexp org-plain-link-re))
9513 (setq type (match-string 1)
9514 path (org-link-unescape (match-string 2)))
9515 (throw 'match t)))
9516 (save-excursion
9517 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9518 (setq type "tags"
9519 path (match-string 1))
9520 (while (string-match ":" path)
9521 (setq path (replace-match "+" t t path)))
9522 (throw 'match t)))
9523 (when (org-in-regexp "<\\([^><\n]+\\)>")
9524 (setq type "tree-match"
9525 path (match-string 1))
9526 (throw 'match t)))
9527 (unless path
9528 (error "No link found"))
9530 ;; switch back to reference buffer
9531 ;; needed when if called in a temporary buffer through
9532 ;; org-open-link-from-string
9533 (with-current-buffer (or reference-buffer (current-buffer))
9535 ;; Remove any trailing spaces in path
9536 (if (string-match " +\\'" path)
9537 (setq path (replace-match "" t t path)))
9538 (if (and org-link-translation-function
9539 (fboundp org-link-translation-function))
9540 ;; Check if we need to translate the link
9541 (let ((tmp (funcall org-link-translation-function type path)))
9542 (setq type (car tmp) path (cdr tmp))))
9544 (cond
9546 ((assoc type org-link-protocols)
9547 (funcall (nth 1 (assoc type org-link-protocols)) path))
9549 ((equal type "mailto")
9550 (let ((cmd (car org-link-mailto-program))
9551 (args (cdr org-link-mailto-program)) args1
9552 (address path) (subject "") a)
9553 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9554 (setq address (match-string 1 path)
9555 subject (org-link-escape (match-string 2 path))))
9556 (while args
9557 (cond
9558 ((not (stringp (car args))) (push (pop args) args1))
9559 (t (setq a (pop args))
9560 (if (string-match "%a" a)
9561 (setq a (replace-match address t t a)))
9562 (if (string-match "%s" a)
9563 (setq a (replace-match subject t t a)))
9564 (push a args1))))
9565 (apply cmd (nreverse args1))))
9567 ((member type '("http" "https" "ftp" "news"))
9568 (browse-url (concat type ":" (org-link-escape
9569 path org-link-escape-chars-browser))))
9571 ((string= type "doi")
9572 (browse-url (concat "http://dx.doi.org/"
9573 (org-link-escape
9574 path org-link-escape-chars-browser))))
9576 ((member type '("message"))
9577 (browse-url (concat type ":" path)))
9579 ((string= type "tags")
9580 (org-tags-view arg path))
9582 ((string= type "tree-match")
9583 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9585 ((string= type "file")
9586 (if (string-match "::\\([0-9]+\\)\\'" path)
9587 (setq line (string-to-number (match-string 1 path))
9588 path (substring path 0 (match-beginning 0)))
9589 (if (string-match "::\\(.+\\)\\'" path)
9590 (setq search (match-string 1 path)
9591 path (substring path 0 (match-beginning 0)))))
9592 (if (string-match "[*?{]" (file-name-nondirectory path))
9593 (dired path)
9594 (org-open-file path arg line search)))
9596 ((string= type "shell")
9597 (let ((cmd path))
9598 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9599 (string-match org-confirm-shell-link-not-regexp cmd))
9600 (not org-confirm-shell-link-function)
9601 (funcall org-confirm-shell-link-function
9602 (format "Execute \"%s\" in shell? "
9603 (org-add-props cmd nil
9604 'face 'org-warning))))
9605 (progn
9606 (message "Executing %s" cmd)
9607 (shell-command cmd))
9608 (error "Abort"))))
9610 ((string= type "elisp")
9611 (let ((cmd path))
9612 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9613 (string-match org-confirm-elisp-link-not-regexp cmd))
9614 (not org-confirm-elisp-link-function)
9615 (funcall org-confirm-elisp-link-function
9616 (format "Execute \"%s\" as elisp? "
9617 (org-add-props cmd nil
9618 'face 'org-warning))))
9619 (message "%s => %s" cmd
9620 (if (equal (string-to-char cmd) ?\()
9621 (eval (read cmd))
9622 (call-interactively (read cmd))))
9623 (error "Abort"))))
9625 ((and (string= type "thisfile")
9626 (run-hook-with-args-until-success
9627 'org-open-link-functions path)))
9629 ((string= type "thisfile")
9630 (if arg
9631 (switch-to-buffer-other-window
9632 (org-get-buffer-for-internal-link (current-buffer)))
9633 (org-mark-ring-push))
9634 (let ((cmd `(org-link-search
9635 ,path
9636 ,(cond ((equal arg '(4)) ''occur)
9637 ((equal arg '(16)) ''org-occur)
9638 (t nil))
9639 ,pos)))
9640 (condition-case nil (let ((org-link-search-inhibit-query t))
9641 (eval cmd))
9642 (error (progn (widen) (eval cmd))))))
9645 (browse-url-at-point)))))))
9646 (move-marker org-open-link-marker nil)
9647 (run-hook-with-args 'org-follow-link-hook)))
9649 (defun org-offer-links-in-entry (&optional nth zero)
9650 "Offer links in the current entry and follow the selected link.
9651 If there is only one link, follow it immediately as well.
9652 If NTH is an integer, immediately pick the NTH link found.
9653 If ZERO is a string, check also this string for a link, and if
9654 there is one, offer it as link number zero."
9655 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9656 "\\(" org-angle-link-re "\\)\\|"
9657 "\\(" org-plain-link-re "\\)"))
9658 (cnt ?0)
9659 (in-emacs (if (integerp nth) nil nth))
9660 have-zero end links link c)
9661 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9662 (push (match-string 0 zero) links)
9663 (setq cnt (1- cnt) have-zero t))
9664 (save-excursion
9665 (org-back-to-heading t)
9666 (setq end (save-excursion (outline-next-heading) (point)))
9667 (while (re-search-forward re end t)
9668 (push (match-string 0) links))
9669 (setq links (org-uniquify (reverse links))))
9671 (cond
9672 ((null links)
9673 (message "No links"))
9674 ((equal (length links) 1)
9675 (setq link (list (car links))))
9676 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9677 (setq link (nth (if have-zero nth (1- nth)) links)))
9678 (t ; we have to select a link
9679 (save-excursion
9680 (save-window-excursion
9681 (delete-other-windows)
9682 (with-output-to-temp-buffer "*Select Link*"
9683 (mapc (lambda (l)
9684 (if (not (string-match org-bracket-link-regexp l))
9685 (princ (format "[%c] %s\n" (incf cnt)
9686 (org-remove-angle-brackets l)))
9687 (if (match-end 3)
9688 (princ (format "[%c] %s (%s)\n" (incf cnt)
9689 (match-string 3 l) (match-string 1 l)))
9690 (princ (format "[%c] %s\n" (incf cnt)
9691 (match-string 1 l))))))
9692 links))
9693 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9694 (message "Select link to open, RET to open all:")
9695 (setq c (read-char-exclusive))
9696 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9697 (when (equal c ?q) (error "Abort"))
9698 (if (equal c ?\C-m)
9699 (setq link links)
9700 (setq nth (- c ?0))
9701 (if have-zero (setq nth (1+ nth)))
9702 (unless (and (integerp nth) (>= (length links) nth))
9703 (error "Invalid link selection"))
9704 (setq link (list (nth (1- nth) links))))))
9705 (if link
9706 (let ((buf (current-buffer)))
9707 (dolist (l link)
9708 (org-open-link-from-string l in-emacs buf))
9710 nil)))
9712 ;; Add special file links that specify the way of opening
9714 (org-add-link-type "file+sys" 'org-open-file-with-system)
9715 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9716 (defun org-open-file-with-system (path)
9717 "Open file at PATH using the system way of opening it."
9718 (org-open-file path 'system))
9719 (defun org-open-file-with-emacs (path)
9720 "Open file at PATH in Emacs."
9721 (org-open-file path 'emacs))
9722 (defun org-remove-file-link-modifiers ()
9723 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9724 (goto-char (point-min))
9725 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9726 (org-if-unprotected
9727 (replace-match "file:" t t))))
9728 (eval-after-load "org-exp"
9729 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9730 'org-remove-file-link-modifiers))
9732 ;;;; Time estimates
9734 (defun org-get-effort (&optional pom)
9735 "Get the effort estimate for the current entry."
9736 (org-entry-get pom org-effort-property))
9738 ;;; File search
9740 (defvar org-create-file-search-functions nil
9741 "List of functions to construct the right search string for a file link.
9742 These functions are called in turn with point at the location to
9743 which the link should point.
9745 A function in the hook should first test if it would like to
9746 handle this file type, for example by checking the `major-mode'
9747 or the file extension. If it decides not to handle this file, it
9748 should just return nil to give other functions a chance. If it
9749 does handle the file, it must return the search string to be used
9750 when following the link. The search string will be part of the
9751 file link, given after a double colon, and `org-open-at-point'
9752 will automatically search for it. If special measures must be
9753 taken to make the search successful, another function should be
9754 added to the companion hook `org-execute-file-search-functions',
9755 which see.
9757 A function in this hook may also use `setq' to set the variable
9758 `description' to provide a suggestion for the descriptive text to
9759 be used for this link when it gets inserted into an Org-mode
9760 buffer with \\[org-insert-link].")
9762 (defvar org-execute-file-search-functions nil
9763 "List of functions to execute a file search triggered by a link.
9765 Functions added to this hook must accept a single argument, the
9766 search string that was part of the file link, the part after the
9767 double colon. The function must first check if it would like to
9768 handle this search, for example by checking the `major-mode' or
9769 the file extension. If it decides not to handle this search, it
9770 should just return nil to give other functions a chance. If it
9771 does handle the search, it must return a non-nil value to keep
9772 other functions from trying.
9774 Each function can access the current prefix argument through the
9775 variable `current-prefix-argument'. Note that a single prefix is
9776 used to force opening a link in Emacs, so it may be good to only
9777 use a numeric or double prefix to guide the search function.
9779 In case this is needed, a function in this hook can also restore
9780 the window configuration before `org-open-at-point' was called using:
9782 (set-window-configuration org-window-config-before-follow-link)")
9784 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9785 (defun org-link-search (s &optional type avoid-pos stealth)
9786 "Search for a link search option.
9787 If S is surrounded by forward slashes, it is interpreted as a
9788 regular expression. In org-mode files, this will create an `org-occur'
9789 sparse tree. In ordinary files, `occur' will be used to list matches.
9790 If the current buffer is in `dired-mode', grep will be used to search
9791 in all files. If AVOID-POS is given, ignore matches near that position.
9793 When optional argument STEALTH is non-nil, do not modify
9794 visibility around point, thus ignoring
9795 `org-show-hierarchy-above', `org-show-following-heading' and
9796 `org-show-siblings' variables."
9797 (let ((case-fold-search t)
9798 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9799 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9800 (append '(("") (" ") ("\t") ("\n"))
9801 org-emphasis-alist)
9802 "\\|") "\\)"))
9803 (pos (point))
9804 (pre nil) (post nil)
9805 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9806 (cond
9807 ;; First check if there are any special search functions
9808 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9809 ;; Now try the builtin stuff
9810 ((and (equal (string-to-char s0) ?#)
9811 (> (length s0) 1)
9812 (save-excursion
9813 (goto-char (point-min))
9814 (and
9815 (re-search-forward
9816 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9817 (setq type 'dedicated
9818 pos (match-beginning 0))))
9819 ;; There is an exact target for this
9820 (goto-char pos)
9821 (org-back-to-heading t)))
9822 ((save-excursion
9823 (goto-char (point-min))
9824 (and
9825 (re-search-forward
9826 (concat "<<" (regexp-quote s0) ">>") nil t)
9827 (setq type 'dedicated
9828 pos (match-beginning 0))))
9829 ;; There is an exact target for this
9830 (goto-char pos))
9831 ((and (string-match "^(\\(.*\\))$" s0)
9832 (save-excursion
9833 (goto-char (point-min))
9834 (and
9835 (re-search-forward
9836 (concat "[^[]" (regexp-quote
9837 (format org-coderef-label-format
9838 (match-string 1 s0))))
9839 nil t)
9840 (setq type 'dedicated
9841 pos (1+ (match-beginning 0))))))
9842 ;; There is a coderef target for this
9843 (goto-char pos))
9844 ((string-match "^/\\(.*\\)/$" s)
9845 ;; A regular expression
9846 (cond
9847 ((eq major-mode 'org-mode)
9848 (org-occur (match-string 1 s)))
9849 ;;((eq major-mode 'dired-mode)
9850 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9851 (t (org-do-occur (match-string 1 s)))))
9852 ((and (eq major-mode 'org-mode) org-link-search-must-match-exact-headline)
9853 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
9854 (goto-char (point-min))
9855 (cond
9856 ((let (case-fold-search)
9857 (re-search-forward (format org-complex-heading-regexp-format
9858 (regexp-quote s))
9859 nil t))
9860 ;; OK, found a match
9861 (setq type 'dedicated)
9862 (goto-char (match-beginning 0)))
9863 ((and (not org-link-search-inhibit-query)
9864 (eq org-link-search-must-match-exact-headline 'query-to-create)
9865 (y-or-n-p "No match - create this as a new heading? "))
9866 (goto-char (point-max))
9867 (or (bolp) (newline))
9868 (insert "* " s "\n")
9869 (beginning-of-line 0))
9871 (goto-char pos)
9872 (error "No match"))))
9874 ;; A normal search string
9875 (when (equal (string-to-char s) ?*)
9876 ;; Anchor on headlines, post may include tags.
9877 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
9878 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
9879 s (substring s 1)))
9880 (remove-text-properties
9881 0 (length s)
9882 '(face nil mouse-face nil keymap nil fontified nil) s)
9883 ;; Make a series of regular expressions to find a match
9884 (setq words (org-split-string s "[ \n\r\t]+")
9886 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9887 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
9888 "\\)" markers)
9889 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9890 re2a (concat "[ \t\r\n]" re2a_)
9891 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9892 re4 (concat "[^a-zA-Z_]" re4_)
9894 re1 (concat pre re2 post)
9895 re3 (concat pre (if pre re4_ re4) post)
9896 re5 (concat pre ".*" re4)
9897 re2 (concat pre re2)
9898 re2a (concat pre (if pre re2a_ re2a))
9899 re4 (concat pre (if pre re4_ re4))
9900 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9901 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9902 re5 "\\)"
9904 (cond
9905 ((eq type 'org-occur) (org-occur reall))
9906 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9907 (t (goto-char (point-min))
9908 (setq type 'fuzzy)
9909 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
9910 (org-search-not-self 1 re1 nil t)
9911 (org-search-not-self 1 re2 nil t)
9912 (org-search-not-self 1 re2a nil t)
9913 (org-search-not-self 1 re3 nil t)
9914 (org-search-not-self 1 re4 nil t)
9915 (org-search-not-self 1 re5 nil t)
9917 (goto-char (match-beginning 1))
9918 (goto-char pos)
9919 (error "No match"))))))
9920 (and (eq major-mode 'org-mode)
9921 (not stealth)
9922 (org-show-context 'link-search))
9923 type))
9925 (defun org-search-not-self (group &rest args)
9926 "Execute `re-search-forward', but only accept matches that do not
9927 enclose the position of `org-open-link-marker'."
9928 (let ((m org-open-link-marker))
9929 (catch 'exit
9930 (while (apply 're-search-forward args)
9931 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
9932 (goto-char (match-end group))
9933 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
9934 (> (match-beginning 0) (marker-position m))
9935 (< (match-end 0) (marker-position m)))
9936 (save-match-data
9937 (or (not (org-in-regexp
9938 org-bracket-link-analytic-regexp 1))
9939 (not (match-end 4)) ; no description
9940 (and (<= (match-beginning 4) (point))
9941 (>= (match-end 4) (point))))))
9942 (throw 'exit (point))))))))
9944 (defun org-get-buffer-for-internal-link (buffer)
9945 "Return a buffer to be used for displaying the link target of internal links."
9946 (cond
9947 ((not org-display-internal-link-with-indirect-buffer)
9948 buffer)
9949 ((string-match "(Clone)$" (buffer-name buffer))
9950 (message "Buffer is already a clone, not making another one")
9951 ;; we also do not modify visibility in this case
9952 buffer)
9953 (t ; make a new indirect buffer for displaying the link
9954 (let* ((bn (buffer-name buffer))
9955 (ibn (concat bn "(Clone)"))
9956 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
9957 (with-current-buffer ib (org-overview))
9958 ib))))
9960 (defun org-do-occur (regexp &optional cleanup)
9961 "Call the Emacs command `occur'.
9962 If CLEANUP is non-nil, remove the printout of the regular expression
9963 in the *Occur* buffer. This is useful if the regex is long and not useful
9964 to read."
9965 (occur regexp)
9966 (when cleanup
9967 (let ((cwin (selected-window)) win beg end)
9968 (when (setq win (get-buffer-window "*Occur*"))
9969 (select-window win))
9970 (goto-char (point-min))
9971 (when (re-search-forward "match[a-z]+" nil t)
9972 (setq beg (match-end 0))
9973 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9974 (setq end (1- (match-beginning 0)))))
9975 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
9976 (goto-char (point-min))
9977 (select-window cwin))))
9979 ;;; The mark ring for links jumps
9981 (defvar org-mark-ring nil
9982 "Mark ring for positions before jumps in Org-mode.")
9983 (defvar org-mark-ring-last-goto nil
9984 "Last position in the mark ring used to go back.")
9985 ;; Fill and close the ring
9986 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9987 (loop for i from 1 to org-mark-ring-length do
9988 (push (make-marker) org-mark-ring))
9989 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
9990 org-mark-ring)
9992 (defun org-mark-ring-push (&optional pos buffer)
9993 "Put the current position or POS into the mark ring and rotate it."
9994 (interactive)
9995 (setq pos (or pos (point)))
9996 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
9997 (move-marker (car org-mark-ring)
9998 (or pos (point))
9999 (or buffer (current-buffer)))
10000 (message "%s"
10001 (substitute-command-keys
10002 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10004 (defun org-mark-ring-goto (&optional n)
10005 "Jump to the previous position in the mark ring.
10006 With prefix arg N, jump back that many stored positions. When
10007 called several times in succession, walk through the entire ring.
10008 Org-mode commands jumping to a different position in the current file,
10009 or to another Org-mode file, automatically push the old position
10010 onto the ring."
10011 (interactive "p")
10012 (let (p m)
10013 (if (eq last-command this-command)
10014 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10015 (setq p org-mark-ring))
10016 (setq org-mark-ring-last-goto p)
10017 (setq m (car p))
10018 (org-pop-to-buffer-same-window (marker-buffer m))
10019 (goto-char m)
10020 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10022 (defun org-remove-angle-brackets (s)
10023 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10024 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10026 (defun org-add-angle-brackets (s)
10027 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10028 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10030 (defun org-remove-double-quotes (s)
10031 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10032 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10035 ;;; Following specific links
10037 (defun org-follow-timestamp-link ()
10038 (cond
10039 ((org-at-date-range-p t)
10040 (let ((org-agenda-start-on-weekday)
10041 (t1 (match-string 1))
10042 (t2 (match-string 2)))
10043 (setq t1 (time-to-days (org-time-string-to-time t1))
10044 t2 (time-to-days (org-time-string-to-time t2)))
10045 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10046 ((org-at-timestamp-p t)
10047 (org-agenda-list nil (time-to-days (org-time-string-to-time
10048 (substring (match-string 1) 0 10)))
10050 (t (error "This should not happen"))))
10053 ;;; Following file links
10054 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10055 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10056 (declare-function mailcap-mime-info
10057 "mailcap" (string &optional request no-decode))
10058 (defvar org-wait nil)
10059 (defun org-open-file (path &optional in-emacs line search)
10060 "Open the file at PATH.
10061 First, this expands any special file name abbreviations. Then the
10062 configuration variable `org-file-apps' is checked if it contains an
10063 entry for this file type, and if yes, the corresponding command is launched.
10065 If no application is found, Emacs simply visits the file.
10067 With optional prefix argument IN-EMACS, Emacs will visit the file.
10068 With a double \\[universal-argument] \\[universal-argument] \
10069 prefix arg, Org tries to avoid opening in Emacs
10070 and to use an external application to visit the file.
10072 Optional LINE specifies a line to go to, optional SEARCH a string
10073 to search for. If LINE or SEARCH is given, the file will be
10074 opened in Emacs, unless an entry from org-file-apps that makes
10075 use of groups in a regexp matches.
10077 If you want to change the way frames are used when following a
10078 link, please customize `org-link-frame-setup'.
10080 If the file does not exist, an error is thrown."
10081 (let* ((file (if (equal path "")
10082 buffer-file-name
10083 (substitute-in-file-name (expand-file-name path))))
10084 (file-apps (append org-file-apps (org-default-apps)))
10085 (apps (org-remove-if
10086 'org-file-apps-entry-match-against-dlink-p file-apps))
10087 (apps-dlink (org-remove-if-not
10088 'org-file-apps-entry-match-against-dlink-p file-apps))
10089 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10090 (dirp (if remp nil (file-directory-p file)))
10091 (file (if (and dirp org-open-directory-means-index-dot-org)
10092 (concat (file-name-as-directory file) "index.org")
10093 file))
10094 (a-m-a-p (assq 'auto-mode apps))
10095 (dfile (downcase file))
10096 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10097 (link (cond ((and (eq line nil)
10098 (eq search nil))
10099 file)
10100 (line
10101 (concat file "::" (number-to-string line)))
10102 (search
10103 (concat file "::" search))))
10104 (dlink (downcase link))
10105 (old-buffer (current-buffer))
10106 (old-pos (point))
10107 (old-mode major-mode)
10108 ext cmd link-match-data)
10109 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10110 (setq ext (match-string 1 dfile))
10111 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10112 (setq ext (match-string 1 dfile))))
10113 (cond
10114 ((member in-emacs '((16) system))
10115 (setq cmd (cdr (assoc 'system apps))))
10116 (in-emacs (setq cmd 'emacs))
10118 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10119 (and dirp (cdr (assoc 'directory apps)))
10120 ; first, try matching against apps-dlink
10121 ; if we get a match here, store the match data for later
10122 (let ((match (assoc-default dlink apps-dlink
10123 'string-match)))
10124 (if match
10125 (progn (setq link-match-data (match-data))
10126 match)
10127 (progn (setq in-emacs (or in-emacs line search))
10128 nil))) ; if we have no match in apps-dlink,
10129 ; always open the file in emacs if line or search
10130 ; is given (for backwards compatibility)
10131 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10132 'string-match)
10133 (cdr (assoc ext apps))
10134 (cdr (assoc t apps))))))
10135 (when (eq cmd 'system)
10136 (setq cmd (cdr (assoc 'system apps))))
10137 (when (eq cmd 'default)
10138 (setq cmd (cdr (assoc t apps))))
10139 (when (eq cmd 'mailcap)
10140 (require 'mailcap)
10141 (mailcap-parse-mailcaps)
10142 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10143 (command (mailcap-mime-info mime-type)))
10144 (if (stringp command)
10145 (setq cmd command)
10146 (setq cmd 'emacs))))
10147 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10148 (not (file-exists-p file))
10149 (not org-open-non-existing-files))
10150 (error "No such file: %s" file))
10151 (cond
10152 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10153 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10154 (while (string-match "['\"]%s['\"]" cmd)
10155 (setq cmd (replace-match "%s" t t cmd)))
10156 (while (string-match "%s" cmd)
10157 (setq cmd (replace-match
10158 (save-match-data
10159 (shell-quote-argument
10160 (convert-standard-filename file)))
10161 t t cmd)))
10163 ;; Replace "%1", "%2" etc. in command with group matches from regex
10164 (save-match-data
10165 (let ((match-index 1)
10166 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10167 (set-match-data link-match-data)
10168 (while (<= match-index number-of-groups)
10169 (let ((regex (concat "%" (number-to-string match-index)))
10170 (replace-with (match-string match-index dlink)))
10171 (while (string-match regex cmd)
10172 (setq cmd (replace-match replace-with t t cmd))))
10173 (setq match-index (+ match-index 1)))))
10175 (save-window-excursion
10176 (start-process-shell-command cmd nil cmd)
10177 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10179 ((or (stringp cmd)
10180 (eq cmd 'emacs))
10181 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10182 (widen)
10183 (if line (org-goto-line line)
10184 (if search (org-link-search search))))
10185 ((consp cmd)
10186 (let ((file (convert-standard-filename file)))
10187 (save-match-data
10188 (set-match-data link-match-data)
10189 (eval cmd))))
10190 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10191 (and (eq major-mode 'org-mode) (eq old-mode 'org-mode)
10192 (or (not (equal old-buffer (current-buffer)))
10193 (not (equal old-pos (point))))
10194 (org-mark-ring-push old-pos old-buffer))))
10196 (defun org-file-apps-entry-match-against-dlink-p (entry)
10197 "This function returns non-nil if `entry' uses a regular
10198 expression which should be matched against the whole link by
10199 org-open-file.
10201 It assumes that is the case when the entry uses a regular
10202 expression which has at least one grouping construct and the
10203 action is either a lisp form or a command string containing
10204 '%1', i.e. using at least one subexpression match as a
10205 parameter."
10206 (let ((selector (car entry))
10207 (action (cdr entry)))
10208 (if (stringp selector)
10209 (and (> (regexp-opt-depth selector) 0)
10210 (or (and (stringp action)
10211 (string-match "%[0-9]" action))
10212 (consp action)))
10213 nil)))
10215 (defun org-default-apps ()
10216 "Return the default applications for this operating system."
10217 (cond
10218 ((eq system-type 'darwin)
10219 org-file-apps-defaults-macosx)
10220 ((eq system-type 'windows-nt)
10221 org-file-apps-defaults-windowsnt)
10222 (t org-file-apps-defaults-gnu)))
10224 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10225 "Convert extensions to regular expressions in the cars of LIST.
10226 Also, weed out any non-string entries, because the return value is used
10227 only for regexp matching.
10228 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10229 point to the symbol `emacs', indicating that the file should
10230 be opened in Emacs."
10231 (append
10232 (delq nil
10233 (mapcar (lambda (x)
10234 (if (not (stringp (car x)))
10236 (if (string-match "\\W" (car x))
10238 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10239 list))
10240 (if add-auto-mode
10241 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10243 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10244 (defun org-file-remote-p (file)
10245 "Test whether FILE specifies a location on a remote system.
10246 Return non-nil if the location is indeed remote.
10248 For example, the filename \"/user@host:/foo\" specifies a location
10249 on the system \"/user@host:\"."
10250 (cond ((fboundp 'file-remote-p)
10251 (file-remote-p file))
10252 ((fboundp 'tramp-handle-file-remote-p)
10253 (tramp-handle-file-remote-p file))
10254 ((and (boundp 'ange-ftp-name-format)
10255 (string-match (car ange-ftp-name-format) file))
10257 (t nil)))
10260 ;;;; Refiling
10262 (defun org-get-org-file ()
10263 "Read a filename, with default directory `org-directory'."
10264 (let ((default (or org-default-notes-file remember-data-file)))
10265 (read-file-name (format "File name [%s]: " default)
10266 (file-name-as-directory org-directory)
10267 default)))
10269 (defun org-notes-order-reversed-p ()
10270 "Check if the current file should receive notes in reversed order."
10271 (cond
10272 ((not org-reverse-note-order) nil)
10273 ((eq t org-reverse-note-order) t)
10274 ((not (listp org-reverse-note-order)) nil)
10275 (t (catch 'exit
10276 (let ((all org-reverse-note-order)
10277 entry)
10278 (while (setq entry (pop all))
10279 (if (string-match (car entry) buffer-file-name)
10280 (throw 'exit (cdr entry))))
10281 nil)))))
10283 (defvar org-refile-target-table nil
10284 "The list of refile targets, created by `org-refile'.")
10286 (defvar org-agenda-new-buffers nil
10287 "Buffers created to visit agenda files.")
10289 (defvar org-refile-cache nil
10290 "Cache for refile targets.")
10292 (defvar org-refile-markers nil
10293 "All the markers used for caching refile locations.")
10295 (defun org-refile-marker (pos)
10296 "Get a new refile marker, but only if caching is in use."
10297 (if (not org-refile-use-cache)
10299 (let ((m (make-marker)))
10300 (move-marker m pos)
10301 (push m org-refile-markers)
10302 m)))
10304 (defun org-refile-cache-clear ()
10305 "Clear the refile cache and disable all the markers."
10306 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10307 (setq org-refile-markers nil)
10308 (setq org-refile-cache nil)
10309 (message "Refile cache has been cleared"))
10311 (defun org-refile-cache-check-set (set)
10312 "Check if all the markers in the cache still have live buffers."
10313 (let (marker)
10314 (catch 'exit
10315 (while (and set (setq marker (nth 3 (pop set))))
10316 ;; if org-refile-use-outline-path is 'file, marker may be nil
10317 (when (and marker (null (marker-buffer marker)))
10318 (message "not found") (sit-for 3)
10319 (throw 'exit nil)))
10320 t)))
10322 (defun org-refile-cache-put (set &rest identifiers)
10323 "Push the refile targets SET into the cache, under IDENTIFIERS."
10324 (let* ((key (sha1 (prin1-to-string identifiers)))
10325 (entry (assoc key org-refile-cache)))
10326 (if entry
10327 (setcdr entry set)
10328 (push (cons key set) org-refile-cache))))
10330 (defun org-refile-cache-get (&rest identifiers)
10331 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10332 (cond
10333 ((not org-refile-cache) nil)
10334 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10336 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10337 org-refile-cache))))
10338 (and set (org-refile-cache-check-set set) set)))))
10340 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10341 "Produce a table with refile targets."
10342 (let ((case-fold-search nil)
10343 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10344 (entries (or org-refile-targets '((nil . (:level . 1)))))
10345 targets tgs txt re files f desc descre fast-path-p level pos0)
10346 (message "Getting targets...")
10347 (with-current-buffer (or default-buffer (current-buffer))
10348 (while (setq entry (pop entries))
10349 (setq files (car entry) desc (cdr entry))
10350 (setq fast-path-p nil)
10351 (cond
10352 ((null files) (setq files (list (current-buffer))))
10353 ((eq files 'org-agenda-files)
10354 (setq files (org-agenda-files 'unrestricted)))
10355 ((and (symbolp files) (fboundp files))
10356 (setq files (funcall files)))
10357 ((and (symbolp files) (boundp files))
10358 (setq files (symbol-value files))))
10359 (if (stringp files) (setq files (list files)))
10360 (cond
10361 ((eq (car desc) :tag)
10362 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10363 ((eq (car desc) :todo)
10364 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10365 ((eq (car desc) :regexp)
10366 (setq descre (cdr desc)))
10367 ((eq (car desc) :level)
10368 (setq descre (concat "^\\*\\{" (number-to-string
10369 (if org-odd-levels-only
10370 (1- (* 2 (cdr desc)))
10371 (cdr desc)))
10372 "\\}[ \t]")))
10373 ((eq (car desc) :maxlevel)
10374 (setq fast-path-p t)
10375 (setq descre (concat "^\\*\\{1," (number-to-string
10376 (if org-odd-levels-only
10377 (1- (* 2 (cdr desc)))
10378 (cdr desc)))
10379 "\\}[ \t]")))
10380 (t (error "Bad refiling target description %s" desc)))
10381 (while (setq f (pop files))
10382 (with-current-buffer
10383 (if (bufferp f) f (org-get-agenda-file-buffer f))
10385 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10386 (progn
10387 (if (bufferp f) (setq f (buffer-file-name
10388 (buffer-base-buffer f))))
10389 (setq f (and f (expand-file-name f)))
10390 (if (eq org-refile-use-outline-path 'file)
10391 (push (list (file-name-nondirectory f) f nil nil) tgs))
10392 (save-excursion
10393 (save-restriction
10394 (widen)
10395 (goto-char (point-min))
10396 (while (re-search-forward descre nil t)
10397 (goto-char (setq pos0 (point-at-bol)))
10398 (catch 'next
10399 (when org-refile-target-verify-function
10400 (save-match-data
10401 (or (funcall org-refile-target-verify-function)
10402 (throw 'next t))))
10403 (when (and (looking-at org-complex-heading-regexp)
10404 (not (member (match-string 4) excluded-entries)))
10405 (setq level (org-reduced-level
10406 (- (match-end 1) (match-beginning 1)))
10407 txt (org-link-display-format (match-string 4))
10408 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10409 re (format org-complex-heading-regexp-format
10410 (regexp-quote (match-string 4))))
10411 (when org-refile-use-outline-path
10412 (setq txt (mapconcat
10413 'org-protect-slash
10414 (append
10415 (if (eq org-refile-use-outline-path
10416 'file)
10417 (list (file-name-nondirectory
10418 (buffer-file-name
10419 (buffer-base-buffer))))
10420 (if (eq org-refile-use-outline-path
10421 'full-file-path)
10422 (list (buffer-file-name
10423 (buffer-base-buffer)))))
10424 (org-get-outline-path fast-path-p
10425 level txt)
10426 (list txt))
10427 "/")))
10428 (push (list txt f re (org-refile-marker (point)))
10429 tgs)))
10430 (when (= (point) pos0)
10431 ;; verification function has not moved point
10432 (goto-char (point-at-eol))))))))
10433 (when org-refile-use-cache
10434 (org-refile-cache-put tgs (buffer-file-name) descre))
10435 (setq targets (append tgs targets))
10436 ))))
10437 (message "Getting targets...done")
10438 (nreverse targets)))
10440 (defun org-protect-slash (s)
10441 (while (string-match "/" s)
10442 (setq s (replace-match "\\" t t s)))
10445 (defvar org-olpa (make-vector 20 nil))
10447 (defun org-get-outline-path (&optional fastp level heading)
10448 "Return the outline path to the current entry, as a list.
10450 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10451 routine which makes outline path derivations for an entire file,
10452 avoiding backtracing. Refile target collection makes use of that."
10453 (if fastp
10454 (progn
10455 (if (> level 19)
10456 (error "Outline path failure, more than 19 levels"))
10457 (loop for i from level upto 19 do
10458 (aset org-olpa i nil))
10459 (prog1
10460 (delq nil (append org-olpa nil))
10461 (aset org-olpa level heading)))
10462 (let (rtn case-fold-search)
10463 (save-excursion
10464 (save-restriction
10465 (widen)
10466 (while (org-up-heading-safe)
10467 (when (looking-at org-complex-heading-regexp)
10468 (push (org-match-string-no-properties 4) rtn)))
10469 rtn)))))
10471 (defun org-format-outline-path (path &optional width prefix)
10472 "Format the outline path PATH for display.
10473 Width is the maximum number of characters that is available.
10474 Prefix is a prefix to be included in the returned string,
10475 such as the file name."
10476 (setq width (or width 79))
10477 (if prefix (setq width (- width (length prefix))))
10478 (if (not path)
10479 (or prefix "")
10480 (let* ((nsteps (length path))
10481 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10482 (maxwidth (if (<= total-width width)
10483 10000 ;; everything fits
10484 ;; we need to shorten the level headings
10485 (/ (- width nsteps) nsteps)))
10486 (org-odd-levels-only nil)
10487 (n 0)
10488 (total (1+ (length prefix))))
10489 (setq maxwidth (max maxwidth 10))
10490 (concat prefix
10491 (mapconcat
10492 (lambda (h)
10493 (setq n (1+ n))
10494 (if (and (= n nsteps) (< maxwidth 10000))
10495 (setq maxwidth (- total-width total)))
10496 (if (< (length h) maxwidth)
10497 (progn (setq total (+ total (length h) 1)) h)
10498 (setq h (substring h 0 (- maxwidth 2))
10499 total (+ total maxwidth 1))
10500 (if (string-match "[ \t]+\\'" h)
10501 (setq h (substring h 0 (match-beginning 0))))
10502 (setq h (concat h "..")))
10503 (org-add-props h nil 'face
10504 (nth (% (1- n) org-n-level-faces)
10505 org-level-faces))
10507 path "/")))))
10509 (defun org-display-outline-path (&optional file current)
10510 "Display the current outline path in the echo area."
10511 (interactive "P")
10512 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10513 (case-fold-search nil)
10514 (path (and (eq major-mode 'org-mode) (org-get-outline-path))))
10515 (if current (setq path (append path
10516 (save-excursion
10517 (org-back-to-heading t)
10518 (if (looking-at org-complex-heading-regexp)
10519 (list (match-string 4)))))))
10520 (message "%s"
10521 (org-format-outline-path
10522 path
10523 (1- (frame-width))
10524 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10526 (defvar org-refile-history nil
10527 "History for refiling operations.")
10529 (defvar org-after-refile-insert-hook nil
10530 "Hook run after `org-refile' has inserted its stuff at the new location.
10531 Note that this is still *before* the stuff will be removed from
10532 the *old* location.")
10534 (defvar org-capture-last-stored-marker)
10535 (defun org-refile (&optional goto default-buffer rfloc)
10536 "Move the entry or entries at point to another heading.
10537 The list of target headings is compiled using the information in
10538 `org-refile-targets', which see.
10540 At the target location, the entry is filed as a subitem of the target
10541 heading. Depending on `org-reverse-note-order', the new subitem will
10542 either be the first or the last subitem.
10544 If there is an active region, all entries in that region will be moved.
10545 However, the region must fulfill the requirement that the first heading
10546 is the first one sets the top-level of the moved text - at most siblings
10547 below it are allowed.
10549 With prefix arg GOTO, the command will only visit the target location
10550 and not actually move anything.
10552 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10553 go to the location where the last refiling operation has put the subtree.
10554 With a prefix argument of `2', refile to the running clock.
10556 RFLOC can be a refile location obtained in a different way.
10558 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10560 If you are using target caching (see `org-refile-use-cache'),
10561 You have to clear the target cache in order to find new targets.
10562 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10563 prefix argument (`C-u C-u C-u C-c C-w')."
10565 (interactive "P")
10566 (if (member goto '(0 (64)))
10567 (org-refile-cache-clear)
10568 (let* ((cbuf (current-buffer))
10569 (regionp (org-region-active-p))
10570 (region-start (and regionp (region-beginning)))
10571 (region-end (and regionp (region-end)))
10572 (region-length (and regionp (- region-end region-start)))
10573 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10574 pos it nbuf file re level reversed)
10575 (setq last-command nil)
10576 (when regionp
10577 (goto-char region-start)
10578 (or (bolp) (goto-char (point-at-bol)))
10579 (setq region-start (point))
10580 (unless (or (org-kill-is-subtree-p
10581 (buffer-substring region-start region-end))
10582 (prog1 org-refile-active-region-within-subtree
10583 (org-toggle-heading)))
10584 (error "The region is not a (sequence of) subtree(s)")))
10585 (if (equal goto '(16))
10586 (org-refile-goto-last-stored)
10587 (when (or
10588 (and (equal goto 2)
10589 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10590 (prog1
10591 (setq it (list (or org-clock-heading "running clock")
10592 (buffer-file-name
10593 (marker-buffer org-clock-hd-marker))
10595 (marker-position org-clock-hd-marker)))
10596 (setq goto nil)))
10597 (setq it (or rfloc
10598 (let (heading-text)
10599 (save-excursion
10600 (unless goto
10601 (org-back-to-heading t)
10602 (setq heading-text
10603 (nth 4 (org-heading-components))))
10604 (org-refile-get-location
10605 (cond (goto "Goto")
10606 (regionp "Refile region to")
10607 (t (concat "Refile subtree \""
10608 heading-text "\" to")))
10609 default-buffer
10610 org-refile-allow-creating-parent-nodes
10611 goto))))))
10612 (setq file (nth 1 it)
10613 re (nth 2 it)
10614 pos (nth 3 it))
10615 (if (and (not goto)
10617 (equal (buffer-file-name) file)
10618 (if regionp
10619 (and (>= pos region-start)
10620 (<= pos region-end))
10621 (and (>= pos (point))
10622 (< pos (save-excursion
10623 (org-end-of-subtree t t))))))
10624 (error "Cannot refile to position inside the tree or region"))
10626 (setq nbuf (or (find-buffer-visiting file)
10627 (find-file-noselect file)))
10628 (if goto
10629 (progn
10630 (org-pop-to-buffer-same-window nbuf)
10631 (goto-char pos)
10632 (org-show-context 'org-goto))
10633 (if regionp
10634 (progn
10635 (org-kill-new (buffer-substring region-start region-end))
10636 (org-save-markers-in-region region-start region-end))
10637 (org-copy-subtree 1 nil t))
10638 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10639 (find-file-noselect file)))
10640 (setq reversed (org-notes-order-reversed-p))
10641 (save-excursion
10642 (save-restriction
10643 (widen)
10644 (if pos
10645 (progn
10646 (goto-char pos)
10647 (looking-at org-outline-regexp)
10648 (setq level (org-get-valid-level (funcall outline-level) 1))
10649 (goto-char
10650 (if reversed
10651 (or (outline-next-heading) (point-max))
10652 (or (save-excursion (org-get-next-sibling))
10653 (org-end-of-subtree t t)
10654 (point-max)))))
10655 (setq level 1)
10656 (if (not reversed)
10657 (goto-char (point-max))
10658 (goto-char (point-min))
10659 (or (outline-next-heading) (goto-char (point-max)))))
10660 (if (not (bolp)) (newline))
10661 (org-paste-subtree level)
10662 (when org-log-refile
10663 (org-add-log-setup 'refile nil nil 'findpos
10664 org-log-refile)
10665 (unless (eq org-log-refile 'note)
10666 (save-excursion (org-add-log-note))))
10667 (and org-auto-align-tags (org-set-tags nil t))
10668 (bookmark-set "org-refile-last-stored")
10669 ;; If we are refiling for capture, make sure that the
10670 ;; last-capture pointers point here
10671 (when (org-bound-and-true-p org-refile-for-capture)
10672 (bookmark-set "org-capture-last-stored-marker")
10673 (move-marker org-capture-last-stored-marker (point)))
10674 (if (fboundp 'deactivate-mark) (deactivate-mark))
10675 (run-hooks 'org-after-refile-insert-hook))))
10676 (if regionp
10677 (delete-region (point) (+ (point) region-length))
10678 (org-cut-subtree))
10679 (when (featurep 'org-inlinetask)
10680 (org-inlinetask-remove-END-maybe))
10681 (setq org-markers-to-move nil)
10682 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10684 (defun org-refile-goto-last-stored ()
10685 "Go to the location where the last refile was stored."
10686 (interactive)
10687 (bookmark-jump "org-refile-last-stored")
10688 (message "This is the location of the last refile"))
10690 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10691 no-exclude)
10692 "Prompt the user for a refile location, using PROMPT.
10693 PROMPT should not be suffixed with a colon and a space, because
10694 this function appends the default value from
10695 `org-refile-history' automatically, if that is not empty.
10696 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10697 this is used for the GOTO interface."
10698 (let ((org-refile-targets org-refile-targets)
10699 (org-refile-use-outline-path org-refile-use-outline-path)
10700 excluded-entries)
10701 (when (and (eq major-mode 'org-mode)
10702 (not org-refile-use-cache)
10703 (not no-exclude))
10704 (org-map-tree
10705 (lambda()
10706 (setq excluded-entries
10707 (append excluded-entries (list (org-get-heading t t)))))))
10708 (setq org-refile-target-table
10709 (org-refile-get-targets default-buffer excluded-entries)))
10710 (unless org-refile-target-table
10711 (error "No refile targets"))
10712 (let* ((prompt (concat prompt
10713 (and (car org-refile-history)
10714 (concat " (default " (car org-refile-history) ")"))
10715 ": "))
10716 (cbuf (current-buffer))
10717 (partial-completion-mode nil)
10718 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10719 (cfunc (if (and org-refile-use-outline-path
10720 org-outline-path-complete-in-steps)
10721 'org-olpath-completing-read
10722 'org-icompleting-read))
10723 (extra (if org-refile-use-outline-path "/" ""))
10724 (filename (and cfn (expand-file-name cfn)))
10725 (tbl (mapcar
10726 (lambda (x)
10727 (if (and (not (member org-refile-use-outline-path
10728 '(file full-file-path)))
10729 (not (equal filename (nth 1 x))))
10730 (cons (concat (car x) extra " ("
10731 (file-name-nondirectory (nth 1 x)) ")")
10732 (cdr x))
10733 (cons (concat (car x) extra) (cdr x))))
10734 org-refile-target-table))
10735 (completion-ignore-case t)
10736 pa answ parent-target child parent old-hist)
10737 (setq old-hist org-refile-history)
10738 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10739 nil 'org-refile-history (car org-refile-history)))
10740 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10741 (org-refile-check-position pa)
10742 (if pa
10743 (progn
10744 (when (or (not org-refile-history)
10745 (not (eq old-hist org-refile-history))
10746 (not (equal (car pa) (car org-refile-history))))
10747 (setq org-refile-history
10748 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10749 org-refile-history
10750 (cdr org-refile-history))))
10751 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10752 (pop org-refile-history)))
10754 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10755 (progn
10756 (setq parent (match-string 1 answ)
10757 child (match-string 2 answ))
10758 (setq parent-target (or (assoc parent tbl)
10759 (assoc (concat parent "/") tbl)))
10760 (when (and parent-target
10761 (or (eq new-nodes t)
10762 (and (eq new-nodes 'confirm)
10763 (y-or-n-p (format "Create new node \"%s\"? "
10764 child)))))
10765 (org-refile-new-child parent-target child)))
10766 (error "Invalid target location")))))
10768 (defun org-refile-check-position (refile-pointer)
10769 "Check if the refile pointer matches the readline to which it points."
10770 (let* ((file (nth 1 refile-pointer))
10771 (re (nth 2 refile-pointer))
10772 (pos (nth 3 refile-pointer))
10773 buffer)
10774 (when (org-string-nw-p re)
10775 (setq buffer (if (markerp pos)
10776 (marker-buffer pos)
10777 (or (find-buffer-visiting file)
10778 (find-file-noselect file))))
10779 (with-current-buffer buffer
10780 (save-excursion
10781 (save-restriction
10782 (widen)
10783 (goto-char pos)
10784 (beginning-of-line 1)
10785 (unless (org-looking-at-p re)
10786 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
10788 (defun org-refile-new-child (parent-target child)
10789 "Use refile target PARENT-TARGET to add new CHILD below it."
10790 (unless parent-target
10791 (error "Cannot find parent for new node"))
10792 (let ((file (nth 1 parent-target))
10793 (pos (nth 3 parent-target))
10794 level)
10795 (with-current-buffer (or (find-buffer-visiting file)
10796 (find-file-noselect file))
10797 (save-excursion
10798 (save-restriction
10799 (widen)
10800 (if pos
10801 (goto-char pos)
10802 (goto-char (point-max))
10803 (if (not (bolp)) (newline)))
10804 (when (looking-at org-outline-regexp)
10805 (setq level (funcall outline-level))
10806 (org-end-of-subtree t t))
10807 (org-back-over-empty-lines)
10808 (insert "\n" (make-string
10809 (if pos (org-get-valid-level level 1) 1) ?*)
10810 " " child "\n")
10811 (beginning-of-line 0)
10812 (list (concat (car parent-target) "/" child) file "" (point)))))))
10814 (defun org-olpath-completing-read (prompt collection &rest args)
10815 "Read an outline path like a file name."
10816 (let ((thetable collection)
10817 (org-completion-use-ido nil) ; does not work with ido.
10818 (org-completion-use-iswitchb nil)) ; or iswitchb
10819 (apply
10820 'org-icompleting-read prompt
10821 (lambda (string predicate &optional flag)
10822 (let (rtn r f (l (length string)))
10823 (cond
10824 ((eq flag nil)
10825 ;; try completion
10826 (try-completion string thetable))
10827 ((eq flag t)
10828 ;; all-completions
10829 (setq rtn (all-completions string thetable predicate))
10830 (mapcar
10831 (lambda (x)
10832 (setq r (substring x l))
10833 (if (string-match " ([^)]*)$" x)
10834 (setq f (match-string 0 x))
10835 (setq f ""))
10836 (if (string-match "/" r)
10837 (concat string (substring r 0 (match-end 0)) f)
10839 rtn))
10840 ((eq flag 'lambda)
10841 ;; exact match?
10842 (assoc string thetable)))
10844 args)))
10846 ;;;; Dynamic blocks
10848 (defun org-find-dblock (name)
10849 "Find the first dynamic block with name NAME in the buffer.
10850 If not found, stay at current position and return nil."
10851 (let (pos)
10852 (save-excursion
10853 (goto-char (point-min))
10854 (setq pos (and (re-search-forward (concat "^[ \t]*#\\+BEGIN:[ \t]+" name "\\>")
10855 nil t)
10856 (match-beginning 0))))
10857 (if pos (goto-char pos))
10858 pos))
10860 (defconst org-dblock-start-re
10861 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10862 "Matches the start line of a dynamic block, with parameters.")
10864 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
10865 "Matches the end of a dynamic block.")
10867 (defun org-create-dblock (plist)
10868 "Create a dynamic block section, with parameters taken from PLIST.
10869 PLIST must contain a :name entry which is used as name of the block."
10870 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
10871 (end-of-line 1)
10872 (newline))
10873 (let ((col (current-column))
10874 (name (plist-get plist :name)))
10875 (insert "#+BEGIN: " name)
10876 (while plist
10877 (if (eq (car plist) :name)
10878 (setq plist (cddr plist))
10879 (insert " " (prin1-to-string (pop plist)))))
10880 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
10881 (beginning-of-line -2)))
10883 (defun org-prepare-dblock ()
10884 "Prepare dynamic block for refresh.
10885 This empties the block, puts the cursor at the insert position and returns
10886 the property list including an extra property :name with the block name."
10887 (unless (looking-at org-dblock-start-re)
10888 (error "Not at a dynamic block"))
10889 (let* ((begdel (1+ (match-end 0)))
10890 (name (org-no-properties (match-string 1)))
10891 (params (append (list :name name)
10892 (read (concat "(" (match-string 3) ")")))))
10893 (save-excursion
10894 (beginning-of-line 1)
10895 (skip-chars-forward " \t")
10896 (setq params (plist-put params :indentation-column (current-column))))
10897 (unless (re-search-forward org-dblock-end-re nil t)
10898 (error "Dynamic block not terminated"))
10899 (setq params
10900 (append params
10901 (list :content (buffer-substring
10902 begdel (match-beginning 0)))))
10903 (delete-region begdel (match-beginning 0))
10904 (goto-char begdel)
10905 (open-line 1)
10906 params))
10908 (defun org-map-dblocks (&optional command)
10909 "Apply COMMAND to all dynamic blocks in the current buffer.
10910 If COMMAND is not given, use `org-update-dblock'."
10911 (let ((cmd (or command 'org-update-dblock)))
10912 (save-excursion
10913 (goto-char (point-min))
10914 (while (re-search-forward org-dblock-start-re nil t)
10915 (goto-char (match-beginning 0))
10916 (save-excursion
10917 (condition-case nil
10918 (funcall cmd)
10919 (error (message "Error during update of dynamic block"))))
10920 (unless (re-search-forward org-dblock-end-re nil t)
10921 (error "Dynamic block not terminated"))))))
10923 (defun org-dblock-update (&optional arg)
10924 "User command for updating dynamic blocks.
10925 Update the dynamic block at point. With prefix ARG, update all dynamic
10926 blocks in the buffer."
10927 (interactive "P")
10928 (if arg
10929 (org-update-all-dblocks)
10930 (or (looking-at org-dblock-start-re)
10931 (org-beginning-of-dblock))
10932 (org-update-dblock)))
10934 (defun org-update-dblock ()
10935 "Update the dynamic block at point.
10936 This means to empty the block, parse for parameters and then call
10937 the correct writing function."
10938 (interactive)
10939 (save-window-excursion
10940 (let* ((pos (point))
10941 (line (org-current-line))
10942 (params (org-prepare-dblock))
10943 (name (plist-get params :name))
10944 (indent (plist-get params :indentation-column))
10945 (cmd (intern (concat "org-dblock-write:" name))))
10946 (message "Updating dynamic block `%s' at line %d..." name line)
10947 (funcall cmd params)
10948 (message "Updating dynamic block `%s' at line %d...done" name line)
10949 (goto-char pos)
10950 (when (and indent (> indent 0))
10951 (setq indent (make-string indent ?\ ))
10952 (save-excursion
10953 (org-beginning-of-dblock)
10954 (forward-line 1)
10955 (while (not (looking-at org-dblock-end-re))
10956 (insert indent)
10957 (beginning-of-line 2))
10958 (when (looking-at org-dblock-end-re)
10959 (and (looking-at "[ \t]+")
10960 (replace-match ""))
10961 (insert indent)))))))
10963 (defun org-beginning-of-dblock ()
10964 "Find the beginning of the dynamic block at point.
10965 Error if there is no such block at point."
10966 (let ((pos (point))
10967 beg)
10968 (end-of-line 1)
10969 (if (and (re-search-backward org-dblock-start-re nil t)
10970 (setq beg (match-beginning 0))
10971 (re-search-forward org-dblock-end-re nil t)
10972 (> (match-end 0) pos))
10973 (goto-char beg)
10974 (goto-char pos)
10975 (error "Not in a dynamic block"))))
10977 (defun org-update-all-dblocks ()
10978 "Update all dynamic blocks in the buffer.
10979 This function can be used in a hook."
10980 (interactive)
10981 (when (eq major-mode 'org-mode)
10982 (org-map-dblocks 'org-update-dblock)))
10985 ;;;; Completion
10987 (defconst org-additional-option-like-keywords
10988 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
10989 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
10990 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
10991 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
10992 "BEGIN:" "END:"
10993 "ORGTBL" "TBLFM:" "TBLNAME:"
10994 "BEGIN_EXAMPLE" "END_EXAMPLE"
10995 "BEGIN_QUOTE" "END_QUOTE"
10996 "BEGIN_VERSE" "END_VERSE"
10997 "BEGIN_CENTER" "END_CENTER"
10998 "BEGIN_SRC" "END_SRC"
10999 "BEGIN_RESULT" "END_RESULT"
11000 "SOURCE:" "SRCNAME:" "FUNCTION:"
11001 "RESULTS:" "DATA:"
11002 "HEADER:" "HEADERS:"
11003 "BABEL:"
11004 "CATEGORY:" "COLUMNS:" "PROPERTY:"
11005 "CAPTION:" "LABEL:"
11006 "SETUPFILE:"
11007 "INCLUDE:"
11008 "BIND:"
11009 "MACRO:"))
11011 (defcustom org-structure-template-alist
11013 ("s" "#+begin_src ?\n\n#+end_src"
11014 "<src lang=\"?\">\n\n</src>")
11015 ("e" "#+begin_example\n?\n#+end_example"
11016 "<example>\n?\n</example>")
11017 ("q" "#+begin_quote\n?\n#+end_quote"
11018 "<quote>\n?\n</quote>")
11019 ("v" "#+begin_verse\n?\n#+end_verse"
11020 "<verse>\n?\n/verse>")
11021 ("c" "#+begin_center\n?\n#+end_center"
11022 "<center>\n?\n/center>")
11023 ("l" "#+begin_latex\n?\n#+end_latex"
11024 "<literal style=\"latex\">\n?\n</literal>")
11025 ("L" "#+latex: "
11026 "<literal style=\"latex\">?</literal>")
11027 ("h" "#+begin_html\n?\n#+end_html"
11028 "<literal style=\"html\">\n?\n</literal>")
11029 ("H" "#+html: "
11030 "<literal style=\"html\">?</literal>")
11031 ("a" "#+begin_ascii\n?\n#+end_ascii")
11032 ("A" "#+ascii: ")
11033 ("i" "#+index: ?"
11034 "#+index: ?")
11035 ("I" "#+include %file ?"
11036 "<include file=%file markup=\"?\">")
11038 "Structure completion elements.
11039 This is a list of abbreviation keys and values. The value gets inserted
11040 if you type `<' followed by the key and then press the completion key,
11041 usually `M-TAB'. %file will be replaced by a file name after prompting
11042 for the file using completion. The cursor will be placed at the position
11043 of the `?` in the template.
11044 There are two templates for each key, the first uses the original Org syntax,
11045 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11046 the default when the /org-mtags.el/ module has been loaded. See also the
11047 variable `org-mtags-prefer-muse-templates'.
11048 This is an experimental feature, it is undecided if it is going to stay in."
11049 :group 'org-completion
11050 :type '(repeat
11051 (string :tag "Key")
11052 (string :tag "Template")
11053 (string :tag "Muse Template")))
11055 (defun org-try-structure-completion ()
11056 "Try to complete a structure template before point.
11057 This looks for strings like \"<e\" on an otherwise empty line and
11058 expands them."
11059 (let ((l (buffer-substring (point-at-bol) (point)))
11061 (when (and (looking-at "[ \t]*$")
11062 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11063 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11064 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11065 (match-beginning 1)) a)
11066 t)))
11068 (defun org-complete-expand-structure-template (start cell)
11069 "Expand a structure template."
11070 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11071 (rpl (nth (if musep 2 1) cell))
11072 (ind ""))
11073 (delete-region start (point))
11074 (when (string-match "\\`#\\+" rpl)
11075 (cond
11076 ((bolp))
11077 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11078 (setq ind (buffer-substring (point-at-bol) (point))))
11079 (t (newline))))
11080 (setq start (point))
11081 (if (string-match "%file" rpl)
11082 (setq rpl (replace-match
11083 (concat
11084 "\""
11085 (save-match-data
11086 (abbreviate-file-name (read-file-name "Include file: ")))
11087 "\"")
11088 t t rpl)))
11089 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11090 (concat "\n" ind)))
11091 (insert rpl)
11092 (if (re-search-backward "\\?" start t) (delete-char 1))))
11094 ;;;; TODO, DEADLINE, Comments
11096 (defun org-toggle-comment ()
11097 "Change the COMMENT state of an entry."
11098 (interactive)
11099 (save-excursion
11100 (org-back-to-heading)
11101 (let (case-fold-search)
11102 (cond
11103 ((looking-at (format org-heading-keyword-regexp-format
11104 org-comment-string))
11105 (goto-char (match-end 1))
11106 (looking-at (concat " +" org-comment-string))
11107 (replace-match "" t t)
11108 (when (eolp) (insert " ")))
11109 ((looking-at org-outline-regexp)
11110 (goto-char (match-end 0))
11111 (insert org-comment-string " "))))))
11113 (defvar org-last-todo-state-is-todo nil
11114 "This is non-nil when the last TODO state change led to a TODO state.
11115 If the last change removed the TODO tag or switched to DONE, then
11116 this is nil.")
11118 (defvar org-setting-tags nil) ; dynamically skipped
11120 (defvar org-todo-setup-filter-hook nil
11121 "Hook for functions that pre-filter todo specs.
11122 Each function takes a todo spec and returns either nil or the spec
11123 transformed into canonical form." )
11125 (defvar org-todo-get-default-hook nil
11126 "Hook for functions that get a default item for todo.
11127 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11128 nil or a string to be used for the todo mark." )
11130 (defvar org-agenda-headline-snapshot-before-repeat)
11132 (defun org-current-effective-time ()
11133 "Return current time adjusted for `org-extend-today-until' variable"
11134 (let* ((ct (org-current-time))
11135 (dct (decode-time ct))
11136 (ct1
11137 (if (and org-use-effective-time
11138 (< (nth 2 dct) org-extend-today-until))
11139 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11140 ct)))
11141 ct1))
11143 (defun org-todo-yesterday (&optional arg)
11144 "Like `org-todo' but the time of change will be 23:59 of yesterday"
11145 (interactive "P")
11146 (let* ((hour (third (decode-time
11147 (org-current-time))))
11148 (org-extend-today-until (1+ hour)))
11149 (org-todo arg)))
11151 (defun org-todo (&optional arg)
11152 "Change the TODO state of an item.
11153 The state of an item is given by a keyword at the start of the heading,
11154 like
11155 *** TODO Write paper
11156 *** DONE Call mom
11158 The different keywords are specified in the variable `org-todo-keywords'.
11159 By default the available states are \"TODO\" and \"DONE\".
11160 So for this example: when the item starts with TODO, it is changed to DONE.
11161 When it starts with DONE, the DONE is removed. And when neither TODO nor
11162 DONE are present, add TODO at the beginning of the heading.
11164 With \\[universal-argument] prefix arg, use completion to determine the new \
11165 state.
11166 With numeric prefix arg, switch to that state.
11167 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11168 keywords (nextset).
11169 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11171 For calling through lisp, arg is also interpreted in the following way:
11172 'none -> empty state
11173 \"\"(empty string) -> switch to empty state
11174 'done -> switch to DONE
11175 'nextset -> switch to the next set of keywords
11176 'previousset -> switch to the previous set of keywords
11177 \"WAITING\" -> switch to the specified keyword, but only if it
11178 really is a member of `org-todo-keywords'."
11179 (interactive "P")
11180 (if (equal arg '(16)) (setq arg 'nextset))
11181 (let ((org-blocker-hook org-blocker-hook)
11182 (case-fold-search nil))
11183 (when (equal arg '(64))
11184 (setq arg nil org-blocker-hook nil))
11185 (when (and org-blocker-hook
11186 (or org-inhibit-blocking
11187 (org-entry-get nil "NOBLOCKING")))
11188 (setq org-blocker-hook nil))
11189 (save-excursion
11190 (catch 'exit
11191 (org-back-to-heading t)
11192 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11193 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11194 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11195 (let* ((match-data (match-data))
11196 (startpos (point-at-bol))
11197 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11198 (org-log-done org-log-done)
11199 (org-log-repeat org-log-repeat)
11200 (org-todo-log-states org-todo-log-states)
11201 (this (match-string 1))
11202 (hl-pos (match-beginning 0))
11203 (head (org-get-todo-sequence-head this))
11204 (ass (assoc head org-todo-kwd-alist))
11205 (interpret (nth 1 ass))
11206 (done-word (nth 3 ass))
11207 (final-done-word (nth 4 ass))
11208 (last-state (or this ""))
11209 (completion-ignore-case t)
11210 (member (member this org-todo-keywords-1))
11211 (tail (cdr member))
11212 (state (cond
11213 ((and org-todo-key-trigger
11214 (or (and (equal arg '(4))
11215 (eq org-use-fast-todo-selection 'prefix))
11216 (and (not arg) org-use-fast-todo-selection
11217 (not (eq org-use-fast-todo-selection
11218 'prefix)))))
11219 ;; Use fast selection
11220 (org-fast-todo-selection))
11221 ((and (equal arg '(4))
11222 (or (not org-use-fast-todo-selection)
11223 (not org-todo-key-trigger)))
11224 ;; Read a state with completion
11225 (org-icompleting-read
11226 "State: " (mapcar (lambda(x) (list x))
11227 org-todo-keywords-1)
11228 nil t))
11229 ((eq arg 'right)
11230 (if this
11231 (if tail (car tail) nil)
11232 (car org-todo-keywords-1)))
11233 ((eq arg 'left)
11234 (if (equal member org-todo-keywords-1)
11236 (if this
11237 (nth (- (length org-todo-keywords-1)
11238 (length tail) 2)
11239 org-todo-keywords-1)
11240 (org-last org-todo-keywords-1))))
11241 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11242 (setq arg nil))) ; hack to fall back to cycling
11243 (arg
11244 ;; user or caller requests a specific state
11245 (cond
11246 ((equal arg "") nil)
11247 ((eq arg 'none) nil)
11248 ((eq arg 'done) (or done-word (car org-done-keywords)))
11249 ((eq arg 'nextset)
11250 (or (car (cdr (member head org-todo-heads)))
11251 (car org-todo-heads)))
11252 ((eq arg 'previousset)
11253 (let ((org-todo-heads (reverse org-todo-heads)))
11254 (or (car (cdr (member head org-todo-heads)))
11255 (car org-todo-heads))))
11256 ((car (member arg org-todo-keywords-1)))
11257 ((stringp arg)
11258 (error "State `%s' not valid in this file" arg))
11259 ((nth (1- (prefix-numeric-value arg))
11260 org-todo-keywords-1))))
11261 ((null member) (or head (car org-todo-keywords-1)))
11262 ((equal this final-done-word) nil) ;; -> make empty
11263 ((null tail) nil) ;; -> first entry
11264 ((memq interpret '(type priority))
11265 (if (eq this-command last-command)
11266 (car tail)
11267 (if (> (length tail) 0)
11268 (or done-word (car org-done-keywords))
11269 nil)))
11271 (car tail))))
11272 (state (or
11273 (run-hook-with-args-until-success
11274 'org-todo-get-default-hook state last-state)
11275 state))
11276 (next (if state (concat " " state " ") " "))
11277 (change-plist (list :type 'todo-state-change :from this :to state
11278 :position startpos))
11279 dolog now-done-p)
11280 (when org-blocker-hook
11281 (setq org-last-todo-state-is-todo
11282 (not (member this org-done-keywords)))
11283 (unless (save-excursion
11284 (save-match-data
11285 (org-with-wide-buffer
11286 (run-hook-with-args-until-failure
11287 'org-blocker-hook change-plist))))
11288 (if (org-called-interactively-p 'interactive)
11289 (error "TODO state change from %s to %s blocked" this state)
11290 ;; fail silently
11291 (message "TODO state change from %s to %s blocked" this state)
11292 (throw 'exit nil))))
11293 (store-match-data match-data)
11294 (replace-match next t t)
11295 (unless (pos-visible-in-window-p hl-pos)
11296 (message "TODO state changed to %s" (org-trim next)))
11297 (unless head
11298 (setq head (org-get-todo-sequence-head state)
11299 ass (assoc head org-todo-kwd-alist)
11300 interpret (nth 1 ass)
11301 done-word (nth 3 ass)
11302 final-done-word (nth 4 ass)))
11303 (when (memq arg '(nextset previousset))
11304 (message "Keyword-Set %d/%d: %s"
11305 (- (length org-todo-sets) -1
11306 (length (memq (assoc state org-todo-sets) org-todo-sets)))
11307 (length org-todo-sets)
11308 (mapconcat 'identity (assoc state org-todo-sets) " ")))
11309 (setq org-last-todo-state-is-todo
11310 (not (member state org-done-keywords)))
11311 (setq now-done-p (and (member state org-done-keywords)
11312 (not (member this org-done-keywords))))
11313 (and logging (org-local-logging logging))
11314 (when (and (or org-todo-log-states org-log-done)
11315 (not (eq org-inhibit-logging t))
11316 (not (memq arg '(nextset previousset))))
11317 ;; we need to look at recording a time and note
11318 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
11319 (nth 2 (assoc this org-todo-log-states))))
11320 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11321 (setq dolog 'time))
11322 (when (and state
11323 (member state org-not-done-keywords)
11324 (not (member this org-not-done-keywords)))
11325 ;; This is now a todo state and was not one before
11326 ;; If there was a CLOSED time stamp, get rid of it.
11327 (org-add-planning-info nil nil 'closed))
11328 (when (and now-done-p org-log-done)
11329 ;; It is now done, and it was not done before
11330 (org-add-planning-info 'closed (org-current-effective-time))
11331 (if (and (not dolog) (eq 'note org-log-done))
11332 (org-add-log-setup 'done state this 'findpos 'note)))
11333 (when (and state dolog)
11334 ;; This is a non-nil state, and we need to log it
11335 (org-add-log-setup 'state state this 'findpos dolog)))
11336 ;; Fixup tag positioning
11337 (org-todo-trigger-tag-changes state)
11338 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11339 (when org-provide-todo-statistics
11340 (org-update-parent-todo-statistics))
11341 (run-hooks 'org-after-todo-state-change-hook)
11342 (if (and arg (not (member state org-done-keywords)))
11343 (setq head (org-get-todo-sequence-head state)))
11344 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11345 ;; Do we need to trigger a repeat?
11346 (when now-done-p
11347 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11348 ;; This is for the agenda, take a snapshot of the headline.
11349 (save-match-data
11350 (setq org-agenda-headline-snapshot-before-repeat
11351 (org-get-heading))))
11352 (org-auto-repeat-maybe state))
11353 ;; Fixup cursor location if close to the keyword
11354 (if (and (outline-on-heading-p)
11355 (not (bolp))
11356 (save-excursion (beginning-of-line 1)
11357 (looking-at org-todo-line-regexp))
11358 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11359 (progn
11360 (goto-char (or (match-end 2) (match-end 1)))
11361 (and (looking-at " ") (just-one-space))))
11362 (when org-trigger-hook
11363 (save-excursion
11364 (run-hook-with-args 'org-trigger-hook change-plist))))))))
11366 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11367 "Block turning an entry into a TODO, using the hierarchy.
11368 This checks whether the current task should be blocked from state
11369 changes. Such blocking occurs when:
11371 1. The task has children which are not all in a completed state.
11373 2. A task has a parent with the property :ORDERED:, and there
11374 are siblings prior to the current task with incomplete
11375 status.
11377 3. The parent of the task is blocked because it has siblings that should
11378 be done first, or is child of a block grandparent TODO entry."
11380 (if (not org-enforce-todo-dependencies)
11381 t ; if locally turned off don't block
11382 (catch 'dont-block
11383 ;; If this is not a todo state change, or if this entry is already DONE,
11384 ;; do not block
11385 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11386 (member (plist-get change-plist :from)
11387 (cons 'done org-done-keywords))
11388 (member (plist-get change-plist :to)
11389 (cons 'todo org-not-done-keywords))
11390 (not (plist-get change-plist :to)))
11391 (throw 'dont-block t))
11392 ;; If this task has children, and any are undone, it's blocked
11393 (save-excursion
11394 (org-back-to-heading t)
11395 (let ((this-level (funcall outline-level)))
11396 (outline-next-heading)
11397 (let ((child-level (funcall outline-level)))
11398 (while (and (not (eobp))
11399 (> child-level this-level))
11400 ;; this todo has children, check whether they are all
11401 ;; completed
11402 (if (and (not (org-entry-is-done-p))
11403 (org-entry-is-todo-p))
11404 (throw 'dont-block nil))
11405 (outline-next-heading)
11406 (setq child-level (funcall outline-level))))))
11407 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11408 ;; any previous siblings are undone, it's blocked
11409 (save-excursion
11410 (org-back-to-heading t)
11411 (let* ((pos (point))
11412 (parent-pos (and (org-up-heading-safe) (point))))
11413 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11414 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11415 (forward-line 1)
11416 (re-search-forward org-not-done-heading-regexp pos t))
11417 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11418 ;; Search further up the hierarchy, to see if an anchestor is blocked
11419 (while t
11420 (goto-char parent-pos)
11421 (if (not (looking-at org-not-done-heading-regexp))
11422 (throw 'dont-block t)) ; do not block, parent is not a TODO
11423 (setq pos (point))
11424 (setq parent-pos (and (org-up-heading-safe) (point)))
11425 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11426 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11427 (forward-line 1)
11428 (re-search-forward org-not-done-heading-regexp pos t))
11429 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11431 (defcustom org-track-ordered-property-with-tag nil
11432 "Should the ORDERED property also be shown as a tag?
11433 The ORDERED property decides if an entry should require subtasks to be
11434 completed in sequence. Since a property is not very visible, setting
11435 this option means that toggling the ORDERED property with the command
11436 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11437 not relevant for the behavior, but it makes things more visible.
11439 Note that toggling the tag with tags commands will not change the property
11440 and therefore not influence behavior!
11442 This can be t, meaning the tag ORDERED should be used, It can also be a
11443 string to select a different tag for this task."
11444 :group 'org-todo
11445 :type '(choice
11446 (const :tag "No tracking" nil)
11447 (const :tag "Track with ORDERED tag" t)
11448 (string :tag "Use other tag")))
11450 (defun org-toggle-ordered-property ()
11451 "Toggle the ORDERED property of the current entry.
11452 For better visibility, you can track the value of this property with a tag.
11453 See variable `org-track-ordered-property-with-tag'."
11454 (interactive)
11455 (let* ((t1 org-track-ordered-property-with-tag)
11456 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11457 (save-excursion
11458 (org-back-to-heading)
11459 (if (org-entry-get nil "ORDERED")
11460 (progn
11461 (org-delete-property "ORDERED")
11462 (and tag (org-toggle-tag tag 'off))
11463 (message "Subtasks can be completed in arbitrary order"))
11464 (org-entry-put nil "ORDERED" "t")
11465 (and tag (org-toggle-tag tag 'on))
11466 (message "Subtasks must be completed in sequence")))))
11468 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11469 (defun org-block-todo-from-checkboxes (change-plist)
11470 "Block turning an entry into a TODO, using checkboxes.
11471 This checks whether the current task should be blocked from state
11472 changes because there are unchecked boxes in this entry."
11473 (if (not org-enforce-todo-checkbox-dependencies)
11474 t ; if locally turned off don't block
11475 (catch 'dont-block
11476 ;; If this is not a todo state change, or if this entry is already DONE,
11477 ;; do not block
11478 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11479 (member (plist-get change-plist :from)
11480 (cons 'done org-done-keywords))
11481 (member (plist-get change-plist :to)
11482 (cons 'todo org-not-done-keywords))
11483 (not (plist-get change-plist :to)))
11484 (throw 'dont-block t))
11485 ;; If this task has checkboxes that are not checked, it's blocked
11486 (save-excursion
11487 (org-back-to-heading t)
11488 (let ((beg (point)) end)
11489 (outline-next-heading)
11490 (setq end (point))
11491 (goto-char beg)
11492 (if (org-list-search-forward
11493 (concat (org-item-beginning-re)
11494 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11495 "\\[[- ]\\]")
11496 end t)
11497 (progn
11498 (if (boundp 'org-blocked-by-checkboxes)
11499 (setq org-blocked-by-checkboxes t))
11500 (throw 'dont-block nil)))))
11501 t))) ; do not block
11503 (defun org-entry-blocked-p ()
11504 "Is the current entry blocked?"
11505 (if (org-entry-get nil "NOBLOCKING")
11506 nil ;; Never block this entry
11507 (not
11508 (run-hook-with-args-until-failure
11509 'org-blocker-hook
11510 (list :type 'todo-state-change
11511 :position (point)
11512 :from 'todo
11513 :to 'done)))))
11515 (defun org-update-statistics-cookies (all)
11516 "Update the statistics cookie, either from TODO or from checkboxes.
11517 This should be called with the cursor in a line with a statistics cookie."
11518 (interactive "P")
11519 (if all
11520 (progn
11521 (org-update-checkbox-count 'all)
11522 (org-map-entries 'org-update-parent-todo-statistics))
11523 (if (not (org-on-heading-p))
11524 (org-update-checkbox-count)
11525 (let ((pos (move-marker (make-marker) (point)))
11526 end l1 l2)
11527 (ignore-errors (org-back-to-heading t))
11528 (if (not (org-on-heading-p))
11529 (org-update-checkbox-count)
11530 (setq l1 (org-outline-level))
11531 (setq end (save-excursion
11532 (outline-next-heading)
11533 (if (org-on-heading-p) (setq l2 (org-outline-level)))
11534 (point)))
11535 (if (and (save-excursion
11536 (re-search-forward
11537 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11538 (not (save-excursion (re-search-forward
11539 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11540 (org-update-checkbox-count)
11541 (if (and l2 (> l2 l1))
11542 (progn
11543 (goto-char end)
11544 (org-update-parent-todo-statistics))
11545 (goto-char pos)
11546 (beginning-of-line 1)
11547 (while (re-search-forward
11548 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11549 (point-at-eol) t)
11550 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11551 (goto-char pos)
11552 (move-marker pos nil)))))
11554 (defvar org-entry-property-inherited-from) ;; defined below
11555 (defun org-update-parent-todo-statistics ()
11556 "Update any statistics cookie in the parent of the current headline.
11557 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11558 the entire subtree and this will travel up the hierarchy and update
11559 statistics everywhere."
11560 (let* ((prop (save-excursion (org-up-heading-safe)
11561 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11562 (recursive (or (not org-hierarchical-todo-statistics)
11563 (and prop (string-match "\\<recursive\\>" prop))))
11564 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11566 (first t)
11567 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11568 level ltoggle l1 new ndel
11569 (cnt-all 0) (cnt-done 0) is-percent kwd
11570 checkbox-beg ov ovs ove cookie-present)
11571 (catch 'exit
11572 (save-excursion
11573 (beginning-of-line 1)
11574 (setq ltoggle (funcall outline-level))
11575 ;; Three situations are to consider:
11577 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11578 ;; to the top-level ancestor on the headline;
11580 ;; 2. If parent has "recursive" property, repeat up to the
11581 ;; headline setting that property, taking inheritance into
11582 ;; account;
11584 ;; 3. Else, move up to direct parent and proceed only once.
11585 (while (and (setq level (org-up-heading-safe))
11586 (or recursive first)
11587 (>= (point) lim))
11588 (setq first nil cookie-present nil)
11589 (unless (and level
11590 (not (string-match
11591 "\\<checkbox\\>"
11592 (downcase (or (org-entry-get nil "COOKIE_DATA")
11593 "")))))
11594 (throw 'exit nil))
11595 (while (re-search-forward box-re (point-at-eol) t)
11596 (setq cnt-all 0 cnt-done 0 cookie-present t)
11597 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11598 (save-match-data
11599 (unless (outline-next-heading) (throw 'exit nil))
11600 (while (and (looking-at org-complex-heading-regexp)
11601 (> (setq l1 (length (match-string 1))) level))
11602 (setq kwd (and (or recursive (= l1 ltoggle))
11603 (match-string 2)))
11604 (if (or (eq org-provide-todo-statistics 'all-headlines)
11605 (and (listp org-provide-todo-statistics)
11606 (or (member kwd org-provide-todo-statistics)
11607 (member kwd org-done-keywords))))
11608 (setq cnt-all (1+ cnt-all))
11609 (if (eq org-provide-todo-statistics t)
11610 (and kwd (setq cnt-all (1+ cnt-all)))))
11611 (and (member kwd org-done-keywords)
11612 (setq cnt-done (1+ cnt-done)))
11613 (outline-next-heading)))
11614 (setq new
11615 (if is-percent
11616 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11617 (format "[%d/%d]" cnt-done cnt-all))
11618 ndel (- (match-end 0) checkbox-beg))
11619 ;; handle overlays when updating cookie from column view
11620 (when (setq ov (car (overlays-at checkbox-beg)))
11621 (setq ovs (overlay-start ov) ove (overlay-end ov))
11622 (delete-overlay ov))
11623 (goto-char checkbox-beg)
11624 (insert new)
11625 (delete-region (point) (+ (point) ndel))
11626 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11627 (when ov (move-overlay ov ovs ove)))
11628 (when cookie-present
11629 (run-hook-with-args 'org-after-todo-statistics-hook
11630 cnt-done (- cnt-all cnt-done))))))
11631 (run-hooks 'org-todo-statistics-hook)))
11633 (defvar org-after-todo-statistics-hook nil
11634 "Hook that is called after a TODO statistics cookie has been updated.
11635 Each function is called with two arguments: the number of not-done entries
11636 and the number of done entries.
11638 For example, the following function, when added to this hook, will switch
11639 an entry to DONE when all children are done, and back to TODO when new
11640 entries are set to a TODO status. Note that this hook is only called
11641 when there is a statistics cookie in the headline!
11643 (defun org-summary-todo (n-done n-not-done)
11644 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11645 (let (org-log-done org-log-states) ; turn off logging
11646 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11649 (defvar org-todo-statistics-hook nil
11650 "Hook that is run whenever Org thinks TODO statistics should be updated.
11651 This hook runs even if there is no statistics cookie present, in which case
11652 `org-after-todo-statistics-hook' would not run.")
11654 (defun org-todo-trigger-tag-changes (state)
11655 "Apply the changes defined in `org-todo-state-tags-triggers'."
11656 (let ((l org-todo-state-tags-triggers)
11657 changes)
11658 (when (or (not state) (equal state ""))
11659 (setq changes (append changes (cdr (assoc "" l)))))
11660 (when (and (stringp state) (> (length state) 0))
11661 (setq changes (append changes (cdr (assoc state l)))))
11662 (when (member state org-not-done-keywords)
11663 (setq changes (append changes (cdr (assoc 'todo l)))))
11664 (when (member state org-done-keywords)
11665 (setq changes (append changes (cdr (assoc 'done l)))))
11666 (dolist (c changes)
11667 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11669 (defun org-local-logging (value)
11670 "Get logging settings from a property VALUE."
11671 (let* (words w a)
11672 ;; directly set the variables, they are already local.
11673 (setq org-log-done nil
11674 org-log-repeat nil
11675 org-todo-log-states nil)
11676 (setq words (org-split-string value))
11677 (while (setq w (pop words))
11678 (cond
11679 ((setq a (assoc w org-startup-options))
11680 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11681 (set (nth 1 a) (nth 2 a))))
11682 ((setq a (org-extract-log-state-settings w))
11683 (and (member (car a) org-todo-keywords-1)
11684 (push a org-todo-log-states)))))))
11686 (defun org-get-todo-sequence-head (kwd)
11687 "Return the head of the TODO sequence to which KWD belongs.
11688 If KWD is not set, check if there is a text property remembering the
11689 right sequence."
11690 (let (p)
11691 (cond
11692 ((not kwd)
11693 (or (get-text-property (point-at-bol) 'org-todo-head)
11694 (progn
11695 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11696 nil (point-at-eol)))
11697 (get-text-property p 'org-todo-head))))
11698 ((not (member kwd org-todo-keywords-1))
11699 (car org-todo-keywords-1))
11700 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11702 (defun org-fast-todo-selection ()
11703 "Fast TODO keyword selection with single keys.
11704 Returns the new TODO keyword, or nil if no state change should occur."
11705 (let* ((fulltable org-todo-key-alist)
11706 (done-keywords org-done-keywords) ;; needed for the faces.
11707 (maxlen (apply 'max (mapcar
11708 (lambda (x)
11709 (if (stringp (car x)) (string-width (car x)) 0))
11710 fulltable)))
11711 (expert nil)
11712 (fwidth (+ maxlen 3 1 3))
11713 (ncol (/ (- (window-width) 4) fwidth))
11714 tg cnt e c tbl
11715 groups ingroup)
11716 (save-excursion
11717 (save-window-excursion
11718 (if expert
11719 (set-buffer (get-buffer-create " *Org todo*"))
11720 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11721 (erase-buffer)
11722 (org-set-local 'org-done-keywords done-keywords)
11723 (setq tbl fulltable cnt 0)
11724 (while (setq e (pop tbl))
11725 (cond
11726 ((equal e '(:startgroup))
11727 (push '() groups) (setq ingroup t)
11728 (when (not (= cnt 0))
11729 (setq cnt 0)
11730 (insert "\n"))
11731 (insert "{ "))
11732 ((equal e '(:endgroup))
11733 (setq ingroup nil cnt 0)
11734 (insert "}\n"))
11735 ((equal e '(:newline))
11736 (when (not (= cnt 0))
11737 (setq cnt 0)
11738 (insert "\n")
11739 (setq e (car tbl))
11740 (while (equal (car tbl) '(:newline))
11741 (insert "\n")
11742 (setq tbl (cdr tbl)))))
11744 (setq tg (car e) c (cdr e))
11745 (if ingroup (push tg (car groups)))
11746 (setq tg (org-add-props tg nil 'face
11747 (org-get-todo-face tg)))
11748 (if (and (= cnt 0) (not ingroup)) (insert " "))
11749 (insert "[" c "] " tg (make-string
11750 (- fwidth 4 (length tg)) ?\ ))
11751 (when (= (setq cnt (1+ cnt)) ncol)
11752 (insert "\n")
11753 (if ingroup (insert " "))
11754 (setq cnt 0)))))
11755 (insert "\n")
11756 (goto-char (point-min))
11757 (if (not expert) (org-fit-window-to-buffer))
11758 (message "[a-z..]:Set [SPC]:clear")
11759 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11760 (cond
11761 ((or (= c ?\C-g)
11762 (and (= c ?q) (not (rassoc c fulltable))))
11763 (setq quit-flag t))
11764 ((= c ?\ ) nil)
11765 ((setq e (rassoc c fulltable) tg (car e))
11767 (t (setq quit-flag t)))))))
11769 (defun org-entry-is-todo-p ()
11770 (member (org-get-todo-state) org-not-done-keywords))
11772 (defun org-entry-is-done-p ()
11773 (member (org-get-todo-state) org-done-keywords))
11775 (defun org-get-todo-state ()
11776 (save-excursion
11777 (org-back-to-heading t)
11778 (and (looking-at org-todo-line-regexp)
11779 (match-end 2)
11780 (match-string 2))))
11782 (defun org-at-date-range-p (&optional inactive-ok)
11783 "Is the cursor inside a date range?"
11784 (interactive)
11785 (save-excursion
11786 (catch 'exit
11787 (let ((pos (point)))
11788 (skip-chars-backward "^[<\r\n")
11789 (skip-chars-backward "<[")
11790 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11791 (>= (match-end 0) pos)
11792 (throw 'exit t))
11793 (skip-chars-backward "^<[\r\n")
11794 (skip-chars-backward "<[")
11795 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11796 (>= (match-end 0) pos)
11797 (throw 'exit t)))
11798 nil)))
11800 (defun org-get-repeat (&optional tagline)
11801 "Check if there is a deadline/schedule with repeater in this entry."
11802 (save-match-data
11803 (save-excursion
11804 (org-back-to-heading t)
11805 (and (re-search-forward (if tagline
11806 (concat tagline "\\s-*" org-repeat-re)
11807 org-repeat-re)
11808 (org-entry-end-position) t)
11809 (match-string-no-properties 1)))))
11811 (defvar org-last-changed-timestamp)
11812 (defvar org-last-inserted-timestamp)
11813 (defvar org-log-post-message)
11814 (defvar org-log-note-purpose)
11815 (defvar org-log-note-how)
11816 (defvar org-log-note-extra)
11817 (defun org-auto-repeat-maybe (done-word)
11818 "Check if the current headline contains a repeated deadline/schedule.
11819 If yes, set TODO state back to what it was and change the base date
11820 of repeating deadline/scheduled time stamps to new date.
11821 This function is run automatically after each state change to a DONE state."
11822 ;; last-state is dynamically scoped into this function
11823 (let* ((repeat (org-get-repeat))
11824 (aa (assoc last-state org-todo-kwd-alist))
11825 (interpret (nth 1 aa))
11826 (head (nth 2 aa))
11827 (whata '(("d" . day) ("m" . month) ("y" . year)))
11828 (msg "Entry repeats: ")
11829 (org-log-done nil)
11830 (org-todo-log-states nil)
11831 re type n what ts time to-state)
11832 (when repeat
11833 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11834 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11835 org-todo-repeat-to-state))
11836 (unless (and to-state (member to-state org-todo-keywords-1))
11837 (setq to-state (if (eq interpret 'type) last-state head)))
11838 (org-todo to-state)
11839 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11840 (org-entry-put nil "LAST_REPEAT" (format-time-string
11841 (org-time-stamp-format t t))))
11842 (when org-log-repeat
11843 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11844 (memq 'org-add-log-note post-command-hook))
11845 ;; OK, we are already setup for some record
11846 (if (eq org-log-repeat 'note)
11847 ;; make sure we take a note, not only a time stamp
11848 (setq org-log-note-how 'note))
11849 ;; Set up for taking a record
11850 (org-add-log-setup 'state (or done-word (car org-done-keywords))
11851 last-state
11852 'findpos org-log-repeat)))
11853 (org-back-to-heading t)
11854 (org-add-planning-info nil nil 'closed)
11855 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11856 org-deadline-time-regexp "\\)\\|\\("
11857 org-ts-regexp "\\)"))
11858 (while (re-search-forward
11859 re (save-excursion (outline-next-heading) (point)) t)
11860 (setq type (if (match-end 1) org-scheduled-string
11861 (if (match-end 3) org-deadline-string "Plain:"))
11862 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
11863 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
11864 (setq n (string-to-number (match-string 2 ts))
11865 what (match-string 3 ts))
11866 (if (equal what "w") (setq n (* n 7) what "d"))
11867 ;; Preparation, see if we need to modify the start date for the change
11868 (when (match-end 1)
11869 (setq time (save-match-data (org-time-string-to-time ts)))
11870 (cond
11871 ((equal (match-string 1 ts) ".")
11872 ;; Shift starting date to today
11873 (org-timestamp-change
11874 (- (org-today) (time-to-days time))
11875 'day))
11876 ((equal (match-string 1 ts) "+")
11877 (let ((nshiftmax 10) (nshift 0))
11878 (while (or (= nshift 0)
11879 (<= (time-to-days time)
11880 (time-to-days (current-time))))
11881 (when (= (incf nshift) nshiftmax)
11882 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
11883 (error "Abort")))
11884 (org-timestamp-change n (cdr (assoc what whata)))
11885 (org-at-timestamp-p t)
11886 (setq ts (match-string 1))
11887 (setq time (save-match-data (org-time-string-to-time ts)))))
11888 (org-timestamp-change (- n) (cdr (assoc what whata)))
11889 ;; rematch, so that we have everything in place for the real shift
11890 (org-at-timestamp-p t)
11891 (setq ts (match-string 1))
11892 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
11893 (org-timestamp-change n (cdr (assoc what whata)))
11894 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
11895 (setq org-log-post-message msg)
11896 (message "%s" msg))))
11898 (defun org-show-todo-tree (arg)
11899 "Make a compact tree which shows all headlines marked with TODO.
11900 The tree will show the lines where the regexp matches, and all higher
11901 headlines above the match.
11902 With a \\[universal-argument] prefix, prompt for a regexp to match.
11903 With a numeric prefix N, construct a sparse tree for the Nth element
11904 of `org-todo-keywords-1'."
11905 (interactive "P")
11906 (let ((case-fold-search nil)
11907 (kwd-re
11908 (cond ((null arg) org-not-done-regexp)
11909 ((equal arg '(4))
11910 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
11911 (mapcar 'list org-todo-keywords-1))))
11912 (concat "\\("
11913 (mapconcat 'identity (org-split-string kwd "|") "\\|")
11914 "\\)\\>")))
11915 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
11916 (regexp-quote (nth (1- (prefix-numeric-value arg))
11917 org-todo-keywords-1)))
11918 (t (error "Invalid prefix argument: %s" arg)))))
11919 (message "%d TODO entries found"
11920 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
11922 (defun org-deadline (&optional remove time)
11923 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
11924 With argument REMOVE, remove any deadline from the item.
11925 With argument TIME, set the deadline at the corresponding date. TIME
11926 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
11927 (interactive "P")
11928 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11929 (let (org-loop-over-headlines-in-active-region)
11930 (org-map-entries
11931 `(org-deadline ',remove ,time) org-loop-over-headlines-in-active-region 'region (if (outline-invisible-p) (org-end-of-subtree nil t))))
11932 (let* ((old-date (org-entry-get nil "DEADLINE"))
11933 (repeater (and old-date
11934 (string-match
11935 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
11936 old-date)
11937 (match-string 1 old-date))))
11938 (if remove
11939 (progn
11940 (when (and old-date org-log-redeadline)
11941 (org-add-log-setup 'deldeadline nil old-date 'findpos
11942 org-log-redeadline))
11943 (org-remove-timestamp-with-keyword org-deadline-string)
11944 (message "Item no longer has a deadline."))
11945 (org-add-planning-info 'deadline time 'closed)
11946 (when (and old-date org-log-redeadline
11947 (not (equal old-date
11948 (substring org-last-inserted-timestamp 1 -1))))
11949 (org-add-log-setup 'redeadline nil old-date 'findpos
11950 org-log-redeadline))
11951 (when repeater
11952 (save-excursion
11953 (org-back-to-heading t)
11954 (when (re-search-forward (concat org-deadline-string " "
11955 org-last-inserted-timestamp)
11956 (save-excursion
11957 (outline-next-heading) (point)) t)
11958 (goto-char (1- (match-end 0)))
11959 (insert " " repeater)
11960 (setq org-last-inserted-timestamp
11961 (concat (substring org-last-inserted-timestamp 0 -1)
11962 " " repeater
11963 (substring org-last-inserted-timestamp -1))))))
11964 (message "Deadline on %s" org-last-inserted-timestamp)))))
11966 (defun org-schedule (&optional remove time)
11967 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
11968 With argument REMOVE, remove any scheduling date from the item.
11969 With argument TIME, scheduled at the corresponding date. TIME can
11970 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
11971 (interactive "P")
11972 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11973 (let (org-loop-over-headlines-in-active-region)
11974 (org-map-entries
11975 `(org-schedule ',remove ,time) org-loop-over-headlines-in-active-region 'region (if (outline-invisible-p) (org-end-of-subtree nil t))))
11976 (let* ((old-date (org-entry-get nil "SCHEDULED"))
11977 (repeater (and old-date
11978 (string-match
11979 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
11980 old-date)
11981 (match-string 1 old-date))))
11982 (if remove
11983 (progn
11984 (when (and old-date org-log-reschedule)
11985 (org-add-log-setup 'delschedule nil old-date 'findpos
11986 org-log-reschedule))
11987 (org-remove-timestamp-with-keyword org-scheduled-string)
11988 (message "Item is no longer scheduled."))
11989 (org-add-planning-info 'scheduled time 'closed)
11990 (when (and old-date org-log-reschedule
11991 (not (equal old-date
11992 (substring org-last-inserted-timestamp 1 -1))))
11993 (org-add-log-setup 'reschedule nil old-date 'findpos
11994 org-log-reschedule))
11995 (when repeater
11996 (save-excursion
11997 (org-back-to-heading t)
11998 (when (re-search-forward (concat org-scheduled-string " "
11999 org-last-inserted-timestamp)
12000 (save-excursion
12001 (outline-next-heading) (point)) t)
12002 (goto-char (1- (match-end 0)))
12003 (insert " " repeater)
12004 (setq org-last-inserted-timestamp
12005 (concat (substring org-last-inserted-timestamp 0 -1)
12006 " " repeater
12007 (substring org-last-inserted-timestamp -1))))))
12008 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12010 (defun org-get-scheduled-time (pom &optional inherit)
12011 "Get the scheduled time as a time tuple, of a format suitable
12012 for calling org-schedule with, or if there is no scheduling,
12013 returns nil."
12014 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12015 (when time
12016 (apply 'encode-time (org-parse-time-string time)))))
12018 (defun org-get-deadline-time (pom &optional inherit)
12019 "Get the deadline as a time tuple, of a format suitable for
12020 calling org-deadline with, or if there is no scheduling, returns
12021 nil."
12022 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12023 (when time
12024 (apply 'encode-time (org-parse-time-string time)))))
12026 (defun org-remove-timestamp-with-keyword (keyword)
12027 "Remove all time stamps with KEYWORD in the current entry."
12028 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12029 beg)
12030 (save-excursion
12031 (org-back-to-heading t)
12032 (setq beg (point))
12033 (outline-next-heading)
12034 (while (re-search-backward re beg t)
12035 (replace-match "")
12036 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12037 (equal (char-before) ?\ ))
12038 (backward-delete-char 1)
12039 (if (string-match "^[ \t]*$" (buffer-substring
12040 (point-at-bol) (point-at-eol)))
12041 (delete-region (point-at-bol)
12042 (min (point-max) (1+ (point-at-eol))))))))))
12044 (defun org-add-planning-info (what &optional time &rest remove)
12045 "Insert new timestamp with keyword in the line directly after the headline.
12046 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12047 If non is given, the user is prompted for a date.
12048 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12049 be removed."
12050 (interactive)
12051 (let (org-time-was-given org-end-time-was-given ts
12052 end default-time default-input)
12054 (catch 'exit
12055 (when (and (memq what '(scheduled deadline))
12056 (or (not time)
12057 (and (stringp time)
12058 (string-match "^[-+]+[0-9]" time))))
12059 ;; Try to get a default date/time from existing timestamp
12060 (save-excursion
12061 (org-back-to-heading t)
12062 (setq end (save-excursion (outline-next-heading) (point)))
12063 (when (re-search-forward (if (eq what 'scheduled)
12064 org-scheduled-time-regexp
12065 org-deadline-time-regexp)
12066 end t)
12067 (setq ts (match-string 1)
12068 default-time
12069 (apply 'encode-time (org-parse-time-string ts))
12070 default-input (and ts (org-get-compact-tod ts))))))
12071 (when what
12072 (setq time
12073 (if (and (stringp time)
12074 (string-match "^[-+]+[0-9]" time))
12075 ;; This is a relative time, set the proper date
12076 (apply 'encode-time
12077 (org-read-date-analyze
12078 time default-time (decode-time default-time)))
12079 ;; If necessary, get the time from the user
12080 (or time (org-read-date nil 'to-time nil nil
12081 default-time default-input)))))
12083 (when (and org-insert-labeled-timestamps-at-point
12084 (member what '(scheduled deadline)))
12085 (insert
12086 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12087 (org-insert-time-stamp time org-time-was-given
12088 nil nil nil (list org-end-time-was-given))
12089 (setq what nil))
12090 (save-excursion
12091 (save-restriction
12092 (let (col list elt ts buffer-invisibility-spec)
12093 (org-back-to-heading t)
12094 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12095 (goto-char (match-end 1))
12096 (setq col (current-column))
12097 (goto-char (match-end 0))
12098 (if (eobp) (insert "\n") (forward-char 1))
12099 (when (and (not what)
12100 (not (looking-at
12101 (concat "[ \t]*"
12102 org-keyword-time-not-clock-regexp))))
12103 ;; Nothing to add, nothing to remove...... :-)
12104 (throw 'exit nil))
12105 (if (and (not (looking-at org-outline-regexp))
12106 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12107 "[^\r\n]*"))
12108 (not (equal (match-string 1) org-clock-string)))
12109 (narrow-to-region (match-beginning 0) (match-end 0))
12110 (insert-before-markers "\n")
12111 (backward-char 1)
12112 (narrow-to-region (point) (point))
12113 (and org-adapt-indentation (org-indent-to-column col)))
12114 ;; Check if we have to remove something.
12115 (setq list (cons what remove))
12116 (while list
12117 (setq elt (pop list))
12118 (when (or (and (eq elt 'scheduled)
12119 (re-search-forward org-scheduled-time-regexp nil t))
12120 (and (eq elt 'deadline)
12121 (re-search-forward org-deadline-time-regexp nil t))
12122 (and (eq elt 'closed)
12123 (re-search-forward org-closed-time-regexp nil t)))
12124 (replace-match "")
12125 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12126 (and (looking-at "[ \t]+") (replace-match ""))
12127 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12128 (when what
12129 (insert
12130 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12131 (cond ((eq what 'scheduled) org-scheduled-string)
12132 ((eq what 'deadline) org-deadline-string)
12133 ((eq what 'closed) org-closed-string))
12134 " ")
12135 (setq ts (org-insert-time-stamp
12136 time
12137 (or org-time-was-given
12138 (and (eq what 'closed) org-log-done-with-time))
12139 (eq what 'closed)
12140 nil nil (list org-end-time-was-given)))
12141 (insert
12142 (if (not (or (bolp) (eq (char-before) ?\ )
12143 (memq (char-after) '(32 10))
12144 (eobp))) " " ""))
12145 (end-of-line 1))
12146 (goto-char (point-min))
12147 (widen)
12148 (if (and (looking-at "[ \t]*\n")
12149 (equal (char-before) ?\n))
12150 (delete-region (1- (point)) (point-at-eol)))
12151 ts))))))
12153 (defvar org-log-note-marker (make-marker))
12154 (defvar org-log-note-purpose nil)
12155 (defvar org-log-note-state nil)
12156 (defvar org-log-note-previous-state nil)
12157 (defvar org-log-note-how nil)
12158 (defvar org-log-note-extra nil)
12159 (defvar org-log-note-window-configuration nil)
12160 (defvar org-log-note-return-to (make-marker))
12161 (defvar org-log-note-effective-time nil
12162 "Remembered current time so that dynamically scoped
12163 `org-extend-today-until' affects tha timestamps in state change
12164 log")
12166 (defvar org-log-post-message nil
12167 "Message to be displayed after a log note has been stored.
12168 The auto-repeater uses this.")
12170 (defun org-add-note ()
12171 "Add a note to the current entry.
12172 This is done in the same way as adding a state change note."
12173 (interactive)
12174 (org-add-log-setup 'note nil nil 'findpos nil))
12176 (defvar org-property-end-re)
12177 (defun org-add-log-setup (&optional purpose state prev-state
12178 findpos how extra)
12179 "Set up the post command hook to take a note.
12180 If this is about to TODO state change, the new state is expected in STATE.
12181 When FINDPOS is non-nil, find the correct position for the note in
12182 the current entry. If not, assume that it can be inserted at point.
12183 HOW is an indicator what kind of note should be created.
12184 EXTRA is additional text that will be inserted into the notes buffer."
12185 (let* ((org-log-into-drawer (org-log-into-drawer))
12186 (drawer (cond ((stringp org-log-into-drawer)
12187 org-log-into-drawer)
12188 (org-log-into-drawer "LOGBOOK")
12189 (t nil))))
12190 (save-restriction
12191 (save-excursion
12192 (when findpos
12193 (org-back-to-heading t)
12194 (narrow-to-region (point) (save-excursion
12195 (outline-next-heading) (point)))
12196 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12197 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12198 "[^\r\n]*\\)?"))
12199 (goto-char (match-end 0))
12200 (cond
12201 (drawer
12202 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12203 nil t)
12204 (progn
12205 (goto-char (match-end 0))
12206 (or org-log-states-order-reversed
12207 (and (re-search-forward org-property-end-re nil t)
12208 (goto-char (1- (match-beginning 0))))))
12209 (insert "\n:" drawer ":\n:END:")
12210 (beginning-of-line 0)
12211 (org-indent-line-function)
12212 (beginning-of-line 2)
12213 (org-indent-line-function)
12214 (end-of-line 0)))
12215 ((and org-log-state-notes-insert-after-drawers
12216 (save-excursion
12217 (forward-line) (looking-at org-drawer-regexp)))
12218 (forward-line)
12219 (while (looking-at org-drawer-regexp)
12220 (goto-char (match-end 0))
12221 (re-search-forward org-property-end-re (point-max) t)
12222 (forward-line))
12223 (forward-line -1)))
12224 (unless org-log-states-order-reversed
12225 (and (= (char-after) ?\n) (forward-char 1))
12226 (org-skip-over-state-notes)
12227 (skip-chars-backward " \t\n\r")))
12228 (move-marker org-log-note-marker (point))
12229 (setq org-log-note-purpose purpose
12230 org-log-note-state state
12231 org-log-note-previous-state prev-state
12232 org-log-note-how how
12233 org-log-note-extra extra
12234 org-log-note-effective-time (org-current-effective-time))
12235 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12237 (defun org-skip-over-state-notes ()
12238 "Skip past the list of State notes in an entry."
12239 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12240 (when (ignore-errors (goto-char (org-in-item-p)))
12241 (let* ((struct (org-list-struct))
12242 (prevs (org-list-prevs-alist struct)))
12243 (while (looking-at "[ \t]*- State")
12244 (goto-char (or (org-list-get-next-item (point) struct prevs)
12245 (org-list-get-item-end (point) struct)))))))
12247 (defun org-add-log-note (&optional purpose)
12248 "Pop up a window for taking a note, and add this note later at point."
12249 (remove-hook 'post-command-hook 'org-add-log-note)
12250 (setq org-log-note-window-configuration (current-window-configuration))
12251 (delete-other-windows)
12252 (move-marker org-log-note-return-to (point))
12253 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12254 (goto-char org-log-note-marker)
12255 (org-switch-to-buffer-other-window "*Org Note*")
12256 (erase-buffer)
12257 (if (memq org-log-note-how '(time state))
12258 (let (current-prefix-arg) (org-store-log-note))
12259 (let ((org-inhibit-startup t)) (org-mode))
12260 (insert (format "# Insert note for %s.
12261 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12262 (cond
12263 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12264 ((eq org-log-note-purpose 'done) "closed todo item")
12265 ((eq org-log-note-purpose 'state)
12266 (format "state change from \"%s\" to \"%s\""
12267 (or org-log-note-previous-state "")
12268 (or org-log-note-state "")))
12269 ((eq org-log-note-purpose 'reschedule)
12270 "rescheduling")
12271 ((eq org-log-note-purpose 'delschedule)
12272 "no longer scheduled")
12273 ((eq org-log-note-purpose 'redeadline)
12274 "changing deadline")
12275 ((eq org-log-note-purpose 'deldeadline)
12276 "removing deadline")
12277 ((eq org-log-note-purpose 'refile)
12278 "refiling")
12279 ((eq org-log-note-purpose 'note)
12280 "this entry")
12281 (t (error "This should not happen")))))
12282 (if org-log-note-extra (insert org-log-note-extra))
12283 (org-set-local 'org-finish-function 'org-store-log-note)
12284 (run-hooks 'org-log-buffer-setup-hook)))
12286 (defvar org-note-abort nil) ; dynamically scoped
12287 (defun org-store-log-note ()
12288 "Finish taking a log note, and insert it to where it belongs."
12289 (let ((txt (buffer-string))
12290 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12291 lines ind bul)
12292 (kill-buffer (current-buffer))
12293 (while (string-match "\\`#.*\n[ \t\n]*" txt)
12294 (setq txt (replace-match "" t t txt)))
12295 (if (string-match "\\s-+\\'" txt)
12296 (setq txt (replace-match "" t t txt)))
12297 (setq lines (org-split-string txt "\n"))
12298 (when (and note (string-match "\\S-" note))
12299 (setq note
12300 (org-replace-escapes
12301 note
12302 (list (cons "%u" (user-login-name))
12303 (cons "%U" user-full-name)
12304 (cons "%t" (format-time-string
12305 (org-time-stamp-format 'long 'inactive)
12306 org-log-note-effective-time))
12307 (cons "%T" (format-time-string
12308 (org-time-stamp-format 'long nil)
12309 org-log-note-effective-time))
12310 (cons "%d" (format-time-string
12311 (org-time-stamp-format nil 'inactive)
12312 org-log-note-effective-time))
12313 (cons "%D" (format-time-string
12314 (org-time-stamp-format nil nil)
12315 org-log-note-effective-time))
12316 (cons "%s" (if org-log-note-state
12317 (concat "\"" org-log-note-state "\"")
12318 ""))
12319 (cons "%S" (if org-log-note-previous-state
12320 (concat "\"" org-log-note-previous-state "\"")
12321 "\"\"")))))
12322 (if lines (setq note (concat note " \\\\")))
12323 (push note lines))
12324 (when (or current-prefix-arg org-note-abort)
12325 (when org-log-into-drawer
12326 (org-remove-empty-drawer-at
12327 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12328 org-log-note-marker))
12329 (setq lines nil))
12330 (when lines
12331 (with-current-buffer (marker-buffer org-log-note-marker)
12332 (save-excursion
12333 (goto-char org-log-note-marker)
12334 (move-marker org-log-note-marker nil)
12335 (end-of-line 1)
12336 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12337 (setq ind (save-excursion
12338 (if (ignore-errors (goto-char (org-in-item-p)))
12339 (let ((struct (org-list-struct)))
12340 (org-list-get-ind
12341 (org-list-get-top-point struct) struct))
12342 (skip-chars-backward " \r\t\n")
12343 (cond
12344 ((and (org-at-heading-p)
12345 org-adapt-indentation)
12346 (1+ (org-current-level)))
12347 ((org-at-heading-p) 0)
12348 (t (org-get-indentation))))))
12349 (setq bul (org-list-bullet-string "-"))
12350 (org-indent-line-to ind)
12351 (insert bul (pop lines))
12352 (let ((ind-body (+ (length bul) ind)))
12353 (while lines
12354 (insert "\n")
12355 (org-indent-line-to ind-body)
12356 (insert (pop lines))))
12357 (message "Note stored")
12358 (org-back-to-heading t)
12359 (org-cycle-hide-drawers 'children)))))
12360 (set-window-configuration org-log-note-window-configuration)
12361 (with-current-buffer (marker-buffer org-log-note-return-to)
12362 (goto-char org-log-note-return-to))
12363 (move-marker org-log-note-return-to nil)
12364 (and org-log-post-message (message "%s" org-log-post-message)))
12366 (defun org-remove-empty-drawer-at (drawer pos)
12367 "Remove an empty drawer DRAWER at position POS.
12368 POS may also be a marker."
12369 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12370 (save-excursion
12371 (save-restriction
12372 (widen)
12373 (goto-char pos)
12374 (if (org-in-regexp
12375 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12376 (replace-match ""))))))
12378 (defun org-sparse-tree (&optional arg)
12379 "Create a sparse tree, prompt for the details.
12380 This command can create sparse trees. You first need to select the type
12381 of match used to create the tree:
12383 t Show all TODO entries.
12384 T Show entries with a specific TODO keyword.
12385 m Show entries selected by a tags/property match.
12386 p Enter a property name and its value (both with completion on existing
12387 names/values) and show entries with that property.
12388 r Show entries matching a regular expression (`/' can be used as well)
12389 d Show deadlines due within `org-deadline-warning-days'.
12390 b Show deadlines and scheduled items before a date.
12391 a Show deadlines and scheduled items after a date."
12392 (interactive "P")
12393 (let (ans kwd value)
12394 (message "Sparse tree: [r]egexp [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty\n [d]eadlines [b]efore-date [a]fter-date")
12395 (setq ans (read-char-exclusive))
12396 (cond
12397 ((equal ans ?d)
12398 (call-interactively 'org-check-deadlines))
12399 ((equal ans ?b)
12400 (call-interactively 'org-check-before-date))
12401 ((equal ans ?a)
12402 (call-interactively 'org-check-after-date))
12403 ((equal ans ?t)
12404 (org-show-todo-tree nil))
12405 ((equal ans ?T)
12406 (org-show-todo-tree '(4)))
12407 ((member ans '(?T ?m))
12408 (call-interactively 'org-match-sparse-tree))
12409 ((member ans '(?p ?P))
12410 (setq kwd (org-icompleting-read "Property: "
12411 (mapcar 'list (org-buffer-property-keys))))
12412 (setq value (org-icompleting-read "Value: "
12413 (mapcar 'list (org-property-values kwd))))
12414 (unless (string-match "\\`{.*}\\'" value)
12415 (setq value (concat "\"" value "\"")))
12416 (org-match-sparse-tree arg (concat kwd "=" value)))
12417 ((member ans '(?r ?R ?/))
12418 (call-interactively 'org-occur))
12419 (t (error "No such sparse tree command \"%c\"" ans)))))
12421 (defvar org-occur-highlights nil
12422 "List of overlays used for occur matches.")
12423 (make-variable-buffer-local 'org-occur-highlights)
12424 (defvar org-occur-parameters nil
12425 "Parameters of the active org-occur calls.
12426 This is a list, each call to org-occur pushes as cons cell,
12427 containing the regular expression and the callback, onto the list.
12428 The list can contain several entries if `org-occur' has been called
12429 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12430 will only contain one set of parameters. When the highlights are
12431 removed (for example with `C-c C-c', or with the next edit (depending
12432 on `org-remove-highlights-with-change'), this variable is emptied
12433 as well.")
12434 (make-variable-buffer-local 'org-occur-parameters)
12436 (defun org-occur (regexp &optional keep-previous callback)
12437 "Make a compact tree which shows all matches of REGEXP.
12438 The tree will show the lines where the regexp matches, and all higher
12439 headlines above the match. It will also show the heading after the match,
12440 to make sure editing the matching entry is easy.
12441 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12442 call to `org-occur' will be kept, to allow stacking of calls to this
12443 command.
12444 If CALLBACK is non-nil, it is a function which is called to confirm
12445 that the match should indeed be shown."
12446 (interactive "sRegexp: \nP")
12447 (when (equal regexp "")
12448 (error "Regexp cannot be empty"))
12449 (unless keep-previous
12450 (org-remove-occur-highlights nil nil t))
12451 (push (cons regexp callback) org-occur-parameters)
12452 (let ((cnt 0))
12453 (save-excursion
12454 (goto-char (point-min))
12455 (if (or (not keep-previous) ; do not want to keep
12456 (not org-occur-highlights)) ; no previous matches
12457 ;; hide everything
12458 (org-overview))
12459 (while (re-search-forward regexp nil t)
12460 (when (or (not callback)
12461 (save-match-data (funcall callback)))
12462 (setq cnt (1+ cnt))
12463 (when org-highlight-sparse-tree-matches
12464 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12465 (org-show-context 'occur-tree))))
12466 (when org-remove-highlights-with-change
12467 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12468 nil 'local))
12469 (unless org-sparse-tree-open-archived-trees
12470 (org-hide-archived-subtrees (point-min) (point-max)))
12471 (run-hooks 'org-occur-hook)
12472 (if (org-called-interactively-p 'interactive)
12473 (message "%d match(es) for regexp %s" cnt regexp))
12474 cnt))
12476 (defun org-occur-next-match (&optional n reset)
12477 "Function for `next-error-function' to find sparse tree matches.
12478 N is the number of matches to move, when negative move backwards.
12479 RESET is entirely ignored - this function always goes back to the
12480 starting point when no match is found."
12481 (let* ((limit (if (< n 0) (point-min) (point-max)))
12482 (search-func (if (< n 0)
12483 'previous-single-char-property-change
12484 'next-single-char-property-change))
12485 (n (abs n))
12486 (pos (point))
12488 (catch 'exit
12489 (while (setq p1 (funcall search-func (point) 'org-type))
12490 (when (equal p1 limit)
12491 (goto-char pos)
12492 (error "No more matches"))
12493 (when (equal (get-char-property p1 'org-type) 'org-occur)
12494 (setq n (1- n))
12495 (when (= n 0)
12496 (goto-char p1)
12497 (throw 'exit (point))))
12498 (goto-char p1))
12499 (goto-char p1)
12500 (error "No more matches"))))
12502 (defun org-show-context (&optional key)
12503 "Make sure point and context are visible.
12504 How much context is shown depends upon the variables
12505 `org-show-hierarchy-above', `org-show-following-heading'. and
12506 `org-show-siblings'."
12507 (let ((heading-p (org-on-heading-p t))
12508 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12509 (following-p (org-get-alist-option org-show-following-heading key))
12510 (entry-p (org-get-alist-option org-show-entry-below key))
12511 (siblings-p (org-get-alist-option org-show-siblings key)))
12512 (catch 'exit
12513 ;; Show heading or entry text
12514 (if (and heading-p (not entry-p))
12515 (org-flag-heading nil) ; only show the heading
12516 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12517 (org-show-hidden-entry))) ; show entire entry
12518 (when following-p
12519 ;; Show next sibling, or heading below text
12520 (save-excursion
12521 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12522 (org-flag-heading nil))))
12523 (when siblings-p (org-show-siblings))
12524 (when hierarchy-p
12525 ;; show all higher headings, possibly with siblings
12526 (save-excursion
12527 (while (and (condition-case nil
12528 (progn (org-up-heading-all 1) t)
12529 (error nil))
12530 (not (bobp)))
12531 (org-flag-heading nil)
12532 (when siblings-p (org-show-siblings))))))))
12534 (defvar org-reveal-start-hook nil
12535 "Hook run before revealing a location.")
12537 (defun org-reveal (&optional siblings)
12538 "Show current entry, hierarchy above it, and the following headline.
12539 This can be used to show a consistent set of context around locations
12540 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12541 not t for the search context.
12543 With optional argument SIBLINGS, on each level of the hierarchy all
12544 siblings are shown. This repairs the tree structure to what it would
12545 look like when opened with hierarchical calls to `org-cycle'.
12546 With double optional argument \\[universal-argument] \\[universal-argument], \
12547 go to the parent and show the
12548 entire tree."
12549 (interactive "P")
12550 (run-hooks 'org-reveal-start-hook)
12551 (let ((org-show-hierarchy-above t)
12552 (org-show-following-heading t)
12553 (org-show-siblings (if siblings t org-show-siblings)))
12554 (org-show-context nil))
12555 (when (equal siblings '(16))
12556 (save-excursion
12557 (when (org-up-heading-safe)
12558 (org-show-subtree)
12559 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12561 (defun org-highlight-new-match (beg end)
12562 "Highlight from BEG to END and mark the highlight is an occur headline."
12563 (let ((ov (make-overlay beg end)))
12564 (overlay-put ov 'face 'secondary-selection)
12565 (overlay-put ov 'org-type 'org-occur)
12566 (push ov org-occur-highlights)))
12568 (defun org-remove-occur-highlights (&optional beg end noremove)
12569 "Remove the occur highlights from the buffer.
12570 BEG and END are ignored. If NOREMOVE is nil, remove this function
12571 from the `before-change-functions' in the current buffer."
12572 (interactive)
12573 (unless org-inhibit-highlight-removal
12574 (mapc 'delete-overlay org-occur-highlights)
12575 (setq org-occur-highlights nil)
12576 (setq org-occur-parameters nil)
12577 (unless noremove
12578 (remove-hook 'before-change-functions
12579 'org-remove-occur-highlights 'local))))
12581 ;;;; Priorities
12583 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12584 "Regular expression matching the priority indicator.")
12586 (defvar org-remove-priority-next-time nil)
12588 (defun org-priority-up ()
12589 "Increase the priority of the current item."
12590 (interactive)
12591 (org-priority 'up))
12593 (defun org-priority-down ()
12594 "Decrease the priority of the current item."
12595 (interactive)
12596 (org-priority 'down))
12598 (defun org-priority (&optional action)
12599 "Change the priority of an item by ARG.
12600 ACTION can be `set', `up', `down', or a character."
12601 (interactive)
12602 (unless org-enable-priority-commands
12603 (error "Priority commands are disabled"))
12604 (setq action (or action 'set))
12605 (let (current new news have remove)
12606 (save-excursion
12607 (org-back-to-heading t)
12608 (if (looking-at org-priority-regexp)
12609 (setq current (string-to-char (match-string 2))
12610 have t))
12611 (cond
12612 ((eq action 'remove)
12613 (setq remove t new ?\ ))
12614 ((or (eq action 'set)
12615 (if (featurep 'xemacs) (characterp action) (integerp action)))
12616 (if (not (eq action 'set))
12617 (setq new action)
12618 (message "Priority %c-%c, SPC to remove: "
12619 org-highest-priority org-lowest-priority)
12620 (save-match-data
12621 (setq new (read-char-exclusive))))
12622 (if (and (= (upcase org-highest-priority) org-highest-priority)
12623 (= (upcase org-lowest-priority) org-lowest-priority))
12624 (setq new (upcase new)))
12625 (cond ((equal new ?\ ) (setq remove t))
12626 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12627 (error "Priority must be between `%c' and `%c'"
12628 org-highest-priority org-lowest-priority))))
12629 ((eq action 'up)
12630 (setq new (if have
12631 (1- current) ; normal cycling
12632 ;; last priority was empty
12633 (if (eq last-command this-command)
12634 org-lowest-priority ; wrap around empty to lowest
12635 ;; default
12636 (if org-priority-start-cycle-with-default
12637 org-default-priority
12638 (1- org-default-priority))))))
12639 ((eq action 'down)
12640 (setq new (if have
12641 (1+ current) ; normal cycling
12642 ;; last priority was empty
12643 (if (eq last-command this-command)
12644 org-highest-priority ; wrap around empty to highest
12645 ;; default
12646 (if org-priority-start-cycle-with-default
12647 org-default-priority
12648 (1+ org-default-priority))))))
12649 (t (error "Invalid action")))
12650 (if (or (< (upcase new) org-highest-priority)
12651 (> (upcase new) org-lowest-priority))
12652 (if (and (memq action '(up down))
12653 (not have) (not (eq last-command this-command)))
12654 ;; `new' is from default priority
12655 (error
12656 "The default can not be set, see `org-default-priority' why")
12657 ;; normal cycling: `new' is beyond highest/lowest priority
12658 ;; and is wrapped around to the empty priority
12659 (setq remove t)))
12660 (setq news (format "%c" new))
12661 (if have
12662 (if remove
12663 (replace-match "" t t nil 1)
12664 (replace-match news t t nil 2))
12665 (if remove
12666 (error "No priority cookie found in line")
12667 (let ((case-fold-search nil))
12668 (looking-at org-todo-line-regexp))
12669 (if (match-end 2)
12670 (progn
12671 (goto-char (match-end 2))
12672 (insert " [#" news "]"))
12673 (goto-char (match-beginning 3))
12674 (insert "[#" news "] "))))
12675 (org-preserve-lc (org-set-tags nil 'align)))
12676 (if remove
12677 (message "Priority removed")
12678 (message "Priority of current item set to %s" news))))
12680 (defun org-get-priority (s)
12681 "Find priority cookie and return priority."
12682 (if (functionp org-get-priority-function)
12683 (funcall org-get-priority-function)
12684 (save-match-data
12685 (if (not (string-match org-priority-regexp s))
12686 (* 1000 (- org-lowest-priority org-default-priority))
12687 (* 1000 (- org-lowest-priority
12688 (string-to-char (match-string 2 s))))))))
12690 ;;;; Tags
12692 (defvar org-agenda-archives-mode)
12693 (defvar org-map-continue-from nil
12694 "Position from where mapping should continue.
12695 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
12697 (defvar org-scanner-tags nil
12698 "The current tag list while the tags scanner is running.")
12699 (defvar org-trust-scanner-tags nil
12700 "Should `org-get-tags-at' use the tags for the scanner.
12701 This is for internal dynamical scoping only.
12702 When this is non-nil, the function `org-get-tags-at' will return the value
12703 of `org-scanner-tags' instead of building the list by itself. This
12704 can lead to large speed-ups when the tags scanner is used in a file with
12705 many entries, and when the list of tags is retrieved, for example to
12706 obtain a list of properties. Building the tags list for each entry in such
12707 a file becomes an N^2 operation - but with this variable set, it scales
12708 as N.")
12710 (defun org-scan-tags (action matcher &optional todo-only)
12711 "Scan headline tags with inheritance and produce output ACTION.
12713 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12714 or `agenda' to produce an entry list for an agenda view. It can also be
12715 a Lisp form or a function that should be called at each matched headline, in
12716 this case the return value is a list of all return values from these calls.
12718 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12719 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12720 only lines with a TODO keyword are included in the output."
12721 (require 'org-agenda)
12722 (let* ((re (concat "^" org-outline-regexp " *\\(\\<\\("
12723 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12724 (org-re
12725 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
12726 (props (list 'face 'default
12727 'done-face 'org-agenda-done
12728 'undone-face 'default
12729 'mouse-face 'highlight
12730 'org-not-done-regexp org-not-done-regexp
12731 'org-todo-regexp org-todo-regexp
12732 'org-complex-heading-regexp org-complex-heading-regexp
12733 'help-echo
12734 (format "mouse-2 or RET jump to org file %s"
12735 (abbreviate-file-name
12736 (or (buffer-file-name (buffer-base-buffer))
12737 (buffer-name (buffer-base-buffer)))))))
12738 (case-fold-search nil)
12739 (org-map-continue-from nil)
12740 lspos tags tags-list
12741 (tags-alist (list (cons 0 org-file-tags)))
12742 (llast 0) rtn rtn1 level category i txt
12743 todo marker entry priority)
12744 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12745 (setq action (list 'lambda nil action)))
12746 (save-excursion
12747 (goto-char (point-min))
12748 (when (eq action 'sparse-tree)
12749 (org-overview)
12750 (org-remove-occur-highlights))
12751 (while (re-search-forward re nil t)
12752 (catch :skip
12753 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12754 tags (if (match-end 4) (org-match-string-no-properties 4)))
12755 (goto-char (setq lspos (match-beginning 0)))
12756 (setq level (org-reduced-level (funcall outline-level))
12757 category (org-get-category))
12758 (setq i llast llast level)
12759 ;; remove tag lists from same and sublevels
12760 (while (>= i level)
12761 (when (setq entry (assoc i tags-alist))
12762 (setq tags-alist (delete entry tags-alist)))
12763 (setq i (1- i)))
12764 ;; add the next tags
12765 (when tags
12766 (setq tags (org-split-string tags ":")
12767 tags-alist
12768 (cons (cons level tags) tags-alist)))
12769 ;; compile tags for current headline
12770 (setq tags-list
12771 (if org-use-tag-inheritance
12772 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12773 tags)
12774 org-scanner-tags tags-list)
12775 (when org-use-tag-inheritance
12776 (setcdr (car tags-alist)
12777 (mapcar (lambda (x)
12778 (setq x (copy-sequence x))
12779 (org-add-prop-inherited x))
12780 (cdar tags-alist))))
12781 (when (and tags org-use-tag-inheritance
12782 (or (not (eq t org-use-tag-inheritance))
12783 org-tags-exclude-from-inheritance))
12784 ;; selective inheritance, remove uninherited ones
12785 (setcdr (car tags-alist)
12786 (org-remove-uninherited-tags (cdar tags-alist))))
12787 (when (and
12789 ;; eval matcher only when the todo condition is OK
12790 (and (or (not todo-only) (member todo org-not-done-keywords))
12791 (let ((case-fold-search t)) (eval matcher)))
12793 ;; Call the skipper, but return t if it does not skip,
12794 ;; so that the `and' form continues evaluating
12795 (progn
12796 (unless (eq action 'sparse-tree) (org-agenda-skip))
12799 ;; Check if timestamps are deselecting this entry
12800 (or (not todo-only)
12801 (and (member todo org-not-done-keywords)
12802 (or (not org-agenda-tags-todo-honor-ignore-options)
12803 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
12805 ;; Extra check for the archive tag
12806 ;; FIXME: Does the skipper already do this????
12808 (not (member org-archive-tag tags-list))
12809 ;; we have an archive tag, should we use this anyway?
12810 (or (not org-agenda-skip-archived-trees)
12811 (and (eq action 'agenda) org-agenda-archives-mode))))
12813 ;; select this headline
12815 (cond
12816 ((eq action 'sparse-tree)
12817 (and org-highlight-sparse-tree-matches
12818 (org-get-heading) (match-end 0)
12819 (org-highlight-new-match
12820 (match-beginning 0) (match-beginning 1)))
12821 (org-show-context 'tags-tree))
12822 ((eq action 'agenda)
12823 (setq txt (org-agenda-format-item
12825 (concat
12826 (if (eq org-tags-match-list-sublevels 'indented)
12827 (make-string (1- level) ?.) "")
12828 (org-get-heading))
12829 category
12830 tags-list
12832 priority (org-get-priority txt))
12833 (goto-char lspos)
12834 (setq marker (org-agenda-new-marker))
12835 (org-add-props txt props
12836 'org-marker marker 'org-hd-marker marker 'org-category category
12837 'todo-state todo
12838 'priority priority 'type "tagsmatch")
12839 (push txt rtn))
12840 ((functionp action)
12841 (setq org-map-continue-from nil)
12842 (save-excursion
12843 (setq rtn1 (funcall action))
12844 (push rtn1 rtn)))
12845 (t (error "Invalid action")))
12847 ;; if we are to skip sublevels, jump to end of subtree
12848 (unless org-tags-match-list-sublevels
12849 (org-end-of-subtree t)
12850 (backward-char 1))))
12851 ;; Get the correct position from where to continue
12852 (if org-map-continue-from
12853 (goto-char org-map-continue-from)
12854 (and (= (point) lspos) (end-of-line 1)))))
12855 (when (and (eq action 'sparse-tree)
12856 (not org-sparse-tree-open-archived-trees))
12857 (org-hide-archived-subtrees (point-min) (point-max)))
12858 (nreverse rtn)))
12860 (defun org-remove-uninherited-tags (tags)
12861 "Remove all tags that are not inherited from the list TAGS."
12862 (cond
12863 ((eq org-use-tag-inheritance t)
12864 (if org-tags-exclude-from-inheritance
12865 (org-delete-all org-tags-exclude-from-inheritance tags)
12866 tags))
12867 ((not org-use-tag-inheritance) nil)
12868 ((stringp org-use-tag-inheritance)
12869 (delq nil (mapcar
12870 (lambda (x)
12871 (if (and (string-match org-use-tag-inheritance x)
12872 (not (member x org-tags-exclude-from-inheritance)))
12873 x nil))
12874 tags)))
12875 ((listp org-use-tag-inheritance)
12876 (delq nil (mapcar
12877 (lambda (x)
12878 (if (member x org-use-tag-inheritance) x nil))
12879 tags)))))
12881 (defvar todo-only) ;; dynamically scoped
12883 (defun org-match-sparse-tree (&optional todo-only match)
12884 "Create a sparse tree according to tags string MATCH.
12885 MATCH can contain positive and negative selection of tags, like
12886 \"+WORK+URGENT-WITHBOSS\".
12887 If optional argument TODO-ONLY is non-nil, only select lines that are
12888 also TODO lines."
12889 (interactive "P")
12890 (org-prepare-agenda-buffers (list (current-buffer)))
12891 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
12893 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
12895 (defvar org-cached-props nil)
12896 (defun org-cached-entry-get (pom property)
12897 (if (or (eq t org-use-property-inheritance)
12898 (and (stringp org-use-property-inheritance)
12899 (string-match org-use-property-inheritance property))
12900 (and (listp org-use-property-inheritance)
12901 (member property org-use-property-inheritance)))
12902 ;; Caching is not possible, check it directly
12903 (org-entry-get pom property 'inherit)
12904 ;; Get all properties, so that we can do complicated checks easily
12905 (cdr (assoc property (or org-cached-props
12906 (setq org-cached-props
12907 (org-entry-properties pom)))))))
12909 (defun org-global-tags-completion-table (&optional files)
12910 "Return the list of all tags in all agenda buffer/files.
12911 Optional FILES argument is a list of files to which can be used
12912 instead of the agenda files."
12913 (save-excursion
12914 (org-uniquify
12915 (delq nil
12916 (apply 'append
12917 (mapcar
12918 (lambda (file)
12919 (set-buffer (find-file-noselect file))
12920 (append (org-get-buffer-tags)
12921 (mapcar (lambda (x) (if (stringp (car-safe x))
12922 (list (car-safe x)) nil))
12923 org-tag-alist)))
12924 (if (and files (car files))
12925 files
12926 (org-agenda-files))))))))
12928 (defun org-make-tags-matcher (match)
12929 "Create the TAGS/TODO matcher form for the selection string MATCH."
12930 ;; todo-only is scoped dynamically into this function, and the function
12931 ;; may change it if the matcher asks for it.
12932 (unless match
12933 ;; Get a new match request, with completion
12934 (let ((org-last-tags-completion-table
12935 (org-global-tags-completion-table)))
12936 (setq match (org-completing-read-no-i
12937 "Match: " 'org-tags-completion-function nil nil nil
12938 'org-tags-history))))
12940 ;; Parse the string and create a lisp form
12941 (let ((match0 match)
12942 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
12943 minus tag mm
12944 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
12945 orterms term orlist re-p str-p level-p level-op time-p
12946 prop-p pn pv po gv rest)
12947 (if (string-match "/+" match)
12948 ;; match contains also a todo-matching request
12949 (progn
12950 (setq tagsmatch (substring match 0 (match-beginning 0))
12951 todomatch (substring match (match-end 0)))
12952 (if (string-match "^!" todomatch)
12953 (setq todo-only t todomatch (substring todomatch 1)))
12954 (if (string-match "^\\s-*$" todomatch)
12955 (setq todomatch nil)))
12956 ;; only matching tags
12957 (setq tagsmatch match todomatch nil))
12959 ;; Make the tags matcher
12960 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
12961 (setq tagsmatcher t)
12962 (setq orterms (org-split-string tagsmatch "|") orlist nil)
12963 (while (setq term (pop orterms))
12964 (while (and (equal (substring term -1) "\\") orterms)
12965 (setq term (concat term "|" (pop orterms)))) ; repair bad split
12966 (while (string-match re term)
12967 (setq rest (substring term (match-end 0))
12968 minus (and (match-end 1)
12969 (equal (match-string 1 term) "-"))
12970 tag (save-match-data (replace-regexp-in-string
12971 "\\\\-" "-"
12972 (match-string 2 term)))
12973 re-p (equal (string-to-char tag) ?{)
12974 level-p (match-end 4)
12975 prop-p (match-end 5)
12976 mm (cond
12977 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
12978 (level-p
12979 (setq level-op (org-op-to-function (match-string 3 term)))
12980 `(,level-op level ,(string-to-number
12981 (match-string 4 term))))
12982 (prop-p
12983 (setq pn (match-string 5 term)
12984 po (match-string 6 term)
12985 pv (match-string 7 term)
12986 re-p (equal (string-to-char pv) ?{)
12987 str-p (equal (string-to-char pv) ?\")
12988 time-p (save-match-data
12989 (string-match "^\"[[<].*[]>]\"$" pv))
12990 pv (if (or re-p str-p) (substring pv 1 -1) pv))
12991 (if time-p (setq pv (org-matcher-time pv)))
12992 (setq po (org-op-to-function po (if time-p 'time str-p)))
12993 (cond
12994 ((equal pn "CATEGORY")
12995 (setq gv '(get-text-property (point) 'org-category)))
12996 ((equal pn "TODO")
12997 (setq gv 'todo))
12999 (setq gv `(org-cached-entry-get nil ,pn))))
13000 (if re-p
13001 (if (eq po 'org<>)
13002 `(not (string-match ,pv (or ,gv "")))
13003 `(string-match ,pv (or ,gv "")))
13004 (if str-p
13005 `(,po (or ,gv "") ,pv)
13006 `(,po (string-to-number (or ,gv ""))
13007 ,(string-to-number pv) ))))
13008 (t `(member ,tag tags-list)))
13009 mm (if minus (list 'not mm) mm)
13010 term rest)
13011 (push mm tagsmatcher))
13012 (push (if (> (length tagsmatcher) 1)
13013 (cons 'and tagsmatcher)
13014 (car tagsmatcher))
13015 orlist)
13016 (setq tagsmatcher nil))
13017 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13018 (setq tagsmatcher
13019 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13020 ;; Make the todo matcher
13021 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13022 (setq todomatcher t)
13023 (setq orterms (org-split-string todomatch "|") orlist nil)
13024 (while (setq term (pop orterms))
13025 (while (string-match re term)
13026 (setq minus (and (match-end 1)
13027 (equal (match-string 1 term) "-"))
13028 kwd (match-string 2 term)
13029 re-p (equal (string-to-char kwd) ?{)
13030 term (substring term (match-end 0))
13031 mm (if re-p
13032 `(string-match ,(substring kwd 1 -1) todo)
13033 (list 'equal 'todo kwd))
13034 mm (if minus (list 'not mm) mm))
13035 (push mm todomatcher))
13036 (push (if (> (length todomatcher) 1)
13037 (cons 'and todomatcher)
13038 (car todomatcher))
13039 orlist)
13040 (setq todomatcher nil))
13041 (setq todomatcher (if (> (length orlist) 1)
13042 (cons 'or orlist) (car orlist))))
13044 ;; Return the string and lisp forms of the matcher
13045 (setq matcher (if todomatcher
13046 (list 'and tagsmatcher todomatcher)
13047 tagsmatcher))
13048 (cons match0 matcher)))
13050 (defun org-op-to-function (op &optional stringp)
13051 "Turn an operator into the appropriate function."
13052 (setq op
13053 (cond
13054 ((equal op "<" ) '(< string< org-time<))
13055 ((equal op ">" ) '(> org-string> org-time>))
13056 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13057 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13058 ((member op '("=" "==")) '(= string= org-time=))
13059 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13060 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13062 (defun org<> (a b) (not (= a b)))
13063 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13064 (defun org-string>= (a b) (not (string< a b)))
13065 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13066 (defun org-string<> (a b) (not (string= a b)))
13067 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13068 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13069 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13070 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13071 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13072 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13073 (defun org-2ft (s)
13074 "Convert S to a floating point time.
13075 If S is already a number, just return it. If it is a string, parse
13076 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13077 (cond
13078 ((numberp s) s)
13079 ((stringp s)
13080 (condition-case nil
13081 (float-time (apply 'encode-time (org-parse-time-string s)))
13082 (error 0.)))
13083 (t 0.)))
13085 (defun org-time-today ()
13086 "Time in seconds today at 0:00.
13087 Returns the float number of seconds since the beginning of the
13088 epoch to the beginning of today (00:00)."
13089 (float-time (apply 'encode-time
13090 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13092 (defun org-matcher-time (s)
13093 "Interpret a time comparison value."
13094 (save-match-data
13095 (cond
13096 ((string= s "<now>") (float-time))
13097 ((string= s "<today>") (org-time-today))
13098 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13099 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13100 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
13101 (+ (org-time-today)
13102 (* (string-to-number (match-string 1 s))
13103 (cdr (assoc (match-string 2 s)
13104 '(("d" . 86400.0) ("w" . 604800.0)
13105 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13106 (t (org-2ft s)))))
13108 (defun org-match-any-p (re list)
13109 "Does re match any element of list?"
13110 (setq list (mapcar (lambda (x) (string-match re x)) list))
13111 (delq nil list))
13113 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13114 (defvar org-tags-overlay (make-overlay 1 1))
13115 (org-detach-overlay org-tags-overlay)
13117 (defun org-get-local-tags-at (&optional pos)
13118 "Get a list of tags defined in the current headline."
13119 (org-get-tags-at pos 'local))
13121 (defun org-get-local-tags ()
13122 "Get a list of tags defined in the current headline."
13123 (org-get-tags-at nil 'local))
13125 (defun org-get-tags-at (&optional pos local)
13126 "Get a list of all headline tags applicable at POS.
13127 POS defaults to point. If tags are inherited, the list contains
13128 the targets in the same sequence as the headlines appear, i.e.
13129 the tags of the current headline come last.
13130 When LOCAL is non-nil, only return tags from the current headline,
13131 ignore inherited ones."
13132 (interactive)
13133 (if (and org-trust-scanner-tags
13134 (or (not pos) (equal pos (point)))
13135 (not local))
13136 org-scanner-tags
13137 (let (tags ltags lastpos parent)
13138 (save-excursion
13139 (save-restriction
13140 (widen)
13141 (goto-char (or pos (point)))
13142 (save-match-data
13143 (catch 'done
13144 (condition-case nil
13145 (progn
13146 (org-back-to-heading t)
13147 (while (not (equal lastpos (point)))
13148 (setq lastpos (point))
13149 (when (looking-at
13150 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13151 (setq ltags (org-split-string
13152 (org-match-string-no-properties 1) ":"))
13153 (when parent
13154 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13155 (setq tags (append
13156 (if parent
13157 (org-remove-uninherited-tags ltags)
13158 ltags)
13159 tags)))
13160 (or org-use-tag-inheritance (throw 'done t))
13161 (if local (throw 'done t))
13162 (or (org-up-heading-safe) (error nil))
13163 (setq parent t)))
13164 (error nil)))))
13165 (if local
13166 tags
13167 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13169 (defun org-add-prop-inherited (s)
13170 (add-text-properties 0 (length s) '(inherited t) s)
13173 (defun org-toggle-tag (tag &optional onoff)
13174 "Toggle the tag TAG for the current line.
13175 If ONOFF is `on' or `off', don't toggle but set to this state."
13176 (let (res current)
13177 (save-excursion
13178 (org-back-to-heading t)
13179 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13180 (point-at-eol) t)
13181 (progn
13182 (setq current (match-string 1))
13183 (replace-match ""))
13184 (setq current ""))
13185 (setq current (nreverse (org-split-string current ":")))
13186 (cond
13187 ((eq onoff 'on)
13188 (setq res t)
13189 (or (member tag current) (push tag current)))
13190 ((eq onoff 'off)
13191 (or (not (member tag current)) (setq current (delete tag current))))
13192 (t (if (member tag current)
13193 (setq current (delete tag current))
13194 (setq res t)
13195 (push tag current))))
13196 (end-of-line 1)
13197 (if current
13198 (progn
13199 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13200 (org-set-tags nil t))
13201 (delete-horizontal-space))
13202 (run-hooks 'org-after-tags-change-hook))
13203 res))
13205 (defun org-align-tags-here (to-col)
13206 ;; Assumes that this is a headline
13207 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13208 (beginning-of-line 1)
13209 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13210 (< pos (match-beginning 2)))
13211 (progn
13212 (setq tags-l (- (match-end 2) (match-beginning 2)))
13213 (goto-char (match-beginning 1))
13214 (insert " ")
13215 (delete-region (point) (1+ (match-beginning 2)))
13216 (setq ncol (max (current-column)
13217 (1+ col)
13218 (if (> to-col 0)
13219 to-col
13220 (- (abs to-col) tags-l))))
13221 (setq p (point))
13222 (insert (make-string (- ncol (current-column)) ?\ ))
13223 (setq ncol (current-column))
13224 (when indent-tabs-mode (tabify p (point-at-eol)))
13225 (org-move-to-column (min ncol col) t))
13226 (goto-char pos))))
13228 (defun org-set-tags-command (&optional arg just-align)
13229 "Call the set-tags command for the current entry."
13230 (interactive "P")
13231 (if (org-on-heading-p)
13232 (org-set-tags arg just-align)
13233 (save-excursion
13234 (org-back-to-heading t)
13235 (org-set-tags arg just-align))))
13237 (defun org-set-tags-to (data)
13238 "Set the tags of the current entry to DATA, replacing the current tags.
13239 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13240 If DATA is nil or the empty string, any tags will be removed."
13241 (interactive "sTags: ")
13242 (setq data
13243 (cond
13244 ((eq data nil) "")
13245 ((equal data "") "")
13246 ((stringp data)
13247 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13248 ":"))
13249 ((listp data)
13250 (concat ":" (mapconcat 'identity data ":") ":"))
13251 (t nil)))
13252 (when data
13253 (save-excursion
13254 (org-back-to-heading t)
13255 (when (looking-at org-complex-heading-regexp)
13256 (if (match-end 5)
13257 (progn
13258 (goto-char (match-beginning 5))
13259 (insert data)
13260 (delete-region (point) (point-at-eol))
13261 (org-set-tags nil 'align))
13262 (goto-char (point-at-eol))
13263 (insert " " data)
13264 (org-set-tags nil 'align)))
13265 (beginning-of-line 1)
13266 (if (looking-at ".*?\\([ \t]+\\)$")
13267 (delete-region (match-beginning 1) (match-end 1))))))
13269 (defun org-align-all-tags ()
13270 "Align the tags i all headings."
13271 (interactive)
13272 (save-excursion
13273 (or (ignore-errors (org-back-to-heading t))
13274 (outline-next-heading))
13275 (if (org-on-heading-p)
13276 (org-set-tags t)
13277 (message "No headings"))))
13279 (defvar org-indent-indentation-per-level)
13280 (defun org-set-tags (&optional arg just-align)
13281 "Set the tags for the current headline.
13282 With prefix ARG, realign all tags in headings in the current buffer."
13283 (interactive "P")
13284 (let* ((re org-outline-regexp-bol)
13285 (current (org-get-tags-string))
13286 (col (current-column))
13287 (org-setting-tags t)
13288 table current-tags inherited-tags ; computed below when needed
13289 tags p0 c0 c1 rpl di tc level)
13290 (if arg
13291 (save-excursion
13292 (goto-char (point-min))
13293 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13294 (while (re-search-forward re nil t)
13295 (org-set-tags nil t)
13296 (end-of-line 1)))
13297 (message "All tags realigned to column %d" org-tags-column))
13298 (if just-align
13299 (setq tags current)
13300 ;; Get a new set of tags from the user
13301 (save-excursion
13302 (setq table (append org-tag-persistent-alist
13303 (or org-tag-alist (org-get-buffer-tags))
13304 (and
13305 org-complete-tags-always-offer-all-agenda-tags
13306 (org-global-tags-completion-table
13307 (org-agenda-files))))
13308 org-last-tags-completion-table table
13309 current-tags (org-split-string current ":")
13310 inherited-tags (nreverse
13311 (nthcdr (length current-tags)
13312 (nreverse (org-get-tags-at))))
13313 tags
13314 (if (or (eq t org-use-fast-tag-selection)
13315 (and org-use-fast-tag-selection
13316 (delq nil (mapcar 'cdr table))))
13317 (org-fast-tag-selection
13318 current-tags inherited-tags table
13319 (if org-fast-tag-selection-include-todo
13320 org-todo-key-alist))
13321 (let ((org-add-colon-after-tag-completion t))
13322 (org-trim
13323 (org-icompleting-read "Tags: "
13324 'org-tags-completion-function
13325 nil nil current 'org-tags-history))))))
13326 (while (string-match "[-+&]+" tags)
13327 ;; No boolean logic, just a list
13328 (setq tags (replace-match ":" t t tags))))
13330 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13332 (if org-tags-sort-function
13333 (setq tags (mapconcat 'identity
13334 (sort (org-split-string
13335 tags (org-re "[^[:alnum:]_@#%]+"))
13336 org-tags-sort-function) ":")))
13338 (if (string-match "\\`[\t ]*\\'" tags)
13339 (setq tags "")
13340 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13341 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13343 ;; Insert new tags at the correct column
13344 (beginning-of-line 1)
13345 (setq level (or (and (looking-at org-outline-regexp)
13346 (- (match-end 0) (point) 1))
13348 (cond
13349 ((and (equal current "") (equal tags "")))
13350 ((re-search-forward
13351 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13352 (point-at-eol) t)
13353 (if (equal tags "")
13354 (setq rpl "")
13355 (goto-char (match-beginning 0))
13356 (setq c0 (current-column)
13357 ;; compute offset for the case of org-indent-mode active
13358 di (if org-indent-mode
13359 (* (1- org-indent-indentation-per-level) (1- level))
13361 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13362 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13363 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13364 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13365 (replace-match rpl t t)
13366 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13367 tags)
13368 (t (error "Tags alignment failed")))
13369 (org-move-to-column col)
13370 (unless just-align
13371 (run-hooks 'org-after-tags-change-hook)))))
13373 (defun org-change-tag-in-region (beg end tag off)
13374 "Add or remove TAG for each entry in the region.
13375 This works in the agenda, and also in an org-mode buffer."
13376 (interactive
13377 (list (region-beginning) (region-end)
13378 (let ((org-last-tags-completion-table
13379 (if (eq major-mode 'org-mode)
13380 (org-get-buffer-tags)
13381 (org-global-tags-completion-table))))
13382 (org-icompleting-read
13383 "Tag: " 'org-tags-completion-function nil nil nil
13384 'org-tags-history))
13385 (progn
13386 (message "[s]et or [r]emove? ")
13387 (equal (read-char-exclusive) ?r))))
13388 (if (fboundp 'deactivate-mark) (deactivate-mark))
13389 (let ((agendap (equal major-mode 'org-agenda-mode))
13390 l1 l2 m buf pos newhead (cnt 0))
13391 (goto-char end)
13392 (setq l2 (1- (org-current-line)))
13393 (goto-char beg)
13394 (setq l1 (org-current-line))
13395 (loop for l from l1 to l2 do
13396 (org-goto-line l)
13397 (setq m (get-text-property (point) 'org-hd-marker))
13398 (when (or (and (eq major-mode 'org-mode) (org-on-heading-p))
13399 (and agendap m))
13400 (setq buf (if agendap (marker-buffer m) (current-buffer))
13401 pos (if agendap m (point)))
13402 (with-current-buffer buf
13403 (save-excursion
13404 (save-restriction
13405 (goto-char pos)
13406 (setq cnt (1+ cnt))
13407 (org-toggle-tag tag (if off 'off 'on))
13408 (setq newhead (org-get-heading)))))
13409 (and agendap (org-agenda-change-all-lines newhead m))))
13410 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13412 (defun org-tags-completion-function (string predicate &optional flag)
13413 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13414 (confirm (lambda (x) (stringp (car x)))))
13415 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13416 (setq s1 (match-string 1 string)
13417 s2 (match-string 2 string))
13418 (setq s1 "" s2 string))
13419 (cond
13420 ((eq flag nil)
13421 ;; try completion
13422 (setq rtn (try-completion s2 ctable confirm))
13423 (if (stringp rtn)
13424 (setq rtn
13425 (concat s1 s2 (substring rtn (length s2))
13426 (if (and org-add-colon-after-tag-completion
13427 (assoc rtn ctable))
13428 ":" ""))))
13429 rtn)
13430 ((eq flag t)
13431 ;; all-completions
13432 (all-completions s2 ctable confirm)
13434 ((eq flag 'lambda)
13435 ;; exact match?
13436 (assoc s2 ctable)))
13439 (defun org-fast-tag-insert (kwd tags face &optional end)
13440 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13441 (insert (format "%-12s" (concat kwd ":"))
13442 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13443 (or end "")))
13445 (defun org-fast-tag-show-exit (flag)
13446 (save-excursion
13447 (org-goto-line 3)
13448 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13449 (replace-match ""))
13450 (when flag
13451 (end-of-line 1)
13452 (org-move-to-column (- (window-width) 19) t)
13453 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13455 (defun org-set-current-tags-overlay (current prefix)
13456 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13457 (if (featurep 'xemacs)
13458 (org-overlay-display org-tags-overlay (concat prefix s)
13459 'secondary-selection)
13460 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13461 (org-overlay-display org-tags-overlay (concat prefix s)))))
13463 (defvar org-last-tag-selection-key nil)
13464 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13465 "Fast tag selection with single keys.
13466 CURRENT is the current list of tags in the headline, INHERITED is the
13467 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13468 possibly with grouping information. TODO-TABLE is a similar table with
13469 TODO keywords, should these have keys assigned to them.
13470 If the keys are nil, a-z are automatically assigned.
13471 Returns the new tags string, or nil to not change the current settings."
13472 (let* ((fulltable (append table todo-table))
13473 (maxlen (apply 'max (mapcar
13474 (lambda (x)
13475 (if (stringp (car x)) (string-width (car x)) 0))
13476 fulltable)))
13477 (buf (current-buffer))
13478 (expert (eq org-fast-tag-selection-single-key 'expert))
13479 (buffer-tags nil)
13480 (fwidth (+ maxlen 3 1 3))
13481 (ncol (/ (- (window-width) 4) fwidth))
13482 (i-face 'org-done)
13483 (c-face 'org-todo)
13484 tg cnt e c char c1 c2 ntable tbl rtn
13485 ov-start ov-end ov-prefix
13486 (exit-after-next org-fast-tag-selection-single-key)
13487 (done-keywords org-done-keywords)
13488 groups ingroup)
13489 (save-excursion
13490 (beginning-of-line 1)
13491 (if (looking-at
13492 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13493 (setq ov-start (match-beginning 1)
13494 ov-end (match-end 1)
13495 ov-prefix "")
13496 (setq ov-start (1- (point-at-eol))
13497 ov-end (1+ ov-start))
13498 (skip-chars-forward "^\n\r")
13499 (setq ov-prefix
13500 (concat
13501 (buffer-substring (1- (point)) (point))
13502 (if (> (current-column) org-tags-column)
13504 (make-string (- org-tags-column (current-column)) ?\ ))))))
13505 (move-overlay org-tags-overlay ov-start ov-end)
13506 (save-window-excursion
13507 (if expert
13508 (set-buffer (get-buffer-create " *Org tags*"))
13509 (delete-other-windows)
13510 (split-window-vertically)
13511 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13512 (erase-buffer)
13513 (org-set-local 'org-done-keywords done-keywords)
13514 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13515 (org-fast-tag-insert "Current" current c-face "\n\n")
13516 (org-fast-tag-show-exit exit-after-next)
13517 (org-set-current-tags-overlay current ov-prefix)
13518 (setq tbl fulltable char ?a cnt 0)
13519 (while (setq e (pop tbl))
13520 (cond
13521 ((equal (car e) :startgroup)
13522 (push '() groups) (setq ingroup t)
13523 (when (not (= cnt 0))
13524 (setq cnt 0)
13525 (insert "\n"))
13526 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13527 ((equal (car e) :endgroup)
13528 (setq ingroup nil cnt 0)
13529 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13530 ((equal e '(:newline))
13531 (when (not (= cnt 0))
13532 (setq cnt 0)
13533 (insert "\n")
13534 (setq e (car tbl))
13535 (while (equal (car tbl) '(:newline))
13536 (insert "\n")
13537 (setq tbl (cdr tbl)))))
13539 (setq tg (copy-sequence (car e)) c2 nil)
13540 (if (cdr e)
13541 (setq c (cdr e))
13542 ;; automatically assign a character.
13543 (setq c1 (string-to-char
13544 (downcase (substring
13545 tg (if (= (string-to-char tg) ?@) 1 0)))))
13546 (if (or (rassoc c1 ntable) (rassoc c1 table))
13547 (while (or (rassoc char ntable) (rassoc char table))
13548 (setq char (1+ char)))
13549 (setq c2 c1))
13550 (setq c (or c2 char)))
13551 (if ingroup (push tg (car groups)))
13552 (setq tg (org-add-props tg nil 'face
13553 (cond
13554 ((not (assoc tg table))
13555 (org-get-todo-face tg))
13556 ((member tg current) c-face)
13557 ((member tg inherited) i-face)
13558 (t nil))))
13559 (if (and (= cnt 0) (not ingroup)) (insert " "))
13560 (insert "[" c "] " tg (make-string
13561 (- fwidth 4 (length tg)) ?\ ))
13562 (push (cons tg c) ntable)
13563 (when (= (setq cnt (1+ cnt)) ncol)
13564 (insert "\n")
13565 (if ingroup (insert " "))
13566 (setq cnt 0)))))
13567 (setq ntable (nreverse ntable))
13568 (insert "\n")
13569 (goto-char (point-min))
13570 (if (not expert) (org-fit-window-to-buffer))
13571 (setq rtn
13572 (catch 'exit
13573 (while t
13574 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13575 (if (not groups) "no " "")
13576 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13577 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13578 (setq org-last-tag-selection-key c)
13579 (cond
13580 ((= c ?\r) (throw 'exit t))
13581 ((= c ?!)
13582 (setq groups (not groups))
13583 (goto-char (point-min))
13584 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13585 ((= c ?\C-c)
13586 (if (not expert)
13587 (org-fast-tag-show-exit
13588 (setq exit-after-next (not exit-after-next)))
13589 (setq expert nil)
13590 (delete-other-windows)
13591 (set-window-buffer (split-window-vertically) " *Org tags*")
13592 (org-switch-to-buffer-other-window " *Org tags*")
13593 (org-fit-window-to-buffer)))
13594 ((or (= c ?\C-g)
13595 (and (= c ?q) (not (rassoc c ntable))))
13596 (org-detach-overlay org-tags-overlay)
13597 (setq quit-flag t))
13598 ((= c ?\ )
13599 (setq current nil)
13600 (if exit-after-next (setq exit-after-next 'now)))
13601 ((= c ?\t)
13602 (condition-case nil
13603 (setq tg (org-icompleting-read
13604 "Tag: "
13605 (or buffer-tags
13606 (with-current-buffer buf
13607 (org-get-buffer-tags)))))
13608 (quit (setq tg "")))
13609 (when (string-match "\\S-" tg)
13610 (add-to-list 'buffer-tags (list tg))
13611 (if (member tg current)
13612 (setq current (delete tg current))
13613 (push tg current)))
13614 (if exit-after-next (setq exit-after-next 'now)))
13615 ((setq e (rassoc c todo-table) tg (car e))
13616 (with-current-buffer buf
13617 (save-excursion (org-todo tg)))
13618 (if exit-after-next (setq exit-after-next 'now)))
13619 ((setq e (rassoc c ntable) tg (car e))
13620 (if (member tg current)
13621 (setq current (delete tg current))
13622 (loop for g in groups do
13623 (if (member tg g)
13624 (mapc (lambda (x)
13625 (setq current (delete x current)))
13626 g)))
13627 (push tg current))
13628 (if exit-after-next (setq exit-after-next 'now))))
13630 ;; Create a sorted list
13631 (setq current
13632 (sort current
13633 (lambda (a b)
13634 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13635 (if (eq exit-after-next 'now) (throw 'exit t))
13636 (goto-char (point-min))
13637 (beginning-of-line 2)
13638 (delete-region (point) (point-at-eol))
13639 (org-fast-tag-insert "Current" current c-face)
13640 (org-set-current-tags-overlay current ov-prefix)
13641 (while (re-search-forward
13642 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13643 (setq tg (match-string 1))
13644 (add-text-properties
13645 (match-beginning 1) (match-end 1)
13646 (list 'face
13647 (cond
13648 ((member tg current) c-face)
13649 ((member tg inherited) i-face)
13650 (t (get-text-property (match-beginning 1) 'face))))))
13651 (goto-char (point-min)))))
13652 (org-detach-overlay org-tags-overlay)
13653 (if rtn
13654 (mapconcat 'identity current ":")
13655 nil))))
13657 (defun org-get-tags-string ()
13658 "Get the TAGS string in the current headline."
13659 (unless (org-on-heading-p t)
13660 (error "Not on a heading"))
13661 (save-excursion
13662 (beginning-of-line 1)
13663 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13664 (org-match-string-no-properties 1)
13665 "")))
13667 (defun org-get-tags ()
13668 "Get the list of tags specified in the current headline."
13669 (org-split-string (org-get-tags-string) ":"))
13671 (defun org-get-buffer-tags ()
13672 "Get a table of all tags used in the buffer, for completion."
13673 (let (tags)
13674 (save-excursion
13675 (goto-char (point-min))
13676 (while (re-search-forward
13677 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13678 (when (equal (char-after (point-at-bol 0)) ?*)
13679 (mapc (lambda (x) (add-to-list 'tags x))
13680 (org-split-string (org-match-string-no-properties 1) ":")))))
13681 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13682 (mapcar 'list tags)))
13684 ;;;; The mapping API
13686 ;;;###autoload
13687 (defun org-map-entries (func &optional match scope &rest skip)
13688 "Call FUNC at each headline selected by MATCH in SCOPE.
13690 FUNC is a function or a lisp form. The function will be called without
13691 arguments, with the cursor positioned at the beginning of the headline.
13692 The return values of all calls to the function will be collected and
13693 returned as a list.
13695 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13696 does not need to preserve point. After evaluation, the cursor will be
13697 moved to the end of the line (presumably of the headline of the
13698 processed entry) and search continues from there. Under some
13699 circumstances, this may not produce the wanted results. For example,
13700 if you have removed (e.g. archived) the current (sub)tree it could
13701 mean that the next entry will be skipped entirely. In such cases, you
13702 can specify the position from where search should continue by making
13703 FUNC set the variable `org-map-continue-from' to the desired buffer
13704 position.
13706 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13707 Only headlines that are matched by this query will be considered during
13708 the iteration. When MATCH is nil or t, all headlines will be
13709 visited by the iteration.
13711 SCOPE determines the scope of this command. It can be any of:
13713 nil The current buffer, respecting the restriction if any
13714 tree The subtree started with the entry at point
13715 region The entries within the active region, if any
13716 file The current buffer, without restriction
13717 file-with-archives
13718 The current buffer, and any archives associated with it
13719 agenda All agenda files
13720 agenda-with-archives
13721 All agenda files with any archive files associated with them
13722 \(file1 file2 ...)
13723 If this is a list, all files in the list will be scanned
13725 The remaining args are treated as settings for the skipping facilities of
13726 the scanner. The following items can be given here:
13728 archive skip trees with the archive tag.
13729 comment skip trees with the COMMENT keyword
13730 function or Emacs Lisp form:
13731 will be used as value for `org-agenda-skip-function', so whenever
13732 the function returns t, FUNC will not be called for that
13733 entry and search will continue from the point where the
13734 function leaves it.
13736 If your function needs to retrieve the tags including inherited tags
13737 at the *current* entry, you can use the value of the variable
13738 `org-scanner-tags' which will be much faster than getting the value
13739 with `org-get-tags-at'. If your function gets properties with
13740 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13741 to t around the call to `org-entry-properties' to get the same speedup.
13742 Note that if your function moves around to retrieve tags and properties at
13743 a *different* entry, you cannot use these techniques."
13744 (unless (and (eq scope 'region) (not (org-region-active-p)))
13745 (let* ((org-agenda-archives-mode nil) ; just to make sure
13746 (org-agenda-skip-archived-trees (memq 'archive skip))
13747 (org-agenda-skip-comment-trees (memq 'comment skip))
13748 (org-agenda-skip-function
13749 (car (org-delete-all '(comment archive) skip)))
13750 (org-tags-match-list-sublevels t)
13751 matcher file res
13752 org-todo-keywords-for-agenda
13753 org-done-keywords-for-agenda
13754 org-todo-keyword-alist-for-agenda
13755 org-drawers-for-agenda
13756 org-tag-alist-for-agenda)
13758 (cond
13759 ((eq match t) (setq matcher t))
13760 ((eq match nil) (setq matcher t))
13761 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13763 (save-excursion
13764 (save-restriction
13765 (cond ((eq scope 'tree)
13766 (org-back-to-heading t)
13767 (org-narrow-to-subtree)
13768 (setq scope nil))
13769 ((and (eq scope 'region) (org-region-active-p))
13770 (narrow-to-region (region-beginning)
13771 (save-excursion
13772 (goto-char (region-end))
13773 (unless (and (bolp) (org-at-heading-p))
13774 (outline-next-heading))
13775 (point)))
13776 (setq scope nil)))
13778 (if (not scope)
13779 (progn
13780 (org-prepare-agenda-buffers
13781 (list (buffer-file-name (current-buffer))))
13782 (setq res (org-scan-tags func matcher)))
13783 ;; Get the right scope
13784 (cond
13785 ((and scope (listp scope) (symbolp (car scope)))
13786 (setq scope (eval scope)))
13787 ((eq scope 'agenda)
13788 (setq scope (org-agenda-files t)))
13789 ((eq scope 'agenda-with-archives)
13790 (setq scope (org-agenda-files t))
13791 (setq scope (org-add-archive-files scope)))
13792 ((eq scope 'file)
13793 (setq scope (list (buffer-file-name))))
13794 ((eq scope 'file-with-archives)
13795 (setq scope (org-add-archive-files (list (buffer-file-name))))))
13796 (org-prepare-agenda-buffers scope)
13797 (while (setq file (pop scope))
13798 (with-current-buffer (org-find-base-buffer-visiting file)
13799 (save-excursion
13800 (save-restriction
13801 (widen)
13802 (goto-char (point-min))
13803 (setq res (append res (org-scan-tags func matcher))))))))))
13804 res)))
13806 ;;;; Properties
13808 ;;; Setting and retrieving properties
13810 (defconst org-special-properties
13811 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
13812 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM")
13813 "The special properties valid in Org-mode.
13815 These are properties that are not defined in the property drawer,
13816 but in some other way.")
13818 (defconst org-default-properties
13819 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
13820 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
13821 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
13822 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
13823 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
13824 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
13825 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
13826 "Some properties that are used by Org-mode for various purposes.
13827 Being in this list makes sure that they are offered for completion.")
13829 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
13830 "Regular expression matching the first line of a property drawer.")
13832 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
13833 "Regular expression matching the last line of a property drawer.")
13835 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
13836 "Regular expression matching the first line of a property drawer.")
13838 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
13839 "Regular expression matching the first line of a property drawer.")
13841 (defconst org-property-drawer-re
13842 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
13843 org-property-end-re "\\)\n?")
13844 "Matches an entire property drawer.")
13846 (defconst org-clock-drawer-re
13847 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
13848 org-property-end-re "\\)\n?")
13849 "Matches an entire clock drawer.")
13851 (defsubst org-re-property (property)
13852 "Return a regexp matching PROPERTY.
13853 Match group 1 will be set to the value "
13854 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
13856 (defun org-property-action ()
13857 "Do an action on properties."
13858 (interactive)
13859 (let (c)
13860 (org-at-property-p)
13861 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
13862 (setq c (read-char-exclusive))
13863 (cond
13864 ((equal c ?s)
13865 (call-interactively 'org-set-property))
13866 ((equal c ?d)
13867 (call-interactively 'org-delete-property))
13868 ((equal c ?D)
13869 (call-interactively 'org-delete-property-globally))
13870 ((equal c ?c)
13871 (call-interactively 'org-compute-property-at-point))
13872 (t (error "No such property action %c" c)))))
13874 (defun org-set-effort (&optional value)
13875 "Set the effort property of the current entry.
13876 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
13877 allowed value."
13878 (interactive "P")
13879 (if (equal value 0) (setq value 10))
13880 (let* ((completion-ignore-case t)
13881 (prop org-effort-property)
13882 (cur (org-entry-get nil prop))
13883 (allowed (org-property-get-allowed-values nil prop 'table))
13884 (existing (mapcar 'list (org-property-values prop)))
13886 (val (cond
13887 ((stringp value) value)
13888 ((and allowed (integerp value))
13889 (or (car (nth (1- value) allowed))
13890 (car (org-last allowed))))
13891 (allowed
13892 (message "Select 1-9,0, [RET%s]: %s"
13893 (if cur (concat "=" cur) "")
13894 (mapconcat 'car allowed " "))
13895 (setq rpl (read-char-exclusive))
13896 (if (equal rpl ?\r)
13898 (setq rpl (- rpl ?0))
13899 (if (equal rpl 0) (setq rpl 10))
13900 (if (and (> rpl 0) (<= rpl (length allowed)))
13901 (car (nth (1- rpl) allowed))
13902 (org-completing-read "Effort: " allowed nil))))
13904 (let (org-completion-use-ido org-completion-use-iswitchb)
13905 (org-completing-read
13906 (concat "Effort " (if (and cur (string-match "\\S-" cur))
13907 (concat "[" cur "]") "")
13908 ": ")
13909 existing nil nil "" nil cur))))))
13910 (unless (equal (org-entry-get nil prop) val)
13911 (org-entry-put nil prop val))
13912 (message "%s is now %s" prop val)))
13914 (defun org-at-property-p ()
13915 "Is cursor inside a property drawer?"
13916 (save-excursion
13917 (beginning-of-line 1)
13918 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
13919 (save-match-data ;; Used by calling procedures
13920 (let ((p (point))
13921 (range (unless (org-before-first-heading-p)
13922 (org-get-property-block))))
13923 (and range (<= (car range) p) (< p (cdr range))))))))
13925 (defun org-get-property-block (&optional beg end force)
13926 "Return the (beg . end) range of the body of the property drawer.
13927 BEG and END can be beginning and end of subtree, if not given
13928 they will be found.
13929 If the drawer does not exist and FORCE is non-nil, create the drawer."
13930 (catch 'exit
13931 (save-excursion
13932 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
13933 (end (or end (progn (outline-next-heading) (point)))))
13934 (goto-char beg)
13935 (if (re-search-forward org-property-start-re end t)
13936 (setq beg (1+ (match-end 0)))
13937 (if force
13938 (save-excursion
13939 (org-insert-property-drawer)
13940 (setq end (progn (outline-next-heading) (point))))
13941 (throw 'exit nil))
13942 (goto-char beg)
13943 (if (re-search-forward org-property-start-re end t)
13944 (setq beg (1+ (match-end 0)))))
13945 (if (re-search-forward org-property-end-re end t)
13946 (setq end (match-beginning 0))
13947 (or force (throw 'exit nil))
13948 (goto-char beg)
13949 (setq end beg)
13950 (org-indent-line-function)
13951 (insert ":END:\n"))
13952 (cons beg end)))))
13954 (defun org-entry-properties (&optional pom which specific)
13955 "Get all properties of the entry at point-or-marker POM.
13956 This includes the TODO keyword, the tags, time strings for deadline,
13957 scheduled, and clocking, and any additional properties defined in the
13958 entry. The return value is an alist, keys may occur multiple times
13959 if the property key was used several times.
13960 POM may also be nil, in which case the current entry is used.
13961 If WHICH is nil or `all', get all properties. If WHICH is
13962 `special' or `standard', only get that subclass. If WHICH
13963 is a string only get exactly this property. SPECIFIC can be a string, the
13964 specific property we are interested in. Specifying it can speed
13965 things up because then unnecessary parsing is avoided."
13966 (setq which (or which 'all))
13967 (org-with-point-at pom
13968 (let ((clockstr (substring org-clock-string 0 -1))
13969 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
13970 (case-fold-search nil)
13971 beg end range props sum-props key key1 value string clocksum)
13972 (save-excursion
13973 (when (condition-case nil
13974 (and (eq major-mode 'org-mode) (org-back-to-heading t))
13975 (error nil))
13976 (setq beg (point))
13977 (setq sum-props (get-text-property (point) 'org-summaries))
13978 (setq clocksum (get-text-property (point) :org-clock-minutes))
13979 (outline-next-heading)
13980 (setq end (point))
13981 (when (memq which '(all special))
13982 ;; Get the special properties, like TODO and tags
13983 (goto-char beg)
13984 (when (and (or (not specific) (string= specific "TODO"))
13985 (looking-at org-todo-line-regexp) (match-end 2))
13986 (push (cons "TODO" (org-match-string-no-properties 2)) props))
13987 (when (and (or (not specific) (string= specific "PRIORITY"))
13988 (looking-at org-priority-regexp))
13989 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
13990 (when (or (not specific) (string= specific "FILE"))
13991 (push (cons "FILE" buffer-file-name) props))
13992 (when (and (or (not specific) (string= specific "TAGS"))
13993 (setq value (org-get-tags-string))
13994 (string-match "\\S-" value))
13995 (push (cons "TAGS" value) props))
13996 (when (and (or (not specific) (string= specific "ALLTAGS"))
13997 (setq value (org-get-tags-at)))
13998 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
13999 ":"))
14000 props))
14001 (when (or (not specific) (string= specific "BLOCKED"))
14002 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14003 (when (or (not specific)
14004 (member specific
14005 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14006 "TIMESTAMP" "TIMESTAMP_IA")))
14007 (catch 'match
14008 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14009 (setq key (if (match-end 1)
14010 (substring (org-match-string-no-properties 1)
14011 0 -1))
14012 string (if (equal key clockstr)
14013 (org-no-properties
14014 (org-trim
14015 (buffer-substring
14016 (match-beginning 3) (goto-char
14017 (point-at-eol)))))
14018 (substring (org-match-string-no-properties 3)
14019 1 -1)))
14020 ;; Get the correct property name from the key. This is
14021 ;; necessary if the user has configured time keywords.
14022 (setq key1 (concat key ":"))
14023 (cond
14024 ((not key)
14025 (setq key
14026 (if (= (char-after (match-beginning 3)) ?\[)
14027 "TIMESTAMP_IA" "TIMESTAMP")))
14028 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14029 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14030 ((equal key1 org-closed-string) (setq key "CLOSED"))
14031 ((equal key1 org-clock-string) (setq key "CLOCK")))
14032 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14033 (progn
14034 (push (cons key string) props)
14035 ;; no need to search further if match is found
14036 (throw 'match t))
14037 (when (or (equal key "CLOCK") (not (assoc key props)))
14038 (push (cons key string) props))))))
14041 (when (memq which '(all standard))
14042 ;; Get the standard properties, like :PROP: ...
14043 (setq range (org-get-property-block beg end))
14044 (when range
14045 (goto-char (car range))
14046 (while (re-search-forward
14047 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14048 (cdr range) t)
14049 (setq key (org-match-string-no-properties 1)
14050 value (org-trim (or (org-match-string-no-properties 2) "")))
14051 (unless (member key excluded)
14052 (push (cons key (or value "")) props)))))
14053 (if clocksum
14054 (push (cons "CLOCKSUM"
14055 (org-columns-number-to-string (/ (float clocksum) 60.)
14056 'add_times))
14057 props))
14058 (unless (assoc "CATEGORY" props)
14059 (push (cons "CATEGORY" (org-get-category)) props))
14060 (append sum-props (nreverse props)))))))
14062 (defun org-entry-get (pom property &optional inherit literal-nil)
14063 "Get value of PROPERTY for entry at point-or-marker POM.
14064 If INHERIT is non-nil and the entry does not have the property,
14065 then also check higher levels of the hierarchy.
14066 If INHERIT is the symbol `selective', use inheritance only if the setting
14067 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14068 If the property is present but empty, the return value is the empty string.
14069 If the property is not present at all, nil is returned.
14071 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14072 do not interpret it as the list atom nil. This is used for inheritance
14073 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14074 (org-with-point-at pom
14075 (if (and inherit (if (eq inherit 'selective)
14076 (org-property-inherit-p property)
14078 (org-entry-get-with-inheritance property literal-nil)
14079 (if (member property org-special-properties)
14080 ;; We need a special property. Use `org-entry-properties' to
14081 ;; retrieve it, but specify the wanted property
14082 (cdr (assoc property (org-entry-properties nil 'special property)))
14083 (let ((range (unless (org-before-first-heading-p)
14084 (org-get-property-block))))
14085 (if (and range
14086 (goto-char (car range))
14087 (re-search-forward
14088 (org-re-property property)
14089 (cdr range) t))
14090 ;; Found the property, return it.
14091 (if (match-end 1)
14092 (if literal-nil
14093 (org-match-string-no-properties 1)
14094 (org-not-nil (org-match-string-no-properties 1)))
14095 "")))))))
14097 (defun org-property-or-variable-value (var &optional inherit)
14098 "Check if there is a property fixing the value of VAR.
14099 If yes, return this value. If not, return the current value of the variable."
14100 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14101 (if (and prop (stringp prop) (string-match "\\S-" prop))
14102 (read prop)
14103 (symbol-value var))))
14105 (defun org-entry-delete (pom property)
14106 "Delete the property PROPERTY from entry at point-or-marker POM."
14107 (org-with-point-at pom
14108 (if (member property org-special-properties)
14109 nil ; cannot delete these properties.
14110 (let ((range (org-get-property-block)))
14111 (if (and range
14112 (goto-char (car range))
14113 (re-search-forward
14114 (org-re-property property)
14115 (cdr range) t))
14116 (progn
14117 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14119 nil)))))
14121 ;; Multi-values properties are properties that contain multiple values
14122 ;; These values are assumed to be single words, separated by whitespace.
14123 (defun org-entry-add-to-multivalued-property (pom property value)
14124 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14125 (let* ((old (org-entry-get pom property))
14126 (values (and old (org-split-string old "[ \t]"))))
14127 (setq value (org-entry-protect-space value))
14128 (unless (member value values)
14129 (setq values (cons value values))
14130 (org-entry-put pom property
14131 (mapconcat 'identity values " ")))))
14133 (defun org-entry-remove-from-multivalued-property (pom property value)
14134 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14135 (let* ((old (org-entry-get pom property))
14136 (values (and old (org-split-string old "[ \t]"))))
14137 (setq value (org-entry-protect-space value))
14138 (when (member value values)
14139 (setq values (delete value values))
14140 (org-entry-put pom property
14141 (mapconcat 'identity values " ")))))
14143 (defun org-entry-member-in-multivalued-property (pom property value)
14144 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14145 (let* ((old (org-entry-get pom property))
14146 (values (and old (org-split-string old "[ \t]"))))
14147 (setq value (org-entry-protect-space value))
14148 (member value values)))
14150 (defun org-entry-get-multivalued-property (pom property)
14151 "Return a list of values in a multivalued property."
14152 (let* ((value (org-entry-get pom property))
14153 (values (and value (org-split-string value "[ \t]"))))
14154 (mapcar 'org-entry-restore-space values)))
14156 (defun org-entry-put-multivalued-property (pom property &rest values)
14157 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14158 VALUES should be a list of strings. Spaces will be protected."
14159 (org-entry-put pom property
14160 (mapconcat 'org-entry-protect-space values " "))
14161 (let* ((value (org-entry-get pom property))
14162 (values (and value (org-split-string value "[ \t]"))))
14163 (mapcar 'org-entry-restore-space values)))
14165 (defun org-entry-protect-space (s)
14166 "Protect spaces and newline in string S."
14167 (while (string-match " " s)
14168 (setq s (replace-match "%20" t t s)))
14169 (while (string-match "\n" s)
14170 (setq s (replace-match "%0A" t t s)))
14173 (defun org-entry-restore-space (s)
14174 "Restore spaces and newline in string S."
14175 (while (string-match "%20" s)
14176 (setq s (replace-match " " t t s)))
14177 (while (string-match "%0A" s)
14178 (setq s (replace-match "\n" t t s)))
14181 (defvar org-entry-property-inherited-from (make-marker)
14182 "Marker pointing to the entry from where a property was inherited.
14183 Each call to `org-entry-get-with-inheritance' will set this marker to the
14184 location of the entry where the inheritance search matched. If there was
14185 no match, the marker will point nowhere.
14186 Note that also `org-entry-get' calls this function, if the INHERIT flag
14187 is set.")
14189 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14190 "Get entry property, and search higher levels if not present.
14191 The search will stop at the first ancestor which has the property defined.
14192 If the value found is \"nil\", return nil to show that the property
14193 should be considered as undefined (this is the meaning of nil here).
14194 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14195 (move-marker org-entry-property-inherited-from nil)
14196 (let (tmp)
14197 (unless (org-before-first-heading-p)
14198 (save-excursion
14199 (save-restriction
14200 (widen)
14201 (catch 'ex
14202 (while t
14203 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14204 (org-back-to-heading t)
14205 (move-marker org-entry-property-inherited-from (point))
14206 (throw 'ex tmp))
14207 (or (org-up-heading-safe) (throw 'ex nil)))))))
14208 (setq tmp (or tmp
14209 (cdr (assoc property org-file-properties))
14210 (cdr (assoc property org-global-properties))
14211 (cdr (assoc property org-global-properties-fixed))))
14212 (if literal-nil tmp (org-not-nil tmp))))
14214 (defvar org-property-changed-functions nil
14215 "Hook called when the value of a property has changed.
14216 Each hook function should accept two arguments, the name of the property
14217 and the new value.")
14219 (defun org-entry-put (pom property value)
14220 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14221 (org-with-point-at pom
14222 (org-back-to-heading t)
14223 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14224 range)
14225 (cond
14226 ((equal property "TODO")
14227 (when (and (stringp value) (string-match "\\S-" value)
14228 (not (member value org-todo-keywords-1)))
14229 (error "\"%s\" is not a valid TODO state" value))
14230 (if (or (not value)
14231 (not (string-match "\\S-" value)))
14232 (setq value 'none))
14233 (org-todo value)
14234 (org-set-tags nil 'align))
14235 ((equal property "PRIORITY")
14236 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14237 (string-to-char value) ?\ ))
14238 (org-set-tags nil 'align))
14239 ((equal property "SCHEDULED")
14240 (if (re-search-forward org-scheduled-time-regexp end t)
14241 (cond
14242 ((eq value 'earlier) (org-timestamp-change -1 'day))
14243 ((eq value 'later) (org-timestamp-change 1 'day))
14244 (t (call-interactively 'org-schedule)))
14245 (call-interactively 'org-schedule)))
14246 ((equal property "DEADLINE")
14247 (if (re-search-forward org-deadline-time-regexp end t)
14248 (cond
14249 ((eq value 'earlier) (org-timestamp-change -1 'day))
14250 ((eq value 'later) (org-timestamp-change 1 'day))
14251 (t (call-interactively 'org-deadline)))
14252 (call-interactively 'org-deadline)))
14253 ((member property org-special-properties)
14254 (error "The %s property can not yet be set with `org-entry-put'"
14255 property))
14256 (t ; a non-special property
14257 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14258 (setq range (org-get-property-block beg end 'force))
14259 (goto-char (car range))
14260 (if (re-search-forward
14261 (org-re-property property) (cdr range) t)
14262 (progn
14263 (delete-region (match-beginning 0) (match-end 0))
14264 (goto-char (match-beginning 0)))
14265 (goto-char (cdr range))
14266 (insert "\n")
14267 (backward-char 1)
14268 (org-indent-line-function))
14269 (insert ":" property ":")
14270 (and value (insert " " value))
14271 (org-indent-line-function)))))
14272 (run-hook-with-args 'org-property-changed-functions property value)))
14274 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14275 "Get all property keys in the current buffer.
14276 With INCLUDE-SPECIALS, also list the special properties that reflect things
14277 like tags and TODO state.
14278 With INCLUDE-DEFAULTS, also include properties that has special meaning
14279 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14280 and others.
14281 With INCLUDE-COLUMNS, also include property names given in COLUMN
14282 formats in the current buffer."
14283 (let (rtn range cfmt s p)
14284 (save-excursion
14285 (save-restriction
14286 (widen)
14287 (goto-char (point-min))
14288 (while (re-search-forward org-property-start-re nil t)
14289 (setq range (org-get-property-block))
14290 (goto-char (car range))
14291 (while (re-search-forward
14292 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14293 (cdr range) t)
14294 (add-to-list 'rtn (org-match-string-no-properties 1)))
14295 (outline-next-heading))))
14297 (when include-specials
14298 (setq rtn (append org-special-properties rtn)))
14300 (when include-defaults
14301 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14302 (add-to-list 'rtn org-effort-property))
14304 (when include-columns
14305 (save-excursion
14306 (save-restriction
14307 (widen)
14308 (goto-char (point-min))
14309 (while (re-search-forward
14310 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14311 nil t)
14312 (setq cfmt (match-string 2) s 0)
14313 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14314 cfmt s)
14315 (setq s (match-end 0)
14316 p (match-string 1 cfmt))
14317 (unless (or (equal p "ITEM")
14318 (member p org-special-properties))
14319 (add-to-list 'rtn (match-string 1 cfmt))))))))
14321 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14323 (defun org-property-values (key)
14324 "Return a list of all values of property KEY in the current buffer."
14325 (save-excursion
14326 (save-restriction
14327 (widen)
14328 (goto-char (point-min))
14329 (let ((re (org-re-property key))
14330 values)
14331 (while (re-search-forward re nil t)
14332 (add-to-list 'values (org-trim (match-string 1))))
14333 (delete "" values)))))
14335 (defun org-insert-property-drawer ()
14336 "Insert a property drawer into the current entry."
14337 (interactive)
14338 (org-back-to-heading t)
14339 (looking-at org-outline-regexp)
14340 (let ((indent (if org-adapt-indentation
14341 (- (match-end 0)(match-beginning 0))
14343 (beg (point))
14344 (re (concat "^[ \t]*" org-keyword-time-regexp))
14345 end hiddenp)
14346 (outline-next-heading)
14347 (setq end (point))
14348 (goto-char beg)
14349 (while (re-search-forward re end t))
14350 (setq hiddenp (outline-invisible-p))
14351 (end-of-line 1)
14352 (and (equal (char-after) ?\n) (forward-char 1))
14353 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14354 (if (member (match-string 1) '("CLOCK:" ":END:"))
14355 ;; just skip this line
14356 (beginning-of-line 2)
14357 ;; Drawer start, find the end
14358 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14359 (beginning-of-line 1)))
14360 (org-skip-over-state-notes)
14361 (skip-chars-backward " \t\n\r")
14362 (if (eq (char-before) ?*) (forward-char 1))
14363 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14364 (beginning-of-line 0)
14365 (org-indent-to-column indent)
14366 (beginning-of-line 2)
14367 (org-indent-to-column indent)
14368 (beginning-of-line 0)
14369 (if hiddenp
14370 (save-excursion
14371 (org-back-to-heading t)
14372 (hide-entry))
14373 (org-flag-drawer t))))
14375 (defvar org-property-set-functions-alist nil
14376 "Property set function alist.
14377 Each entry should have the following format:
14379 (PROPERTY . READ-FUNCTION)
14381 The read function will be called with the same argument as
14382 `org-completing-read'.")
14384 (defun org-set-property-function (property)
14385 "Get the function that should be used to set PROPERTY.
14386 This is computed according to `org-property-set-functions-alist'."
14387 (or (cdr (assoc property org-property-set-functions-alist))
14388 'org-completing-read))
14390 (defun org-read-property-value (property)
14391 "Read PROPERTY value from user."
14392 (let* ((completion-ignore-case t)
14393 (allowed (org-property-get-allowed-values nil property 'table))
14394 (cur (org-entry-get nil property))
14395 (prompt (concat property " value"
14396 (if (and cur (string-match "\\S-" cur))
14397 (concat " [" cur "]") "") ": "))
14398 (set-function (org-set-property-function property))
14399 (val (if allowed
14400 (funcall set-function prompt allowed nil
14401 (not (get-text-property 0 'org-unrestricted
14402 (caar allowed))))
14403 (let (org-completion-use-ido org-completion-use-iswitchb)
14404 (funcall set-function prompt
14405 (mapcar 'list (org-property-values property))
14406 nil nil "" nil cur)))))
14407 (if (equal val "")
14409 val)))
14411 (defvar org-last-set-property nil)
14412 (defun org-read-property-name ()
14413 "Read a property name."
14414 (let* ((completion-ignore-case t)
14415 (keys (org-buffer-property-keys nil t t))
14416 (default-prop (or (save-excursion
14417 (save-match-data
14418 (beginning-of-line)
14419 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14420 (null (string= (match-string 1) "END"))
14421 (match-string 1))))
14422 org-last-set-property))
14423 (property (org-icompleting-read
14424 (concat "Property"
14425 (if default-prop (concat " [" default-prop "]") "")
14426 ": ")
14427 (mapcar 'list keys)
14428 nil nil nil nil
14429 default-prop
14431 (if (member property keys)
14432 property
14433 (or (cdr (assoc (downcase property)
14434 (mapcar (lambda (x) (cons (downcase x) x))
14435 keys)))
14436 property))))
14438 (defun org-set-property (property value)
14439 "In the current entry, set PROPERTY to VALUE.
14440 When called interactively, this will prompt for a property name, offering
14441 completion on existing and default properties. And then it will prompt
14442 for a value, offering completion either on allowed values (via an inherited
14443 xxx_ALL property) or on existing values in other instances of this property
14444 in the current file."
14445 (interactive (list nil nil))
14446 (let* ((property (or property (org-read-property-name)))
14447 (value (or value (org-read-property-value property)))
14448 (fn (assoc property org-properties-postprocess-alist)))
14449 (setq org-last-set-property property)
14450 ;; Possibly postprocess the inserted value:
14451 (when fn (setq value (funcall (cadr fn) value)))
14452 (unless (equal (org-entry-get nil property) value)
14453 (org-entry-put nil property value))))
14455 (defun org-delete-property (property)
14456 "In the current entry, delete PROPERTY."
14457 (interactive
14458 (let* ((completion-ignore-case t)
14459 (prop (org-icompleting-read "Property: "
14460 (org-entry-properties nil 'standard))))
14461 (list prop)))
14462 (message "Property %s %s" property
14463 (if (org-entry-delete nil property)
14464 "deleted"
14465 "was not present in the entry")))
14467 (defun org-delete-property-globally (property)
14468 "Remove PROPERTY globally, from all entries."
14469 (interactive
14470 (let* ((completion-ignore-case t)
14471 (prop (org-icompleting-read
14472 "Globally remove property: "
14473 (mapcar 'list (org-buffer-property-keys)))))
14474 (list prop)))
14475 (save-excursion
14476 (save-restriction
14477 (widen)
14478 (goto-char (point-min))
14479 (let ((cnt 0))
14480 (while (re-search-forward
14481 (org-re-property property)
14482 nil t)
14483 (setq cnt (1+ cnt))
14484 (replace-match ""))
14485 (message "Property \"%s\" removed from %d entries" property cnt)))))
14487 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14489 (defun org-compute-property-at-point ()
14490 "Compute the property at point.
14491 This looks for an enclosing column format, extracts the operator and
14492 then applies it to the property in the column format's scope."
14493 (interactive)
14494 (unless (org-at-property-p)
14495 (error "Not at a property"))
14496 (let ((prop (org-match-string-no-properties 2)))
14497 (org-columns-get-format-and-top-level)
14498 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14499 (error "No operator defined for property %s" prop))
14500 (org-columns-compute prop)))
14502 (defvar org-property-allowed-value-functions nil
14503 "Hook for functions supplying allowed values for a specific property.
14504 The functions must take a single argument, the name of the property, and
14505 return a flat list of allowed values. If \":ETC\" is one of
14506 the values, this means that these values are intended as defaults for
14507 completion, but that other values should be allowed too.
14508 The functions must return nil if they are not responsible for this
14509 property.")
14511 (defun org-property-get-allowed-values (pom property &optional table)
14512 "Get allowed values for the property PROPERTY.
14513 When TABLE is non-nil, return an alist that can directly be used for
14514 completion."
14515 (let (vals)
14516 (cond
14517 ((equal property "TODO")
14518 (setq vals (org-with-point-at pom
14519 (append org-todo-keywords-1 '("")))))
14520 ((equal property "PRIORITY")
14521 (let ((n org-lowest-priority))
14522 (while (>= n org-highest-priority)
14523 (push (char-to-string n) vals)
14524 (setq n (1- n)))))
14525 ((member property org-special-properties))
14526 ((setq vals (run-hook-with-args-until-success
14527 'org-property-allowed-value-functions property)))
14529 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14530 (when (and vals (string-match "\\S-" vals))
14531 (setq vals (car (read-from-string (concat "(" vals ")"))))
14532 (setq vals (mapcar (lambda (x)
14533 (cond ((stringp x) x)
14534 ((numberp x) (number-to-string x))
14535 ((symbolp x) (symbol-name x))
14536 (t "???")))
14537 vals)))))
14538 (when (member ":ETC" vals)
14539 (setq vals (remove ":ETC" vals))
14540 (org-add-props (car vals) '(org-unrestricted t)))
14541 (if table (mapcar 'list vals) vals)))
14543 (defun org-property-previous-allowed-value (&optional previous)
14544 "Switch to the next allowed value for this property."
14545 (interactive)
14546 (org-property-next-allowed-value t))
14548 (defun org-property-next-allowed-value (&optional previous)
14549 "Switch to the next allowed value for this property."
14550 (interactive)
14551 (unless (org-at-property-p)
14552 (error "Not at a property"))
14553 (let* ((key (match-string 2))
14554 (value (match-string 3))
14555 (allowed (or (org-property-get-allowed-values (point) key)
14556 (and (member value '("[ ]" "[-]" "[X]"))
14557 '("[ ]" "[X]"))))
14558 nval)
14559 (unless allowed
14560 (error "Allowed values for this property have not been defined"))
14561 (if previous (setq allowed (reverse allowed)))
14562 (if (member value allowed)
14563 (setq nval (car (cdr (member value allowed)))))
14564 (setq nval (or nval (car allowed)))
14565 (if (equal nval value)
14566 (error "Only one allowed value for this property"))
14567 (org-at-property-p)
14568 (replace-match (concat " :" key ": " nval) t t)
14569 (org-indent-line-function)
14570 (beginning-of-line 1)
14571 (skip-chars-forward " \t")
14572 (run-hook-with-args 'org-property-changed-functions key nval)))
14574 (defun org-find-olp (path &optional this-buffer)
14575 "Return a marker pointing to the entry at outline path OLP.
14576 If anything goes wrong, throw an error.
14577 You can wrap this call to catch the error like this:
14579 (condition-case msg
14580 (org-mobile-locate-entry (match-string 4))
14581 (error (nth 1 msg)))
14583 The return value will then be either a string with the error message,
14584 or a marker if everything is OK.
14586 If THIS-BUFFER is set, the outline path does not contain a file,
14587 only headings."
14588 (let* ((file (if this-buffer buffer-file-name (pop path)))
14589 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14590 (level 1)
14591 (lmin 1)
14592 (lmax 1)
14593 limit re end found pos heading cnt flevel)
14594 (unless buffer (error "File not found :%s" file))
14595 (with-current-buffer buffer
14596 (save-excursion
14597 (save-restriction
14598 (widen)
14599 (setq limit (point-max))
14600 (goto-char (point-min))
14601 (while (setq heading (pop path))
14602 (setq re (format org-complex-heading-regexp-format
14603 (regexp-quote heading)))
14604 (setq cnt 0 pos (point))
14605 (while (re-search-forward re end t)
14606 (setq level (- (match-end 1) (match-beginning 1)))
14607 (if (and (>= level lmin) (<= level lmax))
14608 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
14609 (when (= cnt 0) (error "Heading not found on level %d: %s"
14610 lmax heading))
14611 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14612 lmax heading))
14613 (goto-char found)
14614 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
14615 (setq end (save-excursion (org-end-of-subtree t t))))
14616 (when (org-on-heading-p)
14617 (move-marker (make-marker) (point))))))))
14619 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14620 "Find node HEADING in BUFFER.
14621 Return a marker to the heading if it was found, or nil if not.
14622 If POS-ONLY is set, return just the position instead of a marker.
14624 The heading text must match exact, but it may have a TODO keyword,
14625 a priority cookie and tags in the standard locations."
14626 (with-current-buffer (or buffer (current-buffer))
14627 (save-excursion
14628 (save-restriction
14629 (widen)
14630 (goto-char (point-min))
14631 (let (case-fold-search)
14632 (if (re-search-forward
14633 (format org-complex-heading-regexp-format
14634 (regexp-quote heading)) nil t)
14635 (if pos-only
14636 (match-beginning 0)
14637 (move-marker (make-marker) (match-beginning 0)))))))))
14639 (defun org-find-exact-heading-in-directory (heading &optional dir)
14640 "Find Org node headline HEADING in all .org files in directory DIR.
14641 When the target headline is found, return a marker to this location."
14642 (let ((files (directory-files (or dir default-directory)
14643 nil "\\`[^.#].*\\.org\\'"))
14644 file visiting m buffer)
14645 (catch 'found
14646 (while (setq file (pop files))
14647 (message "trying %s" file)
14648 (setq visiting (org-find-base-buffer-visiting file))
14649 (setq buffer (or visiting (find-file-noselect file)))
14650 (setq m (org-find-exact-headline-in-buffer
14651 heading buffer))
14652 (when (and (not m) (not visiting)) (kill-buffer buffer))
14653 (and m (throw 'found m))))))
14655 (defun org-find-entry-with-id (ident)
14656 "Locate the entry that contains the ID property with exact value IDENT.
14657 IDENT can be a string, a symbol or a number, this function will search for
14658 the string representation of it.
14659 Return the position where this entry starts, or nil if there is no such entry."
14660 (interactive "sID: ")
14661 (let ((id (cond
14662 ((stringp ident) ident)
14663 ((symbol-name ident) (symbol-name ident))
14664 ((numberp ident) (number-to-string ident))
14665 (t (error "IDENT %s must be a string, symbol or number" ident))))
14666 (case-fold-search nil))
14667 (save-excursion
14668 (save-restriction
14669 (widen)
14670 (goto-char (point-min))
14671 (when (re-search-forward
14672 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
14673 nil t)
14674 (org-back-to-heading t)
14675 (point))))))
14677 ;;;; Timestamps
14679 (defvar org-last-changed-timestamp nil)
14680 (defvar org-last-inserted-timestamp nil
14681 "The last time stamp inserted with `org-insert-time-stamp'.")
14682 (defvar org-time-was-given) ; dynamically scoped parameter
14683 (defvar org-end-time-was-given) ; dynamically scoped parameter
14684 (defvar org-ts-what) ; dynamically scoped parameter
14686 (defun org-time-stamp (arg &optional inactive)
14687 "Prompt for a date/time and insert a time stamp.
14688 If the user specifies a time like HH:MM, or if this command is called
14689 with a prefix argument, the time stamp will contain date and time.
14690 Otherwise, only the date will be included. All parts of a date not
14691 specified by the user will be filled in from the current date/time.
14692 So if you press just return without typing anything, the time stamp
14693 will represent the current date/time. If there is already a timestamp
14694 at the cursor, it will be modified."
14695 (interactive "P")
14696 (let* ((ts nil)
14697 (default-time
14698 ;; Default time is either today, or, when entering a range,
14699 ;; the range start.
14700 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
14701 (save-excursion
14702 (re-search-backward
14703 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
14704 (- (point) 20) t)))
14705 (apply 'encode-time (org-parse-time-string (match-string 1)))
14706 (current-time)))
14707 (default-input (and ts (org-get-compact-tod ts)))
14708 (repeater (save-excursion
14709 (save-match-data
14710 (beginning-of-line)
14711 (when (re-search-forward
14712 "\\([.+-]+[0-9]+[dwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
14713 (save-excursion (progn (end-of-line) (point))) t)
14714 (match-string 0)))))
14715 org-time-was-given org-end-time-was-given time)
14716 (cond
14717 ((and (org-at-timestamp-p t)
14718 (memq last-command '(org-time-stamp org-time-stamp-inactive))
14719 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
14720 (insert "--")
14721 (setq time (let ((this-command this-command))
14722 (org-read-date arg 'totime nil nil
14723 default-time default-input)))
14724 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
14725 ((org-at-timestamp-p t)
14726 (setq time (let ((this-command this-command))
14727 (org-read-date arg 'totime nil nil default-time default-input)))
14728 (when (org-at-timestamp-p t) ; just to get the match data
14729 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
14730 (replace-match "")
14731 (setq org-last-changed-timestamp
14732 (org-insert-time-stamp
14733 time (or org-time-was-given arg)
14734 inactive nil nil (list org-end-time-was-given)))
14735 (when repeater (goto-char (1- (point))) (insert " " repeater)
14736 (setq org-last-changed-timestamp
14737 (concat (substring org-last-inserted-timestamp 0 -1)
14738 " " repeater ">"))))
14739 (message "Timestamp updated"))
14741 (setq time (let ((this-command this-command))
14742 (org-read-date arg 'totime nil nil default-time default-input)))
14743 (org-insert-time-stamp time (or org-time-was-given arg) inactive
14744 nil nil (list org-end-time-was-given))))))
14746 ;; FIXME: can we use this for something else, like computing time differences?
14747 (defun org-get-compact-tod (s)
14748 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
14749 (let* ((t1 (match-string 1 s))
14750 (h1 (string-to-number (match-string 2 s)))
14751 (m1 (string-to-number (match-string 3 s)))
14752 (t2 (and (match-end 4) (match-string 5 s)))
14753 (h2 (and t2 (string-to-number (match-string 6 s))))
14754 (m2 (and t2 (string-to-number (match-string 7 s))))
14755 dh dm)
14756 (if (not t2)
14758 (setq dh (- h2 h1) dm (- m2 m1))
14759 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
14760 (concat t1 "+" (number-to-string dh)
14761 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
14763 (defun org-time-stamp-inactive (&optional arg)
14764 "Insert an inactive time stamp.
14765 An inactive time stamp is enclosed in square brackets instead of angle
14766 brackets. It is inactive in the sense that it does not trigger agenda entries,
14767 does not link to the calendar and cannot be changed with the S-cursor keys.
14768 So these are more for recording a certain time/date."
14769 (interactive "P")
14770 (org-time-stamp arg 'inactive))
14772 (defvar org-date-ovl (make-overlay 1 1))
14773 (overlay-put org-date-ovl 'face 'org-warning)
14774 (org-detach-overlay org-date-ovl)
14776 (defvar org-ans1) ; dynamically scoped parameter
14777 (defvar org-ans2) ; dynamically scoped parameter
14779 (defvar org-plain-time-of-day-regexp) ; defined below
14781 (defvar org-overriding-default-time nil) ; dynamically scoped
14782 (defvar org-read-date-overlay nil)
14783 (defvar org-dcst nil) ; dynamically scoped
14784 (defvar org-read-date-history nil)
14785 (defvar org-read-date-final-answer nil)
14786 (defvar org-read-date-analyze-futurep nil)
14787 (defvar org-read-date-analyze-forced-year nil)
14789 (defun org-read-date (&optional with-time to-time from-string prompt
14790 default-time default-input)
14791 "Read a date, possibly a time, and make things smooth for the user.
14792 The prompt will suggest to enter an ISO date, but you can also enter anything
14793 which will at least partially be understood by `parse-time-string'.
14794 Unrecognized parts of the date will default to the current day, month, year,
14795 hour and minute. If this command is called to replace a timestamp at point,
14796 of to enter the second timestamp of a range, the default time is taken
14797 from the existing stamp. Furthermore, the command prefers the future,
14798 so if you are giving a date where the year is not given, and the day-month
14799 combination is already past in the current year, it will assume you
14800 mean next year. For details, see the manual. A few examples:
14802 3-2-5 --> 2003-02-05
14803 feb 15 --> currentyear-02-15
14804 2/15 --> currentyear-02-15
14805 sep 12 9 --> 2009-09-12
14806 12:45 --> today 12:45
14807 22 sept 0:34 --> currentyear-09-22 0:34
14808 12 --> currentyear-currentmonth-12
14809 Fri --> nearest Friday (today or later)
14810 etc.
14812 Furthermore you can specify a relative date by giving, as the *first* thing
14813 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
14814 change in days weeks, months, years.
14815 With a single plus or minus, the date is relative to today. With a double
14816 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
14817 +4d --> four days from today
14818 +4 --> same as above
14819 +2w --> two weeks from today
14820 ++5 --> five days from default date
14822 The function understands only English month and weekday abbreviations,
14823 but this can be configured with the variables `parse-time-months' and
14824 `parse-time-weekdays'.
14826 While prompting, a calendar is popped up - you can also select the
14827 date with the mouse (button 1). The calendar shows a period of three
14828 months. To scroll it to other months, use the keys `>' and `<'.
14829 If you don't like the calendar, turn it off with
14830 \(setq org-read-date-popup-calendar nil)
14832 With optional argument TO-TIME, the date will immediately be converted
14833 to an internal time.
14834 With an optional argument WITH-TIME, the prompt will suggest to also
14835 insert a time. Note that when WITH-TIME is not set, you can still
14836 enter a time, and this function will inform the calling routine about
14837 this change. The calling routine may then choose to change the format
14838 used to insert the time stamp into the buffer to include the time.
14839 With optional argument FROM-STRING, read from this string instead from
14840 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
14841 the time/date that is used for everything that is not specified by the
14842 user."
14843 (require 'parse-time)
14844 (let* ((org-time-stamp-rounding-minutes
14845 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
14846 (org-dcst org-display-custom-times)
14847 (ct (org-current-time))
14848 (def (or org-overriding-default-time default-time ct))
14849 (defdecode (decode-time def))
14850 (dummy (progn
14851 (when (< (nth 2 defdecode) org-extend-today-until)
14852 (setcar (nthcdr 2 defdecode) -1)
14853 (setcar (nthcdr 1 defdecode) 59)
14854 (setq def (apply 'encode-time defdecode)
14855 defdecode (decode-time def)))))
14856 (calendar-frame-setup nil)
14857 (calendar-setup nil)
14858 (calendar-move-hook nil)
14859 (calendar-view-diary-initially-flag nil)
14860 (calendar-view-holidays-initially-flag nil)
14861 (timestr (format-time-string
14862 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
14863 (prompt (concat (if prompt (concat prompt " ") "")
14864 (format "Date+time [%s]: " timestr)))
14865 ans (org-ans0 "") org-ans1 org-ans2 final)
14867 (cond
14868 (from-string (setq ans from-string))
14869 (org-read-date-popup-calendar
14870 (save-excursion
14871 (save-window-excursion
14872 (calendar)
14873 (unwind-protect
14874 (progn
14875 (calendar-forward-day (- (time-to-days def)
14876 (calendar-absolute-from-gregorian
14877 (calendar-current-date))))
14878 (org-eval-in-calendar nil t)
14879 (let* ((old-map (current-local-map))
14880 (map (copy-keymap calendar-mode-map))
14881 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
14882 (org-defkey map (kbd "RET") 'org-calendar-select)
14883 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
14884 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
14885 (org-defkey minibuffer-local-map [(meta shift left)]
14886 (lambda () (interactive)
14887 (org-eval-in-calendar '(calendar-backward-month 1))))
14888 (org-defkey minibuffer-local-map [(meta shift right)]
14889 (lambda () (interactive)
14890 (org-eval-in-calendar '(calendar-forward-month 1))))
14891 (org-defkey minibuffer-local-map [(meta shift up)]
14892 (lambda () (interactive)
14893 (org-eval-in-calendar '(calendar-backward-year 1))))
14894 (org-defkey minibuffer-local-map [(meta shift down)]
14895 (lambda () (interactive)
14896 (org-eval-in-calendar '(calendar-forward-year 1))))
14897 (org-defkey minibuffer-local-map [?\e (shift left)]
14898 (lambda () (interactive)
14899 (org-eval-in-calendar '(calendar-backward-month 1))))
14900 (org-defkey minibuffer-local-map [?\e (shift right)]
14901 (lambda () (interactive)
14902 (org-eval-in-calendar '(calendar-forward-month 1))))
14903 (org-defkey minibuffer-local-map [?\e (shift up)]
14904 (lambda () (interactive)
14905 (org-eval-in-calendar '(calendar-backward-year 1))))
14906 (org-defkey minibuffer-local-map [?\e (shift down)]
14907 (lambda () (interactive)
14908 (org-eval-in-calendar '(calendar-forward-year 1))))
14909 (org-defkey minibuffer-local-map [(shift up)]
14910 (lambda () (interactive)
14911 (org-eval-in-calendar '(calendar-backward-week 1))))
14912 (org-defkey minibuffer-local-map [(shift down)]
14913 (lambda () (interactive)
14914 (org-eval-in-calendar '(calendar-forward-week 1))))
14915 (org-defkey minibuffer-local-map [(shift left)]
14916 (lambda () (interactive)
14917 (org-eval-in-calendar '(calendar-backward-day 1))))
14918 (org-defkey minibuffer-local-map [(shift right)]
14919 (lambda () (interactive)
14920 (org-eval-in-calendar '(calendar-forward-day 1))))
14921 (org-defkey minibuffer-local-map ">"
14922 (lambda () (interactive)
14923 (org-eval-in-calendar '(scroll-calendar-left 1))))
14924 (org-defkey minibuffer-local-map "<"
14925 (lambda () (interactive)
14926 (org-eval-in-calendar '(scroll-calendar-right 1))))
14927 (org-defkey minibuffer-local-map "\C-v"
14928 (lambda () (interactive)
14929 (org-eval-in-calendar
14930 '(calendar-scroll-left-three-months 1))))
14931 (org-defkey minibuffer-local-map "\M-v"
14932 (lambda () (interactive)
14933 (org-eval-in-calendar
14934 '(calendar-scroll-right-three-months 1))))
14935 (run-hooks 'org-read-date-minibuffer-setup-hook)
14936 (unwind-protect
14937 (progn
14938 (use-local-map map)
14939 (add-hook 'post-command-hook 'org-read-date-display)
14940 (setq org-ans0 (read-string prompt default-input
14941 'org-read-date-history nil))
14942 ;; org-ans0: from prompt
14943 ;; org-ans1: from mouse click
14944 ;; org-ans2: from calendar motion
14945 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
14946 (remove-hook 'post-command-hook 'org-read-date-display)
14947 (use-local-map old-map)
14948 (when org-read-date-overlay
14949 (delete-overlay org-read-date-overlay)
14950 (setq org-read-date-overlay nil)))))
14951 (bury-buffer "*Calendar*")))))
14953 (t ; Naked prompt only
14954 (unwind-protect
14955 (setq ans (read-string prompt default-input
14956 'org-read-date-history timestr))
14957 (when org-read-date-overlay
14958 (delete-overlay org-read-date-overlay)
14959 (setq org-read-date-overlay nil)))))
14961 (setq final (org-read-date-analyze ans def defdecode))
14963 (when org-read-date-analyze-forced-year
14964 (message "Year was forced into %s"
14965 (if org-read-date-force-compatible-dates
14966 "compatible range (1970-2037)"
14967 "range representable on this machine"))
14968 (ding))
14970 ;; One round trip to get rid of 34th of August and stuff like that....
14971 (setq final (decode-time (apply 'encode-time final)))
14973 (setq org-read-date-final-answer ans)
14975 (if to-time
14976 (apply 'encode-time final)
14977 (if (and (boundp 'org-time-was-given) org-time-was-given)
14978 (format "%04d-%02d-%02d %02d:%02d"
14979 (nth 5 final) (nth 4 final) (nth 3 final)
14980 (nth 2 final) (nth 1 final))
14981 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
14983 (defvar def)
14984 (defvar defdecode)
14985 (defvar with-time)
14986 (defun org-read-date-display ()
14987 "Display the current date prompt interpretation in the minibuffer."
14988 (when org-read-date-display-live
14989 (when org-read-date-overlay
14990 (delete-overlay org-read-date-overlay))
14991 (let ((p (point)))
14992 (end-of-line 1)
14993 (while (not (equal (buffer-substring
14994 (max (point-min) (- (point) 4)) (point))
14995 " "))
14996 (insert " "))
14997 (goto-char p))
14998 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
14999 " " (or org-ans1 org-ans2)))
15000 (org-end-time-was-given nil)
15001 (f (org-read-date-analyze ans def defdecode))
15002 (fmts (if org-dcst
15003 org-time-stamp-custom-formats
15004 org-time-stamp-formats))
15005 (fmt (if (or with-time
15006 (and (boundp 'org-time-was-given) org-time-was-given))
15007 (cdr fmts)
15008 (car fmts)))
15009 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
15010 (when (and org-end-time-was-given
15011 (string-match org-plain-time-of-day-regexp txt))
15012 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15013 org-end-time-was-given
15014 (substring txt (match-end 0)))))
15015 (when org-read-date-analyze-futurep
15016 (setq txt (concat txt " (=>F)")))
15017 (setq org-read-date-overlay
15018 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15019 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
15021 (defun org-read-date-analyze (ans def defdecode)
15022 "Analyze the combined answer of the date prompt."
15023 ;; FIXME: cleanup and comment
15024 (let ((nowdecode (decode-time (current-time)))
15025 delta deltan deltaw deltadef year month day
15026 hour minute second wday pm h2 m2 tl wday1
15027 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15028 (setq org-read-date-analyze-futurep nil
15029 org-read-date-analyze-forced-year nil)
15030 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15031 (setq ans "+0"))
15033 (when (setq delta (org-read-date-get-relative ans (current-time) def))
15034 (setq ans (replace-match "" t t ans)
15035 deltan (car delta)
15036 deltaw (nth 1 delta)
15037 deltadef (nth 2 delta)))
15039 ;; Check if there is an iso week date in there
15040 ;; If yes, store the info and postpone interpreting it until the rest
15041 ;; of the parsing is done
15042 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15043 (setq iso-year (if (match-end 1)
15044 (org-small-year-to-year
15045 (string-to-number (match-string 1 ans))))
15046 iso-weekday (if (match-end 3)
15047 (string-to-number (match-string 3 ans)))
15048 iso-week (string-to-number (match-string 2 ans)))
15049 (setq ans (replace-match "" t t ans)))
15051 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15052 (when (string-match
15053 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15054 (setq year (if (match-end 2)
15055 (string-to-number (match-string 2 ans))
15056 (progn (setq kill-year t)
15057 (string-to-number (format-time-string "%Y"))))
15058 month (string-to-number (match-string 3 ans))
15059 day (string-to-number (match-string 4 ans)))
15060 (if (< year 100) (setq year (+ 2000 year)))
15061 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15062 t nil ans)))
15064 ;; Help matching dottet european dates
15065 (when (string-match
15066 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15067 (setq year (if (match-end 3)
15068 (string-to-number (match-string 3 ans))
15069 (progn (setq kill-year t)
15070 (string-to-number (format-time-string "%Y"))))
15071 day (string-to-number (match-string 1 ans))
15072 month (string-to-number (match-string 2 ans))
15073 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15074 t nil ans)))
15076 ;; Help matching american dates, like 5/30 or 5/30/7
15077 (when (string-match
15078 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15079 (setq year (if (match-end 4)
15080 (string-to-number (match-string 4 ans))
15081 (progn (setq kill-year t)
15082 (string-to-number (format-time-string "%Y"))))
15083 month (string-to-number (match-string 1 ans))
15084 day (string-to-number (match-string 2 ans)))
15085 (if (< year 100) (setq year (+ 2000 year)))
15086 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15087 t nil ans)))
15088 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15089 ;; If there is a time with am/pm, and *no* time without it, we convert
15090 ;; so that matching will be successful.
15091 (loop for i from 1 to 2 do ; twice, for end time as well
15092 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15093 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15094 (setq hour (string-to-number (match-string 1 ans))
15095 minute (if (match-end 3)
15096 (string-to-number (match-string 3 ans))
15098 pm (equal ?p
15099 (string-to-char (downcase (match-string 4 ans)))))
15100 (if (and (= hour 12) (not pm))
15101 (setq hour 0)
15102 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15103 (setq ans (replace-match (format "%02d:%02d" hour minute)
15104 t t ans))))
15106 ;; Check if a time range is given as a duration
15107 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15108 (setq hour (string-to-number (match-string 1 ans))
15109 h2 (+ hour (string-to-number (match-string 3 ans)))
15110 minute (string-to-number (match-string 2 ans))
15111 m2 (+ minute (if (match-end 5) (string-to-number
15112 (match-string 5 ans))0)))
15113 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15114 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15115 t t ans)))
15117 ;; Check if there is a time range
15118 (when (boundp 'org-end-time-was-given)
15119 (setq org-time-was-given nil)
15120 (when (and (string-match org-plain-time-of-day-regexp ans)
15121 (match-end 8))
15122 (setq org-end-time-was-given (match-string 8 ans))
15123 (setq ans (concat (substring ans 0 (match-beginning 7))
15124 (substring ans (match-end 7))))))
15126 (setq tl (parse-time-string ans)
15127 day (or (nth 3 tl) (nth 3 defdecode))
15128 month (or (nth 4 tl)
15129 (if (and org-read-date-prefer-future
15130 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15131 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15132 (nth 4 defdecode)))
15133 year (or (and (not kill-year) (nth 5 tl))
15134 (if (and org-read-date-prefer-future
15135 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15136 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15137 (nth 5 defdecode)))
15138 hour (or (nth 2 tl) (nth 2 defdecode))
15139 minute (or (nth 1 tl) (nth 1 defdecode))
15140 second (or (nth 0 tl) 0)
15141 wday (nth 6 tl))
15143 (when (and (eq org-read-date-prefer-future 'time)
15144 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15145 (equal day (nth 3 nowdecode))
15146 (equal month (nth 4 nowdecode))
15147 (equal year (nth 5 nowdecode))
15148 (nth 2 tl)
15149 (or (< (nth 2 tl) (nth 2 nowdecode))
15150 (and (= (nth 2 tl) (nth 2 nowdecode))
15151 (nth 1 tl)
15152 (< (nth 1 tl) (nth 1 nowdecode)))))
15153 (setq day (1+ day)
15154 futurep t))
15156 ;; Special date definitions below
15157 (cond
15158 (iso-week
15159 ;; There was an iso week
15160 (require 'cal-iso)
15161 (setq futurep nil)
15162 (setq year (or iso-year year)
15163 day (or iso-weekday wday 1)
15164 wday nil ; to make sure that the trigger below does not match
15165 iso-date (calendar-gregorian-from-absolute
15166 (calendar-absolute-from-iso
15167 (list iso-week day year))))
15168 ; FIXME: Should we also push ISO weeks into the future?
15169 ; (when (and org-read-date-prefer-future
15170 ; (not iso-year)
15171 ; (< (calendar-absolute-from-gregorian iso-date)
15172 ; (time-to-days (current-time))))
15173 ; (setq year (1+ year)
15174 ; iso-date (calendar-gregorian-from-absolute
15175 ; (calendar-absolute-from-iso
15176 ; (list iso-week day year)))))
15177 (setq month (car iso-date)
15178 year (nth 2 iso-date)
15179 day (nth 1 iso-date)))
15180 (deltan
15181 (setq futurep nil)
15182 (unless deltadef
15183 (let ((now (decode-time (current-time))))
15184 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15185 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15186 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15187 ((equal deltaw "m") (setq month (+ month deltan)))
15188 ((equal deltaw "y") (setq year (+ year deltan)))))
15189 ((and wday (not (nth 3 tl)))
15190 (setq futurep nil)
15191 ;; Weekday was given, but no day, so pick that day in the week
15192 ;; on or after the derived date.
15193 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15194 (unless (equal wday wday1)
15195 (setq day (+ day (% (- wday wday1 -7) 7))))))
15196 (if (and (boundp 'org-time-was-given)
15197 (nth 2 tl))
15198 (setq org-time-was-given t))
15199 (if (< year 100) (setq year (+ 2000 year)))
15200 ;; Check of the date is representable
15201 (if org-read-date-force-compatible-dates
15202 (progn
15203 (if (< year 1970)
15204 (setq year 1970 org-read-date-analyze-forced-year t))
15205 (if (> year 2037)
15206 (setq year 2037 org-read-date-analyze-forced-year t)))
15207 (condition-case nil
15208 (ignore (encode-time second minute hour day month year))
15209 (error
15210 (setq year (nth 5 defdecode))
15211 (setq org-read-date-analyze-forced-year t))))
15212 (setq org-read-date-analyze-futurep futurep)
15213 (list second minute hour day month year)))
15215 (defvar parse-time-weekdays)
15217 (defun org-read-date-get-relative (s today default)
15218 "Check string S for special relative date string.
15219 TODAY and DEFAULT are internal times, for today and for a default.
15220 Return shift list (N what def-flag)
15221 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15222 N is the number of WHATs to shift.
15223 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15224 the DEFAULT date rather than TODAY."
15225 (when (and
15226 (string-match
15227 (concat
15228 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15229 "\\([0-9]+\\)?"
15230 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15231 "\\([ \t]\\|$\\)") s)
15232 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15233 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15234 (string-to-char (substring (match-string 1 s) -1))
15235 ?+))
15236 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15237 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15238 (what (if (match-end 3) (match-string 3 s) "d"))
15239 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15240 (date (if rel default today))
15241 (wday (nth 6 (decode-time date)))
15242 delta)
15243 (if wday1
15244 (progn
15245 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15246 (if (= dir ?-) (setq delta (- delta 7)))
15247 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15248 (list delta "d" rel))
15249 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15251 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15252 "Turn a user-specified date into the internal representation.
15253 The internal representation needed by the calendar is (month day year).
15254 This is a wrapper to handle the brain-dead convention in calendar that
15255 user function argument order change dependent on argument order."
15256 (if (boundp 'calendar-date-style)
15257 (cond
15258 ((eq calendar-date-style 'american)
15259 (list arg1 arg2 arg3))
15260 ((eq calendar-date-style 'european)
15261 (list arg2 arg1 arg3))
15262 ((eq calendar-date-style 'iso)
15263 (list arg2 arg3 arg1)))
15264 (with-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15265 (if (org-bound-and-true-p european-calendar-style)
15266 (list arg2 arg1 arg3)
15267 (list arg1 arg2 arg3)))))
15269 (defun org-eval-in-calendar (form &optional keepdate)
15270 "Eval FORM in the calendar window and return to current window.
15271 Also, store the cursor date in variable org-ans2."
15272 (let ((sf (selected-frame))
15273 (sw (selected-window)))
15274 (select-window (get-buffer-window "*Calendar*" t))
15275 (eval form)
15276 (when (and (not keepdate) (calendar-cursor-to-date))
15277 (let* ((date (calendar-cursor-to-date))
15278 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15279 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15280 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15281 (select-window sw)
15282 (org-select-frame-set-input-focus sf)))
15284 (defun org-calendar-select ()
15285 "Return to `org-read-date' with the date currently selected.
15286 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15287 (interactive)
15288 (when (calendar-cursor-to-date)
15289 (let* ((date (calendar-cursor-to-date))
15290 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15291 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15292 (if (active-minibuffer-window) (exit-minibuffer))))
15294 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15295 "Insert a date stamp for the date given by the internal TIME.
15296 WITH-HM means use the stamp format that includes the time of the day.
15297 INACTIVE means use square brackets instead of angular ones, so that the
15298 stamp will not contribute to the agenda.
15299 PRE and POST are optional strings to be inserted before and after the
15300 stamp.
15301 The command returns the inserted time stamp."
15302 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15303 stamp)
15304 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15305 (insert-before-markers (or pre ""))
15306 (when (listp extra)
15307 (setq extra (car extra))
15308 (if (and (stringp extra)
15309 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15310 (setq extra (format "-%02d:%02d"
15311 (string-to-number (match-string 1 extra))
15312 (string-to-number (match-string 2 extra))))
15313 (setq extra nil)))
15314 (when extra
15315 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15316 (insert-before-markers (setq stamp (format-time-string fmt time)))
15317 (insert-before-markers (or post ""))
15318 (setq org-last-inserted-timestamp stamp)))
15320 (defun org-toggle-time-stamp-overlays ()
15321 "Toggle the use of custom time stamp formats."
15322 (interactive)
15323 (setq org-display-custom-times (not org-display-custom-times))
15324 (unless org-display-custom-times
15325 (let ((p (point-min)) (bmp (buffer-modified-p)))
15326 (while (setq p (next-single-property-change p 'display))
15327 (if (and (get-text-property p 'display)
15328 (eq (get-text-property p 'face) 'org-date))
15329 (remove-text-properties
15330 p (setq p (next-single-property-change p 'display))
15331 '(display t))))
15332 (set-buffer-modified-p bmp)))
15333 (if (featurep 'xemacs)
15334 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15335 (org-restart-font-lock)
15336 (setq org-table-may-need-update t)
15337 (if org-display-custom-times
15338 (message "Time stamps are overlayed with custom format")
15339 (message "Time stamp overlays removed")))
15341 (defun org-display-custom-time (beg end)
15342 "Overlay modified time stamp format over timestamp between BEG and END."
15343 (let* ((ts (buffer-substring beg end))
15344 t1 w1 with-hm tf time str w2 (off 0))
15345 (save-match-data
15346 (setq t1 (org-parse-time-string ts t))
15347 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
15348 (setq off (- (match-end 0) (match-beginning 0)))))
15349 (setq end (- end off))
15350 (setq w1 (- end beg)
15351 with-hm (and (nth 1 t1) (nth 2 t1))
15352 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15353 time (org-fix-decoded-time t1)
15354 str (org-add-props
15355 (format-time-string
15356 (substring tf 1 -1) (apply 'encode-time time))
15357 nil 'mouse-face 'highlight)
15358 w2 (length str))
15359 (if (not (= w2 w1))
15360 (add-text-properties (1+ beg) (+ 2 beg)
15361 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15362 (if (featurep 'xemacs)
15363 (progn
15364 (put-text-property beg end 'invisible t)
15365 (put-text-property beg end 'end-glyph (make-glyph str)))
15366 (put-text-property beg end 'display str))))
15368 (defun org-translate-time (string)
15369 "Translate all timestamps in STRING to custom format.
15370 But do this only if the variable `org-display-custom-times' is set."
15371 (when org-display-custom-times
15372 (save-match-data
15373 (let* ((start 0)
15374 (re org-ts-regexp-both)
15375 t1 with-hm inactive tf time str beg end)
15376 (while (setq start (string-match re string start))
15377 (setq beg (match-beginning 0)
15378 end (match-end 0)
15379 t1 (save-match-data
15380 (org-parse-time-string (substring string beg end) t))
15381 with-hm (and (nth 1 t1) (nth 2 t1))
15382 inactive (equal (substring string beg (1+ beg)) "[")
15383 tf (funcall (if with-hm 'cdr 'car)
15384 org-time-stamp-custom-formats)
15385 time (org-fix-decoded-time t1)
15386 str (format-time-string
15387 (concat
15388 (if inactive "[" "<") (substring tf 1 -1)
15389 (if inactive "]" ">"))
15390 (apply 'encode-time time))
15391 string (replace-match str t t string)
15392 start (+ start (length str)))))))
15393 string)
15395 (defun org-fix-decoded-time (time)
15396 "Set 0 instead of nil for the first 6 elements of time.
15397 Don't touch the rest."
15398 (let ((n 0))
15399 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15401 (defun org-days-to-time (timestamp-string)
15402 "Difference between TIMESTAMP-STRING and now in days."
15403 (- (time-to-days (org-time-string-to-time timestamp-string))
15404 (time-to-days (current-time))))
15406 (defun org-deadline-close (timestamp-string &optional ndays)
15407 "Is the time in TIMESTAMP-STRING close to the current date?"
15408 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15409 (and (< (org-days-to-time timestamp-string) ndays)
15410 (not (org-entry-is-done-p))))
15412 (defun org-get-wdays (ts)
15413 "Get the deadline lead time appropriate for timestring TS."
15414 (cond
15415 ((<= org-deadline-warning-days 0)
15416 ;; 0 or negative, enforce this value no matter what
15417 (- org-deadline-warning-days))
15418 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
15419 ;; lead time is specified.
15420 (floor (* (string-to-number (match-string 1 ts))
15421 (cdr (assoc (match-string 2 ts)
15422 '(("d" . 1) ("w" . 7)
15423 ("m" . 30.4) ("y" . 365.25)))))))
15424 ;; go for the default.
15425 (t org-deadline-warning-days)))
15427 (defun org-calendar-select-mouse (ev)
15428 "Return to `org-read-date' with the date currently selected.
15429 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15430 (interactive "e")
15431 (mouse-set-point ev)
15432 (when (calendar-cursor-to-date)
15433 (let* ((date (calendar-cursor-to-date))
15434 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15435 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15436 (if (active-minibuffer-window) (exit-minibuffer))))
15438 (defun org-check-deadlines (ndays)
15439 "Check if there are any deadlines due or past due.
15440 A deadline is considered due if it happens within `org-deadline-warning-days'
15441 days from today's date. If the deadline appears in an entry marked DONE,
15442 it is not shown. The prefix arg NDAYS can be used to test that many
15443 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15444 (interactive "P")
15445 (let* ((org-warn-days
15446 (cond
15447 ((equal ndays '(4)) 100000)
15448 (ndays (prefix-numeric-value ndays))
15449 (t (abs org-deadline-warning-days))))
15450 (case-fold-search nil)
15451 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15452 (callback
15453 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15455 (message "%d deadlines past-due or due within %d days"
15456 (org-occur regexp nil callback)
15457 org-warn-days)))
15459 (defun org-check-before-date (date)
15460 "Check if there are deadlines or scheduled entries before DATE."
15461 (interactive (list (org-read-date)))
15462 (let ((case-fold-search nil)
15463 (regexp (concat "\\<\\(" org-deadline-string
15464 "\\|" org-scheduled-string
15465 "\\) *<\\([^>]+\\)>"))
15466 (callback
15467 (lambda () (time-less-p
15468 (org-time-string-to-time (match-string 2))
15469 (org-time-string-to-time date)))))
15470 (message "%d entries before %s"
15471 (org-occur regexp nil callback) date)))
15473 (defun org-check-after-date (date)
15474 "Check if there are deadlines or scheduled entries after DATE."
15475 (interactive (list (org-read-date)))
15476 (let ((case-fold-search nil)
15477 (regexp (concat "\\<\\(" org-deadline-string
15478 "\\|" org-scheduled-string
15479 "\\) *<\\([^>]+\\)>"))
15480 (callback
15481 (lambda () (not
15482 (time-less-p
15483 (org-time-string-to-time (match-string 2))
15484 (org-time-string-to-time date))))))
15485 (message "%d entries after %s"
15486 (org-occur regexp nil callback) date)))
15488 (defun org-evaluate-time-range (&optional to-buffer)
15489 "Evaluate a time range by computing the difference between start and end.
15490 Normally the result is just printed in the echo area, but with prefix arg
15491 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15492 If the time range is actually in a table, the result is inserted into the
15493 next column.
15494 For time difference computation, a year is assumed to be exactly 365
15495 days in order to avoid rounding problems."
15496 (interactive "P")
15498 (org-clock-update-time-maybe)
15499 (save-excursion
15500 (unless (org-at-date-range-p t)
15501 (goto-char (point-at-bol))
15502 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15503 (if (not (org-at-date-range-p t))
15504 (error "Not at a time-stamp range, and none found in current line")))
15505 (let* ((ts1 (match-string 1))
15506 (ts2 (match-string 2))
15507 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15508 (match-end (match-end 0))
15509 (time1 (org-time-string-to-time ts1))
15510 (time2 (org-time-string-to-time ts2))
15511 (t1 (org-float-time time1))
15512 (t2 (org-float-time time2))
15513 (diff (abs (- t2 t1)))
15514 (negative (< (- t2 t1) 0))
15515 ;; (ys (floor (* 365 24 60 60)))
15516 (ds (* 24 60 60))
15517 (hs (* 60 60))
15518 (fy "%dy %dd %02d:%02d")
15519 (fy1 "%dy %dd")
15520 (fd "%dd %02d:%02d")
15521 (fd1 "%dd")
15522 (fh "%02d:%02d")
15523 y d h m align)
15524 (if havetime
15525 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15527 d (floor (/ diff ds)) diff (mod diff ds)
15528 h (floor (/ diff hs)) diff (mod diff hs)
15529 m (floor (/ diff 60)))
15530 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15532 d (floor (+ (/ diff ds) 0.5))
15533 h 0 m 0))
15534 (if (not to-buffer)
15535 (message "%s" (org-make-tdiff-string y d h m))
15536 (if (org-at-table-p)
15537 (progn
15538 (goto-char match-end)
15539 (setq align t)
15540 (and (looking-at " *|") (goto-char (match-end 0))))
15541 (goto-char match-end))
15542 (if (looking-at
15543 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15544 (replace-match ""))
15545 (if negative (insert " -"))
15546 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15547 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15548 (insert " " (format fh h m))))
15549 (if align (org-table-align))
15550 (message "Time difference inserted")))))
15552 (defun org-make-tdiff-string (y d h m)
15553 (let ((fmt "")
15554 (l nil))
15555 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15556 l (push y l)))
15557 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15558 l (push d l)))
15559 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15560 l (push h l)))
15561 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15562 l (push m l)))
15563 (apply 'format fmt (nreverse l))))
15565 (defun org-time-string-to-time (s &optional buffer pos)
15566 (condition-case errdata
15567 (apply 'encode-time (org-parse-time-string s))
15568 (error (error "Bad timestamp `%s'%s\nError was: %s"
15569 s (if (not (and buffer pos))
15571 (format " at %d in buffer `%s'" pos buffer))
15572 (cdr errdata)))))
15574 (defun org-time-string-to-seconds (s)
15575 (org-float-time (org-time-string-to-time s)))
15577 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
15578 "Convert a time stamp to an absolute day number.
15579 If there is a specifier for a cyclic time stamp, get the closest date to
15580 DAYNR.
15581 PREFER and SHOW-ALL are passed through to `org-closest-date'.
15582 The variable date is bound by the calendar when this is called."
15583 (cond
15584 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15585 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15586 daynr
15587 (+ daynr 1000)))
15588 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
15589 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15590 (time-to-days (current-time))) (match-string 0 s)
15591 prefer show-all))
15592 (t (time-to-days
15593 (condition-case errdata
15594 (apply 'encode-time (org-parse-time-string s))
15595 (error (error "Bad timestamp `%s'%s\nError was: %s"
15596 s (if (not (and buffer pos))
15598 (format " at %d in buffer `%s'" pos buffer))
15599 (cdr errdata))))))))
15601 (defun org-days-to-iso-week (days)
15602 "Return the iso week number."
15603 (require 'cal-iso)
15604 (car (calendar-iso-from-absolute days)))
15606 (defun org-small-year-to-year (year)
15607 "Convert 2-digit years into 4-digit years.
15608 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15609 The year 2000 cannot be abbreviated. Any year larger than 99
15610 is returned unchanged."
15611 (if (< year 38)
15612 (setq year (+ 2000 year))
15613 (if (< year 100)
15614 (setq year (+ 1900 year))))
15615 year)
15617 (defun org-time-from-absolute (d)
15618 "Return the time corresponding to date D.
15619 D may be an absolute day number, or a calendar-type list (month day year)."
15620 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15621 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15623 (defun org-calendar-holiday ()
15624 "List of holidays, for Diary display in Org-mode."
15625 (require 'holidays)
15626 (let ((hl (funcall
15627 (if (fboundp 'calendar-check-holidays)
15628 'calendar-check-holidays 'check-calendar-holidays) date)))
15629 (if hl (mapconcat 'identity hl "; "))))
15631 (defun org-diary-sexp-entry (sexp entry date)
15632 "Process a SEXP diary ENTRY for DATE."
15633 (require 'diary-lib)
15634 (let ((result (if calendar-debug-sexp
15635 (let ((stack-trace-on-error t))
15636 (eval (car (read-from-string sexp))))
15637 (condition-case nil
15638 (eval (car (read-from-string sexp)))
15639 (error
15640 (beep)
15641 (message "Bad sexp at line %d in %s: %s"
15642 (org-current-line)
15643 (buffer-file-name) sexp)
15644 (sleep-for 2))))))
15645 (cond ((stringp result) (split-string result "; "))
15646 ((and (consp result)
15647 (not (consp (cdr result)))
15648 (stringp (cdr result))) (cdr result))
15649 ((and (consp result)
15650 (stringp (car result))) result)
15651 (result entry)
15652 (t nil))))
15654 (defun org-diary-to-ical-string (frombuf)
15655 "Get iCalendar entries from diary entries in buffer FROMBUF.
15656 This uses the icalendar.el library."
15657 (let* ((tmpdir (if (featurep 'xemacs)
15658 (temp-directory)
15659 temporary-file-directory))
15660 (tmpfile (make-temp-name
15661 (expand-file-name "orgics" tmpdir)))
15662 buf rtn b e)
15663 (with-current-buffer frombuf
15664 (icalendar-export-region (point-min) (point-max) tmpfile)
15665 (setq buf (find-buffer-visiting tmpfile))
15666 (set-buffer buf)
15667 (goto-char (point-min))
15668 (if (re-search-forward "^BEGIN:VEVENT" nil t)
15669 (setq b (match-beginning 0)))
15670 (goto-char (point-max))
15671 (if (re-search-backward "^END:VEVENT" nil t)
15672 (setq e (match-end 0)))
15673 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
15674 (kill-buffer buf)
15675 (delete-file tmpfile)
15676 rtn))
15678 (defun org-closest-date (start current change prefer show-all)
15679 "Find the date closest to CURRENT that is consistent with START and CHANGE.
15680 When PREFER is `past', return a date that is either CURRENT or past.
15681 When PREFER is `future', return a date that is either CURRENT or future.
15682 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
15683 ;; Make the proper lists from the dates
15684 (catch 'exit
15685 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
15686 dn dw sday cday n1 n2 n0
15687 d m y y1 y2 date1 date2 nmonths nm ny m2)
15689 (setq start (org-date-to-gregorian start)
15690 current (org-date-to-gregorian
15691 (if show-all
15692 current
15693 (time-to-days (current-time))))
15694 sday (calendar-absolute-from-gregorian start)
15695 cday (calendar-absolute-from-gregorian current))
15697 (if (<= cday sday) (throw 'exit sday))
15699 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
15700 (setq dn (string-to-number (match-string 1 change))
15701 dw (cdr (assoc (match-string 2 change) a1)))
15702 (error "Invalid change specifier: %s" change))
15703 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
15704 (cond
15705 ((eq dw 'day)
15706 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
15707 n2 (+ n1 dn)))
15708 ((eq dw 'year)
15709 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
15710 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
15711 (setq date1 (list m d y1)
15712 n1 (calendar-absolute-from-gregorian date1)
15713 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
15714 n2 (calendar-absolute-from-gregorian date2)))
15715 ((eq dw 'month)
15716 ;; approx number of month between the two dates
15717 (setq nmonths (floor (/ (- cday sday) 30.436875)))
15718 ;; How often does dn fit in there?
15719 (setq d (nth 1 start) m (car start) y (nth 2 start)
15720 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
15721 m (+ m nm)
15722 ny (floor (/ m 12))
15723 y (+ y ny)
15724 m (- m (* ny 12)))
15725 (while (> m 12) (setq m (- m 12) y (1+ y)))
15726 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
15727 (setq m2 (+ m dn) y2 y)
15728 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15729 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
15730 (while (<= n2 cday)
15731 (setq n1 n2 m m2 y y2)
15732 (setq m2 (+ m dn) y2 y)
15733 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15734 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
15735 ;; Make sure n1 is the earlier date
15736 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
15737 (if show-all
15738 (cond
15739 ((eq prefer 'past) (if (= cday n2) n2 n1))
15740 ((eq prefer 'future) (if (= cday n1) n1 n2))
15741 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
15742 (cond
15743 ((eq prefer 'past) (if (= cday n2) n2 n1))
15744 ((eq prefer 'future) (if (= cday n1) n1 n2))
15745 (t (if (= cday n1) n1 n2)))))))
15747 (defun org-date-to-gregorian (date)
15748 "Turn any specification of DATE into a Gregorian date for the calendar."
15749 (cond ((integerp date) (calendar-gregorian-from-absolute date))
15750 ((and (listp date) (= (length date) 3)) date)
15751 ((stringp date)
15752 (setq date (org-parse-time-string date))
15753 (list (nth 4 date) (nth 3 date) (nth 5 date)))
15754 ((listp date)
15755 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
15757 (defun org-parse-time-string (s &optional nodefault)
15758 "Parse the standard Org-mode time string.
15759 This should be a lot faster than the normal `parse-time-string'.
15760 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
15761 hour and minute fields will be nil if not given."
15762 (if (string-match org-ts-regexp0 s)
15763 (list 0
15764 (if (or (match-beginning 8) (not nodefault))
15765 (string-to-number (or (match-string 8 s) "0")))
15766 (if (or (match-beginning 7) (not nodefault))
15767 (string-to-number (or (match-string 7 s) "0")))
15768 (string-to-number (match-string 4 s))
15769 (string-to-number (match-string 3 s))
15770 (string-to-number (match-string 2 s))
15771 nil nil nil)
15772 (error "Not a standard Org-mode time string: %s" s)))
15774 (defun org-timestamp-up (&optional arg)
15775 "Increase the date item at the cursor by one.
15776 If the cursor is on the year, change the year. If it is on the month,
15777 the day or the time, change that.
15778 With prefix ARG, change by that many units."
15779 (interactive "p")
15780 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
15782 (defun org-timestamp-down (&optional arg)
15783 "Decrease the date item at the cursor by one.
15784 If the cursor is on the year, change the year. If it is on the month,
15785 the day or the time, change that.
15786 With prefix ARG, change by that many units."
15787 (interactive "p")
15788 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
15790 (defun org-timestamp-up-day (&optional arg)
15791 "Increase the date in the time stamp by one day.
15792 With prefix ARG, change that many days."
15793 (interactive "p")
15794 (if (and (not (org-at-timestamp-p t))
15795 (org-on-heading-p))
15796 (org-todo 'up)
15797 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
15799 (defun org-timestamp-down-day (&optional arg)
15800 "Decrease the date in the time stamp by one day.
15801 With prefix ARG, change that many days."
15802 (interactive "p")
15803 (if (and (not (org-at-timestamp-p t))
15804 (org-on-heading-p))
15805 (org-todo 'down)
15806 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
15808 (defun org-at-timestamp-p (&optional inactive-ok)
15809 "Determine if the cursor is in or at a timestamp."
15810 (interactive)
15811 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
15812 (pos (point))
15813 (ans (or (looking-at tsr)
15814 (save-excursion
15815 (skip-chars-backward "^[<\n\r\t")
15816 (if (> (point) (point-min)) (backward-char 1))
15817 (and (looking-at tsr)
15818 (> (- (match-end 0) pos) -1))))))
15819 (and ans
15820 (boundp 'org-ts-what)
15821 (setq org-ts-what
15822 (cond
15823 ((= pos (match-beginning 0)) 'bracket)
15824 ;; Point is considered to be "on the bracket" whether
15825 ;; it's really on it or right after it.
15826 ((or (= pos (1- (match-end 0)))
15827 (= pos (match-end 0))) 'bracket)
15828 ((org-pos-in-match-range pos 2) 'year)
15829 ((org-pos-in-match-range pos 3) 'month)
15830 ((org-pos-in-match-range pos 7) 'hour)
15831 ((org-pos-in-match-range pos 8) 'minute)
15832 ((or (org-pos-in-match-range pos 4)
15833 (org-pos-in-match-range pos 5)) 'day)
15834 ((and (> pos (or (match-end 8) (match-end 5)))
15835 (< pos (match-end 0)))
15836 (- pos (or (match-end 8) (match-end 5))))
15837 (t 'day))))
15838 ans))
15840 (defun org-toggle-timestamp-type ()
15841 "Toggle the type (<active> or [inactive]) of a time stamp."
15842 (interactive)
15843 (when (org-at-timestamp-p t)
15844 (let ((beg (match-beginning 0)) (end (match-end 0))
15845 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
15846 (save-excursion
15847 (goto-char beg)
15848 (while (re-search-forward "[][<>]" end t)
15849 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
15850 t t)))
15851 (message "Timestamp is now %sactive"
15852 (if (equal (char-after beg) ?<) "" "in")))))
15854 (defun org-timestamp-change (n &optional what updown)
15855 "Change the date in the time stamp at point.
15856 The date will be changed by N times WHAT. WHAT can be `day', `month',
15857 `year', `minute', `second'. If WHAT is not given, the cursor position
15858 in the timestamp determines what will be changed."
15859 (let ((origin (point)) origin-cat
15860 with-hm inactive
15861 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
15862 org-ts-what
15863 extra rem
15864 ts time time0)
15865 (if (not (org-at-timestamp-p t))
15866 (error "Not at a timestamp"))
15867 (if (and (not what) (eq org-ts-what 'bracket))
15868 (org-toggle-timestamp-type)
15869 ;; Point isn't on brackets. Remember the part of the time-stamp
15870 ;; the point was in. Indeed, size of time-stamps may change,
15871 ;; but point must be kept in the same category nonetheless.
15872 (setq origin-cat org-ts-what)
15873 (if (and (not what) (not (eq org-ts-what 'day))
15874 org-display-custom-times
15875 (get-text-property (point) 'display)
15876 (not (get-text-property (1- (point)) 'display)))
15877 (setq org-ts-what 'day))
15878 (setq org-ts-what (or what org-ts-what)
15879 inactive (= (char-after (match-beginning 0)) ?\[)
15880 ts (match-string 0))
15881 (replace-match "")
15882 (if (string-match
15883 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
15885 (setq extra (match-string 1 ts)))
15886 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
15887 (setq with-hm t))
15888 (setq time0 (org-parse-time-string ts))
15889 (when (and updown
15890 (eq org-ts-what 'minute)
15891 (not current-prefix-arg))
15892 ;; This looks like s-up and s-down. Change by one rounding step.
15893 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
15894 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
15895 (setcar (cdr time0) (+ (nth 1 time0)
15896 (if (> n 0) (- rem) (- dm rem))))))
15897 (setq time
15898 (encode-time (or (car time0) 0)
15899 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
15900 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
15901 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
15902 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
15903 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
15904 (nthcdr 6 time0)))
15905 (when (and (member org-ts-what '(hour minute))
15906 extra
15907 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
15908 (setq extra (org-modify-ts-extra
15909 extra
15910 (if (eq org-ts-what 'hour) 2 5)
15911 n dm)))
15912 (when (integerp org-ts-what)
15913 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
15914 (if (eq what 'calendar)
15915 (let ((cal-date (org-get-date-from-calendar)))
15916 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
15917 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
15918 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
15919 (setcar time0 (or (car time0) 0))
15920 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
15921 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
15922 (setq time (apply 'encode-time time0))))
15923 ;; Insert the new time-stamp, and ensure point stays in the same
15924 ;; category as before (i.e. not after the last position in that
15925 ;; category).
15926 (let ((pos (point)))
15927 ;; Stay before inserted string. `save-excursion' is of no use.
15928 (setq org-last-changed-timestamp
15929 (org-insert-time-stamp time with-hm inactive nil nil extra))
15930 (goto-char pos))
15931 (save-match-data
15932 (looking-at org-ts-regexp3)
15933 (goto-char (cond
15934 ;; `day' category ends before `hour' if any, or at
15935 ;; the end of the day name.
15936 ((eq origin-cat 'day)
15937 (min (or (match-beginning 7) (1- (match-end 5))) origin))
15938 ((eq origin-cat 'hour) (min (match-end 7) origin))
15939 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
15940 ((integerp origin-cat) (min (1- (match-end 0)) origin))
15941 ;; `year' and `month' have both fixed size: point
15942 ;; couldn't have moved into another part.
15943 (t origin))))
15944 ;; Update clock if on a CLOCK line.
15945 (org-clock-update-time-maybe)
15946 ;; Try to recenter the calendar window, if any.
15947 (if (and org-calendar-follow-timestamp-change
15948 (get-buffer-window "*Calendar*" t)
15949 (memq org-ts-what '(day month year)))
15950 (org-recenter-calendar (time-to-days time))))))
15952 (defun org-modify-ts-extra (s pos n dm)
15953 "Change the different parts of the lead-time and repeat fields in timestamp."
15954 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
15955 ng h m new rem)
15956 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
15957 (cond
15958 ((or (org-pos-in-match-range pos 2)
15959 (org-pos-in-match-range pos 3))
15960 (setq m (string-to-number (match-string 3 s))
15961 h (string-to-number (match-string 2 s)))
15962 (if (org-pos-in-match-range pos 2)
15963 (setq h (+ h n))
15964 (setq n (* dm (org-no-warnings (signum n))))
15965 (when (not (= 0 (setq rem (% m dm))))
15966 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
15967 (setq m (+ m n)))
15968 (if (< m 0) (setq m (+ m 60) h (1- h)))
15969 (if (> m 59) (setq m (- m 60) h (1+ h)))
15970 (setq h (min 24 (max 0 h)))
15971 (setq ng 1 new (format "-%02d:%02d" h m)))
15972 ((org-pos-in-match-range pos 6)
15973 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
15974 ((org-pos-in-match-range pos 5)
15975 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
15977 ((org-pos-in-match-range pos 9)
15978 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
15979 ((org-pos-in-match-range pos 8)
15980 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
15982 (when ng
15983 (setq s (concat
15984 (substring s 0 (match-beginning ng))
15986 (substring s (match-end ng))))))
15989 (defun org-recenter-calendar (date)
15990 "If the calendar is visible, recenter it to DATE."
15991 (let* ((win (selected-window))
15992 (cwin (get-buffer-window "*Calendar*" t))
15993 (calendar-move-hook nil))
15994 (when cwin
15995 (select-window cwin)
15996 (calendar-goto-date (if (listp date) date
15997 (calendar-gregorian-from-absolute date)))
15998 (select-window win))))
16000 (defun org-goto-calendar (&optional arg)
16001 "Go to the Emacs calendar at the current date.
16002 If there is a time stamp in the current line, go to that date.
16003 A prefix ARG can be used to force the current date."
16004 (interactive "P")
16005 (let ((tsr org-ts-regexp) diff
16006 (calendar-move-hook nil)
16007 (calendar-view-holidays-initially-flag nil)
16008 (calendar-view-diary-initially-flag nil))
16009 (if (or (org-at-timestamp-p)
16010 (save-excursion
16011 (beginning-of-line 1)
16012 (looking-at (concat ".*" tsr))))
16013 (let ((d1 (time-to-days (current-time)))
16014 (d2 (time-to-days
16015 (org-time-string-to-time (match-string 1)))))
16016 (setq diff (- d2 d1))))
16017 (calendar)
16018 (calendar-goto-today)
16019 (if (and diff (not arg)) (calendar-forward-day diff))))
16021 (defun org-get-date-from-calendar ()
16022 "Return a list (month day year) of date at point in calendar."
16023 (with-current-buffer "*Calendar*"
16024 (save-match-data
16025 (calendar-cursor-to-date))))
16027 (defun org-date-from-calendar ()
16028 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16029 If there is already a time stamp at the cursor position, update it."
16030 (interactive)
16031 (if (org-at-timestamp-p t)
16032 (org-timestamp-change 0 'calendar)
16033 (let ((cal-date (org-get-date-from-calendar)))
16034 (org-insert-time-stamp
16035 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16037 (defun org-minutes-to-hh:mm-string (m)
16038 "Compute H:MM from a number of minutes."
16039 (let ((h (/ m 60)))
16040 (setq m (- m (* 60 h)))
16041 (format org-time-clocksum-format h m)))
16043 (defun org-hh:mm-string-to-minutes (s)
16044 "Convert a string H:MM to a number of minutes.
16045 If the string is just a number, interpret it as minutes.
16046 In fact, the first hh:mm or number in the string will be taken,
16047 there can be extra stuff in the string.
16048 If no number is found, the return value is 0."
16049 (cond
16050 ((integerp s) s)
16051 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16052 (+ (* (string-to-number (match-string 1 s)) 60)
16053 (string-to-number (match-string 2 s))))
16054 ((string-match "\\([0-9]+\\)" s)
16055 (string-to-number (match-string 1 s)))
16056 (t 0)))
16058 (defcustom org-effort-durations
16059 `(("h" . 60)
16060 ("d" . ,(* 60 8))
16061 ("w" . ,(* 60 8 5))
16062 ("m" . ,(* 60 8 5 4))
16063 ("y" . ,(* 60 8 5 40)))
16064 "Conversion factor to minutes for an effort modifier.
16066 Each entry has the form (MODIFIER . MINUTES).
16068 In an effort string, a number followed by MODIFIER is multiplied
16069 by the specified number of MINUTES to obtain an effort in
16070 minutes.
16072 For example, if the value of this variable is ((\"hours\" . 60)), then an
16073 effort string \"2hours\" is equivalent to 120 minutes."
16074 :group 'org-agenda
16075 :type '(alist :key-type (string :tag "Modifier")
16076 :value-type (number :tag "Minutes")))
16078 (defun org-duration-string-to-minutes (s)
16079 "Convert a duration string S to minutes.
16081 A bare number is interpreted as minutes, modifiers can be set by
16082 customizing `org-effort-durations' (which see).
16084 Entries containing a colon are interpreted as H:MM by
16085 `org-hh:mm-string-to-minutes'."
16086 (let ((result 0)
16087 (re (concat "\\([0-9]+\\) *\\("
16088 (regexp-opt (mapcar 'car org-effort-durations))
16089 "\\)")))
16090 (while (string-match re s)
16091 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16092 (string-to-number (match-string 1 s))))
16093 (setq s (replace-match "" nil t s)))
16094 (incf result (org-hh:mm-string-to-minutes s))
16095 result))
16097 ;;;; Files
16099 (defun org-save-all-org-buffers ()
16100 "Save all Org-mode buffers without user confirmation."
16101 (interactive)
16102 (message "Saving all Org-mode buffers...")
16103 (save-some-buffers t (lambda () (eq major-mode 'org-mode)))
16104 (when (featurep 'org-id) (org-id-locations-save))
16105 (message "Saving all Org-mode buffers... done"))
16107 (defun org-revert-all-org-buffers ()
16108 "Revert all Org-mode buffers.
16109 Prompt for confirmation when there are unsaved changes.
16110 Be sure you know what you are doing before letting this function
16111 overwrite your changes.
16113 This function is useful in a setup where one tracks org files
16114 with a version control system, to revert on one machine after pulling
16115 changes from another. I believe the procedure must be like this:
16117 1. M-x org-save-all-org-buffers
16118 2. Pull changes from the other machine, resolve conflicts
16119 3. M-x org-revert-all-org-buffers"
16120 (interactive)
16121 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16122 (error "Abort"))
16123 (save-excursion
16124 (save-window-excursion
16125 (mapc
16126 (lambda (b)
16127 (when (and (with-current-buffer b (eq major-mode 'org-mode))
16128 (with-current-buffer b buffer-file-name))
16129 (org-pop-to-buffer-same-window b)
16130 (revert-buffer t 'no-confirm)))
16131 (buffer-list))
16132 (when (and (featurep 'org-id) org-id-track-globally)
16133 (org-id-locations-load)))))
16135 ;;;; Agenda files
16137 ;;;###autoload
16138 (defun org-switchb (&optional arg)
16139 "Switch between Org buffers.
16140 With one prefix argument, restrict available buffers to files.
16141 With two prefix arguments, restrict available buffers to agenda files.
16143 Defaults to `iswitchb' for buffer name completion.
16144 Set `org-completion-use-ido' to make it use ido instead."
16145 (interactive "P")
16146 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16147 ((equal arg '(16)) (org-buffer-list 'agenda))
16148 (t (org-buffer-list))))
16149 (org-completion-use-iswitchb org-completion-use-iswitchb)
16150 (org-completion-use-ido org-completion-use-ido))
16151 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16152 (setq org-completion-use-iswitchb t))
16153 (org-pop-to-buffer-same-window
16154 (org-icompleting-read "Org buffer: "
16155 (mapcar 'list (mapcar 'buffer-name blist))
16156 nil t))))
16158 ;;; Define some older names previously used for this functionality
16159 ;;;###autoload
16160 (defalias 'org-ido-switchb 'org-switchb)
16161 ;;;###autoload
16162 (defalias 'org-iswitchb 'org-switchb)
16164 (defun org-buffer-list (&optional predicate exclude-tmp)
16165 "Return a list of Org buffers.
16166 PREDICATE can be `export', `files' or `agenda'.
16168 export restrict the list to Export buffers.
16169 files restrict the list to buffers visiting Org files.
16170 agenda restrict the list to buffers visiting agenda files.
16172 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16173 (let* ((bfn nil)
16174 (agenda-files (and (eq predicate 'agenda)
16175 (mapcar 'file-truename (org-agenda-files t))))
16176 (filter
16177 (cond
16178 ((eq predicate 'files)
16179 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
16180 ((eq predicate 'export)
16181 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16182 ((eq predicate 'agenda)
16183 (lambda (b)
16184 (with-current-buffer b
16185 (and (eq major-mode 'org-mode)
16186 (setq bfn (buffer-file-name b))
16187 (member (file-truename bfn) agenda-files)))))
16188 (t (lambda (b) (with-current-buffer b
16189 (or (eq major-mode 'org-mode)
16190 (string-match "\*Org .*Export"
16191 (buffer-name b)))))))))
16192 (delq nil
16193 (mapcar
16194 (lambda(b)
16195 (if (and (funcall filter b)
16196 (or (not exclude-tmp)
16197 (not (string-match "tmp" (buffer-name b)))))
16199 nil))
16200 (buffer-list)))))
16202 (defun org-agenda-files (&optional unrestricted archives)
16203 "Get the list of agenda files.
16204 Optional UNRESTRICTED means return the full list even if a restriction
16205 is currently in place.
16206 When ARCHIVES is t, include all archive files that are really being
16207 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16208 `org-agenda-archives-mode' is t."
16209 (let ((files
16210 (cond
16211 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16212 ((stringp org-agenda-files) (org-read-agenda-file-list))
16213 ((listp org-agenda-files) org-agenda-files)
16214 (t (error "Invalid value of `org-agenda-files'")))))
16215 (setq files (apply 'append
16216 (mapcar (lambda (f)
16217 (if (file-directory-p f)
16218 (directory-files
16219 f t org-agenda-file-regexp)
16220 (list f)))
16221 files)))
16222 (when org-agenda-skip-unavailable-files
16223 (setq files (delq nil
16224 (mapcar (function
16225 (lambda (file)
16226 (and (file-readable-p file) file)))
16227 files))))
16228 (when (or (eq archives t)
16229 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16230 (setq files (org-add-archive-files files)))
16231 files))
16233 (defun org-agenda-file-p (&optional file)
16234 "Return non-nil, if FILE is an agenda file.
16235 If FILE is omitted, use the file associated with the current
16236 buffer."
16237 (member (or file (buffer-file-name))
16238 (org-agenda-files t)))
16240 (defun org-edit-agenda-file-list ()
16241 "Edit the list of agenda files.
16242 Depending on setup, this either uses customize to edit the variable
16243 `org-agenda-files', or it visits the file that is holding the list. In the
16244 latter case, the buffer is set up in a way that saving it automatically kills
16245 the buffer and restores the previous window configuration."
16246 (interactive)
16247 (if (stringp org-agenda-files)
16248 (let ((cw (current-window-configuration)))
16249 (find-file org-agenda-files)
16250 (org-set-local 'org-window-configuration cw)
16251 (org-add-hook 'after-save-hook
16252 (lambda ()
16253 (set-window-configuration
16254 (prog1 org-window-configuration
16255 (kill-buffer (current-buffer))))
16256 (org-install-agenda-files-menu)
16257 (message "New agenda file list installed"))
16258 nil 'local)
16259 (message "%s" (substitute-command-keys
16260 "Edit list and finish with \\[save-buffer]")))
16261 (customize-variable 'org-agenda-files)))
16263 (defun org-store-new-agenda-file-list (list)
16264 "Set new value for the agenda file list and save it correctly."
16265 (if (stringp org-agenda-files)
16266 (let ((fe (org-read-agenda-file-list t)) b u)
16267 (while (setq b (find-buffer-visiting org-agenda-files))
16268 (kill-buffer b))
16269 (with-temp-file org-agenda-files
16270 (insert
16271 (mapconcat
16272 (lambda (f) ;; Keep un-expanded entries.
16273 (if (setq u (assoc f fe))
16274 (cdr u)
16276 list "\n")
16277 "\n")))
16278 (let ((org-mode-hook nil) (org-inhibit-startup t)
16279 (org-insert-mode-line-in-empty-file nil))
16280 (setq org-agenda-files list)
16281 (customize-save-variable 'org-agenda-files org-agenda-files))))
16283 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16284 "Read the list of agenda files from a file.
16285 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16286 filenames, used by `org-store-new-agenda-file-list' to write back
16287 un-expanded file names."
16288 (when (file-directory-p org-agenda-files)
16289 (error "`org-agenda-files' cannot be a single directory"))
16290 (when (stringp org-agenda-files)
16291 (with-temp-buffer
16292 (insert-file-contents org-agenda-files)
16293 (mapcar
16294 (lambda (f)
16295 (let ((e (expand-file-name (substitute-in-file-name f)
16296 org-directory)))
16297 (if pair-with-expansion
16298 (cons e f)
16299 e)))
16300 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16302 ;;;###autoload
16303 (defun org-cycle-agenda-files ()
16304 "Cycle through the files in `org-agenda-files'.
16305 If the current buffer visits an agenda file, find the next one in the list.
16306 If the current buffer does not, find the first agenda file."
16307 (interactive)
16308 (let* ((fs (org-agenda-files t))
16309 (files (append fs (list (car fs))))
16310 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16311 file)
16312 (unless files (error "No agenda files"))
16313 (catch 'exit
16314 (while (setq file (pop files))
16315 (if (equal (file-truename file) tcf)
16316 (when (car files)
16317 (find-file (car files))
16318 (throw 'exit t))))
16319 (find-file (car fs)))
16320 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16322 (defun org-agenda-file-to-front (&optional to-end)
16323 "Move/add the current file to the top of the agenda file list.
16324 If the file is not present in the list, it is added to the front. If it is
16325 present, it is moved there. With optional argument TO-END, add/move to the
16326 end of the list."
16327 (interactive "P")
16328 (let ((org-agenda-skip-unavailable-files nil)
16329 (file-alist (mapcar (lambda (x)
16330 (cons (file-truename x) x))
16331 (org-agenda-files t)))
16332 (ctf (file-truename buffer-file-name))
16333 x had)
16334 (setq x (assoc ctf file-alist) had x)
16336 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16337 (if to-end
16338 (setq file-alist (append (delq x file-alist) (list x)))
16339 (setq file-alist (cons x (delq x file-alist))))
16340 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16341 (org-install-agenda-files-menu)
16342 (message "File %s to %s of agenda file list"
16343 (if had "moved" "added") (if to-end "end" "front"))))
16345 (defun org-remove-file (&optional file)
16346 "Remove current file from the list of files in variable `org-agenda-files'.
16347 These are the files which are being checked for agenda entries.
16348 Optional argument FILE means use this file instead of the current."
16349 (interactive)
16350 (let* ((org-agenda-skip-unavailable-files nil)
16351 (file (or file buffer-file-name))
16352 (true-file (file-truename file))
16353 (afile (abbreviate-file-name file))
16354 (files (delq nil (mapcar
16355 (lambda (x)
16356 (if (equal true-file
16357 (file-truename x))
16358 nil x))
16359 (org-agenda-files t)))))
16360 (if (not (= (length files) (length (org-agenda-files t))))
16361 (progn
16362 (org-store-new-agenda-file-list files)
16363 (org-install-agenda-files-menu)
16364 (message "Removed file: %s" afile))
16365 (message "File was not in list: %s (not removed)" afile))))
16367 (defun org-file-menu-entry (file)
16368 (vector file (list 'find-file file) t))
16370 (defun org-check-agenda-file (file)
16371 "Make sure FILE exists. If not, ask user what to do."
16372 (when (not (file-exists-p file))
16373 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16374 (abbreviate-file-name file))
16375 (let ((r (downcase (read-char-exclusive))))
16376 (cond
16377 ((equal r ?r)
16378 (org-remove-file file)
16379 (throw 'nextfile t))
16380 (t (error "Abort"))))))
16382 (defun org-get-agenda-file-buffer (file)
16383 "Get a buffer visiting FILE. If the buffer needs to be created, add
16384 it to the list of buffers which might be released later."
16385 (let ((buf (org-find-base-buffer-visiting file)))
16386 (if buf
16387 buf ; just return it
16388 ;; Make a new buffer and remember it
16389 (setq buf (find-file-noselect file))
16390 (if buf (push buf org-agenda-new-buffers))
16391 buf)))
16393 (defun org-release-buffers (blist)
16394 "Release all buffers in list, asking the user for confirmation when needed.
16395 When a buffer is unmodified, it is just killed. When modified, it is saved
16396 \(if the user agrees) and then killed."
16397 (let (buf file)
16398 (while (setq buf (pop blist))
16399 (setq file (buffer-file-name buf))
16400 (when (and (buffer-modified-p buf)
16401 file
16402 (y-or-n-p (format "Save file %s? " file)))
16403 (with-current-buffer buf (save-buffer)))
16404 (kill-buffer buf))))
16406 (defun org-prepare-agenda-buffers (files)
16407 "Create buffers for all agenda files, protect archived trees and comments."
16408 (interactive)
16409 (let ((pa '(:org-archived t))
16410 (pc '(:org-comment t))
16411 (pall '(:org-archived t :org-comment t))
16412 (inhibit-read-only t)
16413 (rea (concat ":" org-archive-tag ":"))
16414 bmp file re)
16415 (save-excursion
16416 (save-restriction
16417 (while (setq file (pop files))
16418 (catch 'nextfile
16419 (if (bufferp file)
16420 (set-buffer file)
16421 (org-check-agenda-file file)
16422 (set-buffer (org-get-agenda-file-buffer file)))
16423 (widen)
16424 (setq bmp (buffer-modified-p))
16425 (org-refresh-category-properties)
16426 (setq org-todo-keywords-for-agenda
16427 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16428 (setq org-done-keywords-for-agenda
16429 (append org-done-keywords-for-agenda org-done-keywords))
16430 (setq org-todo-keyword-alist-for-agenda
16431 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16432 (setq org-drawers-for-agenda
16433 (append org-drawers-for-agenda org-drawers))
16434 (setq org-tag-alist-for-agenda
16435 (append org-tag-alist-for-agenda org-tag-alist))
16437 (save-excursion
16438 (remove-text-properties (point-min) (point-max) pall)
16439 (when org-agenda-skip-archived-trees
16440 (goto-char (point-min))
16441 (while (re-search-forward rea nil t)
16442 (if (org-on-heading-p t)
16443 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16444 (goto-char (point-min))
16445 (setq re (format org-heading-keyword-regexp-format
16446 org-comment-string))
16447 (while (re-search-forward re nil t)
16448 (add-text-properties
16449 (match-beginning 0) (org-end-of-subtree t) pc)))
16450 (set-buffer-modified-p bmp)))))
16451 (setq org-todo-keywords-for-agenda
16452 (org-uniquify org-todo-keywords-for-agenda))
16453 (setq org-todo-keyword-alist-for-agenda
16454 (org-uniquify org-todo-keyword-alist-for-agenda)
16455 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16457 ;;;; Embedded LaTeX
16459 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16460 "Keymap for the minor `org-cdlatex-mode'.")
16462 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16463 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16464 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16465 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16466 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16468 (defvar org-cdlatex-texmathp-advice-is-done nil
16469 "Flag remembering if we have applied the advice to texmathp already.")
16471 (define-minor-mode org-cdlatex-mode
16472 "Toggle the minor `org-cdlatex-mode'.
16473 This mode supports entering LaTeX environment and math in LaTeX fragments
16474 in Org-mode.
16475 \\{org-cdlatex-mode-map}"
16476 nil " OCDL" nil
16477 (when org-cdlatex-mode
16478 (require 'cdlatex)
16479 (run-hooks 'cdlatex-mode-hook)
16480 (cdlatex-compute-tables))
16481 (unless org-cdlatex-texmathp-advice-is-done
16482 (setq org-cdlatex-texmathp-advice-is-done t)
16483 (defadvice texmathp (around org-math-always-on activate)
16484 "Always return t in org-mode buffers.
16485 This is because we want to insert math symbols without dollars even outside
16486 the LaTeX math segments. If Orgmode thinks that point is actually inside
16487 an embedded LaTeX fragment, let texmathp do its job.
16488 \\[org-cdlatex-mode-map]"
16489 (interactive)
16490 (let (p)
16491 (cond
16492 ((not (eq major-mode 'org-mode)) ad-do-it)
16493 ((eq this-command 'cdlatex-math-symbol)
16494 (setq ad-return-value t
16495 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16497 (let ((p (org-inside-LaTeX-fragment-p)))
16498 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16499 (setq ad-return-value t
16500 texmathp-why '("Org-mode embedded math" . 0))
16501 (if p ad-do-it)))))))))
16503 (defun turn-on-org-cdlatex ()
16504 "Unconditionally turn on `org-cdlatex-mode'."
16505 (org-cdlatex-mode 1))
16507 (defun org-inside-LaTeX-fragment-p ()
16508 "Test if point is inside a LaTeX fragment.
16509 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16510 sequence appearing also before point.
16511 Even though the matchers for math are configurable, this function assumes
16512 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16513 delimiters are skipped when they have been removed by customization.
16514 The return value is nil, or a cons cell with the delimiter and the
16515 position of this delimiter.
16517 This function does a reasonably good job, but can locally be fooled by
16518 for example currency specifications. For example it will assume being in
16519 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16520 fragments that are properly closed, but during editing, we have to live
16521 with the uncertainty caused by missing closing delimiters. This function
16522 looks only before point, not after."
16523 (catch 'exit
16524 (let ((pos (point))
16525 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16526 (lim (progn
16527 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16528 (point)))
16529 dd-on str (start 0) m re)
16530 (goto-char pos)
16531 (when dodollar
16532 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16533 re (nth 1 (assoc "$" org-latex-regexps)))
16534 (while (string-match re str start)
16535 (cond
16536 ((= (match-end 0) (length str))
16537 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16538 ((= (match-end 0) (- (length str) 5))
16539 (throw 'exit nil))
16540 (t (setq start (match-end 0))))))
16541 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16542 (goto-char pos)
16543 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16544 (and (match-beginning 2) (throw 'exit nil))
16545 ;; count $$
16546 (while (re-search-backward "\\$\\$" lim t)
16547 (setq dd-on (not dd-on)))
16548 (goto-char pos)
16549 (if dd-on (cons "$$" m))))))
16551 (defun org-inside-latex-macro-p ()
16552 "Is point inside a LaTeX macro or its arguments?"
16553 (save-match-data
16554 (org-in-regexp
16555 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16557 (defun org-try-cdlatex-tab ()
16558 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16559 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16560 - inside a LaTeX fragment, or
16561 - after the first word in a line, where an abbreviation expansion could
16562 insert a LaTeX environment."
16563 (when org-cdlatex-mode
16564 (cond
16565 ((save-excursion
16566 (skip-chars-backward "a-zA-Z0-9*")
16567 (skip-chars-backward " \t")
16568 (bolp))
16569 (cdlatex-tab) t)
16570 ((org-inside-LaTeX-fragment-p)
16571 (cdlatex-tab) t)
16572 (t nil))))
16574 (defun org-cdlatex-underscore-caret (&optional arg)
16575 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16576 Revert to the normal definition outside of these fragments."
16577 (interactive "P")
16578 (if (org-inside-LaTeX-fragment-p)
16579 (call-interactively 'cdlatex-sub-superscript)
16580 (let (org-cdlatex-mode)
16581 (call-interactively (key-binding (vector last-input-event))))))
16583 (defun org-cdlatex-math-modify (&optional arg)
16584 "Execute `cdlatex-math-modify' in LaTeX fragments.
16585 Revert to the normal definition outside of these fragments."
16586 (interactive "P")
16587 (if (org-inside-LaTeX-fragment-p)
16588 (call-interactively 'cdlatex-math-modify)
16589 (let (org-cdlatex-mode)
16590 (call-interactively (key-binding (vector last-input-event))))))
16592 (defvar org-latex-fragment-image-overlays nil
16593 "List of overlays carrying the images of latex fragments.")
16594 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16596 (defun org-remove-latex-fragment-image-overlays ()
16597 "Remove all overlays with LaTeX fragment images in current buffer."
16598 (mapc 'delete-overlay org-latex-fragment-image-overlays)
16599 (setq org-latex-fragment-image-overlays nil))
16601 (defun org-preview-latex-fragment (&optional subtree)
16602 "Preview the LaTeX fragment at point, or all locally or globally.
16603 If the cursor is in a LaTeX fragment, create the image and overlay
16604 it over the source code. If there is no fragment at point, display
16605 all fragments in the current text, from one headline to the next. With
16606 prefix SUBTREE, display all fragments in the current subtree. With a
16607 double prefix arg \\[universal-argument] \\[universal-argument], or when \
16608 the cursor is before the first headline,
16609 display all fragments in the buffer.
16610 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16611 (interactive "P")
16612 (org-remove-latex-fragment-image-overlays)
16613 (save-excursion
16614 (save-restriction
16615 (let (beg end at msg)
16616 (cond
16617 ((or (equal subtree '(16))
16618 (not (save-excursion
16619 (re-search-backward org-outline-regexp-bol nil t))))
16620 (setq beg (point-min) end (point-max)
16621 msg "Creating images for buffer...%s"))
16622 ((equal subtree '(4))
16623 (org-back-to-heading)
16624 (setq beg (point) end (org-end-of-subtree t)
16625 msg "Creating images for subtree...%s"))
16627 (if (setq at (org-inside-LaTeX-fragment-p))
16628 (goto-char (max (point-min) (- (cdr at) 2)))
16629 (org-back-to-heading))
16630 (setq beg (point) end (progn (outline-next-heading) (point))
16631 msg (if at "Creating image...%s"
16632 "Creating images for entry...%s"))))
16633 (message msg "")
16634 (narrow-to-region beg end)
16635 (goto-char beg)
16636 (org-format-latex
16637 (concat "ltxpng/" (file-name-sans-extension
16638 (file-name-nondirectory
16639 buffer-file-name)))
16640 default-directory 'overlays msg at 'forbuffer 'dvipng)
16641 (message msg "done. Use `C-c C-c' to remove images.")))))
16643 (defvar org-latex-regexps
16644 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16645 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16646 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16647 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16648 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16649 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16650 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
16651 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
16652 "Regular expressions for matching embedded LaTeX.")
16654 (defvar org-export-have-math nil) ;; dynamic scoping
16655 (defun org-format-latex (prefix &optional dir overlays msg at
16656 forbuffer processing-type)
16657 "Replace LaTeX fragments with links to an image, and produce images.
16658 Some of the options can be changed using the variable
16659 `org-format-latex-options'."
16660 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16661 (let* ((prefixnodir (file-name-nondirectory prefix))
16662 (absprefix (expand-file-name prefix dir))
16663 (todir (file-name-directory absprefix))
16664 (opt org-format-latex-options)
16665 (matchers (plist-get opt :matchers))
16666 (re-list org-latex-regexps)
16667 (org-format-latex-header-extra
16668 (plist-get (org-infile-export-plist) :latex-header-extra))
16669 (cnt 0) txt hash link beg end re e checkdir
16670 executables-checked string
16671 m n block-type block linkfile movefile ov)
16672 ;; Check the different regular expressions
16673 (while (setq e (pop re-list))
16674 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
16675 block (if block-type "\n\n" ""))
16676 (when (member m matchers)
16677 (goto-char (point-min))
16678 (while (re-search-forward re nil t)
16679 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
16680 (not (get-text-property (match-beginning n)
16681 'org-protected))
16682 (or (not overlays)
16683 (not (eq (get-char-property (match-beginning n)
16684 'org-overlay-type)
16685 'org-latex-overlay))))
16686 (setq org-export-have-math t)
16687 (cond
16688 ((eq processing-type 'verbatim)
16689 ;; Leave the text verbatim, just protect it
16690 (add-text-properties (match-beginning n) (match-end n)
16691 '(org-protected t)))
16692 ((eq processing-type 'mathjax)
16693 ;; Prepare for MathJax processing
16694 (setq string (match-string n))
16695 (if (member m '("$" "$1"))
16696 (save-excursion
16697 (delete-region (match-beginning n) (match-end n))
16698 (goto-char (match-beginning n))
16699 (insert (org-add-props (concat "\\(" (substring string 1 -1)
16700 "\\)")
16701 '(org-protected t))))
16702 (add-text-properties (match-beginning n) (match-end n)
16703 '(org-protected t))))
16704 ((eq processing-type 'dvipng)
16705 ;; Process to an image
16706 (setq txt (match-string n)
16707 beg (match-beginning n) end (match-end n)
16708 cnt (1+ cnt))
16709 (let (print-length print-level) ; make sure full list is printed
16710 (setq hash (sha1 (prin1-to-string
16711 (list org-format-latex-header
16712 org-format-latex-header-extra
16713 org-export-latex-default-packages-alist
16714 org-export-latex-packages-alist
16715 org-format-latex-options
16716 forbuffer txt)))
16717 linkfile (format "%s_%s.png" prefix hash)
16718 movefile (format "%s_%s.png" absprefix hash)))
16719 (setq link (concat block "[[file:" linkfile "]]" block))
16720 (if msg (message msg cnt))
16721 (goto-char beg)
16722 (unless checkdir ; make sure the directory exists
16723 (setq checkdir t)
16724 (or (file-directory-p todir) (make-directory todir t)))
16726 (unless executables-checked
16727 (org-check-external-command
16728 "latex" "needed to convert LaTeX fragments to images")
16729 (org-check-external-command
16730 "dvipng" "needed to convert LaTeX fragments to images")
16731 (setq executables-checked t))
16733 (unless (file-exists-p movefile)
16734 (org-create-formula-image
16735 txt movefile opt forbuffer))
16736 (if overlays
16737 (progn
16738 (mapc (lambda (o)
16739 (if (eq (overlay-get o 'org-overlay-type)
16740 'org-latex-overlay)
16741 (delete-overlay o)))
16742 (overlays-in beg end))
16743 (setq ov (make-overlay beg end))
16744 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
16745 (if (featurep 'xemacs)
16746 (progn
16747 (overlay-put ov 'invisible t)
16748 (overlay-put
16749 ov 'end-glyph
16750 (make-glyph (vector 'png :file movefile))))
16751 (overlay-put
16752 ov 'display
16753 (list 'image :type 'png :file movefile :ascent 'center)))
16754 (push ov org-latex-fragment-image-overlays)
16755 (goto-char end))
16756 (delete-region beg end)
16757 (insert (org-add-props link
16758 (list 'org-latex-src
16759 (replace-regexp-in-string
16760 "\"" "" txt)
16761 'org-latex-src-embed-type
16762 (if block-type 'paragraph 'character))))))
16763 ((eq processing-type 'mathml)
16764 ;; Process to MathML
16765 (unless executables-checked
16766 (unless (save-match-data (org-format-latex-mathml-available-p))
16767 (error "LaTeX to MathML converter not configured"))
16768 (setq executables-checked t))
16769 (setq txt (match-string n)
16770 beg (match-beginning n) end (match-end n)
16771 cnt (1+ cnt))
16772 (if msg (message msg cnt))
16773 (goto-char beg)
16774 (delete-region beg end)
16775 (insert (org-format-latex-as-mathml
16776 txt block-type prefix dir)))
16778 (error "Unknown conversion type %s for latex fragments"
16779 processing-type)))))))))
16781 (defun org-create-math-formula (latex-frag &optional mathml-file)
16782 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
16783 Use `org-latex-to-mathml-convert-command'. If the conversion is
16784 sucessful, return the portion between \"<math...> </math>\"
16785 elements otherwise return nil. When MATHML-FILE is specified,
16786 write the results in to that file. When invoked as an
16787 interactive command, prompt for LATEX-FRAG, with initial value
16788 set to the current active region and echo the results for user
16789 inspection."
16790 (interactive (list (let ((frag (when (region-active-p)
16791 (buffer-substring-no-properties
16792 (region-beginning) (region-end)))))
16793 (read-string "LaTeX Fragment: " frag nil frag))))
16794 (unless latex-frag (error "Invalid latex-frag"))
16795 (let* ((tmp-in-file (file-relative-name
16796 (make-temp-name (expand-file-name "ltxmathml-in"))))
16797 (ignore (write-region latex-frag nil tmp-in-file))
16798 (tmp-out-file (file-relative-name
16799 (make-temp-name (expand-file-name "ltxmathml-out"))))
16800 (cmd (format-spec
16801 org-latex-to-mathml-convert-command
16802 `((?j . ,(shell-quote-argument
16803 (expand-file-name org-latex-to-mathml-jar-file)))
16804 (?I . ,(shell-quote-argument tmp-in-file))
16805 (?o . ,(shell-quote-argument tmp-out-file)))))
16806 mathml shell-command-output)
16807 (when (org-called-interactively-p 'any)
16808 (unless (org-format-latex-mathml-available-p)
16809 (error "LaTeX to MathML converter not configured")))
16810 (message "Running %s" cmd)
16811 (setq shell-command-output (shell-command-to-string cmd))
16812 (setq mathml
16813 (when (file-readable-p tmp-out-file)
16814 (with-current-buffer (find-file-noselect tmp-out-file t)
16815 (goto-char (point-min))
16816 (when (re-search-forward
16817 (concat
16818 (regexp-quote
16819 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
16820 "\\(.\\|\n\\)*"
16821 (regexp-quote "</math>")) nil t)
16822 (prog1 (match-string 0) (kill-buffer))))))
16823 (cond
16824 (mathml
16825 (setq mathml
16826 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
16827 (when mathml-file
16828 (write-region mathml nil mathml-file))
16829 (when (org-called-interactively-p 'any)
16830 (message mathml)))
16831 ((message "LaTeX to MathML conversion failed")
16832 (message shell-command-output)))
16833 (delete-file tmp-in-file)
16834 (when (file-exists-p tmp-out-file)
16835 (delete-file tmp-out-file))
16836 mathml))
16838 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
16839 prefix &optional dir)
16840 "Use `org-create-math-formula' but check local cache first."
16841 (let* ((absprefix (expand-file-name prefix dir))
16842 (print-length nil) (print-level nil)
16843 (formula-id (concat
16844 "formula-"
16845 (sha1
16846 (prin1-to-string
16847 (list latex-frag
16848 org-latex-to-mathml-convert-command)))))
16849 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
16850 (formula-cache-dir (file-name-directory formula-cache)))
16852 (unless (file-directory-p formula-cache-dir)
16853 (make-directory formula-cache-dir t))
16855 (unless (file-exists-p formula-cache)
16856 (org-create-math-formula latex-frag formula-cache))
16858 (if (file-exists-p formula-cache)
16859 ;; Successful conversion. Return the link to MathML file.
16860 (org-add-props
16861 (format "[[file:%s]]" (file-relative-name formula-cache dir))
16862 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
16863 'org-latex-src-embed-type (if latex-frag-type
16864 'paragraph 'character)))
16865 ;; Failed conversion. Return the LaTeX fragment verbatim
16866 (add-text-properties
16867 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
16868 latex-frag)))
16870 ;; This function borrows from Ganesh Swami's latex2png.el
16871 (defun org-create-formula-image (string tofile options buffer)
16872 "This calls dvipng."
16873 (require 'org-latex)
16874 (let* ((tmpdir (if (featurep 'xemacs)
16875 (temp-directory)
16876 temporary-file-directory))
16877 (texfilebase (make-temp-name
16878 (expand-file-name "orgtex" tmpdir)))
16879 (texfile (concat texfilebase ".tex"))
16880 (dvifile (concat texfilebase ".dvi"))
16881 (pngfile (concat texfilebase ".png"))
16882 (fnh (if (featurep 'xemacs)
16883 (font-height (get-face-font 'default))
16884 (face-attribute 'default :height nil)))
16885 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
16886 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
16887 (fg (or (plist-get options (if buffer :foreground :html-foreground))
16888 "Black"))
16889 (bg (or (plist-get options (if buffer :background :html-background))
16890 "Transparent")))
16891 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
16892 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
16893 (with-temp-file texfile
16894 (insert (org-splice-latex-header
16895 org-format-latex-header
16896 org-export-latex-default-packages-alist
16897 org-export-latex-packages-alist t
16898 org-format-latex-header-extra))
16899 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
16900 (require 'org-latex)
16901 (org-export-latex-fix-inputenc))
16902 (let ((dir default-directory))
16903 (condition-case nil
16904 (progn
16905 (cd tmpdir)
16906 (call-process "latex" nil nil nil texfile))
16907 (error nil))
16908 (cd dir))
16909 (if (not (file-exists-p dvifile))
16910 (progn (message "Failed to create dvi file from %s" texfile) nil)
16911 (condition-case nil
16912 (call-process "dvipng" nil nil nil
16913 "-fg" fg "-bg" bg
16914 "-D" dpi
16915 ;;"-x" scale "-y" scale
16916 "-T" "tight"
16917 "-o" pngfile
16918 dvifile)
16919 (error nil))
16920 (if (not (file-exists-p pngfile))
16921 (if org-format-latex-signal-error
16922 (error "Failed to create png file from %s" texfile)
16923 (message "Failed to create png file from %s" texfile)
16924 nil)
16925 ;; Use the requested file name and clean up
16926 (copy-file pngfile tofile 'replace)
16927 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
16928 (delete-file (concat texfilebase e)))
16929 pngfile))))
16931 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
16932 "Fill a LaTeX header template TPL.
16933 In the template, the following place holders will be recognized:
16935 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
16936 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
16937 [PACKAGES] \\usepackage statements for PKG
16938 [NO-PACKAGES] do not include PKG
16939 [EXTRA] the string EXTRA
16940 [NO-EXTRA] do not include EXTRA
16942 For backward compatibility, if both the positive and the negative place
16943 holder is missing, the positive one (without the \"NO-\") will be
16944 assumed to be present at the end of the template.
16945 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
16946 EXTRA is a string.
16947 SNIPPETS-P indicates if this is run to create snippet images for HTML."
16948 (let (rpl (end ""))
16949 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
16950 (setq rpl (if (or (match-end 1) (not def-pkg))
16951 "" (org-latex-packages-to-string def-pkg snippets-p t))
16952 tpl (replace-match rpl t t tpl))
16953 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
16955 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
16956 (setq rpl (if (or (match-end 1) (not pkg))
16957 "" (org-latex-packages-to-string pkg snippets-p t))
16958 tpl (replace-match rpl t t tpl))
16959 (if pkg (setq end
16960 (concat end "\n"
16961 (org-latex-packages-to-string pkg snippets-p)))))
16963 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
16964 (setq rpl (if (or (match-end 1) (not extra))
16965 "" (concat extra "\n"))
16966 tpl (replace-match rpl t t tpl))
16967 (if (and extra (string-match "\\S-" extra))
16968 (setq end (concat end "\n" extra))))
16970 (if (string-match "\\S-" end)
16971 (concat tpl "\n" end)
16972 tpl)))
16974 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
16975 "Turn an alist of packages into a string with the \\usepackage macros."
16976 (setq pkg (mapconcat (lambda(p)
16977 (cond
16978 ((stringp p) p)
16979 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
16980 (format "%% Package %s omitted" (cadr p)))
16981 ((equal "" (car p))
16982 (format "\\usepackage{%s}" (cadr p)))
16984 (format "\\usepackage[%s]{%s}"
16985 (car p) (cadr p)))))
16987 "\n"))
16988 (if newline (concat pkg "\n") pkg))
16990 (defun org-dvipng-color (attr)
16991 "Return an rgb color specification for dvipng."
16992 (apply 'format "rgb %s %s %s"
16993 (mapcar 'org-normalize-color
16994 (color-values (face-attribute 'default attr nil)))))
16996 (defun org-normalize-color (value)
16997 "Return string to be used as color value for an RGB component."
16998 (format "%g" (/ value 65535.0)))
17000 ;; Image display
17003 (defvar org-inline-image-overlays nil)
17004 (make-variable-buffer-local 'org-inline-image-overlays)
17006 (defun org-toggle-inline-images (&optional include-linked)
17007 "Toggle the display of inline images.
17008 INCLUDE-LINKED is passed to `org-display-inline-images'."
17009 (interactive "P")
17010 (if org-inline-image-overlays
17011 (progn
17012 (org-remove-inline-images)
17013 (message "Inline image display turned off"))
17014 (org-display-inline-images include-linked)
17015 (if org-inline-image-overlays
17016 (message "%d images displayed inline"
17017 (length org-inline-image-overlays))
17018 (message "No images to display inline"))))
17020 (defun org-display-inline-images (&optional include-linked refresh beg end)
17021 "Display inline images.
17022 Normally only links without a description part are inlined, because this
17023 is how it will work for export. When INCLUDE-LINKED is set, also links
17024 with a description part will be inlined. This can be nice for a quick
17025 look at those images, but it does not reflect what exported files will look
17026 like.
17027 When REFRESH is set, refresh existing images between BEG and END.
17028 This will create new image displays only if necessary.
17029 BEG and END default to the buffer boundaries."
17030 (interactive "P")
17031 (unless refresh
17032 (org-remove-inline-images)
17033 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17034 (save-excursion
17035 (save-restriction
17036 (widen)
17037 (setq beg (or beg (point-min)) end (or end (point-max)))
17038 (goto-char (point-min))
17039 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17040 (substring (org-image-file-name-regexp) 0 -2)
17041 "\\)\\]" (if include-linked "" "\\]")))
17042 old file ov img)
17043 (while (re-search-forward re end t)
17044 (setq old (get-char-property-and-overlay (match-beginning 1)
17045 'org-image-overlay))
17046 (setq file (expand-file-name
17047 (concat (or (match-string 3) "") (match-string 4))))
17048 (when (file-exists-p file)
17049 (if (and (car-safe old) refresh)
17050 (image-refresh (overlay-get (cdr old) 'display))
17051 (setq img (save-match-data (create-image file)))
17052 (when img
17053 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17054 (overlay-put ov 'display img)
17055 (overlay-put ov 'face 'default)
17056 (overlay-put ov 'org-image-overlay t)
17057 (overlay-put ov 'modification-hooks
17058 (list 'org-display-inline-modification-hook))
17059 (push ov org-inline-image-overlays)))))))))
17061 (defun org-display-inline-modification-hook (ov after beg end &optional len)
17062 "Remove inline-display overlay if a corresponding region is modified."
17063 (let ((inhibit-modification-hooks t))
17064 (when (and ov after)
17065 (delete ov org-inline-image-overlays)
17066 (delete-overlay ov))))
17068 (defun org-remove-inline-images ()
17069 "Remove inline display of images."
17070 (interactive)
17071 (mapc 'delete-overlay org-inline-image-overlays)
17072 (setq org-inline-image-overlays nil))
17074 ;;;; Key bindings
17076 ;; Remap outline keys
17077 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17078 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17080 ;; Make `C-c C-x' a prefix key
17081 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17083 ;; TAB key with modifiers
17084 (org-defkey org-mode-map "\C-i" 'org-cycle)
17085 (org-defkey org-mode-map [(tab)] 'org-cycle)
17086 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17087 (org-defkey org-mode-map [(meta tab)] 'pcomplete)
17088 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17089 (org-defkey org-mode-map "\M-\C-i" 'pcomplete)
17090 ;; The following line is necessary under Suse GNU/Linux
17091 (unless (featurep 'xemacs)
17092 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17093 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17094 (define-key org-mode-map [backtab] 'org-shifttab)
17096 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17097 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17098 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17100 ;; Cursor keys with modifiers
17101 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17102 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17103 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17104 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17106 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17107 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17108 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17109 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17111 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17112 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17113 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17114 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17116 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17117 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17118 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17119 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17121 ;; Babel keys
17122 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17123 (mapc (lambda (pair)
17124 (define-key org-babel-map (car pair) (cdr pair)))
17125 org-babel-key-bindings)
17127 ;;; Extra keys for tty access.
17128 ;; We only set them when really needed because otherwise the
17129 ;; menus don't show the simple keys
17131 (when (or org-use-extra-keys
17132 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17133 (not window-system))
17134 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17135 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17136 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17137 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17138 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17139 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17140 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17141 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17142 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17143 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17144 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17145 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17146 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17147 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17148 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17149 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17150 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17151 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17152 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17153 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17154 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17155 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17156 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17157 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17158 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17159 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17160 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17161 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17163 ;; All the other keys
17165 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17166 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17167 (if (boundp 'narrow-map)
17168 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17169 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17170 (if (boundp 'narrow-map)
17171 (org-defkey narrow-map "b" 'org-narrow-to-block)
17172 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17173 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
17174 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
17175 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17176 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17177 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17178 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17179 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17180 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17181 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17182 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17183 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17184 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17185 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17186 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17187 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17188 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17189 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17190 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17191 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17192 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17193 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17194 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17195 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
17196 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
17197 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
17198 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
17199 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
17200 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
17201 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
17202 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
17203 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17204 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17205 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17206 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17207 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
17208 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
17209 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17210 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
17211 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
17212 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
17213 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
17214 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17215 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
17216 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
17217 (org-defkey org-mode-map "\C-c^" 'org-sort)
17218 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
17219 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
17220 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
17221 (org-defkey org-mode-map "\C-m" 'org-return)
17222 (org-defkey org-mode-map "\C-j" 'org-return-indent)
17223 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
17224 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
17225 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
17226 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
17227 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
17228 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
17229 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
17230 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
17231 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
17232 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
17233 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
17234 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
17235 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
17236 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
17237 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
17238 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
17239 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
17240 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
17241 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
17242 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
17243 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
17245 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
17246 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
17247 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
17248 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
17250 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
17251 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
17252 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
17253 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
17254 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
17255 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
17256 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
17257 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
17258 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
17259 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
17260 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
17261 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
17262 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
17263 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
17264 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
17265 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
17266 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
17267 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
17269 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
17270 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
17271 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
17272 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
17273 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
17275 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
17277 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
17279 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
17280 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
17282 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
17285 (when (featurep 'xemacs)
17286 (org-defkey org-mode-map 'button3 'popup-mode-menu))
17289 (defconst org-speed-commands-default
17291 ("Outline Navigation")
17292 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
17293 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
17294 ("f" . (org-speed-move-safe 'org-forward-same-level))
17295 ("b" . (org-speed-move-safe 'org-backward-same-level))
17296 ("u" . (org-speed-move-safe 'outline-up-heading))
17297 ("j" . org-goto)
17298 ("g" . (org-refile t))
17299 ("Outline Visibility")
17300 ("c" . org-cycle)
17301 ("C" . org-shifttab)
17302 (" " . org-display-outline-path)
17303 ("Outline Structure Editing")
17304 ("U" . org-shiftmetaup)
17305 ("D" . org-shiftmetadown)
17306 ("r" . org-metaright)
17307 ("l" . org-metaleft)
17308 ("R" . org-shiftmetaright)
17309 ("L" . org-shiftmetaleft)
17310 ("i" . (progn (forward-char 1) (call-interactively
17311 'org-insert-heading-respect-content)))
17312 ("^" . org-sort)
17313 ("w" . org-refile)
17314 ("a" . org-archive-subtree-default-with-confirmation)
17315 ("." . org-mark-subtree)
17316 ("Clock Commands")
17317 ("I" . org-clock-in)
17318 ("O" . org-clock-out)
17319 ("Meta Data Editing")
17320 ("t" . org-todo)
17321 ("0" . (org-priority ?\ ))
17322 ("1" . (org-priority ?A))
17323 ("2" . (org-priority ?B))
17324 ("3" . (org-priority ?C))
17325 (";" . org-set-tags-command)
17326 ("e" . org-set-effort)
17327 ("Agenda Views etc")
17328 ("v" . org-agenda)
17329 ("/" . org-sparse-tree)
17330 ("Misc")
17331 ("o" . org-open-at-point)
17332 ("?" . org-speed-command-help)
17333 ("<" . (org-agenda-set-restriction-lock 'subtree))
17334 (">" . (org-agenda-remove-restriction-lock))
17336 "The default speed commands.")
17338 (defun org-print-speed-command (e)
17339 (if (> (length (car e)) 1)
17340 (progn
17341 (princ "\n")
17342 (princ (car e))
17343 (princ "\n")
17344 (princ (make-string (length (car e)) ?-))
17345 (princ "\n"))
17346 (princ (car e))
17347 (princ " ")
17348 (if (symbolp (cdr e))
17349 (princ (symbol-name (cdr e)))
17350 (prin1 (cdr e)))
17351 (princ "\n")))
17353 (defun org-speed-command-help ()
17354 "Show the available speed commands."
17355 (interactive)
17356 (if (not org-use-speed-commands)
17357 (error "Speed commands are not activated, customize `org-use-speed-commands'")
17358 (with-output-to-temp-buffer "*Help*"
17359 (princ "User-defined Speed commands\n===========================\n")
17360 (mapc 'org-print-speed-command org-speed-commands-user)
17361 (princ "\n")
17362 (princ "Built-in Speed commands\n=======================\n")
17363 (mapc 'org-print-speed-command org-speed-commands-default))
17364 (with-current-buffer "*Help*"
17365 (setq truncate-lines t))))
17367 (defun org-speed-move-safe (cmd)
17368 "Execute CMD, but make sure that the cursor always ends up in a headline.
17369 If not, return to the original position and throw an error."
17370 (interactive)
17371 (let ((pos (point)))
17372 (call-interactively cmd)
17373 (unless (and (bolp) (org-on-heading-p))
17374 (goto-char pos)
17375 (error "Boundary reached while executing %s" cmd))))
17377 (defvar org-self-insert-command-undo-counter 0)
17379 (defvar org-table-auto-blank-field) ; defined in org-table.el
17380 (defvar org-speed-command nil)
17382 (defun org-speed-command-default-hook (keys)
17383 "Hook for activating single-letter speed commands.
17384 `org-speed-commands-default' specifies a minimal command set.
17385 Use `org-speed-commands-user' for further customization."
17386 (when (or (and (bolp) (looking-at org-outline-regexp))
17387 (and (functionp org-use-speed-commands)
17388 (funcall org-use-speed-commands)))
17389 (cdr (assoc keys (append org-speed-commands-user
17390 org-speed-commands-default)))))
17392 (defun org-babel-speed-command-hook (keys)
17393 "Hook for activating single-letter code block commands."
17394 (when (and (bolp) (looking-at org-babel-src-block-regexp))
17395 (cdr (assoc keys org-babel-key-bindings))))
17397 (defcustom org-speed-command-hook
17398 '(org-speed-command-default-hook org-babel-speed-command-hook)
17399 "Hook for activating speed commands at strategic locations.
17400 Hook functions are called in sequence until a valid handler is
17401 found.
17403 Each hook takes a single argument, a user-pressed command key
17404 which is also a `self-insert-command' from the global map.
17406 Within the hook, examine the cursor position and the command key
17407 and return nil or a valid handler as appropriate. Handler could
17408 be one of an interactive command, a function, or a form.
17410 Set `org-use-speed-commands' to non-nil value to enable this
17411 hook. The default setting is `org-speed-command-default-hook'."
17412 :group 'org-structure
17413 :type 'hook)
17415 (defun org-self-insert-command (N)
17416 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
17417 If the cursor is in a table looking at whitespace, the whitespace is
17418 overwritten, and the table is not marked as requiring realignment."
17419 (interactive "p")
17420 (org-check-before-invisible-edit 'insert)
17421 (cond
17422 ((and org-use-speed-commands
17423 (setq org-speed-command
17424 (run-hook-with-args-until-success
17425 'org-speed-command-hook (this-command-keys))))
17426 (cond
17427 ((commandp org-speed-command)
17428 (setq this-command org-speed-command)
17429 (call-interactively org-speed-command))
17430 ((functionp org-speed-command)
17431 (funcall org-speed-command))
17432 ((and org-speed-command (listp org-speed-command))
17433 (eval org-speed-command))
17434 (t (let (org-use-speed-commands)
17435 (call-interactively 'org-self-insert-command)))))
17436 ((and
17437 (org-table-p)
17438 (progn
17439 ;; check if we blank the field, and if that triggers align
17440 (and (featurep 'org-table) org-table-auto-blank-field
17441 (member last-command
17442 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
17443 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
17444 ;; got extra space, this field does not determine column width
17445 (let (org-table-may-need-update) (org-table-blank-field))
17446 ;; no extra space, this field may determine column width
17447 (org-table-blank-field)))
17449 (eq N 1)
17450 (looking-at "[^|\n]* |"))
17451 (let (org-table-may-need-update)
17452 (goto-char (1- (match-end 0)))
17453 (delete-char -1)
17454 (goto-char (match-beginning 0))
17455 (self-insert-command N)))
17457 (setq org-table-may-need-update t)
17458 (self-insert-command N)
17459 (org-fix-tags-on-the-fly)
17460 (if org-self-insert-cluster-for-undo
17461 (if (not (eq last-command 'org-self-insert-command))
17462 (setq org-self-insert-command-undo-counter 1)
17463 (if (>= org-self-insert-command-undo-counter 20)
17464 (setq org-self-insert-command-undo-counter 1)
17465 (and (> org-self-insert-command-undo-counter 0)
17466 buffer-undo-list (listp buffer-undo-list)
17467 (not (cadr buffer-undo-list)) ; remove nil entry
17468 (setcdr buffer-undo-list (cddr buffer-undo-list)))
17469 (setq org-self-insert-command-undo-counter
17470 (1+ org-self-insert-command-undo-counter))))))))
17472 (defun org-check-before-invisible-edit (kind)
17473 "Check is editing if kind KIND would be dangerous with invisible text around.
17474 The detailed reaction depends on the user option `org-catch-invisible-edits'."
17475 ;; First, try to get out of here as quickly as possible, to reduce overhead
17476 (if (and org-catch-invisible-edits
17477 (or (not (boundp 'visible-mode)) (not visible-mode))
17478 (or (get-char-property (point) 'invisible)
17479 (get-char-property (max (point-min) (1- (point))) 'invisible)))
17480 ;; OK, we need to take a closer look
17481 (let* ((invisible-at-point (get-char-property (point) 'invisible))
17482 (invisible-before-point (if (bobp) nil (get-char-property
17483 (1- (point)) 'invisible)))
17484 (border-and-ok-direction
17486 ;; Check if we are acting predictably before invisible text
17487 (and invisible-at-point (not invisible-before-point)
17488 (memq kind '(insert delete-backward)))
17489 ;; Check if we are acting predictably after invisible text
17490 ;; This works not well, and I have turned it off. It seems
17491 ;; better to always show and stop after invisible text.
17492 ;; (and (not invisible-at-point) invisible-before-point
17493 ;; (memq kind '(insert delete)))
17496 (when (or (memq invisible-at-point '(outline org-hide-block))
17497 (memq invisible-before-point '(outline org-hide-block)))
17498 (if (eq org-catch-invisible-edits 'error)
17499 (error "Editing in invisible areas is prohibited - make visible first"))
17500 ;; Make the area visible
17501 (save-excursion
17502 (if invisible-before-point
17503 (goto-char (previous-single-char-property-change
17504 (point) 'invisible)))
17505 (org-cycle))
17506 (cond
17507 ((eq org-catch-invisible-edits 'show)
17508 ;; That's it, we do the edit after showing
17509 (message
17510 "Unfolding invisible region around point before editing")
17511 (sit-for 1))
17512 ((and (eq org-catch-invisible-edits 'smart)
17513 border-and-ok-direction)
17514 (message "Unfolding invisible region around point before editing"))
17516 ;; Don't do the edit, make the user repeat it in full visibility
17517 (error "Edit in invisible region aborted, repeat to confirm with text visible")))))))
17519 (defun org-fix-tags-on-the-fly ()
17520 (when (and (equal (char-after (point-at-bol)) ?*)
17521 (org-on-heading-p))
17522 (org-align-tags-here org-tags-column)))
17524 (defun org-delete-backward-char (N)
17525 "Like `delete-backward-char', insert whitespace at field end in tables.
17526 When deleting backwards, in tables this function will insert whitespace in
17527 front of the next \"|\" separator, to keep the table aligned. The table will
17528 still be marked for re-alignment if the field did fill the entire column,
17529 because, in this case the deletion might narrow the column."
17530 (interactive "p")
17531 (org-check-before-invisible-edit 'delete-backward)
17532 (if (and (org-table-p)
17533 (eq N 1)
17534 (string-match "|" (buffer-substring (point-at-bol) (point)))
17535 (looking-at ".*?|"))
17536 (let ((pos (point))
17537 (noalign (looking-at "[^|\n\r]* |"))
17538 (c org-table-may-need-update))
17539 (backward-delete-char N)
17540 (if (not overwrite-mode)
17541 (progn
17542 (skip-chars-forward "^|")
17543 (insert " ")
17544 (goto-char (1- pos))))
17545 ;; noalign: if there were two spaces at the end, this field
17546 ;; does not determine the width of the column.
17547 (if noalign (setq org-table-may-need-update c)))
17548 (backward-delete-char N)
17549 (org-fix-tags-on-the-fly)))
17551 (defun org-delete-char (N)
17552 "Like `delete-char', but insert whitespace at field end in tables.
17553 When deleting characters, in tables this function will insert whitespace in
17554 front of the next \"|\" separator, to keep the table aligned. The table will
17555 still be marked for re-alignment if the field did fill the entire column,
17556 because, in this case the deletion might narrow the column."
17557 (interactive "p")
17558 (org-check-before-invisible-edit 'delete)
17559 (if (and (org-table-p)
17560 (not (bolp))
17561 (not (= (char-after) ?|))
17562 (eq N 1))
17563 (if (looking-at ".*?|")
17564 (let ((pos (point))
17565 (noalign (looking-at "[^|\n\r]* |"))
17566 (c org-table-may-need-update))
17567 (replace-match (concat
17568 (substring (match-string 0) 1 -1)
17569 " |"))
17570 (goto-char pos)
17571 ;; noalign: if there were two spaces at the end, this field
17572 ;; does not determine the width of the column.
17573 (if noalign (setq org-table-may-need-update c)))
17574 (delete-char N))
17575 (delete-char N)
17576 (org-fix-tags-on-the-fly)))
17578 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
17579 (put 'org-self-insert-command 'delete-selection t)
17580 (put 'orgtbl-self-insert-command 'delete-selection t)
17581 (put 'org-delete-char 'delete-selection 'supersede)
17582 (put 'org-delete-backward-char 'delete-selection 'supersede)
17583 (put 'org-yank 'delete-selection 'yank)
17585 ;; Make `flyspell-mode' delay after some commands
17586 (put 'org-self-insert-command 'flyspell-delayed t)
17587 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
17588 (put 'org-delete-char 'flyspell-delayed t)
17589 (put 'org-delete-backward-char 'flyspell-delayed t)
17591 ;; Make pabbrev-mode expand after org-mode commands
17592 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
17593 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
17595 ;; How to do this: Measure non-white length of current string
17596 ;; If equal to column width, we should realign.
17598 (defun org-remap (map &rest commands)
17599 "In MAP, remap the functions given in COMMANDS.
17600 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
17601 (let (new old)
17602 (while commands
17603 (setq old (pop commands) new (pop commands))
17604 (if (fboundp 'command-remapping)
17605 (org-defkey map (vector 'remap old) new)
17606 (substitute-key-definition old new map global-map)))))
17608 (when (eq org-enable-table-editor 'optimized)
17609 ;; If the user wants maximum table support, we need to hijack
17610 ;; some standard editing functions
17611 (org-remap org-mode-map
17612 'self-insert-command 'org-self-insert-command
17613 'delete-char 'org-delete-char
17614 'delete-backward-char 'org-delete-backward-char)
17615 (org-defkey org-mode-map "|" 'org-force-self-insert))
17617 (defvar org-ctrl-c-ctrl-c-hook nil
17618 "Hook for functions attaching themselves to `C-c C-c'.
17620 This can be used to add additional functionality to the C-c C-c
17621 key which executes context-dependent commands. This hook is run
17622 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
17623 run after the last test.
17625 Each function will be called with no arguments. The function
17626 must check if the context is appropriate for it to act. If yes,
17627 it should do its thing and then return a non-nil value. If the
17628 context is wrong, just do nothing and return nil.")
17630 (defvar org-ctrl-c-ctrl-c-final-hook nil
17631 "Hook for functions attaching themselves to `C-c C-c'.
17633 This can be used to add additional functionality to the C-c C-c
17634 key which executes context-dependent commands. This hook is run
17635 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
17636 before the first test.
17638 Each function will be called with no arguments. The function
17639 must check if the context is appropriate for it to act. If yes,
17640 it should do its thing and then return a non-nil value. If the
17641 context is wrong, just do nothing and return nil.")
17643 (defvar org-tab-first-hook nil
17644 "Hook for functions to attach themselves to TAB.
17645 See `org-ctrl-c-ctrl-c-hook' for more information.
17646 This hook runs as the first action when TAB is pressed, even before
17647 `org-cycle' messes around with the `outline-regexp' to cater for
17648 inline tasks and plain list item folding.
17649 If any function in this hook returns t, any other actions that
17650 would have been caused by TAB (such as table field motion or visibility
17651 cycling) will not occur.")
17653 (defvar org-tab-after-check-for-table-hook nil
17654 "Hook for functions to attach themselves to TAB.
17655 See `org-ctrl-c-ctrl-c-hook' for more information.
17656 This hook runs after it has been established that the cursor is not in a
17657 table, but before checking if the cursor is in a headline or if global cycling
17658 should be done.
17659 If any function in this hook returns t, not other actions like visibility
17660 cycling will be done.")
17662 (defvar org-tab-after-check-for-cycling-hook nil
17663 "Hook for functions to attach themselves to TAB.
17664 See `org-ctrl-c-ctrl-c-hook' for more information.
17665 This hook runs after it has been established that not table field motion and
17666 not visibility should be done because of current context. This is probably
17667 the place where a package like yasnippets can hook in.")
17669 (defvar org-tab-before-tab-emulation-hook nil
17670 "Hook for functions to attach themselves to TAB.
17671 See `org-ctrl-c-ctrl-c-hook' for more information.
17672 This hook runs after every other options for TAB have been exhausted, but
17673 before indentation and \t insertion takes place.")
17675 (defvar org-metaleft-hook nil
17676 "Hook for functions attaching themselves to `M-left'.
17677 See `org-ctrl-c-ctrl-c-hook' for more information.")
17678 (defvar org-metaright-hook nil
17679 "Hook for functions attaching themselves to `M-right'.
17680 See `org-ctrl-c-ctrl-c-hook' for more information.")
17681 (defvar org-metaup-hook nil
17682 "Hook for functions attaching themselves to `M-up'.
17683 See `org-ctrl-c-ctrl-c-hook' for more information.")
17684 (defvar org-metadown-hook nil
17685 "Hook for functions attaching themselves to `M-down'.
17686 See `org-ctrl-c-ctrl-c-hook' for more information.")
17687 (defvar org-shiftmetaleft-hook nil
17688 "Hook for functions attaching themselves to `M-S-left'.
17689 See `org-ctrl-c-ctrl-c-hook' for more information.")
17690 (defvar org-shiftmetaright-hook nil
17691 "Hook for functions attaching themselves to `M-S-right'.
17692 See `org-ctrl-c-ctrl-c-hook' for more information.")
17693 (defvar org-shiftmetaup-hook nil
17694 "Hook for functions attaching themselves to `M-S-up'.
17695 See `org-ctrl-c-ctrl-c-hook' for more information.")
17696 (defvar org-shiftmetadown-hook nil
17697 "Hook for functions attaching themselves to `M-S-down'.
17698 See `org-ctrl-c-ctrl-c-hook' for more information.")
17699 (defvar org-metareturn-hook nil
17700 "Hook for functions attaching themselves to `M-RET'.
17701 See `org-ctrl-c-ctrl-c-hook' for more information.")
17702 (defvar org-shiftup-hook nil
17703 "Hook for functions attaching themselves to `S-up'.
17704 See `org-ctrl-c-ctrl-c-hook' for more information.")
17705 (defvar org-shiftup-final-hook nil
17706 "Hook for functions attaching themselves to `S-up'.
17707 This one runs after all other options except shift-select have been excluded.
17708 See `org-ctrl-c-ctrl-c-hook' for more information.")
17709 (defvar org-shiftdown-hook nil
17710 "Hook for functions attaching themselves to `S-down'.
17711 See `org-ctrl-c-ctrl-c-hook' for more information.")
17712 (defvar org-shiftdown-final-hook nil
17713 "Hook for functions attaching themselves to `S-down'.
17714 This one runs after all other options except shift-select have been excluded.
17715 See `org-ctrl-c-ctrl-c-hook' for more information.")
17716 (defvar org-shiftleft-hook nil
17717 "Hook for functions attaching themselves to `S-left'.
17718 See `org-ctrl-c-ctrl-c-hook' for more information.")
17719 (defvar org-shiftleft-final-hook nil
17720 "Hook for functions attaching themselves to `S-left'.
17721 This one runs after all other options except shift-select have been excluded.
17722 See `org-ctrl-c-ctrl-c-hook' for more information.")
17723 (defvar org-shiftright-hook nil
17724 "Hook for functions attaching themselves to `S-right'.
17725 See `org-ctrl-c-ctrl-c-hook' for more information.")
17726 (defvar org-shiftright-final-hook nil
17727 "Hook for functions attaching themselves to `S-right'.
17728 This one runs after all other options except shift-select have been excluded.
17729 See `org-ctrl-c-ctrl-c-hook' for more information.")
17731 (defun org-modifier-cursor-error ()
17732 "Throw an error, a modified cursor command was applied in wrong context."
17733 (error "This command is active in special context like tables, headlines or items"))
17735 (defun org-shiftselect-error ()
17736 "Throw an error because Shift-Cursor command was applied in wrong context."
17737 (if (and (boundp 'shift-select-mode) shift-select-mode)
17738 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
17739 (error "This command works only in special context like headlines or timestamps")))
17741 (defun org-call-for-shift-select (cmd)
17742 (let ((this-command-keys-shift-translated t))
17743 (call-interactively cmd)))
17745 (defun org-shifttab (&optional arg)
17746 "Global visibility cycling or move to previous table field.
17747 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
17748 on context.
17749 See the individual commands for more information."
17750 (interactive "P")
17751 (cond
17752 ((org-at-table-p) (call-interactively 'org-table-previous-field))
17753 ((integerp arg)
17754 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
17755 (message "Content view to level: %d" arg)
17756 (org-content (prefix-numeric-value arg2))
17757 (setq org-cycle-global-status 'overview)))
17758 (t (call-interactively 'org-global-cycle))))
17760 (defun org-shiftmetaleft ()
17761 "Promote subtree or delete table column.
17762 Calls `org-promote-subtree', `org-outdent-item',
17763 or `org-table-delete-column', depending on context.
17764 See the individual commands for more information."
17765 (interactive)
17766 (cond
17767 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
17768 ((org-at-table-p) (call-interactively 'org-table-delete-column))
17769 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
17770 ((org-at-item-p) (call-interactively 'org-outdent-item-tree))
17771 (t (org-modifier-cursor-error))))
17773 (defun org-shiftmetaright ()
17774 "Demote subtree or insert table column.
17775 Calls `org-demote-subtree', `org-indent-item',
17776 or `org-table-insert-column', depending on context.
17777 See the individual commands for more information."
17778 (interactive)
17779 (cond
17780 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
17781 ((org-at-table-p) (call-interactively 'org-table-insert-column))
17782 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
17783 ((org-at-item-p) (call-interactively 'org-indent-item-tree))
17784 (t (org-modifier-cursor-error))))
17786 (defun org-shiftmetaup (&optional arg)
17787 "Move subtree up or kill table row.
17788 Calls `org-move-subtree-up' or `org-table-kill-row' or
17789 `org-move-item-up' depending on context. See the individual commands
17790 for more information."
17791 (interactive "P")
17792 (cond
17793 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
17794 ((org-at-table-p) (call-interactively 'org-table-kill-row))
17795 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17796 ((org-at-item-p) (call-interactively 'org-move-item-up))
17797 (t (org-modifier-cursor-error))))
17799 (defun org-shiftmetadown (&optional arg)
17800 "Move subtree down or insert table row.
17801 Calls `org-move-subtree-down' or `org-table-insert-row' or
17802 `org-move-item-down', depending on context. See the individual
17803 commands for more information."
17804 (interactive "P")
17805 (cond
17806 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
17807 ((org-at-table-p) (call-interactively 'org-table-insert-row))
17808 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17809 ((org-at-item-p) (call-interactively 'org-move-item-down))
17810 (t (org-modifier-cursor-error))))
17812 (defsubst org-hidden-tree-error ()
17813 (error
17814 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
17816 (defun org-metaleft (&optional arg)
17817 "Promote heading or move table column to left.
17818 Calls `org-do-promote' or `org-table-move-column', depending on context.
17819 With no specific context, calls the Emacs default `backward-word'.
17820 See the individual commands for more information."
17821 (interactive "P")
17822 (cond
17823 ((run-hook-with-args-until-success 'org-metaleft-hook))
17824 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
17825 ((org-with-limited-levels
17826 (or (org-on-heading-p)
17827 (and (org-region-active-p)
17828 (save-excursion
17829 (goto-char (region-beginning))
17830 (org-on-heading-p)))))
17831 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17832 (call-interactively 'org-do-promote))
17833 ;; At an inline task.
17834 ((org-on-heading-p)
17835 (call-interactively 'org-inlinetask-promote))
17836 ((or (org-at-item-p)
17837 (and (org-region-active-p)
17838 (save-excursion
17839 (goto-char (region-beginning))
17840 (org-at-item-p))))
17841 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17842 (call-interactively 'org-outdent-item))
17843 (t (call-interactively 'backward-word))))
17845 (defun org-metaright (&optional arg)
17846 "Demote subtree or move table column to right.
17847 Calls `org-do-demote' or `org-table-move-column', depending on context.
17848 With no specific context, calls the Emacs default `forward-word'.
17849 See the individual commands for more information."
17850 (interactive "P")
17851 (cond
17852 ((run-hook-with-args-until-success 'org-metaright-hook))
17853 ((org-at-table-p) (call-interactively 'org-table-move-column))
17854 ((org-with-limited-levels
17855 (or (org-on-heading-p)
17856 (and (org-region-active-p)
17857 (save-excursion
17858 (goto-char (region-beginning))
17859 (org-on-heading-p)))))
17860 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17861 (call-interactively 'org-do-demote))
17862 ;; At an inline task.
17863 ((org-on-heading-p)
17864 (call-interactively 'org-inlinetask-demote))
17865 ((or (org-at-item-p)
17866 (and (org-region-active-p)
17867 (save-excursion
17868 (goto-char (region-beginning))
17869 (org-at-item-p))))
17870 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17871 (call-interactively 'org-indent-item))
17872 (t (call-interactively 'forward-word))))
17874 (defun org-check-for-hidden (what)
17875 "Check if there are hidden headlines/items in the current visual line.
17876 WHAT can be either `headlines' or `items'. If the current line is
17877 an outline or item heading and it has a folded subtree below it,
17878 this function returns t, nil otherwise."
17879 (let ((re (cond
17880 ((eq what 'headlines) org-outline-regexp-bol)
17881 ((eq what 'items) (org-item-beginning-re))
17882 (t (error "This should not happen"))))
17883 beg end)
17884 (save-excursion
17885 (catch 'exit
17886 (unless (org-region-active-p)
17887 (setq beg (point-at-bol))
17888 (beginning-of-line 2)
17889 (while (and (not (eobp)) ;; this is like `next-line'
17890 (get-char-property (1- (point)) 'invisible))
17891 (beginning-of-line 2))
17892 (setq end (point))
17893 (goto-char beg)
17894 (goto-char (point-at-eol))
17895 (setq end (max end (point)))
17896 (while (re-search-forward re end t)
17897 (if (get-char-property (match-beginning 0) 'invisible)
17898 (throw 'exit t))))
17899 nil))))
17901 (defun org-metaup (&optional arg)
17902 "Move subtree up or move table row up.
17903 Calls `org-move-subtree-up' or `org-table-move-row' or
17904 `org-move-item-up', depending on context. See the individual commands
17905 for more information."
17906 (interactive "P")
17907 (cond
17908 ((run-hook-with-args-until-success 'org-metaup-hook))
17909 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
17910 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17911 ((org-at-item-p) (call-interactively 'org-move-item-up))
17912 (t (transpose-lines 1) (beginning-of-line -1))))
17914 (defun org-metadown (&optional arg)
17915 "Move subtree down or move table row down.
17916 Calls `org-move-subtree-down' or `org-table-move-row' or
17917 `org-move-item-down', depending on context. See the individual
17918 commands for more information."
17919 (interactive "P")
17920 (cond
17921 ((run-hook-with-args-until-success 'org-metadown-hook))
17922 ((org-at-table-p) (call-interactively 'org-table-move-row))
17923 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17924 ((org-at-item-p) (call-interactively 'org-move-item-down))
17925 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
17927 (defun org-shiftup (&optional arg)
17928 "Increase item in timestamp or increase priority of current headline.
17929 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
17930 depending on context. See the individual commands for more information."
17931 (interactive "P")
17932 (cond
17933 ((run-hook-with-args-until-success 'org-shiftup-hook))
17934 ((and org-support-shift-select (org-region-active-p))
17935 (org-call-for-shift-select 'previous-line))
17936 ((org-at-timestamp-p t)
17937 (call-interactively (if org-edit-timestamp-down-means-later
17938 'org-timestamp-down 'org-timestamp-up)))
17939 ((and (not (eq org-support-shift-select 'always))
17940 org-enable-priority-commands
17941 (org-on-heading-p))
17942 (call-interactively 'org-priority-up))
17943 ((and (not org-support-shift-select) (org-at-item-p))
17944 (call-interactively 'org-previous-item))
17945 ((org-clocktable-try-shift 'up arg))
17946 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
17947 (org-support-shift-select
17948 (org-call-for-shift-select 'previous-line))
17949 (t (org-shiftselect-error))))
17951 (defun org-shiftdown (&optional arg)
17952 "Decrease item in timestamp or decrease priority of current headline.
17953 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
17954 depending on context. See the individual commands for more information."
17955 (interactive "P")
17956 (cond
17957 ((run-hook-with-args-until-success 'org-shiftdown-hook))
17958 ((and org-support-shift-select (org-region-active-p))
17959 (org-call-for-shift-select 'next-line))
17960 ((org-at-timestamp-p t)
17961 (call-interactively (if org-edit-timestamp-down-means-later
17962 'org-timestamp-up 'org-timestamp-down)))
17963 ((and (not (eq org-support-shift-select 'always))
17964 org-enable-priority-commands
17965 (org-on-heading-p))
17966 (call-interactively 'org-priority-down))
17967 ((and (not org-support-shift-select) (org-at-item-p))
17968 (call-interactively 'org-next-item))
17969 ((org-clocktable-try-shift 'down arg))
17970 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
17971 (org-support-shift-select
17972 (org-call-for-shift-select 'next-line))
17973 (t (org-shiftselect-error))))
17975 (defun org-shiftright (&optional arg)
17976 "Cycle the thing at point or in the current line, depending on context.
17977 Depending on context, this does one of the following:
17979 - switch a timestamp at point one day into the future
17980 - on a headline, switch to the next TODO keyword.
17981 - on an item, switch entire list to the next bullet type
17982 - on a property line, switch to the next allowed value
17983 - on a clocktable definition line, move time block into the future"
17984 (interactive "P")
17985 (cond
17986 ((run-hook-with-args-until-success 'org-shiftright-hook))
17987 ((and org-support-shift-select (org-region-active-p))
17988 (org-call-for-shift-select 'forward-char))
17989 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
17990 ((and (not (eq org-support-shift-select 'always))
17991 (org-on-heading-p))
17992 (let ((org-inhibit-logging
17993 (not org-treat-S-cursor-todo-selection-as-state-change))
17994 (org-inhibit-blocking
17995 (not org-treat-S-cursor-todo-selection-as-state-change)))
17996 (org-call-with-arg 'org-todo 'right)))
17997 ((or (and org-support-shift-select
17998 (not (eq org-support-shift-select 'always))
17999 (org-at-item-bullet-p))
18000 (and (not org-support-shift-select) (org-at-item-p)))
18001 (org-call-with-arg 'org-cycle-list-bullet nil))
18002 ((and (not (eq org-support-shift-select 'always))
18003 (org-at-property-p))
18004 (call-interactively 'org-property-next-allowed-value))
18005 ((org-clocktable-try-shift 'right arg))
18006 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18007 (org-support-shift-select
18008 (org-call-for-shift-select 'forward-char))
18009 (t (org-shiftselect-error))))
18011 (defun org-shiftleft (&optional arg)
18012 "Cycle the thing at point or in the current line, depending on context.
18013 Depending on context, this does one of the following:
18015 - switch a timestamp at point one day into the past
18016 - on a headline, switch to the previous TODO keyword.
18017 - on an item, switch entire list to the previous bullet type
18018 - on a property line, switch to the previous allowed value
18019 - on a clocktable definition line, move time block into the past"
18020 (interactive "P")
18021 (cond
18022 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18023 ((and org-support-shift-select (org-region-active-p))
18024 (org-call-for-shift-select 'backward-char))
18025 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18026 ((and (not (eq org-support-shift-select 'always))
18027 (org-on-heading-p))
18028 (let ((org-inhibit-logging
18029 (not org-treat-S-cursor-todo-selection-as-state-change))
18030 (org-inhibit-blocking
18031 (not org-treat-S-cursor-todo-selection-as-state-change)))
18032 (org-call-with-arg 'org-todo 'left)))
18033 ((or (and org-support-shift-select
18034 (not (eq org-support-shift-select 'always))
18035 (org-at-item-bullet-p))
18036 (and (not org-support-shift-select) (org-at-item-p)))
18037 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18038 ((and (not (eq org-support-shift-select 'always))
18039 (org-at-property-p))
18040 (call-interactively 'org-property-previous-allowed-value))
18041 ((org-clocktable-try-shift 'left arg))
18042 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18043 (org-support-shift-select
18044 (org-call-for-shift-select 'backward-char))
18045 (t (org-shiftselect-error))))
18047 (defun org-shiftcontrolright ()
18048 "Switch to next TODO set."
18049 (interactive)
18050 (cond
18051 ((and org-support-shift-select (org-region-active-p))
18052 (org-call-for-shift-select 'forward-word))
18053 ((and (not (eq org-support-shift-select 'always))
18054 (org-on-heading-p))
18055 (org-call-with-arg 'org-todo 'nextset))
18056 (org-support-shift-select
18057 (org-call-for-shift-select 'forward-word))
18058 (t (org-shiftselect-error))))
18060 (defun org-shiftcontrolleft ()
18061 "Switch to previous TODO set."
18062 (interactive)
18063 (cond
18064 ((and org-support-shift-select (org-region-active-p))
18065 (org-call-for-shift-select 'backward-word))
18066 ((and (not (eq org-support-shift-select 'always))
18067 (org-on-heading-p))
18068 (org-call-with-arg 'org-todo 'previousset))
18069 (org-support-shift-select
18070 (org-call-for-shift-select 'backward-word))
18071 (t (org-shiftselect-error))))
18073 (defun org-shiftcontrolup ()
18074 "Change timestamps synchronously up in CLOCK log lines."
18075 (interactive)
18076 (cond ((and (not org-support-shift-select)
18077 (org-at-clock-log-p)
18078 (org-at-timestamp-p t))
18079 (org-clock-timestamps-up))
18080 (t (org-shiftselect-error))))
18082 (defun org-shiftcontroldown ()
18083 "Change timestamps synchronously down in CLOCK log lines."
18084 (interactive)
18085 (cond ((and (not org-support-shift-select)
18086 (org-at-clock-log-p)
18087 (org-at-timestamp-p t))
18088 (org-clock-timestamps-down))
18089 (t (org-shiftselect-error))))
18091 (defun org-ctrl-c-ret ()
18092 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18093 (interactive)
18094 (cond
18095 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18096 (t (call-interactively 'org-insert-heading))))
18098 (defun org-find-visible ()
18099 (let ((s (point)))
18100 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18101 (get-char-property s 'invisible)))
18103 (defun org-find-invisible ()
18104 (let ((s (point)))
18105 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18106 (not (get-char-property s 'invisible))))
18109 (defun org-copy-visible (beg end)
18110 "Copy the visible parts of the region."
18111 (interactive "r")
18112 (let (snippets s)
18113 (save-excursion
18114 (save-restriction
18115 (narrow-to-region beg end)
18116 (setq s (goto-char (point-min)))
18117 (while (not (= (point) (point-max)))
18118 (goto-char (org-find-invisible))
18119 (push (buffer-substring s (point)) snippets)
18120 (setq s (goto-char (org-find-visible))))))
18121 (kill-new (apply 'concat (nreverse snippets)))))
18123 (defun org-copy-special ()
18124 "Copy region in table or copy current subtree.
18125 Calls `org-table-copy' or `org-copy-subtree', depending on context.
18126 See the individual commands for more information."
18127 (interactive)
18128 (call-interactively
18129 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
18131 (defun org-cut-special ()
18132 "Cut region in table or cut current subtree.
18133 Calls `org-table-copy' or `org-cut-subtree', depending on context.
18134 See the individual commands for more information."
18135 (interactive)
18136 (call-interactively
18137 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
18139 (defun org-paste-special (arg)
18140 "Paste rectangular region into table, or past subtree relative to level.
18141 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
18142 See the individual commands for more information."
18143 (interactive "P")
18144 (if (org-at-table-p)
18145 (org-table-paste-rectangle)
18146 (org-paste-subtree arg)))
18148 (defun org-edit-special (&optional arg)
18149 "Call a special editor for the stuff at point.
18150 When at a table, call the formula editor with `org-table-edit-formulas'.
18151 When at the first line of an src example, call `org-edit-src-code'.
18152 When in an #+include line, visit the include file. Otherwise call
18153 `ffap' to visit the file at point."
18154 (interactive)
18155 ;; possibly prep session before editing source
18156 (when arg
18157 (let* ((info (org-babel-get-src-block-info))
18158 (lang (nth 0 info))
18159 (params (nth 2 info))
18160 (session (cdr (assoc :session params))))
18161 (when (and info session) ;; we are in a source-code block with a session
18162 (funcall
18163 (intern (concat "org-babel-prep-session:" lang)) session params))))
18164 (cond ;; proceed with `org-edit-special'
18165 ((save-excursion
18166 (beginning-of-line 1)
18167 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
18168 (find-file (org-trim (match-string 1))))
18169 ((org-edit-src-code))
18170 ((org-edit-fixed-width-region))
18171 ((org-at-table.el-p)
18172 (org-edit-src-code))
18173 ((or (org-at-table-p)
18174 (save-excursion
18175 (beginning-of-line 1)
18176 (looking-at "[ \t]*#\\+TBLFM:")))
18177 (call-interactively 'org-table-edit-formulas))
18178 (t (call-interactively 'ffap))))
18180 (defvar org-table-coordinate-overlays) ; defined in org-table.el
18181 (defun org-ctrl-c-ctrl-c (&optional arg)
18182 "Set tags in headline, or update according to changed information at point.
18184 This command does many different things, depending on context:
18186 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
18187 this is what we do.
18189 - If the cursor is on a statistics cookie, update it.
18191 - If the cursor is in a headline, prompt for tags and insert them
18192 into the current line, aligned to `org-tags-column'. When called
18193 with prefix arg, realign all tags in the current buffer.
18195 - If the cursor is in one of the special #+KEYWORD lines, this
18196 triggers scanning the buffer for these lines and updating the
18197 information.
18199 - If the cursor is inside a table, realign the table. This command
18200 works even if the automatic table editor has been turned off.
18202 - If the cursor is on a #+TBLFM line, re-apply the formulas to
18203 the entire table.
18205 - If the cursor is at a footnote reference or definition, jump to
18206 the corresponding definition or references, respectively.
18208 - If the cursor is a the beginning of a dynamic block, update it.
18210 - If the current buffer is a capture buffer, close note and file it.
18212 - If the cursor is on a <<<target>>>, update radio targets and
18213 corresponding links in this buffer.
18215 - If the cursor is on a numbered item in a plain list, renumber the
18216 ordered list.
18218 - If the cursor is on a checkbox, toggle it.
18220 - If the cursor is on a code block, evaluate it. The variable
18221 `org-confirm-babel-evaluate' can be used to control prompting
18222 before code block evaluation, by default every code block
18223 evaluation requires confirmation. Code block evaluation can be
18224 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
18225 (interactive "P")
18226 (let ((org-enable-table-editor t))
18227 (cond
18228 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
18229 org-occur-highlights
18230 org-latex-fragment-image-overlays)
18231 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
18232 (org-remove-occur-highlights)
18233 (org-remove-latex-fragment-image-overlays)
18234 (message "Temporary highlights/overlays removed from current buffer"))
18235 ((and (local-variable-p 'org-finish-function (current-buffer))
18236 (fboundp org-finish-function))
18237 (funcall org-finish-function))
18238 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
18239 ((or (looking-at org-property-start-re)
18240 (org-at-property-p))
18241 (call-interactively 'org-property-action))
18242 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
18243 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
18244 (or (org-on-heading-p) (org-at-item-p)))
18245 (call-interactively 'org-update-statistics-cookies))
18246 ((org-on-heading-p) (call-interactively 'org-set-tags))
18247 ((org-at-table.el-p)
18248 (message "Use C-c ' to edit table.el tables"))
18249 ((org-at-table-p)
18250 (org-table-maybe-eval-formula)
18251 (if arg
18252 (call-interactively 'org-table-recalculate)
18253 (org-table-maybe-recalculate-line))
18254 (call-interactively 'org-table-align)
18255 (orgtbl-send-table 'maybe))
18256 ((or (org-footnote-at-reference-p)
18257 (org-footnote-at-definition-p))
18258 (call-interactively 'org-footnote-action))
18259 ((org-at-item-checkbox-p)
18260 ;; Cursor at a checkbox: repair list and update checkboxes. Send
18261 ;; list only if at top item.
18262 (let* ((cbox (match-string 1))
18263 (struct (org-list-struct))
18264 (old-struct (copy-tree struct))
18265 (parents (org-list-parents-alist struct))
18266 (orderedp (org-entry-get nil "ORDERED"))
18267 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18268 block-item)
18269 ;; Use a light version of `org-toggle-checkbox' to avoid
18270 ;; computing list structure twice.
18271 (org-list-set-checkbox (point-at-bol) struct
18272 (cond
18273 ((equal arg '(16)) "[-]")
18274 ((equal arg '(4)) nil)
18275 ((equal "[X]" cbox) "[ ]")
18276 (t "[X]")))
18277 ;; Replicate `org-list-write-struct', while grabbing a return
18278 ;; value from `org-list-struct-fix-box'.
18279 (org-list-struct-fix-ind struct parents 2)
18280 (org-list-struct-fix-item-end struct)
18281 (let ((prevs (org-list-prevs-alist struct)))
18282 (org-list-struct-fix-bul struct prevs)
18283 (org-list-struct-fix-ind struct parents)
18284 (setq block-item
18285 (org-list-struct-fix-box struct parents prevs orderedp)))
18286 (org-list-struct-apply-struct struct old-struct)
18287 (org-update-checkbox-count-maybe)
18288 (when block-item
18289 (message
18290 "Checkboxes were removed due to unchecked box at line %d"
18291 (org-current-line block-item)))
18292 (when firstp (org-list-send-list 'maybe))))
18293 ((org-at-item-p)
18294 ;; Cursor at an item: repair list. Do checkbox related actions
18295 ;; only if function was called with an argument. Send list only
18296 ;; if at top item.
18297 (let* ((struct (org-list-struct))
18298 (firstp (= (org-list-get-top-point struct) (point-at-bol))))
18299 (when arg (org-list-set-checkbox (point-at-bol) struct "[ ]"))
18300 (org-list-write-struct struct (org-list-parents-alist struct))
18301 (when arg (org-update-checkbox-count-maybe))
18302 (when firstp (org-list-send-list 'maybe))))
18303 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
18304 ;; Dynamic block
18305 (beginning-of-line 1)
18306 (save-excursion (org-update-dblock)))
18307 ((save-excursion
18308 (beginning-of-line 1)
18309 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
18310 (cond
18311 ((equal (match-string 1) "TBLFM")
18312 ;; Recalculate the table before this line
18313 (save-excursion
18314 (beginning-of-line 1)
18315 (skip-chars-backward " \r\n\t")
18316 (if (org-at-table-p)
18317 (org-call-with-arg 'org-table-recalculate (or arg t)))))
18319 (let ((org-inhibit-startup-visibility-stuff t)
18320 (org-startup-align-all-tables nil))
18321 (when (boundp 'org-table-coordinate-overlays)
18322 (mapc 'delete-overlay org-table-coordinate-overlays)
18323 (setq org-table-coordinate-overlays nil))
18324 (org-save-outline-visibility 'use-markers (org-mode-restart)))
18325 (message "Local setup has been refreshed"))))
18326 ((org-clock-update-time-maybe))
18328 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
18329 (error "C-c C-c can do nothing useful at this location"))))))
18331 (defun org-mode-restart ()
18332 "Restart Org-mode, to scan again for special lines.
18333 Also updates the keyword regular expressions."
18334 (interactive)
18335 (org-mode)
18336 (message "Org-mode restarted"))
18338 (defun org-kill-note-or-show-branches ()
18339 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
18340 (interactive)
18341 (if (not org-finish-function)
18342 (progn
18343 (hide-subtree)
18344 (call-interactively 'show-branches))
18345 (let ((org-note-abort t))
18346 (funcall org-finish-function))))
18348 (defun org-return (&optional indent)
18349 "Goto next table row or insert a newline.
18350 Calls `org-table-next-row' or `newline', depending on context.
18351 See the individual commands for more information."
18352 (interactive)
18353 (cond
18354 ((bobp) (if indent (newline-and-indent) (newline)))
18355 ((org-at-table-p)
18356 (org-table-justify-field-maybe)
18357 (call-interactively 'org-table-next-row))
18358 ;; when `newline-and-indent' is called within a list, make sure
18359 ;; text moved stays inside the item.
18360 ((and (org-in-item-p) indent)
18361 (if (and (org-at-item-p) (>= (point) (match-end 0)))
18362 (progn
18363 (save-match-data (newline))
18364 (org-indent-line-to (length (match-string 0))))
18365 (let ((ind (org-get-indentation)))
18366 (newline)
18367 (if (org-looking-back org-list-end-re)
18368 (org-indent-line-function)
18369 (org-indent-line-to ind)))))
18370 ((and org-return-follows-link
18371 (let ((tprop (get-text-property (point) 'face)))
18372 (or (eq tprop 'org-link)
18373 (and (listp tprop) (memq 'org-link tprop)))))
18374 (call-interactively 'org-open-at-point))
18375 ((and (org-at-heading-p)
18376 (looking-at
18377 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
18378 (org-show-entry)
18379 (end-of-line 1)
18380 (newline))
18381 (t (if indent (newline-and-indent) (newline)))))
18383 (defun org-return-indent ()
18384 "Goto next table row or insert a newline and indent.
18385 Calls `org-table-next-row' or `newline-and-indent', depending on
18386 context. See the individual commands for more information."
18387 (interactive)
18388 (org-return t))
18390 (defun org-ctrl-c-star ()
18391 "Compute table, or change heading status of lines.
18392 Calls `org-table-recalculate' or `org-toggle-heading',
18393 depending on context."
18394 (interactive)
18395 (cond
18396 ((org-at-table-p)
18397 (call-interactively 'org-table-recalculate))
18399 ;; Convert all lines in region to list items
18400 (call-interactively 'org-toggle-heading))))
18402 (defun org-ctrl-c-minus ()
18403 "Insert separator line in table or modify bullet status of line.
18404 Also turns a plain line or a region of lines into list items.
18405 Calls `org-table-insert-hline', `org-toggle-item', or
18406 `org-cycle-list-bullet', depending on context."
18407 (interactive)
18408 (cond
18409 ((org-at-table-p)
18410 (call-interactively 'org-table-insert-hline))
18411 ((org-region-active-p)
18412 (call-interactively 'org-toggle-item))
18413 ((org-in-item-p)
18414 (call-interactively 'org-cycle-list-bullet))
18416 (call-interactively 'org-toggle-item))))
18418 (defun org-toggle-item (arg)
18419 "Convert headings or normal lines to items, items to normal lines.
18420 If there is no active region, only the current line is considered.
18422 If the first non blank line in the region is an headline, convert
18423 all headlines to items, shifting text accordingly.
18425 If it is an item, convert all items to normal lines.
18427 If it is normal text, change region into an item. With a prefix
18428 argument ARG, change each line in region into an item."
18429 (interactive "P")
18430 (let ((shift-text
18431 (function
18432 ;; Shift text in current section to IND, from point to END.
18433 ;; The function leaves point to END line.
18434 (lambda (ind end)
18435 (let ((min-i 1000) (end (copy-marker end)))
18436 ;; First determine the minimum indentation (MIN-I) of
18437 ;; the text.
18438 (save-excursion
18439 (catch 'exit
18440 (while (< (point) end)
18441 (let ((i (org-get-indentation)))
18442 (cond
18443 ;; Skip blank lines and inline tasks.
18444 ((looking-at "^[ \t]*$"))
18445 ((looking-at org-outline-regexp-bol))
18446 ;; We can't find less than 0 indentation.
18447 ((zerop i) (throw 'exit (setq min-i 0)))
18448 ((< i min-i) (setq min-i i))))
18449 (forward-line))))
18450 ;; Then indent each line so that a line indented to
18451 ;; MIN-I becomes indented to IND. Ignore blank lines
18452 ;; and inline tasks in the process.
18453 (let ((delta (- ind min-i)))
18454 (while (< (point) end)
18455 (unless (or (looking-at "^[ \t]*$")
18456 (looking-at org-outline-regexp-bol))
18457 (org-indent-line-to (+ (org-get-indentation) delta)))
18458 (forward-line)))))))
18459 (skip-blanks
18460 (function
18461 ;; Return beginning of first non-blank line, starting from
18462 ;; line at POS.
18463 (lambda (pos)
18464 (save-excursion
18465 (goto-char pos)
18466 (skip-chars-forward " \r\t\n")
18467 (point-at-bol)))))
18468 beg end)
18469 ;; Determine boundaries of changes.
18470 (if (org-region-active-p)
18471 (setq beg (funcall skip-blanks (region-beginning))
18472 end (copy-marker (region-end)))
18473 (setq beg (funcall skip-blanks (point-at-bol))
18474 end (copy-marker (point-at-eol))))
18475 ;; Depending on the starting line, choose an action on the text
18476 ;; between BEG and END.
18477 (org-with-limited-levels
18478 (save-excursion
18479 (goto-char beg)
18480 (cond
18481 ;; Case 1. Start at an item: de-itemize. Note that it only
18482 ;; happens when a region is active: `org-ctrl-c-minus'
18483 ;; would call `org-cycle-list-bullet' otherwise.
18484 ((org-at-item-p)
18485 (while (< (point) end)
18486 (when (org-at-item-p)
18487 (skip-chars-forward " \t")
18488 (delete-region (point) (match-end 0)))
18489 (forward-line)))
18490 ;; Case 2. Start at an heading: convert to items.
18491 ((org-on-heading-p)
18492 (let* ((bul (org-list-bullet-string "-"))
18493 (bul-len (length bul))
18494 ;; Indentation of the first heading. It should be
18495 ;; relative to the indentation of its parent, if any.
18496 (start-ind (save-excursion
18497 (cond
18498 ((not org-adapt-indentation) 0)
18499 ((not (outline-previous-heading)) 0)
18500 (t (length (match-string 0))))))
18501 ;; Level of first heading. Further headings will be
18502 ;; compared to it to determine hierarchy in the list.
18503 (ref-level (org-reduced-level (org-outline-level))))
18504 (while (< (point) end)
18505 (let* ((level (org-reduced-level (org-outline-level)))
18506 (delta (max 0 (- level ref-level))))
18507 ;; If current headline is less indented than the first
18508 ;; one, set it as reference, in order to preserve
18509 ;; subtrees.
18510 (when (< level ref-level) (setq ref-level level))
18511 (replace-match bul t t)
18512 (org-indent-line-to (+ start-ind (* delta bul-len)))
18513 ;; Ensure all text down to END (or SECTION-END) belongs
18514 ;; to the newly created item.
18515 (let ((section-end (save-excursion
18516 (or (outline-next-heading) (point)))))
18517 (forward-line)
18518 (funcall shift-text
18519 (+ start-ind (* (1+ delta) bul-len))
18520 (min end section-end)))))))
18521 ;; Case 3. Normal line with ARG: turn each non-item line into
18522 ;; an item.
18523 (arg
18524 (while (< (point) end)
18525 (unless (or (org-on-heading-p) (org-at-item-p))
18526 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
18527 (replace-match
18528 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
18529 (forward-line)))
18530 ;; Case 4. Normal line without ARG: make the first line of
18531 ;; region an item, and shift indentation of others
18532 ;; lines to set them as item's body.
18533 (t (let* ((bul (org-list-bullet-string "-"))
18534 (bul-len (length bul))
18535 (ref-ind (org-get-indentation)))
18536 (skip-chars-forward " \t")
18537 (insert bul)
18538 (forward-line)
18539 (while (< (point) end)
18540 ;; Ensure that lines less indented than first one
18541 ;; still get included in item body.
18542 (funcall shift-text
18543 (+ ref-ind bul-len)
18544 (min end (save-excursion (or (outline-next-heading)
18545 (point)))))
18546 (forward-line)))))))))
18548 (defun org-toggle-heading (&optional nstars)
18549 "Convert headings to normal text, or items or text to headings.
18550 If there is no active region, only the current line is considered.
18552 If the first non blank line is an headline, remove the stars from
18553 all headlines in the region.
18555 If it is a plain list item, turn all plain list items into headings.
18557 If it is a normal line, turn each and every normal line (i.e. not
18558 an heading or an item) in the region into a heading.
18560 When converting a line into a heading, the number of stars is chosen
18561 such that the lines become children of the current entry. However,
18562 when a prefix argument is given, its value determines the number of
18563 stars to add."
18564 (interactive "P")
18565 (let ((skip-blanks
18566 (function
18567 ;; Return beginning of first non-blank line, starting from
18568 ;; line at POS.
18569 (lambda (pos)
18570 (save-excursion
18571 (goto-char pos)
18572 (skip-chars-forward " \r\t\n")
18573 (point-at-bol)))))
18574 beg end)
18575 ;; Determine boundaries of changes. If region ends at a bol, do
18576 ;; not consider the last line to be in the region.
18577 (if (org-region-active-p)
18578 (setq beg (funcall skip-blanks (region-beginning))
18579 end (copy-marker (save-excursion
18580 (goto-char (region-end))
18581 (if (bolp) (point) (point-at-eol)))))
18582 (setq beg (funcall skip-blanks (point-at-bol))
18583 end (copy-marker (point-at-eol))))
18584 ;; Ensure inline tasks don't count as headings.
18585 (org-with-limited-levels
18586 (save-excursion
18587 (goto-char beg)
18588 (cond
18589 ;; Case 1. Started at an heading: de-star headings.
18590 ((org-on-heading-p)
18591 (while (< (point) end)
18592 (when (org-on-heading-p t)
18593 (looking-at org-outline-regexp) (replace-match ""))
18594 (forward-line)))
18595 ;; Case 2. Started at an item: change items into headlines.
18596 ;; One star will be added by `org-list-to-subtree'.
18597 ((org-at-item-p)
18598 (let* ((stars (make-string
18599 (if nstars
18600 ;; subtract the star that will be added again by
18601 ;; `org-list-to-subtree'
18602 (1- (prefix-numeric-value current-prefix-arg))
18603 (or (org-current-level) 0))
18604 ?*))
18605 (add-stars
18606 (cond (nstars "") ; stars from prefix only
18607 ((equal stars "") "") ; before first heading
18608 (org-odd-levels-only "*") ; inside heading, odd
18609 (t "")))) ; inside heading, oddeven
18610 (while (< (point) end)
18611 (when (org-at-item-p)
18612 ;; Pay attention to cases when region ends before list.
18613 (let* ((struct (org-list-struct))
18614 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
18615 (save-restriction
18616 (narrow-to-region (point) list-end)
18617 (insert
18618 (org-list-to-subtree
18619 (org-list-parse-list t)
18620 '(:istart (concat stars add-stars (funcall get-stars depth))
18621 :icount (concat stars add-stars (funcall get-stars depth))))))))
18622 (forward-line))))
18623 ;; Case 3. Started at normal text: make every line an heading,
18624 ;; skipping headlines and items.
18625 (t (let* ((stars (make-string
18626 (if nstars
18627 (prefix-numeric-value current-prefix-arg)
18628 (or (org-current-level) 0))
18629 ?*))
18630 (add-stars
18631 (cond (nstars "") ; stars from prefix only
18632 ((equal stars "") "*") ; before first heading
18633 (org-odd-levels-only "**") ; inside heading, odd
18634 (t "*"))) ; inside heading, oddeven
18635 (rpl (concat stars add-stars " ")))
18636 (while (< (point) end)
18637 (when (and (not (org-on-heading-p)) (not (org-at-item-p))
18638 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
18639 (replace-match (concat rpl (match-string 2))))
18640 (forward-line)))))))))
18642 (defun org-meta-return (&optional arg)
18643 "Insert a new heading or wrap a region in a table.
18644 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
18645 See the individual commands for more information."
18646 (interactive "P")
18647 (cond
18648 ((run-hook-with-args-until-success 'org-metareturn-hook))
18649 ((org-at-table-p)
18650 (call-interactively 'org-table-wrap-region))
18651 (t (call-interactively 'org-insert-heading))))
18653 ;;; Menu entries
18655 ;; Define the Org-mode menus
18656 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
18657 '("Tbl"
18658 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
18659 ["Next Field" org-cycle (org-at-table-p)]
18660 ["Previous Field" org-shifttab (org-at-table-p)]
18661 ["Next Row" org-return (org-at-table-p)]
18662 "--"
18663 ["Blank Field" org-table-blank-field (org-at-table-p)]
18664 ["Edit Field" org-table-edit-field (org-at-table-p)]
18665 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
18666 "--"
18667 ("Column"
18668 ["Move Column Left" org-metaleft (org-at-table-p)]
18669 ["Move Column Right" org-metaright (org-at-table-p)]
18670 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
18671 ["Insert Column" org-shiftmetaright (org-at-table-p)])
18672 ("Row"
18673 ["Move Row Up" org-metaup (org-at-table-p)]
18674 ["Move Row Down" org-metadown (org-at-table-p)]
18675 ["Delete Row" org-shiftmetaup (org-at-table-p)]
18676 ["Insert Row" org-shiftmetadown (org-at-table-p)]
18677 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
18678 "--"
18679 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
18680 ("Rectangle"
18681 ["Copy Rectangle" org-copy-special (org-at-table-p)]
18682 ["Cut Rectangle" org-cut-special (org-at-table-p)]
18683 ["Paste Rectangle" org-paste-special (org-at-table-p)]
18684 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
18685 "--"
18686 ("Calculate"
18687 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
18688 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
18689 ["Edit Formulas" org-edit-special (org-at-table-p)]
18690 "--"
18691 ["Recalculate line" org-table-recalculate (org-at-table-p)]
18692 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
18693 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
18694 "--"
18695 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
18696 "--"
18697 ["Sum Column/Rectangle" org-table-sum
18698 (or (org-at-table-p) (org-region-active-p))]
18699 ["Which Column?" org-table-current-column (org-at-table-p)])
18700 ["Debug Formulas"
18701 org-table-toggle-formula-debugger
18702 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
18703 ["Show Col/Row Numbers"
18704 org-table-toggle-coordinate-overlays
18705 :style toggle
18706 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
18707 "--"
18708 ["Create" org-table-create (and (not (org-at-table-p))
18709 org-enable-table-editor)]
18710 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
18711 ["Import from File" org-table-import (not (org-at-table-p))]
18712 ["Export to File" org-table-export (org-at-table-p)]
18713 "--"
18714 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
18716 (easy-menu-define org-org-menu org-mode-map "Org menu"
18717 '("Org"
18718 ("Show/Hide"
18719 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
18720 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
18721 ["Sparse Tree..." org-sparse-tree t]
18722 ["Reveal Context" org-reveal t]
18723 ["Show All" show-all t]
18724 "--"
18725 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
18726 "--"
18727 ["New Heading" org-insert-heading t]
18728 ("Navigate Headings"
18729 ["Up" outline-up-heading t]
18730 ["Next" outline-next-visible-heading t]
18731 ["Previous" outline-previous-visible-heading t]
18732 ["Next Same Level" outline-forward-same-level t]
18733 ["Previous Same Level" outline-backward-same-level t]
18734 "--"
18735 ["Jump" org-goto t])
18736 ("Edit Structure"
18737 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
18738 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
18739 "--"
18740 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
18741 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
18742 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
18743 "--"
18744 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
18745 "--"
18746 ["Copy visible text" org-copy-visible t]
18747 "--"
18748 ["Promote Heading" org-metaleft (not (org-at-table-p))]
18749 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
18750 ["Demote Heading" org-metaright (not (org-at-table-p))]
18751 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
18752 "--"
18753 ["Sort Region/Children" org-sort (not (org-at-table-p))]
18754 "--"
18755 ["Convert to odd levels" org-convert-to-odd-levels t]
18756 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
18757 ("Editing"
18758 ["Emphasis..." org-emphasize t]
18759 ["Edit Source Example" org-edit-special t]
18760 "--"
18761 ["Footnote new/jump" org-footnote-action t]
18762 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
18763 ("Archive"
18764 ["Archive (default method)" org-archive-subtree-default t]
18765 "--"
18766 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
18767 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
18768 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
18770 "--"
18771 ("Hyperlinks"
18772 ["Store Link (Global)" org-store-link t]
18773 ["Find existing link to here" org-occur-link-in-agenda-files t]
18774 ["Insert Link" org-insert-link t]
18775 ["Follow Link" org-open-at-point t]
18776 "--"
18777 ["Next link" org-next-link t]
18778 ["Previous link" org-previous-link t]
18779 "--"
18780 ["Descriptive Links"
18781 org-toggle-link-display
18782 :style radio
18783 :selected org-descriptive-links
18785 ["Literal Links"
18786 org-toggle-link-display
18787 :style radio
18788 :selected (not org-descriptive-links)])
18789 "--"
18790 ("TODO Lists"
18791 ["TODO/DONE/-" org-todo t]
18792 ("Select keyword"
18793 ["Next keyword" org-shiftright (org-on-heading-p)]
18794 ["Previous keyword" org-shiftleft (org-on-heading-p)]
18795 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
18796 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
18797 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
18798 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
18799 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
18800 "--"
18801 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
18802 :selected org-enforce-todo-dependencies :style toggle :active t]
18803 "Settings for tree at point"
18804 ["Do Children sequentially" org-toggle-ordered-property :style radio
18805 :selected (org-entry-get nil "ORDERED")
18806 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
18807 ["Do Children parallel" org-toggle-ordered-property :style radio
18808 :selected (not (org-entry-get nil "ORDERED"))
18809 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
18810 "--"
18811 ["Set Priority" org-priority t]
18812 ["Priority Up" org-shiftup t]
18813 ["Priority Down" org-shiftdown t]
18814 "--"
18815 ["Get news from all feeds" org-feed-update-all t]
18816 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
18817 ["Customize feeds" (customize-variable 'org-feed-alist) t])
18818 ("TAGS and Properties"
18819 ["Set Tags" org-set-tags-command t]
18820 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
18821 "--"
18822 ["Set property" org-set-property t]
18823 ["Column view of properties" org-columns t]
18824 ["Insert Column View DBlock" org-insert-columns-dblock t])
18825 ("Dates and Scheduling"
18826 ["Timestamp" org-time-stamp t]
18827 ["Timestamp (inactive)" org-time-stamp-inactive t]
18828 ("Change Date"
18829 ["1 Day Later" org-shiftright t]
18830 ["1 Day Earlier" org-shiftleft t]
18831 ["1 ... Later" org-shiftup t]
18832 ["1 ... Earlier" org-shiftdown t])
18833 ["Compute Time Range" org-evaluate-time-range t]
18834 ["Schedule Item" org-schedule t]
18835 ["Deadline" org-deadline t]
18836 "--"
18837 ["Custom time format" org-toggle-time-stamp-overlays
18838 :style radio :selected org-display-custom-times]
18839 "--"
18840 ["Goto Calendar" org-goto-calendar t]
18841 ["Date from Calendar" org-date-from-calendar t]
18842 "--"
18843 ["Start/Restart Timer" org-timer-start t]
18844 ["Pause/Continue Timer" org-timer-pause-or-continue t]
18845 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
18846 ["Insert Timer String" org-timer t]
18847 ["Insert Timer Item" org-timer-item t])
18848 ("Logging work"
18849 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
18850 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
18851 ["Clock out" org-clock-out t]
18852 ["Clock cancel" org-clock-cancel t]
18853 "--"
18854 ["Mark as default task" org-clock-mark-default-task t]
18855 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
18856 ["Goto running clock" org-clock-goto t]
18857 "--"
18858 ["Display times" org-clock-display t]
18859 ["Create clock table" org-clock-report t]
18860 "--"
18861 ["Record DONE time"
18862 (progn (setq org-log-done (not org-log-done))
18863 (message "Switching to %s will %s record a timestamp"
18864 (car org-done-keywords)
18865 (if org-log-done "automatically" "not")))
18866 :style toggle :selected org-log-done])
18867 "--"
18868 ["Agenda Command..." org-agenda t]
18869 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
18870 ("File List for Agenda")
18871 ("Special views current file"
18872 ["TODO Tree" org-show-todo-tree t]
18873 ["Check Deadlines" org-check-deadlines t]
18874 ["Timeline" org-timeline t]
18875 ["Tags/Property tree" org-match-sparse-tree t])
18876 "--"
18877 ["Export/Publish..." org-export t]
18878 ("LaTeX"
18879 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
18880 :selected org-cdlatex-mode]
18881 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
18882 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
18883 ["Modify math symbol" org-cdlatex-math-modify
18884 (org-inside-LaTeX-fragment-p)]
18885 ["Insert citation" org-reftex-citation t]
18886 "--"
18887 ["Template for BEAMER" org-insert-beamer-options-template t])
18888 "--"
18889 ("MobileOrg"
18890 ["Push Files and Views" org-mobile-push t]
18891 ["Get Captured and Flagged" org-mobile-pull t]
18892 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
18893 "--"
18894 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
18895 "--"
18896 ("Documentation"
18897 ["Show Version" org-version t]
18898 ["Info Documentation" org-info t])
18899 ("Customize"
18900 ["Browse Org Group" org-customize t]
18901 "--"
18902 ["Expand This Menu" org-create-customize-menu
18903 (fboundp 'customize-menu-create)])
18904 ["Send bug report" org-submit-bug-report t]
18905 "--"
18906 ("Refresh/Reload"
18907 ["Refresh setup current buffer" org-mode-restart t]
18908 ["Reload Org (after update)" org-reload t]
18909 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
18912 (defun org-info (&optional node)
18913 "Read documentation for Org-mode in the info system.
18914 With optional NODE, go directly to that node."
18915 (interactive)
18916 (info (format "(org)%s" (or node ""))))
18918 ;;;###autoload
18919 (defun org-submit-bug-report ()
18920 "Submit a bug report on Org-mode via mail.
18922 Don't hesitate to report any problems or inaccurate documentation.
18924 If you don't have setup sending mail from (X)Emacs, please copy the
18925 output buffer into your mail program, as it gives us important
18926 information about your Org-mode version and configuration."
18927 (interactive)
18928 (require 'reporter)
18929 (org-load-modules-maybe)
18930 (org-require-autoloaded-modules)
18931 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
18932 (reporter-submit-bug-report
18933 "emacs-orgmode@gnu.org"
18934 (org-version)
18935 (let (list)
18936 (save-window-excursion
18937 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
18938 (delete-other-windows)
18939 (erase-buffer)
18940 (insert "You are about to submit a bug report to the Org-mode mailing list.
18942 We would like to add your full Org-mode and Outline configuration to the
18943 bug report. This greatly simplifies the work of the maintainer and
18944 other experts on the mailing list.
18946 HOWEVER, some variables you have customized may contain private
18947 information. The names of customers, colleagues, or friends, might
18948 appear in the form of file names, tags, todo states, or search strings.
18949 If you answer yes to the prompt, you might want to check and remove
18950 such private information before sending the email.")
18951 (add-text-properties (point-min) (point-max) '(face org-warning))
18952 (when (yes-or-no-p "Include your Org-mode configuration ")
18953 (mapatoms
18954 (lambda (v)
18955 (and (boundp v)
18956 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
18957 (or (and (symbol-value v)
18958 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
18959 (and
18960 (get v 'custom-type) (get v 'standard-value)
18961 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
18962 (push v list)))))
18963 (kill-buffer (get-buffer "*Warn about privacy*"))
18964 list))
18965 nil nil
18966 "Remember to cover the basics, that is, what you expected to happen and
18967 what in fact did happen. You don't know how to make a good report? See
18969 http://orgmode.org/manual/Feedback.html#Feedback
18971 Your bug report will be posted to the Org-mode mailing list.
18972 ------------------------------------------------------------------------")
18973 (save-excursion
18974 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
18975 (replace-match "\\1Bug: \\3 [\\2]")))))
18978 (defun org-install-agenda-files-menu ()
18979 (let ((bl (buffer-list)))
18980 (save-excursion
18981 (while bl
18982 (set-buffer (pop bl))
18983 (if (eq major-mode 'org-mode) (setq bl nil)))
18984 (when (eq major-mode 'org-mode)
18985 (easy-menu-change
18986 '("Org") "File List for Agenda"
18987 (append
18988 (list
18989 ["Edit File List" (org-edit-agenda-file-list) t]
18990 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
18991 ["Remove Current File from List" org-remove-file t]
18992 ["Cycle through agenda files" org-cycle-agenda-files t]
18993 ["Occur in all agenda files" org-occur-in-agenda-files t]
18994 "--")
18995 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
18997 ;;;; Documentation
18999 ;;;###autoload
19000 (defun org-require-autoloaded-modules ()
19001 (interactive)
19002 (mapc 'require
19003 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19004 org-docbook org-exp org-html org-icalendar
19005 org-id org-latex
19006 org-publish org-remember org-table
19007 org-timer org-xoxo)))
19009 ;;;###autoload
19010 (defun org-reload (&optional uncompiled)
19011 "Reload all org lisp files.
19012 With prefix arg UNCOMPILED, load the uncompiled versions."
19013 (interactive "P")
19014 (require 'find-func)
19015 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
19016 (dir-org (file-name-directory (org-find-library-name "org")))
19017 (dir-org-contrib (ignore-errors
19018 (file-name-directory
19019 (org-find-library-name "org-contribdir"))))
19020 (babel-files
19021 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19022 (append (list nil "comint" "eval" "exp" "keys"
19023 "lob" "ref" "table" "tangle")
19024 (delq nil
19025 (mapcar
19026 (lambda (lang)
19027 (when (cdr lang) (symbol-name (car lang))))
19028 org-babel-load-languages)))))
19029 (files
19030 (append (directory-files dir-org t file-re)
19031 babel-files
19032 (and dir-org-contrib
19033 (directory-files dir-org-contrib t file-re))))
19034 (remove-re (concat (if (featurep 'xemacs)
19035 "org-colview" "org-colview-xemacs")
19036 "\\'")))
19037 (setq files (mapcar 'file-name-sans-extension files))
19038 (setq files (mapcar
19039 (lambda (x) (if (string-match remove-re x) nil x))
19040 files))
19041 (setq files (delq nil files))
19042 (mapc
19043 (lambda (f)
19044 (when (featurep (intern (file-name-nondirectory f)))
19045 (if (and (not uncompiled)
19046 (file-exists-p (concat f ".elc")))
19047 (load (concat f ".elc") nil nil t)
19048 (load (concat f ".el") nil nil t))))
19049 files))
19050 (org-version))
19052 ;;;###autoload
19053 (defun org-customize ()
19054 "Call the customize function with org as argument."
19055 (interactive)
19056 (org-load-modules-maybe)
19057 (org-require-autoloaded-modules)
19058 (customize-browse 'org))
19060 (defun org-create-customize-menu ()
19061 "Create a full customization menu for Org-mode, insert it into the menu."
19062 (interactive)
19063 (org-load-modules-maybe)
19064 (org-require-autoloaded-modules)
19065 (if (fboundp 'customize-menu-create)
19066 (progn
19067 (easy-menu-change
19068 '("Org") "Customize"
19069 `(["Browse Org group" org-customize t]
19070 "--"
19071 ,(customize-menu-create 'org)
19072 ["Set" Custom-set t]
19073 ["Save" Custom-save t]
19074 ["Reset to Current" Custom-reset-current t]
19075 ["Reset to Saved" Custom-reset-saved t]
19076 ["Reset to Standard Settings" Custom-reset-standard t]))
19077 (message "\"Org\"-menu now contains full customization menu"))
19078 (error "Cannot expand menu (outdated version of cus-edit.el)")))
19080 ;;;; Miscellaneous stuff
19082 ;;; Generally useful functions
19084 (defun org-get-at-bol (property)
19085 "Get text property PROPERTY at beginning of line."
19086 (get-text-property (point-at-bol) property))
19088 (defun org-find-text-property-in-string (prop s)
19089 "Return the first non-nil value of property PROP in string S."
19090 (or (get-text-property 0 prop s)
19091 (get-text-property (or (next-single-property-change 0 prop s) 0)
19092 prop s)))
19094 (defun org-display-warning (message) ;; Copied from Emacs-Muse
19095 "Display the given MESSAGE as a warning."
19096 (if (fboundp 'display-warning)
19097 (display-warning 'org message
19098 (if (featurep 'xemacs) 'warning :warning))
19099 (let ((buf (get-buffer-create "*Org warnings*")))
19100 (with-current-buffer buf
19101 (goto-char (point-max))
19102 (insert "Warning (Org): " message)
19103 (unless (bolp)
19104 (newline)))
19105 (display-buffer buf)
19106 (sit-for 0))))
19108 (defun org-eval (form)
19109 "Eval FORM and return result."
19110 (condition-case error
19111 (eval form)
19112 (error (format "%%![Error: %s]" error))))
19114 (defun org-in-commented-line ()
19115 "Is point in a line starting with `#'?"
19116 (equal (char-after (point-at-bol)) ?#))
19118 (defun org-in-indented-comment-line ()
19119 "Is point in a line starting with `#' after some white space?"
19120 (save-excursion
19121 (save-match-data
19122 (goto-char (point-at-bol))
19123 (looking-at "[ \t]*#"))))
19125 (defun org-in-verbatim-emphasis ()
19126 (save-match-data
19127 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
19129 (defun org-goto-marker-or-bmk (marker &optional bookmark)
19130 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
19131 (if (and marker (marker-buffer marker)
19132 (buffer-live-p (marker-buffer marker)))
19133 (progn
19134 (org-pop-to-buffer-same-window (marker-buffer marker))
19135 (if (or (> marker (point-max)) (< marker (point-min)))
19136 (widen))
19137 (goto-char marker)
19138 (org-show-context 'org-goto))
19139 (if bookmark
19140 (bookmark-jump bookmark)
19141 (error "Cannot find location"))))
19143 (defun org-quote-csv-field (s)
19144 "Quote field for inclusion in CSV material."
19145 (if (string-match "[\",]" s)
19146 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
19149 (defun org-force-self-insert (N)
19150 "Needed to enforce self-insert under remapping."
19151 (interactive "p")
19152 (self-insert-command N))
19154 (defun org-string-width (s)
19155 "Compute width of string, ignoring invisible characters.
19156 This ignores character with invisibility property `org-link', and also
19157 characters with property `org-cwidth', because these will become invisible
19158 upon the next fontification round."
19159 (let (b l)
19160 (when (or (eq t buffer-invisibility-spec)
19161 (assq 'org-link buffer-invisibility-spec))
19162 (while (setq b (text-property-any 0 (length s)
19163 'invisible 'org-link s))
19164 (setq s (concat (substring s 0 b)
19165 (substring s (or (next-single-property-change
19166 b 'invisible s) (length s)))))))
19167 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
19168 (setq s (concat (substring s 0 b)
19169 (substring s (or (next-single-property-change
19170 b 'org-cwidth s) (length s))))))
19171 (setq l (string-width s) b -1)
19172 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
19173 (setq l (- l (get-text-property b 'org-dwidth-n s))))
19176 (defun org-shorten-string (s maxlength)
19177 "Shorten string S so tht it is no longer than MAXLENGTH characters.
19178 If the string is shorter or has length MAXLENGTH, just return the
19179 original string. If it is longer, the functions finds a space in the
19180 string, breaks this string off at that locations and adds three dots
19181 as ellipsis. Including the ellipsis, the string will not be longer
19182 than MAXLENGTH. If finding a good breaking point in the string does
19183 not work, the string is just chopped off in the middle of a word
19184 if necessary."
19185 (if (<= (length s) maxlength)
19187 (let* ((n (max (- maxlength 4) 1))
19188 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
19189 (if (string-match re s)
19190 (concat (match-string 1 s) "...")
19191 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
19193 (defun org-get-indentation (&optional line)
19194 "Get the indentation of the current line, interpreting tabs.
19195 When LINE is given, assume it represents a line and compute its indentation."
19196 (if line
19197 (if (string-match "^ *" (org-remove-tabs line))
19198 (match-end 0))
19199 (save-excursion
19200 (beginning-of-line 1)
19201 (skip-chars-forward " \t")
19202 (current-column))))
19204 (defun org-get-string-indentation (s)
19205 "What indentation has S due to SPACE and TAB at the beginning of the string?"
19206 (let ((n -1) (i 0) (w tab-width) c)
19207 (catch 'exit
19208 (while (< (setq n (1+ n)) (length s))
19209 (setq c (aref s n))
19210 (cond ((= c ?\ ) (setq i (1+ i)))
19211 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
19212 (t (throw 'exit t)))))
19215 (defun org-remove-tabs (s &optional width)
19216 "Replace tabulators in S with spaces.
19217 Assumes that s is a single line, starting in column 0."
19218 (setq width (or width tab-width))
19219 (while (string-match "\t" s)
19220 (setq s (replace-match
19221 (make-string
19222 (- (* width (/ (+ (match-beginning 0) width) width))
19223 (match-beginning 0)) ?\ )
19224 t t s)))
19227 (defun org-fix-indentation (line ind)
19228 "Fix indentation in LINE.
19229 IND is a cons cell with target and minimum indentation.
19230 If the current indentation in LINE is smaller than the minimum,
19231 leave it alone. If it is larger than ind, set it to the target."
19232 (let* ((l (org-remove-tabs line))
19233 (i (org-get-indentation l))
19234 (i1 (car ind)) (i2 (cdr ind)))
19235 (if (>= i i2) (setq l (substring line i2)))
19236 (if (> i1 0)
19237 (concat (make-string i1 ?\ ) l)
19238 l)))
19240 (defun org-remove-indentation (code &optional n)
19241 "Remove the maximum common indentation from the lines in CODE.
19242 N may optionally be the number of spaces to remove."
19243 (with-temp-buffer
19244 (insert code)
19245 (org-do-remove-indentation n)
19246 (buffer-string)))
19248 (defun org-do-remove-indentation (&optional n)
19249 "Remove the maximum common indentation from the buffer."
19250 (untabify (point-min) (point-max))
19251 (let ((min 10000) re)
19252 (if n
19253 (setq min n)
19254 (goto-char (point-min))
19255 (while (re-search-forward "^ *[^ \n]" nil t)
19256 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
19257 (unless (or (= min 0) (= min 10000))
19258 (setq re (format "^ \\{%d\\}" min))
19259 (goto-char (point-min))
19260 (while (re-search-forward re nil t)
19261 (replace-match "")
19262 (end-of-line 1))
19263 min)))
19265 (defun org-fill-template (template alist)
19266 "Find each %key of ALIST in TEMPLATE and replace it."
19267 (let ((case-fold-search nil)
19268 entry key value)
19269 (setq alist (sort (copy-sequence alist)
19270 (lambda (a b) (< (length (car a)) (length (car b))))))
19271 (while (setq entry (pop alist))
19272 (setq template
19273 (replace-regexp-in-string
19274 (concat "%" (regexp-quote (car entry)))
19275 (cdr entry) template t t)))
19276 template))
19278 (defun org-base-buffer (buffer)
19279 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
19280 (if (not buffer)
19281 buffer
19282 (or (buffer-base-buffer buffer)
19283 buffer)))
19285 (defun org-trim (s)
19286 "Remove whitespace at beginning and end of string."
19287 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
19288 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
19291 (defun org-wrap (string &optional width lines)
19292 "Wrap string to either a number of lines, or a width in characters.
19293 If WIDTH is non-nil, the string is wrapped to that width, however many lines
19294 that costs. If there is a word longer than WIDTH, the text is actually
19295 wrapped to the length of that word.
19296 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
19297 many lines, whatever width that takes.
19298 The return value is a list of lines, without newlines at the end."
19299 (let* ((words (org-split-string string "[ \t\n]+"))
19300 (maxword (apply 'max (mapcar 'org-string-width words)))
19301 w ll)
19302 (cond (width
19303 (org-do-wrap words (max maxword width)))
19304 (lines
19305 (setq w maxword)
19306 (setq ll (org-do-wrap words maxword))
19307 (if (<= (length ll) lines)
19309 (setq ll words)
19310 (while (> (length ll) lines)
19311 (setq w (1+ w))
19312 (setq ll (org-do-wrap words w)))
19313 ll))
19314 (t (error "Cannot wrap this")))))
19316 (defun org-do-wrap (words width)
19317 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
19318 (let (lines line)
19319 (while words
19320 (setq line (pop words))
19321 (while (and words (< (+ (length line) (length (car words))) width))
19322 (setq line (concat line " " (pop words))))
19323 (setq lines (push line lines)))
19324 (nreverse lines)))
19326 (defun org-split-string (string &optional separators)
19327 "Splits STRING into substrings at SEPARATORS.
19328 No empty strings are returned if there are matches at the beginning
19329 and end of string."
19330 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
19331 (start 0)
19332 notfirst
19333 (list nil))
19334 (while (and (string-match rexp string
19335 (if (and notfirst
19336 (= start (match-beginning 0))
19337 (< start (length string)))
19338 (1+ start) start))
19339 (< (match-beginning 0) (length string)))
19340 (setq notfirst t)
19341 (or (eq (match-beginning 0) 0)
19342 (and (eq (match-beginning 0) (match-end 0))
19343 (eq (match-beginning 0) start))
19344 (setq list
19345 (cons (substring string start (match-beginning 0))
19346 list)))
19347 (setq start (match-end 0)))
19348 (or (eq start (length string))
19349 (setq list
19350 (cons (substring string start)
19351 list)))
19352 (nreverse list)))
19354 (defun org-quote-vert (s)
19355 "Replace \"|\" with \"\\vert\"."
19356 (while (string-match "|" s)
19357 (setq s (replace-match "\\vert" t t s)))
19360 (defun org-uuidgen-p (s)
19361 "Is S an ID created by UUIDGEN?"
19362 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
19364 (defun org-context ()
19365 "Return a list of contexts of the current cursor position.
19366 If several contexts apply, all are returned.
19367 Each context entry is a list with a symbol naming the context, and
19368 two positions indicating start and end of the context. Possible
19369 contexts are:
19371 :headline anywhere in a headline
19372 :headline-stars on the leading stars in a headline
19373 :todo-keyword on a TODO keyword (including DONE) in a headline
19374 :tags on the TAGS in a headline
19375 :priority on the priority cookie in a headline
19376 :item on the first line of a plain list item
19377 :item-bullet on the bullet/number of a plain list item
19378 :checkbox on the checkbox in a plain list item
19379 :table in an org-mode table
19380 :table-special on a special filed in a table
19381 :table-table in a table.el table
19382 :link on a hyperlink
19383 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
19384 :target on a <<target>>
19385 :radio-target on a <<<radio-target>>>
19386 :latex-fragment on a LaTeX fragment
19387 :latex-preview on a LaTeX fragment with overlayed preview image
19389 This function expects the position to be visible because it uses font-lock
19390 faces as a help to recognize the following contexts: :table-special, :link,
19391 and :keyword."
19392 (let* ((f (get-text-property (point) 'face))
19393 (faces (if (listp f) f (list f)))
19394 (p (point)) clist o)
19395 ;; First the large context
19396 (cond
19397 ((org-on-heading-p t)
19398 (push (list :headline (point-at-bol) (point-at-eol)) clist)
19399 (when (progn
19400 (beginning-of-line 1)
19401 (looking-at org-todo-line-tags-regexp))
19402 (push (org-point-in-group p 1 :headline-stars) clist)
19403 (push (org-point-in-group p 2 :todo-keyword) clist)
19404 (push (org-point-in-group p 4 :tags) clist))
19405 (goto-char p)
19406 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
19407 (if (looking-at "\\[#[A-Z0-9]\\]")
19408 (push (org-point-in-group p 0 :priority) clist)))
19410 ((org-at-item-p)
19411 (push (org-point-in-group p 2 :item-bullet) clist)
19412 (push (list :item (point-at-bol)
19413 (save-excursion (org-end-of-item) (point)))
19414 clist)
19415 (and (org-at-item-checkbox-p)
19416 (push (org-point-in-group p 0 :checkbox) clist)))
19418 ((org-at-table-p)
19419 (push (list :table (org-table-begin) (org-table-end)) clist)
19420 (if (memq 'org-formula faces)
19421 (push (list :table-special
19422 (previous-single-property-change p 'face)
19423 (next-single-property-change p 'face)) clist)))
19424 ((org-at-table-p 'any)
19425 (push (list :table-table) clist)))
19426 (goto-char p)
19428 ;; Now the small context
19429 (cond
19430 ((org-at-timestamp-p)
19431 (push (org-point-in-group p 0 :timestamp) clist))
19432 ((memq 'org-link faces)
19433 (push (list :link
19434 (previous-single-property-change p 'face)
19435 (next-single-property-change p 'face)) clist))
19436 ((memq 'org-special-keyword faces)
19437 (push (list :keyword
19438 (previous-single-property-change p 'face)
19439 (next-single-property-change p 'face)) clist))
19440 ((org-on-target-p)
19441 (push (org-point-in-group p 0 :target) clist)
19442 (goto-char (1- (match-beginning 0)))
19443 (if (looking-at org-radio-target-regexp)
19444 (push (org-point-in-group p 0 :radio-target) clist))
19445 (goto-char p))
19446 ((setq o (car (delq nil
19447 (mapcar
19448 (lambda (x)
19449 (if (memq x org-latex-fragment-image-overlays) x))
19450 (overlays-at (point))))))
19451 (push (list :latex-fragment
19452 (overlay-start o) (overlay-end o)) clist)
19453 (push (list :latex-preview
19454 (overlay-start o) (overlay-end o)) clist))
19455 ((org-inside-LaTeX-fragment-p)
19456 ;; FIXME: positions wrong.
19457 (push (list :latex-fragment (point) (point)) clist)))
19459 (setq clist (nreverse (delq nil clist)))
19460 clist))
19462 ;; FIXME: Compare with at-regexp-p Do we need both?
19463 (defun org-in-regexp (re &optional nlines visually)
19464 "Check if point is inside a match of regexp.
19465 Normally only the current line is checked, but you can include NLINES extra
19466 lines both before and after point into the search.
19467 If VISUALLY is set, require that the cursor is not after the match but
19468 really on, so that the block visually is on the match."
19469 (catch 'exit
19470 (let ((pos (point))
19471 (eol (point-at-eol (+ 1 (or nlines 0))))
19472 (inc (if visually 1 0)))
19473 (save-excursion
19474 (beginning-of-line (- 1 (or nlines 0)))
19475 (while (re-search-forward re eol t)
19476 (if (and (<= (match-beginning 0) pos)
19477 (>= (+ inc (match-end 0)) pos))
19478 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
19480 (defun org-at-regexp-p (regexp)
19481 "Is point inside a match of REGEXP in the current line?"
19482 (catch 'exit
19483 (save-excursion
19484 (let ((pos (point)) (end (point-at-eol)))
19485 (beginning-of-line 1)
19486 (while (re-search-forward regexp end t)
19487 (if (and (<= (match-beginning 0) pos)
19488 (>= (match-end 0) pos))
19489 (throw 'exit t)))
19490 nil))))
19492 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
19493 "Non-nil when point is between matches of START-RE and END-RE.
19495 Also return a non-nil value when point is on one of the matches.
19497 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
19498 buffer positions. Default values are the positions of headlines
19499 surrounding the point.
19501 The functions returns a cons cell whose car (resp. cdr) is the
19502 position before START-RE (resp. after END-RE)."
19503 (save-match-data
19504 (let ((pos (point))
19505 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
19506 (limit-down (or lim-down (save-excursion (outline-next-heading))))
19507 beg end)
19508 (save-excursion
19509 ;; Point is on a block when on START-RE or if START-RE can be
19510 ;; found before it...
19511 (and (or (org-at-regexp-p start-re)
19512 (re-search-backward start-re limit-up t))
19513 (setq beg (match-beginning 0))
19514 ;; ... and END-RE after it...
19515 (goto-char (match-end 0))
19516 (re-search-forward end-re limit-down t)
19517 (> (setq end (match-end 0)) pos)
19518 ;; ... without another START-RE in-between.
19519 (goto-char (match-beginning 0))
19520 (not (re-search-backward start-re (1+ beg) t))
19521 ;; Return value.
19522 (cons beg end))))))
19524 (defun org-in-block-p (names)
19525 "Non-nil when point belongs to a block whose name belongs to NAMES.
19527 NAMES is a list of strings containing names of blocks.
19529 Return first block name matched, or nil. Beware that in case of
19530 nested blocks, the returned name may not belong to the closest
19531 block from point."
19532 (save-match-data
19533 (catch 'exit
19534 (let ((case-fold-search t)
19535 (lim-up (save-excursion (outline-previous-heading)))
19536 (lim-down (save-excursion (outline-next-heading))))
19537 (mapc (lambda (name)
19538 (let ((n (regexp-quote name)))
19539 (when (org-between-regexps-p
19540 (concat "^[ \t]*#\\+begin_" n)
19541 (concat "^[ \t]*#\\+end_" n)
19542 lim-up lim-down)
19543 (throw 'exit n))))
19544 names))
19545 nil)))
19547 (defun org-occur-in-agenda-files (regexp &optional nlines)
19548 "Call `multi-occur' with buffers for all agenda files."
19549 (interactive "sOrg-files matching: \np")
19550 (let* ((files (org-agenda-files))
19551 (tnames (mapcar 'file-truename files))
19552 (extra org-agenda-text-search-extra-files)
19554 (when (eq (car extra) 'agenda-archives)
19555 (setq extra (cdr extra))
19556 (setq files (org-add-archive-files files)))
19557 (while (setq f (pop extra))
19558 (unless (member (file-truename f) tnames)
19559 (add-to-list 'files f 'append)
19560 (add-to-list 'tnames (file-truename f) 'append)))
19561 (multi-occur
19562 (mapcar (lambda (x)
19563 (with-current-buffer
19564 (or (get-file-buffer x) (find-file-noselect x))
19565 (widen)
19566 (current-buffer)))
19567 files)
19568 regexp)))
19570 (if (boundp 'occur-mode-find-occurrence-hook)
19571 ;; Emacs 23
19572 (add-hook 'occur-mode-find-occurrence-hook
19573 (lambda ()
19574 (when (eq major-mode 'org-mode)
19575 (org-reveal))))
19576 ;; Emacs 22
19577 (defadvice occur-mode-goto-occurrence
19578 (after org-occur-reveal activate)
19579 (and (eq major-mode 'org-mode) (org-reveal)))
19580 (defadvice occur-mode-goto-occurrence-other-window
19581 (after org-occur-reveal activate)
19582 (and (eq major-mode 'org-mode) (org-reveal)))
19583 (defadvice occur-mode-display-occurrence
19584 (after org-occur-reveal activate)
19585 (when (eq major-mode 'org-mode)
19586 (let ((pos (occur-mode-find-occurrence)))
19587 (with-current-buffer (marker-buffer pos)
19588 (save-excursion
19589 (goto-char pos)
19590 (org-reveal)))))))
19592 (defun org-occur-link-in-agenda-files ()
19593 "Create a link and search for it in the agendas.
19594 The link is not stored in `org-stored-links', it is just created
19595 for the search purpose."
19596 (interactive)
19597 (let ((link (condition-case nil
19598 (org-store-link nil)
19599 (error "Unable to create a link to here"))))
19600 (org-occur-in-agenda-files (regexp-quote link))))
19602 (defun org-uniquify (list)
19603 "Remove duplicate elements from LIST."
19604 (let (res)
19605 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
19606 res))
19608 (defun org-delete-all (elts list)
19609 "Remove all elements in ELTS from LIST."
19610 (while elts
19611 (setq list (delete (pop elts) list)))
19612 list)
19614 (defun org-count (cl-item cl-seq)
19615 "Count the number of occurrences of ITEM in SEQ.
19616 Taken from `count' in cl-seq.el with all keyword arguments removed."
19617 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
19618 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
19619 (while (< cl-start cl-end)
19620 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
19621 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
19622 (setq cl-start (1+ cl-start)))
19623 cl-count))
19625 (defun org-remove-if (predicate seq)
19626 "Remove everything from SEQ that fulfills PREDICATE."
19627 (let (res e)
19628 (while seq
19629 (setq e (pop seq))
19630 (if (not (funcall predicate e)) (push e res)))
19631 (nreverse res)))
19633 (defun org-remove-if-not (predicate seq)
19634 "Remove everything from SEQ that does not fulfill PREDICATE."
19635 (let (res e)
19636 (while seq
19637 (setq e (pop seq))
19638 (if (funcall predicate e) (push e res)))
19639 (nreverse res)))
19641 (defun org-back-over-empty-lines ()
19642 "Move backwards over whitespace, to the beginning of the first empty line.
19643 Returns the number of empty lines passed."
19644 (let ((pos (point)))
19645 (if (cdr (assoc 'heading org-blank-before-new-entry))
19646 (skip-chars-backward " \t\n\r")
19647 (unless (eobp)
19648 (forward-line -1)))
19649 (beginning-of-line 2)
19650 (goto-char (min (point) pos))
19651 (count-lines (point) pos)))
19653 (defun org-skip-whitespace ()
19654 (skip-chars-forward " \t\n\r"))
19656 (defun org-point-in-group (point group &optional context)
19657 "Check if POINT is in match-group GROUP.
19658 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
19659 match. If the match group does not exist or point is not inside it,
19660 return nil."
19661 (and (match-beginning group)
19662 (>= point (match-beginning group))
19663 (<= point (match-end group))
19664 (if context
19665 (list context (match-beginning group) (match-end group))
19666 t)))
19668 (defun org-switch-to-buffer-other-window (&rest args)
19669 "Switch to buffer in a second window on the current frame.
19670 In particular, do not allow pop-up frames.
19671 Returns the newly created buffer."
19672 (let (pop-up-frames special-display-buffer-names special-display-regexps
19673 special-display-function)
19674 (apply 'switch-to-buffer-other-window args)))
19676 (defun org-combine-plists (&rest plists)
19677 "Create a single property list from all plists in PLISTS.
19678 The process starts by copying the first list, and then setting properties
19679 from the other lists. Settings in the last list are the most significant
19680 ones and overrule settings in the other lists."
19681 (let ((rtn (copy-sequence (pop plists)))
19682 p v ls)
19683 (while plists
19684 (setq ls (pop plists))
19685 (while ls
19686 (setq p (pop ls) v (pop ls))
19687 (setq rtn (plist-put rtn p v))))
19688 rtn))
19690 (defun org-move-line-down (arg)
19691 "Move the current line down. With prefix argument, move it past ARG lines."
19692 (interactive "p")
19693 (let ((col (current-column))
19694 beg end pos)
19695 (beginning-of-line 1) (setq beg (point))
19696 (beginning-of-line 2) (setq end (point))
19697 (beginning-of-line (+ 1 arg))
19698 (setq pos (move-marker (make-marker) (point)))
19699 (insert (delete-and-extract-region beg end))
19700 (goto-char pos)
19701 (org-move-to-column col)))
19703 (defun org-move-line-up (arg)
19704 "Move the current line up. With prefix argument, move it past ARG lines."
19705 (interactive "p")
19706 (let ((col (current-column))
19707 beg end pos)
19708 (beginning-of-line 1) (setq beg (point))
19709 (beginning-of-line 2) (setq end (point))
19710 (beginning-of-line (- arg))
19711 (setq pos (move-marker (make-marker) (point)))
19712 (insert (delete-and-extract-region beg end))
19713 (goto-char pos)
19714 (org-move-to-column col)))
19716 (defun org-replace-escapes (string table)
19717 "Replace %-escapes in STRING with values in TABLE.
19718 TABLE is an association list with keys like \"%a\" and string values.
19719 The sequences in STRING may contain normal field width and padding information,
19720 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
19721 so values can contain further %-escapes if they are define later in TABLE."
19722 (let ((tbl (copy-alist table))
19723 (case-fold-search nil)
19724 (pchg 0)
19725 e re rpl)
19726 (while (setq e (pop tbl))
19727 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
19728 (when (and (cdr e) (string-match re (cdr e)))
19729 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
19730 (safe "SREF"))
19731 (add-text-properties 0 3 (list 'sref sref) safe)
19732 (setcdr e (replace-match safe t t (cdr e)))))
19733 (while (string-match re string)
19734 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
19735 (cdr e)))
19736 (setq string (replace-match rpl t t string))))
19737 (while (setq pchg (next-property-change pchg string))
19738 (let ((sref (get-text-property pchg 'sref string)))
19739 (when (and sref (string-match "SREF" string pchg))
19740 (setq string (replace-match sref t t string)))))
19741 string))
19743 (defun org-sublist (list start end)
19744 "Return a section of LIST, from START to END.
19745 Counting starts at 1."
19746 (let (rtn (c start))
19747 (setq list (nthcdr (1- start) list))
19748 (while (and list (<= c end))
19749 (push (pop list) rtn)
19750 (setq c (1+ c)))
19751 (nreverse rtn)))
19753 (defun org-find-base-buffer-visiting (file)
19754 "Like `find-buffer-visiting' but always return the base buffer and
19755 not an indirect buffer."
19756 (let ((buf (or (get-file-buffer file)
19757 (find-buffer-visiting file))))
19758 (if buf
19759 (or (buffer-base-buffer buf) buf)
19760 nil)))
19762 (defun org-image-file-name-regexp (&optional extensions)
19763 "Return regexp matching the file names of images.
19764 If EXTENSIONS is given, only match these."
19765 (if (and (not extensions) (fboundp 'image-file-name-regexp))
19766 (image-file-name-regexp)
19767 (let ((image-file-name-extensions
19768 (or extensions
19769 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
19770 "xbm" "xpm" "pbm" "pgm" "ppm"))))
19771 (concat "\\."
19772 (regexp-opt (nconc (mapcar 'upcase
19773 image-file-name-extensions)
19774 image-file-name-extensions)
19776 "\\'"))))
19778 (defun org-file-image-p (file &optional extensions)
19779 "Return non-nil if FILE is an image."
19780 (save-match-data
19781 (string-match (org-image-file-name-regexp extensions) file)))
19783 (defun org-get-cursor-date ()
19784 "Return the date at cursor in as a time.
19785 This works in the calendar and in the agenda, anywhere else it just
19786 returns the current time."
19787 (let (date day defd)
19788 (cond
19789 ((eq major-mode 'calendar-mode)
19790 (setq date (calendar-cursor-to-date)
19791 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
19792 ((eq major-mode 'org-agenda-mode)
19793 (setq day (get-text-property (point) 'day))
19794 (if day
19795 (setq date (calendar-gregorian-from-absolute day)
19796 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
19797 (nth 2 date))))))
19798 (or defd (current-time))))
19800 (defvar org-agenda-action-marker (make-marker)
19801 "Marker pointing to the entry for the next agenda action.")
19803 (defun org-mark-entry-for-agenda-action ()
19804 "Mark the current entry as target of an agenda action.
19805 Agenda actions are actions executed from the agenda with the key `k',
19806 which make use of the date at the cursor."
19807 (interactive)
19808 (move-marker org-agenda-action-marker
19809 (save-excursion (org-back-to-heading t) (point))
19810 (current-buffer))
19811 (message
19812 "Entry marked for action; press `k' at desired date in agenda or calendar"))
19814 (defun org-mark-subtree ()
19815 "Mark the current subtree.
19816 This puts point at the start of the current subtree, and mark at the end.
19818 If point is in an inline task, mark that task instead."
19819 (interactive)
19820 (let ((inline-task-p
19821 (and (featurep 'org-inlinetask)
19822 (org-inlinetask-in-task-p)))
19823 (beg))
19824 ;; Get beginning of subtree
19825 (cond
19826 (inline-task-p (org-inlinetask-goto-beginning))
19827 ((org-at-heading-p) (beginning-of-line))
19828 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
19829 (setq beg (point))
19830 ;; Get end of it
19831 (if inline-task-p
19832 (org-inlinetask-goto-end)
19833 (org-end-of-subtree))
19834 ;; Mark zone
19835 (push-mark (point) nil t)
19836 (goto-char beg)))
19838 ;;; Paragraph filling stuff.
19839 ;; We want this to be just right, so use the full arsenal.
19841 (defun org-indent-line-function ()
19842 "Indent line depending on context."
19843 (interactive)
19844 (let* ((pos (point))
19845 (itemp (org-at-item-p))
19846 (case-fold-search t)
19847 (org-drawer-regexp (or org-drawer-regexp "\000"))
19848 (inline-task-p (and (featurep 'org-inlinetask)
19849 (org-inlinetask-in-task-p)))
19850 (inline-re (and inline-task-p
19851 (org-inlinetask-outline-regexp)))
19852 column)
19853 (beginning-of-line 1)
19854 (cond
19855 ;; Comments
19856 ((looking-at "# ") (setq column 0))
19857 ;; Headings
19858 ((looking-at org-outline-regexp) (setq column 0))
19859 ;; Included files
19860 ((looking-at "#\\+include:") (setq column 0))
19861 ;; Footnote definition
19862 ((looking-at org-footnote-definition-re) (setq column 0))
19863 ;; Literal examples
19864 ((looking-at "[ \t]*:\\( \\|$\\)")
19865 (setq column (org-get-indentation))) ; do nothing
19866 ;; Lists
19867 ((ignore-errors (goto-char (org-in-item-p)))
19868 (setq column (if itemp
19869 (org-get-indentation)
19870 (org-list-item-body-column (point))))
19871 (goto-char pos))
19872 ;; Drawers
19873 ((and (looking-at "[ \t]*:END:")
19874 (save-excursion (re-search-backward org-drawer-regexp nil t)))
19875 (save-excursion
19876 (goto-char (1- (match-beginning 1)))
19877 (setq column (current-column))))
19878 ;; Special blocks
19879 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
19880 (save-excursion
19881 (re-search-backward
19882 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
19883 (setq column (org-get-indentation (match-string 0))))
19884 ((and (not (looking-at "[ \t]*#\\+begin_"))
19885 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
19886 (save-excursion
19887 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
19888 (setq column
19889 (cond ((equal (downcase (match-string 1)) "src")
19890 ;; src blocks: let `org-edit-src-exit' handle them
19891 (org-get-indentation))
19892 ((equal (downcase (match-string 1)) "example")
19893 (max (org-get-indentation)
19894 (org-get-indentation (match-string 0))))
19896 (org-get-indentation (match-string 0))))))
19897 ;; This line has nothing special, look at the previous relevant
19898 ;; line to compute indentation
19900 (beginning-of-line 0)
19901 (while (and (not (bobp))
19902 (not (looking-at org-drawer-regexp))
19903 ;; When point started in an inline task, do not move
19904 ;; above task starting line.
19905 (not (and inline-task-p (looking-at inline-re)))
19906 ;; Skip drawers, blocks, empty lines, verbatim,
19907 ;; comments, tables, footnotes definitions, lists,
19908 ;; inline tasks.
19909 (or (and (looking-at "[ \t]*:END:")
19910 (re-search-backward org-drawer-regexp nil t))
19911 (and (looking-at "[ \t]*#\\+end_")
19912 (re-search-backward "[ \t]*#\\+begin_"nil t))
19913 (looking-at "[ \t]*[\n:#|]")
19914 (looking-at org-footnote-definition-re)
19915 (and (ignore-errors (goto-char (org-in-item-p)))
19916 (goto-char
19917 (org-list-get-top-point (org-list-struct))))
19918 (and (not inline-task-p)
19919 (featurep 'org-inlinetask)
19920 (org-inlinetask-in-task-p)
19921 (or (org-inlinetask-goto-beginning) t))))
19922 (beginning-of-line 0))
19923 (cond
19924 ;; There was an heading above.
19925 ((looking-at "\\*+[ \t]+")
19926 (if (not org-adapt-indentation)
19927 (setq column 0)
19928 (goto-char (match-end 0))
19929 (setq column (current-column))))
19930 ;; A drawer had started and is unfinished
19931 ((looking-at org-drawer-regexp)
19932 (goto-char (1- (match-beginning 1)))
19933 (setq column (current-column)))
19934 ;; Else, nothing noticeable found: get indentation and go on.
19935 (t (setq column (org-get-indentation))))))
19936 ;; Now apply indentation and move cursor accordingly
19937 (goto-char pos)
19938 (if (<= (current-column) (current-indentation))
19939 (org-indent-line-to column)
19940 (save-excursion (org-indent-line-to column)))
19941 ;; Special polishing for properties, see `org-property-format'
19942 (setq column (current-column))
19943 (beginning-of-line 1)
19944 (if (looking-at
19945 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
19946 (replace-match (concat (match-string 1)
19947 (format org-property-format
19948 (match-string 2) (match-string 3)))
19949 t t))
19950 (org-move-to-column column)))
19952 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
19953 "Variable to store copy of `adaptive-fill-regexp'.
19954 Since `adaptive-fill-regexp' is set to never match, we need to
19955 store a backup of its value before entering `org-mode' so that
19956 the functionality can be provided as a fall-back.")
19958 (defun org-set-autofill-regexps ()
19959 (interactive)
19960 ;; In the paragraph separator we include headlines, because filling
19961 ;; text in a line directly attached to a headline would otherwise
19962 ;; fill the headline as well.
19963 (org-set-local 'comment-start-skip "^#+[ \t]*")
19964 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
19965 ;; The paragraph starter includes hand-formatted lists.
19966 (org-set-local
19967 'paragraph-start
19968 (concat
19969 "\f" "\\|"
19970 "[ ]*$" "\\|"
19971 org-outline-regexp "\\|"
19972 "[ \t]*#" "\\|"
19973 (org-item-re) "\\|"
19974 "[ \t]*[:|]" "\\|"
19975 "\\$\\$" "\\|"
19976 "\\\\\\(begin\\|end\\|[][]\\)"))
19977 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
19978 ;; But only if the user has not turned off tables or fixed-width regions
19979 (org-set-local
19980 'auto-fill-inhibit-regexp
19981 (concat org-outline-regexp
19982 "\\|#\\+"
19983 "\\|[ \t]*" org-keyword-time-regexp
19984 (if (or org-enable-table-editor org-enable-fixed-width-editor)
19985 (concat
19986 "\\|[ \t]*["
19987 (if org-enable-table-editor "|" "")
19988 (if org-enable-fixed-width-editor ":" "")
19989 "]"))))
19990 ;; We use our own fill-paragraph function, to make sure that tables
19991 ;; and fixed-width regions are not wrapped. That function will pass
19992 ;; through to `fill-paragraph' when appropriate.
19993 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
19994 ;; Prevent auto-fill from inserting unwanted new items.
19995 (if (boundp 'fill-nobreak-predicate)
19996 (org-set-local 'fill-nobreak-predicate
19997 (if (memq 'org-fill-item-nobreak-p fill-nobreak-predicate)
19998 fill-nobreak-predicate
19999 (cons 'org-fill-item-nobreak-p fill-nobreak-predicate))))
20000 ;; Adaptive filling: To get full control, first make sure that
20001 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
20002 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
20003 (org-set-local 'org-adaptive-fill-regexp-backup
20004 adaptive-fill-regexp))
20005 (org-set-local 'adaptive-fill-regexp "\000")
20006 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20007 (org-set-local 'adaptive-fill-function
20008 'org-adaptive-fill-function)
20009 (org-set-local
20010 'align-mode-rules-list
20011 '((org-in-buffer-settings
20012 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
20013 (modes . '(org-mode))))))
20015 (defun org-fill-item-nobreak-p ()
20016 "Non-nil when a line break at point would insert a new item."
20017 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
20019 (defun org-fill-paragraph (&optional justify)
20020 "Re-align a table, pass through to fill-paragraph if no table."
20021 (let ((table-p (org-at-table-p))
20022 (table.el-p (org-at-table.el-p))
20023 (itemp (org-in-item-p)))
20024 (cond ((and (equal (char-after (point-at-bol)) ?*)
20025 (save-excursion (goto-char (point-at-bol))
20026 (looking-at org-outline-regexp)))
20027 t) ; skip headlines
20028 (table.el-p t) ; skip table.el tables
20029 (table-p (org-table-align) t) ; align Org tables
20030 (itemp ; align text in items
20031 (let* ((struct (save-excursion (goto-char itemp)
20032 (org-list-struct)))
20033 (parents (org-list-parents-alist struct))
20034 (children (org-list-get-children itemp struct parents))
20035 beg end prev next prefix)
20036 ;; Determine in which part of item point is: before
20037 ;; first child, after last child, between two
20038 ;; sub-lists, or simply in item if there's no child.
20039 (cond
20040 ((not children)
20041 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20042 beg itemp
20043 end (org-list-get-item-end itemp struct)))
20044 ((< (point) (setq next (car children)))
20045 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20046 beg itemp
20047 end next))
20048 ((> (point) (setq prev (car (last children))))
20049 (setq beg (org-list-get-item-end prev struct)
20050 end (org-list-get-item-end itemp struct)
20051 prefix (save-excursion
20052 (goto-char beg)
20053 (skip-chars-forward " \t")
20054 (make-string (current-column) ?\ ))))
20055 (t (catch 'exit
20056 (while (setq next (pop children))
20057 (if (> (point) next)
20058 (setq prev next)
20059 (setq beg (org-list-get-item-end prev struct)
20060 end next
20061 prefix (save-excursion
20062 (goto-char beg)
20063 (skip-chars-forward " \t")
20064 (make-string (current-column) ?\ )))
20065 (throw 'exit nil))))))
20066 ;; Use `fill-paragraph' with buffer narrowed to item
20067 ;; without any child, and with our computed PREFIX.
20068 (flet ((fill-context-prefix (from to &optional flr) prefix))
20069 (save-restriction
20070 (narrow-to-region beg end)
20071 (save-excursion (fill-paragraph justify)))) t))
20072 ;; Special case where point is not in a list but is on
20073 ;; a paragraph adjacent to a list: make sure this paragraph
20074 ;; doesn't get merged with the end of the list by narrowing
20075 ;; buffer first.
20076 ((save-excursion (forward-paragraph -1)
20077 (setq itemp (org-in-item-p)))
20078 (let ((struct (save-excursion (goto-char itemp)
20079 (org-list-struct))))
20080 (save-restriction
20081 (narrow-to-region (org-list-get-bottom-point struct)
20082 (save-excursion (forward-paragraph 1)
20083 (point)))
20084 (fill-paragraph justify) t)))
20085 ;; Else simply call `fill-paragraph'.
20086 (t nil))))
20088 ;; For reference, this is the default value of adaptive-fill-regexp
20089 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
20091 (defun org-adaptive-fill-function ()
20092 "Return a fill prefix for org-mode files."
20093 (let (itemp)
20094 (save-excursion
20095 (cond
20096 ;; Comment line
20097 ((looking-at "#[ \t]+")
20098 (match-string-no-properties 0))
20099 ;; Plain list item
20100 ((org-at-item-p)
20101 (make-string (org-list-item-body-column (point-at-bol)) ?\ ))
20102 ;; Point is in a list after `backward-paragraph': original
20103 ;; point wasn't in the list, or filling would have been taken
20104 ;; care of by `org-auto-fill-function', but the list and the
20105 ;; real paragraph are not separated by a blank line. Thus, move
20106 ;; point after the list to go back to real paragraph and
20107 ;; determine fill-prefix.
20108 ((setq itemp (org-in-item-p))
20109 (goto-char itemp)
20110 (let* ((struct (org-list-struct))
20111 (bottom (org-list-get-bottom-point struct)))
20112 (goto-char bottom)
20113 (make-string (org-get-indentation) ?\ )))
20114 ;; Other text
20115 ((looking-at org-adaptive-fill-regexp-backup)
20116 (match-string-no-properties 0))))))
20118 (defun org-auto-fill-function ()
20119 "Auto-fill function."
20120 (let (itemp prefix)
20121 ;; When in a list, compute an appropriate fill-prefix and make
20122 ;; sure it will be used by `do-auto-fill'.
20123 (if (setq itemp (org-in-item-p))
20124 (progn
20125 (setq prefix (make-string (org-list-item-body-column itemp) ?\ ))
20126 (flet ((fill-context-prefix (from to &optional flr) prefix))
20127 (do-auto-fill)))
20128 ;; Else just use `do-auto-fill'.
20129 (do-auto-fill))))
20131 ;;; Other stuff.
20133 (defun org-toggle-fixed-width-section (arg)
20134 "Toggle the fixed-width export.
20135 If there is no active region, the QUOTE keyword at the current headline is
20136 inserted or removed. When present, it causes the text between this headline
20137 and the next to be exported as fixed-width text, and unmodified.
20138 If there is an active region, this command adds or removes a colon as the
20139 first character of this line. If the first character of a line is a colon,
20140 this line is also exported in fixed-width font."
20141 (interactive "P")
20142 (let* ((cc 0)
20143 (regionp (org-region-active-p))
20144 (beg (if regionp (region-beginning) (point)))
20145 (end (if regionp (region-end)))
20146 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
20147 (case-fold-search nil)
20148 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
20149 off)
20150 (if regionp
20151 (save-excursion
20152 (goto-char beg)
20153 (setq cc (current-column))
20154 (beginning-of-line 1)
20155 (setq off (looking-at re))
20156 (while (> nlines 0)
20157 (setq nlines (1- nlines))
20158 (beginning-of-line 1)
20159 (cond
20160 (arg
20161 (org-move-to-column cc t)
20162 (insert ": \n")
20163 (forward-line -1))
20164 ((and off (looking-at re))
20165 (replace-match "" t t nil 1))
20166 ((not off) (org-move-to-column cc t) (insert ": ")))
20167 (forward-line 1)))
20168 (save-excursion
20169 (org-back-to-heading)
20170 (cond
20171 ((looking-at (format org-heading-keyword-regexp-format
20172 org-quote-string))
20173 (goto-char (match-end 1))
20174 (looking-at (concat " +" org-quote-string))
20175 (replace-match "" t t)
20176 (when (eolp) (insert " ")))
20177 ((looking-at org-outline-regexp)
20178 (goto-char (match-end 0))
20179 (insert org-quote-string " ")))))))
20181 (defun org-reftex-citation ()
20182 "Use reftex-citation to insert a citation into the buffer.
20183 This looks for a line like
20185 #+BIBLIOGRAPHY: foo plain option:-d
20187 and derives from it that foo.bib is the bibliography file relevant
20188 for this document. It then installs the necessary environment for RefTeX
20189 to work in this buffer and calls `reftex-citation' to insert a citation
20190 into the buffer.
20192 Export of such citations to both LaTeX and HTML is handled by the contributed
20193 package org-exp-bibtex by Taru Karttunen."
20194 (interactive)
20195 (let ((reftex-docstruct-symbol 'rds)
20196 (reftex-cite-format "\\cite{%l}")
20197 rds bib)
20198 (save-excursion
20199 (save-restriction
20200 (widen)
20201 (let ((case-fold-search t)
20202 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
20203 (if (not (save-excursion
20204 (or (re-search-forward re nil t)
20205 (re-search-backward re nil t))))
20206 (error "No bibliography defined in file")
20207 (setq bib (concat (match-string 1) ".bib")
20208 rds (list (list 'bib bib)))))))
20209 (call-interactively 'reftex-citation)))
20211 ;;;; Functions extending outline functionality
20213 (defun org-beginning-of-line (&optional arg)
20214 "Go to the beginning of the current line. If that is invisible, continue
20215 to a visible line beginning. This makes the function of C-a more intuitive.
20216 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20217 first attempt, and only move to after the tags when the cursor is already
20218 beyond the end of the headline."
20219 (interactive "P")
20220 (let ((pos (point))
20221 (special (if (consp org-special-ctrl-a/e)
20222 (car org-special-ctrl-a/e)
20223 org-special-ctrl-a/e))
20224 refpos)
20225 (if (org-bound-and-true-p line-move-visual)
20226 (beginning-of-visual-line 1)
20227 (beginning-of-line 1))
20228 (if (and arg (fboundp 'move-beginning-of-line))
20229 (call-interactively 'move-beginning-of-line)
20230 (if (bobp)
20232 (backward-char 1)
20233 (if (org-truely-invisible-p)
20234 (while (and (not (bobp)) (org-truely-invisible-p))
20235 (backward-char 1)
20236 (beginning-of-line 1))
20237 (forward-char 1))))
20238 (when special
20239 (cond
20240 ((and (looking-at org-complex-heading-regexp)
20241 (= (char-after (match-end 1)) ?\ ))
20242 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
20243 (point-at-eol)))
20244 (goto-char
20245 (if (eq special t)
20246 (cond ((> pos refpos) refpos)
20247 ((= pos (point)) refpos)
20248 (t (point)))
20249 (cond ((> pos (point)) (point))
20250 ((not (eq last-command this-command)) (point))
20251 (t refpos)))))
20252 ((org-at-item-p)
20253 (goto-char
20254 (if (eq special t)
20255 (cond ((> pos (match-end 0)) (match-end 0))
20256 ((= pos (point)) (match-end 0))
20257 (t (point)))
20258 (cond ((> pos (point)) (point))
20259 ((not (eq last-command this-command)) (point))
20260 (t (match-end 0))))))))
20261 (org-no-warnings
20262 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20264 (defun org-end-of-line (&optional arg)
20265 "Go to the end of the line.
20266 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20267 first attempt, and only move to after the tags when the cursor is already
20268 beyond the end of the headline."
20269 (interactive "P")
20270 (let ((special (if (consp org-special-ctrl-a/e)
20271 (cdr org-special-ctrl-a/e)
20272 org-special-ctrl-a/e)))
20273 (cond
20274 ((or (not special) arg
20275 (not (or (org-on-heading-p) (org-at-item-p))))
20276 (call-interactively
20277 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
20278 ((fboundp 'move-end-of-line) 'move-end-of-line)
20279 (t 'end-of-line))))
20280 ((org-on-heading-p)
20281 (let ((pos (point)))
20282 (beginning-of-line 1)
20283 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
20284 (if (eq special t)
20285 (if (or (< pos (match-beginning 1))
20286 (= pos (match-end 0)))
20287 (goto-char (match-beginning 1))
20288 (goto-char (match-end 0)))
20289 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
20290 (goto-char (match-end 0))
20291 (goto-char (match-beginning 1))))
20292 (call-interactively (if (fboundp 'move-end-of-line)
20293 'move-end-of-line
20294 'end-of-line)))))
20295 ;; At an item: Move before any hidden text.
20296 (t (call-interactively 'end-of-line)))
20297 (org-no-warnings
20298 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20300 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
20301 (define-key org-mode-map "\C-e" 'org-end-of-line)
20303 (defun org-backward-sentence (&optional arg)
20304 "Go to beginning of sentence, or beginning of table field.
20305 This will call `backward-sentence' or `org-table-beginning-of-field',
20306 depending on context."
20307 (interactive "P")
20308 (cond
20309 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
20310 (t (call-interactively 'backward-sentence))))
20312 (defun org-forward-sentence (&optional arg)
20313 "Go to end of sentence, or end of table field.
20314 This will call `forward-sentence' or `org-table-end-of-field',
20315 depending on context."
20316 (interactive "P")
20317 (cond
20318 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
20319 (t (call-interactively 'forward-sentence))))
20321 (define-key org-mode-map "\M-a" 'org-backward-sentence)
20322 (define-key org-mode-map "\M-e" 'org-forward-sentence)
20324 (defun org-kill-line (&optional arg)
20325 "Kill line, to tags or end of line."
20326 (interactive "P")
20327 (cond
20328 ((or (not org-special-ctrl-k)
20329 (bolp)
20330 (not (org-on-heading-p)))
20331 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
20332 org-ctrl-k-protect-subtree)
20333 (if (or (eq org-ctrl-k-protect-subtree 'error)
20334 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
20335 (error "C-k aborted - would kill hidden subtree")))
20336 (call-interactively 'kill-line))
20337 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
20338 (kill-region (point) (match-beginning 1))
20339 (org-set-tags nil t))
20340 (t (kill-region (point) (point-at-eol)))))
20342 (define-key org-mode-map "\C-k" 'org-kill-line)
20344 (defun org-yank (&optional arg)
20345 "Yank. If the kill is a subtree, treat it specially.
20346 This command will look at the current kill and check if is a single
20347 subtree, or a series of subtrees[1]. If it passes the test, and if the
20348 cursor is at the beginning of a line or after the stars of a currently
20349 empty headline, then the yank is handled specially. How exactly depends
20350 on the value of the following variables, both set by default.
20352 org-yank-folded-subtrees
20353 When set, the subtree(s) will be folded after insertion, but only
20354 if doing so would now swallow text after the yanked text.
20356 org-yank-adjusted-subtrees
20357 When set, the subtree will be promoted or demoted in order to
20358 fit into the local outline tree structure, which means that the level
20359 will be adjusted so that it becomes the smaller one of the two
20360 *visible* surrounding headings.
20362 Any prefix to this command will cause `yank' to be called directly with
20363 no special treatment. In particular, a simple \\[universal-argument] prefix \
20364 will just
20365 plainly yank the text as it is.
20367 \[1] The test checks if the first non-white line is a heading
20368 and if there are no other headings with fewer stars."
20369 (interactive "P")
20370 (org-yank-generic 'yank arg))
20372 (defun org-yank-generic (command arg)
20373 "Perform some yank-like command.
20375 This function implements the behavior described in the `org-yank'
20376 documentation. However, it has been generalized to work for any
20377 interactive command with similar behavior."
20379 ;; pretend to be command COMMAND
20380 (setq this-command command)
20382 (if arg
20383 (call-interactively command)
20385 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
20386 (and (org-kill-is-subtree-p)
20387 (or (bolp)
20388 (and (looking-at "[ \t]*$")
20389 (string-match
20390 "\\`\\*+\\'"
20391 (buffer-substring (point-at-bol) (point)))))))
20392 swallowp)
20393 (cond
20394 ((and subtreep org-yank-folded-subtrees)
20395 (let ((beg (point))
20396 end)
20397 (if (and subtreep org-yank-adjusted-subtrees)
20398 (org-paste-subtree nil nil 'for-yank)
20399 (call-interactively command))
20401 (setq end (point))
20402 (goto-char beg)
20403 (when (and (bolp) subtreep
20404 (not (setq swallowp
20405 (org-yank-folding-would-swallow-text beg end))))
20406 (org-with-limited-levels
20407 (or (looking-at org-outline-regexp)
20408 (re-search-forward org-outline-regexp-bol end t))
20409 (while (and (< (point) end) (looking-at org-outline-regexp))
20410 (hide-subtree)
20411 (org-cycle-show-empty-lines 'folded)
20412 (condition-case nil
20413 (outline-forward-same-level 1)
20414 (error (goto-char end))))))
20415 (when swallowp
20416 (message
20417 "Inserted text not folded because that would swallow text"))
20419 (goto-char end)
20420 (skip-chars-forward " \t\n\r")
20421 (beginning-of-line 1)
20422 (push-mark beg 'nomsg)))
20423 ((and subtreep org-yank-adjusted-subtrees)
20424 (let ((beg (point-at-bol)))
20425 (org-paste-subtree nil nil 'for-yank)
20426 (push-mark beg 'nomsg)))
20428 (call-interactively command))))))
20430 (defun org-yank-folding-would-swallow-text (beg end)
20431 "Would hide-subtree at BEG swallow any text after END?"
20432 (let (level)
20433 (org-with-limited-levels
20434 (save-excursion
20435 (goto-char beg)
20436 (when (or (looking-at org-outline-regexp)
20437 (re-search-forward org-outline-regexp-bol end t))
20438 (setq level (org-outline-level)))
20439 (goto-char end)
20440 (skip-chars-forward " \t\r\n\v\f")
20441 (if (or (eobp)
20442 (and (bolp) (looking-at org-outline-regexp)
20443 (<= (org-outline-level) level)))
20444 nil ; Nothing would be swallowed
20445 t))))) ; something would swallow
20447 (define-key org-mode-map "\C-y" 'org-yank)
20449 (defun org-truely-invisible-p ()
20450 "Check if point is at a character currently not visible.
20451 This version does not only check the character property, but also
20452 `visible-mode'."
20453 ;; Early versions of noutline don't have `outline-invisible-p'.
20454 (if (org-bound-and-true-p visible-mode)
20456 (outline-invisible-p)))
20458 (defun org-invisible-p2 ()
20459 "Check if point is at a character currently not visible."
20460 (save-excursion
20461 (if (and (eolp) (not (bobp))) (backward-char 1))
20462 ;; Early versions of noutline don't have `outline-invisible-p'.
20463 (outline-invisible-p)))
20465 (defun org-back-to-heading (&optional invisible-ok)
20466 "Call `outline-back-to-heading', but provide a better error message."
20467 (condition-case nil
20468 (outline-back-to-heading invisible-ok)
20469 (error (error "Before first headline at position %d in buffer %s"
20470 (point) (current-buffer)))))
20472 (defun org-beginning-of-defun ()
20473 "Go to the beginning of the subtree, i.e. back to the heading."
20474 (org-back-to-heading))
20475 (defun org-end-of-defun ()
20476 "Go to the end of the subtree."
20477 (org-end-of-subtree nil t))
20479 (defun org-before-first-heading-p ()
20480 "Before first heading?"
20481 (save-excursion
20482 (end-of-line)
20483 (null (re-search-backward org-outline-regexp-bol nil t))))
20485 (defun org-on-heading-p (&optional ignored)
20486 (outline-on-heading-p t))
20487 (defun org-at-heading-p (&optional ignored)
20488 (outline-on-heading-p t))
20490 (defun org-point-at-end-of-empty-headline ()
20491 "If point is at the end of an empty headline, return t, else nil.
20492 If the heading only contains a TODO keyword, it is still still considered
20493 empty."
20494 (and (looking-at "[ \t]*$")
20495 (save-excursion
20496 (beginning-of-line 1)
20497 (let ((case-fold-search nil))
20498 (looking-at org-todo-line-regexp)))
20499 (string= (match-string 3) "")))
20501 (defun org-at-heading-or-item-p ()
20502 (or (org-on-heading-p) (org-at-item-p)))
20504 (defun org-on-target-p ()
20505 (or (org-in-regexp org-radio-target-regexp)
20506 (org-in-regexp org-target-regexp)))
20508 (defun org-up-heading-all (arg)
20509 "Move to the heading line of which the present line is a subheading.
20510 This function considers both visible and invisible heading lines.
20511 With argument, move up ARG levels."
20512 (if (fboundp 'outline-up-heading-all)
20513 (outline-up-heading-all arg) ; emacs 21 version of outline.el
20514 (outline-up-heading arg t))) ; emacs 22 version of outline.el
20516 (defun org-up-heading-safe ()
20517 "Move to the heading line of which the present line is a subheading.
20518 This version will not throw an error. It will return the level of the
20519 headline found, or nil if no higher level is found.
20521 Also, this function will be a lot faster than `outline-up-heading',
20522 because it relies on stars being the outline starters. This can really
20523 make a significant difference in outlines with very many siblings."
20524 (let (start-level re)
20525 (org-back-to-heading t)
20526 (setq start-level (funcall outline-level))
20527 (if (equal start-level 1)
20529 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
20530 (if (re-search-backward re nil t)
20531 (funcall outline-level)))))
20533 (defun org-first-sibling-p ()
20534 "Is this heading the first child of its parents?"
20535 (interactive)
20536 (let ((re org-outline-regexp-bol)
20537 level l)
20538 (unless (org-at-heading-p t)
20539 (error "Not at a heading"))
20540 (setq level (funcall outline-level))
20541 (save-excursion
20542 (if (not (re-search-backward re nil t))
20544 (setq l (funcall outline-level))
20545 (< l level)))))
20547 (defun org-goto-sibling (&optional previous)
20548 "Goto the next sibling, even if it is invisible.
20549 When PREVIOUS is set, go to the previous sibling instead. Returns t
20550 when a sibling was found. When none is found, return nil and don't
20551 move point."
20552 (let ((fun (if previous 're-search-backward 're-search-forward))
20553 (pos (point))
20554 (re org-outline-regexp-bol)
20555 level l)
20556 (when (condition-case nil (org-back-to-heading t) (error nil))
20557 (setq level (funcall outline-level))
20558 (catch 'exit
20559 (or previous (forward-char 1))
20560 (while (funcall fun re nil t)
20561 (setq l (funcall outline-level))
20562 (when (< l level) (goto-char pos) (throw 'exit nil))
20563 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
20564 (goto-char pos)
20565 nil))))
20567 (defun org-show-siblings ()
20568 "Show all siblings of the current headline."
20569 (save-excursion
20570 (while (org-goto-sibling) (org-flag-heading nil)))
20571 (save-excursion
20572 (while (org-goto-sibling 'previous)
20573 (org-flag-heading nil))))
20575 (defun org-goto-first-child ()
20576 "Goto the first child, even if it is invisible.
20577 Return t when a child was found. Otherwise don't move point and
20578 return nil."
20579 (let (level (pos (point)) (re org-outline-regexp-bol))
20580 (when (condition-case nil (org-back-to-heading t) (error nil))
20581 (setq level (outline-level))
20582 (forward-char 1)
20583 (if (and (re-search-forward re nil t) (> (outline-level) level))
20584 (progn (goto-char (match-beginning 0)) t)
20585 (goto-char pos) nil))))
20587 (defun org-show-hidden-entry ()
20588 "Show an entry where even the heading is hidden."
20589 (save-excursion
20590 (org-show-entry)))
20592 (defun org-flag-heading (flag &optional entry)
20593 "Flag the current heading. FLAG non-nil means make invisible.
20594 When ENTRY is non-nil, show the entire entry."
20595 (save-excursion
20596 (org-back-to-heading t)
20597 ;; Check if we should show the entire entry
20598 (if entry
20599 (progn
20600 (org-show-entry)
20601 (save-excursion
20602 (and (outline-next-heading)
20603 (org-flag-heading nil))))
20604 (outline-flag-region (max (point-min) (1- (point)))
20605 (save-excursion (outline-end-of-heading) (point))
20606 flag))))
20608 (defun org-get-next-sibling ()
20609 "Move to next heading of the same level, and return point.
20610 If there is no such heading, return nil.
20611 This is like outline-next-sibling, but invisible headings are ok."
20612 (let ((level (funcall outline-level)))
20613 (outline-next-heading)
20614 (while (and (not (eobp)) (> (funcall outline-level) level))
20615 (outline-next-heading))
20616 (if (or (eobp) (< (funcall outline-level) level))
20618 (point))))
20620 (defun org-get-last-sibling ()
20621 "Move to previous heading of the same level, and return point.
20622 If there is no such heading, return nil."
20623 (let ((opoint (point))
20624 (level (funcall outline-level)))
20625 (outline-previous-heading)
20626 (when (and (/= (point) opoint) (outline-on-heading-p t))
20627 (while (and (> (funcall outline-level) level)
20628 (not (bobp)))
20629 (outline-previous-heading))
20630 (if (< (funcall outline-level) level)
20632 (point)))))
20634 (defun org-end-of-subtree (&optional invisible-OK to-heading)
20635 ;; This contains an exact copy of the original function, but it uses
20636 ;; `org-back-to-heading', to make it work also in invisible
20637 ;; trees. And is uses an invisible-OK argument.
20638 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
20639 ;; Furthermore, when used inside Org, finding the end of a large subtree
20640 ;; with many children and grandchildren etc, this can be much faster
20641 ;; than the outline version.
20642 (org-back-to-heading invisible-OK)
20643 (let ((first t)
20644 (level (funcall outline-level)))
20645 (if (and (eq major-mode 'org-mode) (< level 1000))
20646 ;; A true heading (not a plain list item), in Org-mode
20647 ;; This means we can easily find the end by looking
20648 ;; only for the right number of stars. Using a regexp to do
20649 ;; this is so much faster than using a Lisp loop.
20650 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
20651 (forward-char 1)
20652 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
20653 ;; something else, do it the slow way
20654 (while (and (not (eobp))
20655 (or first (> (funcall outline-level) level)))
20656 (setq first nil)
20657 (outline-next-heading)))
20658 (unless to-heading
20659 (if (memq (preceding-char) '(?\n ?\^M))
20660 (progn
20661 ;; Go to end of line before heading
20662 (forward-char -1)
20663 (if (memq (preceding-char) '(?\n ?\^M))
20664 ;; leave blank line before heading
20665 (forward-char -1))))))
20666 (point))
20668 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
20669 "Use Org version in org-mode, for dramatic speed-up."
20670 (if (eq major-mode 'org-mode)
20671 (progn
20672 (org-end-of-subtree nil t)
20673 (unless (eobp) (backward-char 1)))
20674 ad-do-it))
20676 (defun org-end-of-meta-data-and-drawers ()
20677 "Jump to the first text after meta data and drawers in the current entry.
20678 This will move over empty lines, lines with planning time stamps,
20679 clocking lines, and drawers."
20680 (org-back-to-heading t)
20681 (let ((end (save-excursion (outline-next-heading) (point)))
20682 (re (concat "\\(" org-drawer-regexp "\\)"
20683 "\\|" "[ \t]*" org-keyword-time-regexp)))
20684 (forward-line 1)
20685 (while (re-search-forward re end t)
20686 (if (not (match-end 1))
20687 ;; empty or planning line
20688 (forward-line 1)
20689 ;; a drawer, find the end
20690 (re-search-forward "^[ \t]*:END:" end 'move)
20691 (forward-line 1)))
20692 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
20693 (point)))
20695 (defun org-forward-same-level (arg &optional invisible-ok)
20696 "Move forward to the arg'th subheading at same level as this one.
20697 Stop at the first and last subheadings of a superior heading.
20698 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
20699 it wil also look at invisible ones."
20700 (interactive "p")
20701 (org-back-to-heading invisible-ok)
20702 (org-on-heading-p)
20703 (let* ((level (- (match-end 0) (match-beginning 0) 1))
20704 (re (format "^\\*\\{1,%d\\} " level))
20706 (forward-char 1)
20707 (while (> arg 0)
20708 (while (and (re-search-forward re nil 'move)
20709 (setq l (- (match-end 0) (match-beginning 0) 1))
20710 (= l level)
20711 (not invisible-ok)
20712 (progn (backward-char 1) (outline-invisible-p)))
20713 (if (< l level) (setq arg 1)))
20714 (setq arg (1- arg)))
20715 (beginning-of-line 1)))
20717 (defun org-backward-same-level (arg &optional invisible-ok)
20718 "Move backward to the arg'th subheading at same level as this one.
20719 Stop at the first and last subheadings of a superior heading."
20720 (interactive "p")
20721 (org-back-to-heading)
20722 (org-on-heading-p)
20723 (let* ((level (- (match-end 0) (match-beginning 0) 1))
20724 (re (format "^\\*\\{1,%d\\} " level))
20726 (while (> arg 0)
20727 (while (and (re-search-backward re nil 'move)
20728 (setq l (- (match-end 0) (match-beginning 0) 1))
20729 (= l level)
20730 (not invisible-ok)
20731 (outline-invisible-p))
20732 (if (< l level) (setq arg 1)))
20733 (setq arg (1- arg)))))
20735 (defun org-show-subtree ()
20736 "Show everything after this heading at deeper levels."
20737 (outline-flag-region
20738 (point)
20739 (save-excursion
20740 (org-end-of-subtree t t))
20741 nil))
20743 (defun org-show-entry ()
20744 "Show the body directly following this heading.
20745 Show the heading too, if it is currently invisible."
20746 (interactive)
20747 (save-excursion
20748 (condition-case nil
20749 (progn
20750 (org-back-to-heading t)
20751 (outline-flag-region
20752 (max (point-min) (1- (point)))
20753 (save-excursion
20754 (if (re-search-forward
20755 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
20756 (match-beginning 1)
20757 (point-max)))
20758 nil)
20759 (org-cycle-hide-drawers 'children))
20760 (error nil))))
20762 (defun org-make-options-regexp (kwds &optional extra)
20763 "Make a regular expression for keyword lines."
20764 (concat
20766 "#?[ \t]*\\+\\("
20767 (mapconcat 'regexp-quote kwds "\\|")
20768 (if extra (concat "\\|" extra))
20769 "\\):[ \t]*"
20770 "\\(.*\\)"))
20772 ;; Make isearch reveal the necessary context
20773 (defun org-isearch-end ()
20774 "Reveal context after isearch exits."
20775 (when isearch-success ; only if search was successful
20776 (if (featurep 'xemacs)
20777 ;; Under XEmacs, the hook is run in the correct place,
20778 ;; we directly show the context.
20779 (org-show-context 'isearch)
20780 ;; In Emacs the hook runs *before* restoring the overlays.
20781 ;; So we have to use a one-time post-command-hook to do this.
20782 ;; (Emacs 22 has a special variable, see function `org-mode')
20783 (unless (and (boundp 'isearch-mode-end-hook-quit)
20784 isearch-mode-end-hook-quit)
20785 ;; Only when the isearch was not quitted.
20786 (org-add-hook 'post-command-hook 'org-isearch-post-command
20787 'append 'local)))))
20789 (defun org-isearch-post-command ()
20790 "Remove self from hook, and show context."
20791 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
20792 (org-show-context 'isearch))
20795 ;;;; Integration with and fixes for other packages
20797 ;;; Imenu support
20799 (defvar org-imenu-markers nil
20800 "All markers currently used by Imenu.")
20801 (make-variable-buffer-local 'org-imenu-markers)
20803 (defun org-imenu-new-marker (&optional pos)
20804 "Return a new marker for use by Imenu, and remember the marker."
20805 (let ((m (make-marker)))
20806 (move-marker m (or pos (point)))
20807 (push m org-imenu-markers)
20810 (defun org-imenu-get-tree ()
20811 "Produce the index for Imenu."
20812 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
20813 (setq org-imenu-markers nil)
20814 (let* ((n org-imenu-depth)
20815 (re (concat "^" (org-get-limited-outline-regexp)))
20816 (subs (make-vector (1+ n) nil))
20817 (last-level 0)
20818 m level head)
20819 (save-excursion
20820 (save-restriction
20821 (widen)
20822 (goto-char (point-max))
20823 (while (re-search-backward re nil t)
20824 (setq level (org-reduced-level (funcall outline-level)))
20825 (when (<= level n)
20826 (looking-at org-complex-heading-regexp)
20827 (setq head (org-link-display-format
20828 (org-match-string-no-properties 4))
20829 m (org-imenu-new-marker))
20830 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
20831 (if (>= level last-level)
20832 (push (cons head m) (aref subs level))
20833 (push (cons head (aref subs (1+ level))) (aref subs level))
20834 (loop for i from (1+ level) to n do (aset subs i nil)))
20835 (setq last-level level)))))
20836 (aref subs 1)))
20838 (eval-after-load "imenu"
20839 '(progn
20840 (add-hook 'imenu-after-jump-hook
20841 (lambda ()
20842 (if (eq major-mode 'org-mode)
20843 (org-show-context 'org-goto))))))
20845 (defun org-link-display-format (link)
20846 "Replace a link with either the description, or the link target
20847 if no description is present"
20848 (save-match-data
20849 (if (string-match org-bracket-link-analytic-regexp link)
20850 (replace-match (if (match-end 5)
20851 (match-string 5 link)
20852 (concat (match-string 1 link)
20853 (match-string 3 link)))
20854 nil t link)
20855 link)))
20857 (defun org-toggle-link-display ()
20858 "Toggle the literal or descriptive display of links."
20859 (interactive)
20860 (if org-descriptive-links
20861 (progn (org-remove-from-invisibility-spec '(org-link))
20862 (org-restart-font-lock)
20863 (setq org-descriptive-links nil))
20864 (progn (add-to-invisibility-spec '(org-link))
20865 (org-restart-font-lock)
20866 (setq org-descriptive-links t))))
20868 ;; Speedbar support
20870 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
20871 "Overlay marking the agenda restriction line in speedbar.")
20872 (overlay-put org-speedbar-restriction-lock-overlay
20873 'face 'org-agenda-restriction-lock)
20874 (overlay-put org-speedbar-restriction-lock-overlay
20875 'help-echo "Agendas are currently limited to this item.")
20876 (org-detach-overlay org-speedbar-restriction-lock-overlay)
20878 (defun org-speedbar-set-agenda-restriction ()
20879 "Restrict future agenda commands to the location at point in speedbar.
20880 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
20881 (interactive)
20882 (require 'org-agenda)
20883 (let (p m tp np dir txt)
20884 (cond
20885 ((setq p (text-property-any (point-at-bol) (point-at-eol)
20886 'org-imenu t))
20887 (setq m (get-text-property p 'org-imenu-marker))
20888 (with-current-buffer (marker-buffer m)
20889 (goto-char m)
20890 (org-agenda-set-restriction-lock 'subtree)))
20891 ((setq p (text-property-any (point-at-bol) (point-at-eol)
20892 'speedbar-function 'speedbar-find-file))
20893 (setq tp (previous-single-property-change
20894 (1+ p) 'speedbar-function)
20895 np (next-single-property-change
20896 tp 'speedbar-function)
20897 dir (speedbar-line-directory)
20898 txt (buffer-substring-no-properties (or tp (point-min))
20899 (or np (point-max))))
20900 (with-current-buffer (find-file-noselect
20901 (let ((default-directory dir))
20902 (expand-file-name txt)))
20903 (unless (eq major-mode 'org-mode)
20904 (error "Cannot restrict to non-Org-mode file"))
20905 (org-agenda-set-restriction-lock 'file)))
20906 (t (error "Don't know how to restrict Org-mode's agenda")))
20907 (move-overlay org-speedbar-restriction-lock-overlay
20908 (point-at-bol) (point-at-eol))
20909 (setq current-prefix-arg nil)
20910 (org-agenda-maybe-redo)))
20912 (eval-after-load "speedbar"
20913 '(progn
20914 (speedbar-add-supported-extension ".org")
20915 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
20916 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
20917 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
20918 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
20919 (add-hook 'speedbar-visiting-tag-hook
20920 (lambda () (and (eq major-mode 'org-mode) (org-show-context 'org-goto))))))
20922 ;;; Fixes and Hacks for problems with other packages
20924 ;; Make flyspell not check words in links, to not mess up our keymap
20925 (defun org-mode-flyspell-verify ()
20926 "Don't let flyspell put overlays at active buttons, or on
20927 {todo,all-time,additional-option-like}-keywords."
20928 (let ((pos (max (1- (point)) (point-min)))
20929 (word (thing-at-point 'word)))
20930 (and (not (get-text-property pos 'keymap))
20931 (not (get-text-property pos 'org-no-flyspell))
20932 (not (member word org-todo-keywords-1))
20933 (not (member word org-all-time-keywords))
20934 (not (member word org-additional-option-like-keywords)))))
20936 (defun org-remove-flyspell-overlays-in (beg end)
20937 "Remove flyspell overlays in region."
20938 (and (org-bound-and-true-p flyspell-mode)
20939 (fboundp 'flyspell-delete-region-overlays)
20940 (flyspell-delete-region-overlays beg end))
20941 (add-text-properties beg end '(org-no-flyspell t)))
20943 ;; Make `bookmark-jump' shows the jump location if it was hidden.
20944 (eval-after-load "bookmark"
20945 '(if (boundp 'bookmark-after-jump-hook)
20946 ;; We can use the hook
20947 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
20948 ;; Hook not available, use advice
20949 (defadvice bookmark-jump (after org-make-visible activate)
20950 "Make the position visible."
20951 (org-bookmark-jump-unhide))))
20953 ;; Make sure saveplace shows the location if it was hidden
20954 (eval-after-load "saveplace"
20955 '(defadvice save-place-find-file-hook (after org-make-visible activate)
20956 "Make the position visible."
20957 (org-bookmark-jump-unhide)))
20959 ;; Make sure ecb shows the location if it was hidden
20960 (eval-after-load "ecb"
20961 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
20962 "Make hierarchy visible when jumping into location from ECB tree buffer."
20963 (if (eq major-mode 'org-mode)
20964 (org-show-context))))
20966 (defun org-bookmark-jump-unhide ()
20967 "Unhide the current position, to show the bookmark location."
20968 (and (eq major-mode 'org-mode)
20969 (or (outline-invisible-p)
20970 (save-excursion (goto-char (max (point-min) (1- (point))))
20971 (outline-invisible-p)))
20972 (org-show-context 'bookmark-jump)))
20974 ;; Make session.el ignore our circular variable
20975 (eval-after-load "session"
20976 '(add-to-list 'session-globals-exclude 'org-mark-ring))
20978 ;;;; Experimental code
20980 (defun org-closed-in-range ()
20981 "Sparse tree of items closed in a certain time range.
20982 Still experimental, may disappear in the future."
20983 (interactive)
20984 ;; Get the time interval from the user.
20985 (let* ((time1 (org-float-time
20986 (org-read-date nil 'to-time nil "Starting date: ")))
20987 (time2 (org-float-time
20988 (org-read-date nil 'to-time nil "End date:")))
20989 ;; callback function
20990 (callback (lambda ()
20991 (let ((time
20992 (org-float-time
20993 (apply 'encode-time
20994 (org-parse-time-string
20995 (match-string 1))))))
20996 ;; check if time in interval
20997 (and (>= time time1) (<= time time2))))))
20998 ;; make tree, check each match with the callback
20999 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
21001 ;;;; Finish up
21003 (provide 'org)
21005 (run-hooks 'org-load-hook)
21007 ;;; org.el ends here