Globalize some variables to make them available in buffers not in Org mode
[org-mode.git] / lisp / org.el
blobc3c7bdff94d97f2aeaad7310978f7474c41d8bb4
1 ;;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004-2011 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Maintainer: Bastien Guerry <bzg at gnu dot org>
7 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; Homepage: http://orgmode.org
9 ;; Version: 7.7
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum))
77 (require 'calendar)
79 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
80 (when (fboundp 'defvaralias)
81 (unless (boundp 'calendar-view-holidays-initially-flag)
82 (defvaralias 'calendar-view-holidays-initially-flag
83 'view-calendar-holidays-initially))
84 (unless (boundp 'calendar-view-diary-initially-flag)
85 (defvaralias 'calendar-view-diary-initially-flag
86 'view-diary-entries-initially))
87 (unless (boundp 'diary-fancy-buffer)
88 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
90 (require 'outline) (require 'noutline)
91 ;; Other stuff we need.
92 (require 'time-date)
93 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
94 (require 'easymenu)
95 (require 'overlay)
97 (require 'org-macs)
98 (require 'org-entities)
99 (require 'org-compat)
100 (require 'org-faces)
101 (require 'org-list)
102 (require 'org-pcomplete)
103 (require 'org-src)
104 (require 'org-footnote)
106 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
107 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
108 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
109 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
110 (declare-function org-at-clock-log-p "org-clock" ())
111 (declare-function org-clock-timestamps-up "org-clock" ())
112 (declare-function org-clock-timestamps-down "org-clock" ())
114 ;; babel
115 (require 'ob)
116 (require 'ob-table)
117 (require 'ob-lob)
118 (require 'ob-ref)
119 (require 'ob-tangle)
120 (require 'ob-comint)
121 (require 'ob-keys)
123 ;; load languages based on value of `org-babel-load-languages'
124 (defvar org-babel-load-languages)
125 ;;;###autoload
126 (defun org-babel-do-load-languages (sym value)
127 "Load the languages defined in `org-babel-load-languages'."
128 (set-default sym value)
129 (mapc (lambda (pair)
130 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
131 (if active
132 (progn
133 (require (intern (concat "ob-" lang))))
134 (progn
135 (funcall 'fmakunbound
136 (intern (concat "org-babel-execute:" lang)))
137 (funcall 'fmakunbound
138 (intern (concat "org-babel-expand-body:" lang)))))))
139 org-babel-load-languages))
141 (defcustom org-babel-load-languages '((emacs-lisp . t))
142 "Languages which can be evaluated in Org-mode buffers.
143 This list can be used to load support for any of the languages
144 below, note that each language will depend on a different set of
145 system executables and/or Emacs modes. When a language is
146 \"loaded\", then code blocks in that language can be evaluated
147 with `org-babel-execute-src-block' bound by default to C-c
148 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
149 be set to remove code block evaluation from the C-c C-c
150 keybinding. By default only Emacs Lisp (which has no
151 requirements) is loaded."
152 :group 'org-babel
153 :set 'org-babel-do-load-languages
154 :type '(alist :tag "Babel Languages"
155 :key-type
156 (choice
157 (const :tag "Awk" awk)
158 (const :tag "C" C)
159 (const :tag "R" R)
160 (const :tag "Asymptote" asymptote)
161 (const :tag "Calc" calc)
162 (const :tag "Clojure" clojure)
163 (const :tag "CSS" css)
164 (const :tag "Ditaa" ditaa)
165 (const :tag "Dot" dot)
166 (const :tag "Emacs Lisp" emacs-lisp)
167 (const :tag "Gnuplot" gnuplot)
168 (const :tag "Haskell" haskell)
169 (const :tag "Java" java)
170 (const :tag "Javascript" js)
171 (const :tag "Latex" latex)
172 (const :tag "Ledger" ledger)
173 (const :tag "Lilypond" lilypond)
174 (const :tag "Maxima" maxima)
175 (const :tag "Matlab" matlab)
176 (const :tag "Mscgen" mscgen)
177 (const :tag "Ocaml" ocaml)
178 (const :tag "Octave" octave)
179 (const :tag "Org" org)
180 (const :tag "Perl" perl)
181 (const :tag "PlantUML" plantuml)
182 (const :tag "Python" python)
183 (const :tag "Ruby" ruby)
184 (const :tag "Sass" sass)
185 (const :tag "Scheme" scheme)
186 (const :tag "Screen" screen)
187 (const :tag "Shell Script" sh)
188 (const :tag "Shen" shen)
189 (const :tag "Sql" sql)
190 (const :tag "Sqlite" sqlite))
191 :value-type (boolean :tag "Activate" :value t)))
193 ;;;; Customization variables
194 (defcustom org-clone-delete-id nil
195 "Remove ID property of clones of a subtree.
196 When non-nil, clones of a subtree don't inherit the ID property.
197 Otherwise they inherit the ID property with a new unique
198 identifier."
199 :type 'boolean
200 :group 'org-id)
202 ;;; Version
204 (defconst org-version "7.7"
205 "The version number of the file org.el.")
207 (defun org-version (&optional here)
208 "Show the org-mode version in the echo area.
209 With prefix arg HERE, insert it at point."
210 (interactive "P")
211 (let* ((origin default-directory)
212 (version org-version)
213 (git-version)
214 (dir (concat (file-name-directory (locate-library "org")) "../" )))
215 (when (and (file-exists-p (expand-file-name ".git" dir))
216 (executable-find "git"))
217 (unwind-protect
218 (progn
219 (cd dir)
220 (when (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
221 (with-current-buffer "*Shell Command Output*"
222 (goto-char (point-min))
223 (setq git-version (buffer-substring (point) (point-at-eol))))
224 (subst-char-in-string ?- ?. git-version t)
225 (when (string-match "\\S-"
226 (shell-command-to-string
227 "git diff-index --name-only HEAD --"))
228 (setq git-version (concat git-version ".dirty")))
229 (setq version (concat version " (" git-version ")"))))
230 (cd origin)))
231 (setq version (format "Org-mode version %s" version))
232 (if here (insert version))
233 (message version)))
235 ;;; Compatibility constants
237 ;;; The custom variables
239 (defgroup org nil
240 "Outline-based notes management and organizer."
241 :tag "Org"
242 :group 'outlines
243 :group 'calendar)
245 (defcustom org-mode-hook nil
246 "Mode hook for Org-mode, run after the mode was turned on."
247 :group 'org
248 :type 'hook)
250 (defcustom org-load-hook nil
251 "Hook that is run after org.el has been loaded."
252 :group 'org
253 :type 'hook)
255 (defcustom org-log-buffer-setup-hook nil
256 "Hook that is run after an Org log buffer is created."
257 :group 'org
258 :type 'hook)
260 (defvar org-modules) ; defined below
261 (defvar org-modules-loaded nil
262 "Have the modules been loaded already?")
264 (defun org-load-modules-maybe (&optional force)
265 "Load all extensions listed in `org-modules'."
266 (when (or force (not org-modules-loaded))
267 (mapc (lambda (ext)
268 (condition-case nil (require ext)
269 (error (message "Problems while trying to load feature `%s'" ext))))
270 org-modules)
271 (setq org-modules-loaded t)))
273 (defun org-set-modules (var value)
274 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
275 (set var value)
276 (when (featurep 'org)
277 (org-load-modules-maybe 'force)))
279 (when (org-bound-and-true-p org-modules)
280 (let ((a (member 'org-infojs org-modules)))
281 (and a (setcar a 'org-jsinfo))))
283 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
284 "Modules that should always be loaded together with org.el.
285 If a description starts with <C>, the file is not part of Emacs
286 and loading it will require that you have downloaded and properly installed
287 the org-mode distribution.
289 You can also use this system to load external packages (i.e. neither Org
290 core modules, nor modules from the CONTRIB directory). Just add symbols
291 to the end of the list. If the package is called org-xyz.el, then you need
292 to add the symbol `xyz', and the package must have a call to
294 (provide 'org-xyz)"
295 :group 'org
296 :set 'org-set-modules
297 :type
298 '(set :greedy t
299 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
300 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
301 (const :tag " crypt: Encryption of subtrees" org-crypt)
302 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
303 (const :tag " docview: Links to doc-view buffers" org-docview)
304 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
305 (const :tag " id: Global IDs for identifying entries" org-id)
306 (const :tag " info: Links to Info nodes" org-info)
307 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
308 (const :tag " habit: Track your consistency with habits" org-habit)
309 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
310 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
311 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
312 (const :tag " mew Links to Mew folders/messages" org-mew)
313 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
314 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
315 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
316 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
317 (const :tag " vm: Links to VM folders/messages" org-vm)
318 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
319 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
320 (const :tag " mouse: Additional mouse support" org-mouse)
321 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
323 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
324 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
325 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
326 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
327 (const :tag "C collector: Collect properties into tables" org-collector)
328 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
329 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
330 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
331 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
332 (const :tag "C eval: Include command output as text" org-eval)
333 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
334 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
335 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
336 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
337 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
339 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
341 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
342 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
343 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
344 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
345 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
346 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
347 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
348 (const :tag "C mtags: Support for muse-like tags" org-mtags)
349 (const :tag "C odt: OpenDocumentText exporter for Org-mode" org-odt)
350 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
351 (const :tag "C registry: A registry for Org-mode links" org-registry)
352 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
353 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
354 (const :tag "C secretary: Team management with org-mode" org-secretary)
355 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
356 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
357 (const :tag "C track: Keep up with Org-mode development" org-track)
358 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
359 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
360 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
362 (defcustom org-support-shift-select nil
363 "Non-nil means make shift-cursor commands select text when possible.
365 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
366 start selecting a region, or enlarge regions started in this way.
367 In Org-mode, in special contexts, these same keys are used for
368 other purposes, important enough to compete with shift selection.
369 Org tries to balance these needs by supporting `shift-select-mode'
370 outside these special contexts, under control of this variable.
372 The default of this variable is nil, to avoid confusing behavior. Shifted
373 cursor keys will then execute Org commands in the following contexts:
374 - on a headline, changing TODO state (left/right) and priority (up/down)
375 - on a time stamp, changing the time
376 - in a plain list item, changing the bullet type
377 - in a property definition line, switching between allowed values
378 - in the BEGIN line of a clock table (changing the time block).
379 Outside these contexts, the commands will throw an error.
381 When this variable is t and the cursor is not in a special
382 context, Org-mode will support shift-selection for making and
383 enlarging regions. To make this more effective, the bullet
384 cycling will no longer happen anywhere in an item line, but only
385 if the cursor is exactly on the bullet.
387 If you set this variable to the symbol `always', then the keys
388 will not be special in headlines, property lines, and item lines,
389 to make shift selection work there as well. If this is what you
390 want, you can use the following alternative commands: `C-c C-t'
391 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
392 can be used to switch TODO sets, `C-c -' to cycle item bullet
393 types, and properties can be edited by hand or in column view.
395 However, when the cursor is on a timestamp, shift-cursor commands
396 will still edit the time stamp - this is just too good to give up.
398 XEmacs user should have this variable set to nil, because
399 `shift-select-mode' is in Emacs 23 or later only."
400 :group 'org
401 :type '(choice
402 (const :tag "Never" nil)
403 (const :tag "When outside special context" t)
404 (const :tag "Everywhere except timestamps" always)))
406 (defcustom org-loop-over-headlines-in-active-region nil
407 "Shall some commands act upon headlines in the active region?
409 When set to `t', some commands will be performed in all headlines
410 within the active region.
412 When set to a string, those commands will be performed on the
413 matching headlines within the active region. Such string must be
414 a tags/property/todo match as it is used in the agenda tags view.
416 The list of commands is:
417 - `org-schedule'
418 - `org-deadline'"
419 :type '(choice (const :tag "Don't loop" nil)
420 (const :tag "All headlines in active region" t)
421 (string :tag "Tags/Property/Todo matcher"))
422 :group 'org-todo
423 :group 'org-archive)
425 (defgroup org-startup nil
426 "Options concerning startup of Org-mode."
427 :tag "Org Startup"
428 :group 'org)
430 (defcustom org-startup-folded t
431 "Non-nil means entering Org-mode will switch to OVERVIEW.
432 This can also be configured on a per-file basis by adding one of
433 the following lines anywhere in the buffer:
435 #+STARTUP: fold (or `overview', this is equivalent)
436 #+STARTUP: nofold (or `showall', this is equivalent)
437 #+STARTUP: content
438 #+STARTUP: showeverything"
439 :group 'org-startup
440 :type '(choice
441 (const :tag "nofold: show all" nil)
442 (const :tag "fold: overview" t)
443 (const :tag "content: all headlines" content)
444 (const :tag "show everything, even drawers" showeverything)))
446 (defcustom org-startup-truncated t
447 "Non-nil means entering Org-mode will set `truncate-lines'.
448 This is useful since some lines containing links can be very long and
449 uninteresting. Also tables look terrible when wrapped."
450 :group 'org-startup
451 :type 'boolean)
453 (defcustom org-startup-indented nil
454 "Non-nil means turn on `org-indent-mode' on startup.
455 This can also be configured on a per-file basis by adding one of
456 the following lines anywhere in the buffer:
458 #+STARTUP: indent
459 #+STARTUP: noindent"
460 :group 'org-structure
461 :type '(choice
462 (const :tag "Not" nil)
463 (const :tag "Globally (slow on startup in large files)" t)))
465 (defcustom org-use-sub-superscripts t
466 "Non-nil means interpret \"_\" and \"^\" for export.
467 When this option is turned on, you can use TeX-like syntax for sub- and
468 superscripts. Several characters after \"_\" or \"^\" will be
469 considered as a single item - so grouping with {} is normally not
470 needed. For example, the following things will be parsed as single
471 sub- or superscripts.
473 10^24 or 10^tau several digits will be considered 1 item.
474 10^-12 or 10^-tau a leading sign with digits or a word
475 x^2-y^3 will be read as x^2 - y^3, because items are
476 terminated by almost any nonword/nondigit char.
477 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
479 Still, ambiguity is possible - so when in doubt use {} to enclose the
480 sub/superscript. If you set this variable to the symbol `{}',
481 the braces are *required* in order to trigger interpretations as
482 sub/superscript. This can be helpful in documents that need \"_\"
483 frequently in plain text.
485 Not all export backends support this, but HTML does.
487 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
488 :group 'org-startup
489 :group 'org-export-translation
490 :type '(choice
491 (const :tag "Always interpret" t)
492 (const :tag "Only with braces" {})
493 (const :tag "Never interpret" nil)))
495 (if (fboundp 'defvaralias)
496 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
499 (defcustom org-startup-with-beamer-mode nil
500 "Non-nil means turn on `org-beamer-mode' on startup.
501 This can also be configured on a per-file basis by adding one of
502 the following lines anywhere in the buffer:
504 #+STARTUP: beamer"
505 :group 'org-startup
506 :type 'boolean)
508 (defcustom org-startup-align-all-tables nil
509 "Non-nil means align all tables when visiting a file.
510 This is useful when the column width in tables is forced with <N> cookies
511 in table fields. Such tables will look correct only after the first re-align.
512 This can also be configured on a per-file basis by adding one of
513 the following lines anywhere in the buffer:
514 #+STARTUP: align
515 #+STARTUP: noalign"
516 :group 'org-startup
517 :type 'boolean)
519 (defcustom org-startup-with-inline-images nil
520 "Non-nil means show inline images when loading a new Org file.
521 This can also be configured on a per-file basis by adding one of
522 the following lines anywhere in the buffer:
523 #+STARTUP: inlineimages
524 #+STARTUP: noinlineimages"
525 :group 'org-startup
526 :type 'boolean)
528 (defcustom org-insert-mode-line-in-empty-file nil
529 "Non-nil means insert the first line setting Org-mode in empty files.
530 When the function `org-mode' is called interactively in an empty file, this
531 normally means that the file name does not automatically trigger Org-mode.
532 To ensure that the file will always be in Org-mode in the future, a
533 line enforcing Org-mode will be inserted into the buffer, if this option
534 has been set."
535 :group 'org-startup
536 :type 'boolean)
538 (defcustom org-replace-disputed-keys nil
539 "Non-nil means use alternative key bindings for some keys.
540 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
541 These keys are also used by other packages like shift-selection-mode'
542 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
543 If you want to use Org-mode together with one of these other modes,
544 or more generally if you would like to move some Org-mode commands to
545 other keys, set this variable and configure the keys with the variable
546 `org-disputed-keys'.
548 This option is only relevant at load-time of Org-mode, and must be set
549 *before* org.el is loaded. Changing it requires a restart of Emacs to
550 become effective."
551 :group 'org-startup
552 :type 'boolean)
554 (defcustom org-use-extra-keys nil
555 "Non-nil means use extra key sequence definitions for certain commands.
556 This happens automatically if you run XEmacs or if `window-system'
557 is nil. This variable lets you do the same manually. You must
558 set it before loading org.
560 Example: on Carbon Emacs 22 running graphically, with an external
561 keyboard on a Powerbook, the default way of setting M-left might
562 not work for either Alt or ESC. Setting this variable will make
563 it work for ESC."
564 :group 'org-startup
565 :type 'boolean)
567 (if (fboundp 'defvaralias)
568 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
570 (defcustom org-disputed-keys
571 '(([(shift up)] . [(meta p)])
572 ([(shift down)] . [(meta n)])
573 ([(shift left)] . [(meta -)])
574 ([(shift right)] . [(meta +)])
575 ([(control shift right)] . [(meta shift +)])
576 ([(control shift left)] . [(meta shift -)]))
577 "Keys for which Org-mode and other modes compete.
578 This is an alist, cars are the default keys, second element specifies
579 the alternative to use when `org-replace-disputed-keys' is t.
581 Keys can be specified in any syntax supported by `define-key'.
582 The value of this option takes effect only at Org-mode's startup,
583 therefore you'll have to restart Emacs to apply it after changing."
584 :group 'org-startup
585 :type 'alist)
587 (defun org-key (key)
588 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
589 Or return the original if not disputed.
590 Also apply the translations defined in `org-xemacs-key-equivalents'."
591 (when org-replace-disputed-keys
592 (let* ((nkey (key-description key))
593 (x (org-find-if (lambda (x)
594 (equal (key-description (car x)) nkey))
595 org-disputed-keys)))
596 (setq key (if x (cdr x) key))))
597 (when (featurep 'xemacs)
598 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
599 key)
601 (defun org-find-if (predicate seq)
602 (catch 'exit
603 (while seq
604 (if (funcall predicate (car seq))
605 (throw 'exit (car seq))
606 (pop seq)))))
608 (defun org-defkey (keymap key def)
609 "Define a key, possibly translated, as returned by `org-key'."
610 (define-key keymap (org-key key) def))
612 (defcustom org-ellipsis nil
613 "The ellipsis to use in the Org-mode outline.
614 When nil, just use the standard three dots. When a string, use that instead,
615 When a face, use the standard 3 dots, but with the specified face.
616 The change affects only Org-mode (which will then use its own display table).
617 Changing this requires executing `M-x org-mode' in a buffer to become
618 effective."
619 :group 'org-startup
620 :type '(choice (const :tag "Default" nil)
621 (face :tag "Face" :value org-warning)
622 (string :tag "String" :value "...#")))
624 (defvar org-display-table nil
625 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
627 (defgroup org-keywords nil
628 "Keywords in Org-mode."
629 :tag "Org Keywords"
630 :group 'org)
632 (defcustom org-deadline-string "DEADLINE:"
633 "String to mark deadline entries.
634 A deadline is this string, followed by a time stamp. Should be a word,
635 terminated by a colon. You can insert a schedule keyword and
636 a timestamp with \\[org-deadline].
637 Changes become only effective after restarting Emacs."
638 :group 'org-keywords
639 :type 'string)
641 (defcustom org-scheduled-string "SCHEDULED:"
642 "String to mark scheduled TODO entries.
643 A schedule is this string, followed by a time stamp. Should be a word,
644 terminated by a colon. You can insert a schedule keyword and
645 a timestamp with \\[org-schedule].
646 Changes become only effective after restarting Emacs."
647 :group 'org-keywords
648 :type 'string)
650 (defcustom org-closed-string "CLOSED:"
651 "String used as the prefix for timestamps logging closing a TODO entry."
652 :group 'org-keywords
653 :type 'string)
655 (defcustom org-clock-string "CLOCK:"
656 "String used as prefix for timestamps clocking work hours on an item."
657 :group 'org-keywords
658 :type 'string)
660 (defcustom org-comment-string "COMMENT"
661 "Entries starting with this keyword will never be exported.
662 An entry can be toggled between COMMENT and normal with
663 \\[org-toggle-comment].
664 Changes become only effective after restarting Emacs."
665 :group 'org-keywords
666 :type 'string)
668 (defcustom org-quote-string "QUOTE"
669 "Entries starting with this keyword will be exported in fixed-width font.
670 Quoting applies only to the text in the entry following the headline, and does
671 not extend beyond the next headline, even if that is lower level.
672 An entry can be toggled between QUOTE and normal with
673 \\[org-toggle-fixed-width-section]."
674 :group 'org-keywords
675 :type 'string)
677 (defconst org-repeat-re
678 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
679 "Regular expression for specifying repeated events.
680 After a match, group 1 contains the repeat expression.")
682 (defgroup org-structure nil
683 "Options concerning the general structure of Org-mode files."
684 :tag "Org Structure"
685 :group 'org)
687 (defgroup org-reveal-location nil
688 "Options about how to make context of a location visible."
689 :tag "Org Reveal Location"
690 :group 'org-structure)
692 (defconst org-context-choice
693 '(choice
694 (const :tag "Always" t)
695 (const :tag "Never" nil)
696 (repeat :greedy t :tag "Individual contexts"
697 (cons
698 (choice :tag "Context"
699 (const agenda)
700 (const org-goto)
701 (const occur-tree)
702 (const tags-tree)
703 (const link-search)
704 (const mark-goto)
705 (const bookmark-jump)
706 (const isearch)
707 (const default))
708 (boolean))))
709 "Contexts for the reveal options.")
711 (defcustom org-show-hierarchy-above '((default . t))
712 "Non-nil means show full hierarchy when revealing a location.
713 Org-mode often shows locations in an org-mode file which might have
714 been invisible before. When this is set, the hierarchy of headings
715 above the exposed location is shown.
716 Turning this off for example for sparse trees makes them very compact.
717 Instead of t, this can also be an alist specifying this option for different
718 contexts. Valid contexts are
719 agenda when exposing an entry from the agenda
720 org-goto when using the command `org-goto' on key C-c C-j
721 occur-tree when using the command `org-occur' on key C-c /
722 tags-tree when constructing a sparse tree based on tags matches
723 link-search when exposing search matches associated with a link
724 mark-goto when exposing the jump goal of a mark
725 bookmark-jump when exposing a bookmark location
726 isearch when exiting from an incremental search
727 default default for all contexts not set explicitly"
728 :group 'org-reveal-location
729 :type org-context-choice)
731 (defcustom org-show-following-heading '((default . nil))
732 "Non-nil means show following heading when revealing a location.
733 Org-mode often shows locations in an org-mode file which might have
734 been invisible before. When this is set, the heading following the
735 match is shown.
736 Turning this off for example for sparse trees makes them very compact,
737 but makes it harder to edit the location of the match. In such a case,
738 use the command \\[org-reveal] to show more context.
739 Instead of t, this can also be an alist specifying this option for different
740 contexts. See `org-show-hierarchy-above' for valid contexts."
741 :group 'org-reveal-location
742 :type org-context-choice)
744 (defcustom org-show-siblings '((default . nil) (isearch t))
745 "Non-nil means show all sibling heading when revealing a location.
746 Org-mode often shows locations in an org-mode file which might have
747 been invisible before. When this is set, the sibling of the current entry
748 heading are all made visible. If `org-show-hierarchy-above' is t,
749 the same happens on each level of the hierarchy above the current entry.
751 By default this is on for the isearch context, off for all other contexts.
752 Turning this off for example for sparse trees makes them very compact,
753 but makes it harder to edit the location of the match. In such a case,
754 use the command \\[org-reveal] to show more context.
755 Instead of t, this can also be an alist specifying this option for different
756 contexts. See `org-show-hierarchy-above' for valid contexts."
757 :group 'org-reveal-location
758 :type org-context-choice)
760 (defcustom org-show-entry-below '((default . nil))
761 "Non-nil means show the entry below a headline when revealing a location.
762 Org-mode often shows locations in an org-mode file which might have
763 been invisible before. When this is set, the text below the headline that is
764 exposed is also shown.
766 By default this is off for all contexts.
767 Instead of t, this can also be an alist specifying this option for different
768 contexts. See `org-show-hierarchy-above' for valid contexts."
769 :group 'org-reveal-location
770 :type org-context-choice)
772 (defcustom org-indirect-buffer-display 'other-window
773 "How should indirect tree buffers be displayed?
774 This applies to indirect buffers created with the commands
775 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
776 Valid values are:
777 current-window Display in the current window
778 other-window Just display in another window.
779 dedicated-frame Create one new frame, and re-use it each time.
780 new-frame Make a new frame each time. Note that in this case
781 previously-made indirect buffers are kept, and you need to
782 kill these buffers yourself."
783 :group 'org-structure
784 :group 'org-agenda-windows
785 :type '(choice
786 (const :tag "In current window" current-window)
787 (const :tag "In current frame, other window" other-window)
788 (const :tag "Each time a new frame" new-frame)
789 (const :tag "One dedicated frame" dedicated-frame)))
791 (defcustom org-use-speed-commands nil
792 "Non-nil means activate single letter commands at beginning of a headline.
793 This may also be a function to test for appropriate locations where speed
794 commands should be active."
795 :group 'org-structure
796 :type '(choice
797 (const :tag "Never" nil)
798 (const :tag "At beginning of headline stars" t)
799 (function)))
801 (defcustom org-speed-commands-user nil
802 "Alist of additional speed commands.
803 This list will be checked before `org-speed-commands-default'
804 when the variable `org-use-speed-commands' is non-nil
805 and when the cursor is at the beginning of a headline.
806 The car if each entry is a string with a single letter, which must
807 be assigned to `self-insert-command' in the global map.
808 The cdr is either a command to be called interactively, a function
809 to be called, or a form to be evaluated.
810 An entry that is just a list with a single string will be interpreted
811 as a descriptive headline that will be added when listing the speed
812 commands in the Help buffer using the `?' speed command."
813 :group 'org-structure
814 :type '(repeat :value ("k" . ignore)
815 (choice :value ("k" . ignore)
816 (list :tag "Descriptive Headline" (string :tag "Headline"))
817 (cons :tag "Letter and Command"
818 (string :tag "Command letter")
819 (choice
820 (function)
821 (sexp))))))
823 (defgroup org-cycle nil
824 "Options concerning visibility cycling in Org-mode."
825 :tag "Org Cycle"
826 :group 'org-structure)
828 (defcustom org-cycle-skip-children-state-if-no-children t
829 "Non-nil means skip CHILDREN state in entries that don't have any."
830 :group 'org-cycle
831 :type 'boolean)
833 (defcustom org-cycle-max-level nil
834 "Maximum level which should still be subject to visibility cycling.
835 Levels higher than this will, for cycling, be treated as text, not a headline.
836 When `org-odd-levels-only' is set, a value of N in this variable actually
837 means 2N-1 stars as the limiting headline.
838 When nil, cycle all levels.
839 Note that the limiting level of cycling is also influenced by
840 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
841 `org-inlinetask-min-level' is, cycling will be limited to levels one less
842 than its value."
843 :group 'org-cycle
844 :type '(choice
845 (const :tag "No limit" nil)
846 (integer :tag "Maximum level")))
848 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
849 "Names of drawers. Drawers are not opened by cycling on the headline above.
850 Drawers only open with a TAB on the drawer line itself. A drawer looks like
851 this:
852 :DRAWERNAME:
853 .....
854 :END:
855 The drawer \"PROPERTIES\" is special for capturing properties through
856 the property API.
858 Drawers can be defined on the per-file basis with a line like:
860 #+DRAWERS: HIDDEN STATE PROPERTIES"
861 :group 'org-structure
862 :group 'org-cycle
863 :type '(repeat (string :tag "Drawer Name")))
865 (defcustom org-hide-block-startup nil
866 "Non-nil means entering Org-mode will fold all blocks.
867 This can also be set in on a per-file basis with
869 #+STARTUP: hideblocks
870 #+STARTUP: showblocks"
871 :group 'org-startup
872 :group 'org-cycle
873 :type 'boolean)
875 (defcustom org-cycle-global-at-bob nil
876 "Cycle globally if cursor is at beginning of buffer and not at a headline.
877 This makes it possible to do global cycling without having to use S-TAB or
878 \\[universal-argument] TAB. For this special case to work, the first line \
879 of the buffer
880 must not be a headline - it may be empty or some other text. When used in
881 this way, `org-cycle-hook' is disables temporarily, to make sure the
882 cursor stays at the beginning of the buffer.
883 When this option is nil, don't do anything special at the beginning
884 of the buffer."
885 :group 'org-cycle
886 :type 'boolean)
888 (defcustom org-cycle-level-after-item/entry-creation t
889 "Non-nil means cycle entry level or item indentation in new empty entries.
891 When the cursor is at the end of an empty headline, i.e with only stars
892 and maybe a TODO keyword, TAB will then switch the entry to become a child,
893 and then all possible ancestor states, before returning to the original state.
894 This makes data entry extremely fast: M-RET to create a new headline,
895 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
897 When the cursor is at the end of an empty plain list item, one TAB will
898 make it a subitem, two or more tabs will back up to make this an item
899 higher up in the item hierarchy."
900 :group 'org-cycle
901 :type 'boolean)
903 (defcustom org-cycle-emulate-tab t
904 "Where should `org-cycle' emulate TAB.
905 nil Never
906 white Only in completely white lines
907 whitestart Only at the beginning of lines, before the first non-white char
908 t Everywhere except in headlines
909 exc-hl-bol Everywhere except at the start of a headline
910 If TAB is used in a place where it does not emulate TAB, the current subtree
911 visibility is cycled."
912 :group 'org-cycle
913 :type '(choice (const :tag "Never" nil)
914 (const :tag "Only in completely white lines" white)
915 (const :tag "Before first char in a line" whitestart)
916 (const :tag "Everywhere except in headlines" t)
917 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
920 (defcustom org-cycle-separator-lines 2
921 "Number of empty lines needed to keep an empty line between collapsed trees.
922 If you leave an empty line between the end of a subtree and the following
923 headline, this empty line is hidden when the subtree is folded.
924 Org-mode will leave (exactly) one empty line visible if the number of
925 empty lines is equal or larger to the number given in this variable.
926 So the default 2 means at least 2 empty lines after the end of a subtree
927 are needed to produce free space between a collapsed subtree and the
928 following headline.
930 If the number is negative, and the number of empty lines is at least -N,
931 all empty lines are shown.
933 Special case: when 0, never leave empty lines in collapsed view."
934 :group 'org-cycle
935 :type 'integer)
936 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
938 (defcustom org-pre-cycle-hook nil
939 "Hook that is run before visibility cycling is happening.
940 The function(s) in this hook must accept a single argument which indicates
941 the new state that will be set right after running this hook. The
942 argument is a symbol. Before a global state change, it can have the values
943 `overview', `content', or `all'. Before a local state change, it can have
944 the values `folded', `children', or `subtree'."
945 :group 'org-cycle
946 :type 'hook)
948 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
949 org-cycle-hide-drawers
950 org-cycle-show-empty-lines
951 org-optimize-window-after-visibility-change)
952 "Hook that is run after `org-cycle' has changed the buffer visibility.
953 The function(s) in this hook must accept a single argument which indicates
954 the new state that was set by the most recent `org-cycle' command. The
955 argument is a symbol. After a global state change, it can have the values
956 `overview', `content', or `all'. After a local state change, it can have
957 the values `folded', `children', or `subtree'."
958 :group 'org-cycle
959 :type 'hook)
961 (defgroup org-edit-structure nil
962 "Options concerning structure editing in Org-mode."
963 :tag "Org Edit Structure"
964 :group 'org-structure)
966 (defcustom org-odd-levels-only nil
967 "Non-nil means skip even levels and only use odd levels for the outline.
968 This has the effect that two stars are being added/taken away in
969 promotion/demotion commands. It also influences how levels are
970 handled by the exporters.
971 Changing it requires restart of `font-lock-mode' to become effective
972 for fontification also in regions already fontified.
973 You may also set this on a per-file basis by adding one of the following
974 lines to the buffer:
976 #+STARTUP: odd
977 #+STARTUP: oddeven"
978 :group 'org-edit-structure
979 :group 'org-appearance
980 :type 'boolean)
982 (defcustom org-adapt-indentation t
983 "Non-nil means adapt indentation to outline node level.
985 When this variable is set, Org assumes that you write outlines by
986 indenting text in each node to align with the headline (after the stars).
987 The following issues are influenced by this variable:
989 - When this is set and the *entire* text in an entry is indented, the
990 indentation is increased by one space in a demotion command, and
991 decreased by one in a promotion command. If any line in the entry
992 body starts with text at column 0, indentation is not changed at all.
994 - Property drawers and planning information is inserted indented when
995 this variable s set. When nil, they will not be indented.
997 - TAB indents a line relative to context. The lines below a headline
998 will be indented when this variable is set.
1000 Note that this is all about true indentation, by adding and removing
1001 space characters. See also `org-indent.el' which does level-dependent
1002 indentation in a virtual way, i.e. at display time in Emacs."
1003 :group 'org-edit-structure
1004 :type 'boolean)
1006 (defcustom org-special-ctrl-a/e nil
1007 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1009 When t, `C-a' will bring back the cursor to the beginning of the
1010 headline text, i.e. after the stars and after a possible TODO keyword.
1011 In an item, this will be the position after the bullet.
1012 When the cursor is already at that position, another `C-a' will bring
1013 it to the beginning of the line.
1015 `C-e' will jump to the end of the headline, ignoring the presence of tags
1016 in the headline. A second `C-e' will then jump to the true end of the
1017 line, after any tags. This also means that, when this variable is
1018 non-nil, `C-e' also will never jump beyond the end of the heading of a
1019 folded section, i.e. not after the ellipses.
1021 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
1022 going to the true line boundary first. Only a directly following, identical
1023 keypress will bring the cursor to the special positions.
1025 This may also be a cons cell where the behavior for `C-a' and `C-e' is
1026 set separately."
1027 :group 'org-edit-structure
1028 :type '(choice
1029 (const :tag "off" nil)
1030 (const :tag "on: after stars/bullet and before tags first" t)
1031 (const :tag "reversed: true line boundary first" reversed)
1032 (cons :tag "Set C-a and C-e separately"
1033 (choice :tag "Special C-a"
1034 (const :tag "off" nil)
1035 (const :tag "on: after stars/bullet first" t)
1036 (const :tag "reversed: before stars/bullet first" reversed))
1037 (choice :tag "Special C-e"
1038 (const :tag "off" nil)
1039 (const :tag "on: before tags first" t)
1040 (const :tag "reversed: after tags first" reversed)))))
1041 (if (fboundp 'defvaralias)
1042 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1044 (defcustom org-special-ctrl-k nil
1045 "Non-nil means `C-k' will behave specially in headlines.
1046 When nil, `C-k' will call the default `kill-line' command.
1047 When t, the following will happen while the cursor is in the headline:
1049 - When the cursor is at the beginning of a headline, kill the entire
1050 line and possible the folded subtree below the line.
1051 - When in the middle of the headline text, kill the headline up to the tags.
1052 - When after the headline text, kill the tags."
1053 :group 'org-edit-structure
1054 :type 'boolean)
1056 (defcustom org-ctrl-k-protect-subtree nil
1057 "Non-nil means, do not delete a hidden subtree with C-k.
1058 When set to the symbol `error', simply throw an error when C-k is
1059 used to kill (part-of) a headline that has hidden text behind it.
1060 Any other non-nil value will result in a query to the user, if it is
1061 OK to kill that hidden subtree. When nil, kill without remorse."
1062 :group 'org-edit-structure
1063 :type '(choice
1064 (const :tag "Do not protect hidden subtrees" nil)
1065 (const :tag "Protect hidden subtrees with a security query" t)
1066 (const :tag "Never kill a hidden subtree with C-k" error)))
1068 (defcustom org-yank-folded-subtrees t
1069 "Non-nil means when yanking subtrees, fold them.
1070 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1071 it starts with a heading and all other headings in it are either children
1072 or siblings, then fold all the subtrees. However, do this only if no
1073 text after the yank would be swallowed into a folded tree by this action."
1074 :group 'org-edit-structure
1075 :type 'boolean)
1077 (defcustom org-yank-adjusted-subtrees nil
1078 "Non-nil means when yanking subtrees, adjust the level.
1079 With this setting, `org-paste-subtree' is used to insert the subtree, see
1080 this function for details."
1081 :group 'org-edit-structure
1082 :type 'boolean)
1084 (defcustom org-M-RET-may-split-line '((default . t))
1085 "Non-nil means M-RET will split the line at the cursor position.
1086 When nil, it will go to the end of the line before making a
1087 new line.
1088 You may also set this option in a different way for different
1089 contexts. Valid contexts are:
1091 headline when creating a new headline
1092 item when creating a new item
1093 table in a table field
1094 default the value to be used for all contexts not explicitly
1095 customized"
1096 :group 'org-structure
1097 :group 'org-table
1098 :type '(choice
1099 (const :tag "Always" t)
1100 (const :tag "Never" nil)
1101 (repeat :greedy t :tag "Individual contexts"
1102 (cons
1103 (choice :tag "Context"
1104 (const headline)
1105 (const item)
1106 (const table)
1107 (const default))
1108 (boolean)))))
1111 (defcustom org-insert-heading-respect-content nil
1112 "Non-nil means insert new headings after the current subtree.
1113 When nil, the new heading is created directly after the current line.
1114 The commands \\[org-insert-heading-respect-content] and
1115 \\[org-insert-todo-heading-respect-content] turn this variable on
1116 for the duration of the command."
1117 :group 'org-structure
1118 :type 'boolean)
1120 (defcustom org-blank-before-new-entry '((heading . auto)
1121 (plain-list-item . auto))
1122 "Should `org-insert-heading' leave a blank line before new heading/item?
1123 The value is an alist, with `heading' and `plain-list-item' as CAR,
1124 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1125 which case Org will look at the surrounding headings/items and try to
1126 make an intelligent decision whether to insert a blank line or not.
1128 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1129 set, the setting here is ignored and no empty line is inserted, to avoid
1130 breaking the list structure."
1131 :group 'org-edit-structure
1132 :type '(list
1133 (cons (const heading)
1134 (choice (const :tag "Never" nil)
1135 (const :tag "Always" t)
1136 (const :tag "Auto" auto)))
1137 (cons (const plain-list-item)
1138 (choice (const :tag "Never" nil)
1139 (const :tag "Always" t)
1140 (const :tag "Auto" auto)))))
1142 (defcustom org-insert-heading-hook nil
1143 "Hook being run after inserting a new heading."
1144 :group 'org-edit-structure
1145 :type 'hook)
1147 (defcustom org-enable-fixed-width-editor t
1148 "Non-nil means lines starting with \":\" are treated as fixed-width.
1149 This currently only means they are never auto-wrapped.
1150 When nil, such lines will be treated like ordinary lines.
1151 See also the QUOTE keyword."
1152 :group 'org-edit-structure
1153 :type 'boolean)
1155 (defcustom org-goto-auto-isearch t
1156 "Non-nil means typing characters in `org-goto' starts incremental search."
1157 :group 'org-edit-structure
1158 :type 'boolean)
1160 (defgroup org-sparse-trees nil
1161 "Options concerning sparse trees in Org-mode."
1162 :tag "Org Sparse Trees"
1163 :group 'org-structure)
1165 (defcustom org-highlight-sparse-tree-matches t
1166 "Non-nil means highlight all matches that define a sparse tree.
1167 The highlights will automatically disappear the next time the buffer is
1168 changed by an edit command."
1169 :group 'org-sparse-trees
1170 :type 'boolean)
1172 (defcustom org-remove-highlights-with-change t
1173 "Non-nil means any change to the buffer will remove temporary highlights.
1174 Such highlights are created by `org-occur' and `org-clock-display'.
1175 When nil, `C-c C-c needs to be used to get rid of the highlights.
1176 The highlights created by `org-preview-latex-fragment' always need
1177 `C-c C-c' to be removed."
1178 :group 'org-sparse-trees
1179 :group 'org-time
1180 :type 'boolean)
1183 (defcustom org-occur-hook '(org-first-headline-recenter)
1184 "Hook that is run after `org-occur' has constructed a sparse tree.
1185 This can be used to recenter the window to show as much of the structure
1186 as possible."
1187 :group 'org-sparse-trees
1188 :type 'hook)
1190 (defgroup org-imenu-and-speedbar nil
1191 "Options concerning imenu and speedbar in Org-mode."
1192 :tag "Org Imenu and Speedbar"
1193 :group 'org-structure)
1195 (defcustom org-imenu-depth 2
1196 "The maximum level for Imenu access to Org-mode headlines.
1197 This also applied for speedbar access."
1198 :group 'org-imenu-and-speedbar
1199 :type 'integer)
1201 (defgroup org-table nil
1202 "Options concerning tables in Org-mode."
1203 :tag "Org Table"
1204 :group 'org)
1206 (defcustom org-enable-table-editor 'optimized
1207 "Non-nil means lines starting with \"|\" are handled by the table editor.
1208 When nil, such lines will be treated like ordinary lines.
1210 When equal to the symbol `optimized', the table editor will be optimized to
1211 do the following:
1212 - Automatic overwrite mode in front of whitespace in table fields.
1213 This makes the structure of the table stay in tact as long as the edited
1214 field does not exceed the column width.
1215 - Minimize the number of realigns. Normally, the table is aligned each time
1216 TAB or RET are pressed to move to another field. With optimization this
1217 happens only if changes to a field might have changed the column width.
1218 Optimization requires replacing the functions `self-insert-command',
1219 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1220 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1221 very good at guessing when a re-align will be necessary, but you can always
1222 force one with \\[org-ctrl-c-ctrl-c].
1224 If you would like to use the optimized version in Org-mode, but the
1225 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1227 This variable can be used to turn on and off the table editor during a session,
1228 but in order to toggle optimization, a restart is required.
1230 See also the variable `org-table-auto-blank-field'."
1231 :group 'org-table
1232 :type '(choice
1233 (const :tag "off" nil)
1234 (const :tag "on" t)
1235 (const :tag "on, optimized" optimized)))
1237 (defcustom org-self-insert-cluster-for-undo t
1238 "Non-nil means cluster self-insert commands for undo when possible.
1239 If this is set, then, like in the Emacs command loop, 20 consecutive
1240 characters will be undone together.
1241 This is configurable, because there is some impact on typing performance."
1242 :group 'org-table
1243 :type 'boolean)
1245 (defcustom org-table-tab-recognizes-table.el t
1246 "Non-nil means TAB will automatically notice a table.el table.
1247 When it sees such a table, it moves point into it and - if necessary -
1248 calls `table-recognize-table'."
1249 :group 'org-table-editing
1250 :type 'boolean)
1252 (defgroup org-link nil
1253 "Options concerning links in Org-mode."
1254 :tag "Org Link"
1255 :group 'org)
1257 (defvar org-link-abbrev-alist-local nil
1258 "Buffer-local version of `org-link-abbrev-alist', which see.
1259 The value of this is taken from the #+LINK lines.")
1260 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1262 (defcustom org-link-abbrev-alist nil
1263 "Alist of link abbreviations.
1264 The car of each element is a string, to be replaced at the start of a link.
1265 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1266 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1268 [[linkkey:tag][description]]
1270 The 'linkkey' must be a word word, starting with a letter, followed
1271 by letters, numbers, '-' or '_'.
1273 If REPLACE is a string, the tag will simply be appended to create the link.
1274 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1275 the placeholder \"%h\" will cause a url-encoded version of the tag to
1276 be inserted at that point (see the function `url-hexify-string').
1278 REPLACE may also be a function that will be called with the tag as the
1279 only argument to create the link, which should be returned as a string.
1281 See the manual for examples."
1282 :group 'org-link
1283 :type '(repeat
1284 (cons
1285 (string :tag "Protocol")
1286 (choice
1287 (string :tag "Format")
1288 (function)))))
1290 (defcustom org-descriptive-links t
1291 "Non-nil means Org will display descriptive links.
1292 E.g. [[http://orgmode.org][Org website]] will be displayed as
1293 \"Org Website\", hiding the link itself and just displaying its
1294 description. When set to `nil', Org will display the full links
1295 literally.
1297 You can interactively set the value of this variable by calling
1298 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1299 :group 'org-link
1300 :type 'boolean)
1302 (defcustom org-link-file-path-type 'adaptive
1303 "How the path name in file links should be stored.
1304 Valid values are:
1306 relative Relative to the current directory, i.e. the directory of the file
1307 into which the link is being inserted.
1308 absolute Absolute path, if possible with ~ for home directory.
1309 noabbrev Absolute path, no abbreviation of home directory.
1310 adaptive Use relative path for files in the current directory and sub-
1311 directories of it. For other files, use an absolute path."
1312 :group 'org-link
1313 :type '(choice
1314 (const relative)
1315 (const absolute)
1316 (const noabbrev)
1317 (const adaptive)))
1319 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1320 "Types of links that should be activated in Org-mode files.
1321 This is a list of symbols, each leading to the activation of a certain link
1322 type. In principle, it does not hurt to turn on most link types - there may
1323 be a small gain when turning off unused link types. The types are:
1325 bracket The recommended [[link][description]] or [[link]] links with hiding.
1326 angle Links in angular brackets that may contain whitespace like
1327 <bbdb:Carsten Dominik>.
1328 plain Plain links in normal text, no whitespace, like http://google.com.
1329 radio Text that is matched by a radio target, see manual for details.
1330 tag Tag settings in a headline (link to tag search).
1331 date Time stamps (link to calendar).
1332 footnote Footnote labels.
1334 Changing this variable requires a restart of Emacs to become effective."
1335 :group 'org-link
1336 :type '(set :greedy t
1337 (const :tag "Double bracket links" bracket)
1338 (const :tag "Angular bracket links" angle)
1339 (const :tag "Plain text links" plain)
1340 (const :tag "Radio target matches" radio)
1341 (const :tag "Tags" tag)
1342 (const :tag "Timestamps" date)
1343 (const :tag "Footnotes" footnote)))
1345 (defcustom org-make-link-description-function nil
1346 "Function to use to generate link descriptions from links.
1347 If nil the link location will be used. This function must take
1348 two parameters; the first is the link and the second the
1349 description `org-insert-link' has generated, and should return the
1350 description to use."
1351 :group 'org-link
1352 :type 'function)
1354 (defgroup org-link-store nil
1355 "Options concerning storing links in Org-mode."
1356 :tag "Org Store Link"
1357 :group 'org-link)
1359 (defcustom org-email-link-description-format "Email %c: %.30s"
1360 "Format of the description part of a link to an email or usenet message.
1361 The following %-escapes will be replaced by corresponding information:
1363 %F full \"From\" field
1364 %f name, taken from \"From\" field, address if no name
1365 %T full \"To\" field
1366 %t first name in \"To\" field, address if no name
1367 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1368 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1369 %s subject
1370 %d date
1371 %m message-id.
1373 You may use normal field width specification between the % and the letter.
1374 This is for example useful to limit the length of the subject.
1376 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1377 :group 'org-link-store
1378 :type 'string)
1380 (defcustom org-from-is-user-regexp
1381 (let (r1 r2)
1382 (when (and user-mail-address (not (string= user-mail-address "")))
1383 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1384 (when (and user-full-name (not (string= user-full-name "")))
1385 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1386 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1387 "Regexp matched against the \"From:\" header of an email or usenet message.
1388 It should match if the message is from the user him/herself."
1389 :group 'org-link-store
1390 :type 'regexp)
1392 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1393 "Non-nil means storing a link to an Org file will use entry IDs.
1395 Note that before this variable is even considered, org-id must be loaded,
1396 so please customize `org-modules' and turn it on.
1398 The variable can have the following values:
1400 t Create an ID if needed to make a link to the current entry.
1402 create-if-interactive
1403 If `org-store-link' is called directly (interactively, as a user
1404 command), do create an ID to support the link. But when doing the
1405 job for remember, only use the ID if it already exists. The
1406 purpose of this setting is to avoid proliferation of unwanted
1407 IDs, just because you happen to be in an Org file when you
1408 call `org-remember' that automatically and preemptively
1409 creates a link. If you do want to get an ID link in a remember
1410 template to an entry not having an ID, create it first by
1411 explicitly creating a link to it, using `C-c C-l' first.
1413 create-if-interactive-and-no-custom-id
1414 Like create-if-interactive, but do not create an ID if there is
1415 a CUSTOM_ID property defined in the entry. This is the default.
1417 use-existing
1418 Use existing ID, do not create one.
1420 nil Never use an ID to make a link, instead link using a text search for
1421 the headline text."
1422 :group 'org-link-store
1423 :type '(choice
1424 (const :tag "Create ID to make link" t)
1425 (const :tag "Create if storing link interactively"
1426 create-if-interactive)
1427 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1428 create-if-interactive-and-no-custom-id)
1429 (const :tag "Only use existing" use-existing)
1430 (const :tag "Do not use ID to create link" nil)))
1432 (defcustom org-context-in-file-links t
1433 "Non-nil means file links from `org-store-link' contain context.
1434 A search string will be added to the file name with :: as separator and
1435 used to find the context when the link is activated by the command
1436 `org-open-at-point'. When this option is t, the entire active region
1437 will be placed in the search string of the file link. If set to a
1438 positive integer, only the first n lines of context will be stored.
1440 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1441 negates this setting for the duration of the command."
1442 :group 'org-link-store
1443 :type '(choice boolean integer))
1445 (defcustom org-keep-stored-link-after-insertion nil
1446 "Non-nil means keep link in list for entire session.
1448 The command `org-store-link' adds a link pointing to the current
1449 location to an internal list. These links accumulate during a session.
1450 The command `org-insert-link' can be used to insert links into any
1451 Org-mode file (offering completion for all stored links). When this
1452 option is nil, every link which has been inserted once using \\[org-insert-link]
1453 will be removed from the list, to make completing the unused links
1454 more efficient."
1455 :group 'org-link-store
1456 :type 'boolean)
1458 (defgroup org-link-follow nil
1459 "Options concerning following links in Org-mode."
1460 :tag "Org Follow Link"
1461 :group 'org-link)
1463 (defcustom org-link-translation-function nil
1464 "Function to translate links with different syntax to Org syntax.
1465 This can be used to translate links created for example by the Planner
1466 or emacs-wiki packages to Org syntax.
1467 The function must accept two parameters, a TYPE containing the link
1468 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1469 which is everything after the link protocol. It should return a cons
1470 with possibly modified values of type and path.
1471 Org contains a function for this, so if you set this variable to
1472 `org-translate-link-from-planner', you should be able follow many
1473 links created by planner."
1474 :group 'org-link-follow
1475 :type 'function)
1477 (defcustom org-follow-link-hook nil
1478 "Hook that is run after a link has been followed."
1479 :group 'org-link-follow
1480 :type 'hook)
1482 (defcustom org-tab-follows-link nil
1483 "Non-nil means on links TAB will follow the link.
1484 Needs to be set before org.el is loaded.
1485 This really should not be used, it does not make sense, and the
1486 implementation is bad."
1487 :group 'org-link-follow
1488 :type 'boolean)
1490 (defcustom org-return-follows-link nil
1491 "Non-nil means on links RET will follow the link."
1492 :group 'org-link-follow
1493 :type 'boolean)
1495 (defcustom org-mouse-1-follows-link
1496 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1497 "Non-nil means mouse-1 on a link will follow the link.
1498 A longer mouse click will still set point. Does not work on XEmacs.
1499 Needs to be set before org.el is loaded."
1500 :group 'org-link-follow
1501 :type 'boolean)
1503 (defcustom org-mark-ring-length 4
1504 "Number of different positions to be recorded in the ring.
1505 Changing this requires a restart of Emacs to work correctly."
1506 :group 'org-link-follow
1507 :type 'integer)
1509 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1510 "Non-nil means internal links in Org files must exactly match a headline.
1511 When nil, the link search tries to match a phrase with all words
1512 in the search text."
1513 :group 'org-link-follow
1514 :type '(choice
1515 (const :tag "Use fuzzy text search" nil)
1516 (const :tag "Match only exact headline" t)
1517 (const :tag "Match exact headline or query to create it"
1518 query-to-create)))
1520 (defcustom org-link-frame-setup
1521 '((vm . vm-visit-folder-other-frame)
1522 (gnus . org-gnus-no-new-news)
1523 (file . find-file-other-window)
1524 (wl . wl-other-frame))
1525 "Setup the frame configuration for following links.
1526 When following a link with Emacs, it may often be useful to display
1527 this link in another window or frame. This variable can be used to
1528 set this up for the different types of links.
1529 For VM, use any of
1530 `vm-visit-folder'
1531 `vm-visit-folder-other-window'
1532 `vm-visit-folder-other-frame'
1533 For Gnus, use any of
1534 `gnus'
1535 `gnus-other-frame'
1536 `org-gnus-no-new-news'
1537 For FILE, use any of
1538 `find-file'
1539 `find-file-other-window'
1540 `find-file-other-frame'
1541 For Wanderlust use any of
1542 `wl'
1543 `wl-other-frame'
1544 For the calendar, use the variable `calendar-setup'.
1545 For BBDB, it is currently only possible to display the matches in
1546 another window."
1547 :group 'org-link-follow
1548 :type '(list
1549 (cons (const vm)
1550 (choice
1551 (const vm-visit-folder)
1552 (const vm-visit-folder-other-window)
1553 (const vm-visit-folder-other-frame)))
1554 (cons (const gnus)
1555 (choice
1556 (const gnus)
1557 (const gnus-other-frame)
1558 (const org-gnus-no-new-news)))
1559 (cons (const file)
1560 (choice
1561 (const find-file)
1562 (const find-file-other-window)
1563 (const find-file-other-frame)))
1564 (cons (const wl)
1565 (choice
1566 (const wl)
1567 (const wl-other-frame)))))
1569 (defcustom org-display-internal-link-with-indirect-buffer nil
1570 "Non-nil means use indirect buffer to display infile links.
1571 Activating internal links (from one location in a file to another location
1572 in the same file) normally just jumps to the location. When the link is
1573 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1574 is displayed in
1575 another window. When this option is set, the other window actually displays
1576 an indirect buffer clone of the current buffer, to avoid any visibility
1577 changes to the current buffer."
1578 :group 'org-link-follow
1579 :type 'boolean)
1581 (defcustom org-open-non-existing-files nil
1582 "Non-nil means `org-open-file' will open non-existing files.
1583 When nil, an error will be generated.
1584 This variable applies only to external applications because they
1585 might choke on non-existing files. If the link is to a file that
1586 will be opened in Emacs, the variable is ignored."
1587 :group 'org-link-follow
1588 :type 'boolean)
1590 (defcustom org-open-directory-means-index-dot-org nil
1591 "Non-nil means a link to a directory really means to index.org.
1592 When nil, following a directory link will run dired or open a finder/explorer
1593 window on that directory."
1594 :group 'org-link-follow
1595 :type 'boolean)
1597 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1598 "Function and arguments to call for following mailto links.
1599 This is a list with the first element being a Lisp function, and the
1600 remaining elements being arguments to the function. In string arguments,
1601 %a will be replaced by the address, and %s will be replaced by the subject
1602 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1603 :group 'org-link-follow
1604 :type '(choice
1605 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1606 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1607 (const :tag "message-mail" (message-mail "%a" "%s"))
1608 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1610 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1611 "Non-nil means ask for confirmation before executing shell links.
1612 Shell links can be dangerous: just think about a link
1614 [[shell:rm -rf ~/*][Google Search]]
1616 This link would show up in your Org-mode document as \"Google Search\",
1617 but really it would remove your entire home directory.
1618 Therefore we advise against setting this variable to nil.
1619 Just change it to `y-or-n-p' if you want to confirm with a
1620 single keystroke rather than having to type \"yes\"."
1621 :group 'org-link-follow
1622 :type '(choice
1623 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1624 (const :tag "with y-or-n (faster)" y-or-n-p)
1625 (const :tag "no confirmation (dangerous)" nil)))
1626 (put 'org-confirm-shell-link-function
1627 'safe-local-variable
1628 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1630 (defcustom org-confirm-shell-link-not-regexp ""
1631 "A regexp to skip confirmation for shell links."
1632 :group 'org-link-follow
1633 :type 'regexp)
1635 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1636 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1637 Elisp links can be dangerous: just think about a link
1639 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1641 This link would show up in your Org-mode document as \"Google Search\",
1642 but really it would remove your entire home directory.
1643 Therefore we advise against setting this variable to nil.
1644 Just change it to `y-or-n-p' if you want to confirm with a
1645 single keystroke rather than having to type \"yes\"."
1646 :group 'org-link-follow
1647 :type '(choice
1648 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1649 (const :tag "with y-or-n (faster)" y-or-n-p)
1650 (const :tag "no confirmation (dangerous)" nil)))
1651 (put 'org-confirm-shell-link-function
1652 'safe-local-variable
1653 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1655 (defcustom org-confirm-elisp-link-not-regexp ""
1656 "A regexp to skip confirmation for Elisp links."
1657 :group 'org-link-follow
1658 :type 'regexp)
1660 (defconst org-file-apps-defaults-gnu
1661 '((remote . emacs)
1662 (system . mailcap)
1663 (t . mailcap))
1664 "Default file applications on a UNIX or GNU/Linux system.
1665 See `org-file-apps'.")
1667 (defconst org-file-apps-defaults-macosx
1668 '((remote . emacs)
1669 (t . "open %s")
1670 (system . "open %s")
1671 ("ps.gz" . "gv %s")
1672 ("eps.gz" . "gv %s")
1673 ("dvi" . "xdvi %s")
1674 ("fig" . "xfig %s"))
1675 "Default file applications on a MacOS X system.
1676 The system \"open\" is known as a default, but we use X11 applications
1677 for some files for which the OS does not have a good default.
1678 See `org-file-apps'.")
1680 (defconst org-file-apps-defaults-windowsnt
1681 (list
1682 '(remote . emacs)
1683 (cons t
1684 (list (if (featurep 'xemacs)
1685 'mswindows-shell-execute
1686 'w32-shell-execute)
1687 "open" 'file))
1688 (cons 'system
1689 (list (if (featurep 'xemacs)
1690 'mswindows-shell-execute
1691 'w32-shell-execute)
1692 "open" 'file)))
1693 "Default file applications on a Windows NT system.
1694 The system \"open\" is used for most files.
1695 See `org-file-apps'.")
1697 (defcustom org-file-apps
1699 (auto-mode . emacs)
1700 ("\\.mm\\'" . default)
1701 ("\\.x?html?\\'" . default)
1702 ("\\.pdf\\'" . default)
1704 "External applications for opening `file:path' items in a document.
1705 Org-mode uses system defaults for different file types, but
1706 you can use this variable to set the application for a given file
1707 extension. The entries in this list are cons cells where the car identifies
1708 files and the cdr the corresponding command. Possible values for the
1709 file identifier are
1710 \"string\" A string as a file identifier can be interpreted in different
1711 ways, depending on its contents:
1713 - Alphanumeric characters only:
1714 Match links with this file extension.
1715 Example: (\"pdf\" . \"evince %s\")
1716 to open PDFs with evince.
1718 - Regular expression: Match links where the
1719 filename matches the regexp. If you want to
1720 use groups here, use shy groups.
1722 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1723 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1724 to open *.html and *.xhtml with firefox.
1726 - Regular expression which contains (non-shy) groups:
1727 Match links where the whole link, including \"::\", and
1728 anything after that, matches the regexp.
1729 In a custom command string, %1, %2, etc. are replaced with
1730 the parts of the link that were matched by the groups.
1731 For backwards compatibility, if a command string is given
1732 that does not use any of the group matches, this case is
1733 handled identically to the second one (i.e. match against
1734 file name only).
1735 In a custom lisp form, you can access the group matches with
1736 (match-string n link).
1738 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1739 to open [[file:document.pdf::5]] with evince at page 5.
1741 `directory' Matches a directory
1742 `remote' Matches a remote file, accessible through tramp or efs.
1743 Remote files most likely should be visited through Emacs
1744 because external applications cannot handle such paths.
1745 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1746 so all files Emacs knows how to handle. Using this with
1747 command `emacs' will open most files in Emacs. Beware that this
1748 will also open html files inside Emacs, unless you add
1749 (\"html\" . default) to the list as well.
1750 t Default for files not matched by any of the other options.
1751 `system' The system command to open files, like `open' on Windows
1752 and Mac OS X, and mailcap under GNU/Linux. This is the command
1753 that will be selected if you call `C-c C-o' with a double
1754 \\[universal-argument] \\[universal-argument] prefix.
1756 Possible values for the command are:
1757 `emacs' The file will be visited by the current Emacs process.
1758 `default' Use the default application for this file type, which is the
1759 association for t in the list, most likely in the system-specific
1760 part.
1761 This can be used to overrule an unwanted setting in the
1762 system-specific variable.
1763 `system' Use the system command for opening files, like \"open\".
1764 This command is specified by the entry whose car is `system'.
1765 Most likely, the system-specific version of this variable
1766 does define this command, but you can overrule/replace it
1767 here.
1768 string A command to be executed by a shell; %s will be replaced
1769 by the path to the file.
1770 sexp A Lisp form which will be evaluated. The file path will
1771 be available in the Lisp variable `file'.
1772 For more examples, see the system specific constants
1773 `org-file-apps-defaults-macosx'
1774 `org-file-apps-defaults-windowsnt'
1775 `org-file-apps-defaults-gnu'."
1776 :group 'org-link-follow
1777 :type '(repeat
1778 (cons (choice :value ""
1779 (string :tag "Extension")
1780 (const :tag "System command to open files" system)
1781 (const :tag "Default for unrecognized files" t)
1782 (const :tag "Remote file" remote)
1783 (const :tag "Links to a directory" directory)
1784 (const :tag "Any files that have Emacs modes"
1785 auto-mode))
1786 (choice :value ""
1787 (const :tag "Visit with Emacs" emacs)
1788 (const :tag "Use default" default)
1789 (const :tag "Use the system command" system)
1790 (string :tag "Command")
1791 (sexp :tag "Lisp form")))))
1795 (defgroup org-refile nil
1796 "Options concerning refiling entries in Org-mode."
1797 :tag "Org Refile"
1798 :group 'org)
1800 (defcustom org-directory "~/org"
1801 "Directory with org files.
1802 This is just a default location to look for Org files. There is no need
1803 at all to put your files into this directory. It is only used in the
1804 following situations:
1806 1. When a remember template specifies a target file that is not an
1807 absolute path. The path will then be interpreted relative to
1808 `org-directory'
1809 2. When a remember note is filed away in an interactive way (when exiting the
1810 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1811 with `org-directory' as the default path."
1812 :group 'org-refile
1813 :group 'org-remember
1814 :type 'directory)
1816 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1817 "Default target for storing notes.
1818 Used as a fall back file for org-remember.el and org-capture.el, for
1819 templates that do not specify a target file."
1820 :group 'org-refile
1821 :group 'org-remember
1822 :type '(choice
1823 (const :tag "Default from remember-data-file" nil)
1824 file))
1826 (defcustom org-goto-interface 'outline
1827 "The default interface to be used for `org-goto'.
1828 Allowed values are:
1829 outline The interface shows an outline of the relevant file
1830 and the correct heading is found by moving through
1831 the outline or by searching with incremental search.
1832 outline-path-completion Headlines in the current buffer are offered via
1833 completion. This is the interface also used by
1834 the refile command."
1835 :group 'org-refile
1836 :type '(choice
1837 (const :tag "Outline" outline)
1838 (const :tag "Outline-path-completion" outline-path-completion)))
1840 (defcustom org-goto-max-level 5
1841 "Maximum target level when running `org-goto' with refile interface."
1842 :group 'org-refile
1843 :type 'integer)
1845 (defcustom org-reverse-note-order nil
1846 "Non-nil means store new notes at the beginning of a file or entry.
1847 When nil, new notes will be filed to the end of a file or entry.
1848 This can also be a list with cons cells of regular expressions that
1849 are matched against file names, and values."
1850 :group 'org-remember
1851 :group 'org-refile
1852 :type '(choice
1853 (const :tag "Reverse always" t)
1854 (const :tag "Reverse never" nil)
1855 (repeat :tag "By file name regexp"
1856 (cons regexp boolean))))
1858 (defcustom org-log-refile nil
1859 "Information to record when a task is refiled.
1861 Possible values are:
1863 nil Don't add anything
1864 time Add a time stamp to the task
1865 note Prompt for a note and add it with template `org-log-note-headings'
1867 This option can also be set with on a per-file-basis with
1869 #+STARTUP: nologrefile
1870 #+STARTUP: logrefile
1871 #+STARTUP: lognoterefile
1873 You can have local logging settings for a subtree by setting the LOGGING
1874 property to one or more of these keywords.
1876 When bulk-refiling from the agenda, the value `note' is forbidden and
1877 will temporarily be changed to `time'."
1878 :group 'org-refile
1879 :group 'org-progress
1880 :type '(choice
1881 (const :tag "No logging" nil)
1882 (const :tag "Record timestamp" time)
1883 (const :tag "Record timestamp with note." note)))
1885 (defcustom org-refile-targets nil
1886 "Targets for refiling entries with \\[org-refile].
1887 This is a list of cons cells. Each cell contains:
1888 - a specification of the files to be considered, either a list of files,
1889 or a symbol whose function or variable value will be used to retrieve
1890 a file name or a list of file names. If you use `org-agenda-files' for
1891 that, all agenda files will be scanned for targets. Nil means consider
1892 headings in the current buffer.
1893 - A specification of how to find candidate refile targets. This may be
1894 any of:
1895 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1896 This tag has to be present in all target headlines, inheritance will
1897 not be considered.
1898 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1899 todo keyword.
1900 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1901 headlines that are refiling targets.
1902 - a cons cell (:level . N). Any headline of level N is considered a target.
1903 Note that, when `org-odd-levels-only' is set, level corresponds to
1904 order in hierarchy, not to the number of stars.
1905 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1906 Note that, when `org-odd-levels-only' is set, level corresponds to
1907 order in hierarchy, not to the number of stars.
1909 Each element of this list generates a set of possible targets.
1910 The union of these sets is presented (with completion) to
1911 the user by `org-refile'.
1913 You can set the variable `org-refile-target-verify-function' to a function
1914 to verify each headline found by the simple criteria above.
1916 When this variable is nil, all top-level headlines in the current buffer
1917 are used, equivalent to the value `((nil . (:level . 1))'."
1918 :group 'org-refile
1919 :type '(repeat
1920 (cons
1921 (choice :value org-agenda-files
1922 (const :tag "All agenda files" org-agenda-files)
1923 (const :tag "Current buffer" nil)
1924 (function) (variable) (file))
1925 (choice :tag "Identify target headline by"
1926 (cons :tag "Specific tag" (const :value :tag) (string))
1927 (cons :tag "TODO keyword" (const :value :todo) (string))
1928 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1929 (cons :tag "Level number" (const :value :level) (integer))
1930 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1932 (defcustom org-refile-target-verify-function nil
1933 "Function to verify if the headline at point should be a refile target.
1934 The function will be called without arguments, with point at the
1935 beginning of the headline. It should return t and leave point
1936 where it is if the headline is a valid target for refiling.
1938 If the target should not be selected, the function must return nil.
1939 In addition to this, it may move point to a place from where the search
1940 should be continued. For example, the function may decide that the entire
1941 subtree of the current entry should be excluded and move point to the end
1942 of the subtree."
1943 :group 'org-refile
1944 :type 'function)
1946 (defcustom org-refile-use-cache nil
1947 "Non-nil means cache refile targets to speed up the process.
1948 The cache for a particular file will be updated automatically when
1949 the buffer has been killed, or when any of the marker used for flagging
1950 refile targets no longer points at a live buffer.
1951 If you have added new entries to a buffer that might themselves be targets,
1952 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
1953 find that easier, `C-u C-u C-u C-c C-w'."
1954 :group 'org-refile
1955 :type 'boolean)
1957 (defcustom org-refile-use-outline-path nil
1958 "Non-nil means provide refile targets as paths.
1959 So a level 3 headline will be available as level1/level2/level3.
1961 When the value is `file', also include the file name (without directory)
1962 into the path. In this case, you can also stop the completion after
1963 the file name, to get entries inserted as top level in the file.
1965 When `full-file-path', include the full file path."
1966 :group 'org-refile
1967 :type '(choice
1968 (const :tag "Not" nil)
1969 (const :tag "Yes" t)
1970 (const :tag "Start with file name" file)
1971 (const :tag "Start with full file path" full-file-path)))
1973 (defcustom org-outline-path-complete-in-steps t
1974 "Non-nil means complete the outline path in hierarchical steps.
1975 When Org-mode uses the refile interface to select an outline path
1976 \(see variable `org-refile-use-outline-path'), the completion of
1977 the path can be done is a single go, or if can be done in steps down
1978 the headline hierarchy. Going in steps is probably the best if you
1979 do not use a special completion package like `ido' or `icicles'.
1980 However, when using these packages, going in one step can be very
1981 fast, while still showing the whole path to the entry."
1982 :group 'org-refile
1983 :type 'boolean)
1985 (defcustom org-refile-allow-creating-parent-nodes nil
1986 "Non-nil means allow to create new nodes as refile targets.
1987 New nodes are then created by adding \"/new node name\" to the completion
1988 of an existing node. When the value of this variable is `confirm',
1989 new node creation must be confirmed by the user (recommended)
1990 When nil, the completion must match an existing entry.
1992 Note that, if the new heading is not seen by the criteria
1993 listed in `org-refile-targets', multiple instances of the same
1994 heading would be created by trying again to file under the new
1995 heading."
1996 :group 'org-refile
1997 :type '(choice
1998 (const :tag "Never" nil)
1999 (const :tag "Always" t)
2000 (const :tag "Prompt for confirmation" confirm)))
2002 (defcustom org-refile-active-region-within-subtree nil
2003 "Non-nil means also refile active region within a subtree.
2005 By default `org-refile' doesn't allow refiling regions if they
2006 don't contain a set of subtrees, but it might be convenient to
2007 do so sometimes: in that case, the first line of the region is
2008 converted to a headline before refiling."
2009 :group 'org-refile
2010 :type 'boolean)
2012 (defgroup org-todo nil
2013 "Options concerning TODO items in Org-mode."
2014 :tag "Org TODO"
2015 :group 'org)
2017 (defgroup org-progress nil
2018 "Options concerning Progress logging in Org-mode."
2019 :tag "Org Progress"
2020 :group 'org-time)
2022 (defvar org-todo-interpretation-widgets
2023 '((:tag "Sequence (cycling hits every state)" sequence)
2024 (:tag "Type (cycling directly to DONE)" type))
2025 "The available interpretation symbols for customizing `org-todo-keywords'.
2026 Interested libraries should add to this list.")
2028 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2029 "List of TODO entry keyword sequences and their interpretation.
2030 \\<org-mode-map>This is a list of sequences.
2032 Each sequence starts with a symbol, either `sequence' or `type',
2033 indicating if the keywords should be interpreted as a sequence of
2034 action steps, or as different types of TODO items. The first
2035 keywords are states requiring action - these states will select a headline
2036 for inclusion into the global TODO list Org-mode produces. If one of
2037 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2038 signify that no further action is necessary. If \"|\" is not found,
2039 the last keyword is treated as the only DONE state of the sequence.
2041 The command \\[org-todo] cycles an entry through these states, and one
2042 additional state where no keyword is present. For details about this
2043 cycling, see the manual.
2045 TODO keywords and interpretation can also be set on a per-file basis with
2046 the special #+SEQ_TODO and #+TYP_TODO lines.
2048 Each keyword can optionally specify a character for fast state selection
2049 \(in combination with the variable `org-use-fast-todo-selection')
2050 and specifiers for state change logging, using the same syntax
2051 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
2052 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2053 indicates to record a time stamp each time this state is selected.
2055 Each keyword may also specify if a timestamp or a note should be
2056 recorded when entering or leaving the state, by adding additional
2057 characters in the parenthesis after the keyword. This looks like this:
2058 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2059 record only the time of the state change. With X and Y being either
2060 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2061 Y when leaving the state if and only if the *target* state does not
2062 define X. You may omit any of the fast-selection key or X or /Y,
2063 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2065 For backward compatibility, this variable may also be just a list
2066 of keywords - in this case the interpretation (sequence or type) will be
2067 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2068 :group 'org-todo
2069 :group 'org-keywords
2070 :type '(choice
2071 (repeat :tag "Old syntax, just keywords"
2072 (string :tag "Keyword"))
2073 (repeat :tag "New syntax"
2074 (cons
2075 (choice
2076 :tag "Interpretation"
2077 ;;Quick and dirty way to see
2078 ;;`org-todo-interpretations'. This takes the
2079 ;;place of item arguments
2080 :convert-widget
2081 (lambda (widget)
2082 (widget-put widget
2083 :args (mapcar
2084 #'(lambda (x)
2085 (widget-convert
2086 (cons 'const x)))
2087 org-todo-interpretation-widgets))
2088 widget))
2089 (repeat
2090 (string :tag "Keyword"))))))
2092 (defvar org-todo-keywords-1 nil
2093 "All TODO and DONE keywords active in a buffer.")
2094 (make-variable-buffer-local 'org-todo-keywords-1)
2095 (defvar org-todo-keywords-for-agenda nil)
2096 (defvar org-done-keywords-for-agenda nil)
2097 (defvar org-drawers-for-agenda nil)
2098 (defvar org-todo-keyword-alist-for-agenda nil)
2099 (defvar org-tag-alist-for-agenda nil)
2100 (defvar org-agenda-contributing-files nil)
2101 (defvar org-not-done-keywords nil)
2102 (make-variable-buffer-local 'org-not-done-keywords)
2103 (defvar org-done-keywords nil)
2104 (make-variable-buffer-local 'org-done-keywords)
2105 (defvar org-todo-heads nil)
2106 (make-variable-buffer-local 'org-todo-heads)
2107 (defvar org-todo-sets nil)
2108 (make-variable-buffer-local 'org-todo-sets)
2109 (defvar org-todo-log-states nil)
2110 (make-variable-buffer-local 'org-todo-log-states)
2111 (defvar org-todo-kwd-alist nil)
2112 (make-variable-buffer-local 'org-todo-kwd-alist)
2113 (defvar org-todo-key-alist nil)
2114 (make-variable-buffer-local 'org-todo-key-alist)
2115 (defvar org-todo-key-trigger nil)
2116 (make-variable-buffer-local 'org-todo-key-trigger)
2118 (defcustom org-todo-interpretation 'sequence
2119 "Controls how TODO keywords are interpreted.
2120 This variable is in principle obsolete and is only used for
2121 backward compatibility, if the interpretation of todo keywords is
2122 not given already in `org-todo-keywords'. See that variable for
2123 more information."
2124 :group 'org-todo
2125 :group 'org-keywords
2126 :type '(choice (const sequence)
2127 (const type)))
2129 (defcustom org-use-fast-todo-selection t
2130 "Non-nil means use the fast todo selection scheme with C-c C-t.
2131 This variable describes if and under what circumstances the cycling
2132 mechanism for TODO keywords will be replaced by a single-key, direct
2133 selection scheme.
2135 When nil, fast selection is never used.
2137 When the symbol `prefix', it will be used when `org-todo' is called with
2138 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
2139 in an agenda buffer.
2141 When t, fast selection is used by default. In this case, the prefix
2142 argument forces cycling instead.
2144 In all cases, the special interface is only used if access keys have actually
2145 been assigned by the user, i.e. if keywords in the configuration are followed
2146 by a letter in parenthesis, like TODO(t)."
2147 :group 'org-todo
2148 :type '(choice
2149 (const :tag "Never" nil)
2150 (const :tag "By default" t)
2151 (const :tag "Only with C-u C-c C-t" prefix)))
2153 (defcustom org-provide-todo-statistics t
2154 "Non-nil means update todo statistics after insert and toggle.
2155 ALL-HEADLINES means update todo statistics by including headlines
2156 with no TODO keyword as well, counting them as not done.
2157 A list of TODO keywords means the same, but skip keywords that are
2158 not in this list.
2160 When this is set, todo statistics is updated in the parent of the
2161 current entry each time a todo state is changed."
2162 :group 'org-todo
2163 :type '(choice
2164 (const :tag "Yes, only for TODO entries" t)
2165 (const :tag "Yes, including all entries" 'all-headlines)
2166 (repeat :tag "Yes, for TODOs in this list"
2167 (string :tag "TODO keyword"))
2168 (other :tag "No TODO statistics" nil)))
2170 (defcustom org-hierarchical-todo-statistics t
2171 "Non-nil means TODO statistics covers just direct children.
2172 When nil, all entries in the subtree are considered.
2173 This has only an effect if `org-provide-todo-statistics' is set.
2174 To set this to nil for only a single subtree, use a COOKIE_DATA
2175 property and include the word \"recursive\" into the value."
2176 :group 'org-todo
2177 :type 'boolean)
2179 (defcustom org-after-todo-state-change-hook nil
2180 "Hook which is run after the state of a TODO item was changed.
2181 The new state (a string with a TODO keyword, or nil) is available in the
2182 Lisp variable `state'."
2183 :group 'org-todo
2184 :type 'hook)
2186 (defvar org-blocker-hook nil
2187 "Hook for functions that are allowed to block a state change.
2189 Each function gets as its single argument a property list, see
2190 `org-trigger-hook' for more information about this list.
2192 If any of the functions in this hook returns nil, the state change
2193 is blocked.")
2195 (defvar org-trigger-hook nil
2196 "Hook for functions that are triggered by a state change.
2198 Each function gets as its single argument a property list with at least
2199 the following elements:
2201 (:type type-of-change :position pos-at-entry-start
2202 :from old-state :to new-state)
2204 Depending on the type, more properties may be present.
2206 This mechanism is currently implemented for:
2208 TODO state changes
2209 ------------------
2210 :type todo-state-change
2211 :from previous state (keyword as a string), or nil, or a symbol
2212 'todo' or 'done', to indicate the general type of state.
2213 :to new state, like in :from")
2215 (defcustom org-enforce-todo-dependencies nil
2216 "Non-nil means undone TODO entries will block switching the parent to DONE.
2217 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2218 be blocked if any prior sibling is not yet done.
2219 Finally, if the parent is blocked because of ordered siblings of its own,
2220 the child will also be blocked.
2221 This variable needs to be set before org.el is loaded, and you need to
2222 restart Emacs after a change to make the change effective. The only way
2223 to change is while Emacs is running is through the customize interface."
2224 :set (lambda (var val)
2225 (set var val)
2226 (if val
2227 (add-hook 'org-blocker-hook
2228 'org-block-todo-from-children-or-siblings-or-parent)
2229 (remove-hook 'org-blocker-hook
2230 'org-block-todo-from-children-or-siblings-or-parent)))
2231 :group 'org-todo
2232 :type 'boolean)
2234 (defcustom org-enforce-todo-checkbox-dependencies nil
2235 "Non-nil means unchecked boxes will block switching the parent to DONE.
2236 When this is nil, checkboxes have no influence on switching TODO states.
2237 When non-nil, you first need to check off all check boxes before the TODO
2238 entry can be switched to DONE.
2239 This variable needs to be set before org.el is loaded, and you need to
2240 restart Emacs after a change to make the change effective. The only way
2241 to change is while Emacs is running is through the customize interface."
2242 :set (lambda (var val)
2243 (set var val)
2244 (if val
2245 (add-hook 'org-blocker-hook
2246 'org-block-todo-from-checkboxes)
2247 (remove-hook 'org-blocker-hook
2248 'org-block-todo-from-checkboxes)))
2249 :group 'org-todo
2250 :type 'boolean)
2252 (defcustom org-treat-insert-todo-heading-as-state-change nil
2253 "Non-nil means inserting a TODO heading is treated as state change.
2254 So when the command \\[org-insert-todo-heading] is used, state change
2255 logging will apply if appropriate. When nil, the new TODO item will
2256 be inserted directly, and no logging will take place."
2257 :group 'org-todo
2258 :type 'boolean)
2260 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2261 "Non-nil means switching TODO states with S-cursor counts as state change.
2262 This is the default behavior. However, setting this to nil allows a
2263 convenient way to select a TODO state and bypass any logging associated
2264 with that."
2265 :group 'org-todo
2266 :type 'boolean)
2268 (defcustom org-todo-state-tags-triggers nil
2269 "Tag changes that should be triggered by TODO state changes.
2270 This is a list. Each entry is
2272 (state-change (tag . flag) .......)
2274 State-change can be a string with a state, and empty string to indicate the
2275 state that has no TODO keyword, or it can be one of the symbols `todo'
2276 or `done', meaning any not-done or done state, respectively."
2277 :group 'org-todo
2278 :group 'org-tags
2279 :type '(repeat
2280 (cons (choice :tag "When changing to"
2281 (const :tag "Not-done state" todo)
2282 (const :tag "Done state" done)
2283 (string :tag "State"))
2284 (repeat
2285 (cons :tag "Tag action"
2286 (string :tag "Tag")
2287 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2289 (defcustom org-log-done nil
2290 "Information to record when a task moves to the DONE state.
2292 Possible values are:
2294 nil Don't add anything, just change the keyword
2295 time Add a time stamp to the task
2296 note Prompt for a note and add it with template `org-log-note-headings'
2298 This option can also be set with on a per-file-basis with
2300 #+STARTUP: nologdone
2301 #+STARTUP: logdone
2302 #+STARTUP: lognotedone
2304 You can have local logging settings for a subtree by setting the LOGGING
2305 property to one or more of these keywords."
2306 :group 'org-todo
2307 :group 'org-progress
2308 :type '(choice
2309 (const :tag "No logging" nil)
2310 (const :tag "Record CLOSED timestamp" time)
2311 (const :tag "Record CLOSED timestamp with note." note)))
2313 ;; Normalize old uses of org-log-done.
2314 (cond
2315 ((eq org-log-done t) (setq org-log-done 'time))
2316 ((and (listp org-log-done) (memq 'done org-log-done))
2317 (setq org-log-done 'note)))
2319 (defcustom org-log-reschedule nil
2320 "Information to record when the scheduling date of a tasks is modified.
2322 Possible values are:
2324 nil Don't add anything, just change the date
2325 time Add a time stamp to the task
2326 note Prompt for a note and add it with template `org-log-note-headings'
2328 This option can also be set with on a per-file-basis with
2330 #+STARTUP: nologreschedule
2331 #+STARTUP: logreschedule
2332 #+STARTUP: lognotereschedule"
2333 :group 'org-todo
2334 :group 'org-progress
2335 :type '(choice
2336 (const :tag "No logging" nil)
2337 (const :tag "Record timestamp" time)
2338 (const :tag "Record timestamp with note." note)))
2340 (defcustom org-log-redeadline nil
2341 "Information to record when the deadline date of a tasks is modified.
2343 Possible values are:
2345 nil Don't add anything, just change the date
2346 time Add a time stamp to the task
2347 note Prompt for a note and add it with template `org-log-note-headings'
2349 This option can also be set with on a per-file-basis with
2351 #+STARTUP: nologredeadline
2352 #+STARTUP: logredeadline
2353 #+STARTUP: lognoteredeadline
2355 You can have local logging settings for a subtree by setting the LOGGING
2356 property to one or more of these keywords."
2357 :group 'org-todo
2358 :group 'org-progress
2359 :type '(choice
2360 (const :tag "No logging" nil)
2361 (const :tag "Record timestamp" time)
2362 (const :tag "Record timestamp with note." note)))
2364 (defcustom org-log-note-clock-out nil
2365 "Non-nil means record a note when clocking out of an item.
2366 This can also be configured on a per-file basis by adding one of
2367 the following lines anywhere in the buffer:
2369 #+STARTUP: lognoteclock-out
2370 #+STARTUP: nolognoteclock-out"
2371 :group 'org-todo
2372 :group 'org-progress
2373 :type 'boolean)
2375 (defcustom org-log-done-with-time t
2376 "Non-nil means the CLOSED time stamp will contain date and time.
2377 When nil, only the date will be recorded."
2378 :group 'org-progress
2379 :type 'boolean)
2381 (defcustom org-log-note-headings
2382 '((done . "CLOSING NOTE %t")
2383 (state . "State %-12s from %-12S %t")
2384 (note . "Note taken on %t")
2385 (reschedule . "Rescheduled from %S on %t")
2386 (delschedule . "Not scheduled, was %S on %t")
2387 (redeadline . "New deadline from %S on %t")
2388 (deldeadline . "Removed deadline, was %S on %t")
2389 (refile . "Refiled on %t")
2390 (clock-out . ""))
2391 "Headings for notes added to entries.
2392 The value is an alist, with the car being a symbol indicating the note
2393 context, and the cdr is the heading to be used. The heading may also be the
2394 empty string.
2395 %t in the heading will be replaced by a time stamp.
2396 %T will be an active time stamp instead the default inactive one
2397 %d will be replaced by a short-format time stamp.
2398 %D will be replaced by an active short-format time stamp.
2399 %s will be replaced by the new TODO state, in double quotes.
2400 %S will be replaced by the old TODO state, in double quotes.
2401 %u will be replaced by the user name.
2402 %U will be replaced by the full user name.
2404 In fact, it is not a good idea to change the `state' entry, because
2405 agenda log mode depends on the format of these entries."
2406 :group 'org-todo
2407 :group 'org-progress
2408 :type '(list :greedy t
2409 (cons (const :tag "Heading when closing an item" done) string)
2410 (cons (const :tag
2411 "Heading when changing todo state (todo sequence only)"
2412 state) string)
2413 (cons (const :tag "Heading when just taking a note" note) string)
2414 (cons (const :tag "Heading when clocking out" clock-out) string)
2415 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2416 (cons (const :tag "Heading when rescheduling" reschedule) string)
2417 (cons (const :tag "Heading when changing deadline" redeadline) string)
2418 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2419 (cons (const :tag "Heading when refiling" refile) string)))
2421 (unless (assq 'note org-log-note-headings)
2422 (push '(note . "%t") org-log-note-headings))
2424 (defcustom org-log-into-drawer nil
2425 "Non-nil means insert state change notes and time stamps into a drawer.
2426 When nil, state changes notes will be inserted after the headline and
2427 any scheduling and clock lines, but not inside a drawer.
2429 The value of this variable should be the name of the drawer to use.
2430 LOGBOOK is proposed as the default drawer for this purpose, you can
2431 also set this to a string to define the drawer of your choice.
2433 A value of t is also allowed, representing \"LOGBOOK\".
2435 If this variable is set, `org-log-state-notes-insert-after-drawers'
2436 will be ignored.
2438 You can set the property LOG_INTO_DRAWER to overrule this setting for
2439 a subtree."
2440 :group 'org-todo
2441 :group 'org-progress
2442 :type '(choice
2443 (const :tag "Not into a drawer" nil)
2444 (const :tag "LOGBOOK" t)
2445 (string :tag "Other")))
2447 (if (fboundp 'defvaralias)
2448 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2450 (defun org-log-into-drawer ()
2451 "Return the value of `org-log-into-drawer', but let properties overrule.
2452 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2453 used instead of the default value."
2454 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2455 (cond
2456 ((or (not p) (equal p "nil")) org-log-into-drawer)
2457 ((equal p "t") "LOGBOOK")
2458 (t p))))
2460 (defcustom org-log-state-notes-insert-after-drawers nil
2461 "Non-nil means insert state change notes after any drawers in entry.
2462 Only the drawers that *immediately* follow the headline and the
2463 deadline/scheduled line are skipped.
2464 When nil, insert notes right after the heading and perhaps the line
2465 with deadline/scheduling if present.
2467 This variable will have no effect if `org-log-into-drawer' is
2468 set."
2469 :group 'org-todo
2470 :group 'org-progress
2471 :type 'boolean)
2473 (defcustom org-log-states-order-reversed t
2474 "Non-nil means the latest state note will be directly after heading.
2475 When nil, the state change notes will be ordered according to time."
2476 :group 'org-todo
2477 :group 'org-progress
2478 :type 'boolean)
2480 (defcustom org-todo-repeat-to-state nil
2481 "The TODO state to which a repeater should return the repeating task.
2482 By default this is the first task in a TODO sequence, or the previous state
2483 in a TODO_TYP set. But you can specify another task here.
2484 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2485 :group 'org-todo
2486 :type '(choice (const :tag "Head of sequence" nil)
2487 (string :tag "Specific state")))
2489 (defcustom org-log-repeat 'time
2490 "Non-nil means record moving through the DONE state when triggering repeat.
2491 An auto-repeating task is immediately switched back to TODO when
2492 marked DONE. If you are not logging state changes (by adding \"@\"
2493 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2494 record a closing note, there will be no record of the task moving
2495 through DONE. This variable forces taking a note anyway.
2497 nil Don't force a record
2498 time Record a time stamp
2499 note Record a note
2501 This option can also be set with on a per-file-basis with
2503 #+STARTUP: logrepeat
2504 #+STARTUP: lognoterepeat
2505 #+STARTUP: nologrepeat
2507 You can have local logging settings for a subtree by setting the LOGGING
2508 property to one or more of these keywords."
2509 :group 'org-todo
2510 :group 'org-progress
2511 :type '(choice
2512 (const :tag "Don't force a record" nil)
2513 (const :tag "Force recording the DONE state" time)
2514 (const :tag "Force recording a note with the DONE state" note)))
2517 (defgroup org-priorities nil
2518 "Priorities in Org-mode."
2519 :tag "Org Priorities"
2520 :group 'org-todo)
2522 (defcustom org-enable-priority-commands t
2523 "Non-nil means priority commands are active.
2524 When nil, these commands will be disabled, so that you never accidentally
2525 set a priority."
2526 :group 'org-priorities
2527 :type 'boolean)
2529 (defcustom org-highest-priority ?A
2530 "The highest priority of TODO items. A character like ?A, ?B etc.
2531 Must have a smaller ASCII number than `org-lowest-priority'."
2532 :group 'org-priorities
2533 :type 'character)
2535 (defcustom org-lowest-priority ?C
2536 "The lowest priority of TODO items. A character like ?A, ?B etc.
2537 Must have a larger ASCII number than `org-highest-priority'."
2538 :group 'org-priorities
2539 :type 'character)
2541 (defcustom org-default-priority ?B
2542 "The default priority of TODO items.
2543 This is the priority an item gets if no explicit priority is given.
2544 When starting to cycle on an empty priority the first step in the cycle
2545 depends on `org-priority-start-cycle-with-default'. The resulting first
2546 step priority must not exceed the range from `org-highest-priority' to
2547 `org-lowest-priority' which means that `org-default-priority' has to be
2548 in this range exclusive or inclusive the range boundaries. Else the
2549 first step refuses to set the default and the second will fall back
2550 to (depending on the command used) the highest or lowest priority."
2551 :group 'org-priorities
2552 :type 'character)
2554 (defcustom org-priority-start-cycle-with-default t
2555 "Non-nil means start with default priority when starting to cycle.
2556 When this is nil, the first step in the cycle will be (depending on the
2557 command used) one higher or lower than the default priority.
2558 See also `org-default-priority'."
2559 :group 'org-priorities
2560 :type 'boolean)
2562 (defcustom org-get-priority-function nil
2563 "Function to extract the priority from a string.
2564 The string is normally the headline. If this is nil Org computes the
2565 priority from the priority cookie like [#A] in the headline. It returns
2566 an integer, increasing by 1000 for each priority level.
2567 The user can set a different function here, which should take a string
2568 as an argument and return the numeric priority."
2569 :group 'org-priorities
2570 :type 'function)
2572 (defgroup org-time nil
2573 "Options concerning time stamps and deadlines in Org-mode."
2574 :tag "Org Time"
2575 :group 'org)
2577 (defcustom org-insert-labeled-timestamps-at-point nil
2578 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2579 When nil, these labeled time stamps are forces into the second line of an
2580 entry, just after the headline. When scheduling from the global TODO list,
2581 the time stamp will always be forced into the second line."
2582 :group 'org-time
2583 :type 'boolean)
2585 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2586 "Formats for `format-time-string' which are used for time stamps.
2587 It is not recommended to change this constant.")
2589 (defcustom org-time-stamp-rounding-minutes '(0 5)
2590 "Number of minutes to round time stamps to.
2591 These are two values, the first applies when first creating a time stamp.
2592 The second applies when changing it with the commands `S-up' and `S-down'.
2593 When changing the time stamp, this means that it will change in steps
2594 of N minutes, as given by the second value.
2596 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2597 numbers should be factors of 60, so for example 5, 10, 15.
2599 When this is larger than 1, you can still force an exact time stamp by using
2600 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2601 and by using a prefix arg to `S-up/down' to specify the exact number
2602 of minutes to shift."
2603 :group 'org-time
2604 :get #'(lambda (var) ; Make sure both elements are there
2605 (if (integerp (default-value var))
2606 (list (default-value var) 5)
2607 (default-value var)))
2608 :type '(list
2609 (integer :tag "when inserting times")
2610 (integer :tag "when modifying times")))
2612 ;; Normalize old customizations of this variable.
2613 (when (integerp org-time-stamp-rounding-minutes)
2614 (setq org-time-stamp-rounding-minutes
2615 (list org-time-stamp-rounding-minutes
2616 org-time-stamp-rounding-minutes)))
2618 (defcustom org-display-custom-times nil
2619 "Non-nil means overlay custom formats over all time stamps.
2620 The formats are defined through the variable `org-time-stamp-custom-formats'.
2621 To turn this on on a per-file basis, insert anywhere in the file:
2622 #+STARTUP: customtime"
2623 :group 'org-time
2624 :set 'set-default
2625 :type 'sexp)
2626 (make-variable-buffer-local 'org-display-custom-times)
2628 (defcustom org-time-stamp-custom-formats
2629 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2630 "Custom formats for time stamps. See `format-time-string' for the syntax.
2631 These are overlayed over the default ISO format if the variable
2632 `org-display-custom-times' is set. Time like %H:%M should be at the
2633 end of the second format. The custom formats are also honored by export
2634 commands, if custom time display is turned on at the time of export."
2635 :group 'org-time
2636 :type 'sexp)
2638 (defun org-time-stamp-format (&optional long inactive)
2639 "Get the right format for a time string."
2640 (let ((f (if long (cdr org-time-stamp-formats)
2641 (car org-time-stamp-formats))))
2642 (if inactive
2643 (concat "[" (substring f 1 -1) "]")
2644 f)))
2646 (defcustom org-time-clocksum-format "%d:%02d"
2647 "The format string used when creating CLOCKSUM lines.
2648 This is also used when org-mode generates a time duration."
2649 :group 'org-time
2650 :type 'string)
2652 (defcustom org-time-clocksum-use-fractional nil
2653 "If non-nil, \\[org-clock-display] uses fractional times.
2654 org-mode generates a time duration."
2655 :group 'org-time
2656 :type 'boolean)
2658 (defcustom org-time-clocksum-fractional-format "%.2f"
2659 "The format string used when creating CLOCKSUM lines, or when
2660 org-mode generates a time duration."
2661 :group 'org-time
2662 :type 'string)
2664 (defcustom org-deadline-warning-days 14
2665 "No. of days before expiration during which a deadline becomes active.
2666 This variable governs the display in sparse trees and in the agenda.
2667 When 0 or negative, it means use this number (the absolute value of it)
2668 even if a deadline has a different individual lead time specified.
2670 Custom commands can set this variable in the options section."
2671 :group 'org-time
2672 :group 'org-agenda-daily/weekly
2673 :type 'integer)
2675 (defcustom org-read-date-prefer-future t
2676 "Non-nil means assume future for incomplete date input from user.
2677 This affects the following situations:
2678 1. The user gives a month but not a year.
2679 For example, if it is April and you enter \"feb 2\", this will be read
2680 as Feb 2, *next* year. \"May 5\", however, will be this year.
2681 2. The user gives a day, but no month.
2682 For example, if today is the 15th, and you enter \"3\", Org-mode will
2683 read this as the third of *next* month. However, if you enter \"17\",
2684 it will be considered as *this* month.
2686 If you set this variable to the symbol `time', then also the following
2687 will work:
2689 3. If the user gives a time, but no day. If the time is before now,
2690 to will be interpreted as tomorrow.
2692 Currently none of this works for ISO week specifications.
2694 When this option is nil, the current day, month and year will always be
2695 used as defaults.
2697 See also `org-agenda-jump-prefer-future'."
2698 :group 'org-time
2699 :type '(choice
2700 (const :tag "Never" nil)
2701 (const :tag "Check month and day" t)
2702 (const :tag "Check month, day, and time" time)))
2704 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2705 "Should the agenda jump command prefer the future for incomplete dates?
2706 The default is to do the same as configured in `org-read-date-prefer-future'.
2707 But you can also set a deviating value here.
2708 This may t or nil, or the symbol `org-read-date-prefer-future'."
2709 :group 'org-agenda
2710 :group 'org-time
2711 :type '(choice
2712 (const :tag "Use org-read-date-prefer-future"
2713 org-read-date-prefer-future)
2714 (const :tag "Never" nil)
2715 (const :tag "Always" t)))
2717 (defcustom org-read-date-force-compatible-dates t
2718 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2720 Depending on the system Emacs is running on, certain dates cannot
2721 be represented with the type used internally to represent time.
2722 Dates between 1970-1-1 and 2038-1-1 can always be represented
2723 correctly. Some systems allow for earlier dates, some for later,
2724 some for both. One way to find out it to insert any date into an
2725 Org buffer, putting the cursor on the year and hitting S-up and
2726 S-down to test the range.
2728 When this variable is set to t, the date/time prompt will not let
2729 you specify dates outside the 1970-2037 range, so it is certain that
2730 these dates will work in whatever version of Emacs you are
2731 running, and also that you can move a file from one Emacs implementation
2732 to another. WHenever Org is forcing the year for you, it will display
2733 a message and beep.
2735 When this variable is nil, Org will check if the date is
2736 representable in the specific Emacs implementation you are using.
2737 If not, it will force a year, usually the current year, and beep
2738 to remind you. Currently this setting is not recommended because
2739 the likelihood that you will open your Org files in an Emacs that
2740 has limited date range is not negligible.
2742 A workaround for this problem is to use diary sexp dates for time
2743 stamps outside of this range."
2744 :group 'org-time
2745 :type 'boolean)
2747 (defcustom org-read-date-display-live t
2748 "Non-nil means display current interpretation of date prompt live.
2749 This display will be in an overlay, in the minibuffer."
2750 :group 'org-time
2751 :type 'boolean)
2753 (defcustom org-read-date-popup-calendar t
2754 "Non-nil means pop up a calendar when prompting for a date.
2755 In the calendar, the date can be selected with mouse-1. However, the
2756 minibuffer will also be active, and you can simply enter the date as well.
2757 When nil, only the minibuffer will be available."
2758 :group 'org-time
2759 :type 'boolean)
2760 (if (fboundp 'defvaralias)
2761 (defvaralias 'org-popup-calendar-for-date-prompt
2762 'org-read-date-popup-calendar))
2764 (defcustom org-read-date-minibuffer-setup-hook nil
2765 "Hook to be used to set up keys for the date/time interface.
2766 Add key definitions to `minibuffer-local-map', which will be a temporary
2767 copy."
2768 :group 'org-time
2769 :type 'hook)
2771 (defcustom org-extend-today-until 0
2772 "The hour when your day really ends. Must be an integer.
2773 This has influence for the following applications:
2774 - When switching the agenda to \"today\". It it is still earlier than
2775 the time given here, the day recognized as TODAY is actually yesterday.
2776 - When a date is read from the user and it is still before the time given
2777 here, the current date and time will be assumed to be yesterday, 23:59.
2778 Also, timestamps inserted in remember templates follow this rule.
2780 IMPORTANT: This is a feature whose implementation is and likely will
2781 remain incomplete. Really, it is only here because past midnight seems to
2782 be the favorite working time of John Wiegley :-)"
2783 :group 'org-time
2784 :type 'integer)
2786 (defcustom org-use-effective-time nil
2787 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2788 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2789 \"effective time\" of any timestamps between midnight and 8am will be
2790 23:59 of the previous day."
2791 :group 'boolean
2792 :type 'integer)
2794 (defcustom org-edit-timestamp-down-means-later nil
2795 "Non-nil means S-down will increase the time in a time stamp.
2796 When nil, S-up will increase."
2797 :group 'org-time
2798 :type 'boolean)
2800 (defcustom org-calendar-follow-timestamp-change t
2801 "Non-nil means make the calendar window follow timestamp changes.
2802 When a timestamp is modified and the calendar window is visible, it will be
2803 moved to the new date."
2804 :group 'org-time
2805 :type 'boolean)
2807 (defgroup org-tags nil
2808 "Options concerning tags in Org-mode."
2809 :tag "Org Tags"
2810 :group 'org)
2812 (defcustom org-tag-alist nil
2813 "List of tags allowed in Org-mode files.
2814 When this list is nil, Org-mode will base TAG input on what is already in the
2815 buffer.
2816 The value of this variable is an alist, the car of each entry must be a
2817 keyword as a string, the cdr may be a character that is used to select
2818 that tag through the fast-tag-selection interface.
2819 See the manual for details."
2820 :group 'org-tags
2821 :type '(repeat
2822 (choice
2823 (cons (string :tag "Tag name")
2824 (character :tag "Access char"))
2825 (list :tag "Start radio group"
2826 (const :startgroup)
2827 (option (string :tag "Group description")))
2828 (list :tag "End radio group"
2829 (const :endgroup)
2830 (option (string :tag "Group description")))
2831 (const :tag "New line" (:newline)))))
2833 (defcustom org-tag-persistent-alist nil
2834 "List of tags that will always appear in all Org-mode files.
2835 This is in addition to any in buffer settings or customizations
2836 of `org-tag-alist'.
2837 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2838 The value of this variable is an alist, the car of each entry must be a
2839 keyword as a string, the cdr may be a character that is used to select
2840 that tag through the fast-tag-selection interface.
2841 See the manual for details.
2842 To disable these tags on a per-file basis, insert anywhere in the file:
2843 #+STARTUP: noptag"
2844 :group 'org-tags
2845 :type '(repeat
2846 (choice
2847 (cons (string :tag "Tag name")
2848 (character :tag "Access char"))
2849 (const :tag "Start radio group" (:startgroup))
2850 (const :tag "End radio group" (:endgroup))
2851 (const :tag "New line" (:newline)))))
2853 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2854 "If non-nil, always offer completion for all tags of all agenda files.
2855 Instead of customizing this variable directly, you might want to
2856 set it locally for capture buffers, because there no list of
2857 tags in that file can be created dynamically (there are none).
2859 (add-hook 'org-capture-mode-hook
2860 (lambda ()
2861 (set (make-local-variable
2862 'org-complete-tags-always-offer-all-agenda-tags)
2863 t)))"
2864 :group 'org-tags
2865 :type 'boolean)
2867 (defvar org-file-tags nil
2868 "List of tags that can be inherited by all entries in the file.
2869 The tags will be inherited if the variable `org-use-tag-inheritance'
2870 says they should be.
2871 This variable is populated from #+FILETAGS lines.")
2873 (defcustom org-use-fast-tag-selection 'auto
2874 "Non-nil means use fast tag selection scheme.
2875 This is a special interface to select and deselect tags with single keys.
2876 When nil, fast selection is never used.
2877 When the symbol `auto', fast selection is used if and only if selection
2878 characters for tags have been configured, either through the variable
2879 `org-tag-alist' or through a #+TAGS line in the buffer.
2880 When t, fast selection is always used and selection keys are assigned
2881 automatically if necessary."
2882 :group 'org-tags
2883 :type '(choice
2884 (const :tag "Always" t)
2885 (const :tag "Never" nil)
2886 (const :tag "When selection characters are configured" 'auto)))
2888 (defcustom org-fast-tag-selection-single-key nil
2889 "Non-nil means fast tag selection exits after first change.
2890 When nil, you have to press RET to exit it.
2891 During fast tag selection, you can toggle this flag with `C-c'.
2892 This variable can also have the value `expert'. In this case, the window
2893 displaying the tags menu is not even shown, until you press C-c again."
2894 :group 'org-tags
2895 :type '(choice
2896 (const :tag "No" nil)
2897 (const :tag "Yes" t)
2898 (const :tag "Expert" expert)))
2900 (defvar org-fast-tag-selection-include-todo nil
2901 "Non-nil means fast tags selection interface will also offer TODO states.
2902 This is an undocumented feature, you should not rely on it.")
2904 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2905 "The column to which tags should be indented in a headline.
2906 If this number is positive, it specifies the column. If it is negative,
2907 it means that the tags should be flushright to that column. For example,
2908 -80 works well for a normal 80 character screen.
2909 When 0, place tags directly after headline text, with only one space in
2910 between."
2911 :group 'org-tags
2912 :type 'integer)
2914 (defcustom org-auto-align-tags t
2915 "Non-nil keeps tags aligned when modifying headlines.
2916 Some operations (i.e. demoting) change the length of a headline and
2917 therefore shift the tags around. With this option turned on, after
2918 each such operation the tags are again aligned to `org-tags-column'."
2919 :group 'org-tags
2920 :type 'boolean)
2922 (defcustom org-use-tag-inheritance t
2923 "Non-nil means tags in levels apply also for sublevels.
2924 When nil, only the tags directly given in a specific line apply there.
2925 This may also be a list of tags that should be inherited, or a regexp that
2926 matches tags that should be inherited. Additional control is possible
2927 with the variable `org-tags-exclude-from-inheritance' which gives an
2928 explicit list of tags to be excluded from inheritance., even if the value of
2929 `org-use-tag-inheritance' would select it for inheritance.
2931 If this option is t, a match early-on in a tree can lead to a large
2932 number of matches in the subtree when constructing the agenda or creating
2933 a sparse tree. If you only want to see the first match in a tree during
2934 a search, check out the variable `org-tags-match-list-sublevels'."
2935 :group 'org-tags
2936 :type '(choice
2937 (const :tag "Not" nil)
2938 (const :tag "Always" t)
2939 (repeat :tag "Specific tags" (string :tag "Tag"))
2940 (regexp :tag "Tags matched by regexp")))
2942 (defcustom org-tags-exclude-from-inheritance nil
2943 "List of tags that should never be inherited.
2944 This is a way to exclude a few tags from inheritance. For way to do
2945 the opposite, to actively allow inheritance for selected tags,
2946 see the variable `org-use-tag-inheritance'."
2947 :group 'org-tags
2948 :type '(repeat (string :tag "Tag")))
2950 (defun org-tag-inherit-p (tag)
2951 "Check if TAG is one that should be inherited."
2952 (cond
2953 ((member tag org-tags-exclude-from-inheritance) nil)
2954 ((eq org-use-tag-inheritance t) t)
2955 ((not org-use-tag-inheritance) nil)
2956 ((stringp org-use-tag-inheritance)
2957 (string-match org-use-tag-inheritance tag))
2958 ((listp org-use-tag-inheritance)
2959 (member tag org-use-tag-inheritance))
2960 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2962 (defcustom org-tags-match-list-sublevels t
2963 "Non-nil means list also sublevels of headlines matching a search.
2964 This variable applies to tags/property searches, and also to stuck
2965 projects because this search is based on a tags match as well.
2967 When set to the symbol `indented', sublevels are indented with
2968 leading dots.
2970 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2971 the sublevels of a headline matching a tag search often also match
2972 the same search. Listing all of them can create very long lists.
2973 Setting this variable to nil causes subtrees of a match to be skipped.
2975 This variable is semi-obsolete and probably should always be true. It
2976 is better to limit inheritance to certain tags using the variables
2977 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2978 :group 'org-tags
2979 :type '(choice
2980 (const :tag "No, don't list them" nil)
2981 (const :tag "Yes, do list them" t)
2982 (const :tag "List them, indented with leading dots" indented)))
2984 (defcustom org-tags-sort-function nil
2985 "When set, tags are sorted using this function as a comparator."
2986 :group 'org-tags
2987 :type '(choice
2988 (const :tag "No sorting" nil)
2989 (const :tag "Alphabetical" string<)
2990 (const :tag "Reverse alphabetical" string>)
2991 (function :tag "Custom function" nil)))
2993 (defvar org-tags-history nil
2994 "History of minibuffer reads for tags.")
2995 (defvar org-last-tags-completion-table nil
2996 "The last used completion table for tags.")
2997 (defvar org-after-tags-change-hook nil
2998 "Hook that is run after the tags in a line have changed.")
3000 (defgroup org-properties nil
3001 "Options concerning properties in Org-mode."
3002 :tag "Org Properties"
3003 :group 'org)
3005 (defcustom org-property-format "%-10s %s"
3006 "How property key/value pairs should be formatted by `indent-line'.
3007 When `indent-line' hits a property definition, it will format the line
3008 according to this format, mainly to make sure that the values are
3009 lined-up with respect to each other."
3010 :group 'org-properties
3011 :type 'string)
3013 (defcustom org-properties-postprocess-alist nil
3014 "Alist of properties and functions to adjust inserted values.
3015 Elements of this alist must be of the form
3017 ([string] [function])
3019 where [string] must be a property name and [function] must be a
3020 lambda expression: this lambda expression must take one argument,
3021 the value to adjust, and return the new value as a string.
3023 For example, this element will allow the property \"Remaining\"
3024 to be updated wrt the relation between the \"Effort\" property
3025 and the clock summary:
3027 ((\"Remaining\" (lambda(value)
3028 (let ((clocksum (org-clock-sum-current-item))
3029 (effort (org-duration-string-to-minutes
3030 (org-entry-get (point) \"Effort\"))))
3031 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3032 :group 'org-properties
3033 :type 'alist)
3035 (defcustom org-use-property-inheritance nil
3036 "Non-nil means properties apply also for sublevels.
3038 This setting is chiefly used during property searches. Turning it on can
3039 cause significant overhead when doing a search, which is why it is not
3040 on by default.
3042 When nil, only the properties directly given in the current entry count.
3043 When t, every property is inherited. The value may also be a list of
3044 properties that should have inheritance, or a regular expression matching
3045 properties that should be inherited.
3047 However, note that some special properties use inheritance under special
3048 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3049 and the properties ending in \"_ALL\" when they are used as descriptor
3050 for valid values of a property.
3052 Note for programmers:
3053 When querying an entry with `org-entry-get', you can control if inheritance
3054 should be used. By default, `org-entry-get' looks only at the local
3055 properties. You can request inheritance by setting the inherit argument
3056 to t (to force inheritance) or to `selective' (to respect the setting
3057 in this variable)."
3058 :group 'org-properties
3059 :type '(choice
3060 (const :tag "Not" nil)
3061 (const :tag "Always" t)
3062 (repeat :tag "Specific properties" (string :tag "Property"))
3063 (regexp :tag "Properties matched by regexp")))
3065 (defun org-property-inherit-p (property)
3066 "Check if PROPERTY is one that should be inherited."
3067 (cond
3068 ((eq org-use-property-inheritance t) t)
3069 ((not org-use-property-inheritance) nil)
3070 ((stringp org-use-property-inheritance)
3071 (string-match org-use-property-inheritance property))
3072 ((listp org-use-property-inheritance)
3073 (member property org-use-property-inheritance))
3074 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3076 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3077 "The default column format, if no other format has been defined.
3078 This variable can be set on the per-file basis by inserting a line
3080 #+COLUMNS: %25ITEM ....."
3081 :group 'org-properties
3082 :type 'string)
3084 (defcustom org-columns-ellipses ".."
3085 "The ellipses to be used when a field in column view is truncated.
3086 When this is the empty string, as many characters as possible are shown,
3087 but then there will be no visual indication that the field has been truncated.
3088 When this is a string of length N, the last N characters of a truncated
3089 field are replaced by this string. If the column is narrower than the
3090 ellipses string, only part of the ellipses string will be shown."
3091 :group 'org-properties
3092 :type 'string)
3094 (defcustom org-columns-modify-value-for-display-function nil
3095 "Function that modifies values for display in column view.
3096 For example, it can be used to cut out a certain part from a time stamp.
3097 The function must take 2 arguments:
3099 column-title The title of the column (*not* the property name)
3100 value The value that should be modified.
3102 The function should return the value that should be displayed,
3103 or nil if the normal value should be used."
3104 :group 'org-properties
3105 :type 'function)
3107 (defcustom org-effort-property "Effort"
3108 "The property that is being used to keep track of effort estimates.
3109 Effort estimates given in this property need to have the format H:MM."
3110 :group 'org-properties
3111 :group 'org-progress
3112 :type '(string :tag "Property"))
3114 (defconst org-global-properties-fixed
3115 '(("VISIBILITY_ALL" . "folded children content all")
3116 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3117 "List of property/value pairs that can be inherited by any entry.
3119 These are fixed values, for the preset properties. The user variable
3120 that can be used to add to this list is `org-global-properties'.
3122 The entries in this list are cons cells where the car is a property
3123 name and cdr is a string with the value. If the value represents
3124 multiple items like an \"_ALL\" property, separate the items by
3125 spaces.")
3127 (defcustom org-global-properties nil
3128 "List of property/value pairs that can be inherited by any entry.
3130 This list will be combined with the constant `org-global-properties-fixed'.
3132 The entries in this list are cons cells where the car is a property
3133 name and cdr is a string with the value.
3135 You can set buffer-local values for the same purpose in the variable
3136 `org-file-properties' this by adding lines like
3138 #+PROPERTY: NAME VALUE"
3139 :group 'org-properties
3140 :type '(repeat
3141 (cons (string :tag "Property")
3142 (string :tag "Value"))))
3144 (defvar org-file-properties nil
3145 "List of property/value pairs that can be inherited by any entry.
3146 Valid for the current buffer.
3147 This variable is populated from #+PROPERTY lines.")
3148 (make-variable-buffer-local 'org-file-properties)
3150 (defgroup org-agenda nil
3151 "Options concerning agenda views in Org-mode."
3152 :tag "Org Agenda"
3153 :group 'org)
3155 (defvar org-category nil
3156 "Variable used by org files to set a category for agenda display.
3157 Such files should use a file variable to set it, for example
3159 # -*- mode: org; org-category: \"ELisp\"
3161 or contain a special line
3163 #+CATEGORY: ELisp
3165 If the file does not specify a category, then file's base name
3166 is used instead.")
3167 (make-variable-buffer-local 'org-category)
3168 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3170 (defcustom org-agenda-files nil
3171 "The files to be used for agenda display.
3172 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3173 \\[org-remove-file]. You can also use customize to edit the list.
3175 If an entry is a directory, all files in that directory that are matched by
3176 `org-agenda-file-regexp' will be part of the file list.
3178 If the value of the variable is not a list but a single file name, then
3179 the list of agenda files is actually stored and maintained in that file, one
3180 agenda file per line. In this file paths can be given relative to
3181 `org-directory'. Tilde expansion and environment variable substitution
3182 are also made."
3183 :group 'org-agenda
3184 :type '(choice
3185 (repeat :tag "List of files and directories" file)
3186 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3188 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3189 "Regular expression to match files for `org-agenda-files'.
3190 If any element in the list in that variable contains a directory instead
3191 of a normal file, all files in that directory that are matched by this
3192 regular expression will be included."
3193 :group 'org-agenda
3194 :type 'regexp)
3196 (defcustom org-agenda-text-search-extra-files nil
3197 "List of extra files to be searched by text search commands.
3198 These files will be search in addition to the agenda files by the
3199 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3200 Note that these files will only be searched for text search commands,
3201 not for the other agenda views like todo lists, tag searches or the weekly
3202 agenda. This variable is intended to list notes and possibly archive files
3203 that should also be searched by these two commands.
3204 In fact, if the first element in the list is the symbol `agenda-archives',
3205 than all archive files of all agenda files will be added to the search
3206 scope."
3207 :group 'org-agenda
3208 :type '(set :greedy t
3209 (const :tag "Agenda Archives" agenda-archives)
3210 (repeat :inline t (file))))
3212 (if (fboundp 'defvaralias)
3213 (defvaralias 'org-agenda-multi-occur-extra-files
3214 'org-agenda-text-search-extra-files))
3216 (defcustom org-agenda-skip-unavailable-files nil
3217 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3218 A nil value means to remove them, after a query, from the list."
3219 :group 'org-agenda
3220 :type 'boolean)
3222 (defcustom org-calendar-to-agenda-key [?c]
3223 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3224 The command `org-calendar-goto-agenda' will be bound to this key. The
3225 default is the character `c' because then `c' can be used to switch back and
3226 forth between agenda and calendar."
3227 :group 'org-agenda
3228 :type 'sexp)
3230 (defcustom org-calendar-agenda-action-key [?k]
3231 "The key to be installed in `calendar-mode-map' for agenda-action.
3232 The command `org-agenda-action' will be bound to this key. The
3233 default is the character `k' because we use the same key in the agenda."
3234 :group 'org-agenda
3235 :type 'sexp)
3237 (defcustom org-calendar-insert-diary-entry-key [?i]
3238 "The key to be installed in `calendar-mode-map' for adding diary entries.
3239 This option is irrelevant until `org-agenda-diary-file' has been configured
3240 to point to an Org-mode file. When that is the case, the command
3241 `org-agenda-diary-entry' will be bound to the key given here, by default
3242 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3243 if you want to continue doing this, you need to change this to a different
3244 key."
3245 :group 'org-agenda
3246 :type 'sexp)
3248 (defcustom org-agenda-diary-file 'diary-file
3249 "File to which to add new entries with the `i' key in agenda and calendar.
3250 When this is the symbol `diary-file', the functionality in the Emacs
3251 calendar will be used to add entries to the `diary-file'. But when this
3252 points to a file, `org-agenda-diary-entry' will be used instead."
3253 :group 'org-agenda
3254 :type '(choice
3255 (const :tag "The standard Emacs diary file" diary-file)
3256 (file :tag "Special Org file diary entries")))
3258 (eval-after-load "calendar"
3259 '(progn
3260 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3261 'org-calendar-goto-agenda)
3262 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3263 'org-agenda-action)
3264 (add-hook 'calendar-mode-hook
3265 (lambda ()
3266 (unless (eq org-agenda-diary-file 'diary-file)
3267 (define-key calendar-mode-map
3268 org-calendar-insert-diary-entry-key
3269 'org-agenda-diary-entry))))))
3271 (defgroup org-latex nil
3272 "Options for embedding LaTeX code into Org-mode."
3273 :tag "Org LaTeX"
3274 :group 'org)
3276 (defcustom org-format-latex-options
3277 '(:foreground default :background default :scale 1.0
3278 :html-foreground "Black" :html-background "Transparent"
3279 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3280 "Options for creating images from LaTeX fragments.
3281 This is a property list with the following properties:
3282 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3283 `default' means use the foreground of the default face.
3284 :background the background color, or \"Transparent\".
3285 `default' means use the background of the default face.
3286 :scale a scaling factor for the size of the images, to get more pixels
3287 :html-foreground, :html-background, :html-scale
3288 the same numbers for HTML export.
3289 :matchers a list indicating which matchers should be used to
3290 find LaTeX fragments. Valid members of this list are:
3291 \"begin\" find environments
3292 \"$1\" find single characters surrounded by $.$
3293 \"$\" find math expressions surrounded by $...$
3294 \"$$\" find math expressions surrounded by $$....$$
3295 \"\\(\" find math expressions surrounded by \\(...\\)
3296 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3297 :group 'org-latex
3298 :type 'plist)
3300 (defcustom org-format-latex-signal-error t
3301 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3302 When nil, just push out a message."
3303 :group 'org-latex
3304 :type 'boolean)
3305 (defcustom org-latex-to-mathml-jar-file nil
3306 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3307 Use this to specify additional executable file say a jar file.
3309 When using MathToWeb as the converter, specify the full-path to
3310 your mathtoweb.jar file."
3311 :group 'org-latex
3312 :type '(choice
3313 (const :tag "None" nil)
3314 (file :tag "JAR file" :must-match t)))
3316 (defcustom org-latex-to-mathml-convert-command nil
3317 "Command to convert LaTeX fragments to MathML.
3318 Replace format-specifiers in the command as noted below and use
3319 `shell-command' to convert LaTeX to MathML.
3320 %j: Executable file in fully expanded form as specified by
3321 `org-latex-to-mathml-jar-file'.
3322 %I: Input LaTeX file in fully expanded form
3323 %o: Output MathML file
3324 This command is used by `org-create-math-formula'.
3326 When using MathToWeb as the converter, set this to
3327 \"java -jar %j -unicode -force -df %o %I\"."
3328 :group 'org-latex
3329 :type '(choice
3330 (const :tag "None" nil)
3331 (string :tag "\nShell command")))
3333 (defun org-format-latex-mathml-available-p ()
3334 "Return t if `org-latex-to-mathml-convert-command' is usable."
3335 (save-match-data
3336 (when (and (boundp 'org-latex-to-mathml-convert-command)
3337 org-latex-to-mathml-convert-command)
3338 (let ((executable (car (split-string
3339 org-latex-to-mathml-convert-command))))
3340 (when (executable-find executable)
3341 (if (string-match
3342 "%j" org-latex-to-mathml-convert-command)
3343 (file-readable-p org-latex-to-mathml-jar-file)
3344 t))))))
3346 (defcustom org-format-latex-header "\\documentclass{article}
3347 \\usepackage[usenames]{color}
3348 \\usepackage{amsmath}
3349 \\usepackage[mathscr]{eucal}
3350 \\pagestyle{empty} % do not remove
3351 \[PACKAGES]
3352 \[DEFAULT-PACKAGES]
3353 % The settings below are copied from fullpage.sty
3354 \\setlength{\\textwidth}{\\paperwidth}
3355 \\addtolength{\\textwidth}{-3cm}
3356 \\setlength{\\oddsidemargin}{1.5cm}
3357 \\addtolength{\\oddsidemargin}{-2.54cm}
3358 \\setlength{\\evensidemargin}{\\oddsidemargin}
3359 \\setlength{\\textheight}{\\paperheight}
3360 \\addtolength{\\textheight}{-\\headheight}
3361 \\addtolength{\\textheight}{-\\headsep}
3362 \\addtolength{\\textheight}{-\\footskip}
3363 \\addtolength{\\textheight}{-3cm}
3364 \\setlength{\\topmargin}{1.5cm}
3365 \\addtolength{\\topmargin}{-2.54cm}"
3366 "The document header used for processing LaTeX fragments.
3367 It is imperative that this header make sure that no page number
3368 appears on the page. The package defined in the variables
3369 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3370 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3371 will be appended."
3372 :group 'org-latex
3373 :type 'string)
3375 (defvar org-format-latex-header-extra nil)
3377 (defun org-set-packages-alist (var val)
3378 "Set the packages alist and make sure it has 3 elements per entry."
3379 (set var (mapcar (lambda (x)
3380 (if (and (consp x) (= (length x) 2))
3381 (list (car x) (nth 1 x) t)
3383 val)))
3385 (defun org-get-packages-alist (var)
3387 "Get the packages alist and make sure it has 3 elements per entry."
3388 (mapcar (lambda (x)
3389 (if (and (consp x) (= (length x) 2))
3390 (list (car x) (nth 1 x) t)
3392 (default-value var)))
3394 ;; The following variables are defined here because is it also used
3395 ;; when formatting latex fragments. Originally it was part of the
3396 ;; LaTeX exporter, which is why the name includes "export".
3397 (defcustom org-export-latex-default-packages-alist
3398 '(("AUTO" "inputenc" t)
3399 ("T1" "fontenc" t)
3400 ("" "fixltx2e" nil)
3401 ("" "graphicx" t)
3402 ("" "longtable" nil)
3403 ("" "float" nil)
3404 ("" "wrapfig" nil)
3405 ("" "soul" t)
3406 ("" "textcomp" t)
3407 ("" "marvosym" t)
3408 ("" "wasysym" t)
3409 ("" "latexsym" t)
3410 ("" "amssymb" t)
3411 ("" "hyperref" nil)
3412 "\\tolerance=1000"
3414 "Alist of default packages to be inserted in the header.
3415 Change this only if one of the packages here causes an incompatibility
3416 with another package you are using.
3417 The packages in this list are needed by one part or another of Org-mode
3418 to function properly.
3420 - inputenc, fontenc: for basic font and character selection
3421 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3422 for interpreting the entities in `org-entities'. You can skip some of these
3423 packages if you don't use any of the symbols in it.
3424 - graphicx: for including images
3425 - float, wrapfig: for figure placement
3426 - longtable: for long tables
3427 - hyperref: for cross references
3429 Therefore you should not modify this variable unless you know what you
3430 are doing. The one reason to change it anyway is that you might be loading
3431 some other package that conflicts with one of the default packages.
3432 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3433 If SNIPPET-FLAG is t, the package also needs to be included when
3434 compiling LaTeX snippets into images for inclusion into HTML."
3435 :group 'org-export-latex
3436 :set 'org-set-packages-alist
3437 :get 'org-get-packages-alist
3438 :type '(repeat
3439 (choice
3440 (list :tag "options/package pair"
3441 (string :tag "options")
3442 (string :tag "package")
3443 (boolean :tag "Snippet"))
3444 (string :tag "A line of LaTeX"))))
3446 (defcustom org-export-latex-packages-alist nil
3447 "Alist of packages to be inserted in every LaTeX header.
3448 These will be inserted after `org-export-latex-default-packages-alist'.
3449 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3450 SNIPPET-FLAG, when t, indicates that this package is also needed when
3451 turning LaTeX snippets into images for inclusion into HTML.
3452 Make sure that you only list packages here which:
3453 - you want in every file
3454 - do not conflict with the default packages in
3455 `org-export-latex-default-packages-alist'
3456 - do not conflict with the setup in `org-format-latex-header'."
3457 :group 'org-export-latex
3458 :set 'org-set-packages-alist
3459 :get 'org-get-packages-alist
3460 :type '(repeat
3461 (choice
3462 (list :tag "options/package pair"
3463 (string :tag "options")
3464 (string :tag "package")
3465 (boolean :tag "Snippet"))
3466 (string :tag "A line of LaTeX"))))
3469 (defgroup org-appearance nil
3470 "Settings for Org-mode appearance."
3471 :tag "Org Appearance"
3472 :group 'org)
3474 (defcustom org-level-color-stars-only nil
3475 "Non-nil means fontify only the stars in each headline.
3476 When nil, the entire headline is fontified.
3477 Changing it requires restart of `font-lock-mode' to become effective
3478 also in regions already fontified."
3479 :group 'org-appearance
3480 :type 'boolean)
3482 (defcustom org-hide-leading-stars nil
3483 "Non-nil means hide the first N-1 stars in a headline.
3484 This works by using the face `org-hide' for these stars. This
3485 face is white for a light background, and black for a dark
3486 background. You may have to customize the face `org-hide' to
3487 make this work.
3488 Changing it requires restart of `font-lock-mode' to become effective
3489 also in regions already fontified.
3490 You may also set this on a per-file basis by adding one of the following
3491 lines to the buffer:
3493 #+STARTUP: hidestars
3494 #+STARTUP: showstars"
3495 :group 'org-appearance
3496 :type 'boolean)
3498 (defcustom org-hidden-keywords nil
3499 "List of symbols corresponding to keywords to be hidden the org buffer.
3500 For example, a value '(title) for this list will make the document's title
3501 appear in the buffer without the initial #+TITLE: keyword."
3502 :group 'org-appearance
3503 :type '(set (const :tag "#+AUTHOR" author)
3504 (const :tag "#+DATE" date)
3505 (const :tag "#+EMAIL" email)
3506 (const :tag "#+TITLE" title)))
3508 (defcustom org-fontify-done-headline nil
3509 "Non-nil means change the face of a headline if it is marked DONE.
3510 Normally, only the TODO/DONE keyword indicates the state of a headline.
3511 When this is non-nil, the headline after the keyword is set to the
3512 `org-headline-done' as an additional indication."
3513 :group 'org-appearance
3514 :type 'boolean)
3516 (defcustom org-fontify-emphasized-text t
3517 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3518 Changing this variable requires a restart of Emacs to take effect."
3519 :group 'org-appearance
3520 :type 'boolean)
3522 (defcustom org-fontify-whole-heading-line nil
3523 "Non-nil means fontify the whole line for headings.
3524 This is useful when setting a background color for the
3525 org-level-* faces."
3526 :group 'org-appearance
3527 :type 'boolean)
3529 (defcustom org-highlight-latex-fragments-and-specials nil
3530 "Non-nil means fontify what is treated specially by the exporters."
3531 :group 'org-appearance
3532 :type 'boolean)
3534 (defcustom org-hide-emphasis-markers nil
3535 "Non-nil mean font-lock should hide the emphasis marker characters."
3536 :group 'org-appearance
3537 :type 'boolean)
3539 (defcustom org-pretty-entities nil
3540 "Non-nil means show entities as UTF8 characters.
3541 When nil, the \\name form remains in the buffer."
3542 :group 'org-appearance
3543 :type 'boolean)
3545 (defcustom org-pretty-entities-include-sub-superscripts t
3546 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3547 :group 'org-appearance
3548 :type 'boolean)
3550 (defvar org-emph-re nil
3551 "Regular expression for matching emphasis.
3552 After a match, the match groups contain these elements:
3553 0 The match of the full regular expression, including the characters
3554 before and after the proper match
3555 1 The character before the proper match, or empty at beginning of line
3556 2 The proper match, including the leading and trailing markers
3557 3 The leading marker like * or /, indicating the type of highlighting
3558 4 The text between the emphasis markers, not including the markers
3559 5 The character after the match, empty at the end of a line")
3560 (defvar org-verbatim-re nil
3561 "Regular expression for matching verbatim text.")
3562 (defvar org-emphasis-regexp-components) ; defined just below
3563 (defvar org-emphasis-alist) ; defined just below
3564 (defun org-set-emph-re (var val)
3565 "Set variable and compute the emphasis regular expression."
3566 (set var val)
3567 (when (and (boundp 'org-emphasis-alist)
3568 (boundp 'org-emphasis-regexp-components)
3569 org-emphasis-alist org-emphasis-regexp-components)
3570 (let* ((e org-emphasis-regexp-components)
3571 (pre (car e))
3572 (post (nth 1 e))
3573 (border (nth 2 e))
3574 (body (nth 3 e))
3575 (nl (nth 4 e))
3576 (body1 (concat body "*?"))
3577 (markers (mapconcat 'car org-emphasis-alist ""))
3578 (vmarkers (mapconcat
3579 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3580 org-emphasis-alist "")))
3581 ;; make sure special characters appear at the right position in the class
3582 (if (string-match "\\^" markers)
3583 (setq markers (concat (replace-match "" t t markers) "^")))
3584 (if (string-match "-" markers)
3585 (setq markers (concat (replace-match "" t t markers) "-")))
3586 (if (string-match "\\^" vmarkers)
3587 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3588 (if (string-match "-" vmarkers)
3589 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3590 (if (> nl 0)
3591 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3592 (int-to-string nl) "\\}")))
3593 ;; Make the regexp
3594 (setq org-emph-re
3595 (concat "\\([" pre "]\\|^\\)"
3596 "\\("
3597 "\\([" markers "]\\)"
3598 "\\("
3599 "[^" border "]\\|"
3600 "[^" border "]"
3601 body1
3602 "[^" border "]"
3603 "\\)"
3604 "\\3\\)"
3605 "\\([" post "]\\|$\\)"))
3606 (setq org-verbatim-re
3607 (concat "\\([" pre "]\\|^\\)"
3608 "\\("
3609 "\\([" vmarkers "]\\)"
3610 "\\("
3611 "[^" border "]\\|"
3612 "[^" border "]"
3613 body1
3614 "[^" border "]"
3615 "\\)"
3616 "\\3\\)"
3617 "\\([" post "]\\|$\\)")))))
3619 (defcustom org-emphasis-regexp-components
3620 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3621 "Components used to build the regular expression for emphasis.
3622 This is a list with five entries. Terminology: In an emphasis string
3623 like \" *strong word* \", we call the initial space PREMATCH, the final
3624 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3625 and \"trong wor\" is the body. The different components in this variable
3626 specify what is allowed/forbidden in each part:
3628 pre Chars allowed as prematch. Beginning of line will be allowed too.
3629 post Chars allowed as postmatch. End of line will be allowed too.
3630 border The chars *forbidden* as border characters.
3631 body-regexp A regexp like \".\" to match a body character. Don't use
3632 non-shy groups here, and don't allow newline here.
3633 newline The maximum number of newlines allowed in an emphasis exp.
3635 Use customize to modify this, or restart Emacs after changing it."
3636 :group 'org-appearance
3637 :set 'org-set-emph-re
3638 :type '(list
3639 (sexp :tag "Allowed chars in pre ")
3640 (sexp :tag "Allowed chars in post ")
3641 (sexp :tag "Forbidden chars in border ")
3642 (sexp :tag "Regexp for body ")
3643 (integer :tag "number of newlines allowed")
3644 (option (boolean :tag "Please ignore this button"))))
3646 (defcustom org-emphasis-alist
3647 `(("*" bold "<b>" "</b>")
3648 ("/" italic "<i>" "</i>")
3649 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3650 ("=" org-code "<code>" "</code>" verbatim)
3651 ("~" org-verbatim "<code>" "</code>" verbatim)
3652 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3653 "<del>" "</del>")
3655 "Special syntax for emphasized text.
3656 Text starting and ending with a special character will be emphasized, for
3657 example *bold*, _underlined_ and /italic/. This variable sets the marker
3658 characters, the face to be used by font-lock for highlighting in Org-mode
3659 Emacs buffers, and the HTML tags to be used for this.
3660 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3661 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3662 Use customize to modify this, or restart Emacs after changing it."
3663 :group 'org-appearance
3664 :set 'org-set-emph-re
3665 :type '(repeat
3666 (list
3667 (string :tag "Marker character")
3668 (choice
3669 (face :tag "Font-lock-face")
3670 (plist :tag "Face property list"))
3671 (string :tag "HTML start tag")
3672 (string :tag "HTML end tag")
3673 (option (const verbatim)))))
3675 (defvar org-protecting-blocks
3676 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3677 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3678 This is needed for font-lock setup.")
3680 ;;; Miscellaneous options
3682 (defgroup org-completion nil
3683 "Completion in Org-mode."
3684 :tag "Org Completion"
3685 :group 'org)
3687 (defcustom org-completion-use-ido nil
3688 "Non-nil means use ido completion wherever possible.
3689 Note that `ido-mode' must be active for this variable to be relevant.
3690 If you decide to turn this variable on, you might well want to turn off
3691 `org-outline-path-complete-in-steps'.
3692 See also `org-completion-use-iswitchb'."
3693 :group 'org-completion
3694 :type 'boolean)
3696 (defcustom org-completion-use-iswitchb nil
3697 "Non-nil means use iswitchb completion wherever possible.
3698 Note that `iswitchb-mode' must be active for this variable to be relevant.
3699 If you decide to turn this variable on, you might well want to turn off
3700 `org-outline-path-complete-in-steps'.
3701 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3702 :group 'org-completion
3703 :type 'boolean)
3705 (defcustom org-completion-fallback-command 'hippie-expand
3706 "The expansion command called by \\[pcomplete] in normal context.
3707 Normal means, no org-mode-specific context."
3708 :group 'org-completion
3709 :type 'function)
3711 ;;; Functions and variables from their packages
3712 ;; Declared here to avoid compiler warnings
3714 ;; XEmacs only
3715 (defvar outline-mode-menu-heading)
3716 (defvar outline-mode-menu-show)
3717 (defvar outline-mode-menu-hide)
3718 (defvar zmacs-regions) ; XEmacs regions
3720 ;; Emacs only
3721 (defvar mark-active)
3723 ;; Various packages
3724 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3725 (declare-function calendar-forward-day "cal-move" (arg))
3726 (declare-function calendar-goto-date "cal-move" (date))
3727 (declare-function calendar-goto-today "cal-move" ())
3728 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3729 (defvar calc-embedded-close-formula)
3730 (defvar calc-embedded-open-formula)
3731 (declare-function cdlatex-tab "ext:cdlatex" ())
3732 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3733 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3734 (defvar font-lock-unfontify-region-function)
3735 (declare-function iswitchb-read-buffer "iswitchb"
3736 (prompt &optional default require-match start matches-set))
3737 (defvar iswitchb-temp-buflist)
3738 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3739 (defvar org-agenda-tags-todo-honor-ignore-options)
3740 (declare-function org-agenda-skip "org-agenda" ())
3741 (declare-function
3742 org-agenda-format-item "org-agenda"
3743 (extra txt &optional category tags dotime noprefix remove-re habitp))
3744 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3745 (declare-function org-agenda-change-all-lines "org-agenda"
3746 (newhead hdmarker &optional fixface just-this))
3747 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3748 (declare-function org-agenda-maybe-redo "org-agenda" ())
3749 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3750 (beg end))
3751 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3752 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3753 "org-agenda" (&optional end))
3754 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3755 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3756 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3757 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3758 (declare-function org-indent-mode "org-indent" (&optional arg))
3759 (declare-function parse-time-string "parse-time" (string))
3760 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3761 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3762 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3763 (defvar remember-data-file)
3764 (defvar texmathp-why)
3765 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3766 (declare-function table--at-cell-p "table" (position &optional object at-column))
3768 (defvar w3m-current-url)
3769 (defvar w3m-current-title)
3771 (defvar org-latex-regexps)
3773 ;;; Autoload and prepare some org modules
3775 ;; Some table stuff that needs to be defined here, because it is used
3776 ;; by the functions setting up org-mode or checking for table context.
3778 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3779 "Detect an org-type or table-type table.")
3780 (defconst org-table-line-regexp "^[ \t]*|"
3781 "Detect an org-type table line.")
3782 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3783 "Detect an org-type table line.")
3784 (defconst org-table-hline-regexp "^[ \t]*|-"
3785 "Detect an org-type table hline.")
3786 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3787 "Detect a table-type table hline.")
3788 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3789 "Detect the first line outside a table when searching from within it.
3790 This works for both table types.")
3792 ;; Autoload the functions in org-table.el that are needed by functions here.
3794 (eval-and-compile
3795 (org-autoload "org-table"
3796 '(org-table-align org-table-begin org-table-blank-field
3797 org-table-convert org-table-convert-region org-table-copy-down
3798 org-table-copy-region org-table-create
3799 org-table-create-or-convert-from-region
3800 org-table-create-with-table.el org-table-current-dline
3801 org-table-cut-region org-table-delete-column org-table-edit-field
3802 org-table-edit-formulas org-table-end org-table-eval-formula
3803 org-table-export org-table-field-info
3804 org-table-get-stored-formulas org-table-goto-column
3805 org-table-hline-and-move org-table-import org-table-insert-column
3806 org-table-insert-hline org-table-insert-row org-table-iterate
3807 org-table-justify-field-maybe org-table-kill-row
3808 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3809 org-table-move-column org-table-move-column-left
3810 org-table-move-column-right org-table-move-row
3811 org-table-move-row-down org-table-move-row-up
3812 org-table-next-field org-table-next-row org-table-paste-rectangle
3813 org-table-previous-field org-table-recalculate
3814 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3815 org-table-toggle-coordinate-overlays
3816 org-table-toggle-formula-debugger org-table-wrap-region
3817 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3818 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3819 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3821 (defun org-at-table-p (&optional table-type)
3822 "Return t if the cursor is inside an org-type table.
3823 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3824 (if org-enable-table-editor
3825 (save-excursion
3826 (beginning-of-line 1)
3827 (looking-at (if table-type org-table-any-line-regexp
3828 org-table-line-regexp)))
3829 nil))
3830 (defsubst org-table-p () (org-at-table-p))
3832 (defun org-at-table.el-p ()
3833 "Return t if and only if we are at a table.el table."
3834 (and (org-at-table-p 'any)
3835 (save-excursion
3836 (goto-char (org-table-begin 'any))
3837 (looking-at org-table1-hline-regexp))))
3838 (defun org-table-recognize-table.el ()
3839 "If there is a table.el table nearby, recognize it and move into it."
3840 (if org-table-tab-recognizes-table.el
3841 (if (org-at-table.el-p)
3842 (progn
3843 (beginning-of-line 1)
3844 (if (looking-at org-table-dataline-regexp)
3846 (if (looking-at org-table1-hline-regexp)
3847 (progn
3848 (beginning-of-line 2)
3849 (if (looking-at org-table-any-border-regexp)
3850 (beginning-of-line -1)))))
3851 (if (re-search-forward "|" (org-table-end t) t)
3852 (progn
3853 (require 'table)
3854 (if (table--at-cell-p (point))
3856 (message "recognizing table.el table...")
3857 (table-recognize-table)
3858 (message "recognizing table.el table...done")))
3859 (error "This should not happen"))
3861 nil)
3862 nil))
3864 (defun org-at-table-hline-p ()
3865 "Return t if the cursor is inside a hline in a table."
3866 (if org-enable-table-editor
3867 (save-excursion
3868 (beginning-of-line 1)
3869 (looking-at org-table-hline-regexp))
3870 nil))
3872 (defvar org-table-clean-did-remove-column nil)
3874 (defun org-table-map-tables (function &optional quietly)
3875 "Apply FUNCTION to the start of all tables in the buffer."
3876 (save-excursion
3877 (save-restriction
3878 (widen)
3879 (goto-char (point-min))
3880 (while (re-search-forward org-table-any-line-regexp nil t)
3881 (unless quietly
3882 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3883 (beginning-of-line 1)
3884 (when (looking-at org-table-line-regexp)
3885 (save-excursion (funcall function))
3886 (or (looking-at org-table-line-regexp)
3887 (forward-char 1)))
3888 (re-search-forward org-table-any-border-regexp nil 1))))
3889 (unless quietly (message "Mapping tables: done")))
3891 ;; Declare and autoload functions from org-exp.el & Co
3893 (declare-function org-default-export-plist "org-exp")
3894 (declare-function org-infile-export-plist "org-exp")
3895 (declare-function org-get-current-options "org-exp")
3896 (eval-and-compile
3897 (org-autoload "org-exp"
3898 '(org-export org-export-visible
3899 org-insert-export-options-template
3900 org-table-clean-before-export))
3901 (org-autoload "org-ascii"
3902 '(org-export-as-ascii org-export-ascii-preprocess
3903 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3904 org-export-region-as-ascii))
3905 (org-autoload "org-latex"
3906 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3907 org-replace-region-by-latex org-export-region-as-latex
3908 org-export-as-latex org-export-as-pdf
3909 org-export-as-pdf-and-open))
3910 (org-autoload "org-html"
3911 '(org-export-as-html-and-open
3912 org-export-as-html-batch org-export-as-html-to-buffer
3913 org-replace-region-by-html org-export-region-as-html
3914 org-export-as-html))
3915 (org-autoload "org-docbook"
3916 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3917 org-replace-region-by-docbook org-export-region-as-docbook
3918 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3919 org-export-as-docbook))
3920 (org-autoload "org-icalendar"
3921 '(org-export-icalendar-this-file
3922 org-export-icalendar-all-agenda-files
3923 org-export-icalendar-combine-agenda-files))
3924 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3925 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3927 ;; Declare and autoload functions from org-agenda.el
3929 (eval-and-compile
3930 (org-autoload "org-agenda"
3931 '(org-agenda org-agenda-list org-search-view
3932 org-todo-list org-tags-view org-agenda-list-stuck-projects
3933 org-diary org-agenda-to-appt
3934 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3936 ;; Autoload org-remember
3938 (eval-and-compile
3939 (org-autoload "org-remember"
3940 '(org-remember-insinuate org-remember-annotation
3941 org-remember-apply-template org-remember org-remember-handler)))
3943 (eval-and-compile
3944 (org-autoload "org-capture"
3945 '(org-capture org-capture-insert-template-here
3946 org-capture-import-remember-templates)))
3948 ;; Autoload org-clock.el
3950 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3951 (beg end))
3952 (declare-function org-clock-update-mode-line "org-clock" ())
3953 (declare-function org-resolve-clocks "org-clock"
3954 (&optional also-non-dangling-p prompt last-valid))
3955 (defvar org-clock-start-time)
3956 (defvar org-clock-marker (make-marker)
3957 "Marker recording the last clock-in.")
3958 (defvar org-clock-hd-marker (make-marker)
3959 "Marker recording the last clock-in, but the headline position.")
3960 (defvar org-clock-heading ""
3961 "The heading of the current clock entry.")
3962 (defun org-clock-is-active ()
3963 "Return non-nil if clock is currently running.
3964 The return value is actually the clock marker."
3965 (marker-buffer org-clock-marker))
3967 (eval-and-compile
3968 (org-autoload
3969 "org-clock"
3970 '(org-clock-in org-clock-out org-clock-cancel
3971 org-clock-goto org-clock-sum org-clock-display
3972 org-clock-remove-overlays org-clock-report
3973 org-clocktable-shift org-dblock-write:clocktable
3974 org-get-clocktable org-resolve-clocks)))
3976 (defun org-clock-update-time-maybe ()
3977 "If this is a CLOCK line, update it and return t.
3978 Otherwise, return nil."
3979 (interactive)
3980 (save-excursion
3981 (beginning-of-line 1)
3982 (skip-chars-forward " \t")
3983 (when (looking-at org-clock-string)
3984 (let ((re (concat "[ \t]*" org-clock-string
3985 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3986 "\\([ \t]*=>.*\\)?\\)?"))
3987 ts te h m s neg)
3988 (cond
3989 ((not (looking-at re))
3990 nil)
3991 ((not (match-end 2))
3992 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3993 (> org-clock-marker (point))
3994 (<= org-clock-marker (point-at-eol)))
3995 ;; The clock is running here
3996 (setq org-clock-start-time
3997 (apply 'encode-time
3998 (org-parse-time-string (match-string 1))))
3999 (org-clock-update-mode-line)))
4001 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
4002 (end-of-line 1)
4003 (setq ts (match-string 1)
4004 te (match-string 3))
4005 (setq s (- (org-float-time
4006 (apply 'encode-time (org-parse-time-string te)))
4007 (org-float-time
4008 (apply 'encode-time (org-parse-time-string ts))))
4009 neg (< s 0)
4010 s (abs s)
4011 h (floor (/ s 3600))
4012 s (- s (* 3600 h))
4013 m (floor (/ s 60))
4014 s (- s (* 60 s)))
4015 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
4016 t))))))
4018 (defun org-check-running-clock ()
4019 "Check if the current buffer contains the running clock.
4020 If yes, offer to stop it and to save the buffer with the changes."
4021 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4022 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4023 (buffer-name))))
4024 (org-clock-out)
4025 (when (y-or-n-p "Save changed buffer?")
4026 (save-buffer))))
4028 (defun org-clocktable-try-shift (dir n)
4029 "Check if this line starts a clock table, if yes, shift the time block."
4030 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4031 (org-clocktable-shift dir n)))
4033 ;; Autoload org-timer.el
4035 (eval-and-compile
4036 (org-autoload
4037 "org-timer"
4038 '(org-timer-start org-timer org-timer-item
4039 org-timer-change-times-in-region
4040 org-timer-set-timer
4041 org-timer-reset-timers
4042 org-timer-show-remaining-time)))
4044 ;; Autoload org-feed.el
4046 (eval-and-compile
4047 (org-autoload
4048 "org-feed"
4049 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
4052 ;; Autoload org-indent.el
4054 ;; Define the variable already here, to make sure we have it.
4055 (defvar org-indent-mode nil
4056 "Non-nil if Org-Indent mode is enabled.
4057 Use the command `org-indent-mode' to change this variable.")
4059 (eval-and-compile
4060 (org-autoload
4061 "org-indent"
4062 '(org-indent-mode)))
4064 ;; Autoload org-mobile.el
4066 (eval-and-compile
4067 (org-autoload
4068 "org-mobile"
4069 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
4071 ;; Autoload archiving code
4072 ;; The stuff that is needed for cycling and tags has to be defined here.
4074 (defgroup org-archive nil
4075 "Options concerning archiving in Org-mode."
4076 :tag "Org Archive"
4077 :group 'org-structure)
4079 (defcustom org-archive-location "%s_archive::"
4080 "The location where subtrees should be archived.
4082 The value of this variable is a string, consisting of two parts,
4083 separated by a double-colon. The first part is a filename and
4084 the second part is a headline.
4086 When the filename is omitted, archiving happens in the same file.
4087 %s in the filename will be replaced by the current file
4088 name (without the directory part). Archiving to a different file
4089 is useful to keep archived entries from contributing to the
4090 Org-mode Agenda.
4092 The archived entries will be filed as subtrees of the specified
4093 headline. When the headline is omitted, the subtrees are simply
4094 filed away at the end of the file, as top-level entries. Also in
4095 the heading you can use %s to represent the file name, this can be
4096 useful when using the same archive for a number of different files.
4098 Here are a few examples:
4099 \"%s_archive::\"
4100 If the current file is Projects.org, archive in file
4101 Projects.org_archive, as top-level trees. This is the default.
4103 \"::* Archived Tasks\"
4104 Archive in the current file, under the top-level headline
4105 \"* Archived Tasks\".
4107 \"~/org/archive.org::\"
4108 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4110 \"~/org/archive.org::* From %s\"
4111 Archive in file ~/org/archive.org (absolute path), under headlines
4112 \"From FILENAME\" where file name is the current file name.
4114 \"basement::** Finished Tasks\"
4115 Archive in file ./basement (relative path), as level 3 trees
4116 below the level 2 heading \"** Finished Tasks\".
4118 You may set this option on a per-file basis by adding to the buffer a
4119 line like
4121 #+ARCHIVE: basement::** Finished Tasks
4123 You may also define it locally for a subtree by setting an ARCHIVE property
4124 in the entry. If such a property is found in an entry, or anywhere up
4125 the hierarchy, it will be used."
4126 :group 'org-archive
4127 :type 'string)
4129 (defcustom org-archive-tag "ARCHIVE"
4130 "The tag that marks a subtree as archived.
4131 An archived subtree does not open during visibility cycling, and does
4132 not contribute to the agenda listings.
4133 After changing this, font-lock must be restarted in the relevant buffers to
4134 get the proper fontification."
4135 :group 'org-archive
4136 :group 'org-keywords
4137 :type 'string)
4139 (defcustom org-agenda-skip-archived-trees t
4140 "Non-nil means the agenda will skip any items located in archived trees.
4141 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4142 variable is no longer recommended, you should leave it at the value t.
4143 Instead, use the key `v' to cycle the archives-mode in the agenda."
4144 :group 'org-archive
4145 :group 'org-agenda-skip
4146 :type 'boolean)
4148 (defcustom org-columns-skip-archived-trees t
4149 "Non-nil means ignore archived trees when creating column view."
4150 :group 'org-archive
4151 :group 'org-properties
4152 :type 'boolean)
4154 (defcustom org-cycle-open-archived-trees nil
4155 "Non-nil means `org-cycle' will open archived trees.
4156 An archived tree is a tree marked with the tag ARCHIVE.
4157 When nil, archived trees will stay folded. You can still open them with
4158 normal outline commands like `show-all', but not with the cycling commands."
4159 :group 'org-archive
4160 :group 'org-cycle
4161 :type 'boolean)
4163 (defcustom org-sparse-tree-open-archived-trees nil
4164 "Non-nil means sparse tree construction shows matches in archived trees.
4165 When nil, matches in these trees are highlighted, but the trees are kept in
4166 collapsed state."
4167 :group 'org-archive
4168 :group 'org-sparse-trees
4169 :type 'boolean)
4171 (defun org-cycle-hide-archived-subtrees (state)
4172 "Re-hide all archived subtrees after a visibility state change."
4173 (when (and (not org-cycle-open-archived-trees)
4174 (not (memq state '(overview folded))))
4175 (save-excursion
4176 (let* ((globalp (memq state '(contents all)))
4177 (beg (if globalp (point-min) (point)))
4178 (end (if globalp (point-max) (org-end-of-subtree t))))
4179 (org-hide-archived-subtrees beg end)
4180 (goto-char beg)
4181 (if (looking-at (concat ".*:" org-archive-tag ":"))
4182 (message "%s" (substitute-command-keys
4183 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4185 (defun org-force-cycle-archived ()
4186 "Cycle subtree even if it is archived."
4187 (interactive)
4188 (setq this-command 'org-cycle)
4189 (let ((org-cycle-open-archived-trees t))
4190 (call-interactively 'org-cycle)))
4192 (defun org-hide-archived-subtrees (beg end)
4193 "Re-hide all archived subtrees after a visibility state change."
4194 (save-excursion
4195 (let* ((re (concat ":" org-archive-tag ":")))
4196 (goto-char beg)
4197 (while (re-search-forward re end t)
4198 (when (org-on-heading-p)
4199 (org-flag-subtree t)
4200 (org-end-of-subtree t))))))
4202 (defun org-flag-subtree (flag)
4203 (save-excursion
4204 (org-back-to-heading t)
4205 (outline-end-of-heading)
4206 (outline-flag-region (point)
4207 (progn (org-end-of-subtree t) (point))
4208 flag)))
4210 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4212 (eval-and-compile
4213 (org-autoload "org-archive"
4214 '(org-add-archive-files org-archive-subtree
4215 org-archive-to-archive-sibling org-toggle-archive-tag
4216 org-archive-subtree-default
4217 org-archive-subtree-default-with-confirmation)))
4219 ;; Autoload Column View Code
4221 (declare-function org-columns-number-to-string "org-colview")
4222 (declare-function org-columns-get-format-and-top-level "org-colview")
4223 (declare-function org-columns-compute "org-colview")
4225 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4226 '(org-columns-number-to-string org-columns-get-format-and-top-level
4227 org-columns-compute org-agenda-columns org-columns-remove-overlays
4228 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4230 ;; Autoload ID code
4232 (declare-function org-id-store-link "org-id")
4233 (declare-function org-id-locations-load "org-id")
4234 (declare-function org-id-locations-save "org-id")
4235 (defvar org-id-track-globally)
4236 (org-autoload "org-id"
4237 '(org-id-get-create org-id-new org-id-copy org-id-get
4238 org-id-get-with-outline-path-completion
4239 org-id-get-with-outline-drilling org-id-store-link
4240 org-id-goto org-id-find org-id-store-link))
4242 ;; Autoload Plotting Code
4244 (org-autoload "org-plot"
4245 '(org-plot/gnuplot))
4247 ;;; Variables for pre-computed regular expressions, all buffer local
4249 (defvar org-drawer-regexp nil
4250 "Matches first line of a hidden block.")
4251 (make-variable-buffer-local 'org-drawer-regexp)
4252 (defvar org-todo-regexp nil
4253 "Matches any of the TODO state keywords.")
4254 (make-variable-buffer-local 'org-todo-regexp)
4255 (defvar org-not-done-regexp nil
4256 "Matches any of the TODO state keywords except the last one.")
4257 (make-variable-buffer-local 'org-not-done-regexp)
4258 (defvar org-not-done-heading-regexp nil
4259 "Matches a TODO headline that is not done.")
4260 (make-variable-buffer-local 'org-not-done-regexp)
4261 (defvar org-todo-line-regexp nil
4262 "Matches a headline and puts TODO state into group 2 if present.")
4263 (make-variable-buffer-local 'org-todo-line-regexp)
4264 (defvar org-complex-heading-regexp nil
4265 "Matches a headline and puts everything into groups:
4266 group 1: the stars
4267 group 2: The todo keyword, maybe
4268 group 3: Priority cookie
4269 group 4: True headline
4270 group 5: Tags")
4271 (make-variable-buffer-local 'org-complex-heading-regexp)
4272 (defvar org-complex-heading-regexp-format nil
4273 "Printf format to make regexp to match an exact headline.
4274 This regexp will match the headline of any node which has the
4275 exact headline text that is put into the format, but may have any
4276 TODO state, priority and tags.")
4277 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4278 (defvar org-todo-line-tags-regexp nil
4279 "Matches a headline and puts TODO state into group 2 if present.
4280 Also put tags into group 4 if tags are present.")
4281 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4282 (defvar org-ds-keyword-length 12
4283 "Maximum length of the Deadline and SCHEDULED keywords.")
4284 (make-variable-buffer-local 'org-ds-keyword-length)
4285 (defvar org-deadline-regexp nil
4286 "Matches the DEADLINE keyword.")
4287 (make-variable-buffer-local 'org-deadline-regexp)
4288 (defvar org-deadline-time-regexp nil
4289 "Matches the DEADLINE keyword together with a time stamp.")
4290 (make-variable-buffer-local 'org-deadline-time-regexp)
4291 (defvar org-deadline-line-regexp nil
4292 "Matches the DEADLINE keyword and the rest of the line.")
4293 (make-variable-buffer-local 'org-deadline-line-regexp)
4294 (defvar org-scheduled-regexp nil
4295 "Matches the SCHEDULED keyword.")
4296 (make-variable-buffer-local 'org-scheduled-regexp)
4297 (defvar org-scheduled-time-regexp nil
4298 "Matches the SCHEDULED keyword together with a time stamp.")
4299 (make-variable-buffer-local 'org-scheduled-time-regexp)
4300 (defvar org-closed-time-regexp nil
4301 "Matches the CLOSED keyword together with a time stamp.")
4302 (make-variable-buffer-local 'org-closed-time-regexp)
4304 (defvar org-keyword-time-regexp nil
4305 "Matches any of the 4 keywords, together with the time stamp.")
4306 (make-variable-buffer-local 'org-keyword-time-regexp)
4307 (defvar org-keyword-time-not-clock-regexp nil
4308 "Matches any of the 3 keywords, together with the time stamp.")
4309 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4310 (defvar org-maybe-keyword-time-regexp nil
4311 "Matches a timestamp, possibly preceded by a keyword.")
4312 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4313 (defvar org-planning-or-clock-line-re nil
4314 "Matches a line with planning or clock info.")
4315 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4316 (defvar org-all-time-keywords nil
4317 "List of time keywords.")
4318 (make-variable-buffer-local 'org-all-time-keywords)
4320 (defconst org-plain-time-of-day-regexp
4321 (concat
4322 "\\(\\<[012]?[0-9]"
4323 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4324 "\\(--?"
4325 "\\(\\<[012]?[0-9]"
4326 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4327 "\\)?")
4328 "Regular expression to match a plain time or time range.
4329 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4330 groups carry important information:
4331 0 the full match
4332 1 the first time, range or not
4333 8 the second time, if it is a range.")
4335 (defconst org-plain-time-extension-regexp
4336 (concat
4337 "\\(\\<[012]?[0-9]"
4338 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4339 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4340 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4341 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4342 groups carry important information:
4343 0 the full match
4344 7 hours of duration
4345 9 minutes of duration")
4347 (defconst org-stamp-time-of-day-regexp
4348 (concat
4349 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4350 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4351 "\\(--?"
4352 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4353 "Regular expression to match a timestamp time or time range.
4354 After a match, the following groups carry important information:
4355 0 the full match
4356 1 date plus weekday, for back referencing to make sure both times are on the same day
4357 2 the first time, range or not
4358 4 the second time, if it is a range.")
4360 (defconst org-startup-options
4361 '(("fold" org-startup-folded t)
4362 ("overview" org-startup-folded t)
4363 ("nofold" org-startup-folded nil)
4364 ("showall" org-startup-folded nil)
4365 ("showeverything" org-startup-folded showeverything)
4366 ("content" org-startup-folded content)
4367 ("indent" org-startup-indented t)
4368 ("noindent" org-startup-indented nil)
4369 ("hidestars" org-hide-leading-stars t)
4370 ("showstars" org-hide-leading-stars nil)
4371 ("odd" org-odd-levels-only t)
4372 ("oddeven" org-odd-levels-only nil)
4373 ("align" org-startup-align-all-tables t)
4374 ("noalign" org-startup-align-all-tables nil)
4375 ("inlineimages" org-startup-with-inline-images t)
4376 ("noinlineimages" org-startup-with-inline-images nil)
4377 ("customtime" org-display-custom-times t)
4378 ("logdone" org-log-done time)
4379 ("lognotedone" org-log-done note)
4380 ("nologdone" org-log-done nil)
4381 ("lognoteclock-out" org-log-note-clock-out t)
4382 ("nolognoteclock-out" org-log-note-clock-out nil)
4383 ("logrepeat" org-log-repeat state)
4384 ("lognoterepeat" org-log-repeat note)
4385 ("nologrepeat" org-log-repeat nil)
4386 ("logreschedule" org-log-reschedule time)
4387 ("lognotereschedule" org-log-reschedule note)
4388 ("nologreschedule" org-log-reschedule nil)
4389 ("logredeadline" org-log-redeadline time)
4390 ("lognoteredeadline" org-log-redeadline note)
4391 ("nologredeadline" org-log-redeadline nil)
4392 ("logrefile" org-log-refile time)
4393 ("lognoterefile" org-log-refile note)
4394 ("nologrefile" org-log-refile nil)
4395 ("fninline" org-footnote-define-inline t)
4396 ("nofninline" org-footnote-define-inline nil)
4397 ("fnlocal" org-footnote-section nil)
4398 ("fnauto" org-footnote-auto-label t)
4399 ("fnprompt" org-footnote-auto-label nil)
4400 ("fnconfirm" org-footnote-auto-label confirm)
4401 ("fnplain" org-footnote-auto-label plain)
4402 ("fnadjust" org-footnote-auto-adjust t)
4403 ("nofnadjust" org-footnote-auto-adjust nil)
4404 ("constcgs" constants-unit-system cgs)
4405 ("constSI" constants-unit-system SI)
4406 ("noptag" org-tag-persistent-alist nil)
4407 ("hideblocks" org-hide-block-startup t)
4408 ("nohideblocks" org-hide-block-startup nil)
4409 ("beamer" org-startup-with-beamer-mode t)
4410 ("entitiespretty" org-pretty-entities t)
4411 ("entitiesplain" org-pretty-entities nil))
4412 "Variable associated with STARTUP options for org-mode.
4413 Each element is a list of three items: The startup options as written
4414 in the #+STARTUP line, the corresponding variable, and the value to
4415 set this variable to if the option is found. An optional forth element PUSH
4416 means to push this value onto the list in the variable.")
4418 (defun org-set-regexps-and-options ()
4419 "Precompute regular expressions for current buffer."
4420 (when (eq major-mode 'org-mode)
4421 (org-set-local 'org-todo-kwd-alist nil)
4422 (org-set-local 'org-todo-key-alist nil)
4423 (org-set-local 'org-todo-key-trigger nil)
4424 (org-set-local 'org-todo-keywords-1 nil)
4425 (org-set-local 'org-done-keywords nil)
4426 (org-set-local 'org-todo-heads nil)
4427 (org-set-local 'org-todo-sets nil)
4428 (org-set-local 'org-todo-log-states nil)
4429 (org-set-local 'org-file-properties nil)
4430 (org-set-local 'org-file-tags nil)
4431 (let ((re (org-make-options-regexp
4432 '("CATEGORY" "TODO" "COLUMNS"
4433 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4434 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4435 "OPTIONS")
4436 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4437 (splitre "[ \t]+")
4438 (scripts org-use-sub-superscripts)
4439 kwds kws0 kwsa key log value cat arch tags const links hw dws
4440 tail sep kws1 prio props ftags drawers beamer-p
4441 ext-setup-or-nil setup-contents (start 0))
4442 (save-excursion
4443 (save-restriction
4444 (widen)
4445 (goto-char (point-min))
4446 (while (or (and ext-setup-or-nil
4447 (string-match re ext-setup-or-nil start)
4448 (setq start (match-end 0)))
4449 (and (setq ext-setup-or-nil nil start 0)
4450 (re-search-forward re nil t)))
4451 (setq key (upcase (match-string 1 ext-setup-or-nil))
4452 value (org-match-string-no-properties 2 ext-setup-or-nil))
4453 (if (stringp value) (setq value (org-trim value)))
4454 (cond
4455 ((equal key "CATEGORY")
4456 (setq cat value))
4457 ((member key '("SEQ_TODO" "TODO"))
4458 (push (cons 'sequence (org-split-string value splitre)) kwds))
4459 ((equal key "TYP_TODO")
4460 (push (cons 'type (org-split-string value splitre)) kwds))
4461 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4462 ;; general TODO-like setup
4463 (push (cons (intern (downcase (match-string 1 key)))
4464 (org-split-string value splitre)) kwds))
4465 ((equal key "TAGS")
4466 (setq tags (append tags (if tags '("\\n") nil)
4467 (org-split-string value splitre))))
4468 ((equal key "COLUMNS")
4469 (org-set-local 'org-columns-default-format value))
4470 ((equal key "LINK")
4471 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4472 (push (cons (match-string 1 value)
4473 (org-trim (match-string 2 value)))
4474 links)))
4475 ((equal key "PRIORITIES")
4476 (setq prio (org-split-string value " +")))
4477 ((equal key "PROPERTY")
4478 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4479 (push (cons (match-string 1 value) (match-string 2 value))
4480 props)))
4481 ((equal key "FILETAGS")
4482 (when (string-match "\\S-" value)
4483 (setq ftags
4484 (append
4485 ftags
4486 (apply 'append
4487 (mapcar (lambda (x) (org-split-string x ":"))
4488 (org-split-string value)))))))
4489 ((equal key "DRAWERS")
4490 (setq drawers (org-split-string value splitre)))
4491 ((equal key "CONSTANTS")
4492 (setq const (append const (org-split-string value splitre))))
4493 ((equal key "STARTUP")
4494 (let ((opts (org-split-string value splitre))
4495 l var val)
4496 (while (setq l (pop opts))
4497 (when (setq l (assoc l org-startup-options))
4498 (setq var (nth 1 l) val (nth 2 l))
4499 (if (not (nth 3 l))
4500 (set (make-local-variable var) val)
4501 (if (not (listp (symbol-value var)))
4502 (set (make-local-variable var) nil))
4503 (set (make-local-variable var) (symbol-value var))
4504 (add-to-list var val))))))
4505 ((equal key "ARCHIVE")
4506 (setq arch value)
4507 (remove-text-properties 0 (length arch)
4508 '(face t fontified t) arch))
4509 ((equal key "LATEX_CLASS")
4510 (setq beamer-p (equal value "beamer")))
4511 ((equal key "OPTIONS")
4512 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4513 (setq scripts (read (match-string 2 value)))))
4514 ((equal key "SETUPFILE")
4515 (setq setup-contents (org-file-contents
4516 (expand-file-name
4517 (org-remove-double-quotes value))
4518 'noerror))
4519 (if (not ext-setup-or-nil)
4520 (setq ext-setup-or-nil setup-contents start 0)
4521 (setq ext-setup-or-nil
4522 (concat (substring ext-setup-or-nil 0 start)
4523 "\n" setup-contents "\n"
4524 (substring ext-setup-or-nil start)))))))
4525 ;; search for property blocks
4526 (goto-char (point-min))
4527 (while (re-search-forward org-block-regexp nil t)
4528 (when (equal "PROPERTY" (upcase (match-string 1)))
4529 (setq value (replace-regexp-in-string
4530 "[\n\r]" " " (match-string 4)))
4531 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4532 (push (cons (match-string 1 value) (match-string 2 value))
4533 props))))))
4534 (org-set-local 'org-use-sub-superscripts scripts)
4535 (when cat
4536 (org-set-local 'org-category (intern cat))
4537 (push (cons "CATEGORY" cat) props))
4538 (when prio
4539 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4540 (setq prio (mapcar 'string-to-char prio))
4541 (org-set-local 'org-highest-priority (nth 0 prio))
4542 (org-set-local 'org-lowest-priority (nth 1 prio))
4543 (org-set-local 'org-default-priority (nth 2 prio)))
4544 (and props (org-set-local 'org-file-properties (nreverse props)))
4545 (and ftags (org-set-local 'org-file-tags
4546 (mapcar 'org-add-prop-inherited ftags)))
4547 (and drawers (org-set-local 'org-drawers drawers))
4548 (and arch (org-set-local 'org-archive-location arch))
4549 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4550 ;; Process the TODO keywords
4551 (unless kwds
4552 ;; Use the global values as if they had been given locally.
4553 (setq kwds (default-value 'org-todo-keywords))
4554 (if (stringp (car kwds))
4555 (setq kwds (list (cons org-todo-interpretation
4556 (default-value 'org-todo-keywords)))))
4557 (setq kwds (reverse kwds)))
4558 (setq kwds (nreverse kwds))
4559 (let (inter kws kw)
4560 (while (setq kws (pop kwds))
4561 (let ((kws (or
4562 (run-hook-with-args-until-success
4563 'org-todo-setup-filter-hook kws)
4564 kws)))
4565 (setq inter (pop kws) sep (member "|" kws)
4566 kws0 (delete "|" (copy-sequence kws))
4567 kwsa nil
4568 kws1 (mapcar
4569 (lambda (x)
4570 ;; 1 2
4571 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4572 (progn
4573 (setq kw (match-string 1 x)
4574 key (and (match-end 2) (match-string 2 x))
4575 log (org-extract-log-state-settings x))
4576 (push (cons kw (and key (string-to-char key))) kwsa)
4577 (and log (push log org-todo-log-states))
4579 (error "Invalid TODO keyword %s" x)))
4580 kws0)
4581 kwsa (if kwsa (append '((:startgroup))
4582 (nreverse kwsa)
4583 '((:endgroup))))
4584 hw (car kws1)
4585 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4586 tail (list inter hw (car dws) (org-last dws))))
4587 (add-to-list 'org-todo-heads hw 'append)
4588 (push kws1 org-todo-sets)
4589 (setq org-done-keywords (append org-done-keywords dws nil))
4590 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4591 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4592 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4593 (setq org-todo-sets (nreverse org-todo-sets)
4594 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4595 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4596 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4597 ;; Process the constants
4598 (when const
4599 (let (e cst)
4600 (while (setq e (pop const))
4601 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4602 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4603 (setq org-table-formula-constants-local cst)))
4605 ;; Process the tags.
4606 (when tags
4607 (let (e tgs)
4608 (while (setq e (pop tags))
4609 (cond
4610 ((equal e "{") (push '(:startgroup) tgs))
4611 ((equal e "}") (push '(:endgroup) tgs))
4612 ((equal e "\\n") (push '(:newline) tgs))
4613 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4614 (push (cons (match-string 1 e)
4615 (string-to-char (match-string 2 e)))
4616 tgs))
4617 (t (push (list e) tgs))))
4618 (org-set-local 'org-tag-alist nil)
4619 (while (setq e (pop tgs))
4620 (or (and (stringp (car e))
4621 (assoc (car e) org-tag-alist))
4622 (push e org-tag-alist)))))
4624 ;; Compute the regular expressions and other local variables.
4625 ;; Using `org-outline-regexp-bol' would complicate them much,
4626 ;; because of the fixed white space at the end of that string.
4627 (if (not org-done-keywords)
4628 (setq org-done-keywords (and org-todo-keywords-1
4629 (list (org-last org-todo-keywords-1)))))
4630 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4631 (length org-scheduled-string)
4632 (length org-clock-string)
4633 (length org-closed-string)))
4634 org-drawer-regexp
4635 (concat "^[ \t]*:\\("
4636 (mapconcat 'regexp-quote org-drawers "\\|")
4637 "\\):[ \t]*$")
4638 org-not-done-keywords
4639 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4640 org-todo-regexp
4641 (concat "\\("
4642 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4643 "\\)")
4644 org-not-done-regexp
4645 (concat "\\("
4646 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4647 "\\)")
4648 org-not-done-heading-regexp
4649 (format org-heading-keyword-regexp-format org-not-done-regexp)
4650 org-todo-line-regexp
4651 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4652 org-complex-heading-regexp
4653 (concat "^\\(\\*+\\)"
4654 "\\(?: +" org-todo-regexp "\\)?"
4655 "\\(?: +\\(\\[#.\\]\\)\\)?"
4656 "\\(?: +\\(.*?\\)\\)?"
4657 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4658 "[ \t]*$")
4659 org-complex-heading-regexp-format
4660 (concat "^\\(\\*+\\)"
4661 "\\(?: +" org-todo-regexp "\\)?"
4662 "\\(?: +\\(\\[#.\\]\\)\\)?"
4663 "\\(?: +"
4664 ;; Stats cookies can be sticked to body.
4665 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4666 "\\(%s\\)"
4667 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4668 "\\)"
4669 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4670 "[ \t]*$")
4671 org-todo-line-tags-regexp
4672 (concat "^\\(\\*+\\)"
4673 "\\(?: +" org-todo-regexp "\\)?"
4674 "\\(?: +\\(.*?\\)\\)?"
4675 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4676 "[ \t]*$")
4677 org-deadline-regexp (concat "\\<" org-deadline-string)
4678 org-deadline-time-regexp
4679 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4680 org-deadline-line-regexp
4681 (concat "\\<\\(" org-deadline-string "\\).*")
4682 org-scheduled-regexp
4683 (concat "\\<" org-scheduled-string)
4684 org-scheduled-time-regexp
4685 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4686 org-closed-time-regexp
4687 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4688 org-keyword-time-regexp
4689 (concat "\\<\\(" org-scheduled-string
4690 "\\|" org-deadline-string
4691 "\\|" org-closed-string
4692 "\\|" org-clock-string "\\)"
4693 " *[[<]\\([^]>]+\\)[]>]")
4694 org-keyword-time-not-clock-regexp
4695 (concat "\\<\\(" org-scheduled-string
4696 "\\|" org-deadline-string
4697 "\\|" org-closed-string
4698 "\\)"
4699 " *[[<]\\([^]>]+\\)[]>]")
4700 org-maybe-keyword-time-regexp
4701 (concat "\\(\\<\\(" org-scheduled-string
4702 "\\|" org-deadline-string
4703 "\\|" org-closed-string
4704 "\\|" org-clock-string "\\)\\)?"
4705 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4706 org-planning-or-clock-line-re
4707 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4708 "\\|" org-deadline-string
4709 "\\|" org-closed-string "\\|" org-clock-string
4710 "\\)\\>\\)")
4711 org-all-time-keywords
4712 (mapcar (lambda (w) (substring w 0 -1))
4713 (list org-scheduled-string org-deadline-string
4714 org-clock-string org-closed-string))
4716 (org-compute-latex-and-specials-regexp)
4717 (org-set-font-lock-defaults))))
4719 (defun org-file-contents (file &optional noerror)
4720 "Return the contents of FILE, as a string."
4721 (if (or (not file)
4722 (not (file-readable-p file)))
4723 (if noerror
4724 (progn
4725 (message "Cannot read file \"%s\"" file)
4726 (ding) (sit-for 2)
4728 (error "Cannot read file \"%s\"" file))
4729 (with-temp-buffer
4730 (insert-file-contents file)
4731 (buffer-string))))
4733 (defun org-extract-log-state-settings (x)
4734 "Extract the log state setting from a TODO keyword string.
4735 This will extract info from a string like \"WAIT(w@/!)\"."
4736 (let (kw key log1 log2)
4737 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4738 (setq kw (match-string 1 x)
4739 key (and (match-end 2) (match-string 2 x))
4740 log1 (and (match-end 3) (match-string 3 x))
4741 log2 (and (match-end 4) (match-string 4 x)))
4742 (and (or log1 log2)
4743 (list kw
4744 (and log1 (if (equal log1 "!") 'time 'note))
4745 (and log2 (if (equal log2 "!") 'time 'note)))))))
4747 (defun org-remove-keyword-keys (list)
4748 "Remove a pair of parenthesis at the end of each string in LIST."
4749 (mapcar (lambda (x)
4750 (if (string-match "(.*)$" x)
4751 (substring x 0 (match-beginning 0))
4753 list))
4755 (defun org-assign-fast-keys (alist)
4756 "Assign fast keys to a keyword-key alist.
4757 Respect keys that are already there."
4758 (let (new e (alt ?0))
4759 (while (setq e (pop alist))
4760 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4761 (cdr e)) ;; Key already assigned.
4762 (push e new)
4763 (let ((clist (string-to-list (downcase (car e))))
4764 (used (append new alist)))
4765 (when (= (car clist) ?@)
4766 (pop clist))
4767 (while (and clist (rassoc (car clist) used))
4768 (pop clist))
4769 (unless clist
4770 (while (rassoc alt used)
4771 (incf alt)))
4772 (push (cons (car e) (or (car clist) alt)) new))))
4773 (nreverse new)))
4775 ;;; Some variables used in various places
4777 (defvar org-window-configuration nil
4778 "Used in various places to store a window configuration.")
4779 (defvar org-selected-window nil
4780 "Used in various places to store a window configuration.")
4781 (defvar org-finish-function nil
4782 "Function to be called when `C-c C-c' is used.
4783 This is for getting out of special buffers like remember.")
4786 ;; FIXME: Occasionally check by commenting these, to make sure
4787 ;; no other functions uses these, forgetting to let-bind them.
4788 (defvar entry)
4789 (defvar last-state)
4790 (defvar date)
4792 ;; Defined somewhere in this file, but used before definition.
4793 (defvar org-entities) ;; defined in org-entities.el
4794 (defvar org-struct-menu)
4795 (defvar org-org-menu)
4796 (defvar org-tbl-menu)
4798 ;;;; Define the Org-mode
4800 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4801 (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"))
4804 ;; We use a before-change function to check if a table might need
4805 ;; an update.
4806 (defvar org-table-may-need-update t
4807 "Indicates that a table might need an update.
4808 This variable is set by `org-before-change-function'.
4809 `org-table-align' sets it back to nil.")
4810 (defun org-before-change-function (beg end)
4811 "Every change indicates that a table might need an update."
4812 (setq org-table-may-need-update t))
4813 (defvar org-mode-map)
4814 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4815 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4816 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4817 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4818 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4819 (defvar org-table-buffer-is-an nil)
4821 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
4822 ;; some places -- e.g. see the macro org-with-limited-levels.
4824 ;; In Org buffers, the value of `outline-regexp' is that of
4825 ;; `org-outline-regexp'. The only function still directly relying on
4826 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
4827 ;; job when `orgstruct-mode' is active.
4828 (defvar org-outline-regexp "\\*+ "
4829 "Regexp to match Org headlines.")
4830 (defconst org-outline-regexp-bol "^\\*+ "
4831 "Regexp to match Org headlines.
4832 This is similar to `org-outline-regexp' but additionally makes
4833 sure that we are at the beginning of the line.")
4835 (defconst org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4836 "Matches an headline, putting stars and text into groups.
4837 Stars are put in group 1 and the trimmed body in group 2.")
4838 (defconst org-heading-keyword-regexp-format
4839 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4840 "Printf format for a regexp matching an headline with some keyword.
4841 This regexp will match the headline of any node which has the
4842 exact keyword that is put into the format. The keyword isn't in
4843 any group by default, but the stars and the body are.")
4844 (defconst org-heading-keyword-maybe-regexp-format
4845 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4846 "Printf format for a regexp matching an headline, possibly with some keyword.
4847 This regexp can match any headline with the specified keyword, or
4848 without a keyword. The keyword isn't in any group by default,
4849 but the stars and the body are.")
4851 ;;;###autoload
4852 (define-derived-mode org-mode outline-mode "Org"
4853 "Outline-based notes management and organizer, alias
4854 \"Carsten's outline-mode for keeping track of everything.\"
4856 Org-mode develops organizational tasks around a NOTES file which
4857 contains information about projects as plain text. Org-mode is
4858 implemented on top of outline-mode, which is ideal to keep the content
4859 of large files well structured. It supports ToDo items, deadlines and
4860 time stamps, which magically appear in the diary listing of the Emacs
4861 calendar. Tables are easily created with a built-in table editor.
4862 Plain text URL-like links connect to websites, emails (VM), Usenet
4863 messages (Gnus), BBDB entries, and any files related to the project.
4864 For printing and sharing of notes, an Org-mode file (or a part of it)
4865 can be exported as a structured ASCII or HTML file.
4867 The following commands are available:
4869 \\{org-mode-map}"
4871 ;; Get rid of Outline menus, they are not needed
4872 ;; Need to do this here because define-derived-mode sets up
4873 ;; the keymap so late. Still, it is a waste to call this each time
4874 ;; we switch another buffer into org-mode.
4875 (if (featurep 'xemacs)
4876 (when (boundp 'outline-mode-menu-heading)
4877 ;; Assume this is Greg's port, it uses easymenu
4878 (easy-menu-remove outline-mode-menu-heading)
4879 (easy-menu-remove outline-mode-menu-show)
4880 (easy-menu-remove outline-mode-menu-hide))
4881 (define-key org-mode-map [menu-bar headings] 'undefined)
4882 (define-key org-mode-map [menu-bar hide] 'undefined)
4883 (define-key org-mode-map [menu-bar show] 'undefined))
4885 (org-load-modules-maybe)
4886 (easy-menu-add org-org-menu)
4887 (easy-menu-add org-tbl-menu)
4888 (org-install-agenda-files-menu)
4889 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4890 (add-to-invisibility-spec '(org-cwidth))
4891 (add-to-invisibility-spec '(org-hide-block . t))
4892 (when (featurep 'xemacs)
4893 (org-set-local 'line-move-ignore-invisible t))
4894 (org-set-local 'outline-regexp org-outline-regexp)
4895 (org-set-local 'outline-level 'org-outline-level)
4896 (setq bidi-paragraph-direction 'left-to-right)
4897 (when (and org-ellipsis
4898 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4899 (fboundp 'make-glyph-code))
4900 (unless org-display-table
4901 (setq org-display-table (make-display-table)))
4902 (set-display-table-slot
4903 org-display-table 4
4904 (vconcat (mapcar
4905 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4906 org-ellipsis)))
4907 (if (stringp org-ellipsis) org-ellipsis "..."))))
4908 (setq buffer-display-table org-display-table))
4909 (org-set-regexps-and-options)
4910 (when (and org-tag-faces (not org-tags-special-faces-re))
4911 ;; tag faces set outside customize.... force initialization.
4912 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4913 ;; Calc embedded
4914 (org-set-local 'calc-embedded-open-mode "# ")
4915 (modify-syntax-entry ?@ "w")
4916 (if org-startup-truncated (setq truncate-lines t))
4917 (org-set-local 'font-lock-unfontify-region-function
4918 'org-unfontify-region)
4919 ;; Activate before-change-function
4920 (org-set-local 'org-table-may-need-update t)
4921 (org-add-hook 'before-change-functions 'org-before-change-function nil
4922 'local)
4923 ;; Check for running clock before killing a buffer
4924 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4925 ;; Paragraphs and auto-filling
4926 (org-set-autofill-regexps)
4927 (setq indent-line-function 'org-indent-line-function)
4928 (org-update-radio-target-regexp)
4929 ;; Beginning/end of defun
4930 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
4931 (org-set-local 'end-of-defun-function 'org-end-of-defun)
4932 ;; Next error for sparse trees
4933 (org-set-local 'next-error-function 'org-occur-next-match)
4934 ;; Make sure dependence stuff works reliably, even for users who set it
4935 ;; too late :-(
4936 (if org-enforce-todo-dependencies
4937 (add-hook 'org-blocker-hook
4938 'org-block-todo-from-children-or-siblings-or-parent)
4939 (remove-hook 'org-blocker-hook
4940 'org-block-todo-from-children-or-siblings-or-parent))
4941 (if org-enforce-todo-checkbox-dependencies
4942 (add-hook 'org-blocker-hook
4943 'org-block-todo-from-checkboxes)
4944 (remove-hook 'org-blocker-hook
4945 'org-block-todo-from-checkboxes))
4947 ;; Comment characters
4948 (org-set-local 'comment-start "#")
4949 (org-set-local 'comment-padding " ")
4951 ;; Align options lines
4952 (org-set-local
4953 'align-mode-rules-list
4954 '((org-in-buffer-settings
4955 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4956 (modes . '(org-mode)))))
4958 ;; Imenu
4959 (org-set-local 'imenu-create-index-function
4960 'org-imenu-get-tree)
4962 ;; Make isearch reveal context
4963 (if (or (featurep 'xemacs)
4964 (not (boundp 'outline-isearch-open-invisible-function)))
4965 ;; Emacs 21 and XEmacs make use of the hook
4966 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4967 ;; Emacs 22 deals with this through a special variable
4968 (org-set-local 'outline-isearch-open-invisible-function
4969 (lambda (&rest ignore) (org-show-context 'isearch))))
4971 ;; Turn on org-beamer-mode?
4972 (and org-startup-with-beamer-mode (org-beamer-mode 1))
4974 ;; Setup the pcomplete hooks
4975 (set (make-local-variable 'pcomplete-command-completion-function)
4976 'org-pcomplete-initial)
4977 (set (make-local-variable 'pcomplete-command-name-function)
4978 'org-command-at-point)
4979 (set (make-local-variable 'pcomplete-default-completion-function)
4980 'ignore)
4981 (set (make-local-variable 'pcomplete-parse-arguments-function)
4982 'org-parse-arguments)
4983 (set (make-local-variable 'pcomplete-termination-string) "")
4984 (set (make-local-variable 'face-remapping-alist)
4985 '((default org-default)))
4987 ;; If empty file that did not turn on org-mode automatically, make it to.
4988 (if (and org-insert-mode-line-in-empty-file
4989 (org-called-interactively-p 'any)
4990 (= (point-min) (point-max)))
4991 (insert "# -*- mode: org -*-\n\n"))
4992 (unless org-inhibit-startup
4993 (when org-startup-align-all-tables
4994 (let ((bmp (buffer-modified-p)))
4995 (org-table-map-tables 'org-table-align 'quietly)
4996 (set-buffer-modified-p bmp)))
4997 (when org-startup-with-inline-images
4998 (org-display-inline-images))
4999 (when org-startup-indented
5000 (require 'org-indent)
5001 (org-indent-mode 1))
5002 (unless org-inhibit-startup-visibility-stuff
5003 (org-set-startup-visibility))))
5005 (when (fboundp 'abbrev-table-put)
5006 (abbrev-table-put org-mode-abbrev-table
5007 :parents (list text-mode-abbrev-table)))
5009 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5011 (defun org-current-time ()
5012 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5013 (if (> (car org-time-stamp-rounding-minutes) 1)
5014 (let ((r (car org-time-stamp-rounding-minutes))
5015 (time (decode-time)))
5016 (apply 'encode-time
5017 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5018 (nthcdr 2 time))))
5019 (current-time)))
5021 (defun org-today ()
5022 "Return today date, considering `org-extend-today-until'."
5023 (time-to-days
5024 (time-subtract (current-time)
5025 (list 0 (* 3600 org-extend-today-until) 0))))
5027 ;;;; Font-Lock stuff, including the activators
5029 (defvar org-mouse-map (make-sparse-keymap))
5030 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5031 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5032 (when org-mouse-1-follows-link
5033 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5034 (when org-tab-follows-link
5035 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5036 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5038 (require 'font-lock)
5040 (defconst org-non-link-chars "]\t\n\r<>")
5041 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5042 "shell" "elisp" "doi" "message"))
5043 (defvar org-link-types-re nil
5044 "Matches a link that has a url-like prefix like \"http:\"")
5045 (defvar org-link-re-with-space nil
5046 "Matches a link with spaces, optional angular brackets around it.")
5047 (defvar org-link-re-with-space2 nil
5048 "Matches a link with spaces, optional angular brackets around it.")
5049 (defvar org-link-re-with-space3 nil
5050 "Matches a link with spaces, only for internal part in bracket links.")
5051 (defvar org-angle-link-re nil
5052 "Matches link with angular brackets, spaces are allowed.")
5053 (defvar org-plain-link-re nil
5054 "Matches plain link, without spaces.")
5055 (defvar org-bracket-link-regexp nil
5056 "Matches a link in double brackets.")
5057 (defvar org-bracket-link-analytic-regexp nil
5058 "Regular expression used to analyze links.
5059 Here is what the match groups contain after a match:
5060 1: http:
5061 2: http
5062 3: path
5063 4: [desc]
5064 5: desc")
5065 (defvar org-bracket-link-analytic-regexp++ nil
5066 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5067 (defvar org-any-link-re nil
5068 "Regular expression matching any link.")
5070 (defcustom org-match-sexp-depth 3
5071 "Number of stacked braces for sub/superscript matching.
5072 This has to be set before loading org.el to be effective."
5073 :group 'org-export-translation ; ??????????????????????????/
5074 :type 'integer)
5076 (defun org-create-multibrace-regexp (left right n)
5077 "Create a regular expression which will match a balanced sexp.
5078 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5079 as single character strings.
5080 The regexp returned will match the entire expression including the
5081 delimiters. It will also define a single group which contains the
5082 match except for the outermost delimiters. The maximum depth of
5083 stacked delimiters is N. Escaping delimiters is not possible."
5084 (let* ((nothing (concat "[^" left right "]*?"))
5085 (or "\\|")
5086 (re nothing)
5087 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5088 (while (> n 1)
5089 (setq n (1- n)
5090 re (concat re or next)
5091 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5092 (concat left "\\(" re "\\)" right)))
5094 (defvar org-match-substring-regexp
5095 (concat
5096 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5097 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5098 "\\|"
5099 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5100 "\\|"
5101 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5102 "The regular expression matching a sub- or superscript.")
5104 (defvar org-match-substring-with-braces-regexp
5105 (concat
5106 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5107 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5108 "\\)")
5109 "The regular expression matching a sub- or superscript, forcing braces.")
5111 (defun org-make-link-regexps ()
5112 "Update the link regular expressions.
5113 This should be called after the variable `org-link-types' has changed."
5114 (setq org-link-types-re
5115 (concat
5116 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5117 org-link-re-with-space
5118 (concat
5119 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5120 "\\([^" org-non-link-chars " ]"
5121 "[^" org-non-link-chars "]*"
5122 "[^" org-non-link-chars " ]\\)>?")
5123 org-link-re-with-space2
5124 (concat
5125 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5126 "\\([^" org-non-link-chars " ]"
5127 "[^\t\n\r]*"
5128 "[^" org-non-link-chars " ]\\)>?")
5129 org-link-re-with-space3
5130 (concat
5131 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5132 "\\([^" org-non-link-chars " ]"
5133 "[^\t\n\r]*\\)")
5134 org-angle-link-re
5135 (concat
5136 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5137 "\\([^" org-non-link-chars " ]"
5138 "[^" org-non-link-chars "]*"
5139 "\\)>")
5140 org-plain-link-re
5141 (concat
5142 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5143 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5144 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5145 org-bracket-link-regexp
5146 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5147 org-bracket-link-analytic-regexp
5148 (concat
5149 "\\[\\["
5150 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5151 "\\([^]]+\\)"
5152 "\\]"
5153 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5154 "\\]")
5155 org-bracket-link-analytic-regexp++
5156 (concat
5157 "\\[\\["
5158 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5159 "\\([^]]+\\)"
5160 "\\]"
5161 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5162 "\\]")
5163 org-any-link-re
5164 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5165 org-angle-link-re "\\)\\|\\("
5166 org-plain-link-re "\\)")))
5168 (org-make-link-regexps)
5170 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
5171 "Regular expression for fast time stamp matching.")
5172 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?\\)[]>]"
5173 "Regular expression for fast time stamp matching.")
5174 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5175 "Regular expression matching time strings for analysis.
5176 This one does not require the space after the date, so it can be used
5177 on a string that terminates immediately after the date.")
5178 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5179 "Regular expression matching time strings for analysis.")
5180 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5181 "Regular expression matching time stamps, with groups.")
5182 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5183 "Regular expression matching time stamps (also [..]), with groups.")
5184 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5185 "Regular expression matching a time stamp range.")
5186 (defconst org-tr-regexp-both
5187 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5188 "Regular expression matching a time stamp range.")
5189 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5190 org-ts-regexp "\\)?")
5191 "Regular expression matching a time stamp or time stamp range.")
5192 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5193 org-ts-regexp-both "\\)?")
5194 "Regular expression matching a time stamp or time stamp range.
5195 The time stamps may be either active or inactive.")
5197 (defvar org-emph-face nil)
5199 (defun org-do-emphasis-faces (limit)
5200 "Run through the buffer and add overlays to emphasised strings."
5201 (let (rtn a)
5202 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5203 (if (not (= (char-after (match-beginning 3))
5204 (char-after (match-beginning 4))))
5205 (progn
5206 (setq rtn t)
5207 (setq a (assoc (match-string 3) org-emphasis-alist))
5208 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5209 'face
5210 (nth 1 a))
5211 (and (nth 4 a)
5212 (org-remove-flyspell-overlays-in
5213 (match-beginning 0) (match-end 0)))
5214 (add-text-properties (match-beginning 2) (match-end 2)
5215 '(font-lock-multiline t org-emphasis t))
5216 (when org-hide-emphasis-markers
5217 (add-text-properties (match-end 4) (match-beginning 5)
5218 '(invisible org-link))
5219 (add-text-properties (match-beginning 3) (match-end 3)
5220 '(invisible org-link)))))
5221 (backward-char 1))
5222 rtn))
5224 (defun org-emphasize (&optional char)
5225 "Insert or change an emphasis, i.e. a font like bold or italic.
5226 If there is an active region, change that region to a new emphasis.
5227 If there is no region, just insert the marker characters and position
5228 the cursor between them.
5229 CHAR should be either the marker character, or the first character of the
5230 HTML tag associated with that emphasis. If CHAR is a space, the means
5231 to remove the emphasis of the selected region.
5232 If char is not given (for example in an interactive call) it
5233 will be prompted for."
5234 (interactive)
5235 (let ((eal org-emphasis-alist) e det
5236 (erc org-emphasis-regexp-components)
5237 (prompt "")
5238 (string "") beg end move tag c s)
5239 (if (org-region-active-p)
5240 (setq beg (region-beginning) end (region-end)
5241 string (buffer-substring beg end))
5242 (setq move t))
5244 (while (setq e (pop eal))
5245 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5246 c (aref tag 0))
5247 (push (cons c (string-to-char (car e))) det)
5248 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5249 (substring tag 1)))))
5250 (setq det (nreverse det))
5251 (unless char
5252 (message "%s" (concat "Emphasis marker or tag:" prompt))
5253 (setq char (read-char-exclusive)))
5254 (setq char (or (cdr (assoc char det)) char))
5255 (if (equal char ?\ )
5256 (setq s "" move nil)
5257 (unless (assoc (char-to-string char) org-emphasis-alist)
5258 (error "No such emphasis marker: \"%c\"" char))
5259 (setq s (char-to-string char)))
5260 (while (and (> (length string) 1)
5261 (equal (substring string 0 1) (substring string -1))
5262 (assoc (substring string 0 1) org-emphasis-alist))
5263 (setq string (substring string 1 -1)))
5264 (setq string (concat s string s))
5265 (if beg (delete-region beg end))
5266 (unless (or (bolp)
5267 (string-match (concat "[" (nth 0 erc) "\n]")
5268 (char-to-string (char-before (point)))))
5269 (insert " "))
5270 (unless (or (eobp)
5271 (string-match (concat "[" (nth 1 erc) "\n]")
5272 (char-to-string (char-after (point)))))
5273 (insert " ") (backward-char 1))
5274 (insert string)
5275 (and move (backward-char 1))))
5277 (defconst org-nonsticky-props
5278 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5280 (defsubst org-rear-nonsticky-at (pos)
5281 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5283 (defun org-activate-plain-links (limit)
5284 "Run through the buffer and add overlays to links."
5285 (catch 'exit
5286 (let (f)
5287 (if (re-search-forward org-plain-link-re limit t)
5288 (progn
5289 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5290 (setq f (get-text-property (match-beginning 0) 'face))
5291 (if (or (eq f 'org-tag)
5292 (and (listp f) (memq 'org-tag f)))
5294 (add-text-properties (match-beginning 0) (match-end 0)
5295 (list 'mouse-face 'highlight
5296 'face 'org-link
5297 'keymap org-mouse-map))
5298 (org-rear-nonsticky-at (match-end 0)))
5299 t)))))
5301 (defun org-activate-code (limit)
5302 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5303 (progn
5304 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5305 (remove-text-properties (match-beginning 0) (match-end 0)
5306 '(display t invisible t intangible t))
5307 t)))
5309 (defcustom org-src-fontify-natively nil
5310 "When non-nil, fontify code in code blocks."
5311 :type 'boolean
5312 :group 'org-appearance
5313 :group 'org-babel)
5315 (defun org-fontify-meta-lines-and-blocks (limit)
5316 (condition-case nil
5317 (org-fontify-meta-lines-and-blocks-1 limit)
5318 (error (message "org-mode fontification error"))))
5320 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5321 "Fontify #+ lines and blocks, in the correct ways."
5322 (let ((case-fold-search t))
5323 (if (re-search-forward
5324 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5325 limit t)
5326 (let ((beg (match-beginning 0))
5327 (block-start (match-end 0))
5328 (block-end nil)
5329 (lang (match-string 7))
5330 (beg1 (line-beginning-position 2))
5331 (dc1 (downcase (match-string 2)))
5332 (dc3 (downcase (match-string 3)))
5333 end end1 quoting block-type ovl)
5334 (cond
5335 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
5336 ;; a single line of backend-specific content
5337 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5338 (remove-text-properties (match-beginning 0) (match-end 0)
5339 '(display t invisible t intangible t))
5340 (add-text-properties (match-beginning 1) (match-end 3)
5341 '(font-lock-fontified t face org-meta-line))
5342 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5343 '(font-lock-fontified t face org-block))
5344 ; for backend-specific code
5346 ((and (match-end 4) (equal dc3 "begin"))
5347 ;; Truly a block
5348 (setq block-type (downcase (match-string 5))
5349 quoting (member block-type org-protecting-blocks))
5350 (when (re-search-forward
5351 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5352 nil t) ;; on purpose, we look further than LIMIT
5353 (setq end (match-end 0) end1 (1- (match-beginning 0)))
5354 (setq block-end (match-beginning 0))
5355 (when quoting
5356 (remove-text-properties beg end
5357 '(display t invisible t intangible t)))
5358 (add-text-properties
5359 beg end
5360 '(font-lock-fontified t font-lock-multiline t))
5361 (add-text-properties beg beg1 '(face org-meta-line))
5362 (add-text-properties end1 (min (point-max) (1+ end))
5363 '(face org-meta-line)) ; for end_src
5364 (cond
5365 ((and lang (not (string= lang "")) org-src-fontify-natively)
5366 (org-src-font-lock-fontify-block lang block-start block-end)
5367 ;; remove old background overlays
5368 (mapc (lambda (ov)
5369 (if (eq (overlay-get ov 'face) 'org-block-background)
5370 (delete-overlay ov)))
5371 (overlays-at (/ (+ beg1 block-end) 2)))
5372 ;; add a background overlay
5373 (setq ovl (make-overlay beg1 block-end))
5374 (overlay-put ovl 'face 'org-block-background)
5375 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5376 (quoting
5377 (add-text-properties beg1 (min (point-max) (1+ end1))
5378 '(face org-block))) ; end of source block
5379 ((not org-fontify-quote-and-verse-blocks))
5380 ((string= block-type "quote")
5381 (add-text-properties beg1 (1+ end1) '(face org-quote)))
5382 ((string= block-type "verse")
5383 (add-text-properties beg1 (1+ end1) '(face org-verse))))
5384 (add-text-properties beg beg1 '(face org-block-begin-line))
5385 (add-text-properties (1+ end) (1+ end1) '(face org-block-end-line))
5387 ((member dc1 '("title:" "author:" "email:" "date:"))
5388 (add-text-properties
5389 beg (match-end 3)
5390 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5391 '(font-lock-fontified t invisible t)
5392 '(font-lock-fontified t face org-document-info-keyword)))
5393 (add-text-properties
5394 (match-beginning 6) (match-end 6)
5395 (if (string-equal dc1 "title:")
5396 '(font-lock-fontified t face org-document-title)
5397 '(font-lock-fontified t face org-document-info))))
5398 ((not (member (char-after beg) '(?\ ?\t)))
5399 ;; just any other in-buffer setting, but not indented
5400 (add-text-properties
5401 beg (1+ (match-end 0))
5402 '(font-lock-fontified t face org-meta-line))
5404 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
5405 "orgtbl:" "tblfm:" "tblname:" "result:"
5406 "results:" "source:" "srcname:" "call:"
5407 "data:" "header:" "headers:"))
5408 (and (match-end 4) (equal dc3 "attr")))
5409 (add-text-properties
5410 beg (match-end 0)
5411 '(font-lock-fontified t face org-meta-line))
5413 ((member dc3 '(" " ""))
5414 (add-text-properties
5415 beg (match-end 0)
5416 '(font-lock-fontified t face font-lock-comment-face)))
5417 (t nil))))))
5419 (defun org-activate-angle-links (limit)
5420 "Run through the buffer and add overlays to links."
5421 (if (re-search-forward org-angle-link-re limit t)
5422 (progn
5423 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5424 (add-text-properties (match-beginning 0) (match-end 0)
5425 (list 'mouse-face 'highlight
5426 'keymap org-mouse-map))
5427 (org-rear-nonsticky-at (match-end 0))
5428 t)))
5430 (defun org-activate-footnote-links (limit)
5431 "Run through the buffer and add overlays to footnotes."
5432 (let ((fn (org-footnote-next-reference-or-definition limit)))
5433 (when fn
5434 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5435 (org-remove-flyspell-overlays-in beg end)
5436 (add-text-properties beg end
5437 (list 'mouse-face 'highlight
5438 'keymap org-mouse-map
5439 'help-echo
5440 (if (= (point-at-bol) beg)
5441 "Footnote definition"
5442 "Footnote reference")
5443 'font-lock-fontified t
5444 'font-lock-multiline t
5445 'face 'org-footnote))))))
5447 (defun org-activate-bracket-links (limit)
5448 "Run through the buffer and add overlays to bracketed links."
5449 (if (re-search-forward org-bracket-link-regexp limit t)
5450 (let* ((help (concat "LINK: "
5451 (org-match-string-no-properties 1)))
5452 ;; FIXME: above we should remove the escapes.
5453 ;; but that requires another match, protecting match data,
5454 ;; a lot of overhead for font-lock.
5455 (ip (org-maybe-intangible
5456 (list 'invisible 'org-link
5457 'keymap org-mouse-map 'mouse-face 'highlight
5458 'font-lock-multiline t 'help-echo help)))
5459 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5460 'font-lock-multiline t 'help-echo help)))
5461 ;; We need to remove the invisible property here. Table narrowing
5462 ;; may have made some of this invisible.
5463 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5464 (remove-text-properties (match-beginning 0) (match-end 0)
5465 '(invisible nil))
5466 (if (match-end 3)
5467 (progn
5468 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5469 (org-rear-nonsticky-at (match-beginning 3))
5470 (add-text-properties (match-beginning 3) (match-end 3) vp)
5471 (org-rear-nonsticky-at (match-end 3))
5472 (add-text-properties (match-end 3) (match-end 0) ip)
5473 (org-rear-nonsticky-at (match-end 0)))
5474 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5475 (org-rear-nonsticky-at (match-beginning 1))
5476 (add-text-properties (match-beginning 1) (match-end 1) vp)
5477 (org-rear-nonsticky-at (match-end 1))
5478 (add-text-properties (match-end 1) (match-end 0) ip)
5479 (org-rear-nonsticky-at (match-end 0)))
5480 t)))
5482 (defun org-activate-dates (limit)
5483 "Run through the buffer and add overlays to dates."
5484 (if (re-search-forward org-tsr-regexp-both limit t)
5485 (progn
5486 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5487 (add-text-properties (match-beginning 0) (match-end 0)
5488 (list 'mouse-face 'highlight
5489 'keymap org-mouse-map))
5490 (org-rear-nonsticky-at (match-end 0))
5491 (when org-display-custom-times
5492 (if (match-end 3)
5493 (org-display-custom-time (match-beginning 3) (match-end 3)))
5494 (org-display-custom-time (match-beginning 1) (match-end 1)))
5495 t)))
5497 (defvar org-target-link-regexp nil
5498 "Regular expression matching radio targets in plain text.")
5499 (make-variable-buffer-local 'org-target-link-regexp)
5500 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5501 "Regular expression matching a link target.")
5502 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5503 "Regular expression matching a radio target.")
5504 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5505 "Regular expression matching any target.")
5507 (defun org-activate-target-links (limit)
5508 "Run through the buffer and add overlays to target matches."
5509 (when org-target-link-regexp
5510 (let ((case-fold-search t))
5511 (if (re-search-forward org-target-link-regexp limit t)
5512 (progn
5513 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5514 (add-text-properties (match-beginning 0) (match-end 0)
5515 (list 'mouse-face 'highlight
5516 'keymap org-mouse-map
5517 'help-echo "Radio target link"
5518 'org-linked-text t))
5519 (org-rear-nonsticky-at (match-end 0))
5520 t)))))
5522 (defun org-update-radio-target-regexp ()
5523 "Find all radio targets in this file and update the regular expression."
5524 (interactive)
5525 (when (memq 'radio org-activate-links)
5526 (setq org-target-link-regexp
5527 (org-make-target-link-regexp (org-all-targets 'radio)))
5528 (org-restart-font-lock)))
5530 (defun org-hide-wide-columns (limit)
5531 (let (s e)
5532 (setq s (text-property-any (point) (or limit (point-max))
5533 'org-cwidth t))
5534 (when s
5535 (setq e (next-single-property-change s 'org-cwidth))
5536 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5537 (goto-char e)
5538 t)))
5540 (defvar org-latex-and-specials-regexp nil
5541 "Regular expression for highlighting export special stuff.")
5542 (defvar org-match-substring-regexp)
5543 (defvar org-match-substring-with-braces-regexp)
5545 ;; This should be with the exporter code, but we also use if for font-locking
5546 (defconst org-export-html-special-string-regexps
5547 '(("\\\\-" . "&shy;")
5548 ("---\\([^-]\\)" . "&mdash;\\1")
5549 ("--\\([^-]\\)" . "&ndash;\\1")
5550 ("\\.\\.\\." . "&hellip;"))
5551 "Regular expressions for special string conversion.")
5554 (defun org-compute-latex-and-specials-regexp ()
5555 "Compute regular expression for stuff treated specially by exporters."
5556 (if (not org-highlight-latex-fragments-and-specials)
5557 (org-set-local 'org-latex-and-specials-regexp nil)
5558 (require 'org-exp)
5559 (let*
5560 ((matchers (plist-get org-format-latex-options :matchers))
5561 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5562 org-latex-regexps)))
5563 (org-export-allow-BIND nil)
5564 (options (org-combine-plists (org-default-export-plist)
5565 (org-infile-export-plist)))
5566 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5567 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5568 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5569 (org-export-html-expand (plist-get options :expand-quoted-html))
5570 (org-export-with-special-strings (plist-get options :special-strings))
5571 (re-sub
5572 (cond
5573 ((equal org-export-with-sub-superscripts '{})
5574 (list org-match-substring-with-braces-regexp))
5575 (org-export-with-sub-superscripts
5576 (list org-match-substring-regexp))
5577 (t nil)))
5578 (re-latex
5579 (if org-export-with-LaTeX-fragments
5580 (mapcar (lambda (x) (nth 1 x)) latexs)))
5581 (re-macros
5582 (if org-export-with-TeX-macros
5583 (list (concat "\\\\"
5584 (regexp-opt
5585 (append
5587 (delq nil
5588 (mapcar 'car-safe
5589 (append org-entities-user
5590 org-entities)))
5591 (if (boundp 'org-latex-entities)
5592 (mapcar (lambda (x)
5593 (or (car-safe x) x))
5594 org-latex-entities)
5595 nil))
5596 'words))) ; FIXME
5598 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5599 (re-special (if org-export-with-special-strings
5600 (mapcar (lambda (x) (car x))
5601 org-export-html-special-string-regexps)))
5602 (re-rest
5603 (delq nil
5604 (list
5605 (if org-export-html-expand "@<[^>\n]+>")
5606 ))))
5607 (org-set-local
5608 'org-latex-and-specials-regexp
5609 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5610 re-rest) "\\|")))))
5612 (defun org-do-latex-and-special-faces (limit)
5613 "Run through the buffer and add overlays to links."
5614 (when org-latex-and-specials-regexp
5615 (let (rtn d)
5616 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5617 limit t))
5618 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5619 'face))
5620 '(org-code org-verbatim underline)))
5621 (progn
5622 (setq rtn t
5623 d (cond ((member (char-after (1+ (match-beginning 0)))
5624 '(?_ ?^)) 1)
5625 (t 0)))
5626 (font-lock-prepend-text-property
5627 (+ d (match-beginning 0)) (match-end 0)
5628 'face 'org-latex-and-export-specials)
5629 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5630 '(font-lock-multiline t)))))
5631 rtn)))
5633 (defun org-restart-font-lock ()
5634 "Restart `font-lock-mode', to force refontification."
5635 (when (and (boundp 'font-lock-mode) font-lock-mode)
5636 (font-lock-mode -1)
5637 (font-lock-mode 1)))
5639 (defun org-all-targets (&optional radio)
5640 "Return a list of all targets in this file.
5641 With optional argument RADIO, only find radio targets."
5642 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5643 rtn)
5644 (save-excursion
5645 (goto-char (point-min))
5646 (while (re-search-forward re nil t)
5647 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5648 rtn)))
5650 (defun org-make-target-link-regexp (targets)
5651 "Make regular expression matching all strings in TARGETS.
5652 The regular expression finds the targets also if there is a line break
5653 between words."
5654 (and targets
5655 (concat
5656 "\\<\\("
5657 (mapconcat
5658 (lambda (x)
5659 (setq x (regexp-quote x))
5660 (while (string-match " +" x)
5661 (setq x (replace-match "\\s-+" t t x)))
5663 targets
5664 "\\|")
5665 "\\)\\>")))
5667 (defun org-activate-tags (limit)
5668 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5669 (progn
5670 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5671 (add-text-properties (match-beginning 1) (match-end 1)
5672 (list 'mouse-face 'highlight
5673 'keymap org-mouse-map))
5674 (org-rear-nonsticky-at (match-end 1))
5675 t)))
5677 (defun org-outline-level ()
5678 "Compute the outline level of the heading at point.
5679 This function assumes that the cursor is at the beginning of a line matched
5680 by `outline-regexp'. Otherwise it returns garbage.
5681 If this is called at a normal headline, the level is the number of stars.
5682 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5683 (save-excursion
5684 (looking-at org-outline-regexp)
5685 (1- (- (match-end 0) (match-beginning 0)))))
5687 (defvar org-font-lock-keywords nil)
5689 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5690 "Regular expression matching a property line.")
5692 (defvar org-font-lock-hook nil
5693 "Functions to be called for special font lock stuff.")
5695 (defvar org-font-lock-set-keywords-hook nil
5696 "Functions that can manipulate `org-font-lock-extra-keywords'.
5697 This is calles after `org-font-lock-extra-keywords' is defined, but before
5698 it is installed to be used by font lock. This can be useful if something
5699 needs to be inserted at a specific position in the font-lock sequence.")
5701 (defun org-font-lock-hook (limit)
5702 (run-hook-with-args 'org-font-lock-hook limit))
5704 (defun org-set-font-lock-defaults ()
5705 (let* ((em org-fontify-emphasized-text)
5706 (lk org-activate-links)
5707 (org-font-lock-extra-keywords
5708 (list
5709 ;; Call the hook
5710 '(org-font-lock-hook)
5711 ;; Headlines
5712 `(,(if org-fontify-whole-heading-line
5713 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5714 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5715 (1 (org-get-level-face 1))
5716 (2 (org-get-level-face 2))
5717 (3 (org-get-level-face 3)))
5718 ;; Table lines
5719 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5720 (1 'org-table t))
5721 ;; Table internals
5722 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5723 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5724 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5725 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5726 ;; Drawers
5727 (list org-drawer-regexp '(0 'org-special-keyword t))
5728 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5729 ;; Properties
5730 (list org-property-re
5731 '(1 'org-special-keyword t)
5732 '(3 'org-property-value t))
5733 ;; Links
5734 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5735 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5736 (if (memq 'plain lk) '(org-activate-plain-links))
5737 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5738 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5739 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5740 (if (memq 'footnote lk) '(org-activate-footnote-links))
5741 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5742 '(org-hide-wide-columns (0 nil append))
5743 ;; TODO keyword
5744 (list (format org-heading-keyword-regexp-format
5745 org-todo-regexp)
5746 '(2 (org-get-todo-face 2) t))
5747 ;; DONE
5748 (if org-fontify-done-headline
5749 (list (format org-heading-keyword-regexp-format
5750 (concat
5751 "\\("
5752 (mapconcat 'regexp-quote org-done-keywords "\\|")
5753 "\\)"))
5754 '(2 'org-headline-done t))
5755 nil)
5756 ;; Priorities
5757 '(org-font-lock-add-priority-faces)
5758 ;; Tags
5759 '(org-font-lock-add-tag-faces)
5760 ;; Special keywords
5761 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5762 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5763 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5764 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5765 ;; Emphasis
5766 (if em
5767 (if (featurep 'xemacs)
5768 '(org-do-emphasis-faces (0 nil append))
5769 '(org-do-emphasis-faces)))
5770 ;; Checkboxes
5771 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5772 1 'org-checkbox prepend)
5773 (if (cdr (assq 'checkbox org-list-automatic-rules))
5774 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5775 (0 (org-get-checkbox-statistics-face) t)))
5776 ;; Description list items
5777 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5778 1 'bold prepend)
5779 ;; ARCHIVEd headings
5780 (list (concat
5781 org-outline-regexp-bol
5782 "\\(.*:" org-archive-tag ":.*\\)")
5783 '(1 'org-archived prepend))
5784 ;; Specials
5785 '(org-do-latex-and-special-faces)
5786 '(org-fontify-entities)
5787 '(org-raise-scripts)
5788 ;; Code
5789 '(org-activate-code (1 'org-code t))
5790 ;; COMMENT
5791 (list (format org-heading-keyword-regexp-format
5792 (concat "\\("
5793 org-comment-string "\\|" org-quote-string
5794 "\\)"))
5795 '(1 'org-special-keyword t))
5796 '("^#.*" (0 'font-lock-comment-face t))
5797 ;; Blocks and meta lines
5798 '(org-fontify-meta-lines-and-blocks)
5800 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5801 (run-hooks 'org-font-lock-set-keywords-hook)
5802 ;; Now set the full font-lock-keywords
5803 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5804 (org-set-local 'font-lock-defaults
5805 '(org-font-lock-keywords t nil nil backward-paragraph))
5806 (kill-local-variable 'font-lock-keywords) nil))
5808 (defun org-toggle-pretty-entities ()
5809 "Toggle the composition display of entities as UTF8 characters."
5810 (interactive)
5811 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5812 (org-restart-font-lock)
5813 (if org-pretty-entities
5814 (message "Entities are displayed as UTF8 characers")
5815 (save-restriction
5816 (widen)
5817 (org-decompose-region (point-min) (point-max))
5818 (message "Entities are displayed plain"))))
5820 (defun org-fontify-entities (limit)
5821 "Find an entity to fontify."
5822 (let (ee)
5823 (when org-pretty-entities
5824 (catch 'match
5825 (while (re-search-forward
5826 "\\\\\\(frac[13][24]\\|[a-zA-Z]+\\)\\($\\|[^[:alpha:]\n]\\)"
5827 limit t)
5828 (if (and (not (org-in-indented-comment-line))
5829 (setq ee (org-entity-get (match-string 1)))
5830 (= (length (nth 6 ee)) 1))
5831 (progn
5832 (add-text-properties
5833 (match-beginning 0) (match-end 1)
5834 (list 'font-lock-fontified t))
5835 (compose-region (match-beginning 0) (match-end 1)
5836 (nth 6 ee) nil)
5837 (backward-char 1)
5838 (throw 'match t))))
5839 nil))))
5841 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5842 "Fontify string S like in Org-mode."
5843 (with-temp-buffer
5844 (insert s)
5845 (let ((org-odd-levels-only odd-levels))
5846 (org-mode)
5847 (font-lock-fontify-buffer)
5848 (buffer-string))))
5850 (defvar org-m nil)
5851 (defvar org-l nil)
5852 (defvar org-f nil)
5853 (defun org-get-level-face (n)
5854 "Get the right face for match N in font-lock matching of headlines."
5855 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5856 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5857 (if org-cycle-level-faces
5858 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5859 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5860 (cond
5861 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5862 ((eq n 2) org-f)
5863 (t (if org-level-color-stars-only nil org-f))))
5866 (defun org-get-todo-face (kwd)
5867 "Get the right face for a TODO keyword KWD.
5868 If KWD is a number, get the corresponding match group."
5869 (if (numberp kwd) (setq kwd (match-string kwd)))
5870 (or (org-face-from-face-or-color
5871 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5872 (and (member kwd org-done-keywords) 'org-done)
5873 'org-todo))
5875 (defun org-face-from-face-or-color (context inherit face-or-color)
5876 "Create a face list that inherits INHERIT, but sets the foreground color.
5877 When FACE-OR-COLOR is not a string, just return it."
5878 (if (stringp face-or-color)
5879 (list :inherit inherit
5880 (cdr (assoc context org-faces-easy-properties))
5881 face-or-color)
5882 face-or-color))
5884 (defun org-font-lock-add-tag-faces (limit)
5885 "Add the special tag faces."
5886 (when (and org-tag-faces org-tags-special-faces-re)
5887 (while (re-search-forward org-tags-special-faces-re limit t)
5888 (add-text-properties (match-beginning 1) (match-end 1)
5889 (list 'face (org-get-tag-face 1)
5890 'font-lock-fontified t))
5891 (backward-char 1))))
5893 (defun org-font-lock-add-priority-faces (limit)
5894 "Add the special priority faces."
5895 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5896 (add-text-properties
5897 (match-beginning 0) (match-end 0)
5898 (list 'face (or (org-face-from-face-or-color
5899 'priority 'org-special-keyword
5900 (cdr (assoc (char-after (match-beginning 1))
5901 org-priority-faces)))
5902 'org-special-keyword)
5903 'font-lock-fontified t))))
5905 (defun org-get-tag-face (kwd)
5906 "Get the right face for a TODO keyword KWD.
5907 If KWD is a number, get the corresponding match group."
5908 (if (numberp kwd) (setq kwd (match-string kwd)))
5909 (or (org-face-from-face-or-color
5910 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5911 'org-tag))
5913 (defun org-unfontify-region (beg end &optional maybe_loudly)
5914 "Remove fontification and activation overlays from links."
5915 (font-lock-default-unfontify-region beg end)
5916 (let* ((buffer-undo-list t)
5917 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5918 (inhibit-modification-hooks t)
5919 deactivate-mark buffer-file-name buffer-file-truename)
5920 (org-decompose-region beg end)
5921 (remove-text-properties beg end
5922 '(mouse-face t keymap t org-linked-text t
5923 invisible t intangible t
5924 org-no-flyspell t org-emphasis t))
5925 (org-remove-font-lock-display-properties beg end)))
5927 (defconst org-script-display '(((raise -0.3) (height 0.7))
5928 ((raise 0.3) (height 0.7))
5929 ((raise -0.5))
5930 ((raise 0.5)))
5931 "Display properties for showing superscripts and subscripts.")
5933 (defun org-remove-font-lock-display-properties (beg end)
5934 "Remove specific display properties that have been added by font lock.
5935 The will remove the raise properties that are used to show superscripts
5936 and subscripts."
5937 (let (next prop)
5938 (while (< beg end)
5939 (setq next (next-single-property-change beg 'display nil end)
5940 prop (get-text-property beg 'display))
5941 (if (member prop org-script-display)
5942 (put-text-property beg next 'display nil))
5943 (setq beg next))))
5945 (defun org-raise-scripts (limit)
5946 "Add raise properties to sub/superscripts."
5947 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
5948 (if (re-search-forward
5949 (if (eq org-use-sub-superscripts t)
5950 org-match-substring-regexp
5951 org-match-substring-with-braces-regexp)
5952 limit t)
5953 (let* ((pos (point)) table-p comment-p
5954 (mpos (match-beginning 3))
5955 (emph-p (get-text-property mpos 'org-emphasis))
5956 (link-p (get-text-property mpos 'mouse-face))
5957 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
5958 (goto-char (point-at-bol))
5959 (setq table-p (org-looking-at-p org-table-dataline-regexp)
5960 comment-p (org-looking-at-p "[ \t]*#"))
5961 (goto-char pos)
5962 ;; FIXME: Should we go back one character here, for a_b^c
5963 ;; (goto-char (1- pos)) ;????????????????????
5964 (if (or comment-p emph-p link-p keyw-p)
5966 (put-text-property (match-beginning 3) (match-end 0)
5967 'display
5968 (if (equal (char-after (match-beginning 2)) ?^)
5969 (nth (if table-p 3 1) org-script-display)
5970 (nth (if table-p 2 0) org-script-display)))
5971 (add-text-properties (match-beginning 2) (match-end 2)
5972 (list 'invisible t
5973 'org-dwidth t 'org-dwidth-n 1))
5974 (if (and (eq (char-after (match-beginning 3)) ?{)
5975 (eq (char-before (match-end 3)) ?}))
5976 (progn
5977 (add-text-properties
5978 (match-beginning 3) (1+ (match-beginning 3))
5979 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
5980 (add-text-properties
5981 (1- (match-end 3)) (match-end 3)
5982 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
5983 t)))))
5985 ;;;; Visibility cycling, including org-goto and indirect buffer
5987 ;;; Cycling
5989 (defvar org-cycle-global-status nil)
5990 (make-variable-buffer-local 'org-cycle-global-status)
5991 (defvar org-cycle-subtree-status nil)
5992 (make-variable-buffer-local 'org-cycle-subtree-status)
5994 ;;;###autoload
5996 (defvar org-inlinetask-min-level)
5998 (defun org-cycle (&optional arg)
5999 "TAB-action and visibility cycling for Org-mode.
6001 This is the command invoked in Org-mode by the TAB key. Its main purpose
6002 is outline visibility cycling, but it also invokes other actions
6003 in special contexts.
6005 - When this function is called with a prefix argument, rotate the entire
6006 buffer through 3 states (global cycling)
6007 1. OVERVIEW: Show only top-level headlines.
6008 2. CONTENTS: Show all headlines of all levels, but no body text.
6009 3. SHOW ALL: Show everything.
6010 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6011 determined by the variable `org-startup-folded', and by any VISIBILITY
6012 properties in the buffer.
6013 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6014 including any drawers.
6016 - When inside a table, re-align the table and move to the next field.
6018 - When point is at the beginning of a headline, rotate the subtree started
6019 by this line through 3 different states (local cycling)
6020 1. FOLDED: Only the main headline is shown.
6021 2. CHILDREN: The main headline and the direct children are shown.
6022 From this state, you can move to one of the children
6023 and zoom in further.
6024 3. SUBTREE: Show the entire subtree, including body text.
6025 If there is no subtree, switch directly from CHILDREN to FOLDED.
6027 - When point is at the beginning of an empty headline and the variable
6028 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6029 of the headline by demoting and promoting it to likely levels. This
6030 speeds up creation document structure by pressing TAB once or several
6031 times right after creating a new headline.
6033 - When there is a numeric prefix, go up to a heading with level ARG, do
6034 a `show-subtree' and return to the previous cursor position. If ARG
6035 is negative, go up that many levels.
6037 - When point is not at the beginning of a headline, execute the global
6038 binding for TAB, which is re-indenting the line. See the option
6039 `org-cycle-emulate-tab' for details.
6041 - Special case: if point is at the beginning of the buffer and there is
6042 no headline in line 1, this function will act as if called with prefix arg
6043 (C-u TAB, same as S-TAB) also when called without prefix arg.
6044 But only if also the variable `org-cycle-global-at-bob' is t."
6045 (interactive "P")
6046 (org-load-modules-maybe)
6047 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6048 (and org-cycle-level-after-item/entry-creation
6049 (or (org-cycle-level)
6050 (org-cycle-item-indentation))))
6051 (let* ((limit-level
6052 (or org-cycle-max-level
6053 (and (boundp 'org-inlinetask-min-level)
6054 org-inlinetask-min-level
6055 (1- org-inlinetask-min-level))))
6056 (nstars (and limit-level
6057 (if org-odd-levels-only
6058 (and limit-level (1- (* limit-level 2)))
6059 limit-level)))
6060 (org-outline-regexp
6061 (if (not (eq major-mode 'org-mode))
6062 outline-regexp
6063 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6064 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6065 (not (looking-at org-outline-regexp))))
6066 (org-cycle-hook
6067 (if bob-special
6068 (delq 'org-optimize-window-after-visibility-change
6069 (copy-sequence org-cycle-hook))
6070 org-cycle-hook))
6071 (pos (point)))
6073 (if (or bob-special (equal arg '(4)))
6074 ;; special case: use global cycling
6075 (setq arg t))
6077 (cond
6079 ((equal arg '(16))
6080 (setq last-command 'dummy)
6081 (org-set-startup-visibility)
6082 (message "Startup visibility, plus VISIBILITY properties"))
6084 ((equal arg '(64))
6085 (show-all)
6086 (message "Entire buffer visible, including drawers"))
6088 ;; Table: enter it or move to the next field.
6089 ((org-at-table-p 'any)
6090 (if (org-at-table.el-p)
6091 (message "Use C-c ' to edit table.el tables")
6092 (if arg (org-table-edit-field t)
6093 (org-table-justify-field-maybe)
6094 (call-interactively 'org-table-next-field))))
6096 ((run-hook-with-args-until-success
6097 'org-tab-after-check-for-table-hook))
6099 ;; Global cycling: delegate to `org-cycle-internal-global'.
6100 ((eq arg t) (org-cycle-internal-global))
6102 ;; Drawers: delegate to `org-flag-drawer'.
6103 ((and org-drawers org-drawer-regexp
6104 (save-excursion
6105 (beginning-of-line 1)
6106 (looking-at org-drawer-regexp)))
6107 (org-flag-drawer ; toggle block visibility
6108 (not (get-char-property (match-end 0) 'invisible))))
6110 ;; Show-subtree, ARG levels up from here.
6111 ((integerp arg)
6112 (save-excursion
6113 (org-back-to-heading)
6114 (outline-up-heading (if (< arg 0) (- arg)
6115 (- (funcall outline-level) arg)))
6116 (org-show-subtree)))
6118 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6119 ((and (featurep 'org-inlinetask)
6120 (org-inlinetask-at-task-p)
6121 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6122 (org-inlinetask-toggle-visibility))
6124 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6125 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6126 (save-excursion (beginning-of-line 1)
6127 (looking-at org-outline-regexp)))
6128 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6129 (org-cycle-internal-local))
6131 ;; From there: TAB emulation and template completion.
6132 (buffer-read-only (org-back-to-heading))
6134 ((run-hook-with-args-until-success
6135 'org-tab-after-check-for-cycling-hook))
6137 ((org-try-structure-completion))
6139 ((org-try-cdlatex-tab))
6141 ((run-hook-with-args-until-success
6142 'org-tab-before-tab-emulation-hook))
6144 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6145 (or (not (bolp))
6146 (not (looking-at org-outline-regexp))))
6147 (call-interactively (global-key-binding "\t")))
6149 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6150 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6151 (or (and (eq org-cycle-emulate-tab 'white)
6152 (= (match-end 0) (point-at-eol)))
6153 (and (eq org-cycle-emulate-tab 'whitestart)
6154 (>= (match-end 0) pos))))
6156 (eq org-cycle-emulate-tab t))
6157 (call-interactively (global-key-binding "\t")))
6159 (t (save-excursion
6160 (org-back-to-heading)
6161 (org-cycle)))))))
6163 (defun org-cycle-internal-global ()
6164 "Do the global cycling action."
6165 (cond
6166 ((and (eq last-command this-command)
6167 (eq org-cycle-global-status 'overview))
6168 ;; We just created the overview - now do table of contents
6169 ;; This can be slow in very large buffers, so indicate action
6170 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6171 (message "CONTENTS...")
6172 (org-content)
6173 (message "CONTENTS...done")
6174 (setq org-cycle-global-status 'contents)
6175 (run-hook-with-args 'org-cycle-hook 'contents))
6177 ((and (eq last-command this-command)
6178 (eq org-cycle-global-status 'contents))
6179 ;; We just showed the table of contents - now show everything
6180 (run-hook-with-args 'org-pre-cycle-hook 'all)
6181 (show-all)
6182 (message "SHOW ALL")
6183 (setq org-cycle-global-status 'all)
6184 (run-hook-with-args 'org-cycle-hook 'all))
6187 ;; Default action: go to overview
6188 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6189 (org-overview)
6190 (message "OVERVIEW")
6191 (setq org-cycle-global-status 'overview)
6192 (run-hook-with-args 'org-cycle-hook 'overview))))
6194 (defun org-cycle-internal-local ()
6195 "Do the local cycling action."
6196 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6197 ;; First, determine end of headline (EOH), end of subtree or item
6198 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6199 (save-excursion
6200 (if (org-at-item-p)
6201 (progn
6202 (beginning-of-line)
6203 (setq struct (org-list-struct))
6204 (setq eoh (point-at-eol))
6205 (setq eos (org-list-get-item-end-before-blank (point) struct))
6206 (setq has-children (org-list-has-child-p (point) struct)))
6207 (org-back-to-heading)
6208 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6209 (setq eos (save-excursion
6210 (org-end-of-subtree t)
6211 (unless (eobp)
6212 (skip-chars-forward " \t\n"))
6213 (if (eobp) (point) (1- (point)))))
6214 (setq has-children
6215 (or (save-excursion
6216 (let ((level (funcall outline-level)))
6217 (outline-next-heading)
6218 (and (org-at-heading-p t)
6219 (> (funcall outline-level) level))))
6220 (save-excursion
6221 (org-list-search-forward (org-item-beginning-re) eos t)))))
6222 ;; Determine end invisible part of buffer (EOL)
6223 (beginning-of-line 2)
6224 ;; XEmacs doesn't have `next-single-char-property-change'
6225 (if (featurep 'xemacs)
6226 (while (and (not (eobp)) ;; this is like `next-line'
6227 (get-char-property (1- (point)) 'invisible))
6228 (beginning-of-line 2))
6229 (while (and (not (eobp)) ;; this is like `next-line'
6230 (get-char-property (1- (point)) 'invisible))
6231 (goto-char (next-single-char-property-change (point) 'invisible))
6232 (and (eolp) (beginning-of-line 2))))
6233 (setq eol (point)))
6234 ;; Find out what to do next and set `this-command'
6235 (cond
6236 ((= eos eoh)
6237 ;; Nothing is hidden behind this heading
6238 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6239 (message "EMPTY ENTRY")
6240 (setq org-cycle-subtree-status nil)
6241 (save-excursion
6242 (goto-char eos)
6243 (outline-next-heading)
6244 (if (outline-invisible-p) (org-flag-heading nil))))
6245 ((and (or (>= eol eos)
6246 (not (string-match "\\S-" (buffer-substring eol eos))))
6247 (or has-children
6248 (not (setq children-skipped
6249 org-cycle-skip-children-state-if-no-children))))
6250 ;; Entire subtree is hidden in one line: children view
6251 (run-hook-with-args 'org-pre-cycle-hook 'children)
6252 (if (org-at-item-p)
6253 (org-list-set-item-visibility (point-at-bol) struct 'children)
6254 (org-show-entry)
6255 (show-children)
6256 ;; Fold every list in subtree to top-level items.
6257 (when (eq org-cycle-include-plain-lists 'integrate)
6258 (save-excursion
6259 (org-back-to-heading)
6260 (while (org-list-search-forward (org-item-beginning-re) eos t)
6261 (beginning-of-line 1)
6262 (let* ((struct (org-list-struct))
6263 (prevs (org-list-prevs-alist struct))
6264 (end (org-list-get-bottom-point struct)))
6265 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6266 (org-list-get-all-items (point) struct prevs))
6267 (goto-char end))))))
6268 (message "CHILDREN")
6269 (save-excursion
6270 (goto-char eos)
6271 (outline-next-heading)
6272 (if (outline-invisible-p) (org-flag-heading nil)))
6273 (setq org-cycle-subtree-status 'children)
6274 (run-hook-with-args 'org-cycle-hook 'children))
6275 ((or children-skipped
6276 (and (eq last-command this-command)
6277 (eq org-cycle-subtree-status 'children)))
6278 ;; We just showed the children, or no children are there,
6279 ;; now show everything.
6280 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6281 (outline-flag-region eoh eos nil)
6282 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6283 (setq org-cycle-subtree-status 'subtree)
6284 (run-hook-with-args 'org-cycle-hook 'subtree))
6286 ;; Default action: hide the subtree.
6287 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6288 (outline-flag-region eoh eos t)
6289 (message "FOLDED")
6290 (setq org-cycle-subtree-status 'folded)
6291 (run-hook-with-args 'org-cycle-hook 'folded)))))
6293 ;;;###autoload
6294 (defun org-global-cycle (&optional arg)
6295 "Cycle the global visibility. For details see `org-cycle'.
6296 With \\[universal-argument] prefix arg, switch to startup visibility.
6297 With a numeric prefix, show all headlines up to that level."
6298 (interactive "P")
6299 (let ((org-cycle-include-plain-lists
6300 (if (eq major-mode 'org-mode) org-cycle-include-plain-lists nil)))
6301 (cond
6302 ((integerp arg)
6303 (show-all)
6304 (hide-sublevels arg)
6305 (setq org-cycle-global-status 'contents))
6306 ((equal arg '(4))
6307 (org-set-startup-visibility)
6308 (message "Startup visibility, plus VISIBILITY properties."))
6310 (org-cycle '(4))))))
6312 (defun org-set-startup-visibility ()
6313 "Set the visibility required by startup options and properties."
6314 (cond
6315 ((eq org-startup-folded t)
6316 (org-cycle '(4)))
6317 ((eq org-startup-folded 'content)
6318 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6319 (org-cycle '(4)) (org-cycle '(4)))))
6320 (unless (eq org-startup-folded 'showeverything)
6321 (if org-hide-block-startup (org-hide-block-all))
6322 (org-set-visibility-according-to-property 'no-cleanup)
6323 (org-cycle-hide-archived-subtrees 'all)
6324 (org-cycle-hide-drawers 'all)
6325 (org-cycle-show-empty-lines t)))
6327 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6328 "Switch subtree visibilities according to :VISIBILITY: property."
6329 (interactive)
6330 (let (org-show-entry-below state)
6331 (save-excursion
6332 (goto-char (point-min))
6333 (while (re-search-forward
6334 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6335 nil t)
6336 (setq state (match-string 1))
6337 (save-excursion
6338 (org-back-to-heading t)
6339 (hide-subtree)
6340 (org-reveal)
6341 (cond
6342 ((equal state '("fold" "folded"))
6343 (hide-subtree))
6344 ((equal state "children")
6345 (org-show-hidden-entry)
6346 (show-children))
6347 ((equal state "content")
6348 (save-excursion
6349 (save-restriction
6350 (org-narrow-to-subtree)
6351 (org-content))))
6352 ((member state '("all" "showall"))
6353 (show-subtree)))))
6354 (unless no-cleanup
6355 (org-cycle-hide-archived-subtrees 'all)
6356 (org-cycle-hide-drawers 'all)
6357 (org-cycle-show-empty-lines 'all)))))
6359 ;; This function uses outline-regexp instead of the more fundamental
6360 ;; org-outline-regexp so that org-cycle-global works outside of Org
6361 ;; buffers, where outline-regexp is needed.
6362 (defun org-overview ()
6363 "Switch to overview mode, showing only top-level headlines.
6364 Really, this shows all headlines with level equal or greater than the level
6365 of the first headline in the buffer. This is important, because if the
6366 first headline is not level one, then (hide-sublevels 1) gives confusing
6367 results."
6368 (interactive)
6369 (let ((level (save-excursion
6370 (goto-char (point-min))
6371 (if (re-search-forward (concat "^" outline-regexp) nil t)
6372 (progn
6373 (goto-char (match-beginning 0))
6374 (funcall outline-level))))))
6375 (and level (hide-sublevels level))))
6377 (defun org-content (&optional arg)
6378 "Show all headlines in the buffer, like a table of contents.
6379 With numerical argument N, show content up to level N."
6380 (interactive "P")
6381 (save-excursion
6382 ;; Visit all headings and show their offspring
6383 (and (integerp arg) (org-overview))
6384 (goto-char (point-max))
6385 (catch 'exit
6386 (while (and (progn (condition-case nil
6387 (outline-previous-visible-heading 1)
6388 (error (goto-char (point-min))))
6390 (looking-at org-outline-regexp))
6391 (if (integerp arg)
6392 (show-children (1- arg))
6393 (show-branches))
6394 (if (bobp) (throw 'exit nil))))))
6397 (defun org-optimize-window-after-visibility-change (state)
6398 "Adjust the window after a change in outline visibility.
6399 This function is the default value of the hook `org-cycle-hook'."
6400 (when (get-buffer-window (current-buffer))
6401 (cond
6402 ((eq state 'content) nil)
6403 ((eq state 'all) nil)
6404 ((eq state 'folded) nil)
6405 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6406 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6408 (defun org-remove-empty-overlays-at (pos)
6409 "Remove outline overlays that do not contain non-white stuff."
6410 (mapc
6411 (lambda (o)
6412 (and (eq 'outline (overlay-get o 'invisible))
6413 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6414 (overlay-end o))))
6415 (delete-overlay o)))
6416 (overlays-at pos)))
6418 (defun org-clean-visibility-after-subtree-move ()
6419 "Fix visibility issues after moving a subtree."
6420 ;; First, find a reasonable region to look at:
6421 ;; Start two siblings above, end three below
6422 (let* ((beg (save-excursion
6423 (and (org-get-last-sibling)
6424 (org-get-last-sibling))
6425 (point)))
6426 (end (save-excursion
6427 (and (org-get-next-sibling)
6428 (org-get-next-sibling)
6429 (org-get-next-sibling))
6430 (if (org-at-heading-p)
6431 (point-at-eol)
6432 (point))))
6433 (level (looking-at "\\*+"))
6434 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6435 (save-excursion
6436 (save-restriction
6437 (narrow-to-region beg end)
6438 (when re
6439 ;; Properly fold already folded siblings
6440 (goto-char (point-min))
6441 (while (re-search-forward re nil t)
6442 (if (and (not (outline-invisible-p))
6443 (save-excursion
6444 (goto-char (point-at-eol)) (outline-invisible-p)))
6445 (hide-entry))))
6446 (org-cycle-show-empty-lines 'overview)
6447 (org-cycle-hide-drawers 'overview)))))
6449 (defun org-cycle-show-empty-lines (state)
6450 "Show empty lines above all visible headlines.
6451 The region to be covered depends on STATE when called through
6452 `org-cycle-hook'. Lisp program can use t for STATE to get the
6453 entire buffer covered. Note that an empty line is only shown if there
6454 are at least `org-cycle-separator-lines' empty lines before the headline."
6455 (when (not (= org-cycle-separator-lines 0))
6456 (save-excursion
6457 (let* ((n (abs org-cycle-separator-lines))
6458 (re (cond
6459 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6460 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6461 (t (let ((ns (number-to-string (- n 2))))
6462 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6463 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6464 beg end b e)
6465 (cond
6466 ((memq state '(overview contents t))
6467 (setq beg (point-min) end (point-max)))
6468 ((memq state '(children folded))
6469 (setq beg (point) end (progn (org-end-of-subtree t t)
6470 (beginning-of-line 2)
6471 (point)))))
6472 (when beg
6473 (goto-char beg)
6474 (while (re-search-forward re end t)
6475 (unless (get-char-property (match-end 1) 'invisible)
6476 (setq e (match-end 1))
6477 (if (< org-cycle-separator-lines 0)
6478 (setq b (save-excursion
6479 (goto-char (match-beginning 0))
6480 (org-back-over-empty-lines)
6481 (if (save-excursion
6482 (goto-char (max (point-min) (1- (point))))
6483 (org-on-heading-p))
6484 (1- (point))
6485 (point))))
6486 (setq b (match-beginning 1)))
6487 (outline-flag-region b e nil)))))))
6488 ;; Never hide empty lines at the end of the file.
6489 (save-excursion
6490 (goto-char (point-max))
6491 (outline-previous-heading)
6492 (outline-end-of-heading)
6493 (if (and (looking-at "[ \t\n]+")
6494 (= (match-end 0) (point-max)))
6495 (outline-flag-region (point) (match-end 0) nil))))
6497 (defun org-show-empty-lines-in-parent ()
6498 "Move to the parent and re-show empty lines before visible headlines."
6499 (save-excursion
6500 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6501 (org-cycle-show-empty-lines context))))
6503 (defun org-files-list ()
6504 "Return `org-agenda-files' list, plus all open org-mode files.
6505 This is useful for operations that need to scan all of a user's
6506 open and agenda-wise Org files."
6507 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6508 (dolist (buf (buffer-list))
6509 (with-current-buffer buf
6510 (if (and (eq major-mode 'org-mode) (buffer-file-name))
6511 (let ((file (expand-file-name (buffer-file-name))))
6512 (unless (member file files)
6513 (push file files))))))
6514 files))
6516 (defsubst org-entry-beginning-position ()
6517 "Return the beginning position of the current entry."
6518 (save-excursion (outline-back-to-heading t) (point)))
6520 (defsubst org-entry-end-position ()
6521 "Return the end position of the current entry."
6522 (save-excursion (outline-next-heading) (point)))
6524 (defun org-cycle-hide-drawers (state)
6525 "Re-hide all drawers after a visibility state change."
6526 (when (and (eq major-mode 'org-mode)
6527 (not (memq state '(overview folded contents))))
6528 (save-excursion
6529 (let* ((globalp (memq state '(contents all)))
6530 (beg (if globalp (point-min) (point)))
6531 (end (if globalp (point-max)
6532 (if (eq state 'children)
6533 (save-excursion (outline-next-heading) (point))
6534 (org-end-of-subtree t)))))
6535 (goto-char beg)
6536 (while (re-search-forward org-drawer-regexp end t)
6537 (org-flag-drawer t))))))
6539 (defun org-flag-drawer (flag)
6540 (save-excursion
6541 (beginning-of-line 1)
6542 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6543 (let ((b (match-end 0)))
6544 (if (re-search-forward
6545 "^[ \t]*:END:"
6546 (save-excursion (outline-next-heading) (point)) t)
6547 (outline-flag-region b (point-at-eol) flag)
6548 (error ":END: line missing at position %s" b))))))
6550 (defun org-subtree-end-visible-p ()
6551 "Is the end of the current subtree visible?"
6552 (pos-visible-in-window-p
6553 (save-excursion (org-end-of-subtree t) (point))))
6555 (defun org-first-headline-recenter (&optional N)
6556 "Move cursor to the first headline and recenter the headline.
6557 Optional argument N means put the headline into the Nth line of the window."
6558 (goto-char (point-min))
6559 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6560 (beginning-of-line)
6561 (recenter (prefix-numeric-value N))))
6563 ;;; Saving and restoring visibility
6565 (defun org-outline-overlay-data (&optional use-markers)
6566 "Return a list of the locations of all outline overlays.
6567 These are overlays with the `invisible' property value `outline'.
6568 The return value is a list of cons cells, with start and stop
6569 positions for each overlay.
6570 If USE-MARKERS is set, return the positions as markers."
6571 (let (beg end)
6572 (save-excursion
6573 (save-restriction
6574 (widen)
6575 (delq nil
6576 (mapcar (lambda (o)
6577 (when (eq (overlay-get o 'invisible) 'outline)
6578 (setq beg (overlay-start o)
6579 end (overlay-end o))
6580 (and beg end (> end beg)
6581 (if use-markers
6582 (cons (move-marker (make-marker) beg)
6583 (move-marker (make-marker) end))
6584 (cons beg end)))))
6585 (overlays-in (point-min) (point-max))))))))
6587 (defun org-set-outline-overlay-data (data)
6588 "Create visibility overlays for all positions in DATA.
6589 DATA should have been made by `org-outline-overlay-data'."
6590 (let (o)
6591 (save-excursion
6592 (save-restriction
6593 (widen)
6594 (show-all)
6595 (mapc (lambda (c)
6596 (setq o (make-overlay (car c) (cdr c)))
6597 (overlay-put o 'invisible 'outline))
6598 data)))))
6600 ;;; Folding of blocks
6602 (defconst org-block-regexp
6603 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
6604 "Regular expression for hiding blocks.")
6606 (defvar org-hide-block-overlays nil
6607 "Overlays hiding blocks.")
6608 (make-variable-buffer-local 'org-hide-block-overlays)
6610 (defun org-block-map (function &optional start end)
6611 "Call FUNCTION at the head of all source blocks in the current buffer.
6612 Optional arguments START and END can be used to limit the range."
6613 (let ((start (or start (point-min)))
6614 (end (or end (point-max))))
6615 (save-excursion
6616 (goto-char start)
6617 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6618 (save-excursion
6619 (save-match-data
6620 (goto-char (match-beginning 0))
6621 (funcall function)))))))
6623 (defun org-hide-block-toggle-all ()
6624 "Toggle the visibility of all blocks in the current buffer."
6625 (org-block-map #'org-hide-block-toggle))
6627 (defun org-hide-block-all ()
6628 "Fold all blocks in the current buffer."
6629 (interactive)
6630 (org-show-block-all)
6631 (org-block-map #'org-hide-block-toggle-maybe))
6633 (defun org-show-block-all ()
6634 "Unfold all blocks in the current buffer."
6635 (interactive)
6636 (mapc 'delete-overlay org-hide-block-overlays)
6637 (setq org-hide-block-overlays nil))
6639 (defun org-hide-block-toggle-maybe ()
6640 "Toggle visibility of block at point."
6641 (interactive)
6642 (let ((case-fold-search t))
6643 (if (save-excursion
6644 (beginning-of-line 1)
6645 (looking-at org-block-regexp))
6646 (progn (org-hide-block-toggle)
6647 t) ;; to signal that we took action
6648 nil))) ;; to signal that we did not
6650 (defun org-hide-block-toggle (&optional force)
6651 "Toggle the visibility of the current block."
6652 (interactive)
6653 (save-excursion
6654 (beginning-of-line)
6655 (if (re-search-forward org-block-regexp nil t)
6656 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6657 (end (match-end 0)) ;; end of entire body
6659 (if (memq t (mapcar (lambda (overlay)
6660 (eq (overlay-get overlay 'invisible)
6661 'org-hide-block))
6662 (overlays-at start)))
6663 (if (or (not force) (eq force 'off))
6664 (mapc (lambda (ov)
6665 (when (member ov org-hide-block-overlays)
6666 (setq org-hide-block-overlays
6667 (delq ov org-hide-block-overlays)))
6668 (when (eq (overlay-get ov 'invisible)
6669 'org-hide-block)
6670 (delete-overlay ov)))
6671 (overlays-at start)))
6672 (setq ov (make-overlay start end))
6673 (overlay-put ov 'invisible 'org-hide-block)
6674 ;; make the block accessible to isearch
6675 (overlay-put
6676 ov 'isearch-open-invisible
6677 (lambda (ov)
6678 (when (member ov org-hide-block-overlays)
6679 (setq org-hide-block-overlays
6680 (delq ov org-hide-block-overlays)))
6681 (when (eq (overlay-get ov 'invisible)
6682 'org-hide-block)
6683 (delete-overlay ov))))
6684 (push ov org-hide-block-overlays)))
6685 (error "Not looking at a source block"))))
6687 ;; org-tab-after-check-for-cycling-hook
6688 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6689 ;; Remove overlays when changing major mode
6690 (add-hook 'org-mode-hook
6691 (lambda () (org-add-hook 'change-major-mode-hook
6692 'org-show-block-all 'append 'local)))
6694 ;;; Org-goto
6696 (defvar org-goto-window-configuration nil)
6697 (defvar org-goto-marker nil)
6698 (defvar org-goto-map
6699 (let ((map (make-sparse-keymap)))
6700 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6701 (while (setq cmd (pop cmds))
6702 (substitute-key-definition cmd cmd map global-map)))
6703 (suppress-keymap map)
6704 (org-defkey map "\C-m" 'org-goto-ret)
6705 (org-defkey map [(return)] 'org-goto-ret)
6706 (org-defkey map [(left)] 'org-goto-left)
6707 (org-defkey map [(right)] 'org-goto-right)
6708 (org-defkey map [(control ?g)] 'org-goto-quit)
6709 (org-defkey map "\C-i" 'org-cycle)
6710 (org-defkey map [(tab)] 'org-cycle)
6711 (org-defkey map [(down)] 'outline-next-visible-heading)
6712 (org-defkey map [(up)] 'outline-previous-visible-heading)
6713 (if org-goto-auto-isearch
6714 (if (fboundp 'define-key-after)
6715 (define-key-after map [t] 'org-goto-local-auto-isearch)
6716 nil)
6717 (org-defkey map "q" 'org-goto-quit)
6718 (org-defkey map "n" 'outline-next-visible-heading)
6719 (org-defkey map "p" 'outline-previous-visible-heading)
6720 (org-defkey map "f" 'outline-forward-same-level)
6721 (org-defkey map "b" 'outline-backward-same-level)
6722 (org-defkey map "u" 'outline-up-heading))
6723 (org-defkey map "/" 'org-occur)
6724 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6725 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6726 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6727 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6728 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6729 map))
6731 (defconst org-goto-help
6732 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6733 RET=jump to location [Q]uit and return to previous location
6734 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6736 (defvar org-goto-start-pos) ; dynamically scoped parameter
6738 ;; FIXME: Docstring does not mention both interfaces
6739 (defun org-goto (&optional alternative-interface)
6740 "Look up a different location in the current file, keeping current visibility.
6742 When you want look-up or go to a different location in a document, the
6743 fastest way is often to fold the entire buffer and then dive into the tree.
6744 This method has the disadvantage, that the previous location will be folded,
6745 which may not be what you want.
6747 This command works around this by showing a copy of the current buffer
6748 in an indirect buffer, in overview mode. You can dive into the tree in
6749 that copy, use org-occur and incremental search to find a location.
6750 When pressing RET or `Q', the command returns to the original buffer in
6751 which the visibility is still unchanged. After RET is will also jump to
6752 the location selected in the indirect buffer and expose the headline
6753 hierarchy above."
6754 (interactive "P")
6755 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6756 (org-refile-use-outline-path t)
6757 (org-refile-target-verify-function nil)
6758 (interface
6759 (if (not alternative-interface)
6760 org-goto-interface
6761 (if (eq org-goto-interface 'outline)
6762 'outline-path-completion
6763 'outline)))
6764 (org-goto-start-pos (point))
6765 (selected-point
6766 (if (eq interface 'outline)
6767 (car (org-get-location (current-buffer) org-goto-help))
6768 (let ((pa (org-refile-get-location "Goto")))
6769 (org-refile-check-position pa)
6770 (nth 3 pa)))))
6771 (if selected-point
6772 (progn
6773 (org-mark-ring-push org-goto-start-pos)
6774 (goto-char selected-point)
6775 (if (or (outline-invisible-p) (org-invisible-p2))
6776 (org-show-context 'org-goto)))
6777 (message "Quit"))))
6779 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6780 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6781 (defvar org-goto-local-auto-isearch-map) ; defined below
6783 (defun org-get-location (buf help)
6784 "Let the user select a location in the Org-mode buffer BUF.
6785 This function uses a recursive edit. It returns the selected position
6786 or nil."
6787 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6788 (isearch-hide-immediately nil)
6789 (isearch-search-fun-function
6790 (lambda () 'org-goto-local-search-headings))
6791 (org-goto-selected-point org-goto-exit-command)
6792 (pop-up-frames nil)
6793 (special-display-buffer-names nil)
6794 (special-display-regexps nil)
6795 (special-display-function nil))
6796 (save-excursion
6797 (save-window-excursion
6798 (delete-other-windows)
6799 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6800 (org-pop-to-buffer-same-window
6801 (condition-case nil
6802 (make-indirect-buffer (current-buffer) "*org-goto*")
6803 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6804 (with-output-to-temp-buffer "*Help*"
6805 (princ help))
6806 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6807 (setq buffer-read-only nil)
6808 (let ((org-startup-truncated t)
6809 (org-startup-folded nil)
6810 (org-startup-align-all-tables nil))
6811 (org-mode)
6812 (org-overview))
6813 (setq buffer-read-only t)
6814 (if (and (boundp 'org-goto-start-pos)
6815 (integer-or-marker-p org-goto-start-pos))
6816 (let ((org-show-hierarchy-above t)
6817 (org-show-siblings t)
6818 (org-show-following-heading t))
6819 (goto-char org-goto-start-pos)
6820 (and (outline-invisible-p) (org-show-context)))
6821 (goto-char (point-min)))
6822 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6823 (message "Select location and press RET")
6824 (use-local-map org-goto-map)
6825 (recursive-edit)
6827 (kill-buffer "*org-goto*")
6828 (cons org-goto-selected-point org-goto-exit-command)))
6830 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6831 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6832 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6833 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6835 (defun org-goto-local-search-headings (string bound noerror)
6836 "Search and make sure that any matches are in headlines."
6837 (catch 'return
6838 (while (if isearch-forward
6839 (search-forward string bound noerror)
6840 (search-backward string bound noerror))
6841 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6842 (and (member :headline context)
6843 (not (member :tags context))))
6844 (throw 'return (point))))))
6846 (defun org-goto-local-auto-isearch ()
6847 "Start isearch."
6848 (interactive)
6849 (goto-char (point-min))
6850 (let ((keys (this-command-keys)))
6851 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6852 (isearch-mode t)
6853 (isearch-process-search-char (string-to-char keys)))))
6855 (defun org-goto-ret (&optional arg)
6856 "Finish `org-goto' by going to the new location."
6857 (interactive "P")
6858 (setq org-goto-selected-point (point)
6859 org-goto-exit-command 'return)
6860 (throw 'exit nil))
6862 (defun org-goto-left ()
6863 "Finish `org-goto' by going to the new location."
6864 (interactive)
6865 (if (org-on-heading-p)
6866 (progn
6867 (beginning-of-line 1)
6868 (setq org-goto-selected-point (point)
6869 org-goto-exit-command 'left)
6870 (throw 'exit nil))
6871 (error "Not on a heading")))
6873 (defun org-goto-right ()
6874 "Finish `org-goto' by going to the new location."
6875 (interactive)
6876 (if (org-on-heading-p)
6877 (progn
6878 (setq org-goto-selected-point (point)
6879 org-goto-exit-command 'right)
6880 (throw 'exit nil))
6881 (error "Not on a heading")))
6883 (defun org-goto-quit ()
6884 "Finish `org-goto' without cursor motion."
6885 (interactive)
6886 (setq org-goto-selected-point nil)
6887 (setq org-goto-exit-command 'quit)
6888 (throw 'exit nil))
6890 ;;; Indirect buffer display of subtrees
6892 (defvar org-indirect-dedicated-frame nil
6893 "This is the frame being used for indirect tree display.")
6894 (defvar org-last-indirect-buffer nil)
6896 (defun org-tree-to-indirect-buffer (&optional arg)
6897 "Create indirect buffer and narrow it to current subtree.
6898 With numerical prefix ARG, go up to this level and then take that tree.
6899 If ARG is negative, go up that many levels.
6900 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6901 indirect buffer previously made with this command, to avoid proliferation of
6902 indirect buffers. However, when you call the command with a \
6903 \\[universal-argument] prefix, or
6904 when `org-indirect-buffer-display' is `new-frame', the last buffer
6905 is kept so that you can work with several indirect buffers at the same time.
6906 If `org-indirect-buffer-display' is `dedicated-frame', the \
6907 \\[universal-argument] prefix also
6908 requests that a new frame be made for the new buffer, so that the dedicated
6909 frame is not changed."
6910 (interactive "P")
6911 (let ((cbuf (current-buffer))
6912 (cwin (selected-window))
6913 (pos (point))
6914 beg end level heading ibuf)
6915 (save-excursion
6916 (org-back-to-heading t)
6917 (when (numberp arg)
6918 (setq level (org-outline-level))
6919 (if (< arg 0) (setq arg (+ level arg)))
6920 (while (> (setq level (org-outline-level)) arg)
6921 (outline-up-heading 1 t)))
6922 (setq beg (point)
6923 heading (org-get-heading))
6924 (org-end-of-subtree t t)
6925 (if (org-on-heading-p) (backward-char 1))
6926 (setq end (point)))
6927 (if (and (buffer-live-p org-last-indirect-buffer)
6928 (not (eq org-indirect-buffer-display 'new-frame))
6929 (not arg))
6930 (kill-buffer org-last-indirect-buffer))
6931 (setq ibuf (org-get-indirect-buffer cbuf)
6932 org-last-indirect-buffer ibuf)
6933 (cond
6934 ((or (eq org-indirect-buffer-display 'new-frame)
6935 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6936 (select-frame (make-frame))
6937 (delete-other-windows)
6938 (org-pop-to-buffer-same-window ibuf)
6939 (org-set-frame-title heading))
6940 ((eq org-indirect-buffer-display 'dedicated-frame)
6941 (raise-frame
6942 (select-frame (or (and org-indirect-dedicated-frame
6943 (frame-live-p org-indirect-dedicated-frame)
6944 org-indirect-dedicated-frame)
6945 (setq org-indirect-dedicated-frame (make-frame)))))
6946 (delete-other-windows)
6947 (org-pop-to-buffer-same-window ibuf)
6948 (org-set-frame-title (concat "Indirect: " heading)))
6949 ((eq org-indirect-buffer-display 'current-window)
6950 (org-pop-to-buffer-same-window ibuf))
6951 ((eq org-indirect-buffer-display 'other-window)
6952 (pop-to-buffer ibuf))
6953 (t (error "Invalid value")))
6954 (if (featurep 'xemacs)
6955 (save-excursion (org-mode) (turn-on-font-lock)))
6956 (narrow-to-region beg end)
6957 (show-all)
6958 (goto-char pos)
6959 (run-hook-with-args 'org-cycle-hook 'all)
6960 (and (window-live-p cwin) (select-window cwin))))
6962 (defun org-get-indirect-buffer (&optional buffer)
6963 (setq buffer (or buffer (current-buffer)))
6964 (let ((n 1) (base (buffer-name buffer)) bname)
6965 (while (buffer-live-p
6966 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6967 (setq n (1+ n)))
6968 (condition-case nil
6969 (make-indirect-buffer buffer bname 'clone)
6970 (error (make-indirect-buffer buffer bname)))))
6972 (defun org-set-frame-title (title)
6973 "Set the title of the current frame to the string TITLE."
6974 ;; FIXME: how to name a single frame in XEmacs???
6975 (unless (featurep 'xemacs)
6976 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6978 ;;;; Structure editing
6980 ;;; Inserting headlines
6982 (defun org-previous-line-empty-p ()
6983 (save-excursion
6984 (and (not (bobp))
6985 (or (beginning-of-line 0) t)
6986 (save-match-data
6987 (looking-at "[ \t]*$")))))
6989 (defun org-insert-heading (&optional force-heading invisible-ok)
6990 "Insert a new heading or item with same depth at point.
6991 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6992 If point is at the beginning of a headline, insert a sibling before the
6993 current headline. If point is not at the beginning, split the line,
6994 create the new headline with the text in the current line after point
6995 \(but see also the variable `org-M-RET-may-split-line').
6997 When INVISIBLE-OK is set, stop at invisible headlines when going back.
6998 This is important for non-interactive uses of the command."
6999 (interactive "P")
7000 (if (or (= (buffer-size) 0)
7001 (and (not (save-excursion
7002 (and (ignore-errors (org-back-to-heading invisible-ok))
7003 (org-on-heading-p))))
7004 (or force-heading (not (org-in-item-p)))))
7005 (progn
7006 (insert "\n* ")
7007 (run-hooks 'org-insert-heading-hook))
7008 (when (or force-heading (not (org-insert-item)))
7009 (let* ((empty-line-p nil)
7010 (level nil)
7011 (on-heading (org-on-heading-p))
7012 (head (save-excursion
7013 (condition-case nil
7014 (progn
7015 (org-back-to-heading invisible-ok)
7016 (when (and (not on-heading)
7017 (featurep 'org-inlinetask)
7018 (integerp org-inlinetask-min-level)
7019 (>= (length (match-string 0))
7020 org-inlinetask-min-level))
7021 ;; Find a heading level before the inline task
7022 (while (and (setq level (org-up-heading-safe))
7023 (>= level org-inlinetask-min-level)))
7024 (if (org-on-heading-p)
7025 (org-back-to-heading invisible-ok)
7026 (error "This should not happen")))
7027 (setq empty-line-p (org-previous-line-empty-p))
7028 (match-string 0))
7029 (error "*"))))
7030 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7031 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7032 pos hide-previous previous-pos)
7033 (cond
7034 ((and (org-on-heading-p) (bolp)
7035 (or (bobp)
7036 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7037 ;; insert before the current line
7038 (open-line (if blank 2 1)))
7039 ((and (bolp)
7040 (not org-insert-heading-respect-content)
7041 (or (bobp)
7042 (save-excursion
7043 (backward-char 1) (not (outline-invisible-p)))))
7044 ;; insert right here
7045 nil)
7047 ;; somewhere in the line
7048 (save-excursion
7049 (setq previous-pos (point-at-bol))
7050 (end-of-line)
7051 (setq hide-previous (outline-invisible-p)))
7052 (and org-insert-heading-respect-content (org-show-subtree))
7053 (let ((split
7054 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7055 (save-excursion
7056 (let ((p (point)))
7057 (goto-char (point-at-bol))
7058 (and (looking-at org-complex-heading-regexp)
7059 (match-beginning 4)
7060 (> p (match-beginning 4)))))))
7061 tags pos)
7062 (cond
7063 (org-insert-heading-respect-content
7064 (org-end-of-subtree nil t)
7065 (when (featurep 'org-inlinetask)
7066 (while (and (not (eobp))
7067 (looking-at "\\(\\*+\\)[ \t]+")
7068 (>= (length (match-string 1))
7069 org-inlinetask-min-level))
7070 (org-end-of-subtree nil t)))
7071 (or (bolp) (newline))
7072 (or (org-previous-line-empty-p)
7073 (and blank (newline)))
7074 (open-line 1))
7075 ((org-on-heading-p)
7076 (when hide-previous
7077 (show-children)
7078 (org-show-entry))
7079 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7080 (setq tags (and (match-end 2) (match-string 2)))
7081 (and (match-end 1)
7082 (delete-region (match-beginning 1) (match-end 1)))
7083 (setq pos (point-at-bol))
7084 (or split (end-of-line 1))
7085 (delete-horizontal-space)
7086 (if (string-match "\\`\\*+\\'"
7087 (buffer-substring (point-at-bol) (point)))
7088 (insert " "))
7089 (newline (if blank 2 1))
7090 (when tags
7091 (save-excursion
7092 (goto-char pos)
7093 (end-of-line 1)
7094 (insert " " tags)
7095 (org-set-tags nil 'align))))
7097 (or split (end-of-line 1))
7098 (newline (if blank 2 1)))))))
7099 (insert head) (just-one-space)
7100 (setq pos (point))
7101 (end-of-line 1)
7102 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7103 (when (and org-insert-heading-respect-content hide-previous)
7104 (save-excursion
7105 (goto-char previous-pos)
7106 (hide-subtree)))
7107 (run-hooks 'org-insert-heading-hook)))))
7109 (defun org-get-heading (&optional no-tags no-todo)
7110 "Return the heading of the current entry, without the stars.
7111 When NO-TAGS is non-nil, don't include tags.
7112 When NO-TODO is non-nil, don't include TODO keywords."
7113 (save-excursion
7114 (org-back-to-heading t)
7115 (cond
7116 ((and no-tags no-todo)
7117 (looking-at org-complex-heading-regexp)
7118 (match-string 4))
7119 (no-tags
7120 (looking-at (concat org-outline-regexp
7121 "\\(.*?\\)"
7122 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7123 (match-string 1))
7124 (no-todo
7125 (looking-at org-todo-line-regexp)
7126 (match-string 3))
7127 (t (looking-at org-heading-regexp)
7128 (match-string 2)))))
7130 (defun org-heading-components ()
7131 "Return the components of the current heading.
7132 This is a list with the following elements:
7133 - the level as an integer
7134 - the reduced level, different if `org-odd-levels-only' is set.
7135 - the TODO keyword, or nil
7136 - the priority character, like ?A, or nil if no priority is given
7137 - the headline text itself, or the tags string if no headline text
7138 - the tags string, or nil."
7139 (save-excursion
7140 (org-back-to-heading t)
7141 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7142 (list (length (match-string 1))
7143 (org-reduced-level (length (match-string 1)))
7144 (org-match-string-no-properties 2)
7145 (and (match-end 3) (aref (match-string 3) 2))
7146 (org-match-string-no-properties 4)
7147 (org-match-string-no-properties 5)))))
7149 (defun org-get-entry ()
7150 "Get the entry text, after heading, entire subtree."
7151 (save-excursion
7152 (org-back-to-heading t)
7153 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7155 (defun org-insert-heading-after-current ()
7156 "Insert a new heading with same level as current, after current subtree."
7157 (interactive)
7158 (org-back-to-heading)
7159 (org-insert-heading)
7160 (org-move-subtree-down)
7161 (end-of-line 1))
7163 (defun org-insert-heading-respect-content ()
7164 (interactive)
7165 (let ((org-insert-heading-respect-content t))
7166 (org-insert-heading t)))
7168 (defun org-insert-todo-heading-respect-content (&optional force-state)
7169 (interactive "P")
7170 (let ((org-insert-heading-respect-content t))
7171 (org-insert-todo-heading force-state t)))
7173 (defun org-insert-todo-heading (arg &optional force-heading)
7174 "Insert a new heading with the same level and TODO state as current heading.
7175 If the heading has no TODO state, or if the state is DONE, use the first
7176 state (TODO by default). Also with prefix arg, force first state."
7177 (interactive "P")
7178 (when (or force-heading (not (org-insert-item 'checkbox)))
7179 (org-insert-heading force-heading)
7180 (save-excursion
7181 (org-back-to-heading)
7182 (outline-previous-heading)
7183 (looking-at org-todo-line-regexp))
7184 (let*
7185 ((new-mark-x
7186 (if (or arg
7187 (not (match-beginning 2))
7188 (member (match-string 2) org-done-keywords))
7189 (car org-todo-keywords-1)
7190 (match-string 2)))
7191 (new-mark
7193 (run-hook-with-args-until-success
7194 'org-todo-get-default-hook new-mark-x nil)
7195 new-mark-x)))
7196 (beginning-of-line 1)
7197 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7198 (if org-treat-insert-todo-heading-as-state-change
7199 (org-todo new-mark)
7200 (insert new-mark " "))))
7201 (when org-provide-todo-statistics
7202 (org-update-parent-todo-statistics))))
7204 (defun org-insert-subheading (arg)
7205 "Insert a new subheading and demote it.
7206 Works for outline headings and for plain lists alike."
7207 (interactive "P")
7208 (org-insert-heading arg)
7209 (cond
7210 ((org-on-heading-p) (org-do-demote))
7211 ((org-at-item-p) (org-indent-item))))
7213 (defun org-insert-todo-subheading (arg)
7214 "Insert a new subheading with TODO keyword or checkbox and demote it.
7215 Works for outline headings and for plain lists alike."
7216 (interactive "P")
7217 (org-insert-todo-heading arg)
7218 (cond
7219 ((org-on-heading-p) (org-do-demote))
7220 ((org-at-item-p) (org-indent-item))))
7222 ;;; Promotion and Demotion
7224 (defvar org-after-demote-entry-hook nil
7225 "Hook run after an entry has been demoted.
7226 The cursor will be at the beginning of the entry.
7227 When a subtree is being demoted, the hook will be called for each node.")
7229 (defvar org-after-promote-entry-hook nil
7230 "Hook run after an entry has been promoted.
7231 The cursor will be at the beginning of the entry.
7232 When a subtree is being promoted, the hook will be called for each node.")
7234 (defun org-promote-subtree ()
7235 "Promote the entire subtree.
7236 See also `org-promote'."
7237 (interactive)
7238 (save-excursion
7239 (org-with-limited-levels (org-map-tree 'org-promote)))
7240 (org-fix-position-after-promote))
7242 (defun org-demote-subtree ()
7243 "Demote the entire subtree. See `org-demote'.
7244 See also `org-promote'."
7245 (interactive)
7246 (save-excursion
7247 (org-with-limited-levels (org-map-tree 'org-demote)))
7248 (org-fix-position-after-promote))
7251 (defun org-do-promote ()
7252 "Promote the current heading higher up the tree.
7253 If the region is active in `transient-mark-mode', promote all headings
7254 in the region."
7255 (interactive)
7256 (save-excursion
7257 (if (org-region-active-p)
7258 (org-map-region 'org-promote (region-beginning) (region-end))
7259 (org-promote)))
7260 (org-fix-position-after-promote))
7262 (defun org-do-demote ()
7263 "Demote the current heading lower down the tree.
7264 If the region is active in `transient-mark-mode', demote all headings
7265 in the region."
7266 (interactive)
7267 (save-excursion
7268 (if (org-region-active-p)
7269 (org-map-region 'org-demote (region-beginning) (region-end))
7270 (org-demote)))
7271 (org-fix-position-after-promote))
7273 (defun org-fix-position-after-promote ()
7274 "Make sure that after pro/demotion cursor position is right."
7275 (let ((pos (point)))
7276 (when (save-excursion
7277 (beginning-of-line 1)
7278 (looking-at org-todo-line-regexp)
7279 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7280 (cond ((eobp) (insert " "))
7281 ((eolp) (insert " "))
7282 ((equal (char-after) ?\ ) (forward-char 1))))))
7284 (defun org-current-level ()
7285 "Return the level of the current entry, or nil if before the first headline.
7286 The level is the number of stars at the beginning of the headline."
7287 (save-excursion
7288 (org-with-limited-levels
7289 (if (ignore-errors (org-back-to-heading t))
7290 (funcall outline-level)))))
7292 (defun org-get-previous-line-level ()
7293 "Return the outline depth of the last headline before the current line.
7294 Returns 0 for the first headline in the buffer, and nil if before the
7295 first headline."
7296 (let ((current-level (org-current-level))
7297 (prev-level (when (> (line-number-at-pos) 1)
7298 (save-excursion
7299 (beginning-of-line 0)
7300 (org-current-level)))))
7301 (cond ((null current-level) nil) ; Before first headline
7302 ((null prev-level) 0) ; At first headline
7303 (prev-level))))
7305 (defun org-reduced-level (l)
7306 "Compute the effective level of a heading.
7307 This takes into account the setting of `org-odd-levels-only'."
7308 (cond
7309 ((zerop l) 0)
7310 (org-odd-levels-only (1+ (floor (/ l 2))))
7311 (t l)))
7313 (defun org-level-increment ()
7314 "Return the number of stars that will be added or removed at a
7315 time to headlines when structure editing, based on the value of
7316 `org-odd-levels-only'."
7317 (if org-odd-levels-only 2 1))
7319 (defun org-get-valid-level (level &optional change)
7320 "Rectify a level change under the influence of `org-odd-levels-only'
7321 LEVEL is a current level, CHANGE is by how much the level should be
7322 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7323 even level numbers will become the next higher odd number."
7324 (if org-odd-levels-only
7325 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7326 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7327 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7328 (max 1 (+ level (or change 0)))))
7330 (if (boundp 'define-obsolete-function-alias)
7331 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7332 (define-obsolete-function-alias 'org-get-legal-level
7333 'org-get-valid-level)
7334 (define-obsolete-function-alias 'org-get-legal-level
7335 'org-get-valid-level "23.1")))
7337 (defun org-promote ()
7338 "Promote the current heading higher up the tree.
7339 If the region is active in `transient-mark-mode', promote all headings
7340 in the region."
7341 (org-back-to-heading t)
7342 (let* ((level (save-match-data (funcall outline-level)))
7343 (after-change-functions (remove 'flyspell-after-change-function
7344 after-change-functions))
7345 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7346 (diff (abs (- level (length up-head) -1))))
7347 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
7348 (replace-match up-head nil t)
7349 ;; Fixup tag positioning
7350 (and org-auto-align-tags (org-set-tags nil t))
7351 (if org-adapt-indentation (org-fixup-indentation (- diff)))
7352 (run-hooks 'org-after-promote-entry-hook)))
7354 (defun org-demote ()
7355 "Demote the current heading lower down the tree.
7356 If the region is active in `transient-mark-mode', demote all headings
7357 in the region."
7358 (org-back-to-heading t)
7359 (let* ((level (save-match-data (funcall outline-level)))
7360 (after-change-functions (remove 'flyspell-after-change-function
7361 after-change-functions))
7362 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7363 (diff (abs (- level (length down-head) -1))))
7364 (replace-match down-head nil t)
7365 ;; Fixup tag positioning
7366 (and org-auto-align-tags (org-set-tags nil t))
7367 (if org-adapt-indentation (org-fixup-indentation diff))
7368 (run-hooks 'org-after-demote-entry-hook)))
7370 (defun org-cycle-level ()
7371 "Cycle the level of an empty headline through possible states.
7372 This goes first to child, then to parent, level, then up the hierarchy.
7373 After top level, it switches back to sibling level."
7374 (interactive)
7375 (let ((org-adapt-indentation nil))
7376 (when (org-point-at-end-of-empty-headline)
7377 (setq this-command 'org-cycle-level) ; Only needed for caching
7378 (let ((cur-level (org-current-level))
7379 (prev-level (org-get-previous-line-level)))
7380 (cond
7381 ;; If first headline in file, promote to top-level.
7382 ((= prev-level 0)
7383 (loop repeat (/ (- cur-level 1) (org-level-increment))
7384 do (org-do-promote)))
7385 ;; If same level as prev, demote one.
7386 ((= prev-level cur-level)
7387 (org-do-demote))
7388 ;; If parent is top-level, promote to top level if not already.
7389 ((= prev-level 1)
7390 (loop repeat (/ (- cur-level 1) (org-level-increment))
7391 do (org-do-promote)))
7392 ;; If top-level, return to prev-level.
7393 ((= cur-level 1)
7394 (loop repeat (/ (- prev-level 1) (org-level-increment))
7395 do (org-do-demote)))
7396 ;; If less than prev-level, promote one.
7397 ((< cur-level prev-level)
7398 (org-do-promote))
7399 ;; If deeper than prev-level, promote until higher than
7400 ;; prev-level.
7401 ((> cur-level prev-level)
7402 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7403 do (org-do-promote))))
7404 t))))
7406 (defun org-map-tree (fun)
7407 "Call FUN for every heading underneath the current one."
7408 (org-back-to-heading)
7409 (let ((level (funcall outline-level)))
7410 (save-excursion
7411 (funcall fun)
7412 (while (and (progn
7413 (outline-next-heading)
7414 (> (funcall outline-level) level))
7415 (not (eobp)))
7416 (funcall fun)))))
7418 (defun org-map-region (fun beg end)
7419 "Call FUN for every heading between BEG and END."
7420 (let ((org-ignore-region t))
7421 (save-excursion
7422 (setq end (copy-marker end))
7423 (goto-char beg)
7424 (if (and (re-search-forward org-outline-regexp-bol nil t)
7425 (< (point) end))
7426 (funcall fun))
7427 (while (and (progn
7428 (outline-next-heading)
7429 (< (point) end))
7430 (not (eobp)))
7431 (funcall fun)))))
7433 (defvar org-property-end-re) ; silence byte-compiler
7434 (defun org-fixup-indentation (diff)
7435 "Change the indentation in the current entry by DIFF.
7436 However, if any line in the current entry has no indentation, or if it
7437 would end up with no indentation after the change, nothing at all is done."
7438 (save-excursion
7439 (let ((end (save-excursion (outline-next-heading)
7440 (point-marker)))
7441 (prohibit (if (> diff 0)
7442 "^\\S-"
7443 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7444 col)
7445 (unless (save-excursion (end-of-line 1)
7446 (re-search-forward prohibit end t))
7447 (while (and (< (point) end)
7448 (re-search-forward "^[ \t]+" end t))
7449 (goto-char (match-end 0))
7450 (setq col (current-column))
7451 (if (< diff 0) (replace-match ""))
7452 (org-indent-to-column (+ diff col))))
7453 (move-marker end nil))))
7455 (defun org-convert-to-odd-levels ()
7456 "Convert an org-mode file with all levels allowed to one with odd levels.
7457 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7458 level 5 etc."
7459 (interactive)
7460 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7461 (let ((outline-level 'org-outline-level)
7462 (org-odd-levels-only nil) n)
7463 (save-excursion
7464 (goto-char (point-min))
7465 (while (re-search-forward "^\\*\\*+ " nil t)
7466 (setq n (- (length (match-string 0)) 2))
7467 (while (>= (setq n (1- n)) 0)
7468 (org-demote))
7469 (end-of-line 1))))))
7471 (defun org-convert-to-oddeven-levels ()
7472 "Convert an org-mode file with only odd levels to one with odd/even levels.
7473 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7474 file contains a section with an even level, conversion would
7475 destroy the structure of the file. An error is signaled in this
7476 case."
7477 (interactive)
7478 (goto-char (point-min))
7479 ;; First check if there are no even levels
7480 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7481 (org-show-context t)
7482 (error "Not all levels are odd in this file. Conversion not possible"))
7483 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7484 (let ((outline-regexp org-outline-regexp)
7485 (outline-level 'org-outline-level)
7486 (org-odd-levels-only nil) n)
7487 (save-excursion
7488 (goto-char (point-min))
7489 (while (re-search-forward "^\\*\\*+ " nil t)
7490 (setq n (/ (1- (length (match-string 0))) 2))
7491 (while (>= (setq n (1- n)) 0)
7492 (org-promote))
7493 (end-of-line 1))))))
7495 (defun org-tr-level (n)
7496 "Make N odd if required."
7497 (if org-odd-levels-only (1+ (/ n 2)) n))
7499 ;;; Vertical tree motion, cutting and pasting of subtrees
7501 (defun org-move-subtree-up (&optional arg)
7502 "Move the current subtree up past ARG headlines of the same level."
7503 (interactive "p")
7504 (org-move-subtree-down (- (prefix-numeric-value arg))))
7506 (defun org-move-subtree-down (&optional arg)
7507 "Move the current subtree down past ARG headlines of the same level."
7508 (interactive "p")
7509 (setq arg (prefix-numeric-value arg))
7510 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7511 'org-get-last-sibling))
7512 (ins-point (make-marker))
7513 (cnt (abs arg))
7514 (col (current-column))
7515 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7516 ;; Select the tree
7517 (org-back-to-heading)
7518 (setq beg0 (point))
7519 (save-excursion
7520 (setq ne-beg (org-back-over-empty-lines))
7521 (setq beg (point)))
7522 (save-match-data
7523 (save-excursion (outline-end-of-heading)
7524 (setq folded (outline-invisible-p)))
7525 (outline-end-of-subtree))
7526 (outline-next-heading)
7527 (setq ne-end (org-back-over-empty-lines))
7528 (setq end (point))
7529 (goto-char beg0)
7530 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7531 ;; include less whitespace
7532 (save-excursion
7533 (goto-char beg)
7534 (forward-line (- ne-beg ne-end))
7535 (setq beg (point))))
7536 ;; Find insertion point, with error handling
7537 (while (> cnt 0)
7538 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7539 (progn (goto-char beg0)
7540 (error "Cannot move past superior level or buffer limit")))
7541 (setq cnt (1- cnt)))
7542 (if (> arg 0)
7543 ;; Moving forward - still need to move over subtree
7544 (progn (org-end-of-subtree t t)
7545 (save-excursion
7546 (org-back-over-empty-lines)
7547 (or (bolp) (newline)))))
7548 (setq ne-ins (org-back-over-empty-lines))
7549 (move-marker ins-point (point))
7550 (setq txt (buffer-substring beg end))
7551 (org-save-markers-in-region beg end)
7552 (delete-region beg end)
7553 (org-remove-empty-overlays-at beg)
7554 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7555 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7556 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7557 (let ((bbb (point)))
7558 (insert-before-markers txt)
7559 (org-reinstall-markers-in-region bbb)
7560 (move-marker ins-point bbb))
7561 (or (bolp) (insert "\n"))
7562 (setq ins-end (point))
7563 (goto-char ins-point)
7564 (org-skip-whitespace)
7565 (when (and (< arg 0)
7566 (org-first-sibling-p)
7567 (> ne-ins ne-beg))
7568 ;; Move whitespace back to beginning
7569 (save-excursion
7570 (goto-char ins-end)
7571 (let ((kill-whole-line t))
7572 (kill-line (- ne-ins ne-beg)) (point)))
7573 (insert (make-string (- ne-ins ne-beg) ?\n)))
7574 (move-marker ins-point nil)
7575 (if folded
7576 (hide-subtree)
7577 (org-show-entry)
7578 (show-children)
7579 (org-cycle-hide-drawers 'children))
7580 (org-clean-visibility-after-subtree-move)
7581 ;; move back to the initial column we were at
7582 (move-to-column col)))
7584 (defvar org-subtree-clip ""
7585 "Clipboard for cut and paste of subtrees.
7586 This is actually only a copy of the kill, because we use the normal kill
7587 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7589 (defvar org-subtree-clip-folded nil
7590 "Was the last copied subtree folded?
7591 This is used to fold the tree back after pasting.")
7593 (defun org-cut-subtree (&optional n)
7594 "Cut the current subtree into the clipboard.
7595 With prefix arg N, cut this many sequential subtrees.
7596 This is a short-hand for marking the subtree and then cutting it."
7597 (interactive "p")
7598 (org-copy-subtree n 'cut))
7600 (defun org-copy-subtree (&optional n cut force-store-markers)
7601 "Cut the current subtree into the clipboard.
7602 With prefix arg N, cut this many sequential subtrees.
7603 This is a short-hand for marking the subtree and then copying it.
7604 If CUT is non-nil, actually cut the subtree.
7605 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7606 of some markers in the region, even if CUT is non-nil. This is
7607 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7608 (interactive "p")
7609 (let (beg end folded (beg0 (point)))
7610 (if (org-called-interactively-p 'any)
7611 (org-back-to-heading nil) ; take what looks like a subtree
7612 (org-back-to-heading t)) ; take what is really there
7613 (org-back-over-empty-lines)
7614 (setq beg (point))
7615 (skip-chars-forward " \t\r\n")
7616 (save-match-data
7617 (save-excursion (outline-end-of-heading)
7618 (setq folded (outline-invisible-p)))
7619 (condition-case nil
7620 (org-forward-same-level (1- n) t)
7621 (error nil))
7622 (org-end-of-subtree t t))
7623 (org-back-over-empty-lines)
7624 (setq end (point))
7625 (goto-char beg0)
7626 (when (> end beg)
7627 (setq org-subtree-clip-folded folded)
7628 (when (or cut force-store-markers)
7629 (org-save-markers-in-region beg end))
7630 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7631 (setq org-subtree-clip (current-kill 0))
7632 (message "%s: Subtree(s) with %d characters"
7633 (if cut "Cut" "Copied")
7634 (length org-subtree-clip)))))
7636 (defun org-paste-subtree (&optional level tree for-yank)
7637 "Paste the clipboard as a subtree, with modification of headline level.
7638 The entire subtree is promoted or demoted in order to match a new headline
7639 level.
7641 If the cursor is at the beginning of a headline, the same level as
7642 that headline is used to paste the tree
7644 If not, the new level is derived from the *visible* headings
7645 before and after the insertion point, and taken to be the inferior headline
7646 level of the two. So if the previous visible heading is level 3 and the
7647 next is level 4 (or vice versa), level 4 will be used for insertion.
7648 This makes sure that the subtree remains an independent subtree and does
7649 not swallow low level entries.
7651 You can also force a different level, either by using a numeric prefix
7652 argument, or by inserting the heading marker by hand. For example, if the
7653 cursor is after \"*****\", then the tree will be shifted to level 5.
7655 If optional TREE is given, use this text instead of the kill ring.
7657 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7658 move back over whitespace before inserting, and move point to the end of
7659 the inserted text when done."
7660 (interactive "P")
7661 (setq tree (or tree (and kill-ring (current-kill 0))))
7662 (unless (org-kill-is-subtree-p tree)
7663 (error "%s"
7664 (substitute-command-keys
7665 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7666 (org-with-limited-levels
7667 (let* ((visp (not (outline-invisible-p)))
7668 (txt tree)
7669 (^re_ "\\(\\*+\\)[ \t]*")
7670 (old-level (if (string-match org-outline-regexp-bol txt)
7671 (- (match-end 0) (match-beginning 0) 1)
7672 -1))
7673 (force-level (cond (level (prefix-numeric-value level))
7674 ((and (looking-at "[ \t]*$")
7675 (string-match
7676 "^\\*+$" (buffer-substring
7677 (point-at-bol) (point))))
7678 (- (match-end 1) (match-beginning 1)))
7679 ((and (bolp)
7680 (looking-at org-outline-regexp))
7681 (- (match-end 0) (point) 1))
7682 (t nil)))
7683 (previous-level (save-excursion
7684 (condition-case nil
7685 (progn
7686 (outline-previous-visible-heading 1)
7687 (if (looking-at ^re_)
7688 (- (match-end 0) (match-beginning 0) 1)
7690 (error 1))))
7691 (next-level (save-excursion
7692 (condition-case nil
7693 (progn
7694 (or (looking-at org-outline-regexp)
7695 (outline-next-visible-heading 1))
7696 (if (looking-at ^re_)
7697 (- (match-end 0) (match-beginning 0) 1)
7699 (error 1))))
7700 (new-level (or force-level (max previous-level next-level)))
7701 (shift (if (or (= old-level -1)
7702 (= new-level -1)
7703 (= old-level new-level))
7705 (- new-level old-level)))
7706 (delta (if (> shift 0) -1 1))
7707 (func (if (> shift 0) 'org-demote 'org-promote))
7708 (org-odd-levels-only nil)
7709 beg end newend)
7710 ;; Remove the forced level indicator
7711 (if force-level
7712 (delete-region (point-at-bol) (point)))
7713 ;; Paste
7714 (beginning-of-line (if (bolp) 1 2))
7715 (unless for-yank (org-back-over-empty-lines))
7716 (setq beg (point))
7717 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7718 (insert-before-markers txt)
7719 (unless (string-match "\n\\'" txt) (insert "\n"))
7720 (setq newend (point))
7721 (org-reinstall-markers-in-region beg)
7722 (setq end (point))
7723 (goto-char beg)
7724 (skip-chars-forward " \t\n\r")
7725 (setq beg (point))
7726 (if (and (outline-invisible-p) visp)
7727 (save-excursion (outline-show-heading)))
7728 ;; Shift if necessary
7729 (unless (= shift 0)
7730 (save-restriction
7731 (narrow-to-region beg end)
7732 (while (not (= shift 0))
7733 (org-map-region func (point-min) (point-max))
7734 (setq shift (+ delta shift)))
7735 (goto-char (point-min))
7736 (setq newend (point-max))))
7737 (when (or (org-called-interactively-p 'interactive) for-yank)
7738 (message "Clipboard pasted as level %d subtree" new-level))
7739 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7740 kill-ring
7741 (eq org-subtree-clip (current-kill 0))
7742 org-subtree-clip-folded)
7743 ;; The tree was folded before it was killed/copied
7744 (hide-subtree))
7745 (and for-yank (goto-char newend)))))
7747 (defun org-kill-is-subtree-p (&optional txt)
7748 "Check if the current kill is an outline subtree, or a set of trees.
7749 Returns nil if kill does not start with a headline, or if the first
7750 headline level is not the largest headline level in the tree.
7751 So this will actually accept several entries of equal levels as well,
7752 which is OK for `org-paste-subtree'.
7753 If optional TXT is given, check this string instead of the current kill."
7754 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7755 (re (org-get-limited-outline-regexp))
7756 (^re (concat "^" re))
7757 (start-level (and kill
7758 (string-match
7759 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7760 kill)
7761 (- (match-end 2) (match-beginning 2) 1)))
7762 (start (1+ (or (match-beginning 2) -1))))
7763 (if (not start-level)
7764 (progn
7765 nil) ;; does not even start with a heading
7766 (catch 'exit
7767 (while (setq start (string-match ^re kill (1+ start)))
7768 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7769 (throw 'exit nil)))
7770 t))))
7772 (defvar org-markers-to-move nil
7773 "Markers that should be moved with a cut-and-paste operation.
7774 Those markers are stored together with their positions relative to
7775 the start of the region.")
7777 (defun org-save-markers-in-region (beg end)
7778 "Check markers in region.
7779 If these markers are between BEG and END, record their position relative
7780 to BEG, so that after moving the block of text, we can put the markers back
7781 into place.
7782 This function gets called just before an entry or tree gets cut from the
7783 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7784 called immediately, to move the markers with the entries."
7785 (setq org-markers-to-move nil)
7786 (when (featurep 'org-clock)
7787 (org-clock-save-markers-for-cut-and-paste beg end))
7788 (when (featurep 'org-agenda)
7789 (org-agenda-save-markers-for-cut-and-paste beg end)))
7791 (defun org-check-and-save-marker (marker beg end)
7792 "Check if MARKER is between BEG and END.
7793 If yes, remember the marker and the distance to BEG."
7794 (when (and (marker-buffer marker)
7795 (equal (marker-buffer marker) (current-buffer)))
7796 (if (and (>= marker beg) (< marker end))
7797 (push (cons marker (- marker beg)) org-markers-to-move))))
7799 (defun org-reinstall-markers-in-region (beg)
7800 "Move all remembered markers to their position relative to BEG."
7801 (mapc (lambda (x)
7802 (move-marker (car x) (+ beg (cdr x))))
7803 org-markers-to-move)
7804 (setq org-markers-to-move nil))
7806 (defun org-narrow-to-subtree ()
7807 "Narrow buffer to the current subtree."
7808 (interactive)
7809 (save-excursion
7810 (save-match-data
7811 (org-with-limited-levels
7812 (narrow-to-region
7813 (progn (org-back-to-heading t) (point))
7814 (progn (org-end-of-subtree t t)
7815 (if (and (org-on-heading-p) (not (eobp))) (backward-char 1))
7816 (point)))))))
7818 (defun org-narrow-to-block ()
7819 "Narrow buffer to the current block."
7820 (interactive)
7821 (let* ((case-fold-search t)
7822 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7823 "^[ \t]*#\\+end_.*")))
7824 (if blockp
7825 (narrow-to-region (car blockp) (cdr blockp))
7826 (error "Not in a block"))))
7828 (eval-when-compile
7829 (defvar org-property-drawer-re))
7831 (defvar org-property-start-re) ;; defined below
7832 (defun org-clone-subtree-with-time-shift (n &optional shift)
7833 "Clone the task (subtree) at point N times.
7834 The clones will be inserted as siblings.
7836 In interactive use, the user will be prompted for the number of
7837 clones to be produced, and for a time SHIFT, which may be a
7838 repeater as used in time stamps, for example `+3d'.
7840 When a valid repeater is given and the entry contains any time
7841 stamps, the clones will become a sequence in time, with time
7842 stamps in the subtree shifted for each clone produced. If SHIFT
7843 is nil or the empty string, time stamps will be left alone. The
7844 ID property of the original subtree is removed.
7846 If the original subtree did contain time stamps with a repeater,
7847 the following will happen:
7848 - the repeater will be removed in each clone
7849 - an additional clone will be produced, with the current, unshifted
7850 date(s) in the entry.
7851 - the original entry will be placed *after* all the clones, with
7852 repeater intact.
7853 - the start days in the repeater in the original entry will be shifted
7854 to past the last clone.
7855 I this way you can spell out a number of instances of a repeating task,
7856 and still retain the repeater to cover future instances of the task."
7857 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7858 (let (beg end template task idprop
7859 shift-n shift-what doshift nmin nmax (n-no-remove -1))
7860 (if (not (and (integerp n) (> n 0)))
7861 (error "Invalid number of replications %s" n))
7862 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7863 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
7864 shift)))
7865 (error "Invalid shift specification %s" shift))
7866 (when doshift
7867 (setq shift-n (string-to-number (match-string 1 shift))
7868 shift-what (cdr (assoc (match-string 2 shift)
7869 '(("d" . day) ("w" . week)
7870 ("m" . month) ("y" . year))))))
7871 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7872 (setq nmin 1 nmax n)
7873 (org-back-to-heading t)
7874 (setq beg (point))
7875 (setq idprop (org-entry-get nil "ID"))
7876 (org-end-of-subtree t t)
7877 (or (bolp) (insert "\n"))
7878 (setq end (point))
7879 (setq template (buffer-substring beg end))
7880 ;; Remove clocks and empty drawers
7881 (with-temp-buffer
7882 (insert template)
7883 (goto-char (point-min))
7884 (while (re-search-forward
7885 "^[ \t]*CLOCK:.*$" (save-excursion (org-end-of-subtree t t)) t)
7886 (replace-match "")
7887 (kill-whole-line))
7888 (goto-char (point-min))
7889 (while (re-search-forward
7890 (concat "^[ \t]*:" (regexp-opt org-drawers) ":[ \t]*$") nil t)
7891 (mapc (lambda(d) (org-remove-empty-drawer-at d (point))) org-drawers))
7892 (setq template (buffer-substring (point-min) (point-max))))
7893 (when (and doshift
7894 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
7895 (delete-region beg end)
7896 (setq end beg)
7897 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7898 (goto-char end)
7899 (loop for n from nmin to nmax do
7900 ;; prepare clone
7901 (with-temp-buffer
7902 (insert template)
7903 (org-mode)
7904 (goto-char (point-min))
7905 (and idprop (if org-clone-delete-id
7906 (org-entry-delete nil "ID")
7907 (org-id-get-create t)))
7908 (while (re-search-forward org-property-start-re nil t)
7909 (org-remove-empty-drawer-at "PROPERTIES" (point)))
7910 (goto-char (point-min))
7911 (when doshift
7912 (while (re-search-forward org-ts-regexp-both nil t)
7913 (org-timestamp-change (* n shift-n) shift-what))
7914 (unless (= n n-no-remove)
7915 (goto-char (point-min))
7916 (while (re-search-forward org-ts-regexp nil t)
7917 (save-excursion
7918 (goto-char (match-beginning 0))
7919 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
7920 (delete-region (match-beginning 1) (match-end 1)))))))
7921 (setq task (buffer-string)))
7922 (insert task))
7923 (goto-char beg)))
7925 ;;; Outline Sorting
7927 (defun org-sort (with-case)
7928 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
7929 Optional argument WITH-CASE means sort case-sensitively.
7930 With a double prefix argument, also remove duplicate entries."
7931 (interactive "P")
7932 (cond
7933 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
7934 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
7936 (org-call-with-arg 'org-sort-entries with-case))))
7938 (defun org-sort-remove-invisible (s)
7939 (remove-text-properties 0 (length s) org-rm-props s)
7940 (while (string-match org-bracket-link-regexp s)
7941 (setq s (replace-match (if (match-end 2)
7942 (match-string 3 s)
7943 (match-string 1 s)) t t s)))
7946 (defvar org-priority-regexp) ; defined later in the file
7948 (defvar org-after-sorting-entries-or-items-hook nil
7949 "Hook that is run after a bunch of entries or items have been sorted.
7950 When children are sorted, the cursor is in the parent line when this
7951 hook gets called. When a region or a plain list is sorted, the cursor
7952 will be in the first entry of the sorted region/list.")
7954 (defun org-sort-entries
7955 (&optional with-case sorting-type getkey-func compare-func property)
7956 "Sort entries on a certain level of an outline tree.
7957 If there is an active region, the entries in the region are sorted.
7958 Else, if the cursor is before the first entry, sort the top-level items.
7959 Else, the children of the entry at point are sorted.
7961 Sorting can be alphabetically, numerically, by date/time as given by
7962 a time stamp, by a property or by priority.
7964 The command prompts for the sorting type unless it has been given to the
7965 function through the SORTING-TYPE argument, which needs to be a character,
7966 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
7967 precise meaning of each character:
7969 n Numerically, by converting the beginning of the entry/item to a number.
7970 a Alphabetically, ignoring the TODO keyword and the priority, if any.
7971 t By date/time, either the first active time stamp in the entry, or, if
7972 none exist, by the first inactive one.
7973 s By the scheduled date/time.
7974 d By deadline date/time.
7975 c By creation time, which is assumed to be the first inactive time stamp
7976 at the beginning of a line.
7977 p By priority according to the cookie.
7978 r By the value of a property.
7980 Capital letters will reverse the sort order.
7982 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
7983 called with point at the beginning of the record. It must return either
7984 a string or a number that should serve as the sorting key for that record.
7986 Comparing entries ignores case by default. However, with an optional argument
7987 WITH-CASE, the sorting considers case as well."
7988 (interactive "P")
7989 (let ((case-func (if with-case 'identity 'downcase))
7990 start beg end stars re re2
7991 txt what tmp)
7992 ;; Find beginning and end of region to sort
7993 (cond
7994 ((org-region-active-p)
7995 ;; we will sort the region
7996 (setq end (region-end)
7997 what "region")
7998 (goto-char (region-beginning))
7999 (if (not (org-on-heading-p)) (outline-next-heading))
8000 (setq start (point)))
8001 ((or (org-on-heading-p)
8002 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8003 ;; we will sort the children of the current headline
8004 (org-back-to-heading)
8005 (setq start (point)
8006 end (progn (org-end-of-subtree t t)
8007 (or (bolp) (insert "\n"))
8008 (org-back-over-empty-lines)
8009 (point))
8010 what "children")
8011 (goto-char start)
8012 (show-subtree)
8013 (outline-next-heading))
8015 ;; we will sort the top-level entries in this file
8016 (goto-char (point-min))
8017 (or (org-on-heading-p) (outline-next-heading))
8018 (setq start (point))
8019 (goto-char (point-max))
8020 (beginning-of-line 1)
8021 (when (looking-at ".*?\\S-")
8022 ;; File ends in a non-white line
8023 (end-of-line 1)
8024 (insert "\n"))
8025 (setq end (point-max))
8026 (setq what "top-level")
8027 (goto-char start)
8028 (show-all)))
8030 (setq beg (point))
8031 (if (>= beg end) (error "Nothing to sort"))
8033 (looking-at "\\(\\*+\\)")
8034 (setq stars (match-string 1)
8035 re (concat "^" (regexp-quote stars) " +")
8036 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8037 txt (buffer-substring beg end))
8038 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8039 (if (and (not (equal stars "*")) (string-match re2 txt))
8040 (error "Region to sort contains a level above the first entry"))
8042 (unless sorting-type
8043 (message
8044 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8045 [t]ime [s]cheduled [d]eadline [c]reated
8046 A/N/T/S/D/C/P/O/F means reversed:"
8047 what)
8048 (setq sorting-type (read-char-exclusive))
8050 (and (= (downcase sorting-type) ?f)
8051 (setq getkey-func
8052 (org-icompleting-read "Sort using function: "
8053 obarray 'fboundp t nil nil))
8054 (setq getkey-func (intern getkey-func)))
8056 (and (= (downcase sorting-type) ?r)
8057 (setq property
8058 (org-icompleting-read "Property: "
8059 (mapcar 'list (org-buffer-property-keys t))
8060 nil t))))
8062 (message "Sorting entries...")
8064 (save-restriction
8065 (narrow-to-region start end)
8066 (let ((dcst (downcase sorting-type))
8067 (case-fold-search nil)
8068 (now (current-time)))
8069 (sort-subr
8070 (/= dcst sorting-type)
8071 ;; This function moves to the beginning character of the "record" to
8072 ;; be sorted.
8073 (lambda nil
8074 (if (re-search-forward re nil t)
8075 (goto-char (match-beginning 0))
8076 (goto-char (point-max))))
8077 ;; This function moves to the last character of the "record" being
8078 ;; sorted.
8079 (lambda nil
8080 (save-match-data
8081 (condition-case nil
8082 (outline-forward-same-level 1)
8083 (error
8084 (goto-char (point-max))))))
8085 ;; This function returns the value that gets sorted against.
8086 (lambda nil
8087 (cond
8088 ((= dcst ?n)
8089 (if (looking-at org-complex-heading-regexp)
8090 (string-to-number (match-string 4))
8091 nil))
8092 ((= dcst ?a)
8093 (if (looking-at org-complex-heading-regexp)
8094 (funcall case-func (match-string 4))
8095 nil))
8096 ((= dcst ?t)
8097 (let ((end (save-excursion (outline-next-heading) (point))))
8098 (if (or (re-search-forward org-ts-regexp end t)
8099 (re-search-forward org-ts-regexp-both end t))
8100 (org-time-string-to-seconds (match-string 0))
8101 (org-float-time now))))
8102 ((= dcst ?c)
8103 (let ((end (save-excursion (outline-next-heading) (point))))
8104 (if (re-search-forward
8105 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8106 end t)
8107 (org-time-string-to-seconds (match-string 0))
8108 (org-float-time now))))
8109 ((= dcst ?s)
8110 (let ((end (save-excursion (outline-next-heading) (point))))
8111 (if (re-search-forward org-scheduled-time-regexp end t)
8112 (org-time-string-to-seconds (match-string 1))
8113 (org-float-time now))))
8114 ((= dcst ?d)
8115 (let ((end (save-excursion (outline-next-heading) (point))))
8116 (if (re-search-forward org-deadline-time-regexp end t)
8117 (org-time-string-to-seconds (match-string 1))
8118 (org-float-time now))))
8119 ((= dcst ?p)
8120 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8121 (string-to-char (match-string 2))
8122 org-default-priority))
8123 ((= dcst ?r)
8124 (or (org-entry-get nil property) ""))
8125 ((= dcst ?o)
8126 (if (looking-at org-complex-heading-regexp)
8127 (- 9999 (length (member (match-string 2)
8128 org-todo-keywords-1)))))
8129 ((= dcst ?f)
8130 (if getkey-func
8131 (progn
8132 (setq tmp (funcall getkey-func))
8133 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8134 tmp)
8135 (error "Invalid key function `%s'" getkey-func)))
8136 (t (error "Invalid sorting type `%c'" sorting-type))))
8138 (cond
8139 ((= dcst ?a) 'string<)
8140 ((= dcst ?f) compare-func)
8141 ((member dcst '(?p ?t ?s ?d ?c)) '<)
8142 (t nil)))))
8143 (run-hooks 'org-after-sorting-entries-or-items-hook)
8144 (message "Sorting entries...done")))
8146 (defun org-do-sort (table what &optional with-case sorting-type)
8147 "Sort TABLE of WHAT according to SORTING-TYPE.
8148 The user will be prompted for the SORTING-TYPE if the call to this
8149 function does not specify it. WHAT is only for the prompt, to indicate
8150 what is being sorted. The sorting key will be extracted from
8151 the car of the elements of the table.
8152 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8153 (unless sorting-type
8154 (message
8155 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8156 what)
8157 (setq sorting-type (read-char-exclusive)))
8158 (let ((dcst (downcase sorting-type))
8159 extractfun comparefun)
8160 ;; Define the appropriate functions
8161 (cond
8162 ((= dcst ?n)
8163 (setq extractfun 'string-to-number
8164 comparefun (if (= dcst sorting-type) '< '>)))
8165 ((= dcst ?a)
8166 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8167 (lambda(x) (downcase (org-sort-remove-invisible x))))
8168 comparefun (if (= dcst sorting-type)
8169 'string<
8170 (lambda (a b) (and (not (string< a b))
8171 (not (string= a b)))))))
8172 ((= dcst ?t)
8173 (setq extractfun
8174 (lambda (x)
8175 (if (or (string-match org-ts-regexp x)
8176 (string-match org-ts-regexp-both x))
8177 (org-float-time
8178 (org-time-string-to-time (match-string 0 x)))
8180 comparefun (if (= dcst sorting-type) '< '>)))
8181 (t (error "Invalid sorting type `%c'" sorting-type)))
8183 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8184 table)
8185 (lambda (a b) (funcall comparefun (car a) (car b))))))
8188 ;;; The orgstruct minor mode
8190 ;; Define a minor mode which can be used in other modes in order to
8191 ;; integrate the org-mode structure editing commands.
8193 ;; This is really a hack, because the org-mode structure commands use
8194 ;; keys which normally belong to the major mode. Here is how it
8195 ;; works: The minor mode defines all the keys necessary to operate the
8196 ;; structure commands, but wraps the commands into a function which
8197 ;; tests if the cursor is currently at a headline or a plain list
8198 ;; item. If that is the case, the structure command is used,
8199 ;; temporarily setting many Org-mode variables like regular
8200 ;; expressions for filling etc. However, when any of those keys is
8201 ;; used at a different location, function uses `key-binding' to look
8202 ;; up if the key has an associated command in another currently active
8203 ;; keymap (minor modes, major mode, global), and executes that
8204 ;; command. There might be problems if any of the keys is otherwise
8205 ;; used as a prefix key.
8207 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8208 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8209 ;; addresses this by checking explicitly for both bindings.
8211 (defvar orgstruct-mode-map (make-sparse-keymap)
8212 "Keymap for the minor `orgstruct-mode'.")
8214 (defvar org-local-vars nil
8215 "List of local variables, for use by `orgstruct-mode'.")
8217 ;;;###autoload
8218 (define-minor-mode orgstruct-mode
8219 "Toggle the minor mode `orgstruct-mode'.
8220 This mode is for using Org-mode structure commands in other
8221 modes. The following keys behave as if Org-mode were active, if
8222 the cursor is on a headline, or on a plain list item (both as
8223 defined by Org-mode).
8225 M-up Move entry/item up
8226 M-down Move entry/item down
8227 M-left Promote
8228 M-right Demote
8229 M-S-up Move entry/item up
8230 M-S-down Move entry/item down
8231 M-S-left Promote subtree
8232 M-S-right Demote subtree
8233 M-q Fill paragraph and items like in Org-mode
8234 C-c ^ Sort entries
8235 C-c - Cycle list bullet
8236 TAB Cycle item visibility
8237 M-RET Insert new heading/item
8238 S-M-RET Insert new TODO heading / Checkbox item
8239 C-c C-c Set tags / toggle checkbox"
8240 nil " OrgStruct" nil
8241 (org-load-modules-maybe)
8242 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8244 ;;;###autoload
8245 (defun turn-on-orgstruct ()
8246 "Unconditionally turn on `orgstruct-mode'."
8247 (orgstruct-mode 1))
8249 (defun orgstruct++-mode (&optional arg)
8250 "Toggle `orgstruct-mode', the enhanced version of it.
8251 In addition to setting orgstruct-mode, this also exports all indentation
8252 and autofilling variables from org-mode into the buffer. It will also
8253 recognize item context in multiline items.
8254 Note that turning off orgstruct-mode will *not* remove the
8255 indentation/paragraph settings. This can only be done by refreshing the
8256 major mode, for example with \\[normal-mode]."
8257 (interactive "P")
8258 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8259 (if (< arg 1)
8260 (orgstruct-mode -1)
8261 (orgstruct-mode 1)
8262 (let (var val)
8263 (mapc
8264 (lambda (x)
8265 (when (string-match
8266 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8267 (symbol-name (car x)))
8268 (setq var (car x) val (nth 1 x))
8269 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8270 org-local-vars)
8271 (org-set-local 'orgstruct-is-++ t))))
8273 (defvar orgstruct-is-++ nil
8274 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8275 (make-variable-buffer-local 'orgstruct-is-++)
8277 ;;;###autoload
8278 (defun turn-on-orgstruct++ ()
8279 "Unconditionally turn on `orgstruct++-mode'."
8280 (orgstruct++-mode 1))
8282 (defun orgstruct-error ()
8283 "Error when there is no default binding for a structure key."
8284 (interactive)
8285 (error "This key has no function outside structure elements"))
8287 (defun orgstruct-setup ()
8288 "Setup orgstruct keymaps."
8289 (let ((nfunc 0)
8290 (bindings
8291 (list
8292 '([(meta up)] org-metaup)
8293 '([(meta down)] org-metadown)
8294 '([(meta left)] org-metaleft)
8295 '([(meta right)] org-metaright)
8296 '([(meta shift up)] org-shiftmetaup)
8297 '([(meta shift down)] org-shiftmetadown)
8298 '([(meta shift left)] org-shiftmetaleft)
8299 '([(meta shift right)] org-shiftmetaright)
8300 '([?\e (up)] org-metaup)
8301 '([?\e (down)] org-metadown)
8302 '([?\e (left)] org-metaleft)
8303 '([?\e (right)] org-metaright)
8304 '([?\e (shift up)] org-shiftmetaup)
8305 '([?\e (shift down)] org-shiftmetadown)
8306 '([?\e (shift left)] org-shiftmetaleft)
8307 '([?\e (shift right)] org-shiftmetaright)
8308 '([(shift up)] org-shiftup)
8309 '([(shift down)] org-shiftdown)
8310 '([(shift left)] org-shiftleft)
8311 '([(shift right)] org-shiftright)
8312 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8313 '("\M-q" fill-paragraph)
8314 '("\C-c^" org-sort)
8315 '("\C-c-" org-cycle-list-bullet)))
8316 elt key fun cmd)
8317 (while (setq elt (pop bindings))
8318 (setq nfunc (1+ nfunc))
8319 (setq key (org-key (car elt))
8320 fun (nth 1 elt)
8321 cmd (orgstruct-make-binding fun nfunc key))
8322 (org-defkey orgstruct-mode-map key cmd))
8324 ;; Special treatment needed for TAB and RET
8325 (org-defkey orgstruct-mode-map [(tab)]
8326 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8327 (org-defkey orgstruct-mode-map "\C-i"
8328 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8330 (org-defkey orgstruct-mode-map "\M-\C-m"
8331 (orgstruct-make-binding 'org-insert-heading 105
8332 "\M-\C-m" [(meta return)]))
8333 (org-defkey orgstruct-mode-map [(meta return)]
8334 (orgstruct-make-binding 'org-insert-heading 106
8335 [(meta return)] "\M-\C-m"))
8337 (org-defkey orgstruct-mode-map [(shift meta return)]
8338 (orgstruct-make-binding 'org-insert-todo-heading 107
8339 [(meta return)] "\M-\C-m"))
8341 (org-defkey orgstruct-mode-map "\e\C-m"
8342 (orgstruct-make-binding 'org-insert-heading 108
8343 "\e\C-m" [?\e (return)]))
8344 (org-defkey orgstruct-mode-map [?\e (return)]
8345 (orgstruct-make-binding 'org-insert-heading 109
8346 [?\e (return)] "\e\C-m"))
8347 (org-defkey orgstruct-mode-map [?\e (shift return)]
8348 (orgstruct-make-binding 'org-insert-todo-heading 110
8349 [?\e (return)] "\e\C-m"))
8351 (unless org-local-vars
8352 (setq org-local-vars (org-get-local-variables)))
8356 (defun orgstruct-make-binding (fun n &rest keys)
8357 "Create a function for binding in the structure minor mode.
8358 FUN is the command to call inside a table. N is used to create a unique
8359 command name. KEYS are keys that should be checked in for a command
8360 to execute outside of tables."
8361 (eval
8362 (list 'defun
8363 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8364 '(arg)
8365 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8366 "Outside of structure, run the binding of `"
8367 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8368 "'.")
8369 '(interactive "p")
8370 (list 'if
8371 `(org-context-p 'headline 'item
8372 (and orgstruct-is-++
8373 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8374 'item-body))
8375 (list 'org-run-like-in-org-mode (list 'quote fun))
8376 (list 'let '(orgstruct-mode)
8377 (list 'call-interactively
8378 (append '(or)
8379 (mapcar (lambda (k)
8380 (list 'key-binding k))
8381 keys)
8382 '('orgstruct-error))))))))
8384 (defun org-context-p (&rest contexts)
8385 "Check if local context is any of CONTEXTS.
8386 Possible values in the list of contexts are `table', `headline', and `item'."
8387 (let ((pos (point)))
8388 (goto-char (point-at-bol))
8389 (prog1 (or (and (memq 'table contexts)
8390 (looking-at "[ \t]*|"))
8391 (and (memq 'headline contexts)
8392 (looking-at org-outline-regexp))
8393 (and (memq 'item contexts)
8394 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8395 (and (memq 'item-body contexts)
8396 (org-in-item-p)))
8397 (goto-char pos))))
8399 (defun org-get-local-variables ()
8400 "Return a list of all local variables in an org-mode buffer."
8401 (let (varlist)
8402 (with-current-buffer (get-buffer-create "*Org tmp*")
8403 (erase-buffer)
8404 (org-mode)
8405 (setq varlist (buffer-local-variables)))
8406 (kill-buffer "*Org tmp*")
8407 (delq nil
8408 (mapcar
8409 (lambda (x)
8410 (setq x
8411 (if (symbolp x)
8412 (list x)
8413 (list (car x) (list 'quote (cdr x)))))
8414 (if (string-match
8415 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8416 (symbol-name (car x)))
8417 x nil))
8418 varlist))))
8420 (defun org-clone-local-variables (from-buffer &optional regexp)
8421 "Clone local variables from FROM-BUFFER.
8422 Optional argument REGEXP selects variables to clone."
8423 (mapc
8424 (lambda (pair)
8425 (and (symbolp (car pair))
8426 (or (null regexp)
8427 (string-match regexp (symbol-name (car pair))))
8428 (set (make-local-variable (car pair))
8429 (cdr pair))))
8430 (buffer-local-variables from-buffer)))
8432 ;;;###autoload
8433 (defun org-run-like-in-org-mode (cmd)
8434 "Run a command, pretending that the current buffer is in Org-mode.
8435 This will temporarily bind local variables that are typically bound in
8436 Org-mode to the values they have in Org-mode, and then interactively
8437 call CMD."
8438 (org-load-modules-maybe)
8439 (unless org-local-vars
8440 (setq org-local-vars (org-get-local-variables)))
8441 (eval (list 'let org-local-vars
8442 (list 'call-interactively (list 'quote cmd)))))
8444 ;;;; Archiving
8446 (defun org-get-category (&optional pos force-refresh)
8447 "Get the category applying to position POS."
8448 (if force-refresh (org-refresh-category-properties))
8449 (let ((pos (or pos (point))))
8450 (or (get-text-property pos 'org-category)
8451 (progn (org-refresh-category-properties)
8452 (get-text-property pos 'org-category)))))
8454 (defun org-refresh-category-properties ()
8455 "Refresh category text properties in the buffer."
8456 (let ((def-cat (cond
8457 ((null org-category)
8458 (if buffer-file-name
8459 (file-name-sans-extension
8460 (file-name-nondirectory buffer-file-name))
8461 "???"))
8462 ((symbolp org-category) (symbol-name org-category))
8463 (t org-category)))
8464 beg end cat pos optionp)
8465 (org-unmodified
8466 (save-excursion
8467 (save-restriction
8468 (widen)
8469 (goto-char (point-min))
8470 (put-text-property (point) (point-max) 'org-category def-cat)
8471 (while (re-search-forward
8472 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8473 (setq pos (match-end 0)
8474 optionp (equal (char-after (match-beginning 0)) ?#)
8475 cat (org-trim (match-string 2)))
8476 (if optionp
8477 (setq beg (point-at-bol) end (point-max))
8478 (org-back-to-heading t)
8479 (setq beg (point) end (org-end-of-subtree t t)))
8480 (put-text-property beg end 'org-category cat)
8481 (put-text-property beg end 'org-category-position beg)
8482 (goto-char pos)))))))
8485 ;;;; Link Stuff
8487 ;;; Link abbreviations
8489 (defun org-link-expand-abbrev (link)
8490 "Apply replacements as defined in `org-link-abbrev-alist."
8491 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8492 (let* ((key (match-string 1 link))
8493 (as (or (assoc key org-link-abbrev-alist-local)
8494 (assoc key org-link-abbrev-alist)))
8495 (tag (and (match-end 2) (match-string 3 link)))
8496 rpl)
8497 (if (not as)
8498 link
8499 (setq rpl (cdr as))
8500 (cond
8501 ((symbolp rpl) (funcall rpl tag))
8502 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8503 ((string-match "%h" rpl)
8504 (replace-match (url-hexify-string (or tag "")) t t rpl))
8505 (t (concat rpl tag)))))
8506 link))
8508 ;;; Storing and inserting links
8510 (defvar org-insert-link-history nil
8511 "Minibuffer history for links inserted with `org-insert-link'.")
8513 (defvar org-stored-links nil
8514 "Contains the links stored with `org-store-link'.")
8516 (defvar org-store-link-plist nil
8517 "Plist with info about the most recently link created with `org-store-link'.")
8519 (defvar org-link-protocols nil
8520 "Link protocols added to Org-mode using `org-add-link-type'.")
8522 (defvar org-store-link-functions nil
8523 "List of functions that are called to create and store a link.
8524 Each function will be called in turn until one returns a non-nil
8525 value. Each function should check if it is responsible for creating
8526 this link (for example by looking at the major mode).
8527 If not, it must exit and return nil.
8528 If yes, it should return a non-nil value after a calling
8529 `org-store-link-props' with a list of properties and values.
8530 Special properties are:
8532 :type The link prefix, like \"http\". This must be given.
8533 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8534 This is obligatory as well.
8535 :description Optional default description for the second pair
8536 of brackets in an Org-mode link. The user can still change
8537 this when inserting this link into an Org-mode buffer.
8539 In addition to these, any additional properties can be specified
8540 and then used in remember templates.")
8542 (defun org-add-link-type (type &optional follow export)
8543 "Add TYPE to the list of `org-link-types'.
8544 Re-compute all regular expressions depending on `org-link-types'
8546 FOLLOW and EXPORT are two functions.
8548 FOLLOW should take the link path as the single argument and do whatever
8549 is necessary to follow the link, for example find a file or display
8550 a mail message.
8552 EXPORT should format the link path for export to one of the export formats.
8553 It should be a function accepting three arguments:
8555 path the path of the link, the text after the prefix (like \"http:\")
8556 desc the description of the link, if any, or a description added by
8557 org-export-normalize-links if there is none
8558 format the export format, a symbol like `html' or `latex' or `ascii'..
8560 The function may use the FORMAT information to return different values
8561 depending on the format. The return value will be put literally into
8562 the exported file. If the return value is nil, this means Org should
8563 do what it normally does with links which do not have EXPORT defined.
8565 Org-mode has a built-in default for exporting links. If you are happy with
8566 this default, there is no need to define an export function for the link
8567 type. For a simple example of an export function, see `org-bbdb.el'."
8568 (add-to-list 'org-link-types type t)
8569 (org-make-link-regexps)
8570 (if (assoc type org-link-protocols)
8571 (setcdr (assoc type org-link-protocols) (list follow export))
8572 (push (list type follow export) org-link-protocols)))
8574 (defvar org-agenda-buffer-name)
8576 ;;;###autoload
8577 (defun org-store-link (arg)
8578 "\\<org-mode-map>Store an org-link to the current location.
8579 This link is added to `org-stored-links' and can later be inserted
8580 into an org-buffer with \\[org-insert-link].
8582 For some link types, a prefix arg is interpreted:
8583 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8584 For file links, arg negates `org-context-in-file-links'."
8585 (interactive "P")
8586 (org-load-modules-maybe)
8587 (setq org-store-link-plist nil) ; reset
8588 (org-with-limited-levels
8589 (let (link cpltxt desc description search txt custom-id agenda-link)
8590 (cond
8592 ((run-hook-with-args-until-success 'org-store-link-functions)
8593 (setq link (plist-get org-store-link-plist :link)
8594 desc (or (plist-get org-store-link-plist :description) link)))
8596 ((equal (buffer-name) "*Org Edit Src Example*")
8597 (let (label gc)
8598 (while (or (not label)
8599 (save-excursion
8600 (save-restriction
8601 (widen)
8602 (goto-char (point-min))
8603 (re-search-forward
8604 (regexp-quote (format org-coderef-label-format label))
8605 nil t))))
8606 (when label (message "Label exists already") (sit-for 2))
8607 (setq label (read-string "Code line label: " label)))
8608 (end-of-line 1)
8609 (setq link (format org-coderef-label-format label))
8610 (setq gc (- 79 (length link)))
8611 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8612 (insert link)
8613 (setq link (concat "(" label ")") desc nil)))
8615 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8616 ;; We are in the agenda, link to referenced location
8617 (let ((m (or (get-text-property (point) 'org-hd-marker)
8618 (get-text-property (point) 'org-marker))))
8619 (when m
8620 (org-with-point-at m
8621 (setq agenda-link
8622 (if (org-called-interactively-p 'any)
8623 (call-interactively 'org-store-link)
8624 (org-store-link nil)))))))
8626 ((eq major-mode 'calendar-mode)
8627 (let ((cd (calendar-cursor-to-date)))
8628 (setq link
8629 (format-time-string
8630 (car org-time-stamp-formats)
8631 (apply 'encode-time
8632 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8633 nil nil nil))))
8634 (org-store-link-props :type "calendar" :date cd)))
8636 ((eq major-mode 'w3-mode)
8637 (setq cpltxt (if (and (buffer-name)
8638 (not (string-match "Untitled" (buffer-name))))
8639 (buffer-name)
8640 (url-view-url t))
8641 link (org-make-link (url-view-url t)))
8642 (org-store-link-props :type "w3" :url (url-view-url t)))
8644 ((eq major-mode 'w3m-mode)
8645 (setq cpltxt (or w3m-current-title w3m-current-url)
8646 link (org-make-link w3m-current-url))
8647 (org-store-link-props :type "w3m" :url (url-view-url t)))
8649 ((setq search (run-hook-with-args-until-success
8650 'org-create-file-search-functions))
8651 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8652 "::" search))
8653 (setq cpltxt (or description link)))
8655 ((eq major-mode 'image-mode)
8656 (setq cpltxt (concat "file:"
8657 (abbreviate-file-name buffer-file-name))
8658 link (org-make-link cpltxt))
8659 (org-store-link-props :type "image" :file buffer-file-name))
8661 ((eq major-mode 'dired-mode)
8662 ;; link to the file in the current line
8663 (let ((file (dired-get-filename nil t)))
8664 (setq file (if file
8665 (abbreviate-file-name
8666 (expand-file-name (dired-get-filename nil t)))
8667 ;; otherwise, no file so use current directory.
8668 default-directory))
8669 (setq cpltxt (concat "file:" file)
8670 link (org-make-link cpltxt))))
8672 ((and (buffer-file-name (buffer-base-buffer)) (eq major-mode 'org-mode))
8673 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8674 (cond
8675 ((org-in-regexp "<<\\(.*?\\)>>")
8676 (setq cpltxt
8677 (concat "file:"
8678 (abbreviate-file-name
8679 (buffer-file-name (buffer-base-buffer)))
8680 "::" (match-string 1))
8681 link (org-make-link cpltxt)))
8682 ((and (featurep 'org-id)
8683 (or (eq org-link-to-org-use-id t)
8684 (and (eq org-link-to-org-use-id 'create-if-interactive)
8685 (org-called-interactively-p 'any))
8686 (and (eq org-link-to-org-use-id
8687 'create-if-interactive-and-no-custom-id)
8688 (org-called-interactively-p 'any)
8689 (not custom-id))
8690 (and org-link-to-org-use-id
8691 (org-entry-get nil "ID"))))
8692 ;; We can make a link using the ID.
8693 (setq link (condition-case nil
8694 (prog1 (org-id-store-link)
8695 (setq desc (plist-get org-store-link-plist
8696 :description)))
8697 (error
8698 ;; probably before first headline, link to file only
8699 (concat "file:"
8700 (abbreviate-file-name
8701 (buffer-file-name (buffer-base-buffer))))))))
8703 ;; Just link to current headline
8704 (setq cpltxt (concat "file:"
8705 (abbreviate-file-name
8706 (buffer-file-name (buffer-base-buffer)))))
8707 ;; Add a context search string
8708 (when (org-xor org-context-in-file-links arg)
8709 (setq txt (cond
8710 ((org-on-heading-p) nil)
8711 ((org-region-active-p)
8712 (buffer-substring (region-beginning) (region-end)))
8713 (t nil)))
8714 (when (or (null txt) (string-match "\\S-" txt))
8715 (setq cpltxt
8716 (concat cpltxt "::"
8717 (condition-case nil
8718 (org-make-org-heading-search-string txt)
8719 (error "")))
8720 desc (or (nth 4 (ignore-errors
8721 (org-heading-components))) "NONE"))))
8722 (if (string-match "::\\'" cpltxt)
8723 (setq cpltxt (substring cpltxt 0 -2)))
8724 (setq link (org-make-link cpltxt)))))
8726 ((buffer-file-name (buffer-base-buffer))
8727 ;; Just link to this file here.
8728 (setq cpltxt (concat "file:"
8729 (abbreviate-file-name
8730 (buffer-file-name (buffer-base-buffer)))))
8731 ;; Add a context string
8732 (when (org-xor org-context-in-file-links arg)
8733 (setq txt (if (org-region-active-p)
8734 (buffer-substring (region-beginning) (region-end))
8735 (buffer-substring (point-at-bol) (point-at-eol))))
8736 ;; Only use search option if there is some text.
8737 (when (string-match "\\S-" txt)
8738 (setq cpltxt
8739 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8740 desc "NONE")))
8741 (setq link (org-make-link cpltxt)))
8743 ((org-called-interactively-p 'interactive)
8744 (error "Cannot link to a buffer which is not visiting a file"))
8746 (t (setq link nil)))
8748 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8749 (setq link (or link cpltxt)
8750 desc (or desc cpltxt))
8751 (if (equal desc "NONE") (setq desc nil))
8753 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8754 (progn
8755 (setq org-stored-links
8756 (cons (list link desc) org-stored-links))
8757 (message "Stored: %s" (or desc link))
8758 (when custom-id
8759 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8760 "::#" custom-id))
8761 (setq org-stored-links
8762 (cons (list link desc) org-stored-links))))
8763 (or agenda-link (and link (org-make-link-string link desc)))))))
8765 (defun org-store-link-props (&rest plist)
8766 "Store link properties, extract names and addresses."
8767 (let (x adr)
8768 (when (setq x (plist-get plist :from))
8769 (setq adr (mail-extract-address-components x))
8770 (setq plist (plist-put plist :fromname (car adr)))
8771 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8772 (when (setq x (plist-get plist :to))
8773 (setq adr (mail-extract-address-components x))
8774 (setq plist (plist-put plist :toname (car adr)))
8775 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8776 (let ((from (plist-get plist :from))
8777 (to (plist-get plist :to)))
8778 (when (and from to org-from-is-user-regexp)
8779 (setq plist
8780 (plist-put plist :fromto
8781 (if (string-match org-from-is-user-regexp from)
8782 (concat "to %t")
8783 (concat "from %f"))))))
8784 (setq org-store-link-plist plist))
8786 (defun org-add-link-props (&rest plist)
8787 "Add these properties to the link property list."
8788 (let (key value)
8789 (while plist
8790 (setq key (pop plist) value (pop plist))
8791 (setq org-store-link-plist
8792 (plist-put org-store-link-plist key value)))))
8794 (defun org-email-link-description (&optional fmt)
8795 "Return the description part of an email link.
8796 This takes information from `org-store-link-plist' and formats it
8797 according to FMT (default from `org-email-link-description-format')."
8798 (setq fmt (or fmt org-email-link-description-format))
8799 (let* ((p org-store-link-plist)
8800 (to (plist-get p :toaddress))
8801 (from (plist-get p :fromaddress))
8802 (table
8803 (list
8804 (cons "%c" (plist-get p :fromto))
8805 (cons "%F" (plist-get p :from))
8806 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8807 (cons "%T" (plist-get p :to))
8808 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8809 (cons "%s" (plist-get p :subject))
8810 (cons "%d" (plist-get p :date))
8811 (cons "%m" (plist-get p :message-id)))))
8812 (when (string-match "%c" fmt)
8813 ;; Check if the user wrote this message
8814 (if (and org-from-is-user-regexp from to
8815 (save-match-data (string-match org-from-is-user-regexp from)))
8816 (setq fmt (replace-match "to %t" t t fmt))
8817 (setq fmt (replace-match "from %f" t t fmt))))
8818 (org-replace-escapes fmt table)))
8820 (defun org-make-org-heading-search-string (&optional string heading)
8821 "Make search string for STRING or current headline."
8822 (interactive)
8823 (let ((s (or string (org-get-heading)))
8824 (lines org-context-in-file-links))
8825 (unless (and string (not heading))
8826 ;; We are using a headline, clean up garbage in there.
8827 (if (string-match org-todo-regexp s)
8828 (setq s (replace-match "" t t s)))
8829 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8830 (setq s (replace-match "" t t s)))
8831 (setq s (org-trim s))
8832 (if (string-match (concat "^\\(" org-quote-string "\\|"
8833 org-comment-string "\\)") s)
8834 (setq s (replace-match "" t t s)))
8835 (while (string-match org-ts-regexp s)
8836 (setq s (replace-match "" t t s))))
8837 (or string (setq s (concat "*" s))) ; Add * for headlines
8838 (when (and string (integerp lines) (> lines 0))
8839 (let ((slines (org-split-string s "\n")))
8840 (when (< lines (length slines))
8841 (setq s (mapconcat
8842 'identity
8843 (reverse (nthcdr (- (length slines) lines)
8844 (reverse slines))) "\n")))))
8845 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8847 (defun org-make-link (&rest strings)
8848 "Concatenate STRINGS."
8849 (apply 'concat strings))
8851 (defun org-make-link-string (link &optional description)
8852 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8853 (unless (string-match "\\S-" link)
8854 (error "Empty link"))
8855 (when (and description
8856 (stringp description)
8857 (not (string-match "\\S-" description)))
8858 (setq description nil))
8859 (when (stringp description)
8860 ;; Remove brackets from the description, they are fatal.
8861 (while (string-match "\\[" description)
8862 (setq description (replace-match "{" t t description)))
8863 (while (string-match "\\]" description)
8864 (setq description (replace-match "}" t t description))))
8865 (when (equal link description)
8866 ;; No description needed, it is identical
8867 (setq description nil))
8868 (when (and (not description)
8869 (not (string-match (org-image-file-name-regexp) link))
8870 (not (equal link (org-link-escape link))))
8871 (setq description (org-extract-attributes link)))
8872 (setq link
8873 (cond ((string-match (org-image-file-name-regexp) link) link)
8874 ((string-match org-link-types-re link)
8875 (concat (match-string 1 link)
8876 (org-link-escape (substring link (match-end 1)))))
8877 (t (org-link-escape link))))
8878 (concat "[[" link "]"
8879 (if description (concat "[" description "]") "")
8880 "]"))
8882 (defconst org-link-escape-chars
8883 '(?\ ?\[ ?\] ?\; ?\= ?\+)
8884 "List of characters that should be escaped in link.
8885 This is the list that is used for internal purposes.")
8887 (defvar org-url-encoding-use-url-hexify nil)
8889 (defconst org-link-escape-chars-browser
8890 '(?\ )
8891 "List of escapes for characters that are problematic in links.
8892 This is the list that is used before handing over to the browser.")
8894 (defun org-link-escape (text &optional table merge)
8895 "Return percent escaped representation of TEXT.
8896 TEXT is a string with the text to escape.
8897 Optional argument TABLE is a list with characters that should be
8898 escaped. When nil, `org-link-escape-chars' is used.
8899 If optional argument MERGE is set, merge TABLE into
8900 `org-link-escape-chars'."
8901 (if (and org-url-encoding-use-url-hexify (not table))
8902 (url-hexify-string text)
8903 (cond
8904 ((and table merge)
8905 (mapc (lambda (defchr)
8906 (unless (member defchr table)
8907 (setq table (cons defchr table)))) org-link-escape-chars))
8908 ((null table)
8909 (setq table org-link-escape-chars)))
8910 (mapconcat
8911 (lambda (char)
8912 (if (or (member char table)
8913 (< char 32) (= char 37) (> char 126))
8914 (mapconcat (lambda (sequence-element)
8915 (format "%%%.2X" sequence-element))
8916 (or (encode-coding-char char 'utf-8)
8917 (error "Unable to percent escape character: %s"
8918 (char-to-string char))) "")
8919 (char-to-string char))) text "")))
8921 (defun org-link-unescape (str)
8922 "Unhex hexified unicode strings as returned from the JavaScript function
8923 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
8924 (unless (and (null str) (string= "" str))
8925 (let ((pos 0) (case-fold-search t) unhexed)
8926 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
8927 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
8928 (setq str (replace-match unhexed t t str))
8929 (setq pos (+ pos (length unhexed))))))
8930 str)
8932 (defun org-link-unescape-compound (hex)
8933 "Unhexify unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
8934 Note: this function also decodes single byte encodings like
8935 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
8936 (save-match-data
8937 (let* ((bytes (cdr (split-string hex "%")))
8938 (ret "")
8939 (eat 0)
8940 (sum 0))
8941 (while bytes
8942 (let* ((val (string-to-number (pop bytes) 16))
8943 (shift-xor
8944 (if (= 0 eat)
8945 (cond
8946 ((>= val 252) (cons 6 252))
8947 ((>= val 248) (cons 5 248))
8948 ((>= val 240) (cons 4 240))
8949 ((>= val 224) (cons 3 224))
8950 ((>= val 192) (cons 2 192))
8951 (t (cons 0 0)))
8952 (cons 6 128))))
8953 (if (>= val 192) (setq eat (car shift-xor)))
8954 (setq val (logxor val (cdr shift-xor)))
8955 (setq sum (+ (lsh sum (car shift-xor)) val))
8956 (if (> eat 0) (setq eat (- eat 1)))
8957 (cond
8958 ((= 0 eat) ;multi byte
8959 (setq ret (concat ret (org-char-to-string sum)))
8960 (setq sum 0))
8961 ((not bytes) ; single byte(s)
8962 (setq ret (org-link-unescape-single-byte-sequence hex))))
8963 )) ;; end (while bytes
8964 ret )))
8966 (defun org-link-unescape-single-byte-sequence (hex)
8967 "Unhexify hex-encoded single byte character sequences."
8968 (mapconcat (lambda (byte)
8969 (char-to-string (string-to-number byte 16)))
8970 (cdr (split-string hex "%")) ""))
8972 (defun org-xor (a b)
8973 "Exclusive or."
8974 (if a (not b) b))
8976 (defun org-fixup-message-id-for-http (s)
8977 "Replace special characters in a message id, so it can be used in an http query."
8978 (when (string-match "%" s)
8979 (setq s (mapconcat (lambda (c)
8980 (if (eq c ?%)
8981 "%25"
8982 (char-to-string c)))
8983 s "")))
8984 (while (string-match "<" s)
8985 (setq s (replace-match "%3C" t t s)))
8986 (while (string-match ">" s)
8987 (setq s (replace-match "%3E" t t s)))
8988 (while (string-match "@" s)
8989 (setq s (replace-match "%40" t t s)))
8992 ;;;###autoload
8993 (defun org-insert-link-global ()
8994 "Insert a link like Org-mode does.
8995 This command can be called in any mode to insert a link in Org-mode syntax."
8996 (interactive)
8997 (org-load-modules-maybe)
8998 (org-run-like-in-org-mode 'org-insert-link))
9000 (defun org-insert-link (&optional complete-file link-location default-description)
9001 "Insert a link. At the prompt, enter the link.
9003 Completion can be used to insert any of the link protocol prefixes like
9004 http or ftp in use.
9006 The history can be used to select a link previously stored with
9007 `org-store-link'. When the empty string is entered (i.e. if you just
9008 press RET at the prompt), the link defaults to the most recently
9009 stored link. As SPC triggers completion in the minibuffer, you need to
9010 use M-SPC or C-q SPC to force the insertion of a space character.
9012 You will also be prompted for a description, and if one is given, it will
9013 be displayed in the buffer instead of the link.
9015 If there is already a link at point, this command will allow you to edit link
9016 and description parts.
9018 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9019 be selected using completion. The path to the file will be relative to the
9020 current directory if the file is in the current directory or a subdirectory.
9021 Otherwise, the link will be the absolute path as completed in the minibuffer
9022 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9023 option `org-link-file-path-type'.
9025 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9026 the current directory or below.
9028 With three \\[universal-argument] prefixes, negate the meaning of
9029 `org-keep-stored-link-after-insertion'.
9031 If `org-make-link-description-function' is non-nil, this function will be
9032 called with the link target, and the result will be the default
9033 link description.
9035 If the LINK-LOCATION parameter is non-nil, this value will be
9036 used as the link location instead of reading one interactively.
9038 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9039 be used as the default description."
9040 (interactive "P")
9041 (let* ((wcf (current-window-configuration))
9042 (region (if (org-region-active-p)
9043 (buffer-substring (region-beginning) (region-end))))
9044 (remove (and region (list (region-beginning) (region-end))))
9045 (desc region)
9046 tmphist ; byte-compile incorrectly complains about this
9047 (link link-location)
9048 entry file all-prefixes)
9049 (cond
9050 (link-location) ; specified by arg, just use it.
9051 ((org-in-regexp org-bracket-link-regexp 1)
9052 ;; We do have a link at point, and we are going to edit it.
9053 (setq remove (list (match-beginning 0) (match-end 0)))
9054 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9055 (setq link (read-string "Link: "
9056 (org-link-unescape
9057 (org-match-string-no-properties 1)))))
9058 ((or (org-in-regexp org-angle-link-re)
9059 (org-in-regexp org-plain-link-re))
9060 ;; Convert to bracket link
9061 (setq remove (list (match-beginning 0) (match-end 0))
9062 link (read-string "Link: "
9063 (org-remove-angle-brackets (match-string 0)))))
9064 ((member complete-file '((4) (16)))
9065 ;; Completing read for file names.
9066 (setq link (org-file-complete-link complete-file)))
9068 ;; Read link, with completion for stored links.
9069 (with-output-to-temp-buffer "*Org Links*"
9070 (princ "Insert a link.
9071 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9072 (when org-stored-links
9073 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9074 (princ (mapconcat
9075 (lambda (x)
9076 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
9077 (reverse org-stored-links) "\n"))))
9078 (let ((cw (selected-window)))
9079 (select-window (get-buffer-window "*Org Links*" 'visible))
9080 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9081 (unless (pos-visible-in-window-p (point-max))
9082 (org-fit-window-to-buffer))
9083 (and (window-live-p cw) (select-window cw)))
9084 ;; Fake a link history, containing the stored links.
9085 (setq tmphist (append (mapcar 'car org-stored-links)
9086 org-insert-link-history))
9087 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
9088 (mapcar 'car org-link-abbrev-alist)
9089 org-link-types))
9090 (unwind-protect
9091 (progn
9092 (setq link
9093 (let ((org-completion-use-ido nil)
9094 (org-completion-use-iswitchb nil))
9095 (org-completing-read
9096 "Link: "
9097 (append
9098 (mapcar (lambda (x) (list (concat x ":")))
9099 all-prefixes)
9100 (mapcar 'car org-stored-links))
9101 nil nil nil
9102 'tmphist
9103 (car (car org-stored-links)))))
9104 (if (not (string-match "\\S-" link))
9105 (error "No link selected"))
9106 (if (or (member link all-prefixes)
9107 (and (equal ":" (substring link -1))
9108 (member (substring link 0 -1) all-prefixes)
9109 (setq link (substring link 0 -1))))
9110 (setq link (org-link-try-special-completion link))))
9111 (set-window-configuration wcf)
9112 (kill-buffer "*Org Links*"))
9113 (setq entry (assoc link org-stored-links))
9114 (or entry (push link org-insert-link-history))
9115 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9116 (not org-keep-stored-link-after-insertion))
9117 (setq org-stored-links (delq (assoc link org-stored-links)
9118 org-stored-links)))
9119 (setq desc (or desc (nth 1 entry)))))
9121 (if (string-match org-plain-link-re link)
9122 ;; URL-like link, normalize the use of angular brackets.
9123 (setq link (org-make-link (org-remove-angle-brackets link))))
9125 ;; Check if we are linking to the current file with a search option
9126 ;; If yes, simplify the link by using only the search option.
9127 (when (and buffer-file-name
9128 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9129 (let* ((path (match-string 1 link))
9130 (case-fold-search nil)
9131 (search (match-string 2 link)))
9132 (save-match-data
9133 (if (equal (file-truename buffer-file-name) (file-truename path))
9134 ;; We are linking to this same file, with a search option
9135 (setq link search)))))
9137 ;; Check if we can/should use a relative path. If yes, simplify the link
9138 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9139 (let* ((type (match-string 1 link))
9140 (path (match-string 2 link))
9141 (origpath path)
9142 (case-fold-search nil))
9143 (cond
9144 ((or (eq org-link-file-path-type 'absolute)
9145 (equal complete-file '(16)))
9146 (setq path (abbreviate-file-name (expand-file-name path))))
9147 ((eq org-link-file-path-type 'noabbrev)
9148 (setq path (expand-file-name path)))
9149 ((eq org-link-file-path-type 'relative)
9150 (setq path (file-relative-name path)))
9152 (save-match-data
9153 (if (string-match (concat "^" (regexp-quote
9154 (expand-file-name
9155 (file-name-as-directory
9156 default-directory))))
9157 (expand-file-name path))
9158 ;; We are linking a file with relative path name.
9159 (setq path (substring (expand-file-name path)
9160 (match-end 0)))
9161 (setq path (abbreviate-file-name (expand-file-name path)))))))
9162 (setq link (concat type path))
9163 (if (equal desc origpath)
9164 (setq desc path))))
9166 (if org-make-link-description-function
9167 (setq desc (funcall org-make-link-description-function link desc))
9168 (if default-description (setq desc default-description)))
9170 (setq desc (read-string "Description: " desc))
9171 (unless (string-match "\\S-" desc) (setq desc nil))
9172 (if remove (apply 'delete-region remove))
9173 (insert (org-make-link-string link desc))))
9175 (defun org-link-try-special-completion (type)
9176 "If there is completion support for link type TYPE, offer it."
9177 (let ((fun (intern (concat "org-" type "-complete-link"))))
9178 (if (functionp fun)
9179 (funcall fun)
9180 (read-string "Link (no completion support): " (concat type ":")))))
9182 (defun org-file-complete-link (&optional arg)
9183 "Create a file link using completion."
9184 (let (file link)
9185 (setq file (read-file-name "File: "))
9186 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9187 (pwd1 (file-name-as-directory (abbreviate-file-name
9188 (expand-file-name ".")))))
9189 (cond
9190 ((equal arg '(16))
9191 (setq link (org-make-link
9192 "file:"
9193 (abbreviate-file-name (expand-file-name file)))))
9194 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9195 (setq link (org-make-link "file:" (match-string 1 file))))
9196 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9197 (expand-file-name file))
9198 (setq link (org-make-link
9199 "file:" (match-string 1 (expand-file-name file)))))
9200 (t (setq link (org-make-link "file:" file)))))
9201 link))
9203 (defun org-completing-read (&rest args)
9204 "Completing-read with SPACE being a normal character."
9205 (let ((enable-recursive-minibuffers t)
9206 (minibuffer-local-completion-map
9207 (copy-keymap minibuffer-local-completion-map)))
9208 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9209 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9210 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9211 (apply 'org-icompleting-read args)))
9213 (defun org-completing-read-no-i (&rest args)
9214 (let (org-completion-use-ido org-completion-use-iswitchb)
9215 (apply 'org-completing-read args)))
9217 (defun org-iswitchb-completing-read (prompt choices &rest args)
9218 "Use iswitch as a completing-read replacement to choose from choices.
9219 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9220 from."
9221 (let* ((iswitchb-use-virtual-buffers nil)
9222 (iswitchb-make-buflist-hook
9223 (lambda ()
9224 (setq iswitchb-temp-buflist choices))))
9225 (iswitchb-read-buffer prompt)))
9227 (defun org-icompleting-read (&rest args)
9228 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9229 (org-without-partial-completion
9230 (if (and org-completion-use-ido
9231 (fboundp 'ido-completing-read)
9232 (boundp 'ido-mode) ido-mode
9233 (listp (second args)))
9234 (let ((ido-enter-matching-directory nil))
9235 (apply 'ido-completing-read (concat (car args))
9236 (if (consp (car (nth 1 args)))
9237 (mapcar 'car (nth 1 args))
9238 (nth 1 args))
9239 (cddr args)))
9240 (if (and org-completion-use-iswitchb
9241 (boundp 'iswitchb-mode) iswitchb-mode
9242 (listp (second args)))
9243 (apply 'org-iswitchb-completing-read (concat (car args))
9244 (if (consp (car (nth 1 args)))
9245 (mapcar 'car (nth 1 args))
9246 (nth 1 args))
9247 (cddr args))
9248 (apply 'completing-read args)))))
9250 (defun org-extract-attributes (s)
9251 "Extract the attributes cookie from a string and set as text property."
9252 (let (a attr (start 0) key value)
9253 (save-match-data
9254 (when (string-match "{{\\([^}]+\\)}}$" s)
9255 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9256 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9257 (setq key (match-string 1 a) value (match-string 2 a)
9258 start (match-end 0)
9259 attr (plist-put attr (intern key) value))))
9260 (org-add-props s nil 'org-attr attr))
9263 (defun org-extract-attributes-from-string (tag)
9264 (let (key value attr)
9265 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9266 (setq key (match-string 1 tag) value (match-string 2 tag)
9267 tag (replace-match "" t t tag)
9268 attr (plist-put attr (intern key) value)))
9269 (cons tag attr)))
9271 (defun org-attributes-to-string (plist)
9272 "Format a property list into an HTML attribute list."
9273 (let ((s "") key value)
9274 (while plist
9275 (setq key (pop plist) value (pop plist))
9276 (and value
9277 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9280 ;;; Opening/following a link
9282 (defvar org-link-search-failed nil)
9284 (defvar org-open-link-functions nil
9285 "Hook for functions finding a plain text link.
9286 These functions must take a single argument, the link content.
9287 They will be called for links that look like [[link text][description]]
9288 when LINK TEXT does not have a protocol like \"http:\" and does not look
9289 like a filename (e.g. \"./blue.png\").
9291 These functions will be called *before* Org attempts to resolve the
9292 link by doing text searches in the current buffer - so if you want a
9293 link \"[[target]]\" to still find \"<<target>>\", your function should
9294 handle this as a special case.
9296 When the function does handle the link, it must return a non-nil value.
9297 If it decides that it is not responsible for this link, it must return
9298 nil to indicate that that Org-mode can continue with other options
9299 like exact and fuzzy text search.")
9301 (defun org-next-link ()
9302 "Move forward to the next link.
9303 If the link is in hidden text, expose it."
9304 (interactive)
9305 (when (and org-link-search-failed (eq this-command last-command))
9306 (goto-char (point-min))
9307 (message "Link search wrapped back to beginning of buffer"))
9308 (setq org-link-search-failed nil)
9309 (let* ((pos (point))
9310 (ct (org-context))
9311 (a (assoc :link ct)))
9312 (if a (goto-char (nth 2 a)))
9313 (if (re-search-forward org-any-link-re nil t)
9314 (progn
9315 (goto-char (match-beginning 0))
9316 (if (outline-invisible-p) (org-show-context)))
9317 (goto-char pos)
9318 (setq org-link-search-failed t)
9319 (error "No further link found"))))
9321 (defun org-previous-link ()
9322 "Move backward to the previous link.
9323 If the link is in hidden text, expose it."
9324 (interactive)
9325 (when (and org-link-search-failed (eq this-command last-command))
9326 (goto-char (point-max))
9327 (message "Link search wrapped back to end of buffer"))
9328 (setq org-link-search-failed nil)
9329 (let* ((pos (point))
9330 (ct (org-context))
9331 (a (assoc :link ct)))
9332 (if a (goto-char (nth 1 a)))
9333 (if (re-search-backward org-any-link-re nil t)
9334 (progn
9335 (goto-char (match-beginning 0))
9336 (if (outline-invisible-p) (org-show-context)))
9337 (goto-char pos)
9338 (setq org-link-search-failed t)
9339 (error "No further link found"))))
9341 (defun org-translate-link (s)
9342 "Translate a link string if a translation function has been defined."
9343 (if (and org-link-translation-function
9344 (fboundp org-link-translation-function)
9345 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9346 (progn
9347 (setq s (funcall org-link-translation-function
9348 (match-string 1) (match-string 2)))
9349 (concat (car s) ":" (cdr s)))
9352 (defun org-translate-link-from-planner (type path)
9353 "Translate a link from Emacs Planner syntax so that Org can follow it.
9354 This is still an experimental function, your mileage may vary."
9355 (cond
9356 ((member type '("http" "https" "news" "ftp"))
9357 ;; standard Internet links are the same.
9358 nil)
9359 ((and (equal type "irc") (string-match "^//" path))
9360 ;; Planner has two / at the beginning of an irc link, we have 1.
9361 ;; We should have zero, actually....
9362 (setq path (substring path 1)))
9363 ((and (equal type "lisp") (string-match "^/" path))
9364 ;; Planner has a slash, we do not.
9365 (setq type "elisp" path (substring path 1)))
9366 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9367 ;; A typical message link. Planner has the id after the final slash,
9368 ;; we separate it with a hash mark
9369 (setq path (concat (match-string 1 path) "#"
9370 (org-remove-angle-brackets (match-string 2 path)))))
9372 (cons type path))
9374 (defun org-find-file-at-mouse (ev)
9375 "Open file link or URL at mouse."
9376 (interactive "e")
9377 (mouse-set-point ev)
9378 (org-open-at-point 'in-emacs))
9380 (defun org-open-at-mouse (ev)
9381 "Open file link or URL at mouse.
9382 See the docstring of `org-open-file' for details."
9383 (interactive "e")
9384 (mouse-set-point ev)
9385 (if (eq major-mode 'org-agenda-mode)
9386 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9387 (org-open-at-point))
9389 (defvar org-window-config-before-follow-link nil
9390 "The window configuration before following a link.
9391 This is saved in case the need arises to restore it.")
9393 (defvar org-open-link-marker (make-marker)
9394 "Marker pointing to the location where `org-open-at-point; was called.")
9396 ;;;###autoload
9397 (defun org-open-at-point-global ()
9398 "Follow a link like Org-mode does.
9399 This command can be called in any mode to follow a link that has
9400 Org-mode syntax."
9401 (interactive)
9402 (org-run-like-in-org-mode 'org-open-at-point))
9404 ;;;###autoload
9405 (defun org-open-link-from-string (s &optional arg reference-buffer)
9406 "Open a link in the string S, as if it was in Org-mode."
9407 (interactive "sLink: \nP")
9408 (let ((reference-buffer (or reference-buffer (current-buffer))))
9409 (with-temp-buffer
9410 (let ((org-inhibit-startup t))
9411 (org-mode)
9412 (insert s)
9413 (goto-char (point-min))
9414 (when reference-buffer
9415 (setq org-link-abbrev-alist-local
9416 (with-current-buffer reference-buffer
9417 org-link-abbrev-alist-local)))
9418 (org-open-at-point arg reference-buffer)))))
9420 (defvar org-open-at-point-functions nil
9421 "Hook that is run when following a link at point.
9423 Functions in this hook must return t if they identify and follow
9424 a link at point. If they don't find anything interesting at point,
9425 they must return nil.")
9427 (defun org-open-at-point (&optional arg reference-buffer)
9428 "Open link at or after point.
9429 If there is no link at point, this function will search forward up to
9430 the end of the current line.
9431 Normally, files will be opened by an appropriate application. If the
9432 optional prefix argument ARG is non-nil, Emacs will visit the file.
9433 With a double prefix argument, try to open outside of Emacs, in the
9434 application the system uses for this file type."
9435 (interactive "P")
9436 ;; if in a code block, then open the block's results
9437 (unless (call-interactively #'org-babel-open-src-block-result)
9438 (org-load-modules-maybe)
9439 (move-marker org-open-link-marker (point))
9440 (setq org-window-config-before-follow-link (current-window-configuration))
9441 (org-remove-occur-highlights nil nil t)
9442 (cond
9443 ((and (org-on-heading-p)
9444 (not (org-in-regexp
9445 (concat org-plain-link-re "\\|"
9446 org-bracket-link-regexp "\\|"
9447 org-angle-link-re "\\|"
9448 "[ \t]:[^ \t\n]+:[ \t]*$")))
9449 (not (get-text-property (point) 'org-linked-text)))
9450 (or (org-offer-links-in-entry arg)
9451 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9452 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9453 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9454 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9455 (not (org-in-regexp org-bracket-link-regexp)))
9456 (org-footnote-action))
9458 (let (type path link line search (pos (point)))
9459 (catch 'match
9460 (save-excursion
9461 (skip-chars-forward "^]\n\r")
9462 (when (org-in-regexp org-bracket-link-regexp 1)
9463 (setq link (org-extract-attributes
9464 (org-link-unescape (org-match-string-no-properties 1))))
9465 (while (string-match " *\n *" link)
9466 (setq link (replace-match " " t t link)))
9467 (setq link (org-link-expand-abbrev link))
9468 (cond
9469 ((or (file-name-absolute-p link)
9470 (string-match "^\\.\\.?/" link))
9471 (setq type "file" path link))
9472 ((string-match org-link-re-with-space3 link)
9473 (setq type (match-string 1 link) path (match-string 2 link)))
9474 (t (setq type "thisfile" path link)))
9475 (throw 'match t)))
9477 (when (get-text-property (point) 'org-linked-text)
9478 (setq type "thisfile"
9479 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9480 (1+ (point)) (point))
9481 path (buffer-substring
9482 (or (previous-single-property-change pos 'org-linked-text)
9483 (point-min))
9484 (or (next-single-property-change pos 'org-linked-text)
9485 (point-max))))
9486 (throw 'match t))
9488 (save-excursion
9489 (when (or (org-in-regexp org-angle-link-re)
9490 (org-in-regexp org-plain-link-re))
9491 (setq type (match-string 1)
9492 path (org-link-unescape (match-string 2)))
9493 (throw 'match t)))
9494 (save-excursion
9495 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9496 (setq type "tags"
9497 path (match-string 1))
9498 (while (string-match ":" path)
9499 (setq path (replace-match "+" t t path)))
9500 (throw 'match t)))
9501 (when (org-in-regexp "<\\([^><\n]+\\)>")
9502 (setq type "tree-match"
9503 path (match-string 1))
9504 (throw 'match t)))
9505 (unless path
9506 (error "No link found"))
9508 ;; switch back to reference buffer
9509 ;; needed when if called in a temporary buffer through
9510 ;; org-open-link-from-string
9511 (with-current-buffer (or reference-buffer (current-buffer))
9513 ;; Remove any trailing spaces in path
9514 (if (string-match " +\\'" path)
9515 (setq path (replace-match "" t t path)))
9516 (if (and org-link-translation-function
9517 (fboundp org-link-translation-function))
9518 ;; Check if we need to translate the link
9519 (let ((tmp (funcall org-link-translation-function type path)))
9520 (setq type (car tmp) path (cdr tmp))))
9522 (cond
9524 ((assoc type org-link-protocols)
9525 (funcall (nth 1 (assoc type org-link-protocols)) path))
9527 ((equal type "mailto")
9528 (let ((cmd (car org-link-mailto-program))
9529 (args (cdr org-link-mailto-program)) args1
9530 (address path) (subject "") a)
9531 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9532 (setq address (match-string 1 path)
9533 subject (org-link-escape (match-string 2 path))))
9534 (while args
9535 (cond
9536 ((not (stringp (car args))) (push (pop args) args1))
9537 (t (setq a (pop args))
9538 (if (string-match "%a" a)
9539 (setq a (replace-match address t t a)))
9540 (if (string-match "%s" a)
9541 (setq a (replace-match subject t t a)))
9542 (push a args1))))
9543 (apply cmd (nreverse args1))))
9545 ((member type '("http" "https" "ftp" "news"))
9546 (browse-url (concat type ":" (org-link-escape
9547 path org-link-escape-chars-browser))))
9549 ((string= type "doi")
9550 (browse-url (concat "http://dx.doi.org/"
9551 (org-link-escape
9552 path org-link-escape-chars-browser))))
9554 ((member type '("message"))
9555 (browse-url (concat type ":" path)))
9557 ((string= type "tags")
9558 (org-tags-view arg path))
9560 ((string= type "tree-match")
9561 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9563 ((string= type "file")
9564 (if (string-match "::\\([0-9]+\\)\\'" path)
9565 (setq line (string-to-number (match-string 1 path))
9566 path (substring path 0 (match-beginning 0)))
9567 (if (string-match "::\\(.+\\)\\'" path)
9568 (setq search (match-string 1 path)
9569 path (substring path 0 (match-beginning 0)))))
9570 (if (string-match "[*?{]" (file-name-nondirectory path))
9571 (dired path)
9572 (org-open-file path arg line search)))
9574 ((string= type "shell")
9575 (let ((cmd path))
9576 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9577 (string-match org-confirm-shell-link-not-regexp cmd))
9578 (not org-confirm-shell-link-function)
9579 (funcall org-confirm-shell-link-function
9580 (format "Execute \"%s\" in shell? "
9581 (org-add-props cmd nil
9582 'face 'org-warning))))
9583 (progn
9584 (message "Executing %s" cmd)
9585 (shell-command cmd))
9586 (error "Abort"))))
9588 ((string= type "elisp")
9589 (let ((cmd path))
9590 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9591 (string-match org-confirm-elisp-link-not-regexp cmd))
9592 (not org-confirm-elisp-link-function)
9593 (funcall org-confirm-elisp-link-function
9594 (format "Execute \"%s\" as elisp? "
9595 (org-add-props cmd nil
9596 'face 'org-warning))))
9597 (message "%s => %s" cmd
9598 (if (equal (string-to-char cmd) ?\()
9599 (eval (read cmd))
9600 (call-interactively (read cmd))))
9601 (error "Abort"))))
9603 ((and (string= type "thisfile")
9604 (run-hook-with-args-until-success
9605 'org-open-link-functions path)))
9607 ((string= type "thisfile")
9608 (if arg
9609 (switch-to-buffer-other-window
9610 (org-get-buffer-for-internal-link (current-buffer)))
9611 (org-mark-ring-push))
9612 (let ((cmd `(org-link-search
9613 ,path
9614 ,(cond ((equal arg '(4)) ''occur)
9615 ((equal arg '(16)) ''org-occur)
9616 (t nil))
9617 ,pos)))
9618 (condition-case nil (let ((org-link-search-inhibit-query t))
9619 (eval cmd))
9620 (error (progn (widen) (eval cmd))))))
9623 (browse-url-at-point)))))))
9624 (move-marker org-open-link-marker nil)
9625 (run-hook-with-args 'org-follow-link-hook)))
9627 (defun org-offer-links-in-entry (&optional nth zero)
9628 "Offer links in the current entry and follow the selected link.
9629 If there is only one link, follow it immediately as well.
9630 If NTH is an integer, immediately pick the NTH link found.
9631 If ZERO is a string, check also this string for a link, and if
9632 there is one, offer it as link number zero."
9633 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9634 "\\(" org-angle-link-re "\\)\\|"
9635 "\\(" org-plain-link-re "\\)"))
9636 (cnt ?0)
9637 (in-emacs (if (integerp nth) nil nth))
9638 have-zero end links link c)
9639 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9640 (push (match-string 0 zero) links)
9641 (setq cnt (1- cnt) have-zero t))
9642 (save-excursion
9643 (org-back-to-heading t)
9644 (setq end (save-excursion (outline-next-heading) (point)))
9645 (while (re-search-forward re end t)
9646 (push (match-string 0) links))
9647 (setq links (org-uniquify (reverse links))))
9649 (cond
9650 ((null links)
9651 (message "No links"))
9652 ((equal (length links) 1)
9653 (setq link (list (car links))))
9654 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9655 (setq link (nth (if have-zero nth (1- nth)) links)))
9656 (t ; we have to select a link
9657 (save-excursion
9658 (save-window-excursion
9659 (delete-other-windows)
9660 (with-output-to-temp-buffer "*Select Link*"
9661 (mapc (lambda (l)
9662 (if (not (string-match org-bracket-link-regexp l))
9663 (princ (format "[%c] %s\n" (incf cnt)
9664 (org-remove-angle-brackets l)))
9665 (if (match-end 3)
9666 (princ (format "[%c] %s (%s)\n" (incf cnt)
9667 (match-string 3 l) (match-string 1 l)))
9668 (princ (format "[%c] %s\n" (incf cnt)
9669 (match-string 1 l))))))
9670 links))
9671 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9672 (message "Select link to open, RET to open all:")
9673 (setq c (read-char-exclusive))
9674 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9675 (when (equal c ?q) (error "Abort"))
9676 (if (equal c ?\C-m)
9677 (setq link links)
9678 (setq nth (- c ?0))
9679 (if have-zero (setq nth (1+ nth)))
9680 (unless (and (integerp nth) (>= (length links) nth))
9681 (error "Invalid link selection"))
9682 (setq link (list (nth (1- nth) links))))))
9683 (if link
9684 (let ((buf (current-buffer)))
9685 (dolist (l link)
9686 (org-open-link-from-string l in-emacs buf))
9688 nil)))
9690 ;; Add special file links that specify the way of opening
9692 (org-add-link-type "file+sys" 'org-open-file-with-system)
9693 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9694 (defun org-open-file-with-system (path)
9695 "Open file at PATH using the system way of opening it."
9696 (org-open-file path 'system))
9697 (defun org-open-file-with-emacs (path)
9698 "Open file at PATH in Emacs."
9699 (org-open-file path 'emacs))
9700 (defun org-remove-file-link-modifiers ()
9701 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9702 (goto-char (point-min))
9703 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9704 (org-if-unprotected
9705 (replace-match "file:" t t))))
9706 (eval-after-load "org-exp"
9707 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9708 'org-remove-file-link-modifiers))
9710 ;;;; Time estimates
9712 (defun org-get-effort (&optional pom)
9713 "Get the effort estimate for the current entry."
9714 (org-entry-get pom org-effort-property))
9716 ;;; File search
9718 (defvar org-create-file-search-functions nil
9719 "List of functions to construct the right search string for a file link.
9720 These functions are called in turn with point at the location to
9721 which the link should point.
9723 A function in the hook should first test if it would like to
9724 handle this file type, for example by checking the `major-mode'
9725 or the file extension. If it decides not to handle this file, it
9726 should just return nil to give other functions a chance. If it
9727 does handle the file, it must return the search string to be used
9728 when following the link. The search string will be part of the
9729 file link, given after a double colon, and `org-open-at-point'
9730 will automatically search for it. If special measures must be
9731 taken to make the search successful, another function should be
9732 added to the companion hook `org-execute-file-search-functions',
9733 which see.
9735 A function in this hook may also use `setq' to set the variable
9736 `description' to provide a suggestion for the descriptive text to
9737 be used for this link when it gets inserted into an Org-mode
9738 buffer with \\[org-insert-link].")
9740 (defvar org-execute-file-search-functions nil
9741 "List of functions to execute a file search triggered by a link.
9743 Functions added to this hook must accept a single argument, the
9744 search string that was part of the file link, the part after the
9745 double colon. The function must first check if it would like to
9746 handle this search, for example by checking the `major-mode' or
9747 the file extension. If it decides not to handle this search, it
9748 should just return nil to give other functions a chance. If it
9749 does handle the search, it must return a non-nil value to keep
9750 other functions from trying.
9752 Each function can access the current prefix argument through the
9753 variable `current-prefix-argument'. Note that a single prefix is
9754 used to force opening a link in Emacs, so it may be good to only
9755 use a numeric or double prefix to guide the search function.
9757 In case this is needed, a function in this hook can also restore
9758 the window configuration before `org-open-at-point' was called using:
9760 (set-window-configuration org-window-config-before-follow-link)")
9762 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9763 (defun org-link-search (s &optional type avoid-pos stealth)
9764 "Search for a link search option.
9765 If S is surrounded by forward slashes, it is interpreted as a
9766 regular expression. In org-mode files, this will create an `org-occur'
9767 sparse tree. In ordinary files, `occur' will be used to list matches.
9768 If the current buffer is in `dired-mode', grep will be used to search
9769 in all files. If AVOID-POS is given, ignore matches near that position.
9771 When optional argument STEALTH is non-nil, do not modify
9772 visibility around point, thus ignoring
9773 `org-show-hierarchy-above', `org-show-following-heading' and
9774 `org-show-siblings' variables."
9775 (let ((case-fold-search t)
9776 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9777 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9778 (append '(("") (" ") ("\t") ("\n"))
9779 org-emphasis-alist)
9780 "\\|") "\\)"))
9781 (pos (point))
9782 (pre nil) (post nil)
9783 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9784 (cond
9785 ;; First check if there are any special search functions
9786 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9787 ;; Now try the builtin stuff
9788 ((and (equal (string-to-char s0) ?#)
9789 (> (length s0) 1)
9790 (save-excursion
9791 (goto-char (point-min))
9792 (and
9793 (re-search-forward
9794 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9795 (setq type 'dedicated
9796 pos (match-beginning 0))))
9797 ;; There is an exact target for this
9798 (goto-char pos)
9799 (org-back-to-heading t)))
9800 ((save-excursion
9801 (goto-char (point-min))
9802 (and
9803 (re-search-forward
9804 (concat "<<" (regexp-quote s0) ">>") nil t)
9805 (setq type 'dedicated
9806 pos (match-beginning 0))))
9807 ;; There is an exact target for this
9808 (goto-char pos))
9809 ((and (string-match "^(\\(.*\\))$" s0)
9810 (save-excursion
9811 (goto-char (point-min))
9812 (and
9813 (re-search-forward
9814 (concat "[^[]" (regexp-quote
9815 (format org-coderef-label-format
9816 (match-string 1 s0))))
9817 nil t)
9818 (setq type 'dedicated
9819 pos (1+ (match-beginning 0))))))
9820 ;; There is a coderef target for this
9821 (goto-char pos))
9822 ((string-match "^/\\(.*\\)/$" s)
9823 ;; A regular expression
9824 (cond
9825 ((eq major-mode 'org-mode)
9826 (org-occur (match-string 1 s)))
9827 ;;((eq major-mode 'dired-mode)
9828 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9829 (t (org-do-occur (match-string 1 s)))))
9830 ((and (eq major-mode 'org-mode) org-link-search-must-match-exact-headline)
9831 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
9832 (goto-char (point-min))
9833 (cond
9834 ((let (case-fold-search)
9835 (re-search-forward (format org-complex-heading-regexp-format
9836 (regexp-quote s))
9837 nil t))
9838 ;; OK, found a match
9839 (setq type 'dedicated)
9840 (goto-char (match-beginning 0)))
9841 ((and (not org-link-search-inhibit-query)
9842 (eq org-link-search-must-match-exact-headline 'query-to-create)
9843 (y-or-n-p "No match - create this as a new heading? "))
9844 (goto-char (point-max))
9845 (or (bolp) (newline))
9846 (insert "* " s "\n")
9847 (beginning-of-line 0))
9849 (goto-char pos)
9850 (error "No match"))))
9852 ;; A normal search string
9853 (when (equal (string-to-char s) ?*)
9854 ;; Anchor on headlines, post may include tags.
9855 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
9856 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
9857 s (substring s 1)))
9858 (remove-text-properties
9859 0 (length s)
9860 '(face nil mouse-face nil keymap nil fontified nil) s)
9861 ;; Make a series of regular expressions to find a match
9862 (setq words (org-split-string s "[ \n\r\t]+")
9864 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9865 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
9866 "\\)" markers)
9867 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9868 re2a (concat "[ \t\r\n]" re2a_)
9869 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9870 re4 (concat "[^a-zA-Z_]" re4_)
9872 re1 (concat pre re2 post)
9873 re3 (concat pre (if pre re4_ re4) post)
9874 re5 (concat pre ".*" re4)
9875 re2 (concat pre re2)
9876 re2a (concat pre (if pre re2a_ re2a))
9877 re4 (concat pre (if pre re4_ re4))
9878 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9879 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9880 re5 "\\)"
9882 (cond
9883 ((eq type 'org-occur) (org-occur reall))
9884 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9885 (t (goto-char (point-min))
9886 (setq type 'fuzzy)
9887 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
9888 (org-search-not-self 1 re1 nil t)
9889 (org-search-not-self 1 re2 nil t)
9890 (org-search-not-self 1 re2a nil t)
9891 (org-search-not-self 1 re3 nil t)
9892 (org-search-not-self 1 re4 nil t)
9893 (org-search-not-self 1 re5 nil t)
9895 (goto-char (match-beginning 1))
9896 (goto-char pos)
9897 (error "No match"))))))
9898 (and (eq major-mode 'org-mode)
9899 (not stealth)
9900 (org-show-context 'link-search))
9901 type))
9903 (defun org-search-not-self (group &rest args)
9904 "Execute `re-search-forward', but only accept matches that do not
9905 enclose the position of `org-open-link-marker'."
9906 (let ((m org-open-link-marker))
9907 (catch 'exit
9908 (while (apply 're-search-forward args)
9909 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
9910 (goto-char (match-end group))
9911 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
9912 (> (match-beginning 0) (marker-position m))
9913 (< (match-end 0) (marker-position m)))
9914 (save-match-data
9915 (or (not (org-in-regexp
9916 org-bracket-link-analytic-regexp 1))
9917 (not (match-end 4)) ; no description
9918 (and (<= (match-beginning 4) (point))
9919 (>= (match-end 4) (point))))))
9920 (throw 'exit (point))))))))
9922 (defun org-get-buffer-for-internal-link (buffer)
9923 "Return a buffer to be used for displaying the link target of internal links."
9924 (cond
9925 ((not org-display-internal-link-with-indirect-buffer)
9926 buffer)
9927 ((string-match "(Clone)$" (buffer-name buffer))
9928 (message "Buffer is already a clone, not making another one")
9929 ;; we also do not modify visibility in this case
9930 buffer)
9931 (t ; make a new indirect buffer for displaying the link
9932 (let* ((bn (buffer-name buffer))
9933 (ibn (concat bn "(Clone)"))
9934 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
9935 (with-current-buffer ib (org-overview))
9936 ib))))
9938 (defun org-do-occur (regexp &optional cleanup)
9939 "Call the Emacs command `occur'.
9940 If CLEANUP is non-nil, remove the printout of the regular expression
9941 in the *Occur* buffer. This is useful if the regex is long and not useful
9942 to read."
9943 (occur regexp)
9944 (when cleanup
9945 (let ((cwin (selected-window)) win beg end)
9946 (when (setq win (get-buffer-window "*Occur*"))
9947 (select-window win))
9948 (goto-char (point-min))
9949 (when (re-search-forward "match[a-z]+" nil t)
9950 (setq beg (match-end 0))
9951 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9952 (setq end (1- (match-beginning 0)))))
9953 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
9954 (goto-char (point-min))
9955 (select-window cwin))))
9957 ;;; The mark ring for links jumps
9959 (defvar org-mark-ring nil
9960 "Mark ring for positions before jumps in Org-mode.")
9961 (defvar org-mark-ring-last-goto nil
9962 "Last position in the mark ring used to go back.")
9963 ;; Fill and close the ring
9964 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9965 (loop for i from 1 to org-mark-ring-length do
9966 (push (make-marker) org-mark-ring))
9967 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
9968 org-mark-ring)
9970 (defun org-mark-ring-push (&optional pos buffer)
9971 "Put the current position or POS into the mark ring and rotate it."
9972 (interactive)
9973 (setq pos (or pos (point)))
9974 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
9975 (move-marker (car org-mark-ring)
9976 (or pos (point))
9977 (or buffer (current-buffer)))
9978 (message "%s"
9979 (substitute-command-keys
9980 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
9982 (defun org-mark-ring-goto (&optional n)
9983 "Jump to the previous position in the mark ring.
9984 With prefix arg N, jump back that many stored positions. When
9985 called several times in succession, walk through the entire ring.
9986 Org-mode commands jumping to a different position in the current file,
9987 or to another Org-mode file, automatically push the old position
9988 onto the ring."
9989 (interactive "p")
9990 (let (p m)
9991 (if (eq last-command this-command)
9992 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
9993 (setq p org-mark-ring))
9994 (setq org-mark-ring-last-goto p)
9995 (setq m (car p))
9996 (org-pop-to-buffer-same-window (marker-buffer m))
9997 (goto-char m)
9998 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10000 (defun org-remove-angle-brackets (s)
10001 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10002 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10004 (defun org-add-angle-brackets (s)
10005 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10006 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10008 (defun org-remove-double-quotes (s)
10009 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10010 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10013 ;;; Following specific links
10015 (defun org-follow-timestamp-link ()
10016 (cond
10017 ((org-at-date-range-p t)
10018 (let ((org-agenda-start-on-weekday)
10019 (t1 (match-string 1))
10020 (t2 (match-string 2)))
10021 (setq t1 (time-to-days (org-time-string-to-time t1))
10022 t2 (time-to-days (org-time-string-to-time t2)))
10023 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10024 ((org-at-timestamp-p t)
10025 (org-agenda-list nil (time-to-days (org-time-string-to-time
10026 (substring (match-string 1) 0 10)))
10028 (t (error "This should not happen"))))
10031 ;;; Following file links
10032 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10033 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10034 (declare-function mailcap-mime-info
10035 "mailcap" (string &optional request no-decode))
10036 (defvar org-wait nil)
10037 (defun org-open-file (path &optional in-emacs line search)
10038 "Open the file at PATH.
10039 First, this expands any special file name abbreviations. Then the
10040 configuration variable `org-file-apps' is checked if it contains an
10041 entry for this file type, and if yes, the corresponding command is launched.
10043 If no application is found, Emacs simply visits the file.
10045 With optional prefix argument IN-EMACS, Emacs will visit the file.
10046 With a double \\[universal-argument] \\[universal-argument] \
10047 prefix arg, Org tries to avoid opening in Emacs
10048 and to use an external application to visit the file.
10050 Optional LINE specifies a line to go to, optional SEARCH a string
10051 to search for. If LINE or SEARCH is given, the file will be
10052 opened in Emacs, unless an entry from org-file-apps that makes
10053 use of groups in a regexp matches.
10055 If you want to change the way frames are used when following a
10056 link, please customize `org-link-frame-setup'.
10058 If the file does not exist, an error is thrown."
10059 (let* ((file (if (equal path "")
10060 buffer-file-name
10061 (substitute-in-file-name (expand-file-name path))))
10062 (file-apps (append org-file-apps (org-default-apps)))
10063 (apps (org-remove-if
10064 'org-file-apps-entry-match-against-dlink-p file-apps))
10065 (apps-dlink (org-remove-if-not
10066 'org-file-apps-entry-match-against-dlink-p file-apps))
10067 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10068 (dirp (if remp nil (file-directory-p file)))
10069 (file (if (and dirp org-open-directory-means-index-dot-org)
10070 (concat (file-name-as-directory file) "index.org")
10071 file))
10072 (a-m-a-p (assq 'auto-mode apps))
10073 (dfile (downcase file))
10074 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10075 (link (cond ((and (eq line nil)
10076 (eq search nil))
10077 file)
10078 (line
10079 (concat file "::" (number-to-string line)))
10080 (search
10081 (concat file "::" search))))
10082 (dlink (downcase link))
10083 (old-buffer (current-buffer))
10084 (old-pos (point))
10085 (old-mode major-mode)
10086 ext cmd link-match-data)
10087 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10088 (setq ext (match-string 1 dfile))
10089 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10090 (setq ext (match-string 1 dfile))))
10091 (cond
10092 ((member in-emacs '((16) system))
10093 (setq cmd (cdr (assoc 'system apps))))
10094 (in-emacs (setq cmd 'emacs))
10096 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10097 (and dirp (cdr (assoc 'directory apps)))
10098 ; first, try matching against apps-dlink
10099 ; if we get a match here, store the match data for later
10100 (let ((match (assoc-default dlink apps-dlink
10101 'string-match)))
10102 (if match
10103 (progn (setq link-match-data (match-data))
10104 match)
10105 (progn (setq in-emacs (or in-emacs line search))
10106 nil))) ; if we have no match in apps-dlink,
10107 ; always open the file in emacs if line or search
10108 ; is given (for backwards compatibility)
10109 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10110 'string-match)
10111 (cdr (assoc ext apps))
10112 (cdr (assoc t apps))))))
10113 (when (eq cmd 'system)
10114 (setq cmd (cdr (assoc 'system apps))))
10115 (when (eq cmd 'default)
10116 (setq cmd (cdr (assoc t apps))))
10117 (when (eq cmd 'mailcap)
10118 (require 'mailcap)
10119 (mailcap-parse-mailcaps)
10120 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10121 (command (mailcap-mime-info mime-type)))
10122 (if (stringp command)
10123 (setq cmd command)
10124 (setq cmd 'emacs))))
10125 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10126 (not (file-exists-p file))
10127 (not org-open-non-existing-files))
10128 (error "No such file: %s" file))
10129 (cond
10130 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10131 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10132 (while (string-match "['\"]%s['\"]" cmd)
10133 (setq cmd (replace-match "%s" t t cmd)))
10134 (while (string-match "%s" cmd)
10135 (setq cmd (replace-match
10136 (save-match-data
10137 (shell-quote-argument
10138 (convert-standard-filename file)))
10139 t t cmd)))
10141 ;; Replace "%1", "%2" etc. in command with group matches from regex
10142 (save-match-data
10143 (let ((match-index 1)
10144 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10145 (set-match-data link-match-data)
10146 (while (<= match-index number-of-groups)
10147 (let ((regex (concat "%" (number-to-string match-index)))
10148 (replace-with (match-string match-index dlink)))
10149 (while (string-match regex cmd)
10150 (setq cmd (replace-match replace-with t t cmd))))
10151 (setq match-index (+ match-index 1)))))
10153 (save-window-excursion
10154 (start-process-shell-command cmd nil cmd)
10155 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10157 ((or (stringp cmd)
10158 (eq cmd 'emacs))
10159 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10160 (widen)
10161 (if line (org-goto-line line)
10162 (if search (org-link-search search))))
10163 ((consp cmd)
10164 (let ((file (convert-standard-filename file)))
10165 (save-match-data
10166 (set-match-data link-match-data)
10167 (eval cmd))))
10168 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10169 (and (eq major-mode 'org-mode) (eq old-mode 'org-mode)
10170 (or (not (equal old-buffer (current-buffer)))
10171 (not (equal old-pos (point))))
10172 (org-mark-ring-push old-pos old-buffer))))
10174 (defun org-file-apps-entry-match-against-dlink-p (entry)
10175 "This function returns non-nil if `entry' uses a regular
10176 expression which should be matched against the whole link by
10177 org-open-file.
10179 It assumes that is the case when the entry uses a regular
10180 expression which has at least one grouping construct and the
10181 action is either a lisp form or a command string containing
10182 '%1', i.e. using at least one subexpression match as a
10183 parameter."
10184 (let ((selector (car entry))
10185 (action (cdr entry)))
10186 (if (stringp selector)
10187 (and (> (regexp-opt-depth selector) 0)
10188 (or (and (stringp action)
10189 (string-match "%[0-9]" action))
10190 (consp action)))
10191 nil)))
10193 (defun org-default-apps ()
10194 "Return the default applications for this operating system."
10195 (cond
10196 ((eq system-type 'darwin)
10197 org-file-apps-defaults-macosx)
10198 ((eq system-type 'windows-nt)
10199 org-file-apps-defaults-windowsnt)
10200 (t org-file-apps-defaults-gnu)))
10202 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10203 "Convert extensions to regular expressions in the cars of LIST.
10204 Also, weed out any non-string entries, because the return value is used
10205 only for regexp matching.
10206 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10207 point to the symbol `emacs', indicating that the file should
10208 be opened in Emacs."
10209 (append
10210 (delq nil
10211 (mapcar (lambda (x)
10212 (if (not (stringp (car x)))
10214 (if (string-match "\\W" (car x))
10216 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10217 list))
10218 (if add-auto-mode
10219 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10221 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10222 (defun org-file-remote-p (file)
10223 "Test whether FILE specifies a location on a remote system.
10224 Return non-nil if the location is indeed remote.
10226 For example, the filename \"/user@host:/foo\" specifies a location
10227 on the system \"/user@host:\"."
10228 (cond ((fboundp 'file-remote-p)
10229 (file-remote-p file))
10230 ((fboundp 'tramp-handle-file-remote-p)
10231 (tramp-handle-file-remote-p file))
10232 ((and (boundp 'ange-ftp-name-format)
10233 (string-match (car ange-ftp-name-format) file))
10235 (t nil)))
10238 ;;;; Refiling
10240 (defun org-get-org-file ()
10241 "Read a filename, with default directory `org-directory'."
10242 (let ((default (or org-default-notes-file remember-data-file)))
10243 (read-file-name (format "File name [%s]: " default)
10244 (file-name-as-directory org-directory)
10245 default)))
10247 (defun org-notes-order-reversed-p ()
10248 "Check if the current file should receive notes in reversed order."
10249 (cond
10250 ((not org-reverse-note-order) nil)
10251 ((eq t org-reverse-note-order) t)
10252 ((not (listp org-reverse-note-order)) nil)
10253 (t (catch 'exit
10254 (let ((all org-reverse-note-order)
10255 entry)
10256 (while (setq entry (pop all))
10257 (if (string-match (car entry) buffer-file-name)
10258 (throw 'exit (cdr entry))))
10259 nil)))))
10261 (defvar org-refile-target-table nil
10262 "The list of refile targets, created by `org-refile'.")
10264 (defvar org-agenda-new-buffers nil
10265 "Buffers created to visit agenda files.")
10267 (defvar org-refile-cache nil
10268 "Cache for refile targets.")
10270 (defvar org-refile-markers nil
10271 "All the markers used for caching refile locations.")
10273 (defun org-refile-marker (pos)
10274 "Get a new refile marker, but only if caching is in use."
10275 (if (not org-refile-use-cache)
10277 (let ((m (make-marker)))
10278 (move-marker m pos)
10279 (push m org-refile-markers)
10280 m)))
10282 (defun org-refile-cache-clear ()
10283 "Clear the refile cache and disable all the markers."
10284 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10285 (setq org-refile-markers nil)
10286 (setq org-refile-cache nil)
10287 (message "Refile cache has been cleared"))
10289 (defun org-refile-cache-check-set (set)
10290 "Check if all the markers in the cache still have live buffers."
10291 (let (marker)
10292 (catch 'exit
10293 (while (and set (setq marker (nth 3 (pop set))))
10294 ;; if org-refile-use-outline-path is 'file, marker may be nil
10295 (when (and marker (null (marker-buffer marker)))
10296 (message "not found") (sit-for 3)
10297 (throw 'exit nil)))
10298 t)))
10300 (defun org-refile-cache-put (set &rest identifiers)
10301 "Push the refile targets SET into the cache, under IDENTIFIERS."
10302 (let* ((key (sha1 (prin1-to-string identifiers)))
10303 (entry (assoc key org-refile-cache)))
10304 (if entry
10305 (setcdr entry set)
10306 (push (cons key set) org-refile-cache))))
10308 (defun org-refile-cache-get (&rest identifiers)
10309 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10310 (cond
10311 ((not org-refile-cache) nil)
10312 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10314 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10315 org-refile-cache))))
10316 (and set (org-refile-cache-check-set set) set)))))
10318 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10319 "Produce a table with refile targets."
10320 (let ((case-fold-search nil)
10321 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10322 (entries (or org-refile-targets '((nil . (:level . 1)))))
10323 targets tgs txt re files f desc descre fast-path-p level pos0)
10324 (message "Getting targets...")
10325 (with-current-buffer (or default-buffer (current-buffer))
10326 (while (setq entry (pop entries))
10327 (setq files (car entry) desc (cdr entry))
10328 (setq fast-path-p nil)
10329 (cond
10330 ((null files) (setq files (list (current-buffer))))
10331 ((eq files 'org-agenda-files)
10332 (setq files (org-agenda-files 'unrestricted)))
10333 ((and (symbolp files) (fboundp files))
10334 (setq files (funcall files)))
10335 ((and (symbolp files) (boundp files))
10336 (setq files (symbol-value files))))
10337 (if (stringp files) (setq files (list files)))
10338 (cond
10339 ((eq (car desc) :tag)
10340 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10341 ((eq (car desc) :todo)
10342 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10343 ((eq (car desc) :regexp)
10344 (setq descre (cdr desc)))
10345 ((eq (car desc) :level)
10346 (setq descre (concat "^\\*\\{" (number-to-string
10347 (if org-odd-levels-only
10348 (1- (* 2 (cdr desc)))
10349 (cdr desc)))
10350 "\\}[ \t]")))
10351 ((eq (car desc) :maxlevel)
10352 (setq fast-path-p t)
10353 (setq descre (concat "^\\*\\{1," (number-to-string
10354 (if org-odd-levels-only
10355 (1- (* 2 (cdr desc)))
10356 (cdr desc)))
10357 "\\}[ \t]")))
10358 (t (error "Bad refiling target description %s" desc)))
10359 (while (setq f (pop files))
10360 (with-current-buffer
10361 (if (bufferp f) f (org-get-agenda-file-buffer f))
10363 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10364 (progn
10365 (if (bufferp f) (setq f (buffer-file-name
10366 (buffer-base-buffer f))))
10367 (setq f (and f (expand-file-name f)))
10368 (if (eq org-refile-use-outline-path 'file)
10369 (push (list (file-name-nondirectory f) f nil nil) tgs))
10370 (save-excursion
10371 (save-restriction
10372 (widen)
10373 (goto-char (point-min))
10374 (while (re-search-forward descre nil t)
10375 (goto-char (setq pos0 (point-at-bol)))
10376 (catch 'next
10377 (when org-refile-target-verify-function
10378 (save-match-data
10379 (or (funcall org-refile-target-verify-function)
10380 (throw 'next t))))
10381 (when (and (looking-at org-complex-heading-regexp)
10382 (not (member (match-string 4) excluded-entries)))
10383 (setq level (org-reduced-level
10384 (- (match-end 1) (match-beginning 1)))
10385 txt (org-link-display-format (match-string 4))
10386 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10387 re (format org-complex-heading-regexp-format
10388 (regexp-quote (match-string 4))))
10389 (when org-refile-use-outline-path
10390 (setq txt (mapconcat
10391 'org-protect-slash
10392 (append
10393 (if (eq org-refile-use-outline-path
10394 'file)
10395 (list (file-name-nondirectory
10396 (buffer-file-name
10397 (buffer-base-buffer))))
10398 (if (eq org-refile-use-outline-path
10399 'full-file-path)
10400 (list (buffer-file-name
10401 (buffer-base-buffer)))))
10402 (org-get-outline-path fast-path-p
10403 level txt)
10404 (list txt))
10405 "/")))
10406 (push (list txt f re (org-refile-marker (point)))
10407 tgs)))
10408 (when (= (point) pos0)
10409 ;; verification function has not moved point
10410 (goto-char (point-at-eol))))))))
10411 (when org-refile-use-cache
10412 (org-refile-cache-put tgs (buffer-file-name) descre))
10413 (setq targets (append tgs targets))
10414 ))))
10415 (message "Getting targets...done")
10416 (nreverse targets)))
10418 (defun org-protect-slash (s)
10419 (while (string-match "/" s)
10420 (setq s (replace-match "\\" t t s)))
10423 (defvar org-olpa (make-vector 20 nil))
10425 (defun org-get-outline-path (&optional fastp level heading)
10426 "Return the outline path to the current entry, as a list.
10428 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10429 routine which makes outline path derivations for an entire file,
10430 avoiding backtracing. Refile target collection makes use of that."
10431 (if fastp
10432 (progn
10433 (if (> level 19)
10434 (error "Outline path failure, more than 19 levels"))
10435 (loop for i from level upto 19 do
10436 (aset org-olpa i nil))
10437 (prog1
10438 (delq nil (append org-olpa nil))
10439 (aset org-olpa level heading)))
10440 (let (rtn case-fold-search)
10441 (save-excursion
10442 (save-restriction
10443 (widen)
10444 (while (org-up-heading-safe)
10445 (when (looking-at org-complex-heading-regexp)
10446 (push (org-match-string-no-properties 4) rtn)))
10447 rtn)))))
10449 (defun org-format-outline-path (path &optional width prefix)
10450 "Format the outline path PATH for display.
10451 Width is the maximum number of characters that is available.
10452 Prefix is a prefix to be included in the returned string,
10453 such as the file name."
10454 (setq width (or width 79))
10455 (if prefix (setq width (- width (length prefix))))
10456 (if (not path)
10457 (or prefix "")
10458 (let* ((nsteps (length path))
10459 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10460 (maxwidth (if (<= total-width width)
10461 10000 ;; everything fits
10462 ;; we need to shorten the level headings
10463 (/ (- width nsteps) nsteps)))
10464 (org-odd-levels-only nil)
10465 (n 0)
10466 (total (1+ (length prefix))))
10467 (setq maxwidth (max maxwidth 10))
10468 (concat prefix
10469 (mapconcat
10470 (lambda (h)
10471 (setq n (1+ n))
10472 (if (and (= n nsteps) (< maxwidth 10000))
10473 (setq maxwidth (- total-width total)))
10474 (if (< (length h) maxwidth)
10475 (progn (setq total (+ total (length h) 1)) h)
10476 (setq h (substring h 0 (- maxwidth 2))
10477 total (+ total maxwidth 1))
10478 (if (string-match "[ \t]+\\'" h)
10479 (setq h (substring h 0 (match-beginning 0))))
10480 (setq h (concat h "..")))
10481 (org-add-props h nil 'face
10482 (nth (% (1- n) org-n-level-faces)
10483 org-level-faces))
10485 path "/")))))
10487 (defun org-display-outline-path (&optional file current)
10488 "Display the current outline path in the echo area."
10489 (interactive "P")
10490 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10491 (case-fold-search nil)
10492 (path (and (eq major-mode 'org-mode) (org-get-outline-path))))
10493 (if current (setq path (append path
10494 (save-excursion
10495 (org-back-to-heading t)
10496 (if (looking-at org-complex-heading-regexp)
10497 (list (match-string 4)))))))
10498 (message "%s"
10499 (org-format-outline-path
10500 path
10501 (1- (frame-width))
10502 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10504 (defvar org-refile-history nil
10505 "History for refiling operations.")
10507 (defvar org-after-refile-insert-hook nil
10508 "Hook run after `org-refile' has inserted its stuff at the new location.
10509 Note that this is still *before* the stuff will be removed from
10510 the *old* location.")
10512 (defvar org-capture-last-stored-marker)
10513 (defun org-refile (&optional goto default-buffer rfloc)
10514 "Move the entry or entries at point to another heading.
10515 The list of target headings is compiled using the information in
10516 `org-refile-targets', which see.
10518 At the target location, the entry is filed as a subitem of the target
10519 heading. Depending on `org-reverse-note-order', the new subitem will
10520 either be the first or the last subitem.
10522 If there is an active region, all entries in that region will be moved.
10523 However, the region must fulfill the requirement that the first heading
10524 is the first one sets the top-level of the moved text - at most siblings
10525 below it are allowed.
10527 With prefix arg GOTO, the command will only visit the target location
10528 and not actually move anything.
10530 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10531 go to the location where the last refiling operation has put the subtree.
10532 With a prefix argument of `2', refile to the running clock.
10534 RFLOC can be a refile location obtained in a different way.
10536 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10538 If you are using target caching (see `org-refile-use-cache'),
10539 You have to clear the target cache in order to find new targets.
10540 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10541 prefix argument (`C-u C-u C-u C-c C-w')."
10543 (interactive "P")
10544 (if (member goto '(0 (64)))
10545 (org-refile-cache-clear)
10546 (let* ((cbuf (current-buffer))
10547 (regionp (org-region-active-p))
10548 (region-start (and regionp (region-beginning)))
10549 (region-end (and regionp (region-end)))
10550 (region-length (and regionp (- region-end region-start)))
10551 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10552 pos it nbuf file re level reversed)
10553 (setq last-command nil)
10554 (when regionp
10555 (goto-char region-start)
10556 (or (bolp) (goto-char (point-at-bol)))
10557 (setq region-start (point))
10558 (unless (or (org-kill-is-subtree-p
10559 (buffer-substring region-start region-end))
10560 (prog1 org-refile-active-region-within-subtree
10561 (org-toggle-heading)))
10562 (error "The region is not a (sequence of) subtree(s)")))
10563 (if (equal goto '(16))
10564 (org-refile-goto-last-stored)
10565 (when (or
10566 (and (equal goto 2)
10567 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10568 (prog1
10569 (setq it (list (or org-clock-heading "running clock")
10570 (buffer-file-name
10571 (marker-buffer org-clock-hd-marker))
10573 (marker-position org-clock-hd-marker)))
10574 (setq goto nil)))
10575 (setq it (or rfloc
10576 (let (heading-text)
10577 (save-excursion
10578 (unless goto
10579 (org-back-to-heading t)
10580 (setq heading-text
10581 (nth 4 (org-heading-components))))
10582 (org-refile-get-location
10583 (cond (goto "Goto")
10584 (regionp "Refile region to")
10585 (t (concat "Refile subtree \""
10586 heading-text "\" to")))
10587 default-buffer
10588 org-refile-allow-creating-parent-nodes
10589 goto))))))
10590 (setq file (nth 1 it)
10591 re (nth 2 it)
10592 pos (nth 3 it))
10593 (if (and (not goto)
10595 (equal (buffer-file-name) file)
10596 (if regionp
10597 (and (>= pos region-start)
10598 (<= pos region-end))
10599 (and (>= pos (point))
10600 (< pos (save-excursion
10601 (org-end-of-subtree t t))))))
10602 (error "Cannot refile to position inside the tree or region"))
10604 (setq nbuf (or (find-buffer-visiting file)
10605 (find-file-noselect file)))
10606 (if goto
10607 (progn
10608 (org-pop-to-buffer-same-window nbuf)
10609 (goto-char pos)
10610 (org-show-context 'org-goto))
10611 (if regionp
10612 (progn
10613 (org-kill-new (buffer-substring region-start region-end))
10614 (org-save-markers-in-region region-start region-end))
10615 (org-copy-subtree 1 nil t))
10616 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10617 (find-file-noselect file)))
10618 (setq reversed (org-notes-order-reversed-p))
10619 (save-excursion
10620 (save-restriction
10621 (widen)
10622 (if pos
10623 (progn
10624 (goto-char pos)
10625 (looking-at org-outline-regexp)
10626 (setq level (org-get-valid-level (funcall outline-level) 1))
10627 (goto-char
10628 (if reversed
10629 (or (outline-next-heading) (point-max))
10630 (or (save-excursion (org-get-next-sibling))
10631 (org-end-of-subtree t t)
10632 (point-max)))))
10633 (setq level 1)
10634 (if (not reversed)
10635 (goto-char (point-max))
10636 (goto-char (point-min))
10637 (or (outline-next-heading) (goto-char (point-max)))))
10638 (if (not (bolp)) (newline))
10639 (org-paste-subtree level)
10640 (when org-log-refile
10641 (org-add-log-setup 'refile nil nil 'findpos
10642 org-log-refile)
10643 (unless (eq org-log-refile 'note)
10644 (save-excursion (org-add-log-note))))
10645 (and org-auto-align-tags (org-set-tags nil t))
10646 (bookmark-set "org-refile-last-stored")
10647 ;; If we are refiling for capture, make sure that the
10648 ;; last-capture pointers point here
10649 (when (org-bound-and-true-p org-refile-for-capture)
10650 (bookmark-set "org-capture-last-stored-marker")
10651 (move-marker org-capture-last-stored-marker (point)))
10652 (if (fboundp 'deactivate-mark) (deactivate-mark))
10653 (run-hooks 'org-after-refile-insert-hook))))
10654 (if regionp
10655 (delete-region (point) (+ (point) region-length))
10656 (org-cut-subtree))
10657 (when (featurep 'org-inlinetask)
10658 (org-inlinetask-remove-END-maybe))
10659 (setq org-markers-to-move nil)
10660 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10662 (defun org-refile-goto-last-stored ()
10663 "Go to the location where the last refile was stored."
10664 (interactive)
10665 (bookmark-jump "org-refile-last-stored")
10666 (message "This is the location of the last refile"))
10668 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10669 no-exclude)
10670 "Prompt the user for a refile location, using PROMPT.
10671 PROMPT should not be suffixed with a colon and a space, because
10672 this function appends the default value from
10673 `org-refile-history' automatically, if that is not empty.
10674 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10675 this is used for the GOTO interface."
10676 (let ((org-refile-targets org-refile-targets)
10677 (org-refile-use-outline-path org-refile-use-outline-path)
10678 excluded-entries)
10679 (when (and (eq major-mode 'org-mode)
10680 (not org-refile-use-cache)
10681 (not no-exclude))
10682 (org-map-tree
10683 (lambda()
10684 (setq excluded-entries
10685 (append excluded-entries (list (org-get-heading t t)))))))
10686 (setq org-refile-target-table
10687 (org-refile-get-targets default-buffer excluded-entries)))
10688 (unless org-refile-target-table
10689 (error "No refile targets"))
10690 (let* ((prompt (concat prompt
10691 (and (car org-refile-history)
10692 (concat " (default " (car org-refile-history) ")"))
10693 ": "))
10694 (cbuf (current-buffer))
10695 (partial-completion-mode nil)
10696 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10697 (cfunc (if (and org-refile-use-outline-path
10698 org-outline-path-complete-in-steps)
10699 'org-olpath-completing-read
10700 'org-icompleting-read))
10701 (extra (if org-refile-use-outline-path "/" ""))
10702 (filename (and cfn (expand-file-name cfn)))
10703 (tbl (mapcar
10704 (lambda (x)
10705 (if (and (not (member org-refile-use-outline-path
10706 '(file full-file-path)))
10707 (not (equal filename (nth 1 x))))
10708 (cons (concat (car x) extra " ("
10709 (file-name-nondirectory (nth 1 x)) ")")
10710 (cdr x))
10711 (cons (concat (car x) extra) (cdr x))))
10712 org-refile-target-table))
10713 (completion-ignore-case t)
10714 pa answ parent-target child parent old-hist)
10715 (setq old-hist org-refile-history)
10716 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10717 nil 'org-refile-history (car org-refile-history)))
10718 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10719 (org-refile-check-position pa)
10720 (if pa
10721 (progn
10722 (when (or (not org-refile-history)
10723 (not (eq old-hist org-refile-history))
10724 (not (equal (car pa) (car org-refile-history))))
10725 (setq org-refile-history
10726 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10727 org-refile-history
10728 (cdr org-refile-history))))
10729 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10730 (pop org-refile-history)))
10732 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10733 (progn
10734 (setq parent (match-string 1 answ)
10735 child (match-string 2 answ))
10736 (setq parent-target (or (assoc parent tbl)
10737 (assoc (concat parent "/") tbl)))
10738 (when (and parent-target
10739 (or (eq new-nodes t)
10740 (and (eq new-nodes 'confirm)
10741 (y-or-n-p (format "Create new node \"%s\"? "
10742 child)))))
10743 (org-refile-new-child parent-target child)))
10744 (error "Invalid target location")))))
10746 (defun org-refile-check-position (refile-pointer)
10747 "Check if the refile pointer matches the readline to which it points."
10748 (let* ((file (nth 1 refile-pointer))
10749 (re (nth 2 refile-pointer))
10750 (pos (nth 3 refile-pointer))
10751 buffer)
10752 (when (org-string-nw-p re)
10753 (setq buffer (if (markerp pos)
10754 (marker-buffer pos)
10755 (or (find-buffer-visiting file)
10756 (find-file-noselect file))))
10757 (with-current-buffer buffer
10758 (save-excursion
10759 (save-restriction
10760 (widen)
10761 (goto-char pos)
10762 (beginning-of-line 1)
10763 (unless (org-looking-at-p re)
10764 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
10766 (defun org-refile-new-child (parent-target child)
10767 "Use refile target PARENT-TARGET to add new CHILD below it."
10768 (unless parent-target
10769 (error "Cannot find parent for new node"))
10770 (let ((file (nth 1 parent-target))
10771 (pos (nth 3 parent-target))
10772 level)
10773 (with-current-buffer (or (find-buffer-visiting file)
10774 (find-file-noselect file))
10775 (save-excursion
10776 (save-restriction
10777 (widen)
10778 (if pos
10779 (goto-char pos)
10780 (goto-char (point-max))
10781 (if (not (bolp)) (newline)))
10782 (when (looking-at org-outline-regexp)
10783 (setq level (funcall outline-level))
10784 (org-end-of-subtree t t))
10785 (org-back-over-empty-lines)
10786 (insert "\n" (make-string
10787 (if pos (org-get-valid-level level 1) 1) ?*)
10788 " " child "\n")
10789 (beginning-of-line 0)
10790 (list (concat (car parent-target) "/" child) file "" (point)))))))
10792 (defun org-olpath-completing-read (prompt collection &rest args)
10793 "Read an outline path like a file name."
10794 (let ((thetable collection)
10795 (org-completion-use-ido nil) ; does not work with ido.
10796 (org-completion-use-iswitchb nil)) ; or iswitchb
10797 (apply
10798 'org-icompleting-read prompt
10799 (lambda (string predicate &optional flag)
10800 (let (rtn r f (l (length string)))
10801 (cond
10802 ((eq flag nil)
10803 ;; try completion
10804 (try-completion string thetable))
10805 ((eq flag t)
10806 ;; all-completions
10807 (setq rtn (all-completions string thetable predicate))
10808 (mapcar
10809 (lambda (x)
10810 (setq r (substring x l))
10811 (if (string-match " ([^)]*)$" x)
10812 (setq f (match-string 0 x))
10813 (setq f ""))
10814 (if (string-match "/" r)
10815 (concat string (substring r 0 (match-end 0)) f)
10817 rtn))
10818 ((eq flag 'lambda)
10819 ;; exact match?
10820 (assoc string thetable)))
10822 args)))
10824 ;;;; Dynamic blocks
10826 (defun org-find-dblock (name)
10827 "Find the first dynamic block with name NAME in the buffer.
10828 If not found, stay at current position and return nil."
10829 (let (pos)
10830 (save-excursion
10831 (goto-char (point-min))
10832 (setq pos (and (re-search-forward (concat "^[ \t]*#\\+BEGIN:[ \t]+" name "\\>")
10833 nil t)
10834 (match-beginning 0))))
10835 (if pos (goto-char pos))
10836 pos))
10838 (defconst org-dblock-start-re
10839 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10840 "Matches the start line of a dynamic block, with parameters.")
10842 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
10843 "Matches the end of a dynamic block.")
10845 (defun org-create-dblock (plist)
10846 "Create a dynamic block section, with parameters taken from PLIST.
10847 PLIST must contain a :name entry which is used as name of the block."
10848 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
10849 (end-of-line 1)
10850 (newline))
10851 (let ((col (current-column))
10852 (name (plist-get plist :name)))
10853 (insert "#+BEGIN: " name)
10854 (while plist
10855 (if (eq (car plist) :name)
10856 (setq plist (cddr plist))
10857 (insert " " (prin1-to-string (pop plist)))))
10858 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
10859 (beginning-of-line -2)))
10861 (defun org-prepare-dblock ()
10862 "Prepare dynamic block for refresh.
10863 This empties the block, puts the cursor at the insert position and returns
10864 the property list including an extra property :name with the block name."
10865 (unless (looking-at org-dblock-start-re)
10866 (error "Not at a dynamic block"))
10867 (let* ((begdel (1+ (match-end 0)))
10868 (name (org-no-properties (match-string 1)))
10869 (params (append (list :name name)
10870 (read (concat "(" (match-string 3) ")")))))
10871 (save-excursion
10872 (beginning-of-line 1)
10873 (skip-chars-forward " \t")
10874 (setq params (plist-put params :indentation-column (current-column))))
10875 (unless (re-search-forward org-dblock-end-re nil t)
10876 (error "Dynamic block not terminated"))
10877 (setq params
10878 (append params
10879 (list :content (buffer-substring
10880 begdel (match-beginning 0)))))
10881 (delete-region begdel (match-beginning 0))
10882 (goto-char begdel)
10883 (open-line 1)
10884 params))
10886 (defun org-map-dblocks (&optional command)
10887 "Apply COMMAND to all dynamic blocks in the current buffer.
10888 If COMMAND is not given, use `org-update-dblock'."
10889 (let ((cmd (or command 'org-update-dblock)))
10890 (save-excursion
10891 (goto-char (point-min))
10892 (while (re-search-forward org-dblock-start-re nil t)
10893 (goto-char (match-beginning 0))
10894 (save-excursion
10895 (condition-case nil
10896 (funcall cmd)
10897 (error (message "Error during update of dynamic block"))))
10898 (unless (re-search-forward org-dblock-end-re nil t)
10899 (error "Dynamic block not terminated"))))))
10901 (defun org-dblock-update (&optional arg)
10902 "User command for updating dynamic blocks.
10903 Update the dynamic block at point. With prefix ARG, update all dynamic
10904 blocks in the buffer."
10905 (interactive "P")
10906 (if arg
10907 (org-update-all-dblocks)
10908 (or (looking-at org-dblock-start-re)
10909 (org-beginning-of-dblock))
10910 (org-update-dblock)))
10912 (defun org-update-dblock ()
10913 "Update the dynamic block at point.
10914 This means to empty the block, parse for parameters and then call
10915 the correct writing function."
10916 (interactive)
10917 (save-window-excursion
10918 (let* ((pos (point))
10919 (line (org-current-line))
10920 (params (org-prepare-dblock))
10921 (name (plist-get params :name))
10922 (indent (plist-get params :indentation-column))
10923 (cmd (intern (concat "org-dblock-write:" name))))
10924 (message "Updating dynamic block `%s' at line %d..." name line)
10925 (funcall cmd params)
10926 (message "Updating dynamic block `%s' at line %d...done" name line)
10927 (goto-char pos)
10928 (when (and indent (> indent 0))
10929 (setq indent (make-string indent ?\ ))
10930 (save-excursion
10931 (org-beginning-of-dblock)
10932 (forward-line 1)
10933 (while (not (looking-at org-dblock-end-re))
10934 (insert indent)
10935 (beginning-of-line 2))
10936 (when (looking-at org-dblock-end-re)
10937 (and (looking-at "[ \t]+")
10938 (replace-match ""))
10939 (insert indent)))))))
10941 (defun org-beginning-of-dblock ()
10942 "Find the beginning of the dynamic block at point.
10943 Error if there is no such block at point."
10944 (let ((pos (point))
10945 beg)
10946 (end-of-line 1)
10947 (if (and (re-search-backward org-dblock-start-re nil t)
10948 (setq beg (match-beginning 0))
10949 (re-search-forward org-dblock-end-re nil t)
10950 (> (match-end 0) pos))
10951 (goto-char beg)
10952 (goto-char pos)
10953 (error "Not in a dynamic block"))))
10955 (defun org-update-all-dblocks ()
10956 "Update all dynamic blocks in the buffer.
10957 This function can be used in a hook."
10958 (interactive)
10959 (when (eq major-mode 'org-mode)
10960 (org-map-dblocks 'org-update-dblock)))
10963 ;;;; Completion
10965 (defconst org-additional-option-like-keywords
10966 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
10967 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
10968 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
10969 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
10970 "BEGIN:" "END:"
10971 "ORGTBL" "TBLFM:" "TBLNAME:"
10972 "BEGIN_EXAMPLE" "END_EXAMPLE"
10973 "BEGIN_QUOTE" "END_QUOTE"
10974 "BEGIN_VERSE" "END_VERSE"
10975 "BEGIN_CENTER" "END_CENTER"
10976 "BEGIN_SRC" "END_SRC"
10977 "BEGIN_RESULT" "END_RESULT"
10978 "SOURCE:" "SRCNAME:" "FUNCTION:"
10979 "RESULTS:" "DATA:"
10980 "HEADER:" "HEADERS:"
10981 "BABEL:"
10982 "CATEGORY:" "COLUMNS:" "PROPERTY:"
10983 "CAPTION:" "LABEL:"
10984 "SETUPFILE:"
10985 "INCLUDE:"
10986 "BIND:"
10987 "MACRO:"))
10989 (defcustom org-structure-template-alist
10991 ("s" "#+begin_src ?\n\n#+end_src"
10992 "<src lang=\"?\">\n\n</src>")
10993 ("e" "#+begin_example\n?\n#+end_example"
10994 "<example>\n?\n</example>")
10995 ("q" "#+begin_quote\n?\n#+end_quote"
10996 "<quote>\n?\n</quote>")
10997 ("v" "#+begin_verse\n?\n#+end_verse"
10998 "<verse>\n?\n/verse>")
10999 ("c" "#+begin_center\n?\n#+end_center"
11000 "<center>\n?\n/center>")
11001 ("l" "#+begin_latex\n?\n#+end_latex"
11002 "<literal style=\"latex\">\n?\n</literal>")
11003 ("L" "#+latex: "
11004 "<literal style=\"latex\">?</literal>")
11005 ("h" "#+begin_html\n?\n#+end_html"
11006 "<literal style=\"html\">\n?\n</literal>")
11007 ("H" "#+html: "
11008 "<literal style=\"html\">?</literal>")
11009 ("a" "#+begin_ascii\n?\n#+end_ascii")
11010 ("A" "#+ascii: ")
11011 ("i" "#+index: ?"
11012 "#+index: ?")
11013 ("I" "#+include %file ?"
11014 "<include file=%file markup=\"?\">")
11016 "Structure completion elements.
11017 This is a list of abbreviation keys and values. The value gets inserted
11018 if you type `<' followed by the key and then press the completion key,
11019 usually `M-TAB'. %file will be replaced by a file name after prompting
11020 for the file using completion. The cursor will be placed at the position
11021 of the `?` in the template.
11022 There are two templates for each key, the first uses the original Org syntax,
11023 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11024 the default when the /org-mtags.el/ module has been loaded. See also the
11025 variable `org-mtags-prefer-muse-templates'.
11026 This is an experimental feature, it is undecided if it is going to stay in."
11027 :group 'org-completion
11028 :type '(repeat
11029 (string :tag "Key")
11030 (string :tag "Template")
11031 (string :tag "Muse Template")))
11033 (defun org-try-structure-completion ()
11034 "Try to complete a structure template before point.
11035 This looks for strings like \"<e\" on an otherwise empty line and
11036 expands them."
11037 (let ((l (buffer-substring (point-at-bol) (point)))
11039 (when (and (looking-at "[ \t]*$")
11040 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11041 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11042 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11043 (match-beginning 1)) a)
11044 t)))
11046 (defun org-complete-expand-structure-template (start cell)
11047 "Expand a structure template."
11048 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11049 (rpl (nth (if musep 2 1) cell))
11050 (ind ""))
11051 (delete-region start (point))
11052 (when (string-match "\\`#\\+" rpl)
11053 (cond
11054 ((bolp))
11055 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11056 (setq ind (buffer-substring (point-at-bol) (point))))
11057 (t (newline))))
11058 (setq start (point))
11059 (if (string-match "%file" rpl)
11060 (setq rpl (replace-match
11061 (concat
11062 "\""
11063 (save-match-data
11064 (abbreviate-file-name (read-file-name "Include file: ")))
11065 "\"")
11066 t t rpl)))
11067 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11068 (concat "\n" ind)))
11069 (insert rpl)
11070 (if (re-search-backward "\\?" start t) (delete-char 1))))
11072 ;;;; TODO, DEADLINE, Comments
11074 (defun org-toggle-comment ()
11075 "Change the COMMENT state of an entry."
11076 (interactive)
11077 (save-excursion
11078 (org-back-to-heading)
11079 (let (case-fold-search)
11080 (cond
11081 ((looking-at (format org-heading-keyword-regexp-format
11082 org-comment-string))
11083 (goto-char (match-end 1))
11084 (looking-at (concat " +" org-comment-string))
11085 (replace-match "" t t)
11086 (when (eolp) (insert " ")))
11087 ((looking-at org-outline-regexp)
11088 (goto-char (match-end 0))
11089 (insert org-comment-string " "))))))
11091 (defvar org-last-todo-state-is-todo nil
11092 "This is non-nil when the last TODO state change led to a TODO state.
11093 If the last change removed the TODO tag or switched to DONE, then
11094 this is nil.")
11096 (defvar org-setting-tags nil) ; dynamically skipped
11098 (defvar org-todo-setup-filter-hook nil
11099 "Hook for functions that pre-filter todo specs.
11100 Each function takes a todo spec and returns either nil or the spec
11101 transformed into canonical form." )
11103 (defvar org-todo-get-default-hook nil
11104 "Hook for functions that get a default item for todo.
11105 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11106 nil or a string to be used for the todo mark." )
11108 (defvar org-agenda-headline-snapshot-before-repeat)
11110 (defun org-current-effective-time ()
11111 "Return current time adjusted for `org-extend-today-until' variable"
11112 (let* ((ct (org-current-time))
11113 (dct (decode-time ct))
11114 (ct1
11115 (if (and org-use-effective-time
11116 (< (nth 2 dct) org-extend-today-until))
11117 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11118 ct)))
11119 ct1))
11121 (defun org-todo-yesterday (&optional arg)
11122 "Like `org-todo' but the time of change will be 23:59 of yesterday"
11123 (interactive "P")
11124 (let* ((hour (third (decode-time
11125 (org-current-time))))
11126 (org-extend-today-until (1+ hour)))
11127 (org-todo arg)))
11129 (defun org-todo (&optional arg)
11130 "Change the TODO state of an item.
11131 The state of an item is given by a keyword at the start of the heading,
11132 like
11133 *** TODO Write paper
11134 *** DONE Call mom
11136 The different keywords are specified in the variable `org-todo-keywords'.
11137 By default the available states are \"TODO\" and \"DONE\".
11138 So for this example: when the item starts with TODO, it is changed to DONE.
11139 When it starts with DONE, the DONE is removed. And when neither TODO nor
11140 DONE are present, add TODO at the beginning of the heading.
11142 With \\[universal-argument] prefix arg, use completion to determine the new \
11143 state.
11144 With numeric prefix arg, switch to that state.
11145 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11146 keywords (nextset).
11147 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11149 For calling through lisp, arg is also interpreted in the following way:
11150 'none -> empty state
11151 \"\"(empty string) -> switch to empty state
11152 'done -> switch to DONE
11153 'nextset -> switch to the next set of keywords
11154 'previousset -> switch to the previous set of keywords
11155 \"WAITING\" -> switch to the specified keyword, but only if it
11156 really is a member of `org-todo-keywords'."
11157 (interactive "P")
11158 (if (equal arg '(16)) (setq arg 'nextset))
11159 (let ((org-blocker-hook org-blocker-hook)
11160 (case-fold-search nil))
11161 (when (equal arg '(64))
11162 (setq arg nil org-blocker-hook nil))
11163 (when (and org-blocker-hook
11164 (or org-inhibit-blocking
11165 (org-entry-get nil "NOBLOCKING")))
11166 (setq org-blocker-hook nil))
11167 (save-excursion
11168 (catch 'exit
11169 (org-back-to-heading t)
11170 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11171 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11172 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11173 (let* ((match-data (match-data))
11174 (startpos (point-at-bol))
11175 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11176 (org-log-done org-log-done)
11177 (org-log-repeat org-log-repeat)
11178 (org-todo-log-states org-todo-log-states)
11179 (this (match-string 1))
11180 (hl-pos (match-beginning 0))
11181 (head (org-get-todo-sequence-head this))
11182 (ass (assoc head org-todo-kwd-alist))
11183 (interpret (nth 1 ass))
11184 (done-word (nth 3 ass))
11185 (final-done-word (nth 4 ass))
11186 (last-state (or this ""))
11187 (completion-ignore-case t)
11188 (member (member this org-todo-keywords-1))
11189 (tail (cdr member))
11190 (state (cond
11191 ((and org-todo-key-trigger
11192 (or (and (equal arg '(4))
11193 (eq org-use-fast-todo-selection 'prefix))
11194 (and (not arg) org-use-fast-todo-selection
11195 (not (eq org-use-fast-todo-selection
11196 'prefix)))))
11197 ;; Use fast selection
11198 (org-fast-todo-selection))
11199 ((and (equal arg '(4))
11200 (or (not org-use-fast-todo-selection)
11201 (not org-todo-key-trigger)))
11202 ;; Read a state with completion
11203 (org-icompleting-read
11204 "State: " (mapcar (lambda(x) (list x))
11205 org-todo-keywords-1)
11206 nil t))
11207 ((eq arg 'right)
11208 (if this
11209 (if tail (car tail) nil)
11210 (car org-todo-keywords-1)))
11211 ((eq arg 'left)
11212 (if (equal member org-todo-keywords-1)
11214 (if this
11215 (nth (- (length org-todo-keywords-1)
11216 (length tail) 2)
11217 org-todo-keywords-1)
11218 (org-last org-todo-keywords-1))))
11219 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11220 (setq arg nil))) ; hack to fall back to cycling
11221 (arg
11222 ;; user or caller requests a specific state
11223 (cond
11224 ((equal arg "") nil)
11225 ((eq arg 'none) nil)
11226 ((eq arg 'done) (or done-word (car org-done-keywords)))
11227 ((eq arg 'nextset)
11228 (or (car (cdr (member head org-todo-heads)))
11229 (car org-todo-heads)))
11230 ((eq arg 'previousset)
11231 (let ((org-todo-heads (reverse org-todo-heads)))
11232 (or (car (cdr (member head org-todo-heads)))
11233 (car org-todo-heads))))
11234 ((car (member arg org-todo-keywords-1)))
11235 ((stringp arg)
11236 (error "State `%s' not valid in this file" arg))
11237 ((nth (1- (prefix-numeric-value arg))
11238 org-todo-keywords-1))))
11239 ((null member) (or head (car org-todo-keywords-1)))
11240 ((equal this final-done-word) nil) ;; -> make empty
11241 ((null tail) nil) ;; -> first entry
11242 ((memq interpret '(type priority))
11243 (if (eq this-command last-command)
11244 (car tail)
11245 (if (> (length tail) 0)
11246 (or done-word (car org-done-keywords))
11247 nil)))
11249 (car tail))))
11250 (state (or
11251 (run-hook-with-args-until-success
11252 'org-todo-get-default-hook state last-state)
11253 state))
11254 (next (if state (concat " " state " ") " "))
11255 (change-plist (list :type 'todo-state-change :from this :to state
11256 :position startpos))
11257 dolog now-done-p)
11258 (when org-blocker-hook
11259 (setq org-last-todo-state-is-todo
11260 (not (member this org-done-keywords)))
11261 (unless (save-excursion
11262 (save-match-data
11263 (org-with-wide-buffer
11264 (run-hook-with-args-until-failure
11265 'org-blocker-hook change-plist))))
11266 (if (org-called-interactively-p 'interactive)
11267 (error "TODO state change from %s to %s blocked" this state)
11268 ;; fail silently
11269 (message "TODO state change from %s to %s blocked" this state)
11270 (throw 'exit nil))))
11271 (store-match-data match-data)
11272 (replace-match next t t)
11273 (unless (pos-visible-in-window-p hl-pos)
11274 (message "TODO state changed to %s" (org-trim next)))
11275 (unless head
11276 (setq head (org-get-todo-sequence-head state)
11277 ass (assoc head org-todo-kwd-alist)
11278 interpret (nth 1 ass)
11279 done-word (nth 3 ass)
11280 final-done-word (nth 4 ass)))
11281 (when (memq arg '(nextset previousset))
11282 (message "Keyword-Set %d/%d: %s"
11283 (- (length org-todo-sets) -1
11284 (length (memq (assoc state org-todo-sets) org-todo-sets)))
11285 (length org-todo-sets)
11286 (mapconcat 'identity (assoc state org-todo-sets) " ")))
11287 (setq org-last-todo-state-is-todo
11288 (not (member state org-done-keywords)))
11289 (setq now-done-p (and (member state org-done-keywords)
11290 (not (member this org-done-keywords))))
11291 (and logging (org-local-logging logging))
11292 (when (and (or org-todo-log-states org-log-done)
11293 (not (eq org-inhibit-logging t))
11294 (not (memq arg '(nextset previousset))))
11295 ;; we need to look at recording a time and note
11296 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
11297 (nth 2 (assoc this org-todo-log-states))))
11298 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11299 (setq dolog 'time))
11300 (when (and state
11301 (member state org-not-done-keywords)
11302 (not (member this org-not-done-keywords)))
11303 ;; This is now a todo state and was not one before
11304 ;; If there was a CLOSED time stamp, get rid of it.
11305 (org-add-planning-info nil nil 'closed))
11306 (when (and now-done-p org-log-done)
11307 ;; It is now done, and it was not done before
11308 (org-add-planning-info 'closed (org-current-effective-time))
11309 (if (and (not dolog) (eq 'note org-log-done))
11310 (org-add-log-setup 'done state this 'findpos 'note)))
11311 (when (and state dolog)
11312 ;; This is a non-nil state, and we need to log it
11313 (org-add-log-setup 'state state this 'findpos dolog)))
11314 ;; Fixup tag positioning
11315 (org-todo-trigger-tag-changes state)
11316 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11317 (when org-provide-todo-statistics
11318 (org-update-parent-todo-statistics))
11319 (run-hooks 'org-after-todo-state-change-hook)
11320 (if (and arg (not (member state org-done-keywords)))
11321 (setq head (org-get-todo-sequence-head state)))
11322 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11323 ;; Do we need to trigger a repeat?
11324 (when now-done-p
11325 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11326 ;; This is for the agenda, take a snapshot of the headline.
11327 (save-match-data
11328 (setq org-agenda-headline-snapshot-before-repeat
11329 (org-get-heading))))
11330 (org-auto-repeat-maybe state))
11331 ;; Fixup cursor location if close to the keyword
11332 (if (and (outline-on-heading-p)
11333 (not (bolp))
11334 (save-excursion (beginning-of-line 1)
11335 (looking-at org-todo-line-regexp))
11336 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11337 (progn
11338 (goto-char (or (match-end 2) (match-end 1)))
11339 (and (looking-at " ") (just-one-space))))
11340 (when org-trigger-hook
11341 (save-excursion
11342 (run-hook-with-args 'org-trigger-hook change-plist))))))))
11344 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11345 "Block turning an entry into a TODO, using the hierarchy.
11346 This checks whether the current task should be blocked from state
11347 changes. Such blocking occurs when:
11349 1. The task has children which are not all in a completed state.
11351 2. A task has a parent with the property :ORDERED:, and there
11352 are siblings prior to the current task with incomplete
11353 status.
11355 3. The parent of the task is blocked because it has siblings that should
11356 be done first, or is child of a block grandparent TODO entry."
11358 (if (not org-enforce-todo-dependencies)
11359 t ; if locally turned off don't block
11360 (catch 'dont-block
11361 ;; If this is not a todo state change, or if this entry is already DONE,
11362 ;; do not block
11363 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11364 (member (plist-get change-plist :from)
11365 (cons 'done org-done-keywords))
11366 (member (plist-get change-plist :to)
11367 (cons 'todo org-not-done-keywords))
11368 (not (plist-get change-plist :to)))
11369 (throw 'dont-block t))
11370 ;; If this task has children, and any are undone, it's blocked
11371 (save-excursion
11372 (org-back-to-heading t)
11373 (let ((this-level (funcall outline-level)))
11374 (outline-next-heading)
11375 (let ((child-level (funcall outline-level)))
11376 (while (and (not (eobp))
11377 (> child-level this-level))
11378 ;; this todo has children, check whether they are all
11379 ;; completed
11380 (if (and (not (org-entry-is-done-p))
11381 (org-entry-is-todo-p))
11382 (throw 'dont-block nil))
11383 (outline-next-heading)
11384 (setq child-level (funcall outline-level))))))
11385 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11386 ;; any previous siblings are undone, it's blocked
11387 (save-excursion
11388 (org-back-to-heading t)
11389 (let* ((pos (point))
11390 (parent-pos (and (org-up-heading-safe) (point))))
11391 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11392 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11393 (forward-line 1)
11394 (re-search-forward org-not-done-heading-regexp pos t))
11395 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11396 ;; Search further up the hierarchy, to see if an anchestor is blocked
11397 (while t
11398 (goto-char parent-pos)
11399 (if (not (looking-at org-not-done-heading-regexp))
11400 (throw 'dont-block t)) ; do not block, parent is not a TODO
11401 (setq pos (point))
11402 (setq parent-pos (and (org-up-heading-safe) (point)))
11403 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11404 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11405 (forward-line 1)
11406 (re-search-forward org-not-done-heading-regexp pos t))
11407 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11409 (defcustom org-track-ordered-property-with-tag nil
11410 "Should the ORDERED property also be shown as a tag?
11411 The ORDERED property decides if an entry should require subtasks to be
11412 completed in sequence. Since a property is not very visible, setting
11413 this option means that toggling the ORDERED property with the command
11414 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11415 not relevant for the behavior, but it makes things more visible.
11417 Note that toggling the tag with tags commands will not change the property
11418 and therefore not influence behavior!
11420 This can be t, meaning the tag ORDERED should be used, It can also be a
11421 string to select a different tag for this task."
11422 :group 'org-todo
11423 :type '(choice
11424 (const :tag "No tracking" nil)
11425 (const :tag "Track with ORDERED tag" t)
11426 (string :tag "Use other tag")))
11428 (defun org-toggle-ordered-property ()
11429 "Toggle the ORDERED property of the current entry.
11430 For better visibility, you can track the value of this property with a tag.
11431 See variable `org-track-ordered-property-with-tag'."
11432 (interactive)
11433 (let* ((t1 org-track-ordered-property-with-tag)
11434 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11435 (save-excursion
11436 (org-back-to-heading)
11437 (if (org-entry-get nil "ORDERED")
11438 (progn
11439 (org-delete-property "ORDERED")
11440 (and tag (org-toggle-tag tag 'off))
11441 (message "Subtasks can be completed in arbitrary order"))
11442 (org-entry-put nil "ORDERED" "t")
11443 (and tag (org-toggle-tag tag 'on))
11444 (message "Subtasks must be completed in sequence")))))
11446 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11447 (defun org-block-todo-from-checkboxes (change-plist)
11448 "Block turning an entry into a TODO, using checkboxes.
11449 This checks whether the current task should be blocked from state
11450 changes because there are unchecked boxes in this entry."
11451 (if (not org-enforce-todo-checkbox-dependencies)
11452 t ; if locally turned off don't block
11453 (catch 'dont-block
11454 ;; If this is not a todo state change, or if this entry is already DONE,
11455 ;; do not block
11456 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11457 (member (plist-get change-plist :from)
11458 (cons 'done org-done-keywords))
11459 (member (plist-get change-plist :to)
11460 (cons 'todo org-not-done-keywords))
11461 (not (plist-get change-plist :to)))
11462 (throw 'dont-block t))
11463 ;; If this task has checkboxes that are not checked, it's blocked
11464 (save-excursion
11465 (org-back-to-heading t)
11466 (let ((beg (point)) end)
11467 (outline-next-heading)
11468 (setq end (point))
11469 (goto-char beg)
11470 (if (org-list-search-forward
11471 (concat (org-item-beginning-re)
11472 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11473 "\\[[- ]\\]")
11474 end t)
11475 (progn
11476 (if (boundp 'org-blocked-by-checkboxes)
11477 (setq org-blocked-by-checkboxes t))
11478 (throw 'dont-block nil)))))
11479 t))) ; do not block
11481 (defun org-entry-blocked-p ()
11482 "Is the current entry blocked?"
11483 (if (org-entry-get nil "NOBLOCKING")
11484 nil ;; Never block this entry
11485 (not
11486 (run-hook-with-args-until-failure
11487 'org-blocker-hook
11488 (list :type 'todo-state-change
11489 :position (point)
11490 :from 'todo
11491 :to 'done)))))
11493 (defun org-update-statistics-cookies (all)
11494 "Update the statistics cookie, either from TODO or from checkboxes.
11495 This should be called with the cursor in a line with a statistics cookie."
11496 (interactive "P")
11497 (if all
11498 (progn
11499 (org-update-checkbox-count 'all)
11500 (org-map-entries 'org-update-parent-todo-statistics))
11501 (if (not (org-on-heading-p))
11502 (org-update-checkbox-count)
11503 (let ((pos (move-marker (make-marker) (point)))
11504 end l1 l2)
11505 (ignore-errors (org-back-to-heading t))
11506 (if (not (org-on-heading-p))
11507 (org-update-checkbox-count)
11508 (setq l1 (org-outline-level))
11509 (setq end (save-excursion
11510 (outline-next-heading)
11511 (if (org-on-heading-p) (setq l2 (org-outline-level)))
11512 (point)))
11513 (if (and (save-excursion
11514 (re-search-forward
11515 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11516 (not (save-excursion (re-search-forward
11517 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11518 (org-update-checkbox-count)
11519 (if (and l2 (> l2 l1))
11520 (progn
11521 (goto-char end)
11522 (org-update-parent-todo-statistics))
11523 (goto-char pos)
11524 (beginning-of-line 1)
11525 (while (re-search-forward
11526 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11527 (point-at-eol) t)
11528 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11529 (goto-char pos)
11530 (move-marker pos nil)))))
11532 (defvar org-entry-property-inherited-from) ;; defined below
11533 (defun org-update-parent-todo-statistics ()
11534 "Update any statistics cookie in the parent of the current headline.
11535 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11536 the entire subtree and this will travel up the hierarchy and update
11537 statistics everywhere."
11538 (let* ((prop (save-excursion (org-up-heading-safe)
11539 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11540 (recursive (or (not org-hierarchical-todo-statistics)
11541 (and prop (string-match "\\<recursive\\>" prop))))
11542 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11544 (first t)
11545 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11546 level ltoggle l1 new ndel
11547 (cnt-all 0) (cnt-done 0) is-percent kwd
11548 checkbox-beg ov ovs ove cookie-present)
11549 (catch 'exit
11550 (save-excursion
11551 (beginning-of-line 1)
11552 (setq ltoggle (funcall outline-level))
11553 ;; Three situations are to consider:
11555 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11556 ;; to the top-level ancestor on the headline;
11558 ;; 2. If parent has "recursive" property, repeat up to the
11559 ;; headline setting that property, taking inheritance into
11560 ;; account;
11562 ;; 3. Else, move up to direct parent and proceed only once.
11563 (while (and (setq level (org-up-heading-safe))
11564 (or recursive first)
11565 (>= (point) lim))
11566 (setq first nil cookie-present nil)
11567 (unless (and level
11568 (not (string-match
11569 "\\<checkbox\\>"
11570 (downcase (or (org-entry-get nil "COOKIE_DATA")
11571 "")))))
11572 (throw 'exit nil))
11573 (while (re-search-forward box-re (point-at-eol) t)
11574 (setq cnt-all 0 cnt-done 0 cookie-present t)
11575 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11576 (save-match-data
11577 (unless (outline-next-heading) (throw 'exit nil))
11578 (while (and (looking-at org-complex-heading-regexp)
11579 (> (setq l1 (length (match-string 1))) level))
11580 (setq kwd (and (or recursive (= l1 ltoggle))
11581 (match-string 2)))
11582 (if (or (eq org-provide-todo-statistics 'all-headlines)
11583 (and (listp org-provide-todo-statistics)
11584 (or (member kwd org-provide-todo-statistics)
11585 (member kwd org-done-keywords))))
11586 (setq cnt-all (1+ cnt-all))
11587 (if (eq org-provide-todo-statistics t)
11588 (and kwd (setq cnt-all (1+ cnt-all)))))
11589 (and (member kwd org-done-keywords)
11590 (setq cnt-done (1+ cnt-done)))
11591 (outline-next-heading)))
11592 (setq new
11593 (if is-percent
11594 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11595 (format "[%d/%d]" cnt-done cnt-all))
11596 ndel (- (match-end 0) checkbox-beg))
11597 ;; handle overlays when updating cookie from column view
11598 (when (setq ov (car (overlays-at checkbox-beg)))
11599 (setq ovs (overlay-start ov) ove (overlay-end ov))
11600 (delete-overlay ov))
11601 (goto-char checkbox-beg)
11602 (insert new)
11603 (delete-region (point) (+ (point) ndel))
11604 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11605 (when ov (move-overlay ov ovs ove)))
11606 (when cookie-present
11607 (run-hook-with-args 'org-after-todo-statistics-hook
11608 cnt-done (- cnt-all cnt-done))))))
11609 (run-hooks 'org-todo-statistics-hook)))
11611 (defvar org-after-todo-statistics-hook nil
11612 "Hook that is called after a TODO statistics cookie has been updated.
11613 Each function is called with two arguments: the number of not-done entries
11614 and the number of done entries.
11616 For example, the following function, when added to this hook, will switch
11617 an entry to DONE when all children are done, and back to TODO when new
11618 entries are set to a TODO status. Note that this hook is only called
11619 when there is a statistics cookie in the headline!
11621 (defun org-summary-todo (n-done n-not-done)
11622 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11623 (let (org-log-done org-log-states) ; turn off logging
11624 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11627 (defvar org-todo-statistics-hook nil
11628 "Hook that is run whenever Org thinks TODO statistics should be updated.
11629 This hook runs even if there is no statistics cookie present, in which case
11630 `org-after-todo-statistics-hook' would not run.")
11632 (defun org-todo-trigger-tag-changes (state)
11633 "Apply the changes defined in `org-todo-state-tags-triggers'."
11634 (let ((l org-todo-state-tags-triggers)
11635 changes)
11636 (when (or (not state) (equal state ""))
11637 (setq changes (append changes (cdr (assoc "" l)))))
11638 (when (and (stringp state) (> (length state) 0))
11639 (setq changes (append changes (cdr (assoc state l)))))
11640 (when (member state org-not-done-keywords)
11641 (setq changes (append changes (cdr (assoc 'todo l)))))
11642 (when (member state org-done-keywords)
11643 (setq changes (append changes (cdr (assoc 'done l)))))
11644 (dolist (c changes)
11645 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11647 (defun org-local-logging (value)
11648 "Get logging settings from a property VALUE."
11649 (let* (words w a)
11650 ;; directly set the variables, they are already local.
11651 (setq org-log-done nil
11652 org-log-repeat nil
11653 org-todo-log-states nil)
11654 (setq words (org-split-string value))
11655 (while (setq w (pop words))
11656 (cond
11657 ((setq a (assoc w org-startup-options))
11658 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11659 (set (nth 1 a) (nth 2 a))))
11660 ((setq a (org-extract-log-state-settings w))
11661 (and (member (car a) org-todo-keywords-1)
11662 (push a org-todo-log-states)))))))
11664 (defun org-get-todo-sequence-head (kwd)
11665 "Return the head of the TODO sequence to which KWD belongs.
11666 If KWD is not set, check if there is a text property remembering the
11667 right sequence."
11668 (let (p)
11669 (cond
11670 ((not kwd)
11671 (or (get-text-property (point-at-bol) 'org-todo-head)
11672 (progn
11673 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11674 nil (point-at-eol)))
11675 (get-text-property p 'org-todo-head))))
11676 ((not (member kwd org-todo-keywords-1))
11677 (car org-todo-keywords-1))
11678 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11680 (defun org-fast-todo-selection ()
11681 "Fast TODO keyword selection with single keys.
11682 Returns the new TODO keyword, or nil if no state change should occur."
11683 (let* ((fulltable org-todo-key-alist)
11684 (done-keywords org-done-keywords) ;; needed for the faces.
11685 (maxlen (apply 'max (mapcar
11686 (lambda (x)
11687 (if (stringp (car x)) (string-width (car x)) 0))
11688 fulltable)))
11689 (expert nil)
11690 (fwidth (+ maxlen 3 1 3))
11691 (ncol (/ (- (window-width) 4) fwidth))
11692 tg cnt e c tbl
11693 groups ingroup)
11694 (save-excursion
11695 (save-window-excursion
11696 (if expert
11697 (set-buffer (get-buffer-create " *Org todo*"))
11698 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11699 (erase-buffer)
11700 (org-set-local 'org-done-keywords done-keywords)
11701 (setq tbl fulltable cnt 0)
11702 (while (setq e (pop tbl))
11703 (cond
11704 ((equal e '(:startgroup))
11705 (push '() groups) (setq ingroup t)
11706 (when (not (= cnt 0))
11707 (setq cnt 0)
11708 (insert "\n"))
11709 (insert "{ "))
11710 ((equal e '(:endgroup))
11711 (setq ingroup nil cnt 0)
11712 (insert "}\n"))
11713 ((equal e '(:newline))
11714 (when (not (= cnt 0))
11715 (setq cnt 0)
11716 (insert "\n")
11717 (setq e (car tbl))
11718 (while (equal (car tbl) '(:newline))
11719 (insert "\n")
11720 (setq tbl (cdr tbl)))))
11722 (setq tg (car e) c (cdr e))
11723 (if ingroup (push tg (car groups)))
11724 (setq tg (org-add-props tg nil 'face
11725 (org-get-todo-face tg)))
11726 (if (and (= cnt 0) (not ingroup)) (insert " "))
11727 (insert "[" c "] " tg (make-string
11728 (- fwidth 4 (length tg)) ?\ ))
11729 (when (= (setq cnt (1+ cnt)) ncol)
11730 (insert "\n")
11731 (if ingroup (insert " "))
11732 (setq cnt 0)))))
11733 (insert "\n")
11734 (goto-char (point-min))
11735 (if (not expert) (org-fit-window-to-buffer))
11736 (message "[a-z..]:Set [SPC]:clear")
11737 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11738 (cond
11739 ((or (= c ?\C-g)
11740 (and (= c ?q) (not (rassoc c fulltable))))
11741 (setq quit-flag t))
11742 ((= c ?\ ) nil)
11743 ((setq e (rassoc c fulltable) tg (car e))
11745 (t (setq quit-flag t)))))))
11747 (defun org-entry-is-todo-p ()
11748 (member (org-get-todo-state) org-not-done-keywords))
11750 (defun org-entry-is-done-p ()
11751 (member (org-get-todo-state) org-done-keywords))
11753 (defun org-get-todo-state ()
11754 (save-excursion
11755 (org-back-to-heading t)
11756 (and (looking-at org-todo-line-regexp)
11757 (match-end 2)
11758 (match-string 2))))
11760 (defun org-at-date-range-p (&optional inactive-ok)
11761 "Is the cursor inside a date range?"
11762 (interactive)
11763 (save-excursion
11764 (catch 'exit
11765 (let ((pos (point)))
11766 (skip-chars-backward "^[<\r\n")
11767 (skip-chars-backward "<[")
11768 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11769 (>= (match-end 0) pos)
11770 (throw 'exit t))
11771 (skip-chars-backward "^<[\r\n")
11772 (skip-chars-backward "<[")
11773 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11774 (>= (match-end 0) pos)
11775 (throw 'exit t)))
11776 nil)))
11778 (defun org-get-repeat (&optional tagline)
11779 "Check if there is a deadline/schedule with repeater in this entry."
11780 (save-match-data
11781 (save-excursion
11782 (org-back-to-heading t)
11783 (and (re-search-forward (if tagline
11784 (concat tagline "\\s-*" org-repeat-re)
11785 org-repeat-re)
11786 (org-entry-end-position) t)
11787 (match-string-no-properties 1)))))
11789 (defvar org-last-changed-timestamp)
11790 (defvar org-last-inserted-timestamp)
11791 (defvar org-log-post-message)
11792 (defvar org-log-note-purpose)
11793 (defvar org-log-note-how)
11794 (defvar org-log-note-extra)
11795 (defun org-auto-repeat-maybe (done-word)
11796 "Check if the current headline contains a repeated deadline/schedule.
11797 If yes, set TODO state back to what it was and change the base date
11798 of repeating deadline/scheduled time stamps to new date.
11799 This function is run automatically after each state change to a DONE state."
11800 ;; last-state is dynamically scoped into this function
11801 (let* ((repeat (org-get-repeat))
11802 (aa (assoc last-state org-todo-kwd-alist))
11803 (interpret (nth 1 aa))
11804 (head (nth 2 aa))
11805 (whata '(("d" . day) ("m" . month) ("y" . year)))
11806 (msg "Entry repeats: ")
11807 (org-log-done nil)
11808 (org-todo-log-states nil)
11809 re type n what ts time to-state)
11810 (when repeat
11811 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11812 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11813 org-todo-repeat-to-state))
11814 (unless (and to-state (member to-state org-todo-keywords-1))
11815 (setq to-state (if (eq interpret 'type) last-state head)))
11816 (org-todo to-state)
11817 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11818 (org-entry-put nil "LAST_REPEAT" (format-time-string
11819 (org-time-stamp-format t t))))
11820 (when org-log-repeat
11821 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11822 (memq 'org-add-log-note post-command-hook))
11823 ;; OK, we are already setup for some record
11824 (if (eq org-log-repeat 'note)
11825 ;; make sure we take a note, not only a time stamp
11826 (setq org-log-note-how 'note))
11827 ;; Set up for taking a record
11828 (org-add-log-setup 'state (or done-word (car org-done-keywords))
11829 last-state
11830 'findpos org-log-repeat)))
11831 (org-back-to-heading t)
11832 (org-add-planning-info nil nil 'closed)
11833 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11834 org-deadline-time-regexp "\\)\\|\\("
11835 org-ts-regexp "\\)"))
11836 (while (re-search-forward
11837 re (save-excursion (outline-next-heading) (point)) t)
11838 (setq type (if (match-end 1) org-scheduled-string
11839 (if (match-end 3) org-deadline-string "Plain:"))
11840 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
11841 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
11842 (setq n (string-to-number (match-string 2 ts))
11843 what (match-string 3 ts))
11844 (if (equal what "w") (setq n (* n 7) what "d"))
11845 ;; Preparation, see if we need to modify the start date for the change
11846 (when (match-end 1)
11847 (setq time (save-match-data (org-time-string-to-time ts)))
11848 (cond
11849 ((equal (match-string 1 ts) ".")
11850 ;; Shift starting date to today
11851 (org-timestamp-change
11852 (- (org-today) (time-to-days time))
11853 'day))
11854 ((equal (match-string 1 ts) "+")
11855 (let ((nshiftmax 10) (nshift 0))
11856 (while (or (= nshift 0)
11857 (<= (time-to-days time)
11858 (time-to-days (current-time))))
11859 (when (= (incf nshift) nshiftmax)
11860 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
11861 (error "Abort")))
11862 (org-timestamp-change n (cdr (assoc what whata)))
11863 (org-at-timestamp-p t)
11864 (setq ts (match-string 1))
11865 (setq time (save-match-data (org-time-string-to-time ts)))))
11866 (org-timestamp-change (- n) (cdr (assoc what whata)))
11867 ;; rematch, so that we have everything in place for the real shift
11868 (org-at-timestamp-p t)
11869 (setq ts (match-string 1))
11870 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
11871 (org-timestamp-change n (cdr (assoc what whata)))
11872 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
11873 (setq org-log-post-message msg)
11874 (message "%s" msg))))
11876 (defun org-show-todo-tree (arg)
11877 "Make a compact tree which shows all headlines marked with TODO.
11878 The tree will show the lines where the regexp matches, and all higher
11879 headlines above the match.
11880 With a \\[universal-argument] prefix, prompt for a regexp to match.
11881 With a numeric prefix N, construct a sparse tree for the Nth element
11882 of `org-todo-keywords-1'."
11883 (interactive "P")
11884 (let ((case-fold-search nil)
11885 (kwd-re
11886 (cond ((null arg) org-not-done-regexp)
11887 ((equal arg '(4))
11888 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
11889 (mapcar 'list org-todo-keywords-1))))
11890 (concat "\\("
11891 (mapconcat 'identity (org-split-string kwd "|") "\\|")
11892 "\\)\\>")))
11893 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
11894 (regexp-quote (nth (1- (prefix-numeric-value arg))
11895 org-todo-keywords-1)))
11896 (t (error "Invalid prefix argument: %s" arg)))))
11897 (message "%d TODO entries found"
11898 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
11900 (defun org-deadline (&optional remove time)
11901 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
11902 With argument REMOVE, remove any deadline from the item.
11903 With argument TIME, set the deadline at the corresponding date. TIME
11904 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
11905 (interactive "P")
11906 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11907 (let (org-loop-over-headlines-in-active-region)
11908 (org-map-entries
11909 `(org-deadline ',remove ,time) org-loop-over-headlines-in-active-region 'region (if (outline-invisible-p) (org-end-of-subtree nil t))))
11910 (let* ((old-date (org-entry-get nil "DEADLINE"))
11911 (repeater (and old-date
11912 (string-match
11913 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
11914 old-date)
11915 (match-string 1 old-date))))
11916 (if remove
11917 (progn
11918 (when (and old-date org-log-redeadline)
11919 (org-add-log-setup 'deldeadline nil old-date 'findpos
11920 org-log-redeadline))
11921 (org-remove-timestamp-with-keyword org-deadline-string)
11922 (message "Item no longer has a deadline."))
11923 (org-add-planning-info 'deadline time 'closed)
11924 (when (and old-date org-log-redeadline
11925 (not (equal old-date
11926 (substring org-last-inserted-timestamp 1 -1))))
11927 (org-add-log-setup 'redeadline nil old-date 'findpos
11928 org-log-redeadline))
11929 (when repeater
11930 (save-excursion
11931 (org-back-to-heading t)
11932 (when (re-search-forward (concat org-deadline-string " "
11933 org-last-inserted-timestamp)
11934 (save-excursion
11935 (outline-next-heading) (point)) t)
11936 (goto-char (1- (match-end 0)))
11937 (insert " " repeater)
11938 (setq org-last-inserted-timestamp
11939 (concat (substring org-last-inserted-timestamp 0 -1)
11940 " " repeater
11941 (substring org-last-inserted-timestamp -1))))))
11942 (message "Deadline on %s" org-last-inserted-timestamp)))))
11944 (defun org-schedule (&optional remove time)
11945 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
11946 With argument REMOVE, remove any scheduling date from the item.
11947 With argument TIME, scheduled at the corresponding date. TIME can
11948 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
11949 (interactive "P")
11950 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11951 (let (org-loop-over-headlines-in-active-region)
11952 (org-map-entries
11953 `(org-schedule ',remove ,time) org-loop-over-headlines-in-active-region 'region (if (outline-invisible-p) (org-end-of-subtree nil t))))
11954 (let* ((old-date (org-entry-get nil "SCHEDULED"))
11955 (repeater (and old-date
11956 (string-match
11957 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
11958 old-date)
11959 (match-string 1 old-date))))
11960 (if remove
11961 (progn
11962 (when (and old-date org-log-reschedule)
11963 (org-add-log-setup 'delschedule nil old-date 'findpos
11964 org-log-reschedule))
11965 (org-remove-timestamp-with-keyword org-scheduled-string)
11966 (message "Item is no longer scheduled."))
11967 (org-add-planning-info 'scheduled time 'closed)
11968 (when (and old-date org-log-reschedule
11969 (not (equal old-date
11970 (substring org-last-inserted-timestamp 1 -1))))
11971 (org-add-log-setup 'reschedule nil old-date 'findpos
11972 org-log-reschedule))
11973 (when repeater
11974 (save-excursion
11975 (org-back-to-heading t)
11976 (when (re-search-forward (concat org-scheduled-string " "
11977 org-last-inserted-timestamp)
11978 (save-excursion
11979 (outline-next-heading) (point)) t)
11980 (goto-char (1- (match-end 0)))
11981 (insert " " repeater)
11982 (setq org-last-inserted-timestamp
11983 (concat (substring org-last-inserted-timestamp 0 -1)
11984 " " repeater
11985 (substring org-last-inserted-timestamp -1))))))
11986 (message "Scheduled to %s" org-last-inserted-timestamp)))))
11988 (defun org-get-scheduled-time (pom &optional inherit)
11989 "Get the scheduled time as a time tuple, of a format suitable
11990 for calling org-schedule with, or if there is no scheduling,
11991 returns nil."
11992 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
11993 (when time
11994 (apply 'encode-time (org-parse-time-string time)))))
11996 (defun org-get-deadline-time (pom &optional inherit)
11997 "Get the deadline as a time tuple, of a format suitable for
11998 calling org-deadline with, or if there is no scheduling, returns
11999 nil."
12000 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12001 (when time
12002 (apply 'encode-time (org-parse-time-string time)))))
12004 (defun org-remove-timestamp-with-keyword (keyword)
12005 "Remove all time stamps with KEYWORD in the current entry."
12006 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12007 beg)
12008 (save-excursion
12009 (org-back-to-heading t)
12010 (setq beg (point))
12011 (outline-next-heading)
12012 (while (re-search-backward re beg t)
12013 (replace-match "")
12014 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12015 (equal (char-before) ?\ ))
12016 (backward-delete-char 1)
12017 (if (string-match "^[ \t]*$" (buffer-substring
12018 (point-at-bol) (point-at-eol)))
12019 (delete-region (point-at-bol)
12020 (min (point-max) (1+ (point-at-eol))))))))))
12022 (defun org-add-planning-info (what &optional time &rest remove)
12023 "Insert new timestamp with keyword in the line directly after the headline.
12024 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12025 If non is given, the user is prompted for a date.
12026 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12027 be removed."
12028 (interactive)
12029 (let (org-time-was-given org-end-time-was-given ts
12030 end default-time default-input)
12032 (catch 'exit
12033 (when (and (memq what '(scheduled deadline))
12034 (or (not time)
12035 (and (stringp time)
12036 (string-match "^[-+]+[0-9]" time))))
12037 ;; Try to get a default date/time from existing timestamp
12038 (save-excursion
12039 (org-back-to-heading t)
12040 (setq end (save-excursion (outline-next-heading) (point)))
12041 (when (re-search-forward (if (eq what 'scheduled)
12042 org-scheduled-time-regexp
12043 org-deadline-time-regexp)
12044 end t)
12045 (setq ts (match-string 1)
12046 default-time
12047 (apply 'encode-time (org-parse-time-string ts))
12048 default-input (and ts (org-get-compact-tod ts))))))
12049 (when what
12050 (setq time
12051 (if (and (stringp time)
12052 (string-match "^[-+]+[0-9]" time))
12053 ;; This is a relative time, set the proper date
12054 (apply 'encode-time
12055 (org-read-date-analyze
12056 time default-time (decode-time default-time)))
12057 ;; If necessary, get the time from the user
12058 (or time (org-read-date nil 'to-time nil nil
12059 default-time default-input)))))
12061 (when (and org-insert-labeled-timestamps-at-point
12062 (member what '(scheduled deadline)))
12063 (insert
12064 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12065 (org-insert-time-stamp time org-time-was-given
12066 nil nil nil (list org-end-time-was-given))
12067 (setq what nil))
12068 (save-excursion
12069 (save-restriction
12070 (let (col list elt ts buffer-invisibility-spec)
12071 (org-back-to-heading t)
12072 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12073 (goto-char (match-end 1))
12074 (setq col (current-column))
12075 (goto-char (match-end 0))
12076 (if (eobp) (insert "\n") (forward-char 1))
12077 (when (and (not what)
12078 (not (looking-at
12079 (concat "[ \t]*"
12080 org-keyword-time-not-clock-regexp))))
12081 ;; Nothing to add, nothing to remove...... :-)
12082 (throw 'exit nil))
12083 (if (and (not (looking-at org-outline-regexp))
12084 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12085 "[^\r\n]*"))
12086 (not (equal (match-string 1) org-clock-string)))
12087 (narrow-to-region (match-beginning 0) (match-end 0))
12088 (insert-before-markers "\n")
12089 (backward-char 1)
12090 (narrow-to-region (point) (point))
12091 (and org-adapt-indentation (org-indent-to-column col)))
12092 ;; Check if we have to remove something.
12093 (setq list (cons what remove))
12094 (while list
12095 (setq elt (pop list))
12096 (when (or (and (eq elt 'scheduled)
12097 (re-search-forward org-scheduled-time-regexp nil t))
12098 (and (eq elt 'deadline)
12099 (re-search-forward org-deadline-time-regexp nil t))
12100 (and (eq elt 'closed)
12101 (re-search-forward org-closed-time-regexp nil t)))
12102 (replace-match "")
12103 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12104 (and (looking-at "[ \t]+") (replace-match ""))
12105 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12106 (when what
12107 (insert
12108 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12109 (cond ((eq what 'scheduled) org-scheduled-string)
12110 ((eq what 'deadline) org-deadline-string)
12111 ((eq what 'closed) org-closed-string))
12112 " ")
12113 (setq ts (org-insert-time-stamp
12114 time
12115 (or org-time-was-given
12116 (and (eq what 'closed) org-log-done-with-time))
12117 (eq what 'closed)
12118 nil nil (list org-end-time-was-given)))
12119 (insert
12120 (if (not (or (bolp) (eq (char-before) ?\ )
12121 (memq (char-after) '(32 10))
12122 (eobp))) " " ""))
12123 (end-of-line 1))
12124 (goto-char (point-min))
12125 (widen)
12126 (if (and (looking-at "[ \t]*\n")
12127 (equal (char-before) ?\n))
12128 (delete-region (1- (point)) (point-at-eol)))
12129 ts))))))
12131 (defvar org-log-note-marker (make-marker))
12132 (defvar org-log-note-purpose nil)
12133 (defvar org-log-note-state nil)
12134 (defvar org-log-note-previous-state nil)
12135 (defvar org-log-note-how nil)
12136 (defvar org-log-note-extra nil)
12137 (defvar org-log-note-window-configuration nil)
12138 (defvar org-log-note-return-to (make-marker))
12139 (defvar org-log-note-effective-time nil
12140 "Remembered current time so that dynamically scoped
12141 `org-extend-today-until' affects tha timestamps in state change
12142 log")
12144 (defvar org-log-post-message nil
12145 "Message to be displayed after a log note has been stored.
12146 The auto-repeater uses this.")
12148 (defun org-add-note ()
12149 "Add a note to the current entry.
12150 This is done in the same way as adding a state change note."
12151 (interactive)
12152 (org-add-log-setup 'note nil nil 'findpos nil))
12154 (defvar org-property-end-re)
12155 (defun org-add-log-setup (&optional purpose state prev-state
12156 findpos how extra)
12157 "Set up the post command hook to take a note.
12158 If this is about to TODO state change, the new state is expected in STATE.
12159 When FINDPOS is non-nil, find the correct position for the note in
12160 the current entry. If not, assume that it can be inserted at point.
12161 HOW is an indicator what kind of note should be created.
12162 EXTRA is additional text that will be inserted into the notes buffer."
12163 (let* ((org-log-into-drawer (org-log-into-drawer))
12164 (drawer (cond ((stringp org-log-into-drawer)
12165 org-log-into-drawer)
12166 (org-log-into-drawer "LOGBOOK")
12167 (t nil))))
12168 (save-restriction
12169 (save-excursion
12170 (when findpos
12171 (org-back-to-heading t)
12172 (narrow-to-region (point) (save-excursion
12173 (outline-next-heading) (point)))
12174 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12175 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12176 "[^\r\n]*\\)?"))
12177 (goto-char (match-end 0))
12178 (cond
12179 (drawer
12180 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12181 nil t)
12182 (progn
12183 (goto-char (match-end 0))
12184 (or org-log-states-order-reversed
12185 (and (re-search-forward org-property-end-re nil t)
12186 (goto-char (1- (match-beginning 0))))))
12187 (insert "\n:" drawer ":\n:END:")
12188 (beginning-of-line 0)
12189 (org-indent-line-function)
12190 (beginning-of-line 2)
12191 (org-indent-line-function)
12192 (end-of-line 0)))
12193 ((and org-log-state-notes-insert-after-drawers
12194 (save-excursion
12195 (forward-line) (looking-at org-drawer-regexp)))
12196 (forward-line)
12197 (while (looking-at org-drawer-regexp)
12198 (goto-char (match-end 0))
12199 (re-search-forward org-property-end-re (point-max) t)
12200 (forward-line))
12201 (forward-line -1)))
12202 (unless org-log-states-order-reversed
12203 (and (= (char-after) ?\n) (forward-char 1))
12204 (org-skip-over-state-notes)
12205 (skip-chars-backward " \t\n\r")))
12206 (move-marker org-log-note-marker (point))
12207 (setq org-log-note-purpose purpose
12208 org-log-note-state state
12209 org-log-note-previous-state prev-state
12210 org-log-note-how how
12211 org-log-note-extra extra
12212 org-log-note-effective-time (org-current-effective-time))
12213 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12215 (defun org-skip-over-state-notes ()
12216 "Skip past the list of State notes in an entry."
12217 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12218 (when (ignore-errors (goto-char (org-in-item-p)))
12219 (let* ((struct (org-list-struct))
12220 (prevs (org-list-prevs-alist struct)))
12221 (while (looking-at "[ \t]*- State")
12222 (goto-char (or (org-list-get-next-item (point) struct prevs)
12223 (org-list-get-item-end (point) struct)))))))
12225 (defun org-add-log-note (&optional purpose)
12226 "Pop up a window for taking a note, and add this note later at point."
12227 (remove-hook 'post-command-hook 'org-add-log-note)
12228 (setq org-log-note-window-configuration (current-window-configuration))
12229 (delete-other-windows)
12230 (move-marker org-log-note-return-to (point))
12231 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12232 (goto-char org-log-note-marker)
12233 (org-switch-to-buffer-other-window "*Org Note*")
12234 (erase-buffer)
12235 (if (memq org-log-note-how '(time state))
12236 (let (current-prefix-arg) (org-store-log-note))
12237 (let ((org-inhibit-startup t)) (org-mode))
12238 (insert (format "# Insert note for %s.
12239 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12240 (cond
12241 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12242 ((eq org-log-note-purpose 'done) "closed todo item")
12243 ((eq org-log-note-purpose 'state)
12244 (format "state change from \"%s\" to \"%s\""
12245 (or org-log-note-previous-state "")
12246 (or org-log-note-state "")))
12247 ((eq org-log-note-purpose 'reschedule)
12248 "rescheduling")
12249 ((eq org-log-note-purpose 'delschedule)
12250 "no longer scheduled")
12251 ((eq org-log-note-purpose 'redeadline)
12252 "changing deadline")
12253 ((eq org-log-note-purpose 'deldeadline)
12254 "removing deadline")
12255 ((eq org-log-note-purpose 'refile)
12256 "refiling")
12257 ((eq org-log-note-purpose 'note)
12258 "this entry")
12259 (t (error "This should not happen")))))
12260 (if org-log-note-extra (insert org-log-note-extra))
12261 (org-set-local 'org-finish-function 'org-store-log-note)
12262 (run-hooks 'org-log-buffer-setup-hook)))
12264 (defvar org-note-abort nil) ; dynamically scoped
12265 (defun org-store-log-note ()
12266 "Finish taking a log note, and insert it to where it belongs."
12267 (let ((txt (buffer-string))
12268 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12269 lines ind bul)
12270 (kill-buffer (current-buffer))
12271 (while (string-match "\\`#.*\n[ \t\n]*" txt)
12272 (setq txt (replace-match "" t t txt)))
12273 (if (string-match "\\s-+\\'" txt)
12274 (setq txt (replace-match "" t t txt)))
12275 (setq lines (org-split-string txt "\n"))
12276 (when (and note (string-match "\\S-" note))
12277 (setq note
12278 (org-replace-escapes
12279 note
12280 (list (cons "%u" (user-login-name))
12281 (cons "%U" user-full-name)
12282 (cons "%t" (format-time-string
12283 (org-time-stamp-format 'long 'inactive)
12284 org-log-note-effective-time))
12285 (cons "%T" (format-time-string
12286 (org-time-stamp-format 'long nil)
12287 org-log-note-effective-time))
12288 (cons "%d" (format-time-string
12289 (org-time-stamp-format nil 'inactive)
12290 org-log-note-effective-time))
12291 (cons "%D" (format-time-string
12292 (org-time-stamp-format nil nil)
12293 org-log-note-effective-time))
12294 (cons "%s" (if org-log-note-state
12295 (concat "\"" org-log-note-state "\"")
12296 ""))
12297 (cons "%S" (if org-log-note-previous-state
12298 (concat "\"" org-log-note-previous-state "\"")
12299 "\"\"")))))
12300 (if lines (setq note (concat note " \\\\")))
12301 (push note lines))
12302 (when (or current-prefix-arg org-note-abort)
12303 (when org-log-into-drawer
12304 (org-remove-empty-drawer-at
12305 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12306 org-log-note-marker))
12307 (setq lines nil))
12308 (when lines
12309 (with-current-buffer (marker-buffer org-log-note-marker)
12310 (save-excursion
12311 (goto-char org-log-note-marker)
12312 (move-marker org-log-note-marker nil)
12313 (end-of-line 1)
12314 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12315 (setq ind (save-excursion
12316 (if (ignore-errors (goto-char (org-in-item-p)))
12317 (let ((struct (org-list-struct)))
12318 (org-list-get-ind
12319 (org-list-get-top-point struct) struct))
12320 (skip-chars-backward " \r\t\n")
12321 (cond
12322 ((and (org-at-heading-p)
12323 org-adapt-indentation)
12324 (1+ (org-current-level)))
12325 ((org-at-heading-p) 0)
12326 (t (org-get-indentation))))))
12327 (setq bul (org-list-bullet-string "-"))
12328 (org-indent-line-to ind)
12329 (insert bul (pop lines))
12330 (let ((ind-body (+ (length bul) ind)))
12331 (while lines
12332 (insert "\n")
12333 (org-indent-line-to ind-body)
12334 (insert (pop lines))))
12335 (message "Note stored")
12336 (org-back-to-heading t)
12337 (org-cycle-hide-drawers 'children)))))
12338 (set-window-configuration org-log-note-window-configuration)
12339 (with-current-buffer (marker-buffer org-log-note-return-to)
12340 (goto-char org-log-note-return-to))
12341 (move-marker org-log-note-return-to nil)
12342 (and org-log-post-message (message "%s" org-log-post-message)))
12344 (defun org-remove-empty-drawer-at (drawer pos)
12345 "Remove an empty drawer DRAWER at position POS.
12346 POS may also be a marker."
12347 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12348 (save-excursion
12349 (save-restriction
12350 (widen)
12351 (goto-char pos)
12352 (if (org-in-regexp
12353 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12354 (replace-match ""))))))
12356 (defun org-sparse-tree (&optional arg)
12357 "Create a sparse tree, prompt for the details.
12358 This command can create sparse trees. You first need to select the type
12359 of match used to create the tree:
12361 t Show all TODO entries.
12362 T Show entries with a specific TODO keyword.
12363 m Show entries selected by a tags/property match.
12364 p Enter a property name and its value (both with completion on existing
12365 names/values) and show entries with that property.
12366 r Show entries matching a regular expression (`/' can be used as well)
12367 d Show deadlines due within `org-deadline-warning-days'.
12368 b Show deadlines and scheduled items before a date.
12369 a Show deadlines and scheduled items after a date."
12370 (interactive "P")
12371 (let (ans kwd value)
12372 (message "Sparse tree: [r]egexp [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty\n [d]eadlines [b]efore-date [a]fter-date")
12373 (setq ans (read-char-exclusive))
12374 (cond
12375 ((equal ans ?d)
12376 (call-interactively 'org-check-deadlines))
12377 ((equal ans ?b)
12378 (call-interactively 'org-check-before-date))
12379 ((equal ans ?a)
12380 (call-interactively 'org-check-after-date))
12381 ((equal ans ?t)
12382 (org-show-todo-tree nil))
12383 ((equal ans ?T)
12384 (org-show-todo-tree '(4)))
12385 ((member ans '(?T ?m))
12386 (call-interactively 'org-match-sparse-tree))
12387 ((member ans '(?p ?P))
12388 (setq kwd (org-icompleting-read "Property: "
12389 (mapcar 'list (org-buffer-property-keys))))
12390 (setq value (org-icompleting-read "Value: "
12391 (mapcar 'list (org-property-values kwd))))
12392 (unless (string-match "\\`{.*}\\'" value)
12393 (setq value (concat "\"" value "\"")))
12394 (org-match-sparse-tree arg (concat kwd "=" value)))
12395 ((member ans '(?r ?R ?/))
12396 (call-interactively 'org-occur))
12397 (t (error "No such sparse tree command \"%c\"" ans)))))
12399 (defvar org-occur-highlights nil
12400 "List of overlays used for occur matches.")
12401 (make-variable-buffer-local 'org-occur-highlights)
12402 (defvar org-occur-parameters nil
12403 "Parameters of the active org-occur calls.
12404 This is a list, each call to org-occur pushes as cons cell,
12405 containing the regular expression and the callback, onto the list.
12406 The list can contain several entries if `org-occur' has been called
12407 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12408 will only contain one set of parameters. When the highlights are
12409 removed (for example with `C-c C-c', or with the next edit (depending
12410 on `org-remove-highlights-with-change'), this variable is emptied
12411 as well.")
12412 (make-variable-buffer-local 'org-occur-parameters)
12414 (defun org-occur (regexp &optional keep-previous callback)
12415 "Make a compact tree which shows all matches of REGEXP.
12416 The tree will show the lines where the regexp matches, and all higher
12417 headlines above the match. It will also show the heading after the match,
12418 to make sure editing the matching entry is easy.
12419 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12420 call to `org-occur' will be kept, to allow stacking of calls to this
12421 command.
12422 If CALLBACK is non-nil, it is a function which is called to confirm
12423 that the match should indeed be shown."
12424 (interactive "sRegexp: \nP")
12425 (when (equal regexp "")
12426 (error "Regexp cannot be empty"))
12427 (unless keep-previous
12428 (org-remove-occur-highlights nil nil t))
12429 (push (cons regexp callback) org-occur-parameters)
12430 (let ((cnt 0))
12431 (save-excursion
12432 (goto-char (point-min))
12433 (if (or (not keep-previous) ; do not want to keep
12434 (not org-occur-highlights)) ; no previous matches
12435 ;; hide everything
12436 (org-overview))
12437 (while (re-search-forward regexp nil t)
12438 (when (or (not callback)
12439 (save-match-data (funcall callback)))
12440 (setq cnt (1+ cnt))
12441 (when org-highlight-sparse-tree-matches
12442 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12443 (org-show-context 'occur-tree))))
12444 (when org-remove-highlights-with-change
12445 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12446 nil 'local))
12447 (unless org-sparse-tree-open-archived-trees
12448 (org-hide-archived-subtrees (point-min) (point-max)))
12449 (run-hooks 'org-occur-hook)
12450 (if (org-called-interactively-p 'interactive)
12451 (message "%d match(es) for regexp %s" cnt regexp))
12452 cnt))
12454 (defun org-occur-next-match (&optional n reset)
12455 "Function for `next-error-function' to find sparse tree matches.
12456 N is the number of matches to move, when negative move backwards.
12457 RESET is entirely ignored - this function always goes back to the
12458 starting point when no match is found."
12459 (let* ((limit (if (< n 0) (point-min) (point-max)))
12460 (search-func (if (< n 0)
12461 'previous-single-char-property-change
12462 'next-single-char-property-change))
12463 (n (abs n))
12464 (pos (point))
12466 (catch 'exit
12467 (while (setq p1 (funcall search-func (point) 'org-type))
12468 (when (equal p1 limit)
12469 (goto-char pos)
12470 (error "No more matches"))
12471 (when (equal (get-char-property p1 'org-type) 'org-occur)
12472 (setq n (1- n))
12473 (when (= n 0)
12474 (goto-char p1)
12475 (throw 'exit (point))))
12476 (goto-char p1))
12477 (goto-char p1)
12478 (error "No more matches"))))
12480 (defun org-show-context (&optional key)
12481 "Make sure point and context are visible.
12482 How much context is shown depends upon the variables
12483 `org-show-hierarchy-above', `org-show-following-heading'. and
12484 `org-show-siblings'."
12485 (let ((heading-p (org-on-heading-p t))
12486 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12487 (following-p (org-get-alist-option org-show-following-heading key))
12488 (entry-p (org-get-alist-option org-show-entry-below key))
12489 (siblings-p (org-get-alist-option org-show-siblings key)))
12490 (catch 'exit
12491 ;; Show heading or entry text
12492 (if (and heading-p (not entry-p))
12493 (org-flag-heading nil) ; only show the heading
12494 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12495 (org-show-hidden-entry))) ; show entire entry
12496 (when following-p
12497 ;; Show next sibling, or heading below text
12498 (save-excursion
12499 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12500 (org-flag-heading nil))))
12501 (when siblings-p (org-show-siblings))
12502 (when hierarchy-p
12503 ;; show all higher headings, possibly with siblings
12504 (save-excursion
12505 (while (and (condition-case nil
12506 (progn (org-up-heading-all 1) t)
12507 (error nil))
12508 (not (bobp)))
12509 (org-flag-heading nil)
12510 (when siblings-p (org-show-siblings))))))))
12512 (defvar org-reveal-start-hook nil
12513 "Hook run before revealing a location.")
12515 (defun org-reveal (&optional siblings)
12516 "Show current entry, hierarchy above it, and the following headline.
12517 This can be used to show a consistent set of context around locations
12518 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12519 not t for the search context.
12521 With optional argument SIBLINGS, on each level of the hierarchy all
12522 siblings are shown. This repairs the tree structure to what it would
12523 look like when opened with hierarchical calls to `org-cycle'.
12524 With double optional argument \\[universal-argument] \\[universal-argument], \
12525 go to the parent and show the
12526 entire tree."
12527 (interactive "P")
12528 (run-hooks 'org-reveal-start-hook)
12529 (let ((org-show-hierarchy-above t)
12530 (org-show-following-heading t)
12531 (org-show-siblings (if siblings t org-show-siblings)))
12532 (org-show-context nil))
12533 (when (equal siblings '(16))
12534 (save-excursion
12535 (when (org-up-heading-safe)
12536 (org-show-subtree)
12537 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12539 (defun org-highlight-new-match (beg end)
12540 "Highlight from BEG to END and mark the highlight is an occur headline."
12541 (let ((ov (make-overlay beg end)))
12542 (overlay-put ov 'face 'secondary-selection)
12543 (overlay-put ov 'org-type 'org-occur)
12544 (push ov org-occur-highlights)))
12546 (defun org-remove-occur-highlights (&optional beg end noremove)
12547 "Remove the occur highlights from the buffer.
12548 BEG and END are ignored. If NOREMOVE is nil, remove this function
12549 from the `before-change-functions' in the current buffer."
12550 (interactive)
12551 (unless org-inhibit-highlight-removal
12552 (mapc 'delete-overlay org-occur-highlights)
12553 (setq org-occur-highlights nil)
12554 (setq org-occur-parameters nil)
12555 (unless noremove
12556 (remove-hook 'before-change-functions
12557 'org-remove-occur-highlights 'local))))
12559 ;;;; Priorities
12561 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12562 "Regular expression matching the priority indicator.")
12564 (defvar org-remove-priority-next-time nil)
12566 (defun org-priority-up ()
12567 "Increase the priority of the current item."
12568 (interactive)
12569 (org-priority 'up))
12571 (defun org-priority-down ()
12572 "Decrease the priority of the current item."
12573 (interactive)
12574 (org-priority 'down))
12576 (defun org-priority (&optional action)
12577 "Change the priority of an item by ARG.
12578 ACTION can be `set', `up', `down', or a character."
12579 (interactive)
12580 (unless org-enable-priority-commands
12581 (error "Priority commands are disabled"))
12582 (setq action (or action 'set))
12583 (let (current new news have remove)
12584 (save-excursion
12585 (org-back-to-heading t)
12586 (if (looking-at org-priority-regexp)
12587 (setq current (string-to-char (match-string 2))
12588 have t))
12589 (cond
12590 ((eq action 'remove)
12591 (setq remove t new ?\ ))
12592 ((or (eq action 'set)
12593 (if (featurep 'xemacs) (characterp action) (integerp action)))
12594 (if (not (eq action 'set))
12595 (setq new action)
12596 (message "Priority %c-%c, SPC to remove: "
12597 org-highest-priority org-lowest-priority)
12598 (save-match-data
12599 (setq new (read-char-exclusive))))
12600 (if (and (= (upcase org-highest-priority) org-highest-priority)
12601 (= (upcase org-lowest-priority) org-lowest-priority))
12602 (setq new (upcase new)))
12603 (cond ((equal new ?\ ) (setq remove t))
12604 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12605 (error "Priority must be between `%c' and `%c'"
12606 org-highest-priority org-lowest-priority))))
12607 ((eq action 'up)
12608 (setq new (if have
12609 (1- current) ; normal cycling
12610 ;; last priority was empty
12611 (if (eq last-command this-command)
12612 org-lowest-priority ; wrap around empty to lowest
12613 ;; default
12614 (if org-priority-start-cycle-with-default
12615 org-default-priority
12616 (1- org-default-priority))))))
12617 ((eq action 'down)
12618 (setq new (if have
12619 (1+ current) ; normal cycling
12620 ;; last priority was empty
12621 (if (eq last-command this-command)
12622 org-highest-priority ; wrap around empty to highest
12623 ;; default
12624 (if org-priority-start-cycle-with-default
12625 org-default-priority
12626 (1+ org-default-priority))))))
12627 (t (error "Invalid action")))
12628 (if (or (< (upcase new) org-highest-priority)
12629 (> (upcase new) org-lowest-priority))
12630 (if (and (memq action '(up down))
12631 (not have) (not (eq last-command this-command)))
12632 ;; `new' is from default priority
12633 (error
12634 "The default can not be set, see `org-default-priority' why")
12635 ;; normal cycling: `new' is beyond highest/lowest priority
12636 ;; and is wrapped around to the empty priority
12637 (setq remove t)))
12638 (setq news (format "%c" new))
12639 (if have
12640 (if remove
12641 (replace-match "" t t nil 1)
12642 (replace-match news t t nil 2))
12643 (if remove
12644 (error "No priority cookie found in line")
12645 (let ((case-fold-search nil))
12646 (looking-at org-todo-line-regexp))
12647 (if (match-end 2)
12648 (progn
12649 (goto-char (match-end 2))
12650 (insert " [#" news "]"))
12651 (goto-char (match-beginning 3))
12652 (insert "[#" news "] "))))
12653 (org-preserve-lc (org-set-tags nil 'align)))
12654 (if remove
12655 (message "Priority removed")
12656 (message "Priority of current item set to %s" news))))
12658 (defun org-get-priority (s)
12659 "Find priority cookie and return priority."
12660 (if (functionp org-get-priority-function)
12661 (funcall org-get-priority-function)
12662 (save-match-data
12663 (if (not (string-match org-priority-regexp s))
12664 (* 1000 (- org-lowest-priority org-default-priority))
12665 (* 1000 (- org-lowest-priority
12666 (string-to-char (match-string 2 s))))))))
12668 ;;;; Tags
12670 (defvar org-agenda-archives-mode)
12671 (defvar org-map-continue-from nil
12672 "Position from where mapping should continue.
12673 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
12675 (defvar org-scanner-tags nil
12676 "The current tag list while the tags scanner is running.")
12677 (defvar org-trust-scanner-tags nil
12678 "Should `org-get-tags-at' use the tags for the scanner.
12679 This is for internal dynamical scoping only.
12680 When this is non-nil, the function `org-get-tags-at' will return the value
12681 of `org-scanner-tags' instead of building the list by itself. This
12682 can lead to large speed-ups when the tags scanner is used in a file with
12683 many entries, and when the list of tags is retrieved, for example to
12684 obtain a list of properties. Building the tags list for each entry in such
12685 a file becomes an N^2 operation - but with this variable set, it scales
12686 as N.")
12688 (defun org-scan-tags (action matcher &optional todo-only)
12689 "Scan headline tags with inheritance and produce output ACTION.
12691 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12692 or `agenda' to produce an entry list for an agenda view. It can also be
12693 a Lisp form or a function that should be called at each matched headline, in
12694 this case the return value is a list of all return values from these calls.
12696 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12697 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12698 only lines with a TODO keyword are included in the output."
12699 (require 'org-agenda)
12700 (let* ((re (concat "^" org-outline-regexp " *\\(\\<\\("
12701 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12702 (org-re
12703 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
12704 (props (list 'face 'default
12705 'done-face 'org-agenda-done
12706 'undone-face 'default
12707 'mouse-face 'highlight
12708 'org-not-done-regexp org-not-done-regexp
12709 'org-todo-regexp org-todo-regexp
12710 'org-complex-heading-regexp org-complex-heading-regexp
12711 'help-echo
12712 (format "mouse-2 or RET jump to org file %s"
12713 (abbreviate-file-name
12714 (or (buffer-file-name (buffer-base-buffer))
12715 (buffer-name (buffer-base-buffer)))))))
12716 (case-fold-search nil)
12717 (org-map-continue-from nil)
12718 lspos tags tags-list
12719 (tags-alist (list (cons 0 org-file-tags)))
12720 (llast 0) rtn rtn1 level category i txt
12721 todo marker entry priority)
12722 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12723 (setq action (list 'lambda nil action)))
12724 (save-excursion
12725 (goto-char (point-min))
12726 (when (eq action 'sparse-tree)
12727 (org-overview)
12728 (org-remove-occur-highlights))
12729 (while (re-search-forward re nil t)
12730 (catch :skip
12731 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12732 tags (if (match-end 4) (org-match-string-no-properties 4)))
12733 (goto-char (setq lspos (match-beginning 0)))
12734 (setq level (org-reduced-level (funcall outline-level))
12735 category (org-get-category))
12736 (setq i llast llast level)
12737 ;; remove tag lists from same and sublevels
12738 (while (>= i level)
12739 (when (setq entry (assoc i tags-alist))
12740 (setq tags-alist (delete entry tags-alist)))
12741 (setq i (1- i)))
12742 ;; add the next tags
12743 (when tags
12744 (setq tags (org-split-string tags ":")
12745 tags-alist
12746 (cons (cons level tags) tags-alist)))
12747 ;; compile tags for current headline
12748 (setq tags-list
12749 (if org-use-tag-inheritance
12750 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12751 tags)
12752 org-scanner-tags tags-list)
12753 (when org-use-tag-inheritance
12754 (setcdr (car tags-alist)
12755 (mapcar (lambda (x)
12756 (setq x (copy-sequence x))
12757 (org-add-prop-inherited x))
12758 (cdar tags-alist))))
12759 (when (and tags org-use-tag-inheritance
12760 (or (not (eq t org-use-tag-inheritance))
12761 org-tags-exclude-from-inheritance))
12762 ;; selective inheritance, remove uninherited ones
12763 (setcdr (car tags-alist)
12764 (org-remove-uninherited-tags (cdar tags-alist))))
12765 (when (and
12767 ;; eval matcher only when the todo condition is OK
12768 (and (or (not todo-only) (member todo org-not-done-keywords))
12769 (let ((case-fold-search t)) (eval matcher)))
12771 ;; Call the skipper, but return t if it does not skip,
12772 ;; so that the `and' form continues evaluating
12773 (progn
12774 (unless (eq action 'sparse-tree) (org-agenda-skip))
12777 ;; Check if timestamps are deselecting this entry
12778 (or (not todo-only)
12779 (and (member todo org-not-done-keywords)
12780 (or (not org-agenda-tags-todo-honor-ignore-options)
12781 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
12783 ;; Extra check for the archive tag
12784 ;; FIXME: Does the skipper already do this????
12786 (not (member org-archive-tag tags-list))
12787 ;; we have an archive tag, should we use this anyway?
12788 (or (not org-agenda-skip-archived-trees)
12789 (and (eq action 'agenda) org-agenda-archives-mode))))
12791 ;; select this headline
12793 (cond
12794 ((eq action 'sparse-tree)
12795 (and org-highlight-sparse-tree-matches
12796 (org-get-heading) (match-end 0)
12797 (org-highlight-new-match
12798 (match-beginning 0) (match-beginning 1)))
12799 (org-show-context 'tags-tree))
12800 ((eq action 'agenda)
12801 (setq txt (org-agenda-format-item
12803 (concat
12804 (if (eq org-tags-match-list-sublevels 'indented)
12805 (make-string (1- level) ?.) "")
12806 (org-get-heading))
12807 category
12808 tags-list
12810 priority (org-get-priority txt))
12811 (goto-char lspos)
12812 (setq marker (org-agenda-new-marker))
12813 (org-add-props txt props
12814 'org-marker marker 'org-hd-marker marker 'org-category category
12815 'todo-state todo
12816 'priority priority 'type "tagsmatch")
12817 (push txt rtn))
12818 ((functionp action)
12819 (setq org-map-continue-from nil)
12820 (save-excursion
12821 (setq rtn1 (funcall action))
12822 (push rtn1 rtn)))
12823 (t (error "Invalid action")))
12825 ;; if we are to skip sublevels, jump to end of subtree
12826 (unless org-tags-match-list-sublevels
12827 (org-end-of-subtree t)
12828 (backward-char 1))))
12829 ;; Get the correct position from where to continue
12830 (if org-map-continue-from
12831 (goto-char org-map-continue-from)
12832 (and (= (point) lspos) (end-of-line 1)))))
12833 (when (and (eq action 'sparse-tree)
12834 (not org-sparse-tree-open-archived-trees))
12835 (org-hide-archived-subtrees (point-min) (point-max)))
12836 (nreverse rtn)))
12838 (defun org-remove-uninherited-tags (tags)
12839 "Remove all tags that are not inherited from the list TAGS."
12840 (cond
12841 ((eq org-use-tag-inheritance t)
12842 (if org-tags-exclude-from-inheritance
12843 (org-delete-all org-tags-exclude-from-inheritance tags)
12844 tags))
12845 ((not org-use-tag-inheritance) nil)
12846 ((stringp org-use-tag-inheritance)
12847 (delq nil (mapcar
12848 (lambda (x)
12849 (if (and (string-match org-use-tag-inheritance x)
12850 (not (member x org-tags-exclude-from-inheritance)))
12851 x nil))
12852 tags)))
12853 ((listp org-use-tag-inheritance)
12854 (delq nil (mapcar
12855 (lambda (x)
12856 (if (member x org-use-tag-inheritance) x nil))
12857 tags)))))
12859 (defvar todo-only) ;; dynamically scoped
12861 (defun org-match-sparse-tree (&optional todo-only match)
12862 "Create a sparse tree according to tags string MATCH.
12863 MATCH can contain positive and negative selection of tags, like
12864 \"+WORK+URGENT-WITHBOSS\".
12865 If optional argument TODO-ONLY is non-nil, only select lines that are
12866 also TODO lines."
12867 (interactive "P")
12868 (org-prepare-agenda-buffers (list (current-buffer)))
12869 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
12871 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
12873 (defvar org-cached-props nil)
12874 (defun org-cached-entry-get (pom property)
12875 (if (or (eq t org-use-property-inheritance)
12876 (and (stringp org-use-property-inheritance)
12877 (string-match org-use-property-inheritance property))
12878 (and (listp org-use-property-inheritance)
12879 (member property org-use-property-inheritance)))
12880 ;; Caching is not possible, check it directly
12881 (org-entry-get pom property 'inherit)
12882 ;; Get all properties, so that we can do complicated checks easily
12883 (cdr (assoc property (or org-cached-props
12884 (setq org-cached-props
12885 (org-entry-properties pom)))))))
12887 (defun org-global-tags-completion-table (&optional files)
12888 "Return the list of all tags in all agenda buffer/files.
12889 Optional FILES argument is a list of files to which can be used
12890 instead of the agenda files."
12891 (save-excursion
12892 (org-uniquify
12893 (delq nil
12894 (apply 'append
12895 (mapcar
12896 (lambda (file)
12897 (set-buffer (find-file-noselect file))
12898 (append (org-get-buffer-tags)
12899 (mapcar (lambda (x) (if (stringp (car-safe x))
12900 (list (car-safe x)) nil))
12901 org-tag-alist)))
12902 (if (and files (car files))
12903 files
12904 (org-agenda-files))))))))
12906 (defun org-make-tags-matcher (match)
12907 "Create the TAGS/TODO matcher form for the selection string MATCH."
12908 ;; todo-only is scoped dynamically into this function, and the function
12909 ;; may change it if the matcher asks for it.
12910 (unless match
12911 ;; Get a new match request, with completion
12912 (let ((org-last-tags-completion-table
12913 (org-global-tags-completion-table)))
12914 (setq match (org-completing-read-no-i
12915 "Match: " 'org-tags-completion-function nil nil nil
12916 'org-tags-history))))
12918 ;; Parse the string and create a lisp form
12919 (let ((match0 match)
12920 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
12921 minus tag mm
12922 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
12923 orterms term orlist re-p str-p level-p level-op time-p
12924 prop-p pn pv po gv rest)
12925 (if (string-match "/+" match)
12926 ;; match contains also a todo-matching request
12927 (progn
12928 (setq tagsmatch (substring match 0 (match-beginning 0))
12929 todomatch (substring match (match-end 0)))
12930 (if (string-match "^!" todomatch)
12931 (setq todo-only t todomatch (substring todomatch 1)))
12932 (if (string-match "^\\s-*$" todomatch)
12933 (setq todomatch nil)))
12934 ;; only matching tags
12935 (setq tagsmatch match todomatch nil))
12937 ;; Make the tags matcher
12938 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
12939 (setq tagsmatcher t)
12940 (setq orterms (org-split-string tagsmatch "|") orlist nil)
12941 (while (setq term (pop orterms))
12942 (while (and (equal (substring term -1) "\\") orterms)
12943 (setq term (concat term "|" (pop orterms)))) ; repair bad split
12944 (while (string-match re term)
12945 (setq rest (substring term (match-end 0))
12946 minus (and (match-end 1)
12947 (equal (match-string 1 term) "-"))
12948 tag (save-match-data (replace-regexp-in-string
12949 "\\\\-" "-"
12950 (match-string 2 term)))
12951 re-p (equal (string-to-char tag) ?{)
12952 level-p (match-end 4)
12953 prop-p (match-end 5)
12954 mm (cond
12955 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
12956 (level-p
12957 (setq level-op (org-op-to-function (match-string 3 term)))
12958 `(,level-op level ,(string-to-number
12959 (match-string 4 term))))
12960 (prop-p
12961 (setq pn (match-string 5 term)
12962 po (match-string 6 term)
12963 pv (match-string 7 term)
12964 re-p (equal (string-to-char pv) ?{)
12965 str-p (equal (string-to-char pv) ?\")
12966 time-p (save-match-data
12967 (string-match "^\"[[<].*[]>]\"$" pv))
12968 pv (if (or re-p str-p) (substring pv 1 -1) pv))
12969 (if time-p (setq pv (org-matcher-time pv)))
12970 (setq po (org-op-to-function po (if time-p 'time str-p)))
12971 (cond
12972 ((equal pn "CATEGORY")
12973 (setq gv '(get-text-property (point) 'org-category)))
12974 ((equal pn "TODO")
12975 (setq gv 'todo))
12977 (setq gv `(org-cached-entry-get nil ,pn))))
12978 (if re-p
12979 (if (eq po 'org<>)
12980 `(not (string-match ,pv (or ,gv "")))
12981 `(string-match ,pv (or ,gv "")))
12982 (if str-p
12983 `(,po (or ,gv "") ,pv)
12984 `(,po (string-to-number (or ,gv ""))
12985 ,(string-to-number pv) ))))
12986 (t `(member ,tag tags-list)))
12987 mm (if minus (list 'not mm) mm)
12988 term rest)
12989 (push mm tagsmatcher))
12990 (push (if (> (length tagsmatcher) 1)
12991 (cons 'and tagsmatcher)
12992 (car tagsmatcher))
12993 orlist)
12994 (setq tagsmatcher nil))
12995 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
12996 (setq tagsmatcher
12997 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
12998 ;; Make the todo matcher
12999 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13000 (setq todomatcher t)
13001 (setq orterms (org-split-string todomatch "|") orlist nil)
13002 (while (setq term (pop orterms))
13003 (while (string-match re term)
13004 (setq minus (and (match-end 1)
13005 (equal (match-string 1 term) "-"))
13006 kwd (match-string 2 term)
13007 re-p (equal (string-to-char kwd) ?{)
13008 term (substring term (match-end 0))
13009 mm (if re-p
13010 `(string-match ,(substring kwd 1 -1) todo)
13011 (list 'equal 'todo kwd))
13012 mm (if minus (list 'not mm) mm))
13013 (push mm todomatcher))
13014 (push (if (> (length todomatcher) 1)
13015 (cons 'and todomatcher)
13016 (car todomatcher))
13017 orlist)
13018 (setq todomatcher nil))
13019 (setq todomatcher (if (> (length orlist) 1)
13020 (cons 'or orlist) (car orlist))))
13022 ;; Return the string and lisp forms of the matcher
13023 (setq matcher (if todomatcher
13024 (list 'and tagsmatcher todomatcher)
13025 tagsmatcher))
13026 (cons match0 matcher)))
13028 (defun org-op-to-function (op &optional stringp)
13029 "Turn an operator into the appropriate function."
13030 (setq op
13031 (cond
13032 ((equal op "<" ) '(< string< org-time<))
13033 ((equal op ">" ) '(> org-string> org-time>))
13034 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13035 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13036 ((member op '("=" "==")) '(= string= org-time=))
13037 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13038 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13040 (defun org<> (a b) (not (= a b)))
13041 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13042 (defun org-string>= (a b) (not (string< a b)))
13043 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13044 (defun org-string<> (a b) (not (string= a b)))
13045 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13046 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13047 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13048 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13049 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13050 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13051 (defun org-2ft (s)
13052 "Convert S to a floating point time.
13053 If S is already a number, just return it. If it is a string, parse
13054 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13055 (cond
13056 ((numberp s) s)
13057 ((stringp s)
13058 (condition-case nil
13059 (float-time (apply 'encode-time (org-parse-time-string s)))
13060 (error 0.)))
13061 (t 0.)))
13063 (defun org-time-today ()
13064 "Time in seconds today at 0:00.
13065 Returns the float number of seconds since the beginning of the
13066 epoch to the beginning of today (00:00)."
13067 (float-time (apply 'encode-time
13068 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13070 (defun org-matcher-time (s)
13071 "Interpret a time comparison value."
13072 (save-match-data
13073 (cond
13074 ((string= s "<now>") (float-time))
13075 ((string= s "<today>") (org-time-today))
13076 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13077 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13078 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
13079 (+ (org-time-today)
13080 (* (string-to-number (match-string 1 s))
13081 (cdr (assoc (match-string 2 s)
13082 '(("d" . 86400.0) ("w" . 604800.0)
13083 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13084 (t (org-2ft s)))))
13086 (defun org-match-any-p (re list)
13087 "Does re match any element of list?"
13088 (setq list (mapcar (lambda (x) (string-match re x)) list))
13089 (delq nil list))
13091 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13092 (defvar org-tags-overlay (make-overlay 1 1))
13093 (org-detach-overlay org-tags-overlay)
13095 (defun org-get-local-tags-at (&optional pos)
13096 "Get a list of tags defined in the current headline."
13097 (org-get-tags-at pos 'local))
13099 (defun org-get-local-tags ()
13100 "Get a list of tags defined in the current headline."
13101 (org-get-tags-at nil 'local))
13103 (defun org-get-tags-at (&optional pos local)
13104 "Get a list of all headline tags applicable at POS.
13105 POS defaults to point. If tags are inherited, the list contains
13106 the targets in the same sequence as the headlines appear, i.e.
13107 the tags of the current headline come last.
13108 When LOCAL is non-nil, only return tags from the current headline,
13109 ignore inherited ones."
13110 (interactive)
13111 (if (and org-trust-scanner-tags
13112 (or (not pos) (equal pos (point)))
13113 (not local))
13114 org-scanner-tags
13115 (let (tags ltags lastpos parent)
13116 (save-excursion
13117 (save-restriction
13118 (widen)
13119 (goto-char (or pos (point)))
13120 (save-match-data
13121 (catch 'done
13122 (condition-case nil
13123 (progn
13124 (org-back-to-heading t)
13125 (while (not (equal lastpos (point)))
13126 (setq lastpos (point))
13127 (when (looking-at
13128 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13129 (setq ltags (org-split-string
13130 (org-match-string-no-properties 1) ":"))
13131 (when parent
13132 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13133 (setq tags (append
13134 (if parent
13135 (org-remove-uninherited-tags ltags)
13136 ltags)
13137 tags)))
13138 (or org-use-tag-inheritance (throw 'done t))
13139 (if local (throw 'done t))
13140 (or (org-up-heading-safe) (error nil))
13141 (setq parent t)))
13142 (error nil)))))
13143 (if local
13144 tags
13145 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13147 (defun org-add-prop-inherited (s)
13148 (add-text-properties 0 (length s) '(inherited t) s)
13151 (defun org-toggle-tag (tag &optional onoff)
13152 "Toggle the tag TAG for the current line.
13153 If ONOFF is `on' or `off', don't toggle but set to this state."
13154 (let (res current)
13155 (save-excursion
13156 (org-back-to-heading t)
13157 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13158 (point-at-eol) t)
13159 (progn
13160 (setq current (match-string 1))
13161 (replace-match ""))
13162 (setq current ""))
13163 (setq current (nreverse (org-split-string current ":")))
13164 (cond
13165 ((eq onoff 'on)
13166 (setq res t)
13167 (or (member tag current) (push tag current)))
13168 ((eq onoff 'off)
13169 (or (not (member tag current)) (setq current (delete tag current))))
13170 (t (if (member tag current)
13171 (setq current (delete tag current))
13172 (setq res t)
13173 (push tag current))))
13174 (end-of-line 1)
13175 (if current
13176 (progn
13177 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13178 (org-set-tags nil t))
13179 (delete-horizontal-space))
13180 (run-hooks 'org-after-tags-change-hook))
13181 res))
13183 (defun org-align-tags-here (to-col)
13184 ;; Assumes that this is a headline
13185 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13186 (beginning-of-line 1)
13187 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13188 (< pos (match-beginning 2)))
13189 (progn
13190 (setq tags-l (- (match-end 2) (match-beginning 2)))
13191 (goto-char (match-beginning 1))
13192 (insert " ")
13193 (delete-region (point) (1+ (match-beginning 2)))
13194 (setq ncol (max (current-column)
13195 (1+ col)
13196 (if (> to-col 0)
13197 to-col
13198 (- (abs to-col) tags-l))))
13199 (setq p (point))
13200 (insert (make-string (- ncol (current-column)) ?\ ))
13201 (setq ncol (current-column))
13202 (when indent-tabs-mode (tabify p (point-at-eol)))
13203 (org-move-to-column (min ncol col) t))
13204 (goto-char pos))))
13206 (defun org-set-tags-command (&optional arg just-align)
13207 "Call the set-tags command for the current entry."
13208 (interactive "P")
13209 (if (org-on-heading-p)
13210 (org-set-tags arg just-align)
13211 (save-excursion
13212 (org-back-to-heading t)
13213 (org-set-tags arg just-align))))
13215 (defun org-set-tags-to (data)
13216 "Set the tags of the current entry to DATA, replacing the current tags.
13217 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13218 If DATA is nil or the empty string, any tags will be removed."
13219 (interactive "sTags: ")
13220 (setq data
13221 (cond
13222 ((eq data nil) "")
13223 ((equal data "") "")
13224 ((stringp data)
13225 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13226 ":"))
13227 ((listp data)
13228 (concat ":" (mapconcat 'identity data ":") ":"))
13229 (t nil)))
13230 (when data
13231 (save-excursion
13232 (org-back-to-heading t)
13233 (when (looking-at org-complex-heading-regexp)
13234 (if (match-end 5)
13235 (progn
13236 (goto-char (match-beginning 5))
13237 (insert data)
13238 (delete-region (point) (point-at-eol))
13239 (org-set-tags nil 'align))
13240 (goto-char (point-at-eol))
13241 (insert " " data)
13242 (org-set-tags nil 'align)))
13243 (beginning-of-line 1)
13244 (if (looking-at ".*?\\([ \t]+\\)$")
13245 (delete-region (match-beginning 1) (match-end 1))))))
13247 (defun org-align-all-tags ()
13248 "Align the tags i all headings."
13249 (interactive)
13250 (save-excursion
13251 (or (ignore-errors (org-back-to-heading t))
13252 (outline-next-heading))
13253 (if (org-on-heading-p)
13254 (org-set-tags t)
13255 (message "No headings"))))
13257 (defvar org-indent-indentation-per-level)
13258 (defun org-set-tags (&optional arg just-align)
13259 "Set the tags for the current headline.
13260 With prefix ARG, realign all tags in headings in the current buffer."
13261 (interactive "P")
13262 (let* ((re org-outline-regexp-bol)
13263 (current (org-get-tags-string))
13264 (col (current-column))
13265 (org-setting-tags t)
13266 table current-tags inherited-tags ; computed below when needed
13267 tags p0 c0 c1 rpl di tc level)
13268 (if arg
13269 (save-excursion
13270 (goto-char (point-min))
13271 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13272 (while (re-search-forward re nil t)
13273 (org-set-tags nil t)
13274 (end-of-line 1)))
13275 (message "All tags realigned to column %d" org-tags-column))
13276 (if just-align
13277 (setq tags current)
13278 ;; Get a new set of tags from the user
13279 (save-excursion
13280 (setq table (append org-tag-persistent-alist
13281 (or org-tag-alist (org-get-buffer-tags))
13282 (and
13283 org-complete-tags-always-offer-all-agenda-tags
13284 (org-global-tags-completion-table
13285 (org-agenda-files))))
13286 org-last-tags-completion-table table
13287 current-tags (org-split-string current ":")
13288 inherited-tags (nreverse
13289 (nthcdr (length current-tags)
13290 (nreverse (org-get-tags-at))))
13291 tags
13292 (if (or (eq t org-use-fast-tag-selection)
13293 (and org-use-fast-tag-selection
13294 (delq nil (mapcar 'cdr table))))
13295 (org-fast-tag-selection
13296 current-tags inherited-tags table
13297 (if org-fast-tag-selection-include-todo
13298 org-todo-key-alist))
13299 (let ((org-add-colon-after-tag-completion t))
13300 (org-trim
13301 (org-icompleting-read "Tags: "
13302 'org-tags-completion-function
13303 nil nil current 'org-tags-history))))))
13304 (while (string-match "[-+&]+" tags)
13305 ;; No boolean logic, just a list
13306 (setq tags (replace-match ":" t t tags))))
13308 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13310 (if org-tags-sort-function
13311 (setq tags (mapconcat 'identity
13312 (sort (org-split-string
13313 tags (org-re "[^[:alnum:]_@#%]+"))
13314 org-tags-sort-function) ":")))
13316 (if (string-match "\\`[\t ]*\\'" tags)
13317 (setq tags "")
13318 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13319 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13321 ;; Insert new tags at the correct column
13322 (beginning-of-line 1)
13323 (setq level (or (and (looking-at org-outline-regexp)
13324 (- (match-end 0) (point) 1))
13326 (cond
13327 ((and (equal current "") (equal tags "")))
13328 ((re-search-forward
13329 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13330 (point-at-eol) t)
13331 (if (equal tags "")
13332 (setq rpl "")
13333 (goto-char (match-beginning 0))
13334 (setq c0 (current-column)
13335 ;; compute offset for the case of org-indent-mode active
13336 di (if org-indent-mode
13337 (* (1- org-indent-indentation-per-level) (1- level))
13339 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13340 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13341 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13342 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13343 (replace-match rpl t t)
13344 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13345 tags)
13346 (t (error "Tags alignment failed")))
13347 (org-move-to-column col)
13348 (unless just-align
13349 (run-hooks 'org-after-tags-change-hook)))))
13351 (defun org-change-tag-in-region (beg end tag off)
13352 "Add or remove TAG for each entry in the region.
13353 This works in the agenda, and also in an org-mode buffer."
13354 (interactive
13355 (list (region-beginning) (region-end)
13356 (let ((org-last-tags-completion-table
13357 (if (eq major-mode 'org-mode)
13358 (org-get-buffer-tags)
13359 (org-global-tags-completion-table))))
13360 (org-icompleting-read
13361 "Tag: " 'org-tags-completion-function nil nil nil
13362 'org-tags-history))
13363 (progn
13364 (message "[s]et or [r]emove? ")
13365 (equal (read-char-exclusive) ?r))))
13366 (if (fboundp 'deactivate-mark) (deactivate-mark))
13367 (let ((agendap (equal major-mode 'org-agenda-mode))
13368 l1 l2 m buf pos newhead (cnt 0))
13369 (goto-char end)
13370 (setq l2 (1- (org-current-line)))
13371 (goto-char beg)
13372 (setq l1 (org-current-line))
13373 (loop for l from l1 to l2 do
13374 (org-goto-line l)
13375 (setq m (get-text-property (point) 'org-hd-marker))
13376 (when (or (and (eq major-mode 'org-mode) (org-on-heading-p))
13377 (and agendap m))
13378 (setq buf (if agendap (marker-buffer m) (current-buffer))
13379 pos (if agendap m (point)))
13380 (with-current-buffer buf
13381 (save-excursion
13382 (save-restriction
13383 (goto-char pos)
13384 (setq cnt (1+ cnt))
13385 (org-toggle-tag tag (if off 'off 'on))
13386 (setq newhead (org-get-heading)))))
13387 (and agendap (org-agenda-change-all-lines newhead m))))
13388 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13390 (defun org-tags-completion-function (string predicate &optional flag)
13391 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13392 (confirm (lambda (x) (stringp (car x)))))
13393 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13394 (setq s1 (match-string 1 string)
13395 s2 (match-string 2 string))
13396 (setq s1 "" s2 string))
13397 (cond
13398 ((eq flag nil)
13399 ;; try completion
13400 (setq rtn (try-completion s2 ctable confirm))
13401 (if (stringp rtn)
13402 (setq rtn
13403 (concat s1 s2 (substring rtn (length s2))
13404 (if (and org-add-colon-after-tag-completion
13405 (assoc rtn ctable))
13406 ":" ""))))
13407 rtn)
13408 ((eq flag t)
13409 ;; all-completions
13410 (all-completions s2 ctable confirm)
13412 ((eq flag 'lambda)
13413 ;; exact match?
13414 (assoc s2 ctable)))
13417 (defun org-fast-tag-insert (kwd tags face &optional end)
13418 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13419 (insert (format "%-12s" (concat kwd ":"))
13420 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13421 (or end "")))
13423 (defun org-fast-tag-show-exit (flag)
13424 (save-excursion
13425 (org-goto-line 3)
13426 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13427 (replace-match ""))
13428 (when flag
13429 (end-of-line 1)
13430 (org-move-to-column (- (window-width) 19) t)
13431 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13433 (defun org-set-current-tags-overlay (current prefix)
13434 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13435 (if (featurep 'xemacs)
13436 (org-overlay-display org-tags-overlay (concat prefix s)
13437 'secondary-selection)
13438 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13439 (org-overlay-display org-tags-overlay (concat prefix s)))))
13441 (defvar org-last-tag-selection-key nil)
13442 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13443 "Fast tag selection with single keys.
13444 CURRENT is the current list of tags in the headline, INHERITED is the
13445 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13446 possibly with grouping information. TODO-TABLE is a similar table with
13447 TODO keywords, should these have keys assigned to them.
13448 If the keys are nil, a-z are automatically assigned.
13449 Returns the new tags string, or nil to not change the current settings."
13450 (let* ((fulltable (append table todo-table))
13451 (maxlen (apply 'max (mapcar
13452 (lambda (x)
13453 (if (stringp (car x)) (string-width (car x)) 0))
13454 fulltable)))
13455 (buf (current-buffer))
13456 (expert (eq org-fast-tag-selection-single-key 'expert))
13457 (buffer-tags nil)
13458 (fwidth (+ maxlen 3 1 3))
13459 (ncol (/ (- (window-width) 4) fwidth))
13460 (i-face 'org-done)
13461 (c-face 'org-todo)
13462 tg cnt e c char c1 c2 ntable tbl rtn
13463 ov-start ov-end ov-prefix
13464 (exit-after-next org-fast-tag-selection-single-key)
13465 (done-keywords org-done-keywords)
13466 groups ingroup)
13467 (save-excursion
13468 (beginning-of-line 1)
13469 (if (looking-at
13470 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13471 (setq ov-start (match-beginning 1)
13472 ov-end (match-end 1)
13473 ov-prefix "")
13474 (setq ov-start (1- (point-at-eol))
13475 ov-end (1+ ov-start))
13476 (skip-chars-forward "^\n\r")
13477 (setq ov-prefix
13478 (concat
13479 (buffer-substring (1- (point)) (point))
13480 (if (> (current-column) org-tags-column)
13482 (make-string (- org-tags-column (current-column)) ?\ ))))))
13483 (move-overlay org-tags-overlay ov-start ov-end)
13484 (save-window-excursion
13485 (if expert
13486 (set-buffer (get-buffer-create " *Org tags*"))
13487 (delete-other-windows)
13488 (split-window-vertically)
13489 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13490 (erase-buffer)
13491 (org-set-local 'org-done-keywords done-keywords)
13492 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13493 (org-fast-tag-insert "Current" current c-face "\n\n")
13494 (org-fast-tag-show-exit exit-after-next)
13495 (org-set-current-tags-overlay current ov-prefix)
13496 (setq tbl fulltable char ?a cnt 0)
13497 (while (setq e (pop tbl))
13498 (cond
13499 ((equal (car e) :startgroup)
13500 (push '() groups) (setq ingroup t)
13501 (when (not (= cnt 0))
13502 (setq cnt 0)
13503 (insert "\n"))
13504 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13505 ((equal (car e) :endgroup)
13506 (setq ingroup nil cnt 0)
13507 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13508 ((equal e '(:newline))
13509 (when (not (= cnt 0))
13510 (setq cnt 0)
13511 (insert "\n")
13512 (setq e (car tbl))
13513 (while (equal (car tbl) '(:newline))
13514 (insert "\n")
13515 (setq tbl (cdr tbl)))))
13517 (setq tg (copy-sequence (car e)) c2 nil)
13518 (if (cdr e)
13519 (setq c (cdr e))
13520 ;; automatically assign a character.
13521 (setq c1 (string-to-char
13522 (downcase (substring
13523 tg (if (= (string-to-char tg) ?@) 1 0)))))
13524 (if (or (rassoc c1 ntable) (rassoc c1 table))
13525 (while (or (rassoc char ntable) (rassoc char table))
13526 (setq char (1+ char)))
13527 (setq c2 c1))
13528 (setq c (or c2 char)))
13529 (if ingroup (push tg (car groups)))
13530 (setq tg (org-add-props tg nil 'face
13531 (cond
13532 ((not (assoc tg table))
13533 (org-get-todo-face tg))
13534 ((member tg current) c-face)
13535 ((member tg inherited) i-face)
13536 (t nil))))
13537 (if (and (= cnt 0) (not ingroup)) (insert " "))
13538 (insert "[" c "] " tg (make-string
13539 (- fwidth 4 (length tg)) ?\ ))
13540 (push (cons tg c) ntable)
13541 (when (= (setq cnt (1+ cnt)) ncol)
13542 (insert "\n")
13543 (if ingroup (insert " "))
13544 (setq cnt 0)))))
13545 (setq ntable (nreverse ntable))
13546 (insert "\n")
13547 (goto-char (point-min))
13548 (if (not expert) (org-fit-window-to-buffer))
13549 (setq rtn
13550 (catch 'exit
13551 (while t
13552 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13553 (if (not groups) "no " "")
13554 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13555 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13556 (setq org-last-tag-selection-key c)
13557 (cond
13558 ((= c ?\r) (throw 'exit t))
13559 ((= c ?!)
13560 (setq groups (not groups))
13561 (goto-char (point-min))
13562 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13563 ((= c ?\C-c)
13564 (if (not expert)
13565 (org-fast-tag-show-exit
13566 (setq exit-after-next (not exit-after-next)))
13567 (setq expert nil)
13568 (delete-other-windows)
13569 (set-window-buffer (split-window-vertically) " *Org tags*")
13570 (org-switch-to-buffer-other-window " *Org tags*")
13571 (org-fit-window-to-buffer)))
13572 ((or (= c ?\C-g)
13573 (and (= c ?q) (not (rassoc c ntable))))
13574 (org-detach-overlay org-tags-overlay)
13575 (setq quit-flag t))
13576 ((= c ?\ )
13577 (setq current nil)
13578 (if exit-after-next (setq exit-after-next 'now)))
13579 ((= c ?\t)
13580 (condition-case nil
13581 (setq tg (org-icompleting-read
13582 "Tag: "
13583 (or buffer-tags
13584 (with-current-buffer buf
13585 (org-get-buffer-tags)))))
13586 (quit (setq tg "")))
13587 (when (string-match "\\S-" tg)
13588 (add-to-list 'buffer-tags (list tg))
13589 (if (member tg current)
13590 (setq current (delete tg current))
13591 (push tg current)))
13592 (if exit-after-next (setq exit-after-next 'now)))
13593 ((setq e (rassoc c todo-table) tg (car e))
13594 (with-current-buffer buf
13595 (save-excursion (org-todo tg)))
13596 (if exit-after-next (setq exit-after-next 'now)))
13597 ((setq e (rassoc c ntable) tg (car e))
13598 (if (member tg current)
13599 (setq current (delete tg current))
13600 (loop for g in groups do
13601 (if (member tg g)
13602 (mapc (lambda (x)
13603 (setq current (delete x current)))
13604 g)))
13605 (push tg current))
13606 (if exit-after-next (setq exit-after-next 'now))))
13608 ;; Create a sorted list
13609 (setq current
13610 (sort current
13611 (lambda (a b)
13612 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13613 (if (eq exit-after-next 'now) (throw 'exit t))
13614 (goto-char (point-min))
13615 (beginning-of-line 2)
13616 (delete-region (point) (point-at-eol))
13617 (org-fast-tag-insert "Current" current c-face)
13618 (org-set-current-tags-overlay current ov-prefix)
13619 (while (re-search-forward
13620 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13621 (setq tg (match-string 1))
13622 (add-text-properties
13623 (match-beginning 1) (match-end 1)
13624 (list 'face
13625 (cond
13626 ((member tg current) c-face)
13627 ((member tg inherited) i-face)
13628 (t (get-text-property (match-beginning 1) 'face))))))
13629 (goto-char (point-min)))))
13630 (org-detach-overlay org-tags-overlay)
13631 (if rtn
13632 (mapconcat 'identity current ":")
13633 nil))))
13635 (defun org-get-tags-string ()
13636 "Get the TAGS string in the current headline."
13637 (unless (org-on-heading-p t)
13638 (error "Not on a heading"))
13639 (save-excursion
13640 (beginning-of-line 1)
13641 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13642 (org-match-string-no-properties 1)
13643 "")))
13645 (defun org-get-tags ()
13646 "Get the list of tags specified in the current headline."
13647 (org-split-string (org-get-tags-string) ":"))
13649 (defun org-get-buffer-tags ()
13650 "Get a table of all tags used in the buffer, for completion."
13651 (let (tags)
13652 (save-excursion
13653 (goto-char (point-min))
13654 (while (re-search-forward
13655 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13656 (when (equal (char-after (point-at-bol 0)) ?*)
13657 (mapc (lambda (x) (add-to-list 'tags x))
13658 (org-split-string (org-match-string-no-properties 1) ":")))))
13659 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13660 (mapcar 'list tags)))
13662 ;;;; The mapping API
13664 ;;;###autoload
13665 (defun org-map-entries (func &optional match scope &rest skip)
13666 "Call FUNC at each headline selected by MATCH in SCOPE.
13668 FUNC is a function or a lisp form. The function will be called without
13669 arguments, with the cursor positioned at the beginning of the headline.
13670 The return values of all calls to the function will be collected and
13671 returned as a list.
13673 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13674 does not need to preserve point. After evaluation, the cursor will be
13675 moved to the end of the line (presumably of the headline of the
13676 processed entry) and search continues from there. Under some
13677 circumstances, this may not produce the wanted results. For example,
13678 if you have removed (e.g. archived) the current (sub)tree it could
13679 mean that the next entry will be skipped entirely. In such cases, you
13680 can specify the position from where search should continue by making
13681 FUNC set the variable `org-map-continue-from' to the desired buffer
13682 position.
13684 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13685 Only headlines that are matched by this query will be considered during
13686 the iteration. When MATCH is nil or t, all headlines will be
13687 visited by the iteration.
13689 SCOPE determines the scope of this command. It can be any of:
13691 nil The current buffer, respecting the restriction if any
13692 tree The subtree started with the entry at point
13693 region The entries within the active region, if any
13694 file The current buffer, without restriction
13695 file-with-archives
13696 The current buffer, and any archives associated with it
13697 agenda All agenda files
13698 agenda-with-archives
13699 All agenda files with any archive files associated with them
13700 \(file1 file2 ...)
13701 If this is a list, all files in the list will be scanned
13703 The remaining args are treated as settings for the skipping facilities of
13704 the scanner. The following items can be given here:
13706 archive skip trees with the archive tag.
13707 comment skip trees with the COMMENT keyword
13708 function or Emacs Lisp form:
13709 will be used as value for `org-agenda-skip-function', so whenever
13710 the function returns t, FUNC will not be called for that
13711 entry and search will continue from the point where the
13712 function leaves it.
13714 If your function needs to retrieve the tags including inherited tags
13715 at the *current* entry, you can use the value of the variable
13716 `org-scanner-tags' which will be much faster than getting the value
13717 with `org-get-tags-at'. If your function gets properties with
13718 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13719 to t around the call to `org-entry-properties' to get the same speedup.
13720 Note that if your function moves around to retrieve tags and properties at
13721 a *different* entry, you cannot use these techniques."
13722 (unless (and (eq scope 'region) (not (org-region-active-p)))
13723 (let* ((org-agenda-archives-mode nil) ; just to make sure
13724 (org-agenda-skip-archived-trees (memq 'archive skip))
13725 (org-agenda-skip-comment-trees (memq 'comment skip))
13726 (org-agenda-skip-function
13727 (car (org-delete-all '(comment archive) skip)))
13728 (org-tags-match-list-sublevels t)
13729 matcher file res
13730 org-todo-keywords-for-agenda
13731 org-done-keywords-for-agenda
13732 org-todo-keyword-alist-for-agenda
13733 org-drawers-for-agenda
13734 org-tag-alist-for-agenda)
13736 (cond
13737 ((eq match t) (setq matcher t))
13738 ((eq match nil) (setq matcher t))
13739 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13741 (save-excursion
13742 (save-restriction
13743 (cond ((eq scope 'tree)
13744 (org-back-to-heading t)
13745 (org-narrow-to-subtree)
13746 (setq scope nil))
13747 ((and (eq scope 'region) (org-region-active-p))
13748 (narrow-to-region (region-beginning)
13749 (save-excursion
13750 (goto-char (region-end))
13751 (unless (and (bolp) (org-at-heading-p))
13752 (outline-next-heading))
13753 (point)))
13754 (setq scope nil)))
13756 (if (not scope)
13757 (progn
13758 (org-prepare-agenda-buffers
13759 (list (buffer-file-name (current-buffer))))
13760 (setq res (org-scan-tags func matcher)))
13761 ;; Get the right scope
13762 (cond
13763 ((and scope (listp scope) (symbolp (car scope)))
13764 (setq scope (eval scope)))
13765 ((eq scope 'agenda)
13766 (setq scope (org-agenda-files t)))
13767 ((eq scope 'agenda-with-archives)
13768 (setq scope (org-agenda-files t))
13769 (setq scope (org-add-archive-files scope)))
13770 ((eq scope 'file)
13771 (setq scope (list (buffer-file-name))))
13772 ((eq scope 'file-with-archives)
13773 (setq scope (org-add-archive-files (list (buffer-file-name))))))
13774 (org-prepare-agenda-buffers scope)
13775 (while (setq file (pop scope))
13776 (with-current-buffer (org-find-base-buffer-visiting file)
13777 (save-excursion
13778 (save-restriction
13779 (widen)
13780 (goto-char (point-min))
13781 (setq res (append res (org-scan-tags func matcher))))))))))
13782 res)))
13784 ;;;; Properties
13786 ;;; Setting and retrieving properties
13788 (defconst org-special-properties
13789 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
13790 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM")
13791 "The special properties valid in Org-mode.
13793 These are properties that are not defined in the property drawer,
13794 but in some other way.")
13796 (defconst org-default-properties
13797 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
13798 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
13799 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
13800 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
13801 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
13802 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
13803 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
13804 "Some properties that are used by Org-mode for various purposes.
13805 Being in this list makes sure that they are offered for completion.")
13807 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
13808 "Regular expression matching the first line of a property drawer.")
13810 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
13811 "Regular expression matching the last line of a property drawer.")
13813 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
13814 "Regular expression matching the first line of a property drawer.")
13816 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
13817 "Regular expression matching the first line of a property drawer.")
13819 (defconst org-property-drawer-re
13820 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
13821 org-property-end-re "\\)\n?")
13822 "Matches an entire property drawer.")
13824 (defconst org-clock-drawer-re
13825 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
13826 org-property-end-re "\\)\n?")
13827 "Matches an entire clock drawer.")
13829 (defsubst org-re-property (property)
13830 "Return a regexp matching PROPERTY.
13831 Match group 1 will be set to the value "
13832 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
13834 (defun org-property-action ()
13835 "Do an action on properties."
13836 (interactive)
13837 (let (c)
13838 (org-at-property-p)
13839 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
13840 (setq c (read-char-exclusive))
13841 (cond
13842 ((equal c ?s)
13843 (call-interactively 'org-set-property))
13844 ((equal c ?d)
13845 (call-interactively 'org-delete-property))
13846 ((equal c ?D)
13847 (call-interactively 'org-delete-property-globally))
13848 ((equal c ?c)
13849 (call-interactively 'org-compute-property-at-point))
13850 (t (error "No such property action %c" c)))))
13852 (defun org-set-effort (&optional value)
13853 "Set the effort property of the current entry.
13854 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
13855 allowed value."
13856 (interactive "P")
13857 (if (equal value 0) (setq value 10))
13858 (let* ((completion-ignore-case t)
13859 (prop org-effort-property)
13860 (cur (org-entry-get nil prop))
13861 (allowed (org-property-get-allowed-values nil prop 'table))
13862 (existing (mapcar 'list (org-property-values prop)))
13864 (val (cond
13865 ((stringp value) value)
13866 ((and allowed (integerp value))
13867 (or (car (nth (1- value) allowed))
13868 (car (org-last allowed))))
13869 (allowed
13870 (message "Select 1-9,0, [RET%s]: %s"
13871 (if cur (concat "=" cur) "")
13872 (mapconcat 'car allowed " "))
13873 (setq rpl (read-char-exclusive))
13874 (if (equal rpl ?\r)
13876 (setq rpl (- rpl ?0))
13877 (if (equal rpl 0) (setq rpl 10))
13878 (if (and (> rpl 0) (<= rpl (length allowed)))
13879 (car (nth (1- rpl) allowed))
13880 (org-completing-read "Effort: " allowed nil))))
13882 (let (org-completion-use-ido org-completion-use-iswitchb)
13883 (org-completing-read
13884 (concat "Effort " (if (and cur (string-match "\\S-" cur))
13885 (concat "[" cur "]") "")
13886 ": ")
13887 existing nil nil "" nil cur))))))
13888 (unless (equal (org-entry-get nil prop) val)
13889 (org-entry-put nil prop val))
13890 (message "%s is now %s" prop val)))
13892 (defun org-at-property-p ()
13893 "Is cursor inside a property drawer?"
13894 (save-excursion
13895 (beginning-of-line 1)
13896 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
13897 (save-match-data ;; Used by calling procedures
13898 (let ((p (point))
13899 (range (unless (org-before-first-heading-p)
13900 (org-get-property-block))))
13901 (and range (<= (car range) p) (< p (cdr range))))))))
13903 (defun org-get-property-block (&optional beg end force)
13904 "Return the (beg . end) range of the body of the property drawer.
13905 BEG and END can be beginning and end of subtree, if not given
13906 they will be found.
13907 If the drawer does not exist and FORCE is non-nil, create the drawer."
13908 (catch 'exit
13909 (save-excursion
13910 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
13911 (end (or end (progn (outline-next-heading) (point)))))
13912 (goto-char beg)
13913 (if (re-search-forward org-property-start-re end t)
13914 (setq beg (1+ (match-end 0)))
13915 (if force
13916 (save-excursion
13917 (org-insert-property-drawer)
13918 (setq end (progn (outline-next-heading) (point))))
13919 (throw 'exit nil))
13920 (goto-char beg)
13921 (if (re-search-forward org-property-start-re end t)
13922 (setq beg (1+ (match-end 0)))))
13923 (if (re-search-forward org-property-end-re end t)
13924 (setq end (match-beginning 0))
13925 (or force (throw 'exit nil))
13926 (goto-char beg)
13927 (setq end beg)
13928 (org-indent-line-function)
13929 (insert ":END:\n"))
13930 (cons beg end)))))
13932 (defun org-entry-properties (&optional pom which specific)
13933 "Get all properties of the entry at point-or-marker POM.
13934 This includes the TODO keyword, the tags, time strings for deadline,
13935 scheduled, and clocking, and any additional properties defined in the
13936 entry. The return value is an alist, keys may occur multiple times
13937 if the property key was used several times.
13938 POM may also be nil, in which case the current entry is used.
13939 If WHICH is nil or `all', get all properties. If WHICH is
13940 `special' or `standard', only get that subclass. If WHICH
13941 is a string only get exactly this property. SPECIFIC can be a string, the
13942 specific property we are interested in. Specifying it can speed
13943 things up because then unnecessary parsing is avoided."
13944 (setq which (or which 'all))
13945 (org-with-point-at pom
13946 (let ((clockstr (substring org-clock-string 0 -1))
13947 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
13948 (case-fold-search nil)
13949 beg end range props sum-props key key1 value string clocksum)
13950 (save-excursion
13951 (when (condition-case nil
13952 (and (eq major-mode 'org-mode) (org-back-to-heading t))
13953 (error nil))
13954 (setq beg (point))
13955 (setq sum-props (get-text-property (point) 'org-summaries))
13956 (setq clocksum (get-text-property (point) :org-clock-minutes))
13957 (outline-next-heading)
13958 (setq end (point))
13959 (when (memq which '(all special))
13960 ;; Get the special properties, like TODO and tags
13961 (goto-char beg)
13962 (when (and (or (not specific) (string= specific "TODO"))
13963 (looking-at org-todo-line-regexp) (match-end 2))
13964 (push (cons "TODO" (org-match-string-no-properties 2)) props))
13965 (when (and (or (not specific) (string= specific "PRIORITY"))
13966 (looking-at org-priority-regexp))
13967 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
13968 (when (or (not specific) (string= specific "FILE"))
13969 (push (cons "FILE" buffer-file-name) props))
13970 (when (and (or (not specific) (string= specific "TAGS"))
13971 (setq value (org-get-tags-string))
13972 (string-match "\\S-" value))
13973 (push (cons "TAGS" value) props))
13974 (when (and (or (not specific) (string= specific "ALLTAGS"))
13975 (setq value (org-get-tags-at)))
13976 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
13977 ":"))
13978 props))
13979 (when (or (not specific) (string= specific "BLOCKED"))
13980 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
13981 (when (or (not specific)
13982 (member specific
13983 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
13984 "TIMESTAMP" "TIMESTAMP_IA")))
13985 (catch 'match
13986 (while (re-search-forward org-maybe-keyword-time-regexp end t)
13987 (setq key (if (match-end 1)
13988 (substring (org-match-string-no-properties 1)
13989 0 -1))
13990 string (if (equal key clockstr)
13991 (org-no-properties
13992 (org-trim
13993 (buffer-substring
13994 (match-beginning 3) (goto-char
13995 (point-at-eol)))))
13996 (substring (org-match-string-no-properties 3)
13997 1 -1)))
13998 ;; Get the correct property name from the key. This is
13999 ;; necessary if the user has configured time keywords.
14000 (setq key1 (concat key ":"))
14001 (cond
14002 ((not key)
14003 (setq key
14004 (if (= (char-after (match-beginning 3)) ?\[)
14005 "TIMESTAMP_IA" "TIMESTAMP")))
14006 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14007 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14008 ((equal key1 org-closed-string) (setq key "CLOSED"))
14009 ((equal key1 org-clock-string) (setq key "CLOCK")))
14010 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14011 (progn
14012 (push (cons key string) props)
14013 ;; no need to search further if match is found
14014 (throw 'match t))
14015 (when (or (equal key "CLOCK") (not (assoc key props)))
14016 (push (cons key string) props))))))
14019 (when (memq which '(all standard))
14020 ;; Get the standard properties, like :PROP: ...
14021 (setq range (org-get-property-block beg end))
14022 (when range
14023 (goto-char (car range))
14024 (while (re-search-forward
14025 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14026 (cdr range) t)
14027 (setq key (org-match-string-no-properties 1)
14028 value (org-trim (or (org-match-string-no-properties 2) "")))
14029 (unless (member key excluded)
14030 (push (cons key (or value "")) props)))))
14031 (if clocksum
14032 (push (cons "CLOCKSUM"
14033 (org-columns-number-to-string (/ (float clocksum) 60.)
14034 'add_times))
14035 props))
14036 (unless (assoc "CATEGORY" props)
14037 (push (cons "CATEGORY" (org-get-category)) props))
14038 (append sum-props (nreverse props)))))))
14040 (defun org-entry-get (pom property &optional inherit literal-nil)
14041 "Get value of PROPERTY for entry at point-or-marker POM.
14042 If INHERIT is non-nil and the entry does not have the property,
14043 then also check higher levels of the hierarchy.
14044 If INHERIT is the symbol `selective', use inheritance only if the setting
14045 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14046 If the property is present but empty, the return value is the empty string.
14047 If the property is not present at all, nil is returned.
14049 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14050 do not interpret it as the list atom nil. This is used for inheritance
14051 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14052 (org-with-point-at pom
14053 (if (and inherit (if (eq inherit 'selective)
14054 (org-property-inherit-p property)
14056 (org-entry-get-with-inheritance property literal-nil)
14057 (if (member property org-special-properties)
14058 ;; We need a special property. Use `org-entry-properties' to
14059 ;; retrieve it, but specify the wanted property
14060 (cdr (assoc property (org-entry-properties nil 'special property)))
14061 (let ((range (unless (org-before-first-heading-p)
14062 (org-get-property-block))))
14063 (if (and range
14064 (goto-char (car range))
14065 (re-search-forward
14066 (org-re-property property)
14067 (cdr range) t))
14068 ;; Found the property, return it.
14069 (if (match-end 1)
14070 (if literal-nil
14071 (org-match-string-no-properties 1)
14072 (org-not-nil (org-match-string-no-properties 1)))
14073 "")))))))
14075 (defun org-property-or-variable-value (var &optional inherit)
14076 "Check if there is a property fixing the value of VAR.
14077 If yes, return this value. If not, return the current value of the variable."
14078 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14079 (if (and prop (stringp prop) (string-match "\\S-" prop))
14080 (read prop)
14081 (symbol-value var))))
14083 (defun org-entry-delete (pom property)
14084 "Delete the property PROPERTY from entry at point-or-marker POM."
14085 (org-with-point-at pom
14086 (if (member property org-special-properties)
14087 nil ; cannot delete these properties.
14088 (let ((range (org-get-property-block)))
14089 (if (and range
14090 (goto-char (car range))
14091 (re-search-forward
14092 (org-re-property property)
14093 (cdr range) t))
14094 (progn
14095 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14097 nil)))))
14099 ;; Multi-values properties are properties that contain multiple values
14100 ;; These values are assumed to be single words, separated by whitespace.
14101 (defun org-entry-add-to-multivalued-property (pom property value)
14102 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14103 (let* ((old (org-entry-get pom property))
14104 (values (and old (org-split-string old "[ \t]"))))
14105 (setq value (org-entry-protect-space value))
14106 (unless (member value values)
14107 (setq values (cons value values))
14108 (org-entry-put pom property
14109 (mapconcat 'identity values " ")))))
14111 (defun org-entry-remove-from-multivalued-property (pom property value)
14112 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14113 (let* ((old (org-entry-get pom property))
14114 (values (and old (org-split-string old "[ \t]"))))
14115 (setq value (org-entry-protect-space value))
14116 (when (member value values)
14117 (setq values (delete value values))
14118 (org-entry-put pom property
14119 (mapconcat 'identity values " ")))))
14121 (defun org-entry-member-in-multivalued-property (pom property value)
14122 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14123 (let* ((old (org-entry-get pom property))
14124 (values (and old (org-split-string old "[ \t]"))))
14125 (setq value (org-entry-protect-space value))
14126 (member value values)))
14128 (defun org-entry-get-multivalued-property (pom property)
14129 "Return a list of values in a multivalued property."
14130 (let* ((value (org-entry-get pom property))
14131 (values (and value (org-split-string value "[ \t]"))))
14132 (mapcar 'org-entry-restore-space values)))
14134 (defun org-entry-put-multivalued-property (pom property &rest values)
14135 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14136 VALUES should be a list of strings. Spaces will be protected."
14137 (org-entry-put pom property
14138 (mapconcat 'org-entry-protect-space values " "))
14139 (let* ((value (org-entry-get pom property))
14140 (values (and value (org-split-string value "[ \t]"))))
14141 (mapcar 'org-entry-restore-space values)))
14143 (defun org-entry-protect-space (s)
14144 "Protect spaces and newline in string S."
14145 (while (string-match " " s)
14146 (setq s (replace-match "%20" t t s)))
14147 (while (string-match "\n" s)
14148 (setq s (replace-match "%0A" t t s)))
14151 (defun org-entry-restore-space (s)
14152 "Restore spaces and newline in string S."
14153 (while (string-match "%20" s)
14154 (setq s (replace-match " " t t s)))
14155 (while (string-match "%0A" s)
14156 (setq s (replace-match "\n" t t s)))
14159 (defvar org-entry-property-inherited-from (make-marker)
14160 "Marker pointing to the entry from where a property was inherited.
14161 Each call to `org-entry-get-with-inheritance' will set this marker to the
14162 location of the entry where the inheritance search matched. If there was
14163 no match, the marker will point nowhere.
14164 Note that also `org-entry-get' calls this function, if the INHERIT flag
14165 is set.")
14167 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14168 "Get entry property, and search higher levels if not present.
14169 The search will stop at the first ancestor which has the property defined.
14170 If the value found is \"nil\", return nil to show that the property
14171 should be considered as undefined (this is the meaning of nil here).
14172 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14173 (move-marker org-entry-property-inherited-from nil)
14174 (let (tmp)
14175 (unless (org-before-first-heading-p)
14176 (save-excursion
14177 (save-restriction
14178 (widen)
14179 (catch 'ex
14180 (while t
14181 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14182 (org-back-to-heading t)
14183 (move-marker org-entry-property-inherited-from (point))
14184 (throw 'ex tmp))
14185 (or (org-up-heading-safe) (throw 'ex nil)))))))
14186 (setq tmp (or tmp
14187 (cdr (assoc property org-file-properties))
14188 (cdr (assoc property org-global-properties))
14189 (cdr (assoc property org-global-properties-fixed))))
14190 (if literal-nil tmp (org-not-nil tmp))))
14192 (defvar org-property-changed-functions nil
14193 "Hook called when the value of a property has changed.
14194 Each hook function should accept two arguments, the name of the property
14195 and the new value.")
14197 (defun org-entry-put (pom property value)
14198 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14199 (org-with-point-at pom
14200 (org-back-to-heading t)
14201 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14202 range)
14203 (cond
14204 ((equal property "TODO")
14205 (when (and (stringp value) (string-match "\\S-" value)
14206 (not (member value org-todo-keywords-1)))
14207 (error "\"%s\" is not a valid TODO state" value))
14208 (if (or (not value)
14209 (not (string-match "\\S-" value)))
14210 (setq value 'none))
14211 (org-todo value)
14212 (org-set-tags nil 'align))
14213 ((equal property "PRIORITY")
14214 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14215 (string-to-char value) ?\ ))
14216 (org-set-tags nil 'align))
14217 ((equal property "SCHEDULED")
14218 (if (re-search-forward org-scheduled-time-regexp end t)
14219 (cond
14220 ((eq value 'earlier) (org-timestamp-change -1 'day))
14221 ((eq value 'later) (org-timestamp-change 1 'day))
14222 (t (call-interactively 'org-schedule)))
14223 (call-interactively 'org-schedule)))
14224 ((equal property "DEADLINE")
14225 (if (re-search-forward org-deadline-time-regexp end t)
14226 (cond
14227 ((eq value 'earlier) (org-timestamp-change -1 'day))
14228 ((eq value 'later) (org-timestamp-change 1 'day))
14229 (t (call-interactively 'org-deadline)))
14230 (call-interactively 'org-deadline)))
14231 ((member property org-special-properties)
14232 (error "The %s property can not yet be set with `org-entry-put'"
14233 property))
14234 (t ; a non-special property
14235 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14236 (setq range (org-get-property-block beg end 'force))
14237 (goto-char (car range))
14238 (if (re-search-forward
14239 (org-re-property property) (cdr range) t)
14240 (progn
14241 (delete-region (match-beginning 0) (match-end 0))
14242 (goto-char (match-beginning 0)))
14243 (goto-char (cdr range))
14244 (insert "\n")
14245 (backward-char 1)
14246 (org-indent-line-function))
14247 (insert ":" property ":")
14248 (and value (insert " " value))
14249 (org-indent-line-function)))))
14250 (run-hook-with-args 'org-property-changed-functions property value)))
14252 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14253 "Get all property keys in the current buffer.
14254 With INCLUDE-SPECIALS, also list the special properties that reflect things
14255 like tags and TODO state.
14256 With INCLUDE-DEFAULTS, also include properties that has special meaning
14257 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14258 and others.
14259 With INCLUDE-COLUMNS, also include property names given in COLUMN
14260 formats in the current buffer."
14261 (let (rtn range cfmt s p)
14262 (save-excursion
14263 (save-restriction
14264 (widen)
14265 (goto-char (point-min))
14266 (while (re-search-forward org-property-start-re nil t)
14267 (setq range (org-get-property-block))
14268 (goto-char (car range))
14269 (while (re-search-forward
14270 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14271 (cdr range) t)
14272 (add-to-list 'rtn (org-match-string-no-properties 1)))
14273 (outline-next-heading))))
14275 (when include-specials
14276 (setq rtn (append org-special-properties rtn)))
14278 (when include-defaults
14279 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14280 (add-to-list 'rtn org-effort-property))
14282 (when include-columns
14283 (save-excursion
14284 (save-restriction
14285 (widen)
14286 (goto-char (point-min))
14287 (while (re-search-forward
14288 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14289 nil t)
14290 (setq cfmt (match-string 2) s 0)
14291 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14292 cfmt s)
14293 (setq s (match-end 0)
14294 p (match-string 1 cfmt))
14295 (unless (or (equal p "ITEM")
14296 (member p org-special-properties))
14297 (add-to-list 'rtn (match-string 1 cfmt))))))))
14299 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14301 (defun org-property-values (key)
14302 "Return a list of all values of property KEY in the current buffer."
14303 (save-excursion
14304 (save-restriction
14305 (widen)
14306 (goto-char (point-min))
14307 (let ((re (org-re-property key))
14308 values)
14309 (while (re-search-forward re nil t)
14310 (add-to-list 'values (org-trim (match-string 1))))
14311 (delete "" values)))))
14313 (defun org-insert-property-drawer ()
14314 "Insert a property drawer into the current entry."
14315 (interactive)
14316 (org-back-to-heading t)
14317 (looking-at org-outline-regexp)
14318 (let ((indent (if org-adapt-indentation
14319 (- (match-end 0)(match-beginning 0))
14321 (beg (point))
14322 (re (concat "^[ \t]*" org-keyword-time-regexp))
14323 end hiddenp)
14324 (outline-next-heading)
14325 (setq end (point))
14326 (goto-char beg)
14327 (while (re-search-forward re end t))
14328 (setq hiddenp (outline-invisible-p))
14329 (end-of-line 1)
14330 (and (equal (char-after) ?\n) (forward-char 1))
14331 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14332 (if (member (match-string 1) '("CLOCK:" ":END:"))
14333 ;; just skip this line
14334 (beginning-of-line 2)
14335 ;; Drawer start, find the end
14336 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14337 (beginning-of-line 1)))
14338 (org-skip-over-state-notes)
14339 (skip-chars-backward " \t\n\r")
14340 (if (eq (char-before) ?*) (forward-char 1))
14341 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14342 (beginning-of-line 0)
14343 (org-indent-to-column indent)
14344 (beginning-of-line 2)
14345 (org-indent-to-column indent)
14346 (beginning-of-line 0)
14347 (if hiddenp
14348 (save-excursion
14349 (org-back-to-heading t)
14350 (hide-entry))
14351 (org-flag-drawer t))))
14353 (defvar org-property-set-functions-alist nil
14354 "Property set function alist.
14355 Each entry should have the following format:
14357 (PROPERTY . READ-FUNCTION)
14359 The read function will be called with the same argument as
14360 `org-completing-read'.")
14362 (defun org-set-property-function (property)
14363 "Get the function that should be used to set PROPERTY.
14364 This is computed according to `org-property-set-functions-alist'."
14365 (or (cdr (assoc property org-property-set-functions-alist))
14366 'org-completing-read))
14368 (defun org-read-property-value (property)
14369 "Read PROPERTY value from user."
14370 (let* ((completion-ignore-case t)
14371 (allowed (org-property-get-allowed-values nil property 'table))
14372 (cur (org-entry-get nil property))
14373 (prompt (concat property " value"
14374 (if (and cur (string-match "\\S-" cur))
14375 (concat " [" cur "]") "") ": "))
14376 (set-function (org-set-property-function property))
14377 (val (if allowed
14378 (funcall set-function prompt allowed nil
14379 (not (get-text-property 0 'org-unrestricted
14380 (caar allowed))))
14381 (let (org-completion-use-ido org-completion-use-iswitchb)
14382 (funcall set-function prompt
14383 (mapcar 'list (org-property-values property))
14384 nil nil "" nil cur)))))
14385 (if (equal val "")
14387 val)))
14389 (defvar org-last-set-property nil)
14390 (defun org-read-property-name ()
14391 "Read a property name."
14392 (let* ((completion-ignore-case t)
14393 (keys (org-buffer-property-keys nil t t))
14394 (default-prop (or (save-excursion
14395 (save-match-data
14396 (beginning-of-line)
14397 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14398 (null (string= (match-string 1) "END"))
14399 (match-string 1))))
14400 org-last-set-property))
14401 (property (org-icompleting-read
14402 (concat "Property"
14403 (if default-prop (concat " [" default-prop "]") "")
14404 ": ")
14405 (mapcar 'list keys)
14406 nil nil nil nil
14407 default-prop
14409 (if (member property keys)
14410 property
14411 (or (cdr (assoc (downcase property)
14412 (mapcar (lambda (x) (cons (downcase x) x))
14413 keys)))
14414 property))))
14416 (defun org-set-property (property value)
14417 "In the current entry, set PROPERTY to VALUE.
14418 When called interactively, this will prompt for a property name, offering
14419 completion on existing and default properties. And then it will prompt
14420 for a value, offering completion either on allowed values (via an inherited
14421 xxx_ALL property) or on existing values in other instances of this property
14422 in the current file."
14423 (interactive (list nil nil))
14424 (let* ((property (or property (org-read-property-name)))
14425 (value (or value (org-read-property-value property)))
14426 (fn (assoc property org-properties-postprocess-alist)))
14427 (setq org-last-set-property property)
14428 ;; Possibly postprocess the inserted value:
14429 (when fn (setq value (funcall (cadr fn) value)))
14430 (unless (equal (org-entry-get nil property) value)
14431 (org-entry-put nil property value))))
14433 (defun org-delete-property (property)
14434 "In the current entry, delete PROPERTY."
14435 (interactive
14436 (let* ((completion-ignore-case t)
14437 (prop (org-icompleting-read "Property: "
14438 (org-entry-properties nil 'standard))))
14439 (list prop)))
14440 (message "Property %s %s" property
14441 (if (org-entry-delete nil property)
14442 "deleted"
14443 "was not present in the entry")))
14445 (defun org-delete-property-globally (property)
14446 "Remove PROPERTY globally, from all entries."
14447 (interactive
14448 (let* ((completion-ignore-case t)
14449 (prop (org-icompleting-read
14450 "Globally remove property: "
14451 (mapcar 'list (org-buffer-property-keys)))))
14452 (list prop)))
14453 (save-excursion
14454 (save-restriction
14455 (widen)
14456 (goto-char (point-min))
14457 (let ((cnt 0))
14458 (while (re-search-forward
14459 (org-re-property property)
14460 nil t)
14461 (setq cnt (1+ cnt))
14462 (replace-match ""))
14463 (message "Property \"%s\" removed from %d entries" property cnt)))))
14465 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14467 (defun org-compute-property-at-point ()
14468 "Compute the property at point.
14469 This looks for an enclosing column format, extracts the operator and
14470 then applies it to the property in the column format's scope."
14471 (interactive)
14472 (unless (org-at-property-p)
14473 (error "Not at a property"))
14474 (let ((prop (org-match-string-no-properties 2)))
14475 (org-columns-get-format-and-top-level)
14476 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14477 (error "No operator defined for property %s" prop))
14478 (org-columns-compute prop)))
14480 (defvar org-property-allowed-value-functions nil
14481 "Hook for functions supplying allowed values for a specific property.
14482 The functions must take a single argument, the name of the property, and
14483 return a flat list of allowed values. If \":ETC\" is one of
14484 the values, this means that these values are intended as defaults for
14485 completion, but that other values should be allowed too.
14486 The functions must return nil if they are not responsible for this
14487 property.")
14489 (defun org-property-get-allowed-values (pom property &optional table)
14490 "Get allowed values for the property PROPERTY.
14491 When TABLE is non-nil, return an alist that can directly be used for
14492 completion."
14493 (let (vals)
14494 (cond
14495 ((equal property "TODO")
14496 (setq vals (org-with-point-at pom
14497 (append org-todo-keywords-1 '("")))))
14498 ((equal property "PRIORITY")
14499 (let ((n org-lowest-priority))
14500 (while (>= n org-highest-priority)
14501 (push (char-to-string n) vals)
14502 (setq n (1- n)))))
14503 ((member property org-special-properties))
14504 ((setq vals (run-hook-with-args-until-success
14505 'org-property-allowed-value-functions property)))
14507 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14508 (when (and vals (string-match "\\S-" vals))
14509 (setq vals (car (read-from-string (concat "(" vals ")"))))
14510 (setq vals (mapcar (lambda (x)
14511 (cond ((stringp x) x)
14512 ((numberp x) (number-to-string x))
14513 ((symbolp x) (symbol-name x))
14514 (t "???")))
14515 vals)))))
14516 (when (member ":ETC" vals)
14517 (setq vals (remove ":ETC" vals))
14518 (org-add-props (car vals) '(org-unrestricted t)))
14519 (if table (mapcar 'list vals) vals)))
14521 (defun org-property-previous-allowed-value (&optional previous)
14522 "Switch to the next allowed value for this property."
14523 (interactive)
14524 (org-property-next-allowed-value t))
14526 (defun org-property-next-allowed-value (&optional previous)
14527 "Switch to the next allowed value for this property."
14528 (interactive)
14529 (unless (org-at-property-p)
14530 (error "Not at a property"))
14531 (let* ((key (match-string 2))
14532 (value (match-string 3))
14533 (allowed (or (org-property-get-allowed-values (point) key)
14534 (and (member value '("[ ]" "[-]" "[X]"))
14535 '("[ ]" "[X]"))))
14536 nval)
14537 (unless allowed
14538 (error "Allowed values for this property have not been defined"))
14539 (if previous (setq allowed (reverse allowed)))
14540 (if (member value allowed)
14541 (setq nval (car (cdr (member value allowed)))))
14542 (setq nval (or nval (car allowed)))
14543 (if (equal nval value)
14544 (error "Only one allowed value for this property"))
14545 (org-at-property-p)
14546 (replace-match (concat " :" key ": " nval) t t)
14547 (org-indent-line-function)
14548 (beginning-of-line 1)
14549 (skip-chars-forward " \t")
14550 (run-hook-with-args 'org-property-changed-functions key nval)))
14552 (defun org-find-olp (path &optional this-buffer)
14553 "Return a marker pointing to the entry at outline path OLP.
14554 If anything goes wrong, throw an error.
14555 You can wrap this call to catch the error like this:
14557 (condition-case msg
14558 (org-mobile-locate-entry (match-string 4))
14559 (error (nth 1 msg)))
14561 The return value will then be either a string with the error message,
14562 or a marker if everything is OK.
14564 If THIS-BUFFER is set, the outline path does not contain a file,
14565 only headings."
14566 (let* ((file (if this-buffer buffer-file-name (pop path)))
14567 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14568 (level 1)
14569 (lmin 1)
14570 (lmax 1)
14571 limit re end found pos heading cnt flevel)
14572 (unless buffer (error "File not found :%s" file))
14573 (with-current-buffer buffer
14574 (save-excursion
14575 (save-restriction
14576 (widen)
14577 (setq limit (point-max))
14578 (goto-char (point-min))
14579 (while (setq heading (pop path))
14580 (setq re (format org-complex-heading-regexp-format
14581 (regexp-quote heading)))
14582 (setq cnt 0 pos (point))
14583 (while (re-search-forward re end t)
14584 (setq level (- (match-end 1) (match-beginning 1)))
14585 (if (and (>= level lmin) (<= level lmax))
14586 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
14587 (when (= cnt 0) (error "Heading not found on level %d: %s"
14588 lmax heading))
14589 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14590 lmax heading))
14591 (goto-char found)
14592 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
14593 (setq end (save-excursion (org-end-of-subtree t t))))
14594 (when (org-on-heading-p)
14595 (move-marker (make-marker) (point))))))))
14597 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14598 "Find node HEADING in BUFFER.
14599 Return a marker to the heading if it was found, or nil if not.
14600 If POS-ONLY is set, return just the position instead of a marker.
14602 The heading text must match exact, but it may have a TODO keyword,
14603 a priority cookie and tags in the standard locations."
14604 (with-current-buffer (or buffer (current-buffer))
14605 (save-excursion
14606 (save-restriction
14607 (widen)
14608 (goto-char (point-min))
14609 (let (case-fold-search)
14610 (if (re-search-forward
14611 (format org-complex-heading-regexp-format
14612 (regexp-quote heading)) nil t)
14613 (if pos-only
14614 (match-beginning 0)
14615 (move-marker (make-marker) (match-beginning 0)))))))))
14617 (defun org-find-exact-heading-in-directory (heading &optional dir)
14618 "Find Org node headline HEADING in all .org files in directory DIR.
14619 When the target headline is found, return a marker to this location."
14620 (let ((files (directory-files (or dir default-directory)
14621 nil "\\`[^.#].*\\.org\\'"))
14622 file visiting m buffer)
14623 (catch 'found
14624 (while (setq file (pop files))
14625 (message "trying %s" file)
14626 (setq visiting (org-find-base-buffer-visiting file))
14627 (setq buffer (or visiting (find-file-noselect file)))
14628 (setq m (org-find-exact-headline-in-buffer
14629 heading buffer))
14630 (when (and (not m) (not visiting)) (kill-buffer buffer))
14631 (and m (throw 'found m))))))
14633 (defun org-find-entry-with-id (ident)
14634 "Locate the entry that contains the ID property with exact value IDENT.
14635 IDENT can be a string, a symbol or a number, this function will search for
14636 the string representation of it.
14637 Return the position where this entry starts, or nil if there is no such entry."
14638 (interactive "sID: ")
14639 (let ((id (cond
14640 ((stringp ident) ident)
14641 ((symbol-name ident) (symbol-name ident))
14642 ((numberp ident) (number-to-string ident))
14643 (t (error "IDENT %s must be a string, symbol or number" ident))))
14644 (case-fold-search nil))
14645 (save-excursion
14646 (save-restriction
14647 (widen)
14648 (goto-char (point-min))
14649 (when (re-search-forward
14650 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
14651 nil t)
14652 (org-back-to-heading t)
14653 (point))))))
14655 ;;;; Timestamps
14657 (defvar org-last-changed-timestamp nil)
14658 (defvar org-last-inserted-timestamp nil
14659 "The last time stamp inserted with `org-insert-time-stamp'.")
14660 (defvar org-time-was-given) ; dynamically scoped parameter
14661 (defvar org-end-time-was-given) ; dynamically scoped parameter
14662 (defvar org-ts-what) ; dynamically scoped parameter
14664 (defun org-time-stamp (arg &optional inactive)
14665 "Prompt for a date/time and insert a time stamp.
14666 If the user specifies a time like HH:MM, or if this command is called
14667 with a prefix argument, the time stamp will contain date and time.
14668 Otherwise, only the date will be included. All parts of a date not
14669 specified by the user will be filled in from the current date/time.
14670 So if you press just return without typing anything, the time stamp
14671 will represent the current date/time. If there is already a timestamp
14672 at the cursor, it will be modified."
14673 (interactive "P")
14674 (let* ((ts nil)
14675 (default-time
14676 ;; Default time is either today, or, when entering a range,
14677 ;; the range start.
14678 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
14679 (save-excursion
14680 (re-search-backward
14681 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
14682 (- (point) 20) t)))
14683 (apply 'encode-time (org-parse-time-string (match-string 1)))
14684 (current-time)))
14685 (default-input (and ts (org-get-compact-tod ts)))
14686 (repeater (save-excursion
14687 (save-match-data
14688 (beginning-of-line)
14689 (when (re-search-forward
14690 "\\([.+-]+[0-9]+[dwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
14691 (save-excursion (progn (end-of-line) (point))) t)
14692 (match-string 0)))))
14693 org-time-was-given org-end-time-was-given time)
14694 (cond
14695 ((and (org-at-timestamp-p t)
14696 (memq last-command '(org-time-stamp org-time-stamp-inactive))
14697 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
14698 (insert "--")
14699 (setq time (let ((this-command this-command))
14700 (org-read-date arg 'totime nil nil
14701 default-time default-input)))
14702 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
14703 ((org-at-timestamp-p t)
14704 (setq time (let ((this-command this-command))
14705 (org-read-date arg 'totime nil nil default-time default-input)))
14706 (when (org-at-timestamp-p t) ; just to get the match data
14707 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
14708 (replace-match "")
14709 (setq org-last-changed-timestamp
14710 (org-insert-time-stamp
14711 time (or org-time-was-given arg)
14712 inactive nil nil (list org-end-time-was-given)))
14713 (when repeater (goto-char (1- (point))) (insert " " repeater)
14714 (setq org-last-changed-timestamp
14715 (concat (substring org-last-inserted-timestamp 0 -1)
14716 " " repeater ">"))))
14717 (message "Timestamp updated"))
14719 (setq time (let ((this-command this-command))
14720 (org-read-date arg 'totime nil nil default-time default-input)))
14721 (org-insert-time-stamp time (or org-time-was-given arg) inactive
14722 nil nil (list org-end-time-was-given))))))
14724 ;; FIXME: can we use this for something else, like computing time differences?
14725 (defun org-get-compact-tod (s)
14726 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
14727 (let* ((t1 (match-string 1 s))
14728 (h1 (string-to-number (match-string 2 s)))
14729 (m1 (string-to-number (match-string 3 s)))
14730 (t2 (and (match-end 4) (match-string 5 s)))
14731 (h2 (and t2 (string-to-number (match-string 6 s))))
14732 (m2 (and t2 (string-to-number (match-string 7 s))))
14733 dh dm)
14734 (if (not t2)
14736 (setq dh (- h2 h1) dm (- m2 m1))
14737 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
14738 (concat t1 "+" (number-to-string dh)
14739 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
14741 (defun org-time-stamp-inactive (&optional arg)
14742 "Insert an inactive time stamp.
14743 An inactive time stamp is enclosed in square brackets instead of angle
14744 brackets. It is inactive in the sense that it does not trigger agenda entries,
14745 does not link to the calendar and cannot be changed with the S-cursor keys.
14746 So these are more for recording a certain time/date."
14747 (interactive "P")
14748 (org-time-stamp arg 'inactive))
14750 (defvar org-date-ovl (make-overlay 1 1))
14751 (overlay-put org-date-ovl 'face 'org-warning)
14752 (org-detach-overlay org-date-ovl)
14754 (defvar org-ans1) ; dynamically scoped parameter
14755 (defvar org-ans2) ; dynamically scoped parameter
14757 (defvar org-plain-time-of-day-regexp) ; defined below
14759 (defvar org-overriding-default-time nil) ; dynamically scoped
14760 (defvar org-read-date-overlay nil)
14761 (defvar org-dcst nil) ; dynamically scoped
14762 (defvar org-read-date-history nil)
14763 (defvar org-read-date-final-answer nil)
14764 (defvar org-read-date-analyze-futurep nil)
14765 (defvar org-read-date-analyze-forced-year nil)
14767 (defun org-read-date (&optional with-time to-time from-string prompt
14768 default-time default-input)
14769 "Read a date, possibly a time, and make things smooth for the user.
14770 The prompt will suggest to enter an ISO date, but you can also enter anything
14771 which will at least partially be understood by `parse-time-string'.
14772 Unrecognized parts of the date will default to the current day, month, year,
14773 hour and minute. If this command is called to replace a timestamp at point,
14774 of to enter the second timestamp of a range, the default time is taken
14775 from the existing stamp. Furthermore, the command prefers the future,
14776 so if you are giving a date where the year is not given, and the day-month
14777 combination is already past in the current year, it will assume you
14778 mean next year. For details, see the manual. A few examples:
14780 3-2-5 --> 2003-02-05
14781 feb 15 --> currentyear-02-15
14782 2/15 --> currentyear-02-15
14783 sep 12 9 --> 2009-09-12
14784 12:45 --> today 12:45
14785 22 sept 0:34 --> currentyear-09-22 0:34
14786 12 --> currentyear-currentmonth-12
14787 Fri --> nearest Friday (today or later)
14788 etc.
14790 Furthermore you can specify a relative date by giving, as the *first* thing
14791 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
14792 change in days weeks, months, years.
14793 With a single plus or minus, the date is relative to today. With a double
14794 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
14795 +4d --> four days from today
14796 +4 --> same as above
14797 +2w --> two weeks from today
14798 ++5 --> five days from default date
14800 The function understands only English month and weekday abbreviations,
14801 but this can be configured with the variables `parse-time-months' and
14802 `parse-time-weekdays'.
14804 While prompting, a calendar is popped up - you can also select the
14805 date with the mouse (button 1). The calendar shows a period of three
14806 months. To scroll it to other months, use the keys `>' and `<'.
14807 If you don't like the calendar, turn it off with
14808 \(setq org-read-date-popup-calendar nil)
14810 With optional argument TO-TIME, the date will immediately be converted
14811 to an internal time.
14812 With an optional argument WITH-TIME, the prompt will suggest to also
14813 insert a time. Note that when WITH-TIME is not set, you can still
14814 enter a time, and this function will inform the calling routine about
14815 this change. The calling routine may then choose to change the format
14816 used to insert the time stamp into the buffer to include the time.
14817 With optional argument FROM-STRING, read from this string instead from
14818 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
14819 the time/date that is used for everything that is not specified by the
14820 user."
14821 (require 'parse-time)
14822 (let* ((org-time-stamp-rounding-minutes
14823 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
14824 (org-dcst org-display-custom-times)
14825 (ct (org-current-time))
14826 (def (or org-overriding-default-time default-time ct))
14827 (defdecode (decode-time def))
14828 (dummy (progn
14829 (when (< (nth 2 defdecode) org-extend-today-until)
14830 (setcar (nthcdr 2 defdecode) -1)
14831 (setcar (nthcdr 1 defdecode) 59)
14832 (setq def (apply 'encode-time defdecode)
14833 defdecode (decode-time def)))))
14834 (calendar-frame-setup nil)
14835 (calendar-setup nil)
14836 (calendar-move-hook nil)
14837 (calendar-view-diary-initially-flag nil)
14838 (calendar-view-holidays-initially-flag nil)
14839 (timestr (format-time-string
14840 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
14841 (prompt (concat (if prompt (concat prompt " ") "")
14842 (format "Date+time [%s]: " timestr)))
14843 ans (org-ans0 "") org-ans1 org-ans2 final)
14845 (cond
14846 (from-string (setq ans from-string))
14847 (org-read-date-popup-calendar
14848 (save-excursion
14849 (save-window-excursion
14850 (calendar)
14851 (unwind-protect
14852 (progn
14853 (calendar-forward-day (- (time-to-days def)
14854 (calendar-absolute-from-gregorian
14855 (calendar-current-date))))
14856 (org-eval-in-calendar nil t)
14857 (let* ((old-map (current-local-map))
14858 (map (copy-keymap calendar-mode-map))
14859 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
14860 (org-defkey map (kbd "RET") 'org-calendar-select)
14861 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
14862 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
14863 (org-defkey minibuffer-local-map [(meta shift left)]
14864 (lambda () (interactive)
14865 (org-eval-in-calendar '(calendar-backward-month 1))))
14866 (org-defkey minibuffer-local-map [(meta shift right)]
14867 (lambda () (interactive)
14868 (org-eval-in-calendar '(calendar-forward-month 1))))
14869 (org-defkey minibuffer-local-map [(meta shift up)]
14870 (lambda () (interactive)
14871 (org-eval-in-calendar '(calendar-backward-year 1))))
14872 (org-defkey minibuffer-local-map [(meta shift down)]
14873 (lambda () (interactive)
14874 (org-eval-in-calendar '(calendar-forward-year 1))))
14875 (org-defkey minibuffer-local-map [?\e (shift left)]
14876 (lambda () (interactive)
14877 (org-eval-in-calendar '(calendar-backward-month 1))))
14878 (org-defkey minibuffer-local-map [?\e (shift right)]
14879 (lambda () (interactive)
14880 (org-eval-in-calendar '(calendar-forward-month 1))))
14881 (org-defkey minibuffer-local-map [?\e (shift up)]
14882 (lambda () (interactive)
14883 (org-eval-in-calendar '(calendar-backward-year 1))))
14884 (org-defkey minibuffer-local-map [?\e (shift down)]
14885 (lambda () (interactive)
14886 (org-eval-in-calendar '(calendar-forward-year 1))))
14887 (org-defkey minibuffer-local-map [(shift up)]
14888 (lambda () (interactive)
14889 (org-eval-in-calendar '(calendar-backward-week 1))))
14890 (org-defkey minibuffer-local-map [(shift down)]
14891 (lambda () (interactive)
14892 (org-eval-in-calendar '(calendar-forward-week 1))))
14893 (org-defkey minibuffer-local-map [(shift left)]
14894 (lambda () (interactive)
14895 (org-eval-in-calendar '(calendar-backward-day 1))))
14896 (org-defkey minibuffer-local-map [(shift right)]
14897 (lambda () (interactive)
14898 (org-eval-in-calendar '(calendar-forward-day 1))))
14899 (org-defkey minibuffer-local-map ">"
14900 (lambda () (interactive)
14901 (org-eval-in-calendar '(scroll-calendar-left 1))))
14902 (org-defkey minibuffer-local-map "<"
14903 (lambda () (interactive)
14904 (org-eval-in-calendar '(scroll-calendar-right 1))))
14905 (org-defkey minibuffer-local-map "\C-v"
14906 (lambda () (interactive)
14907 (org-eval-in-calendar
14908 '(calendar-scroll-left-three-months 1))))
14909 (org-defkey minibuffer-local-map "\M-v"
14910 (lambda () (interactive)
14911 (org-eval-in-calendar
14912 '(calendar-scroll-right-three-months 1))))
14913 (run-hooks 'org-read-date-minibuffer-setup-hook)
14914 (unwind-protect
14915 (progn
14916 (use-local-map map)
14917 (add-hook 'post-command-hook 'org-read-date-display)
14918 (setq org-ans0 (read-string prompt default-input
14919 'org-read-date-history nil))
14920 ;; org-ans0: from prompt
14921 ;; org-ans1: from mouse click
14922 ;; org-ans2: from calendar motion
14923 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
14924 (remove-hook 'post-command-hook 'org-read-date-display)
14925 (use-local-map old-map)
14926 (when org-read-date-overlay
14927 (delete-overlay org-read-date-overlay)
14928 (setq org-read-date-overlay nil)))))
14929 (bury-buffer "*Calendar*")))))
14931 (t ; Naked prompt only
14932 (unwind-protect
14933 (setq ans (read-string prompt default-input
14934 'org-read-date-history timestr))
14935 (when org-read-date-overlay
14936 (delete-overlay org-read-date-overlay)
14937 (setq org-read-date-overlay nil)))))
14939 (setq final (org-read-date-analyze ans def defdecode))
14941 (when org-read-date-analyze-forced-year
14942 (message "Year was forced into %s"
14943 (if org-read-date-force-compatible-dates
14944 "compatible range (1970-2037)"
14945 "range representable on this machine"))
14946 (ding))
14948 ;; One round trip to get rid of 34th of August and stuff like that....
14949 (setq final (decode-time (apply 'encode-time final)))
14951 (setq org-read-date-final-answer ans)
14953 (if to-time
14954 (apply 'encode-time final)
14955 (if (and (boundp 'org-time-was-given) org-time-was-given)
14956 (format "%04d-%02d-%02d %02d:%02d"
14957 (nth 5 final) (nth 4 final) (nth 3 final)
14958 (nth 2 final) (nth 1 final))
14959 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
14961 (defvar def)
14962 (defvar defdecode)
14963 (defvar with-time)
14964 (defun org-read-date-display ()
14965 "Display the current date prompt interpretation in the minibuffer."
14966 (when org-read-date-display-live
14967 (when org-read-date-overlay
14968 (delete-overlay org-read-date-overlay))
14969 (let ((p (point)))
14970 (end-of-line 1)
14971 (while (not (equal (buffer-substring
14972 (max (point-min) (- (point) 4)) (point))
14973 " "))
14974 (insert " "))
14975 (goto-char p))
14976 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
14977 " " (or org-ans1 org-ans2)))
14978 (org-end-time-was-given nil)
14979 (f (org-read-date-analyze ans def defdecode))
14980 (fmts (if org-dcst
14981 org-time-stamp-custom-formats
14982 org-time-stamp-formats))
14983 (fmt (if (or with-time
14984 (and (boundp 'org-time-was-given) org-time-was-given))
14985 (cdr fmts)
14986 (car fmts)))
14987 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
14988 (when (and org-end-time-was-given
14989 (string-match org-plain-time-of-day-regexp txt))
14990 (setq txt (concat (substring txt 0 (match-end 0)) "-"
14991 org-end-time-was-given
14992 (substring txt (match-end 0)))))
14993 (when org-read-date-analyze-futurep
14994 (setq txt (concat txt " (=>F)")))
14995 (setq org-read-date-overlay
14996 (make-overlay (1- (point-at-eol)) (point-at-eol)))
14997 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
14999 (defun org-read-date-analyze (ans def defdecode)
15000 "Analyze the combined answer of the date prompt."
15001 ;; FIXME: cleanup and comment
15002 (let ((nowdecode (decode-time (current-time)))
15003 delta deltan deltaw deltadef year month day
15004 hour minute second wday pm h2 m2 tl wday1
15005 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15006 (setq org-read-date-analyze-futurep nil
15007 org-read-date-analyze-forced-year nil)
15008 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15009 (setq ans "+0"))
15011 (when (setq delta (org-read-date-get-relative ans (current-time) def))
15012 (setq ans (replace-match "" t t ans)
15013 deltan (car delta)
15014 deltaw (nth 1 delta)
15015 deltadef (nth 2 delta)))
15017 ;; Check if there is an iso week date in there
15018 ;; If yes, store the info and postpone interpreting it until the rest
15019 ;; of the parsing is done
15020 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15021 (setq iso-year (if (match-end 1)
15022 (org-small-year-to-year
15023 (string-to-number (match-string 1 ans))))
15024 iso-weekday (if (match-end 3)
15025 (string-to-number (match-string 3 ans)))
15026 iso-week (string-to-number (match-string 2 ans)))
15027 (setq ans (replace-match "" t t ans)))
15029 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15030 (when (string-match
15031 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15032 (setq year (if (match-end 2)
15033 (string-to-number (match-string 2 ans))
15034 (progn (setq kill-year t)
15035 (string-to-number (format-time-string "%Y"))))
15036 month (string-to-number (match-string 3 ans))
15037 day (string-to-number (match-string 4 ans)))
15038 (if (< year 100) (setq year (+ 2000 year)))
15039 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15040 t nil ans)))
15042 ;; Help matching dottet european dates
15043 (when (string-match
15044 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15045 (setq year (if (match-end 3)
15046 (string-to-number (match-string 3 ans))
15047 (progn (setq kill-year t)
15048 (string-to-number (format-time-string "%Y"))))
15049 day (string-to-number (match-string 1 ans))
15050 month (string-to-number (match-string 2 ans))
15051 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15052 t nil ans)))
15054 ;; Help matching american dates, like 5/30 or 5/30/7
15055 (when (string-match
15056 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15057 (setq year (if (match-end 4)
15058 (string-to-number (match-string 4 ans))
15059 (progn (setq kill-year t)
15060 (string-to-number (format-time-string "%Y"))))
15061 month (string-to-number (match-string 1 ans))
15062 day (string-to-number (match-string 2 ans)))
15063 (if (< year 100) (setq year (+ 2000 year)))
15064 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15065 t nil ans)))
15066 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15067 ;; If there is a time with am/pm, and *no* time without it, we convert
15068 ;; so that matching will be successful.
15069 (loop for i from 1 to 2 do ; twice, for end time as well
15070 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15071 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15072 (setq hour (string-to-number (match-string 1 ans))
15073 minute (if (match-end 3)
15074 (string-to-number (match-string 3 ans))
15076 pm (equal ?p
15077 (string-to-char (downcase (match-string 4 ans)))))
15078 (if (and (= hour 12) (not pm))
15079 (setq hour 0)
15080 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15081 (setq ans (replace-match (format "%02d:%02d" hour minute)
15082 t t ans))))
15084 ;; Check if a time range is given as a duration
15085 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15086 (setq hour (string-to-number (match-string 1 ans))
15087 h2 (+ hour (string-to-number (match-string 3 ans)))
15088 minute (string-to-number (match-string 2 ans))
15089 m2 (+ minute (if (match-end 5) (string-to-number
15090 (match-string 5 ans))0)))
15091 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15092 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15093 t t ans)))
15095 ;; Check if there is a time range
15096 (when (boundp 'org-end-time-was-given)
15097 (setq org-time-was-given nil)
15098 (when (and (string-match org-plain-time-of-day-regexp ans)
15099 (match-end 8))
15100 (setq org-end-time-was-given (match-string 8 ans))
15101 (setq ans (concat (substring ans 0 (match-beginning 7))
15102 (substring ans (match-end 7))))))
15104 (setq tl (parse-time-string ans)
15105 day (or (nth 3 tl) (nth 3 defdecode))
15106 month (or (nth 4 tl)
15107 (if (and org-read-date-prefer-future
15108 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15109 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15110 (nth 4 defdecode)))
15111 year (or (and (not kill-year) (nth 5 tl))
15112 (if (and org-read-date-prefer-future
15113 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15114 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15115 (nth 5 defdecode)))
15116 hour (or (nth 2 tl) (nth 2 defdecode))
15117 minute (or (nth 1 tl) (nth 1 defdecode))
15118 second (or (nth 0 tl) 0)
15119 wday (nth 6 tl))
15121 (when (and (eq org-read-date-prefer-future 'time)
15122 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15123 (equal day (nth 3 nowdecode))
15124 (equal month (nth 4 nowdecode))
15125 (equal year (nth 5 nowdecode))
15126 (nth 2 tl)
15127 (or (< (nth 2 tl) (nth 2 nowdecode))
15128 (and (= (nth 2 tl) (nth 2 nowdecode))
15129 (nth 1 tl)
15130 (< (nth 1 tl) (nth 1 nowdecode)))))
15131 (setq day (1+ day)
15132 futurep t))
15134 ;; Special date definitions below
15135 (cond
15136 (iso-week
15137 ;; There was an iso week
15138 (require 'cal-iso)
15139 (setq futurep nil)
15140 (setq year (or iso-year year)
15141 day (or iso-weekday wday 1)
15142 wday nil ; to make sure that the trigger below does not match
15143 iso-date (calendar-gregorian-from-absolute
15144 (calendar-absolute-from-iso
15145 (list iso-week day year))))
15146 ; FIXME: Should we also push ISO weeks into the future?
15147 ; (when (and org-read-date-prefer-future
15148 ; (not iso-year)
15149 ; (< (calendar-absolute-from-gregorian iso-date)
15150 ; (time-to-days (current-time))))
15151 ; (setq year (1+ year)
15152 ; iso-date (calendar-gregorian-from-absolute
15153 ; (calendar-absolute-from-iso
15154 ; (list iso-week day year)))))
15155 (setq month (car iso-date)
15156 year (nth 2 iso-date)
15157 day (nth 1 iso-date)))
15158 (deltan
15159 (setq futurep nil)
15160 (unless deltadef
15161 (let ((now (decode-time (current-time))))
15162 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15163 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15164 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15165 ((equal deltaw "m") (setq month (+ month deltan)))
15166 ((equal deltaw "y") (setq year (+ year deltan)))))
15167 ((and wday (not (nth 3 tl)))
15168 (setq futurep nil)
15169 ;; Weekday was given, but no day, so pick that day in the week
15170 ;; on or after the derived date.
15171 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15172 (unless (equal wday wday1)
15173 (setq day (+ day (% (- wday wday1 -7) 7))))))
15174 (if (and (boundp 'org-time-was-given)
15175 (nth 2 tl))
15176 (setq org-time-was-given t))
15177 (if (< year 100) (setq year (+ 2000 year)))
15178 ;; Check of the date is representable
15179 (if org-read-date-force-compatible-dates
15180 (progn
15181 (if (< year 1970)
15182 (setq year 1970 org-read-date-analyze-forced-year t))
15183 (if (> year 2037)
15184 (setq year 2037 org-read-date-analyze-forced-year t)))
15185 (condition-case nil
15186 (ignore (encode-time second minute hour day month year))
15187 (error
15188 (setq year (nth 5 defdecode))
15189 (setq org-read-date-analyze-forced-year t))))
15190 (setq org-read-date-analyze-futurep futurep)
15191 (list second minute hour day month year)))
15193 (defvar parse-time-weekdays)
15195 (defun org-read-date-get-relative (s today default)
15196 "Check string S for special relative date string.
15197 TODAY and DEFAULT are internal times, for today and for a default.
15198 Return shift list (N what def-flag)
15199 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15200 N is the number of WHATs to shift.
15201 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15202 the DEFAULT date rather than TODAY."
15203 (when (and
15204 (string-match
15205 (concat
15206 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15207 "\\([0-9]+\\)?"
15208 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15209 "\\([ \t]\\|$\\)") s)
15210 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15211 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15212 (string-to-char (substring (match-string 1 s) -1))
15213 ?+))
15214 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15215 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15216 (what (if (match-end 3) (match-string 3 s) "d"))
15217 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15218 (date (if rel default today))
15219 (wday (nth 6 (decode-time date)))
15220 delta)
15221 (if wday1
15222 (progn
15223 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15224 (if (= dir ?-) (setq delta (- delta 7)))
15225 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15226 (list delta "d" rel))
15227 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15229 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15230 "Turn a user-specified date into the internal representation.
15231 The internal representation needed by the calendar is (month day year).
15232 This is a wrapper to handle the brain-dead convention in calendar that
15233 user function argument order change dependent on argument order."
15234 (if (boundp 'calendar-date-style)
15235 (cond
15236 ((eq calendar-date-style 'american)
15237 (list arg1 arg2 arg3))
15238 ((eq calendar-date-style 'european)
15239 (list arg2 arg1 arg3))
15240 ((eq calendar-date-style 'iso)
15241 (list arg2 arg3 arg1)))
15242 (with-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15243 (if (org-bound-and-true-p european-calendar-style)
15244 (list arg2 arg1 arg3)
15245 (list arg1 arg2 arg3)))))
15247 (defun org-eval-in-calendar (form &optional keepdate)
15248 "Eval FORM in the calendar window and return to current window.
15249 Also, store the cursor date in variable org-ans2."
15250 (let ((sf (selected-frame))
15251 (sw (selected-window)))
15252 (select-window (get-buffer-window "*Calendar*" t))
15253 (eval form)
15254 (when (and (not keepdate) (calendar-cursor-to-date))
15255 (let* ((date (calendar-cursor-to-date))
15256 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15257 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15258 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15259 (select-window sw)
15260 (org-select-frame-set-input-focus sf)))
15262 (defun org-calendar-select ()
15263 "Return to `org-read-date' with the date currently selected.
15264 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15265 (interactive)
15266 (when (calendar-cursor-to-date)
15267 (let* ((date (calendar-cursor-to-date))
15268 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15269 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15270 (if (active-minibuffer-window) (exit-minibuffer))))
15272 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15273 "Insert a date stamp for the date given by the internal TIME.
15274 WITH-HM means use the stamp format that includes the time of the day.
15275 INACTIVE means use square brackets instead of angular ones, so that the
15276 stamp will not contribute to the agenda.
15277 PRE and POST are optional strings to be inserted before and after the
15278 stamp.
15279 The command returns the inserted time stamp."
15280 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15281 stamp)
15282 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15283 (insert-before-markers (or pre ""))
15284 (when (listp extra)
15285 (setq extra (car extra))
15286 (if (and (stringp extra)
15287 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15288 (setq extra (format "-%02d:%02d"
15289 (string-to-number (match-string 1 extra))
15290 (string-to-number (match-string 2 extra))))
15291 (setq extra nil)))
15292 (when extra
15293 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15294 (insert-before-markers (setq stamp (format-time-string fmt time)))
15295 (insert-before-markers (or post ""))
15296 (setq org-last-inserted-timestamp stamp)))
15298 (defun org-toggle-time-stamp-overlays ()
15299 "Toggle the use of custom time stamp formats."
15300 (interactive)
15301 (setq org-display-custom-times (not org-display-custom-times))
15302 (unless org-display-custom-times
15303 (let ((p (point-min)) (bmp (buffer-modified-p)))
15304 (while (setq p (next-single-property-change p 'display))
15305 (if (and (get-text-property p 'display)
15306 (eq (get-text-property p 'face) 'org-date))
15307 (remove-text-properties
15308 p (setq p (next-single-property-change p 'display))
15309 '(display t))))
15310 (set-buffer-modified-p bmp)))
15311 (if (featurep 'xemacs)
15312 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15313 (org-restart-font-lock)
15314 (setq org-table-may-need-update t)
15315 (if org-display-custom-times
15316 (message "Time stamps are overlayed with custom format")
15317 (message "Time stamp overlays removed")))
15319 (defun org-display-custom-time (beg end)
15320 "Overlay modified time stamp format over timestamp between BEG and END."
15321 (let* ((ts (buffer-substring beg end))
15322 t1 w1 with-hm tf time str w2 (off 0))
15323 (save-match-data
15324 (setq t1 (org-parse-time-string ts t))
15325 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
15326 (setq off (- (match-end 0) (match-beginning 0)))))
15327 (setq end (- end off))
15328 (setq w1 (- end beg)
15329 with-hm (and (nth 1 t1) (nth 2 t1))
15330 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15331 time (org-fix-decoded-time t1)
15332 str (org-add-props
15333 (format-time-string
15334 (substring tf 1 -1) (apply 'encode-time time))
15335 nil 'mouse-face 'highlight)
15336 w2 (length str))
15337 (if (not (= w2 w1))
15338 (add-text-properties (1+ beg) (+ 2 beg)
15339 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15340 (if (featurep 'xemacs)
15341 (progn
15342 (put-text-property beg end 'invisible t)
15343 (put-text-property beg end 'end-glyph (make-glyph str)))
15344 (put-text-property beg end 'display str))))
15346 (defun org-translate-time (string)
15347 "Translate all timestamps in STRING to custom format.
15348 But do this only if the variable `org-display-custom-times' is set."
15349 (when org-display-custom-times
15350 (save-match-data
15351 (let* ((start 0)
15352 (re org-ts-regexp-both)
15353 t1 with-hm inactive tf time str beg end)
15354 (while (setq start (string-match re string start))
15355 (setq beg (match-beginning 0)
15356 end (match-end 0)
15357 t1 (save-match-data
15358 (org-parse-time-string (substring string beg end) t))
15359 with-hm (and (nth 1 t1) (nth 2 t1))
15360 inactive (equal (substring string beg (1+ beg)) "[")
15361 tf (funcall (if with-hm 'cdr 'car)
15362 org-time-stamp-custom-formats)
15363 time (org-fix-decoded-time t1)
15364 str (format-time-string
15365 (concat
15366 (if inactive "[" "<") (substring tf 1 -1)
15367 (if inactive "]" ">"))
15368 (apply 'encode-time time))
15369 string (replace-match str t t string)
15370 start (+ start (length str)))))))
15371 string)
15373 (defun org-fix-decoded-time (time)
15374 "Set 0 instead of nil for the first 6 elements of time.
15375 Don't touch the rest."
15376 (let ((n 0))
15377 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15379 (defun org-days-to-time (timestamp-string)
15380 "Difference between TIMESTAMP-STRING and now in days."
15381 (- (time-to-days (org-time-string-to-time timestamp-string))
15382 (time-to-days (current-time))))
15384 (defun org-deadline-close (timestamp-string &optional ndays)
15385 "Is the time in TIMESTAMP-STRING close to the current date?"
15386 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15387 (and (< (org-days-to-time timestamp-string) ndays)
15388 (not (org-entry-is-done-p))))
15390 (defun org-get-wdays (ts)
15391 "Get the deadline lead time appropriate for timestring TS."
15392 (cond
15393 ((<= org-deadline-warning-days 0)
15394 ;; 0 or negative, enforce this value no matter what
15395 (- org-deadline-warning-days))
15396 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
15397 ;; lead time is specified.
15398 (floor (* (string-to-number (match-string 1 ts))
15399 (cdr (assoc (match-string 2 ts)
15400 '(("d" . 1) ("w" . 7)
15401 ("m" . 30.4) ("y" . 365.25)))))))
15402 ;; go for the default.
15403 (t org-deadline-warning-days)))
15405 (defun org-calendar-select-mouse (ev)
15406 "Return to `org-read-date' with the date currently selected.
15407 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15408 (interactive "e")
15409 (mouse-set-point ev)
15410 (when (calendar-cursor-to-date)
15411 (let* ((date (calendar-cursor-to-date))
15412 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15413 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15414 (if (active-minibuffer-window) (exit-minibuffer))))
15416 (defun org-check-deadlines (ndays)
15417 "Check if there are any deadlines due or past due.
15418 A deadline is considered due if it happens within `org-deadline-warning-days'
15419 days from today's date. If the deadline appears in an entry marked DONE,
15420 it is not shown. The prefix arg NDAYS can be used to test that many
15421 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15422 (interactive "P")
15423 (let* ((org-warn-days
15424 (cond
15425 ((equal ndays '(4)) 100000)
15426 (ndays (prefix-numeric-value ndays))
15427 (t (abs org-deadline-warning-days))))
15428 (case-fold-search nil)
15429 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15430 (callback
15431 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15433 (message "%d deadlines past-due or due within %d days"
15434 (org-occur regexp nil callback)
15435 org-warn-days)))
15437 (defun org-check-before-date (date)
15438 "Check if there are deadlines or scheduled entries before DATE."
15439 (interactive (list (org-read-date)))
15440 (let ((case-fold-search nil)
15441 (regexp (concat "\\<\\(" org-deadline-string
15442 "\\|" org-scheduled-string
15443 "\\) *<\\([^>]+\\)>"))
15444 (callback
15445 (lambda () (time-less-p
15446 (org-time-string-to-time (match-string 2))
15447 (org-time-string-to-time date)))))
15448 (message "%d entries before %s"
15449 (org-occur regexp nil callback) date)))
15451 (defun org-check-after-date (date)
15452 "Check if there are deadlines or scheduled entries after DATE."
15453 (interactive (list (org-read-date)))
15454 (let ((case-fold-search nil)
15455 (regexp (concat "\\<\\(" org-deadline-string
15456 "\\|" org-scheduled-string
15457 "\\) *<\\([^>]+\\)>"))
15458 (callback
15459 (lambda () (not
15460 (time-less-p
15461 (org-time-string-to-time (match-string 2))
15462 (org-time-string-to-time date))))))
15463 (message "%d entries after %s"
15464 (org-occur regexp nil callback) date)))
15466 (defun org-evaluate-time-range (&optional to-buffer)
15467 "Evaluate a time range by computing the difference between start and end.
15468 Normally the result is just printed in the echo area, but with prefix arg
15469 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15470 If the time range is actually in a table, the result is inserted into the
15471 next column.
15472 For time difference computation, a year is assumed to be exactly 365
15473 days in order to avoid rounding problems."
15474 (interactive "P")
15476 (org-clock-update-time-maybe)
15477 (save-excursion
15478 (unless (org-at-date-range-p t)
15479 (goto-char (point-at-bol))
15480 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15481 (if (not (org-at-date-range-p t))
15482 (error "Not at a time-stamp range, and none found in current line")))
15483 (let* ((ts1 (match-string 1))
15484 (ts2 (match-string 2))
15485 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15486 (match-end (match-end 0))
15487 (time1 (org-time-string-to-time ts1))
15488 (time2 (org-time-string-to-time ts2))
15489 (t1 (org-float-time time1))
15490 (t2 (org-float-time time2))
15491 (diff (abs (- t2 t1)))
15492 (negative (< (- t2 t1) 0))
15493 ;; (ys (floor (* 365 24 60 60)))
15494 (ds (* 24 60 60))
15495 (hs (* 60 60))
15496 (fy "%dy %dd %02d:%02d")
15497 (fy1 "%dy %dd")
15498 (fd "%dd %02d:%02d")
15499 (fd1 "%dd")
15500 (fh "%02d:%02d")
15501 y d h m align)
15502 (if havetime
15503 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15505 d (floor (/ diff ds)) diff (mod diff ds)
15506 h (floor (/ diff hs)) diff (mod diff hs)
15507 m (floor (/ diff 60)))
15508 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15510 d (floor (+ (/ diff ds) 0.5))
15511 h 0 m 0))
15512 (if (not to-buffer)
15513 (message "%s" (org-make-tdiff-string y d h m))
15514 (if (org-at-table-p)
15515 (progn
15516 (goto-char match-end)
15517 (setq align t)
15518 (and (looking-at " *|") (goto-char (match-end 0))))
15519 (goto-char match-end))
15520 (if (looking-at
15521 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15522 (replace-match ""))
15523 (if negative (insert " -"))
15524 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15525 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15526 (insert " " (format fh h m))))
15527 (if align (org-table-align))
15528 (message "Time difference inserted")))))
15530 (defun org-make-tdiff-string (y d h m)
15531 (let ((fmt "")
15532 (l nil))
15533 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15534 l (push y l)))
15535 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15536 l (push d l)))
15537 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15538 l (push h l)))
15539 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15540 l (push m l)))
15541 (apply 'format fmt (nreverse l))))
15543 (defun org-time-string-to-time (s &optional buffer pos)
15544 (condition-case errdata
15545 (apply 'encode-time (org-parse-time-string s))
15546 (error (error "Bad timestamp `%s'%s\nError was: %s"
15547 s (if (not (and buffer pos))
15549 (format " at %d in buffer `%s'" pos buffer))
15550 (cdr errdata)))))
15552 (defun org-time-string-to-seconds (s)
15553 (org-float-time (org-time-string-to-time s)))
15555 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
15556 "Convert a time stamp to an absolute day number.
15557 If there is a specifier for a cyclic time stamp, get the closest date to
15558 DAYNR.
15559 PREFER and SHOW-ALL are passed through to `org-closest-date'.
15560 The variable date is bound by the calendar when this is called."
15561 (cond
15562 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15563 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15564 daynr
15565 (+ daynr 1000)))
15566 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
15567 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15568 (time-to-days (current-time))) (match-string 0 s)
15569 prefer show-all))
15570 (t (time-to-days
15571 (condition-case errdata
15572 (apply 'encode-time (org-parse-time-string s))
15573 (error (error "Bad timestamp `%s'%s\nError was: %s"
15574 s (if (not (and buffer pos))
15576 (format " at %d in buffer `%s'" pos buffer))
15577 (cdr errdata))))))))
15579 (defun org-days-to-iso-week (days)
15580 "Return the iso week number."
15581 (require 'cal-iso)
15582 (car (calendar-iso-from-absolute days)))
15584 (defun org-small-year-to-year (year)
15585 "Convert 2-digit years into 4-digit years.
15586 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15587 The year 2000 cannot be abbreviated. Any year larger than 99
15588 is returned unchanged."
15589 (if (< year 38)
15590 (setq year (+ 2000 year))
15591 (if (< year 100)
15592 (setq year (+ 1900 year))))
15593 year)
15595 (defun org-time-from-absolute (d)
15596 "Return the time corresponding to date D.
15597 D may be an absolute day number, or a calendar-type list (month day year)."
15598 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15599 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15601 (defun org-calendar-holiday ()
15602 "List of holidays, for Diary display in Org-mode."
15603 (require 'holidays)
15604 (let ((hl (funcall
15605 (if (fboundp 'calendar-check-holidays)
15606 'calendar-check-holidays 'check-calendar-holidays) date)))
15607 (if hl (mapconcat 'identity hl "; "))))
15609 (defun org-diary-sexp-entry (sexp entry date)
15610 "Process a SEXP diary ENTRY for DATE."
15611 (require 'diary-lib)
15612 (let ((result (if calendar-debug-sexp
15613 (let ((stack-trace-on-error t))
15614 (eval (car (read-from-string sexp))))
15615 (condition-case nil
15616 (eval (car (read-from-string sexp)))
15617 (error
15618 (beep)
15619 (message "Bad sexp at line %d in %s: %s"
15620 (org-current-line)
15621 (buffer-file-name) sexp)
15622 (sleep-for 2))))))
15623 (cond ((stringp result) (split-string result "; "))
15624 ((and (consp result)
15625 (not (consp (cdr result)))
15626 (stringp (cdr result))) (cdr result))
15627 ((and (consp result)
15628 (stringp (car result))) result)
15629 (result entry)
15630 (t nil))))
15632 (defun org-diary-to-ical-string (frombuf)
15633 "Get iCalendar entries from diary entries in buffer FROMBUF.
15634 This uses the icalendar.el library."
15635 (let* ((tmpdir (if (featurep 'xemacs)
15636 (temp-directory)
15637 temporary-file-directory))
15638 (tmpfile (make-temp-name
15639 (expand-file-name "orgics" tmpdir)))
15640 buf rtn b e)
15641 (with-current-buffer frombuf
15642 (icalendar-export-region (point-min) (point-max) tmpfile)
15643 (setq buf (find-buffer-visiting tmpfile))
15644 (set-buffer buf)
15645 (goto-char (point-min))
15646 (if (re-search-forward "^BEGIN:VEVENT" nil t)
15647 (setq b (match-beginning 0)))
15648 (goto-char (point-max))
15649 (if (re-search-backward "^END:VEVENT" nil t)
15650 (setq e (match-end 0)))
15651 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
15652 (kill-buffer buf)
15653 (delete-file tmpfile)
15654 rtn))
15656 (defun org-closest-date (start current change prefer show-all)
15657 "Find the date closest to CURRENT that is consistent with START and CHANGE.
15658 When PREFER is `past', return a date that is either CURRENT or past.
15659 When PREFER is `future', return a date that is either CURRENT or future.
15660 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
15661 ;; Make the proper lists from the dates
15662 (catch 'exit
15663 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
15664 dn dw sday cday n1 n2 n0
15665 d m y y1 y2 date1 date2 nmonths nm ny m2)
15667 (setq start (org-date-to-gregorian start)
15668 current (org-date-to-gregorian
15669 (if show-all
15670 current
15671 (time-to-days (current-time))))
15672 sday (calendar-absolute-from-gregorian start)
15673 cday (calendar-absolute-from-gregorian current))
15675 (if (<= cday sday) (throw 'exit sday))
15677 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
15678 (setq dn (string-to-number (match-string 1 change))
15679 dw (cdr (assoc (match-string 2 change) a1)))
15680 (error "Invalid change specifier: %s" change))
15681 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
15682 (cond
15683 ((eq dw 'day)
15684 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
15685 n2 (+ n1 dn)))
15686 ((eq dw 'year)
15687 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
15688 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
15689 (setq date1 (list m d y1)
15690 n1 (calendar-absolute-from-gregorian date1)
15691 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
15692 n2 (calendar-absolute-from-gregorian date2)))
15693 ((eq dw 'month)
15694 ;; approx number of month between the two dates
15695 (setq nmonths (floor (/ (- cday sday) 30.436875)))
15696 ;; How often does dn fit in there?
15697 (setq d (nth 1 start) m (car start) y (nth 2 start)
15698 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
15699 m (+ m nm)
15700 ny (floor (/ m 12))
15701 y (+ y ny)
15702 m (- m (* ny 12)))
15703 (while (> m 12) (setq m (- m 12) y (1+ y)))
15704 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
15705 (setq m2 (+ m dn) y2 y)
15706 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15707 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
15708 (while (<= n2 cday)
15709 (setq n1 n2 m m2 y y2)
15710 (setq m2 (+ m dn) y2 y)
15711 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15712 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
15713 ;; Make sure n1 is the earlier date
15714 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
15715 (if show-all
15716 (cond
15717 ((eq prefer 'past) (if (= cday n2) n2 n1))
15718 ((eq prefer 'future) (if (= cday n1) n1 n2))
15719 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
15720 (cond
15721 ((eq prefer 'past) (if (= cday n2) n2 n1))
15722 ((eq prefer 'future) (if (= cday n1) n1 n2))
15723 (t (if (= cday n1) n1 n2)))))))
15725 (defun org-date-to-gregorian (date)
15726 "Turn any specification of DATE into a Gregorian date for the calendar."
15727 (cond ((integerp date) (calendar-gregorian-from-absolute date))
15728 ((and (listp date) (= (length date) 3)) date)
15729 ((stringp date)
15730 (setq date (org-parse-time-string date))
15731 (list (nth 4 date) (nth 3 date) (nth 5 date)))
15732 ((listp date)
15733 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
15735 (defun org-parse-time-string (s &optional nodefault)
15736 "Parse the standard Org-mode time string.
15737 This should be a lot faster than the normal `parse-time-string'.
15738 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
15739 hour and minute fields will be nil if not given."
15740 (if (string-match org-ts-regexp0 s)
15741 (list 0
15742 (if (or (match-beginning 8) (not nodefault))
15743 (string-to-number (or (match-string 8 s) "0")))
15744 (if (or (match-beginning 7) (not nodefault))
15745 (string-to-number (or (match-string 7 s) "0")))
15746 (string-to-number (match-string 4 s))
15747 (string-to-number (match-string 3 s))
15748 (string-to-number (match-string 2 s))
15749 nil nil nil)
15750 (error "Not a standard Org-mode time string: %s" s)))
15752 (defun org-timestamp-up (&optional arg)
15753 "Increase the date item at the cursor by one.
15754 If the cursor is on the year, change the year. If it is on the month,
15755 the day or the time, change that.
15756 With prefix ARG, change by that many units."
15757 (interactive "p")
15758 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
15760 (defun org-timestamp-down (&optional arg)
15761 "Decrease the date item at the cursor by one.
15762 If the cursor is on the year, change the year. If it is on the month,
15763 the day or the time, change that.
15764 With prefix ARG, change by that many units."
15765 (interactive "p")
15766 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
15768 (defun org-timestamp-up-day (&optional arg)
15769 "Increase the date in the time stamp by one day.
15770 With prefix ARG, change that many days."
15771 (interactive "p")
15772 (if (and (not (org-at-timestamp-p t))
15773 (org-on-heading-p))
15774 (org-todo 'up)
15775 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
15777 (defun org-timestamp-down-day (&optional arg)
15778 "Decrease the date in the time stamp by one day.
15779 With prefix ARG, change that many days."
15780 (interactive "p")
15781 (if (and (not (org-at-timestamp-p t))
15782 (org-on-heading-p))
15783 (org-todo 'down)
15784 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
15786 (defun org-at-timestamp-p (&optional inactive-ok)
15787 "Determine if the cursor is in or at a timestamp."
15788 (interactive)
15789 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
15790 (pos (point))
15791 (ans (or (looking-at tsr)
15792 (save-excursion
15793 (skip-chars-backward "^[<\n\r\t")
15794 (if (> (point) (point-min)) (backward-char 1))
15795 (and (looking-at tsr)
15796 (> (- (match-end 0) pos) -1))))))
15797 (and ans
15798 (boundp 'org-ts-what)
15799 (setq org-ts-what
15800 (cond
15801 ((= pos (match-beginning 0)) 'bracket)
15802 ;; Point is considered to be "on the bracket" whether
15803 ;; it's really on it or right after it.
15804 ((or (= pos (1- (match-end 0)))
15805 (= pos (match-end 0))) 'bracket)
15806 ((org-pos-in-match-range pos 2) 'year)
15807 ((org-pos-in-match-range pos 3) 'month)
15808 ((org-pos-in-match-range pos 7) 'hour)
15809 ((org-pos-in-match-range pos 8) 'minute)
15810 ((or (org-pos-in-match-range pos 4)
15811 (org-pos-in-match-range pos 5)) 'day)
15812 ((and (> pos (or (match-end 8) (match-end 5)))
15813 (< pos (match-end 0)))
15814 (- pos (or (match-end 8) (match-end 5))))
15815 (t 'day))))
15816 ans))
15818 (defun org-toggle-timestamp-type ()
15819 "Toggle the type (<active> or [inactive]) of a time stamp."
15820 (interactive)
15821 (when (org-at-timestamp-p t)
15822 (let ((beg (match-beginning 0)) (end (match-end 0))
15823 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
15824 (save-excursion
15825 (goto-char beg)
15826 (while (re-search-forward "[][<>]" end t)
15827 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
15828 t t)))
15829 (message "Timestamp is now %sactive"
15830 (if (equal (char-after beg) ?<) "" "in")))))
15832 (defun org-timestamp-change (n &optional what updown)
15833 "Change the date in the time stamp at point.
15834 The date will be changed by N times WHAT. WHAT can be `day', `month',
15835 `year', `minute', `second'. If WHAT is not given, the cursor position
15836 in the timestamp determines what will be changed."
15837 (let ((origin (point)) origin-cat
15838 with-hm inactive
15839 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
15840 org-ts-what
15841 extra rem
15842 ts time time0)
15843 (if (not (org-at-timestamp-p t))
15844 (error "Not at a timestamp"))
15845 (if (and (not what) (eq org-ts-what 'bracket))
15846 (org-toggle-timestamp-type)
15847 ;; Point isn't on brackets. Remember the part of the time-stamp
15848 ;; the point was in. Indeed, size of time-stamps may change,
15849 ;; but point must be kept in the same category nonetheless.
15850 (setq origin-cat org-ts-what)
15851 (if (and (not what) (not (eq org-ts-what 'day))
15852 org-display-custom-times
15853 (get-text-property (point) 'display)
15854 (not (get-text-property (1- (point)) 'display)))
15855 (setq org-ts-what 'day))
15856 (setq org-ts-what (or what org-ts-what)
15857 inactive (= (char-after (match-beginning 0)) ?\[)
15858 ts (match-string 0))
15859 (replace-match "")
15860 (if (string-match
15861 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
15863 (setq extra (match-string 1 ts)))
15864 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
15865 (setq with-hm t))
15866 (setq time0 (org-parse-time-string ts))
15867 (when (and updown
15868 (eq org-ts-what 'minute)
15869 (not current-prefix-arg))
15870 ;; This looks like s-up and s-down. Change by one rounding step.
15871 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
15872 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
15873 (setcar (cdr time0) (+ (nth 1 time0)
15874 (if (> n 0) (- rem) (- dm rem))))))
15875 (setq time
15876 (encode-time (or (car time0) 0)
15877 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
15878 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
15879 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
15880 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
15881 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
15882 (nthcdr 6 time0)))
15883 (when (and (member org-ts-what '(hour minute))
15884 extra
15885 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
15886 (setq extra (org-modify-ts-extra
15887 extra
15888 (if (eq org-ts-what 'hour) 2 5)
15889 n dm)))
15890 (when (integerp org-ts-what)
15891 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
15892 (if (eq what 'calendar)
15893 (let ((cal-date (org-get-date-from-calendar)))
15894 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
15895 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
15896 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
15897 (setcar time0 (or (car time0) 0))
15898 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
15899 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
15900 (setq time (apply 'encode-time time0))))
15901 ;; Insert the new time-stamp, and ensure point stays in the same
15902 ;; category as before (i.e. not after the last position in that
15903 ;; category).
15904 (let ((pos (point)))
15905 ;; Stay before inserted string. `save-excursion' is of no use.
15906 (setq org-last-changed-timestamp
15907 (org-insert-time-stamp time with-hm inactive nil nil extra))
15908 (goto-char pos))
15909 (save-match-data
15910 (looking-at org-ts-regexp3)
15911 (goto-char (cond
15912 ;; `day' category ends before `hour' if any, or at
15913 ;; the end of the day name.
15914 ((eq origin-cat 'day)
15915 (min (or (match-beginning 7) (1- (match-end 5))) origin))
15916 ((eq origin-cat 'hour) (min (match-end 7) origin))
15917 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
15918 ((integerp origin-cat) (min (1- (match-end 0)) origin))
15919 ;; `year' and `month' have both fixed size: point
15920 ;; couldn't have moved into another part.
15921 (t origin))))
15922 ;; Update clock if on a CLOCK line.
15923 (org-clock-update-time-maybe)
15924 ;; Try to recenter the calendar window, if any.
15925 (if (and org-calendar-follow-timestamp-change
15926 (get-buffer-window "*Calendar*" t)
15927 (memq org-ts-what '(day month year)))
15928 (org-recenter-calendar (time-to-days time))))))
15930 (defun org-modify-ts-extra (s pos n dm)
15931 "Change the different parts of the lead-time and repeat fields in timestamp."
15932 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
15933 ng h m new rem)
15934 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
15935 (cond
15936 ((or (org-pos-in-match-range pos 2)
15937 (org-pos-in-match-range pos 3))
15938 (setq m (string-to-number (match-string 3 s))
15939 h (string-to-number (match-string 2 s)))
15940 (if (org-pos-in-match-range pos 2)
15941 (setq h (+ h n))
15942 (setq n (* dm (org-no-warnings (signum n))))
15943 (when (not (= 0 (setq rem (% m dm))))
15944 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
15945 (setq m (+ m n)))
15946 (if (< m 0) (setq m (+ m 60) h (1- h)))
15947 (if (> m 59) (setq m (- m 60) h (1+ h)))
15948 (setq h (min 24 (max 0 h)))
15949 (setq ng 1 new (format "-%02d:%02d" h m)))
15950 ((org-pos-in-match-range pos 6)
15951 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
15952 ((org-pos-in-match-range pos 5)
15953 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
15955 ((org-pos-in-match-range pos 9)
15956 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
15957 ((org-pos-in-match-range pos 8)
15958 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
15960 (when ng
15961 (setq s (concat
15962 (substring s 0 (match-beginning ng))
15964 (substring s (match-end ng))))))
15967 (defun org-recenter-calendar (date)
15968 "If the calendar is visible, recenter it to DATE."
15969 (let* ((win (selected-window))
15970 (cwin (get-buffer-window "*Calendar*" t))
15971 (calendar-move-hook nil))
15972 (when cwin
15973 (select-window cwin)
15974 (calendar-goto-date (if (listp date) date
15975 (calendar-gregorian-from-absolute date)))
15976 (select-window win))))
15978 (defun org-goto-calendar (&optional arg)
15979 "Go to the Emacs calendar at the current date.
15980 If there is a time stamp in the current line, go to that date.
15981 A prefix ARG can be used to force the current date."
15982 (interactive "P")
15983 (let ((tsr org-ts-regexp) diff
15984 (calendar-move-hook nil)
15985 (calendar-view-holidays-initially-flag nil)
15986 (calendar-view-diary-initially-flag nil))
15987 (if (or (org-at-timestamp-p)
15988 (save-excursion
15989 (beginning-of-line 1)
15990 (looking-at (concat ".*" tsr))))
15991 (let ((d1 (time-to-days (current-time)))
15992 (d2 (time-to-days
15993 (org-time-string-to-time (match-string 1)))))
15994 (setq diff (- d2 d1))))
15995 (calendar)
15996 (calendar-goto-today)
15997 (if (and diff (not arg)) (calendar-forward-day diff))))
15999 (defun org-get-date-from-calendar ()
16000 "Return a list (month day year) of date at point in calendar."
16001 (with-current-buffer "*Calendar*"
16002 (save-match-data
16003 (calendar-cursor-to-date))))
16005 (defun org-date-from-calendar ()
16006 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16007 If there is already a time stamp at the cursor position, update it."
16008 (interactive)
16009 (if (org-at-timestamp-p t)
16010 (org-timestamp-change 0 'calendar)
16011 (let ((cal-date (org-get-date-from-calendar)))
16012 (org-insert-time-stamp
16013 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16015 (defun org-minutes-to-hh:mm-string (m)
16016 "Compute H:MM from a number of minutes."
16017 (let ((h (/ m 60)))
16018 (setq m (- m (* 60 h)))
16019 (format org-time-clocksum-format h m)))
16021 (defun org-hh:mm-string-to-minutes (s)
16022 "Convert a string H:MM to a number of minutes.
16023 If the string is just a number, interpret it as minutes.
16024 In fact, the first hh:mm or number in the string will be taken,
16025 there can be extra stuff in the string.
16026 If no number is found, the return value is 0."
16027 (cond
16028 ((integerp s) s)
16029 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16030 (+ (* (string-to-number (match-string 1 s)) 60)
16031 (string-to-number (match-string 2 s))))
16032 ((string-match "\\([0-9]+\\)" s)
16033 (string-to-number (match-string 1 s)))
16034 (t 0)))
16036 (defcustom org-effort-durations
16037 `(("h" . 60)
16038 ("d" . ,(* 60 8))
16039 ("w" . ,(* 60 8 5))
16040 ("m" . ,(* 60 8 5 4))
16041 ("y" . ,(* 60 8 5 40)))
16042 "Conversion factor to minutes for an effort modifier.
16044 Each entry has the form (MODIFIER . MINUTES).
16046 In an effort string, a number followed by MODIFIER is multiplied
16047 by the specified number of MINUTES to obtain an effort in
16048 minutes.
16050 For example, if the value of this variable is ((\"hours\" . 60)), then an
16051 effort string \"2hours\" is equivalent to 120 minutes."
16052 :group 'org-agenda
16053 :type '(alist :key-type (string :tag "Modifier")
16054 :value-type (number :tag "Minutes")))
16056 (defun org-duration-string-to-minutes (s)
16057 "Convert a duration string S to minutes.
16059 A bare number is interpreted as minutes, modifiers can be set by
16060 customizing `org-effort-durations' (which see).
16062 Entries containing a colon are interpreted as H:MM by
16063 `org-hh:mm-string-to-minutes'."
16064 (let ((result 0)
16065 (re (concat "\\([0-9]+\\) *\\("
16066 (regexp-opt (mapcar 'car org-effort-durations))
16067 "\\)")))
16068 (while (string-match re s)
16069 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16070 (string-to-number (match-string 1 s))))
16071 (setq s (replace-match "" nil t s)))
16072 (incf result (org-hh:mm-string-to-minutes s))
16073 result))
16075 ;;;; Files
16077 (defun org-save-all-org-buffers ()
16078 "Save all Org-mode buffers without user confirmation."
16079 (interactive)
16080 (message "Saving all Org-mode buffers...")
16081 (save-some-buffers t (lambda () (eq major-mode 'org-mode)))
16082 (when (featurep 'org-id) (org-id-locations-save))
16083 (message "Saving all Org-mode buffers... done"))
16085 (defun org-revert-all-org-buffers ()
16086 "Revert all Org-mode buffers.
16087 Prompt for confirmation when there are unsaved changes.
16088 Be sure you know what you are doing before letting this function
16089 overwrite your changes.
16091 This function is useful in a setup where one tracks org files
16092 with a version control system, to revert on one machine after pulling
16093 changes from another. I believe the procedure must be like this:
16095 1. M-x org-save-all-org-buffers
16096 2. Pull changes from the other machine, resolve conflicts
16097 3. M-x org-revert-all-org-buffers"
16098 (interactive)
16099 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16100 (error "Abort"))
16101 (save-excursion
16102 (save-window-excursion
16103 (mapc
16104 (lambda (b)
16105 (when (and (with-current-buffer b (eq major-mode 'org-mode))
16106 (with-current-buffer b buffer-file-name))
16107 (org-pop-to-buffer-same-window b)
16108 (revert-buffer t 'no-confirm)))
16109 (buffer-list))
16110 (when (and (featurep 'org-id) org-id-track-globally)
16111 (org-id-locations-load)))))
16113 ;;;; Agenda files
16115 ;;;###autoload
16116 (defun org-switchb (&optional arg)
16117 "Switch between Org buffers.
16118 With one prefix argument, restrict available buffers to files.
16119 With two prefix arguments, restrict available buffers to agenda files.
16121 Defaults to `iswitchb' for buffer name completion.
16122 Set `org-completion-use-ido' to make it use ido instead."
16123 (interactive "P")
16124 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16125 ((equal arg '(16)) (org-buffer-list 'agenda))
16126 (t (org-buffer-list))))
16127 (org-completion-use-iswitchb org-completion-use-iswitchb)
16128 (org-completion-use-ido org-completion-use-ido))
16129 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16130 (setq org-completion-use-iswitchb t))
16131 (org-pop-to-buffer-same-window
16132 (org-icompleting-read "Org buffer: "
16133 (mapcar 'list (mapcar 'buffer-name blist))
16134 nil t))))
16136 ;;; Define some older names previously used for this functionality
16137 ;;;###autoload
16138 (defalias 'org-ido-switchb 'org-switchb)
16139 ;;;###autoload
16140 (defalias 'org-iswitchb 'org-switchb)
16142 (defun org-buffer-list (&optional predicate exclude-tmp)
16143 "Return a list of Org buffers.
16144 PREDICATE can be `export', `files' or `agenda'.
16146 export restrict the list to Export buffers.
16147 files restrict the list to buffers visiting Org files.
16148 agenda restrict the list to buffers visiting agenda files.
16150 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16151 (let* ((bfn nil)
16152 (agenda-files (and (eq predicate 'agenda)
16153 (mapcar 'file-truename (org-agenda-files t))))
16154 (filter
16155 (cond
16156 ((eq predicate 'files)
16157 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
16158 ((eq predicate 'export)
16159 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16160 ((eq predicate 'agenda)
16161 (lambda (b)
16162 (with-current-buffer b
16163 (and (eq major-mode 'org-mode)
16164 (setq bfn (buffer-file-name b))
16165 (member (file-truename bfn) agenda-files)))))
16166 (t (lambda (b) (with-current-buffer b
16167 (or (eq major-mode 'org-mode)
16168 (string-match "\*Org .*Export"
16169 (buffer-name b)))))))))
16170 (delq nil
16171 (mapcar
16172 (lambda(b)
16173 (if (and (funcall filter b)
16174 (or (not exclude-tmp)
16175 (not (string-match "tmp" (buffer-name b)))))
16177 nil))
16178 (buffer-list)))))
16180 (defun org-agenda-files (&optional unrestricted archives)
16181 "Get the list of agenda files.
16182 Optional UNRESTRICTED means return the full list even if a restriction
16183 is currently in place.
16184 When ARCHIVES is t, include all archive files that are really being
16185 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16186 `org-agenda-archives-mode' is t."
16187 (let ((files
16188 (cond
16189 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16190 ((stringp org-agenda-files) (org-read-agenda-file-list))
16191 ((listp org-agenda-files) org-agenda-files)
16192 (t (error "Invalid value of `org-agenda-files'")))))
16193 (setq files (apply 'append
16194 (mapcar (lambda (f)
16195 (if (file-directory-p f)
16196 (directory-files
16197 f t org-agenda-file-regexp)
16198 (list f)))
16199 files)))
16200 (when org-agenda-skip-unavailable-files
16201 (setq files (delq nil
16202 (mapcar (function
16203 (lambda (file)
16204 (and (file-readable-p file) file)))
16205 files))))
16206 (when (or (eq archives t)
16207 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16208 (setq files (org-add-archive-files files)))
16209 files))
16211 (defun org-agenda-file-p (&optional file)
16212 "Return non-nil, if FILE is an agenda file.
16213 If FILE is omitted, use the file associated with the current
16214 buffer."
16215 (member (or file (buffer-file-name))
16216 (org-agenda-files t)))
16218 (defun org-edit-agenda-file-list ()
16219 "Edit the list of agenda files.
16220 Depending on setup, this either uses customize to edit the variable
16221 `org-agenda-files', or it visits the file that is holding the list. In the
16222 latter case, the buffer is set up in a way that saving it automatically kills
16223 the buffer and restores the previous window configuration."
16224 (interactive)
16225 (if (stringp org-agenda-files)
16226 (let ((cw (current-window-configuration)))
16227 (find-file org-agenda-files)
16228 (org-set-local 'org-window-configuration cw)
16229 (org-add-hook 'after-save-hook
16230 (lambda ()
16231 (set-window-configuration
16232 (prog1 org-window-configuration
16233 (kill-buffer (current-buffer))))
16234 (org-install-agenda-files-menu)
16235 (message "New agenda file list installed"))
16236 nil 'local)
16237 (message "%s" (substitute-command-keys
16238 "Edit list and finish with \\[save-buffer]")))
16239 (customize-variable 'org-agenda-files)))
16241 (defun org-store-new-agenda-file-list (list)
16242 "Set new value for the agenda file list and save it correctly."
16243 (if (stringp org-agenda-files)
16244 (let ((fe (org-read-agenda-file-list t)) b u)
16245 (while (setq b (find-buffer-visiting org-agenda-files))
16246 (kill-buffer b))
16247 (with-temp-file org-agenda-files
16248 (insert
16249 (mapconcat
16250 (lambda (f) ;; Keep un-expanded entries.
16251 (if (setq u (assoc f fe))
16252 (cdr u)
16254 list "\n")
16255 "\n")))
16256 (let ((org-mode-hook nil) (org-inhibit-startup t)
16257 (org-insert-mode-line-in-empty-file nil))
16258 (setq org-agenda-files list)
16259 (customize-save-variable 'org-agenda-files org-agenda-files))))
16261 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16262 "Read the list of agenda files from a file.
16263 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16264 filenames, used by `org-store-new-agenda-file-list' to write back
16265 un-expanded file names."
16266 (when (file-directory-p org-agenda-files)
16267 (error "`org-agenda-files' cannot be a single directory"))
16268 (when (stringp org-agenda-files)
16269 (with-temp-buffer
16270 (insert-file-contents org-agenda-files)
16271 (mapcar
16272 (lambda (f)
16273 (let ((e (expand-file-name (substitute-in-file-name f)
16274 org-directory)))
16275 (if pair-with-expansion
16276 (cons e f)
16277 e)))
16278 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16280 ;;;###autoload
16281 (defun org-cycle-agenda-files ()
16282 "Cycle through the files in `org-agenda-files'.
16283 If the current buffer visits an agenda file, find the next one in the list.
16284 If the current buffer does not, find the first agenda file."
16285 (interactive)
16286 (let* ((fs (org-agenda-files t))
16287 (files (append fs (list (car fs))))
16288 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16289 file)
16290 (unless files (error "No agenda files"))
16291 (catch 'exit
16292 (while (setq file (pop files))
16293 (if (equal (file-truename file) tcf)
16294 (when (car files)
16295 (find-file (car files))
16296 (throw 'exit t))))
16297 (find-file (car fs)))
16298 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16300 (defun org-agenda-file-to-front (&optional to-end)
16301 "Move/add the current file to the top of the agenda file list.
16302 If the file is not present in the list, it is added to the front. If it is
16303 present, it is moved there. With optional argument TO-END, add/move to the
16304 end of the list."
16305 (interactive "P")
16306 (let ((org-agenda-skip-unavailable-files nil)
16307 (file-alist (mapcar (lambda (x)
16308 (cons (file-truename x) x))
16309 (org-agenda-files t)))
16310 (ctf (file-truename buffer-file-name))
16311 x had)
16312 (setq x (assoc ctf file-alist) had x)
16314 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16315 (if to-end
16316 (setq file-alist (append (delq x file-alist) (list x)))
16317 (setq file-alist (cons x (delq x file-alist))))
16318 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16319 (org-install-agenda-files-menu)
16320 (message "File %s to %s of agenda file list"
16321 (if had "moved" "added") (if to-end "end" "front"))))
16323 (defun org-remove-file (&optional file)
16324 "Remove current file from the list of files in variable `org-agenda-files'.
16325 These are the files which are being checked for agenda entries.
16326 Optional argument FILE means use this file instead of the current."
16327 (interactive)
16328 (let* ((org-agenda-skip-unavailable-files nil)
16329 (file (or file buffer-file-name))
16330 (true-file (file-truename file))
16331 (afile (abbreviate-file-name file))
16332 (files (delq nil (mapcar
16333 (lambda (x)
16334 (if (equal true-file
16335 (file-truename x))
16336 nil x))
16337 (org-agenda-files t)))))
16338 (if (not (= (length files) (length (org-agenda-files t))))
16339 (progn
16340 (org-store-new-agenda-file-list files)
16341 (org-install-agenda-files-menu)
16342 (message "Removed file: %s" afile))
16343 (message "File was not in list: %s (not removed)" afile))))
16345 (defun org-file-menu-entry (file)
16346 (vector file (list 'find-file file) t))
16348 (defun org-check-agenda-file (file)
16349 "Make sure FILE exists. If not, ask user what to do."
16350 (when (not (file-exists-p file))
16351 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16352 (abbreviate-file-name file))
16353 (let ((r (downcase (read-char-exclusive))))
16354 (cond
16355 ((equal r ?r)
16356 (org-remove-file file)
16357 (throw 'nextfile t))
16358 (t (error "Abort"))))))
16360 (defun org-get-agenda-file-buffer (file)
16361 "Get a buffer visiting FILE. If the buffer needs to be created, add
16362 it to the list of buffers which might be released later."
16363 (let ((buf (org-find-base-buffer-visiting file)))
16364 (if buf
16365 buf ; just return it
16366 ;; Make a new buffer and remember it
16367 (setq buf (find-file-noselect file))
16368 (if buf (push buf org-agenda-new-buffers))
16369 buf)))
16371 (defun org-release-buffers (blist)
16372 "Release all buffers in list, asking the user for confirmation when needed.
16373 When a buffer is unmodified, it is just killed. When modified, it is saved
16374 \(if the user agrees) and then killed."
16375 (let (buf file)
16376 (while (setq buf (pop blist))
16377 (setq file (buffer-file-name buf))
16378 (when (and (buffer-modified-p buf)
16379 file
16380 (y-or-n-p (format "Save file %s? " file)))
16381 (with-current-buffer buf (save-buffer)))
16382 (kill-buffer buf))))
16384 (defun org-prepare-agenda-buffers (files)
16385 "Create buffers for all agenda files, protect archived trees and comments."
16386 (interactive)
16387 (let ((pa '(:org-archived t))
16388 (pc '(:org-comment t))
16389 (pall '(:org-archived t :org-comment t))
16390 (inhibit-read-only t)
16391 (rea (concat ":" org-archive-tag ":"))
16392 bmp file re)
16393 (save-excursion
16394 (save-restriction
16395 (while (setq file (pop files))
16396 (catch 'nextfile
16397 (if (bufferp file)
16398 (set-buffer file)
16399 (org-check-agenda-file file)
16400 (set-buffer (org-get-agenda-file-buffer file)))
16401 (widen)
16402 (setq bmp (buffer-modified-p))
16403 (org-refresh-category-properties)
16404 (setq org-todo-keywords-for-agenda
16405 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16406 (setq org-done-keywords-for-agenda
16407 (append org-done-keywords-for-agenda org-done-keywords))
16408 (setq org-todo-keyword-alist-for-agenda
16409 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16410 (setq org-drawers-for-agenda
16411 (append org-drawers-for-agenda org-drawers))
16412 (setq org-tag-alist-for-agenda
16413 (append org-tag-alist-for-agenda org-tag-alist))
16415 (save-excursion
16416 (remove-text-properties (point-min) (point-max) pall)
16417 (when org-agenda-skip-archived-trees
16418 (goto-char (point-min))
16419 (while (re-search-forward rea nil t)
16420 (if (org-on-heading-p t)
16421 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16422 (goto-char (point-min))
16423 (setq re (format org-heading-keyword-regexp-format
16424 org-comment-string))
16425 (while (re-search-forward re nil t)
16426 (add-text-properties
16427 (match-beginning 0) (org-end-of-subtree t) pc)))
16428 (set-buffer-modified-p bmp)))))
16429 (setq org-todo-keywords-for-agenda
16430 (org-uniquify org-todo-keywords-for-agenda))
16431 (setq org-todo-keyword-alist-for-agenda
16432 (org-uniquify org-todo-keyword-alist-for-agenda)
16433 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16435 ;;;; Embedded LaTeX
16437 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16438 "Keymap for the minor `org-cdlatex-mode'.")
16440 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16441 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16442 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16443 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16444 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16446 (defvar org-cdlatex-texmathp-advice-is-done nil
16447 "Flag remembering if we have applied the advice to texmathp already.")
16449 (define-minor-mode org-cdlatex-mode
16450 "Toggle the minor `org-cdlatex-mode'.
16451 This mode supports entering LaTeX environment and math in LaTeX fragments
16452 in Org-mode.
16453 \\{org-cdlatex-mode-map}"
16454 nil " OCDL" nil
16455 (when org-cdlatex-mode
16456 (require 'cdlatex)
16457 (run-hooks 'cdlatex-mode-hook)
16458 (cdlatex-compute-tables))
16459 (unless org-cdlatex-texmathp-advice-is-done
16460 (setq org-cdlatex-texmathp-advice-is-done t)
16461 (defadvice texmathp (around org-math-always-on activate)
16462 "Always return t in org-mode buffers.
16463 This is because we want to insert math symbols without dollars even outside
16464 the LaTeX math segments. If Orgmode thinks that point is actually inside
16465 an embedded LaTeX fragment, let texmathp do its job.
16466 \\[org-cdlatex-mode-map]"
16467 (interactive)
16468 (let (p)
16469 (cond
16470 ((not (eq major-mode 'org-mode)) ad-do-it)
16471 ((eq this-command 'cdlatex-math-symbol)
16472 (setq ad-return-value t
16473 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16475 (let ((p (org-inside-LaTeX-fragment-p)))
16476 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16477 (setq ad-return-value t
16478 texmathp-why '("Org-mode embedded math" . 0))
16479 (if p ad-do-it)))))))))
16481 (defun turn-on-org-cdlatex ()
16482 "Unconditionally turn on `org-cdlatex-mode'."
16483 (org-cdlatex-mode 1))
16485 (defun org-inside-LaTeX-fragment-p ()
16486 "Test if point is inside a LaTeX fragment.
16487 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16488 sequence appearing also before point.
16489 Even though the matchers for math are configurable, this function assumes
16490 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16491 delimiters are skipped when they have been removed by customization.
16492 The return value is nil, or a cons cell with the delimiter and the
16493 position of this delimiter.
16495 This function does a reasonably good job, but can locally be fooled by
16496 for example currency specifications. For example it will assume being in
16497 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16498 fragments that are properly closed, but during editing, we have to live
16499 with the uncertainty caused by missing closing delimiters. This function
16500 looks only before point, not after."
16501 (catch 'exit
16502 (let ((pos (point))
16503 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16504 (lim (progn
16505 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16506 (point)))
16507 dd-on str (start 0) m re)
16508 (goto-char pos)
16509 (when dodollar
16510 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16511 re (nth 1 (assoc "$" org-latex-regexps)))
16512 (while (string-match re str start)
16513 (cond
16514 ((= (match-end 0) (length str))
16515 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16516 ((= (match-end 0) (- (length str) 5))
16517 (throw 'exit nil))
16518 (t (setq start (match-end 0))))))
16519 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16520 (goto-char pos)
16521 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16522 (and (match-beginning 2) (throw 'exit nil))
16523 ;; count $$
16524 (while (re-search-backward "\\$\\$" lim t)
16525 (setq dd-on (not dd-on)))
16526 (goto-char pos)
16527 (if dd-on (cons "$$" m))))))
16529 (defun org-inside-latex-macro-p ()
16530 "Is point inside a LaTeX macro or its arguments?"
16531 (save-match-data
16532 (org-in-regexp
16533 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16535 (defun org-try-cdlatex-tab ()
16536 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16537 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16538 - inside a LaTeX fragment, or
16539 - after the first word in a line, where an abbreviation expansion could
16540 insert a LaTeX environment."
16541 (when org-cdlatex-mode
16542 (cond
16543 ((save-excursion
16544 (skip-chars-backward "a-zA-Z0-9*")
16545 (skip-chars-backward " \t")
16546 (bolp))
16547 (cdlatex-tab) t)
16548 ((org-inside-LaTeX-fragment-p)
16549 (cdlatex-tab) t)
16550 (t nil))))
16552 (defun org-cdlatex-underscore-caret (&optional arg)
16553 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16554 Revert to the normal definition outside of these fragments."
16555 (interactive "P")
16556 (if (org-inside-LaTeX-fragment-p)
16557 (call-interactively 'cdlatex-sub-superscript)
16558 (let (org-cdlatex-mode)
16559 (call-interactively (key-binding (vector last-input-event))))))
16561 (defun org-cdlatex-math-modify (&optional arg)
16562 "Execute `cdlatex-math-modify' in LaTeX fragments.
16563 Revert to the normal definition outside of these fragments."
16564 (interactive "P")
16565 (if (org-inside-LaTeX-fragment-p)
16566 (call-interactively 'cdlatex-math-modify)
16567 (let (org-cdlatex-mode)
16568 (call-interactively (key-binding (vector last-input-event))))))
16570 (defvar org-latex-fragment-image-overlays nil
16571 "List of overlays carrying the images of latex fragments.")
16572 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16574 (defun org-remove-latex-fragment-image-overlays ()
16575 "Remove all overlays with LaTeX fragment images in current buffer."
16576 (mapc 'delete-overlay org-latex-fragment-image-overlays)
16577 (setq org-latex-fragment-image-overlays nil))
16579 (defun org-preview-latex-fragment (&optional subtree)
16580 "Preview the LaTeX fragment at point, or all locally or globally.
16581 If the cursor is in a LaTeX fragment, create the image and overlay
16582 it over the source code. If there is no fragment at point, display
16583 all fragments in the current text, from one headline to the next. With
16584 prefix SUBTREE, display all fragments in the current subtree. With a
16585 double prefix arg \\[universal-argument] \\[universal-argument], or when \
16586 the cursor is before the first headline,
16587 display all fragments in the buffer.
16588 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16589 (interactive "P")
16590 (org-remove-latex-fragment-image-overlays)
16591 (save-excursion
16592 (save-restriction
16593 (let (beg end at msg)
16594 (cond
16595 ((or (equal subtree '(16))
16596 (not (save-excursion
16597 (re-search-backward org-outline-regexp-bol nil t))))
16598 (setq beg (point-min) end (point-max)
16599 msg "Creating images for buffer...%s"))
16600 ((equal subtree '(4))
16601 (org-back-to-heading)
16602 (setq beg (point) end (org-end-of-subtree t)
16603 msg "Creating images for subtree...%s"))
16605 (if (setq at (org-inside-LaTeX-fragment-p))
16606 (goto-char (max (point-min) (- (cdr at) 2)))
16607 (org-back-to-heading))
16608 (setq beg (point) end (progn (outline-next-heading) (point))
16609 msg (if at "Creating image...%s"
16610 "Creating images for entry...%s"))))
16611 (message msg "")
16612 (narrow-to-region beg end)
16613 (goto-char beg)
16614 (org-format-latex
16615 (concat "ltxpng/" (file-name-sans-extension
16616 (file-name-nondirectory
16617 buffer-file-name)))
16618 default-directory 'overlays msg at 'forbuffer 'dvipng)
16619 (message msg "done. Use `C-c C-c' to remove images.")))))
16621 (defvar org-latex-regexps
16622 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16623 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16624 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16625 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16626 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16627 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16628 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
16629 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
16630 "Regular expressions for matching embedded LaTeX.")
16632 (defvar org-export-have-math nil) ;; dynamic scoping
16633 (defun org-format-latex (prefix &optional dir overlays msg at
16634 forbuffer processing-type)
16635 "Replace LaTeX fragments with links to an image, and produce images.
16636 Some of the options can be changed using the variable
16637 `org-format-latex-options'."
16638 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16639 (let* ((prefixnodir (file-name-nondirectory prefix))
16640 (absprefix (expand-file-name prefix dir))
16641 (todir (file-name-directory absprefix))
16642 (opt org-format-latex-options)
16643 (matchers (plist-get opt :matchers))
16644 (re-list org-latex-regexps)
16645 (org-format-latex-header-extra
16646 (plist-get (org-infile-export-plist) :latex-header-extra))
16647 (cnt 0) txt hash link beg end re e checkdir
16648 executables-checked string
16649 m n block-type block linkfile movefile ov)
16650 ;; Check the different regular expressions
16651 (while (setq e (pop re-list))
16652 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
16653 block (if block-type "\n\n" ""))
16654 (when (member m matchers)
16655 (goto-char (point-min))
16656 (while (re-search-forward re nil t)
16657 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
16658 (not (get-text-property (match-beginning n)
16659 'org-protected))
16660 (or (not overlays)
16661 (not (eq (get-char-property (match-beginning n)
16662 'org-overlay-type)
16663 'org-latex-overlay))))
16664 (setq org-export-have-math t)
16665 (cond
16666 ((eq processing-type 'verbatim)
16667 ;; Leave the text verbatim, just protect it
16668 (add-text-properties (match-beginning n) (match-end n)
16669 '(org-protected t)))
16670 ((eq processing-type 'mathjax)
16671 ;; Prepare for MathJax processing
16672 (setq string (match-string n))
16673 (if (member m '("$" "$1"))
16674 (save-excursion
16675 (delete-region (match-beginning n) (match-end n))
16676 (goto-char (match-beginning n))
16677 (insert (org-add-props (concat "\\(" (substring string 1 -1)
16678 "\\)")
16679 '(org-protected t))))
16680 (add-text-properties (match-beginning n) (match-end n)
16681 '(org-protected t))))
16682 ((eq processing-type 'dvipng)
16683 ;; Process to an image
16684 (setq txt (match-string n)
16685 beg (match-beginning n) end (match-end n)
16686 cnt (1+ cnt))
16687 (let (print-length print-level) ; make sure full list is printed
16688 (setq hash (sha1 (prin1-to-string
16689 (list org-format-latex-header
16690 org-format-latex-header-extra
16691 org-export-latex-default-packages-alist
16692 org-export-latex-packages-alist
16693 org-format-latex-options
16694 forbuffer txt)))
16695 linkfile (format "%s_%s.png" prefix hash)
16696 movefile (format "%s_%s.png" absprefix hash)))
16697 (setq link (concat block "[[file:" linkfile "]]" block))
16698 (if msg (message msg cnt))
16699 (goto-char beg)
16700 (unless checkdir ; make sure the directory exists
16701 (setq checkdir t)
16702 (or (file-directory-p todir) (make-directory todir t)))
16704 (unless executables-checked
16705 (org-check-external-command
16706 "latex" "needed to convert LaTeX fragments to images")
16707 (org-check-external-command
16708 "dvipng" "needed to convert LaTeX fragments to images")
16709 (setq executables-checked t))
16711 (unless (file-exists-p movefile)
16712 (org-create-formula-image
16713 txt movefile opt forbuffer))
16714 (if overlays
16715 (progn
16716 (mapc (lambda (o)
16717 (if (eq (overlay-get o 'org-overlay-type)
16718 'org-latex-overlay)
16719 (delete-overlay o)))
16720 (overlays-in beg end))
16721 (setq ov (make-overlay beg end))
16722 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
16723 (if (featurep 'xemacs)
16724 (progn
16725 (overlay-put ov 'invisible t)
16726 (overlay-put
16727 ov 'end-glyph
16728 (make-glyph (vector 'png :file movefile))))
16729 (overlay-put
16730 ov 'display
16731 (list 'image :type 'png :file movefile :ascent 'center)))
16732 (push ov org-latex-fragment-image-overlays)
16733 (goto-char end))
16734 (delete-region beg end)
16735 (insert (org-add-props link
16736 (list 'org-latex-src
16737 (replace-regexp-in-string
16738 "\"" "" txt)
16739 'org-latex-src-embed-type
16740 (if block-type 'paragraph 'character))))))
16741 ((eq processing-type 'mathml)
16742 ;; Process to MathML
16743 (unless executables-checked
16744 (unless (save-match-data (org-format-latex-mathml-available-p))
16745 (error "LaTeX to MathML converter not configured"))
16746 (setq executables-checked t))
16747 (setq txt (match-string n)
16748 beg (match-beginning n) end (match-end n)
16749 cnt (1+ cnt))
16750 (if msg (message msg cnt))
16751 (goto-char beg)
16752 (delete-region beg end)
16753 (insert (org-format-latex-as-mathml
16754 txt block-type prefix dir)))
16756 (error "Unknown conversion type %s for latex fragments"
16757 processing-type)))))))))
16759 (defun org-create-math-formula (latex-frag &optional mathml-file)
16760 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
16761 Use `org-latex-to-mathml-convert-command'. If the conversion is
16762 sucessful, return the portion between \"<math...> </math>\"
16763 elements otherwise return nil. When MATHML-FILE is specified,
16764 write the results in to that file. When invoked as an
16765 interactive command, prompt for LATEX-FRAG, with initial value
16766 set to the current active region and echo the results for user
16767 inspection."
16768 (interactive (list (let ((frag (when (region-active-p)
16769 (buffer-substring-no-properties
16770 (region-beginning) (region-end)))))
16771 (read-string "LaTeX Fragment: " frag nil frag))))
16772 (unless latex-frag (error "Invalid latex-frag"))
16773 (let* ((tmp-in-file (file-relative-name
16774 (make-temp-name (expand-file-name "ltxmathml-in"))))
16775 (ignore (write-region latex-frag nil tmp-in-file))
16776 (tmp-out-file (file-relative-name
16777 (make-temp-name (expand-file-name "ltxmathml-out"))))
16778 (cmd (format-spec
16779 org-latex-to-mathml-convert-command
16780 `((?j . ,(shell-quote-argument
16781 (expand-file-name org-latex-to-mathml-jar-file)))
16782 (?I . ,(shell-quote-argument tmp-in-file))
16783 (?o . ,(shell-quote-argument tmp-out-file)))))
16784 mathml shell-command-output)
16785 (when (org-called-interactively-p 'any)
16786 (unless (org-format-latex-mathml-available-p)
16787 (error "LaTeX to MathML converter not configured")))
16788 (message "Running %s" cmd)
16789 (setq shell-command-output (shell-command-to-string cmd))
16790 (setq mathml
16791 (when (file-readable-p tmp-out-file)
16792 (with-current-buffer (find-file-noselect tmp-out-file t)
16793 (goto-char (point-min))
16794 (when (re-search-forward
16795 (concat
16796 (regexp-quote
16797 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
16798 "\\(.\\|\n\\)*"
16799 (regexp-quote "</math>")) nil t)
16800 (prog1 (match-string 0) (kill-buffer))))))
16801 (cond
16802 (mathml
16803 (setq mathml
16804 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
16805 (when mathml-file
16806 (write-region mathml nil mathml-file))
16807 (when (org-called-interactively-p 'any)
16808 (message mathml)))
16809 ((message "LaTeX to MathML conversion failed")
16810 (message shell-command-output)))
16811 (delete-file tmp-in-file)
16812 (when (file-exists-p tmp-out-file)
16813 (delete-file tmp-out-file))
16814 mathml))
16816 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
16817 prefix &optional dir)
16818 "Use `org-create-math-formula' but check local cache first."
16819 (let* ((absprefix (expand-file-name prefix dir))
16820 (print-length nil) (print-level nil)
16821 (formula-id (concat
16822 "formula-"
16823 (sha1
16824 (prin1-to-string
16825 (list latex-frag
16826 org-latex-to-mathml-convert-command)))))
16827 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
16828 (formula-cache-dir (file-name-directory formula-cache)))
16830 (unless (file-directory-p formula-cache-dir)
16831 (make-directory formula-cache-dir t))
16833 (unless (file-exists-p formula-cache)
16834 (org-create-math-formula latex-frag formula-cache))
16836 (if (file-exists-p formula-cache)
16837 ;; Successful conversion. Return the link to MathML file.
16838 (org-add-props
16839 (format "[[file:%s]]" (file-relative-name formula-cache dir))
16840 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
16841 'org-latex-src-embed-type (if latex-frag-type
16842 'paragraph 'character)))
16843 ;; Failed conversion. Return the LaTeX fragment verbatim
16844 (add-text-properties
16845 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
16846 latex-frag)))
16848 ;; This function borrows from Ganesh Swami's latex2png.el
16849 (defun org-create-formula-image (string tofile options buffer)
16850 "This calls dvipng."
16851 (require 'org-latex)
16852 (let* ((tmpdir (if (featurep 'xemacs)
16853 (temp-directory)
16854 temporary-file-directory))
16855 (texfilebase (make-temp-name
16856 (expand-file-name "orgtex" tmpdir)))
16857 (texfile (concat texfilebase ".tex"))
16858 (dvifile (concat texfilebase ".dvi"))
16859 (pngfile (concat texfilebase ".png"))
16860 (fnh (if (featurep 'xemacs)
16861 (font-height (get-face-font 'default))
16862 (face-attribute 'default :height nil)))
16863 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
16864 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
16865 (fg (or (plist-get options (if buffer :foreground :html-foreground))
16866 "Black"))
16867 (bg (or (plist-get options (if buffer :background :html-background))
16868 "Transparent")))
16869 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
16870 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
16871 (with-temp-file texfile
16872 (insert (org-splice-latex-header
16873 org-format-latex-header
16874 org-export-latex-default-packages-alist
16875 org-export-latex-packages-alist t
16876 org-format-latex-header-extra))
16877 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
16878 (require 'org-latex)
16879 (org-export-latex-fix-inputenc))
16880 (let ((dir default-directory))
16881 (condition-case nil
16882 (progn
16883 (cd tmpdir)
16884 (call-process "latex" nil nil nil texfile))
16885 (error nil))
16886 (cd dir))
16887 (if (not (file-exists-p dvifile))
16888 (progn (message "Failed to create dvi file from %s" texfile) nil)
16889 (condition-case nil
16890 (call-process "dvipng" nil nil nil
16891 "-fg" fg "-bg" bg
16892 "-D" dpi
16893 ;;"-x" scale "-y" scale
16894 "-T" "tight"
16895 "-o" pngfile
16896 dvifile)
16897 (error nil))
16898 (if (not (file-exists-p pngfile))
16899 (if org-format-latex-signal-error
16900 (error "Failed to create png file from %s" texfile)
16901 (message "Failed to create png file from %s" texfile)
16902 nil)
16903 ;; Use the requested file name and clean up
16904 (copy-file pngfile tofile 'replace)
16905 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
16906 (delete-file (concat texfilebase e)))
16907 pngfile))))
16909 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
16910 "Fill a LaTeX header template TPL.
16911 In the template, the following place holders will be recognized:
16913 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
16914 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
16915 [PACKAGES] \\usepackage statements for PKG
16916 [NO-PACKAGES] do not include PKG
16917 [EXTRA] the string EXTRA
16918 [NO-EXTRA] do not include EXTRA
16920 For backward compatibility, if both the positive and the negative place
16921 holder is missing, the positive one (without the \"NO-\") will be
16922 assumed to be present at the end of the template.
16923 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
16924 EXTRA is a string.
16925 SNIPPETS-P indicates if this is run to create snippet images for HTML."
16926 (let (rpl (end ""))
16927 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
16928 (setq rpl (if (or (match-end 1) (not def-pkg))
16929 "" (org-latex-packages-to-string def-pkg snippets-p t))
16930 tpl (replace-match rpl t t tpl))
16931 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
16933 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
16934 (setq rpl (if (or (match-end 1) (not pkg))
16935 "" (org-latex-packages-to-string pkg snippets-p t))
16936 tpl (replace-match rpl t t tpl))
16937 (if pkg (setq end
16938 (concat end "\n"
16939 (org-latex-packages-to-string pkg snippets-p)))))
16941 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
16942 (setq rpl (if (or (match-end 1) (not extra))
16943 "" (concat extra "\n"))
16944 tpl (replace-match rpl t t tpl))
16945 (if (and extra (string-match "\\S-" extra))
16946 (setq end (concat end "\n" extra))))
16948 (if (string-match "\\S-" end)
16949 (concat tpl "\n" end)
16950 tpl)))
16952 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
16953 "Turn an alist of packages into a string with the \\usepackage macros."
16954 (setq pkg (mapconcat (lambda(p)
16955 (cond
16956 ((stringp p) p)
16957 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
16958 (format "%% Package %s omitted" (cadr p)))
16959 ((equal "" (car p))
16960 (format "\\usepackage{%s}" (cadr p)))
16962 (format "\\usepackage[%s]{%s}"
16963 (car p) (cadr p)))))
16965 "\n"))
16966 (if newline (concat pkg "\n") pkg))
16968 (defun org-dvipng-color (attr)
16969 "Return an rgb color specification for dvipng."
16970 (apply 'format "rgb %s %s %s"
16971 (mapcar 'org-normalize-color
16972 (color-values (face-attribute 'default attr nil)))))
16974 (defun org-normalize-color (value)
16975 "Return string to be used as color value for an RGB component."
16976 (format "%g" (/ value 65535.0)))
16978 ;; Image display
16981 (defvar org-inline-image-overlays nil)
16982 (make-variable-buffer-local 'org-inline-image-overlays)
16984 (defun org-toggle-inline-images (&optional include-linked)
16985 "Toggle the display of inline images.
16986 INCLUDE-LINKED is passed to `org-display-inline-images'."
16987 (interactive "P")
16988 (if org-inline-image-overlays
16989 (progn
16990 (org-remove-inline-images)
16991 (message "Inline image display turned off"))
16992 (org-display-inline-images include-linked)
16993 (if org-inline-image-overlays
16994 (message "%d images displayed inline"
16995 (length org-inline-image-overlays))
16996 (message "No images to display inline"))))
16998 (defun org-display-inline-images (&optional include-linked refresh beg end)
16999 "Display inline images.
17000 Normally only links without a description part are inlined, because this
17001 is how it will work for export. When INCLUDE-LINKED is set, also links
17002 with a description part will be inlined. This can be nice for a quick
17003 look at those images, but it does not reflect what exported files will look
17004 like.
17005 When REFRESH is set, refresh existing images between BEG and END.
17006 This will create new image displays only if necessary.
17007 BEG and END default to the buffer boundaries."
17008 (interactive "P")
17009 (unless refresh
17010 (org-remove-inline-images)
17011 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17012 (save-excursion
17013 (save-restriction
17014 (widen)
17015 (setq beg (or beg (point-min)) end (or end (point-max)))
17016 (goto-char (point-min))
17017 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17018 (substring (org-image-file-name-regexp) 0 -2)
17019 "\\)\\]" (if include-linked "" "\\]")))
17020 old file ov img)
17021 (while (re-search-forward re end t)
17022 (setq old (get-char-property-and-overlay (match-beginning 1)
17023 'org-image-overlay))
17024 (setq file (expand-file-name
17025 (concat (or (match-string 3) "") (match-string 4))))
17026 (when (file-exists-p file)
17027 (if (and (car-safe old) refresh)
17028 (image-refresh (overlay-get (cdr old) 'display))
17029 (setq img (save-match-data (create-image file)))
17030 (when img
17031 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17032 (overlay-put ov 'display img)
17033 (overlay-put ov 'face 'default)
17034 (overlay-put ov 'org-image-overlay t)
17035 (overlay-put ov 'modification-hooks
17036 (list 'org-display-inline-modification-hook))
17037 (push ov org-inline-image-overlays)))))))))
17039 (defun org-display-inline-modification-hook (ov after beg end &optional len)
17040 "Remove inline-display overlay if a corresponding region is modified."
17041 (let ((inhibit-modification-hooks t))
17042 (when (and ov after)
17043 (delete ov org-inline-image-overlays)
17044 (delete-overlay ov))))
17046 (defun org-remove-inline-images ()
17047 "Remove inline display of images."
17048 (interactive)
17049 (mapc 'delete-overlay org-inline-image-overlays)
17050 (setq org-inline-image-overlays nil))
17052 ;;;; Key bindings
17054 ;; Remap outline keys
17055 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17056 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17058 ;; Make `C-c C-x' a prefix key
17059 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17061 ;; TAB key with modifiers
17062 (org-defkey org-mode-map "\C-i" 'org-cycle)
17063 (org-defkey org-mode-map [(tab)] 'org-cycle)
17064 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17065 (org-defkey org-mode-map [(meta tab)] 'pcomplete)
17066 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17067 (org-defkey org-mode-map "\M-\C-i" 'pcomplete)
17068 ;; The following line is necessary under Suse GNU/Linux
17069 (unless (featurep 'xemacs)
17070 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17071 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17072 (define-key org-mode-map [backtab] 'org-shifttab)
17074 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17075 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17076 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17078 ;; Cursor keys with modifiers
17079 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17080 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17081 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17082 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17084 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17085 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17086 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17087 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17089 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17090 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17091 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17092 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17094 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17095 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17096 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17097 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17099 ;; Babel keys
17100 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17101 (mapc (lambda (pair)
17102 (define-key org-babel-map (car pair) (cdr pair)))
17103 org-babel-key-bindings)
17105 ;;; Extra keys for tty access.
17106 ;; We only set them when really needed because otherwise the
17107 ;; menus don't show the simple keys
17109 (when (or org-use-extra-keys
17110 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17111 (not window-system))
17112 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17113 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17114 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17115 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17116 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17117 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17118 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17119 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17120 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17121 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17122 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17123 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17124 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17125 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17126 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17127 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17128 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17129 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17130 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17131 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17132 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17133 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17134 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17135 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17136 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17137 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17138 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17139 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17141 ;; All the other keys
17143 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17144 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17145 (if (boundp 'narrow-map)
17146 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17147 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17148 (if (boundp 'narrow-map)
17149 (org-defkey narrow-map "b" 'org-narrow-to-block)
17150 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17151 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
17152 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
17153 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17154 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17155 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17156 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17157 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17158 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17159 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17160 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17161 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17162 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17163 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17164 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17165 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17166 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17167 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17168 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17169 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17170 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17171 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17172 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17173 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
17174 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
17175 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
17176 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
17177 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
17178 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
17179 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
17180 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
17181 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17182 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17183 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17184 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17185 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
17186 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
17187 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17188 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
17189 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
17190 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
17191 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
17192 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17193 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
17194 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
17195 (org-defkey org-mode-map "\C-c^" 'org-sort)
17196 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
17197 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
17198 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
17199 (org-defkey org-mode-map "\C-m" 'org-return)
17200 (org-defkey org-mode-map "\C-j" 'org-return-indent)
17201 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
17202 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
17203 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
17204 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
17205 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
17206 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
17207 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
17208 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
17209 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
17210 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
17211 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
17212 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
17213 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
17214 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
17215 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
17216 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
17217 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
17218 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
17219 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
17220 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
17221 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
17223 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
17224 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
17225 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
17226 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
17228 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
17229 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
17230 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
17231 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
17232 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
17233 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
17234 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
17235 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
17236 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
17237 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
17238 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
17239 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
17240 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
17241 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
17242 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
17243 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
17244 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
17245 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
17247 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
17248 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
17249 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
17250 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
17251 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
17253 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
17255 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
17257 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
17258 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
17260 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
17263 (when (featurep 'xemacs)
17264 (org-defkey org-mode-map 'button3 'popup-mode-menu))
17267 (defconst org-speed-commands-default
17269 ("Outline Navigation")
17270 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
17271 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
17272 ("f" . (org-speed-move-safe 'org-forward-same-level))
17273 ("b" . (org-speed-move-safe 'org-backward-same-level))
17274 ("u" . (org-speed-move-safe 'outline-up-heading))
17275 ("j" . org-goto)
17276 ("g" . (org-refile t))
17277 ("Outline Visibility")
17278 ("c" . org-cycle)
17279 ("C" . org-shifttab)
17280 (" " . org-display-outline-path)
17281 ("Outline Structure Editing")
17282 ("U" . org-shiftmetaup)
17283 ("D" . org-shiftmetadown)
17284 ("r" . org-metaright)
17285 ("l" . org-metaleft)
17286 ("R" . org-shiftmetaright)
17287 ("L" . org-shiftmetaleft)
17288 ("i" . (progn (forward-char 1) (call-interactively
17289 'org-insert-heading-respect-content)))
17290 ("^" . org-sort)
17291 ("w" . org-refile)
17292 ("a" . org-archive-subtree-default-with-confirmation)
17293 ("." . org-mark-subtree)
17294 ("Clock Commands")
17295 ("I" . org-clock-in)
17296 ("O" . org-clock-out)
17297 ("Meta Data Editing")
17298 ("t" . org-todo)
17299 ("0" . (org-priority ?\ ))
17300 ("1" . (org-priority ?A))
17301 ("2" . (org-priority ?B))
17302 ("3" . (org-priority ?C))
17303 (";" . org-set-tags-command)
17304 ("e" . org-set-effort)
17305 ("Agenda Views etc")
17306 ("v" . org-agenda)
17307 ("/" . org-sparse-tree)
17308 ("Misc")
17309 ("o" . org-open-at-point)
17310 ("?" . org-speed-command-help)
17311 ("<" . (org-agenda-set-restriction-lock 'subtree))
17312 (">" . (org-agenda-remove-restriction-lock))
17314 "The default speed commands.")
17316 (defun org-print-speed-command (e)
17317 (if (> (length (car e)) 1)
17318 (progn
17319 (princ "\n")
17320 (princ (car e))
17321 (princ "\n")
17322 (princ (make-string (length (car e)) ?-))
17323 (princ "\n"))
17324 (princ (car e))
17325 (princ " ")
17326 (if (symbolp (cdr e))
17327 (princ (symbol-name (cdr e)))
17328 (prin1 (cdr e)))
17329 (princ "\n")))
17331 (defun org-speed-command-help ()
17332 "Show the available speed commands."
17333 (interactive)
17334 (if (not org-use-speed-commands)
17335 (error "Speed commands are not activated, customize `org-use-speed-commands'")
17336 (with-output-to-temp-buffer "*Help*"
17337 (princ "User-defined Speed commands\n===========================\n")
17338 (mapc 'org-print-speed-command org-speed-commands-user)
17339 (princ "\n")
17340 (princ "Built-in Speed commands\n=======================\n")
17341 (mapc 'org-print-speed-command org-speed-commands-default))
17342 (with-current-buffer "*Help*"
17343 (setq truncate-lines t))))
17345 (defun org-speed-move-safe (cmd)
17346 "Execute CMD, but make sure that the cursor always ends up in a headline.
17347 If not, return to the original position and throw an error."
17348 (interactive)
17349 (let ((pos (point)))
17350 (call-interactively cmd)
17351 (unless (and (bolp) (org-on-heading-p))
17352 (goto-char pos)
17353 (error "Boundary reached while executing %s" cmd))))
17355 (defvar org-self-insert-command-undo-counter 0)
17357 (defvar org-table-auto-blank-field) ; defined in org-table.el
17358 (defvar org-speed-command nil)
17360 (defun org-speed-command-default-hook (keys)
17361 "Hook for activating single-letter speed commands.
17362 `org-speed-commands-default' specifies a minimal command set.
17363 Use `org-speed-commands-user' for further customization."
17364 (when (or (and (bolp) (looking-at org-outline-regexp))
17365 (and (functionp org-use-speed-commands)
17366 (funcall org-use-speed-commands)))
17367 (cdr (assoc keys (append org-speed-commands-user
17368 org-speed-commands-default)))))
17370 (defun org-babel-speed-command-hook (keys)
17371 "Hook for activating single-letter code block commands."
17372 (when (and (bolp) (looking-at org-babel-src-block-regexp))
17373 (cdr (assoc keys org-babel-key-bindings))))
17375 (defcustom org-speed-command-hook
17376 '(org-speed-command-default-hook org-babel-speed-command-hook)
17377 "Hook for activating speed commands at strategic locations.
17378 Hook functions are called in sequence until a valid handler is
17379 found.
17381 Each hook takes a single argument, a user-pressed command key
17382 which is also a `self-insert-command' from the global map.
17384 Within the hook, examine the cursor position and the command key
17385 and return nil or a valid handler as appropriate. Handler could
17386 be one of an interactive command, a function, or a form.
17388 Set `org-use-speed-commands' to non-nil value to enable this
17389 hook. The default setting is `org-speed-command-default-hook'."
17390 :group 'org-structure
17391 :type 'hook)
17393 (defun org-self-insert-command (N)
17394 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
17395 If the cursor is in a table looking at whitespace, the whitespace is
17396 overwritten, and the table is not marked as requiring realignment."
17397 (interactive "p")
17398 (let ((invisible-at-point
17399 (car (get-char-property-and-overlay (point) 'invisible)))
17400 (invisible-before-point
17401 (or (bobp) (car (get-char-property-and-overlay
17402 (1- (point)) 'invisible)))))
17403 (when (or (eq invisible-at-point 'outline)
17404 (eq invisible-at-point 'org-hide-block)
17405 (eq invisible-before-point 'outline)
17406 (eq invisible-before-point 'org-hide-block))
17407 (if (or (eq invisible-before-point 'outline)
17408 (eq invisible-before-point 'org-hide-block))
17409 (goto-char (previous-overlay-change (point))))
17410 (org-cycle)
17411 (if (or (eq invisible-before-point 'outline)
17412 (eq invisible-before-point 'org-hide-block))
17413 (forward-char 1))
17414 (message "Unfolding invisible region around point before editing")
17415 (sit-for 1)))
17416 (cond
17417 ((and org-use-speed-commands
17418 (setq org-speed-command
17419 (run-hook-with-args-until-success
17420 'org-speed-command-hook (this-command-keys))))
17421 (cond
17422 ((commandp org-speed-command)
17423 (setq this-command org-speed-command)
17424 (call-interactively org-speed-command))
17425 ((functionp org-speed-command)
17426 (funcall org-speed-command))
17427 ((and org-speed-command (listp org-speed-command))
17428 (eval org-speed-command))
17429 (t (let (org-use-speed-commands)
17430 (call-interactively 'org-self-insert-command)))))
17431 ((and
17432 (org-table-p)
17433 (progn
17434 ;; check if we blank the field, and if that triggers align
17435 (and (featurep 'org-table) org-table-auto-blank-field
17436 (member last-command
17437 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
17438 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
17439 ;; got extra space, this field does not determine column width
17440 (let (org-table-may-need-update) (org-table-blank-field))
17441 ;; no extra space, this field may determine column width
17442 (org-table-blank-field)))
17444 (eq N 1)
17445 (looking-at "[^|\n]* |"))
17446 (let (org-table-may-need-update)
17447 (goto-char (1- (match-end 0)))
17448 (delete-char -1)
17449 (goto-char (match-beginning 0))
17450 (self-insert-command N)))
17452 (setq org-table-may-need-update t)
17453 (self-insert-command N)
17454 (org-fix-tags-on-the-fly)
17455 (if org-self-insert-cluster-for-undo
17456 (if (not (eq last-command 'org-self-insert-command))
17457 (setq org-self-insert-command-undo-counter 1)
17458 (if (>= org-self-insert-command-undo-counter 20)
17459 (setq org-self-insert-command-undo-counter 1)
17460 (and (> org-self-insert-command-undo-counter 0)
17461 buffer-undo-list (listp buffer-undo-list)
17462 (not (cadr buffer-undo-list)) ; remove nil entry
17463 (setcdr buffer-undo-list (cddr buffer-undo-list)))
17464 (setq org-self-insert-command-undo-counter
17465 (1+ org-self-insert-command-undo-counter))))))))
17467 (defun org-fix-tags-on-the-fly ()
17468 (when (and (equal (char-after (point-at-bol)) ?*)
17469 (org-on-heading-p))
17470 (org-align-tags-here org-tags-column)))
17472 (defun org-delete-backward-char (N)
17473 "Like `delete-backward-char', insert whitespace at field end in tables.
17474 When deleting backwards, in tables this function will insert whitespace in
17475 front of the next \"|\" separator, to keep the table aligned. The table will
17476 still be marked for re-alignment if the field did fill the entire column,
17477 because, in this case the deletion might narrow the column."
17478 (interactive "p")
17479 (if (and (org-table-p)
17480 (eq N 1)
17481 (string-match "|" (buffer-substring (point-at-bol) (point)))
17482 (looking-at ".*?|"))
17483 (let ((pos (point))
17484 (noalign (looking-at "[^|\n\r]* |"))
17485 (c org-table-may-need-update))
17486 (backward-delete-char N)
17487 (if (not overwrite-mode)
17488 (progn
17489 (skip-chars-forward "^|")
17490 (insert " ")
17491 (goto-char (1- pos))))
17492 ;; noalign: if there were two spaces at the end, this field
17493 ;; does not determine the width of the column.
17494 (if noalign (setq org-table-may-need-update c)))
17495 (backward-delete-char N)
17496 (org-fix-tags-on-the-fly)))
17498 (defun org-delete-char (N)
17499 "Like `delete-char', but insert whitespace at field end in tables.
17500 When deleting characters, in tables this function will insert whitespace in
17501 front of the next \"|\" separator, to keep the table aligned. The table will
17502 still be marked for re-alignment if the field did fill the entire column,
17503 because, in this case the deletion might narrow the column."
17504 (interactive "p")
17505 (if (and (org-table-p)
17506 (not (bolp))
17507 (not (= (char-after) ?|))
17508 (eq N 1))
17509 (if (looking-at ".*?|")
17510 (let ((pos (point))
17511 (noalign (looking-at "[^|\n\r]* |"))
17512 (c org-table-may-need-update))
17513 (replace-match (concat
17514 (substring (match-string 0) 1 -1)
17515 " |"))
17516 (goto-char pos)
17517 ;; noalign: if there were two spaces at the end, this field
17518 ;; does not determine the width of the column.
17519 (if noalign (setq org-table-may-need-update c)))
17520 (delete-char N))
17521 (delete-char N)
17522 (org-fix-tags-on-the-fly)))
17524 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
17525 (put 'org-self-insert-command 'delete-selection t)
17526 (put 'orgtbl-self-insert-command 'delete-selection t)
17527 (put 'org-delete-char 'delete-selection 'supersede)
17528 (put 'org-delete-backward-char 'delete-selection 'supersede)
17529 (put 'org-yank 'delete-selection 'yank)
17531 ;; Make `flyspell-mode' delay after some commands
17532 (put 'org-self-insert-command 'flyspell-delayed t)
17533 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
17534 (put 'org-delete-char 'flyspell-delayed t)
17535 (put 'org-delete-backward-char 'flyspell-delayed t)
17537 ;; Make pabbrev-mode expand after org-mode commands
17538 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
17539 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
17541 ;; How to do this: Measure non-white length of current string
17542 ;; If equal to column width, we should realign.
17544 (defun org-remap (map &rest commands)
17545 "In MAP, remap the functions given in COMMANDS.
17546 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
17547 (let (new old)
17548 (while commands
17549 (setq old (pop commands) new (pop commands))
17550 (if (fboundp 'command-remapping)
17551 (org-defkey map (vector 'remap old) new)
17552 (substitute-key-definition old new map global-map)))))
17554 (when (eq org-enable-table-editor 'optimized)
17555 ;; If the user wants maximum table support, we need to hijack
17556 ;; some standard editing functions
17557 (org-remap org-mode-map
17558 'self-insert-command 'org-self-insert-command
17559 'delete-char 'org-delete-char
17560 'delete-backward-char 'org-delete-backward-char)
17561 (org-defkey org-mode-map "|" 'org-force-self-insert))
17563 (defvar org-ctrl-c-ctrl-c-hook nil
17564 "Hook for functions attaching themselves to `C-c C-c'.
17566 This can be used to add additional functionality to the C-c C-c
17567 key which executes context-dependent commands. This hook is run
17568 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
17569 run after the last test.
17571 Each function will be called with no arguments. The function
17572 must check if the context is appropriate for it to act. If yes,
17573 it should do its thing and then return a non-nil value. If the
17574 context is wrong, just do nothing and return nil.")
17576 (defvar org-ctrl-c-ctrl-c-final-hook nil
17577 "Hook for functions attaching themselves to `C-c C-c'.
17579 This can be used to add additional functionality to the C-c C-c
17580 key which executes context-dependent commands. This hook is run
17581 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
17582 before the first test.
17584 Each function will be called with no arguments. The function
17585 must check if the context is appropriate for it to act. If yes,
17586 it should do its thing and then return a non-nil value. If the
17587 context is wrong, just do nothing and return nil.")
17589 (defvar org-tab-first-hook nil
17590 "Hook for functions to attach themselves to TAB.
17591 See `org-ctrl-c-ctrl-c-hook' for more information.
17592 This hook runs as the first action when TAB is pressed, even before
17593 `org-cycle' messes around with the `outline-regexp' to cater for
17594 inline tasks and plain list item folding.
17595 If any function in this hook returns t, any other actions that
17596 would have been caused by TAB (such as table field motion or visibility
17597 cycling) will not occur.")
17599 (defvar org-tab-after-check-for-table-hook nil
17600 "Hook for functions to attach themselves to TAB.
17601 See `org-ctrl-c-ctrl-c-hook' for more information.
17602 This hook runs after it has been established that the cursor is not in a
17603 table, but before checking if the cursor is in a headline or if global cycling
17604 should be done.
17605 If any function in this hook returns t, not other actions like visibility
17606 cycling will be done.")
17608 (defvar org-tab-after-check-for-cycling-hook nil
17609 "Hook for functions to attach themselves to TAB.
17610 See `org-ctrl-c-ctrl-c-hook' for more information.
17611 This hook runs after it has been established that not table field motion and
17612 not visibility should be done because of current context. This is probably
17613 the place where a package like yasnippets can hook in.")
17615 (defvar org-tab-before-tab-emulation-hook nil
17616 "Hook for functions to attach themselves to TAB.
17617 See `org-ctrl-c-ctrl-c-hook' for more information.
17618 This hook runs after every other options for TAB have been exhausted, but
17619 before indentation and \t insertion takes place.")
17621 (defvar org-metaleft-hook nil
17622 "Hook for functions attaching themselves to `M-left'.
17623 See `org-ctrl-c-ctrl-c-hook' for more information.")
17624 (defvar org-metaright-hook nil
17625 "Hook for functions attaching themselves to `M-right'.
17626 See `org-ctrl-c-ctrl-c-hook' for more information.")
17627 (defvar org-metaup-hook nil
17628 "Hook for functions attaching themselves to `M-up'.
17629 See `org-ctrl-c-ctrl-c-hook' for more information.")
17630 (defvar org-metadown-hook nil
17631 "Hook for functions attaching themselves to `M-down'.
17632 See `org-ctrl-c-ctrl-c-hook' for more information.")
17633 (defvar org-shiftmetaleft-hook nil
17634 "Hook for functions attaching themselves to `M-S-left'.
17635 See `org-ctrl-c-ctrl-c-hook' for more information.")
17636 (defvar org-shiftmetaright-hook nil
17637 "Hook for functions attaching themselves to `M-S-right'.
17638 See `org-ctrl-c-ctrl-c-hook' for more information.")
17639 (defvar org-shiftmetaup-hook nil
17640 "Hook for functions attaching themselves to `M-S-up'.
17641 See `org-ctrl-c-ctrl-c-hook' for more information.")
17642 (defvar org-shiftmetadown-hook nil
17643 "Hook for functions attaching themselves to `M-S-down'.
17644 See `org-ctrl-c-ctrl-c-hook' for more information.")
17645 (defvar org-metareturn-hook nil
17646 "Hook for functions attaching themselves to `M-RET'.
17647 See `org-ctrl-c-ctrl-c-hook' for more information.")
17648 (defvar org-shiftup-hook nil
17649 "Hook for functions attaching themselves to `S-up'.
17650 See `org-ctrl-c-ctrl-c-hook' for more information.")
17651 (defvar org-shiftup-final-hook nil
17652 "Hook for functions attaching themselves to `S-up'.
17653 This one runs after all other options except shift-select have been excluded.
17654 See `org-ctrl-c-ctrl-c-hook' for more information.")
17655 (defvar org-shiftdown-hook nil
17656 "Hook for functions attaching themselves to `S-down'.
17657 See `org-ctrl-c-ctrl-c-hook' for more information.")
17658 (defvar org-shiftdown-final-hook nil
17659 "Hook for functions attaching themselves to `S-down'.
17660 This one runs after all other options except shift-select have been excluded.
17661 See `org-ctrl-c-ctrl-c-hook' for more information.")
17662 (defvar org-shiftleft-hook nil
17663 "Hook for functions attaching themselves to `S-left'.
17664 See `org-ctrl-c-ctrl-c-hook' for more information.")
17665 (defvar org-shiftleft-final-hook nil
17666 "Hook for functions attaching themselves to `S-left'.
17667 This one runs after all other options except shift-select have been excluded.
17668 See `org-ctrl-c-ctrl-c-hook' for more information.")
17669 (defvar org-shiftright-hook nil
17670 "Hook for functions attaching themselves to `S-right'.
17671 See `org-ctrl-c-ctrl-c-hook' for more information.")
17672 (defvar org-shiftright-final-hook nil
17673 "Hook for functions attaching themselves to `S-right'.
17674 This one runs after all other options except shift-select have been excluded.
17675 See `org-ctrl-c-ctrl-c-hook' for more information.")
17677 (defun org-modifier-cursor-error ()
17678 "Throw an error, a modified cursor command was applied in wrong context."
17679 (error "This command is active in special context like tables, headlines or items"))
17681 (defun org-shiftselect-error ()
17682 "Throw an error because Shift-Cursor command was applied in wrong context."
17683 (if (and (boundp 'shift-select-mode) shift-select-mode)
17684 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
17685 (error "This command works only in special context like headlines or timestamps")))
17687 (defun org-call-for-shift-select (cmd)
17688 (let ((this-command-keys-shift-translated t))
17689 (call-interactively cmd)))
17691 (defun org-shifttab (&optional arg)
17692 "Global visibility cycling or move to previous table field.
17693 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
17694 on context.
17695 See the individual commands for more information."
17696 (interactive "P")
17697 (cond
17698 ((org-at-table-p) (call-interactively 'org-table-previous-field))
17699 ((integerp arg)
17700 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
17701 (message "Content view to level: %d" arg)
17702 (org-content (prefix-numeric-value arg2))
17703 (setq org-cycle-global-status 'overview)))
17704 (t (call-interactively 'org-global-cycle))))
17706 (defun org-shiftmetaleft ()
17707 "Promote subtree or delete table column.
17708 Calls `org-promote-subtree', `org-outdent-item',
17709 or `org-table-delete-column', depending on context.
17710 See the individual commands for more information."
17711 (interactive)
17712 (cond
17713 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
17714 ((org-at-table-p) (call-interactively 'org-table-delete-column))
17715 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
17716 ((org-at-item-p) (call-interactively 'org-outdent-item-tree))
17717 (t (org-modifier-cursor-error))))
17719 (defun org-shiftmetaright ()
17720 "Demote subtree or insert table column.
17721 Calls `org-demote-subtree', `org-indent-item',
17722 or `org-table-insert-column', depending on context.
17723 See the individual commands for more information."
17724 (interactive)
17725 (cond
17726 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
17727 ((org-at-table-p) (call-interactively 'org-table-insert-column))
17728 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
17729 ((org-at-item-p) (call-interactively 'org-indent-item-tree))
17730 (t (org-modifier-cursor-error))))
17732 (defun org-shiftmetaup (&optional arg)
17733 "Move subtree up or kill table row.
17734 Calls `org-move-subtree-up' or `org-table-kill-row' or
17735 `org-move-item-up' depending on context. See the individual commands
17736 for more information."
17737 (interactive "P")
17738 (cond
17739 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
17740 ((org-at-table-p) (call-interactively 'org-table-kill-row))
17741 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17742 ((org-at-item-p) (call-interactively 'org-move-item-up))
17743 (t (org-modifier-cursor-error))))
17745 (defun org-shiftmetadown (&optional arg)
17746 "Move subtree down or insert table row.
17747 Calls `org-move-subtree-down' or `org-table-insert-row' or
17748 `org-move-item-down', depending on context. See the individual
17749 commands for more information."
17750 (interactive "P")
17751 (cond
17752 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
17753 ((org-at-table-p) (call-interactively 'org-table-insert-row))
17754 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17755 ((org-at-item-p) (call-interactively 'org-move-item-down))
17756 (t (org-modifier-cursor-error))))
17758 (defsubst org-hidden-tree-error ()
17759 (error
17760 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
17762 (defun org-metaleft (&optional arg)
17763 "Promote heading or move table column to left.
17764 Calls `org-do-promote' or `org-table-move-column', depending on context.
17765 With no specific context, calls the Emacs default `backward-word'.
17766 See the individual commands for more information."
17767 (interactive "P")
17768 (cond
17769 ((run-hook-with-args-until-success 'org-metaleft-hook))
17770 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
17771 ((org-with-limited-levels
17772 (or (org-on-heading-p)
17773 (and (org-region-active-p)
17774 (save-excursion
17775 (goto-char (region-beginning))
17776 (org-on-heading-p)))))
17777 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17778 (call-interactively 'org-do-promote))
17779 ;; At an inline task.
17780 ((org-on-heading-p)
17781 (call-interactively 'org-inlinetask-promote))
17782 ((or (org-at-item-p)
17783 (and (org-region-active-p)
17784 (save-excursion
17785 (goto-char (region-beginning))
17786 (org-at-item-p))))
17787 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17788 (call-interactively 'org-outdent-item))
17789 (t (call-interactively 'backward-word))))
17791 (defun org-metaright (&optional arg)
17792 "Demote subtree or move table column to right.
17793 Calls `org-do-demote' or `org-table-move-column', depending on context.
17794 With no specific context, calls the Emacs default `forward-word'.
17795 See the individual commands for more information."
17796 (interactive "P")
17797 (cond
17798 ((run-hook-with-args-until-success 'org-metaright-hook))
17799 ((org-at-table-p) (call-interactively 'org-table-move-column))
17800 ((org-with-limited-levels
17801 (or (org-on-heading-p)
17802 (and (org-region-active-p)
17803 (save-excursion
17804 (goto-char (region-beginning))
17805 (org-on-heading-p)))))
17806 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17807 (call-interactively 'org-do-demote))
17808 ;; At an inline task.
17809 ((org-on-heading-p)
17810 (call-interactively 'org-inlinetask-demote))
17811 ((or (org-at-item-p)
17812 (and (org-region-active-p)
17813 (save-excursion
17814 (goto-char (region-beginning))
17815 (org-at-item-p))))
17816 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17817 (call-interactively 'org-indent-item))
17818 (t (call-interactively 'forward-word))))
17820 (defun org-check-for-hidden (what)
17821 "Check if there are hidden headlines/items in the current visual line.
17822 WHAT can be either `headlines' or `items'. If the current line is
17823 an outline or item heading and it has a folded subtree below it,
17824 this function returns t, nil otherwise."
17825 (let ((re (cond
17826 ((eq what 'headlines) org-outline-regexp-bol)
17827 ((eq what 'items) (org-item-beginning-re))
17828 (t (error "This should not happen"))))
17829 beg end)
17830 (save-excursion
17831 (catch 'exit
17832 (unless (org-region-active-p)
17833 (setq beg (point-at-bol))
17834 (beginning-of-line 2)
17835 (while (and (not (eobp)) ;; this is like `next-line'
17836 (get-char-property (1- (point)) 'invisible))
17837 (beginning-of-line 2))
17838 (setq end (point))
17839 (goto-char beg)
17840 (goto-char (point-at-eol))
17841 (setq end (max end (point)))
17842 (while (re-search-forward re end t)
17843 (if (get-char-property (match-beginning 0) 'invisible)
17844 (throw 'exit t))))
17845 nil))))
17847 (defun org-metaup (&optional arg)
17848 "Move subtree up or move table row up.
17849 Calls `org-move-subtree-up' or `org-table-move-row' or
17850 `org-move-item-up', depending on context. See the individual commands
17851 for more information."
17852 (interactive "P")
17853 (cond
17854 ((run-hook-with-args-until-success 'org-metaup-hook))
17855 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
17856 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17857 ((org-at-item-p) (call-interactively 'org-move-item-up))
17858 (t (transpose-lines 1) (beginning-of-line -1))))
17860 (defun org-metadown (&optional arg)
17861 "Move subtree down or move table row down.
17862 Calls `org-move-subtree-down' or `org-table-move-row' or
17863 `org-move-item-down', depending on context. See the individual
17864 commands for more information."
17865 (interactive "P")
17866 (cond
17867 ((run-hook-with-args-until-success 'org-metadown-hook))
17868 ((org-at-table-p) (call-interactively 'org-table-move-row))
17869 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17870 ((org-at-item-p) (call-interactively 'org-move-item-down))
17871 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
17873 (defun org-shiftup (&optional arg)
17874 "Increase item in timestamp or increase priority of current headline.
17875 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
17876 depending on context. See the individual commands for more information."
17877 (interactive "P")
17878 (cond
17879 ((run-hook-with-args-until-success 'org-shiftup-hook))
17880 ((and org-support-shift-select (org-region-active-p))
17881 (org-call-for-shift-select 'previous-line))
17882 ((org-at-timestamp-p t)
17883 (call-interactively (if org-edit-timestamp-down-means-later
17884 'org-timestamp-down 'org-timestamp-up)))
17885 ((and (not (eq org-support-shift-select 'always))
17886 org-enable-priority-commands
17887 (org-on-heading-p))
17888 (call-interactively 'org-priority-up))
17889 ((and (not org-support-shift-select) (org-at-item-p))
17890 (call-interactively 'org-previous-item))
17891 ((org-clocktable-try-shift 'up arg))
17892 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
17893 (org-support-shift-select
17894 (org-call-for-shift-select 'previous-line))
17895 (t (org-shiftselect-error))))
17897 (defun org-shiftdown (&optional arg)
17898 "Decrease item in timestamp or decrease priority of current headline.
17899 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
17900 depending on context. See the individual commands for more information."
17901 (interactive "P")
17902 (cond
17903 ((run-hook-with-args-until-success 'org-shiftdown-hook))
17904 ((and org-support-shift-select (org-region-active-p))
17905 (org-call-for-shift-select 'next-line))
17906 ((org-at-timestamp-p t)
17907 (call-interactively (if org-edit-timestamp-down-means-later
17908 'org-timestamp-up 'org-timestamp-down)))
17909 ((and (not (eq org-support-shift-select 'always))
17910 org-enable-priority-commands
17911 (org-on-heading-p))
17912 (call-interactively 'org-priority-down))
17913 ((and (not org-support-shift-select) (org-at-item-p))
17914 (call-interactively 'org-next-item))
17915 ((org-clocktable-try-shift 'down arg))
17916 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
17917 (org-support-shift-select
17918 (org-call-for-shift-select 'next-line))
17919 (t (org-shiftselect-error))))
17921 (defun org-shiftright (&optional arg)
17922 "Cycle the thing at point or in the current line, depending on context.
17923 Depending on context, this does one of the following:
17925 - switch a timestamp at point one day into the future
17926 - on a headline, switch to the next TODO keyword.
17927 - on an item, switch entire list to the next bullet type
17928 - on a property line, switch to the next allowed value
17929 - on a clocktable definition line, move time block into the future"
17930 (interactive "P")
17931 (cond
17932 ((run-hook-with-args-until-success 'org-shiftright-hook))
17933 ((and org-support-shift-select (org-region-active-p))
17934 (org-call-for-shift-select 'forward-char))
17935 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
17936 ((and (not (eq org-support-shift-select 'always))
17937 (org-on-heading-p))
17938 (let ((org-inhibit-logging
17939 (not org-treat-S-cursor-todo-selection-as-state-change))
17940 (org-inhibit-blocking
17941 (not org-treat-S-cursor-todo-selection-as-state-change)))
17942 (org-call-with-arg 'org-todo 'right)))
17943 ((or (and org-support-shift-select
17944 (not (eq org-support-shift-select 'always))
17945 (org-at-item-bullet-p))
17946 (and (not org-support-shift-select) (org-at-item-p)))
17947 (org-call-with-arg 'org-cycle-list-bullet nil))
17948 ((and (not (eq org-support-shift-select 'always))
17949 (org-at-property-p))
17950 (call-interactively 'org-property-next-allowed-value))
17951 ((org-clocktable-try-shift 'right arg))
17952 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
17953 (org-support-shift-select
17954 (org-call-for-shift-select 'forward-char))
17955 (t (org-shiftselect-error))))
17957 (defun org-shiftleft (&optional arg)
17958 "Cycle the thing at point or in the current line, depending on context.
17959 Depending on context, this does one of the following:
17961 - switch a timestamp at point one day into the past
17962 - on a headline, switch to the previous TODO keyword.
17963 - on an item, switch entire list to the previous bullet type
17964 - on a property line, switch to the previous allowed value
17965 - on a clocktable definition line, move time block into the past"
17966 (interactive "P")
17967 (cond
17968 ((run-hook-with-args-until-success 'org-shiftleft-hook))
17969 ((and org-support-shift-select (org-region-active-p))
17970 (org-call-for-shift-select 'backward-char))
17971 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
17972 ((and (not (eq org-support-shift-select 'always))
17973 (org-on-heading-p))
17974 (let ((org-inhibit-logging
17975 (not org-treat-S-cursor-todo-selection-as-state-change))
17976 (org-inhibit-blocking
17977 (not org-treat-S-cursor-todo-selection-as-state-change)))
17978 (org-call-with-arg 'org-todo 'left)))
17979 ((or (and org-support-shift-select
17980 (not (eq org-support-shift-select 'always))
17981 (org-at-item-bullet-p))
17982 (and (not org-support-shift-select) (org-at-item-p)))
17983 (org-call-with-arg 'org-cycle-list-bullet 'previous))
17984 ((and (not (eq org-support-shift-select 'always))
17985 (org-at-property-p))
17986 (call-interactively 'org-property-previous-allowed-value))
17987 ((org-clocktable-try-shift 'left arg))
17988 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
17989 (org-support-shift-select
17990 (org-call-for-shift-select 'backward-char))
17991 (t (org-shiftselect-error))))
17993 (defun org-shiftcontrolright ()
17994 "Switch to next TODO set."
17995 (interactive)
17996 (cond
17997 ((and org-support-shift-select (org-region-active-p))
17998 (org-call-for-shift-select 'forward-word))
17999 ((and (not (eq org-support-shift-select 'always))
18000 (org-on-heading-p))
18001 (org-call-with-arg 'org-todo 'nextset))
18002 (org-support-shift-select
18003 (org-call-for-shift-select 'forward-word))
18004 (t (org-shiftselect-error))))
18006 (defun org-shiftcontrolleft ()
18007 "Switch to previous TODO set."
18008 (interactive)
18009 (cond
18010 ((and org-support-shift-select (org-region-active-p))
18011 (org-call-for-shift-select 'backward-word))
18012 ((and (not (eq org-support-shift-select 'always))
18013 (org-on-heading-p))
18014 (org-call-with-arg 'org-todo 'previousset))
18015 (org-support-shift-select
18016 (org-call-for-shift-select 'backward-word))
18017 (t (org-shiftselect-error))))
18019 (defun org-shiftcontrolup ()
18020 "Change timestamps synchronously up in CLOCK log lines."
18021 (interactive)
18022 (cond ((and (not org-support-shift-select)
18023 (org-at-clock-log-p)
18024 (org-at-timestamp-p t))
18025 (org-clock-timestamps-up))
18026 (t (org-shiftselect-error))))
18028 (defun org-shiftcontroldown ()
18029 "Change timestamps synchronously down in CLOCK log lines."
18030 (interactive)
18031 (cond ((and (not org-support-shift-select)
18032 (org-at-clock-log-p)
18033 (org-at-timestamp-p t))
18034 (org-clock-timestamps-down))
18035 (t (org-shiftselect-error))))
18037 (defun org-ctrl-c-ret ()
18038 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18039 (interactive)
18040 (cond
18041 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18042 (t (call-interactively 'org-insert-heading))))
18044 (defun org-find-visible ()
18045 (let ((s (point)))
18046 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18047 (get-char-property s 'invisible)))
18049 (defun org-find-invisible ()
18050 (let ((s (point)))
18051 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18052 (not (get-char-property s 'invisible))))
18055 (defun org-copy-visible (beg end)
18056 "Copy the visible parts of the region."
18057 (interactive "r")
18058 (let (snippets s)
18059 (save-excursion
18060 (save-restriction
18061 (narrow-to-region beg end)
18062 (setq s (goto-char (point-min)))
18063 (while (not (= (point) (point-max)))
18064 (goto-char (org-find-invisible))
18065 (push (buffer-substring s (point)) snippets)
18066 (setq s (goto-char (org-find-visible))))))
18067 (kill-new (apply 'concat (nreverse snippets)))))
18069 (defun org-copy-special ()
18070 "Copy region in table or copy current subtree.
18071 Calls `org-table-copy' or `org-copy-subtree', depending on context.
18072 See the individual commands for more information."
18073 (interactive)
18074 (call-interactively
18075 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
18077 (defun org-cut-special ()
18078 "Cut region in table or cut current subtree.
18079 Calls `org-table-copy' or `org-cut-subtree', depending on context.
18080 See the individual commands for more information."
18081 (interactive)
18082 (call-interactively
18083 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
18085 (defun org-paste-special (arg)
18086 "Paste rectangular region into table, or past subtree relative to level.
18087 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
18088 See the individual commands for more information."
18089 (interactive "P")
18090 (if (org-at-table-p)
18091 (org-table-paste-rectangle)
18092 (org-paste-subtree arg)))
18094 (defun org-edit-special (&optional arg)
18095 "Call a special editor for the stuff at point.
18096 When at a table, call the formula editor with `org-table-edit-formulas'.
18097 When at the first line of an src example, call `org-edit-src-code'.
18098 When in an #+include line, visit the include file. Otherwise call
18099 `ffap' to visit the file at point."
18100 (interactive)
18101 ;; possibly prep session before editing source
18102 (when arg
18103 (let* ((info (org-babel-get-src-block-info))
18104 (lang (nth 0 info))
18105 (params (nth 2 info))
18106 (session (cdr (assoc :session params))))
18107 (when (and info session) ;; we are in a source-code block with a session
18108 (funcall
18109 (intern (concat "org-babel-prep-session:" lang)) session params))))
18110 (cond ;; proceed with `org-edit-special'
18111 ((save-excursion
18112 (beginning-of-line 1)
18113 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
18114 (find-file (org-trim (match-string 1))))
18115 ((org-edit-src-code))
18116 ((org-edit-fixed-width-region))
18117 ((org-at-table.el-p)
18118 (org-edit-src-code))
18119 ((or (org-at-table-p)
18120 (save-excursion
18121 (beginning-of-line 1)
18122 (looking-at "[ \t]*#\\+TBLFM:")))
18123 (call-interactively 'org-table-edit-formulas))
18124 (t (call-interactively 'ffap))))
18126 (defvar org-table-coordinate-overlays) ; defined in org-table.el
18127 (defun org-ctrl-c-ctrl-c (&optional arg)
18128 "Set tags in headline, or update according to changed information at point.
18130 This command does many different things, depending on context:
18132 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
18133 this is what we do.
18135 - If the cursor is on a statistics cookie, update it.
18137 - If the cursor is in a headline, prompt for tags and insert them
18138 into the current line, aligned to `org-tags-column'. When called
18139 with prefix arg, realign all tags in the current buffer.
18141 - If the cursor is in one of the special #+KEYWORD lines, this
18142 triggers scanning the buffer for these lines and updating the
18143 information.
18145 - If the cursor is inside a table, realign the table. This command
18146 works even if the automatic table editor has been turned off.
18148 - If the cursor is on a #+TBLFM line, re-apply the formulas to
18149 the entire table.
18151 - If the cursor is at a footnote reference or definition, jump to
18152 the corresponding definition or references, respectively.
18154 - If the cursor is a the beginning of a dynamic block, update it.
18156 - If the current buffer is a capture buffer, close note and file it.
18158 - If the cursor is on a <<<target>>>, update radio targets and
18159 corresponding links in this buffer.
18161 - If the cursor is on a numbered item in a plain list, renumber the
18162 ordered list.
18164 - If the cursor is on a checkbox, toggle it.
18166 - If the cursor is on a code block, evaluate it. The variable
18167 `org-confirm-babel-evaluate' can be used to control prompting
18168 before code block evaluation, by default every code block
18169 evaluation requires confirmation. Code block evaluation can be
18170 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
18171 (interactive "P")
18172 (let ((org-enable-table-editor t))
18173 (cond
18174 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
18175 org-occur-highlights
18176 org-latex-fragment-image-overlays)
18177 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
18178 (org-remove-occur-highlights)
18179 (org-remove-latex-fragment-image-overlays)
18180 (message "Temporary highlights/overlays removed from current buffer"))
18181 ((and (local-variable-p 'org-finish-function (current-buffer))
18182 (fboundp org-finish-function))
18183 (funcall org-finish-function))
18184 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
18185 ((or (looking-at org-property-start-re)
18186 (org-at-property-p))
18187 (call-interactively 'org-property-action))
18188 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
18189 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
18190 (or (org-on-heading-p) (org-at-item-p)))
18191 (call-interactively 'org-update-statistics-cookies))
18192 ((org-on-heading-p) (call-interactively 'org-set-tags))
18193 ((org-at-table.el-p)
18194 (message "Use C-c ' to edit table.el tables"))
18195 ((org-at-table-p)
18196 (org-table-maybe-eval-formula)
18197 (if arg
18198 (call-interactively 'org-table-recalculate)
18199 (org-table-maybe-recalculate-line))
18200 (call-interactively 'org-table-align)
18201 (orgtbl-send-table 'maybe))
18202 ((or (org-footnote-at-reference-p)
18203 (org-footnote-at-definition-p))
18204 (call-interactively 'org-footnote-action))
18205 ((org-at-item-checkbox-p)
18206 ;; Cursor at a checkbox: repair list and update checkboxes. Send
18207 ;; list only if at top item.
18208 (let* ((cbox (match-string 1))
18209 (struct (org-list-struct))
18210 (old-struct (copy-tree struct))
18211 (parents (org-list-parents-alist struct))
18212 (orderedp (org-entry-get nil "ORDERED"))
18213 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18214 block-item)
18215 ;; Use a light version of `org-toggle-checkbox' to avoid
18216 ;; computing list structure twice.
18217 (org-list-set-checkbox (point-at-bol) struct
18218 (cond
18219 ((equal arg '(16)) "[-]")
18220 ((equal arg '(4)) nil)
18221 ((equal "[X]" cbox) "[ ]")
18222 (t "[X]")))
18223 ;; Replicate `org-list-write-struct', while grabbing a return
18224 ;; value from `org-list-struct-fix-box'.
18225 (org-list-struct-fix-ind struct parents 2)
18226 (org-list-struct-fix-item-end struct)
18227 (let ((prevs (org-list-prevs-alist struct)))
18228 (org-list-struct-fix-bul struct prevs)
18229 (org-list-struct-fix-ind struct parents)
18230 (setq block-item
18231 (org-list-struct-fix-box struct parents prevs orderedp)))
18232 (org-list-struct-apply-struct struct old-struct)
18233 (org-update-checkbox-count-maybe)
18234 (when block-item
18235 (message
18236 "Checkboxes were removed due to unchecked box at line %d"
18237 (org-current-line block-item)))
18238 (when firstp (org-list-send-list 'maybe))))
18239 ((org-at-item-p)
18240 ;; Cursor at an item: repair list. Do checkbox related actions
18241 ;; only if function was called with an argument. Send list only
18242 ;; if at top item.
18243 (let* ((struct (org-list-struct))
18244 (firstp (= (org-list-get-top-point struct) (point-at-bol))))
18245 (when arg (org-list-set-checkbox (point-at-bol) struct "[ ]"))
18246 (org-list-write-struct struct (org-list-parents-alist struct))
18247 (when arg (org-update-checkbox-count-maybe))
18248 (when firstp (org-list-send-list 'maybe))))
18249 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
18250 ;; Dynamic block
18251 (beginning-of-line 1)
18252 (save-excursion (org-update-dblock)))
18253 ((save-excursion
18254 (beginning-of-line 1)
18255 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
18256 (cond
18257 ((equal (match-string 1) "TBLFM")
18258 ;; Recalculate the table before this line
18259 (save-excursion
18260 (beginning-of-line 1)
18261 (skip-chars-backward " \r\n\t")
18262 (if (org-at-table-p)
18263 (org-call-with-arg 'org-table-recalculate (or arg t)))))
18265 (let ((org-inhibit-startup-visibility-stuff t)
18266 (org-startup-align-all-tables nil))
18267 (when (boundp 'org-table-coordinate-overlays)
18268 (mapc 'delete-overlay org-table-coordinate-overlays)
18269 (setq org-table-coordinate-overlays nil))
18270 (org-save-outline-visibility 'use-markers (org-mode-restart)))
18271 (message "Local setup has been refreshed"))))
18272 ((org-clock-update-time-maybe))
18274 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
18275 (error "C-c C-c can do nothing useful at this location"))))))
18277 (defun org-mode-restart ()
18278 "Restart Org-mode, to scan again for special lines.
18279 Also updates the keyword regular expressions."
18280 (interactive)
18281 (org-mode)
18282 (message "Org-mode restarted"))
18284 (defun org-kill-note-or-show-branches ()
18285 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
18286 (interactive)
18287 (if (not org-finish-function)
18288 (progn
18289 (hide-subtree)
18290 (call-interactively 'show-branches))
18291 (let ((org-note-abort t))
18292 (funcall org-finish-function))))
18294 (defun org-return (&optional indent)
18295 "Goto next table row or insert a newline.
18296 Calls `org-table-next-row' or `newline', depending on context.
18297 See the individual commands for more information."
18298 (interactive)
18299 (cond
18300 ((bobp) (if indent (newline-and-indent) (newline)))
18301 ((org-at-table-p)
18302 (org-table-justify-field-maybe)
18303 (call-interactively 'org-table-next-row))
18304 ;; when `newline-and-indent' is called within a list, make sure
18305 ;; text moved stays inside the item.
18306 ((and (org-in-item-p) indent)
18307 (if (and (org-at-item-p) (>= (point) (match-end 0)))
18308 (progn
18309 (save-match-data (newline))
18310 (org-indent-line-to (length (match-string 0))))
18311 (let ((ind (org-get-indentation)))
18312 (newline)
18313 (if (org-looking-back org-list-end-re)
18314 (org-indent-line-function)
18315 (org-indent-line-to ind)))))
18316 ((and org-return-follows-link
18317 (let ((tprop (get-text-property (point) 'face)))
18318 (or (eq tprop 'org-link)
18319 (and (listp tprop) (memq 'org-link tprop)))))
18320 (call-interactively 'org-open-at-point))
18321 ((and (org-at-heading-p)
18322 (looking-at
18323 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
18324 (org-show-entry)
18325 (end-of-line 1)
18326 (newline))
18327 (t (if indent (newline-and-indent) (newline)))))
18329 (defun org-return-indent ()
18330 "Goto next table row or insert a newline and indent.
18331 Calls `org-table-next-row' or `newline-and-indent', depending on
18332 context. See the individual commands for more information."
18333 (interactive)
18334 (org-return t))
18336 (defun org-ctrl-c-star ()
18337 "Compute table, or change heading status of lines.
18338 Calls `org-table-recalculate' or `org-toggle-heading',
18339 depending on context."
18340 (interactive)
18341 (cond
18342 ((org-at-table-p)
18343 (call-interactively 'org-table-recalculate))
18345 ;; Convert all lines in region to list items
18346 (call-interactively 'org-toggle-heading))))
18348 (defun org-ctrl-c-minus ()
18349 "Insert separator line in table or modify bullet status of line.
18350 Also turns a plain line or a region of lines into list items.
18351 Calls `org-table-insert-hline', `org-toggle-item', or
18352 `org-cycle-list-bullet', depending on context."
18353 (interactive)
18354 (cond
18355 ((org-at-table-p)
18356 (call-interactively 'org-table-insert-hline))
18357 ((org-region-active-p)
18358 (call-interactively 'org-toggle-item))
18359 ((org-in-item-p)
18360 (call-interactively 'org-cycle-list-bullet))
18362 (call-interactively 'org-toggle-item))))
18364 (defun org-toggle-item (arg)
18365 "Convert headings or normal lines to items, items to normal lines.
18366 If there is no active region, only the current line is considered.
18368 If the first non blank line in the region is an headline, convert
18369 all headlines to items, shifting text accordingly.
18371 If it is an item, convert all items to normal lines.
18373 If it is normal text, change region into an item. With a prefix
18374 argument ARG, change each line in region into an item."
18375 (interactive "P")
18376 (let ((shift-text
18377 (function
18378 ;; Shift text in current section to IND, from point to END.
18379 ;; The function leaves point to END line.
18380 (lambda (ind end)
18381 (let ((min-i 1000) (end (copy-marker end)))
18382 ;; First determine the minimum indentation (MIN-I) of
18383 ;; the text.
18384 (save-excursion
18385 (catch 'exit
18386 (while (< (point) end)
18387 (let ((i (org-get-indentation)))
18388 (cond
18389 ;; Skip blank lines and inline tasks.
18390 ((looking-at "^[ \t]*$"))
18391 ((looking-at org-outline-regexp-bol))
18392 ;; We can't find less than 0 indentation.
18393 ((zerop i) (throw 'exit (setq min-i 0)))
18394 ((< i min-i) (setq min-i i))))
18395 (forward-line))))
18396 ;; Then indent each line so that a line indented to
18397 ;; MIN-I becomes indented to IND. Ignore blank lines
18398 ;; and inline tasks in the process.
18399 (let ((delta (- ind min-i)))
18400 (while (< (point) end)
18401 (unless (or (looking-at "^[ \t]*$")
18402 (looking-at org-outline-regexp-bol))
18403 (org-indent-line-to (+ (org-get-indentation) delta)))
18404 (forward-line)))))))
18405 (skip-blanks
18406 (function
18407 ;; Return beginning of first non-blank line, starting from
18408 ;; line at POS.
18409 (lambda (pos)
18410 (save-excursion
18411 (goto-char pos)
18412 (skip-chars-forward " \r\t\n")
18413 (point-at-bol)))))
18414 beg end)
18415 ;; Determine boundaries of changes.
18416 (if (org-region-active-p)
18417 (setq beg (funcall skip-blanks (region-beginning))
18418 end (copy-marker (region-end)))
18419 (setq beg (funcall skip-blanks (point-at-bol))
18420 end (copy-marker (point-at-eol))))
18421 ;; Depending on the starting line, choose an action on the text
18422 ;; between BEG and END.
18423 (org-with-limited-levels
18424 (save-excursion
18425 (goto-char beg)
18426 (cond
18427 ;; Case 1. Start at an item: de-itemize. Note that it only
18428 ;; happens when a region is active: `org-ctrl-c-minus'
18429 ;; would call `org-cycle-list-bullet' otherwise.
18430 ((org-at-item-p)
18431 (while (< (point) end)
18432 (when (org-at-item-p)
18433 (skip-chars-forward " \t")
18434 (delete-region (point) (match-end 0)))
18435 (forward-line)))
18436 ;; Case 2. Start at an heading: convert to items.
18437 ((org-on-heading-p)
18438 (let* ((bul (org-list-bullet-string "-"))
18439 (bul-len (length bul))
18440 ;; Indentation of the first heading. It should be
18441 ;; relative to the indentation of its parent, if any.
18442 (start-ind (save-excursion
18443 (cond
18444 ((not org-adapt-indentation) 0)
18445 ((not (outline-previous-heading)) 0)
18446 (t (length (match-string 0))))))
18447 ;; Level of first heading. Further headings will be
18448 ;; compared to it to determine hierarchy in the list.
18449 (ref-level (org-reduced-level (org-outline-level))))
18450 (while (< (point) end)
18451 (let* ((level (org-reduced-level (org-outline-level)))
18452 (delta (max 0 (- level ref-level))))
18453 ;; If current headline is less indented than the first
18454 ;; one, set it as reference, in order to preserve
18455 ;; subtrees.
18456 (when (< level ref-level) (setq ref-level level))
18457 (replace-match bul t t)
18458 (org-indent-line-to (+ start-ind (* delta bul-len)))
18459 ;; Ensure all text down to END (or SECTION-END) belongs
18460 ;; to the newly created item.
18461 (let ((section-end (save-excursion
18462 (or (outline-next-heading) (point)))))
18463 (forward-line)
18464 (funcall shift-text
18465 (+ start-ind (* (1+ delta) bul-len))
18466 (min end section-end)))))))
18467 ;; Case 3. Normal line with ARG: turn each non-item line into
18468 ;; an item.
18469 (arg
18470 (while (< (point) end)
18471 (unless (or (org-on-heading-p) (org-at-item-p))
18472 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
18473 (replace-match
18474 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
18475 (forward-line)))
18476 ;; Case 4. Normal line without ARG: make the first line of
18477 ;; region an item, and shift indentation of others
18478 ;; lines to set them as item's body.
18479 (t (let* ((bul (org-list-bullet-string "-"))
18480 (bul-len (length bul))
18481 (ref-ind (org-get-indentation)))
18482 (skip-chars-forward " \t")
18483 (insert bul)
18484 (forward-line)
18485 (while (< (point) end)
18486 ;; Ensure that lines less indented than first one
18487 ;; still get included in item body.
18488 (funcall shift-text
18489 (+ ref-ind bul-len)
18490 (min end (save-excursion (or (outline-next-heading)
18491 (point)))))
18492 (forward-line)))))))))
18494 (defun org-toggle-heading (&optional nstars)
18495 "Convert headings to normal text, or items or text to headings.
18496 If there is no active region, only the current line is considered.
18498 If the first non blank line is an headline, remove the stars from
18499 all headlines in the region.
18501 If it is a plain list item, turn all plain list items into headings.
18503 If it is a normal line, turn each and every normal line (i.e. not
18504 an heading or an item) in the region into a heading.
18506 When converting a line into a heading, the number of stars is chosen
18507 such that the lines become children of the current entry. However,
18508 when a prefix argument is given, its value determines the number of
18509 stars to add."
18510 (interactive "P")
18511 (let ((skip-blanks
18512 (function
18513 ;; Return beginning of first non-blank line, starting from
18514 ;; line at POS.
18515 (lambda (pos)
18516 (save-excursion
18517 (goto-char pos)
18518 (skip-chars-forward " \r\t\n")
18519 (point-at-bol)))))
18520 beg end)
18521 ;; Determine boundaries of changes. If region ends at a bol, do
18522 ;; not consider the last line to be in the region.
18523 (if (org-region-active-p)
18524 (setq beg (funcall skip-blanks (region-beginning))
18525 end (copy-marker (save-excursion
18526 (goto-char (region-end))
18527 (if (bolp) (point) (point-at-eol)))))
18528 (setq beg (funcall skip-blanks (point-at-bol))
18529 end (copy-marker (point-at-eol))))
18530 ;; Ensure inline tasks don't count as headings.
18531 (org-with-limited-levels
18532 (save-excursion
18533 (goto-char beg)
18534 (cond
18535 ;; Case 1. Started at an heading: de-star headings.
18536 ((org-on-heading-p)
18537 (while (< (point) end)
18538 (when (org-on-heading-p t)
18539 (looking-at org-outline-regexp) (replace-match ""))
18540 (forward-line)))
18541 ;; Case 2. Started at an item: change items into headlines.
18542 ;; One star will be added by `org-list-to-subtree'.
18543 ((org-at-item-p)
18544 (let* ((stars (make-string
18545 (if nstars
18546 ;; subtract the star that will be added again by
18547 ;; `org-list-to-subtree'
18548 (1- (prefix-numeric-value current-prefix-arg))
18549 (or (org-current-level) 0))
18550 ?*))
18551 (add-stars
18552 (cond (nstars "") ; stars from prefix only
18553 ((equal stars "") "") ; before first heading
18554 (org-odd-levels-only "*") ; inside heading, odd
18555 (t "")))) ; inside heading, oddeven
18556 (while (< (point) end)
18557 (when (org-at-item-p)
18558 ;; Pay attention to cases when region ends before list.
18559 (let* ((struct (org-list-struct))
18560 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
18561 (save-restriction
18562 (narrow-to-region (point) list-end)
18563 (insert
18564 (org-list-to-subtree
18565 (org-list-parse-list t)
18566 '(:istart (concat stars add-stars (funcall get-stars depth))
18567 :icount (concat stars add-stars (funcall get-stars depth))))))))
18568 (forward-line))))
18569 ;; Case 3. Started at normal text: make every line an heading,
18570 ;; skipping headlines and items.
18571 (t (let* ((stars (make-string
18572 (if nstars
18573 (prefix-numeric-value current-prefix-arg)
18574 (or (org-current-level) 0))
18575 ?*))
18576 (add-stars
18577 (cond (nstars "") ; stars from prefix only
18578 ((equal stars "") "*") ; before first heading
18579 (org-odd-levels-only "**") ; inside heading, odd
18580 (t "*"))) ; inside heading, oddeven
18581 (rpl (concat stars add-stars " ")))
18582 (while (< (point) end)
18583 (when (and (not (org-on-heading-p)) (not (org-at-item-p))
18584 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
18585 (replace-match (concat rpl (match-string 2))))
18586 (forward-line)))))))))
18588 (defun org-meta-return (&optional arg)
18589 "Insert a new heading or wrap a region in a table.
18590 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
18591 See the individual commands for more information."
18592 (interactive "P")
18593 (cond
18594 ((run-hook-with-args-until-success 'org-metareturn-hook))
18595 ((org-at-table-p)
18596 (call-interactively 'org-table-wrap-region))
18597 (t (call-interactively 'org-insert-heading))))
18599 ;;; Menu entries
18601 ;; Define the Org-mode menus
18602 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
18603 '("Tbl"
18604 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
18605 ["Next Field" org-cycle (org-at-table-p)]
18606 ["Previous Field" org-shifttab (org-at-table-p)]
18607 ["Next Row" org-return (org-at-table-p)]
18608 "--"
18609 ["Blank Field" org-table-blank-field (org-at-table-p)]
18610 ["Edit Field" org-table-edit-field (org-at-table-p)]
18611 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
18612 "--"
18613 ("Column"
18614 ["Move Column Left" org-metaleft (org-at-table-p)]
18615 ["Move Column Right" org-metaright (org-at-table-p)]
18616 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
18617 ["Insert Column" org-shiftmetaright (org-at-table-p)])
18618 ("Row"
18619 ["Move Row Up" org-metaup (org-at-table-p)]
18620 ["Move Row Down" org-metadown (org-at-table-p)]
18621 ["Delete Row" org-shiftmetaup (org-at-table-p)]
18622 ["Insert Row" org-shiftmetadown (org-at-table-p)]
18623 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
18624 "--"
18625 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
18626 ("Rectangle"
18627 ["Copy Rectangle" org-copy-special (org-at-table-p)]
18628 ["Cut Rectangle" org-cut-special (org-at-table-p)]
18629 ["Paste Rectangle" org-paste-special (org-at-table-p)]
18630 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
18631 "--"
18632 ("Calculate"
18633 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
18634 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
18635 ["Edit Formulas" org-edit-special (org-at-table-p)]
18636 "--"
18637 ["Recalculate line" org-table-recalculate (org-at-table-p)]
18638 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
18639 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
18640 "--"
18641 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
18642 "--"
18643 ["Sum Column/Rectangle" org-table-sum
18644 (or (org-at-table-p) (org-region-active-p))]
18645 ["Which Column?" org-table-current-column (org-at-table-p)])
18646 ["Debug Formulas"
18647 org-table-toggle-formula-debugger
18648 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
18649 ["Show Col/Row Numbers"
18650 org-table-toggle-coordinate-overlays
18651 :style toggle
18652 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
18653 "--"
18654 ["Create" org-table-create (and (not (org-at-table-p))
18655 org-enable-table-editor)]
18656 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
18657 ["Import from File" org-table-import (not (org-at-table-p))]
18658 ["Export to File" org-table-export (org-at-table-p)]
18659 "--"
18660 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
18662 (easy-menu-define org-org-menu org-mode-map "Org menu"
18663 '("Org"
18664 ("Show/Hide"
18665 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
18666 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
18667 ["Sparse Tree..." org-sparse-tree t]
18668 ["Reveal Context" org-reveal t]
18669 ["Show All" show-all t]
18670 "--"
18671 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
18672 "--"
18673 ["New Heading" org-insert-heading t]
18674 ("Navigate Headings"
18675 ["Up" outline-up-heading t]
18676 ["Next" outline-next-visible-heading t]
18677 ["Previous" outline-previous-visible-heading t]
18678 ["Next Same Level" outline-forward-same-level t]
18679 ["Previous Same Level" outline-backward-same-level t]
18680 "--"
18681 ["Jump" org-goto t])
18682 ("Edit Structure"
18683 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
18684 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
18685 "--"
18686 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
18687 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
18688 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
18689 "--"
18690 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
18691 "--"
18692 ["Copy visible text" org-copy-visible t]
18693 "--"
18694 ["Promote Heading" org-metaleft (not (org-at-table-p))]
18695 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
18696 ["Demote Heading" org-metaright (not (org-at-table-p))]
18697 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
18698 "--"
18699 ["Sort Region/Children" org-sort (not (org-at-table-p))]
18700 "--"
18701 ["Convert to odd levels" org-convert-to-odd-levels t]
18702 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
18703 ("Editing"
18704 ["Emphasis..." org-emphasize t]
18705 ["Edit Source Example" org-edit-special t]
18706 "--"
18707 ["Footnote new/jump" org-footnote-action t]
18708 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
18709 ("Archive"
18710 ["Archive (default method)" org-archive-subtree-default t]
18711 "--"
18712 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
18713 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
18714 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
18716 "--"
18717 ("Hyperlinks"
18718 ["Store Link (Global)" org-store-link t]
18719 ["Find existing link to here" org-occur-link-in-agenda-files t]
18720 ["Insert Link" org-insert-link t]
18721 ["Follow Link" org-open-at-point t]
18722 "--"
18723 ["Next link" org-next-link t]
18724 ["Previous link" org-previous-link t]
18725 "--"
18726 ["Descriptive Links"
18727 org-toggle-link-display
18728 :style radio
18729 :selected org-descriptive-links
18731 ["Literal Links"
18732 org-toggle-link-display
18733 :style radio
18734 :selected (not org-descriptive-links)])
18735 "--"
18736 ("TODO Lists"
18737 ["TODO/DONE/-" org-todo t]
18738 ("Select keyword"
18739 ["Next keyword" org-shiftright (org-on-heading-p)]
18740 ["Previous keyword" org-shiftleft (org-on-heading-p)]
18741 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
18742 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
18743 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
18744 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
18745 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
18746 "--"
18747 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
18748 :selected org-enforce-todo-dependencies :style toggle :active t]
18749 "Settings for tree at point"
18750 ["Do Children sequentially" org-toggle-ordered-property :style radio
18751 :selected (org-entry-get nil "ORDERED")
18752 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
18753 ["Do Children parallel" org-toggle-ordered-property :style radio
18754 :selected (not (org-entry-get nil "ORDERED"))
18755 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
18756 "--"
18757 ["Set Priority" org-priority t]
18758 ["Priority Up" org-shiftup t]
18759 ["Priority Down" org-shiftdown t]
18760 "--"
18761 ["Get news from all feeds" org-feed-update-all t]
18762 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
18763 ["Customize feeds" (customize-variable 'org-feed-alist) t])
18764 ("TAGS and Properties"
18765 ["Set Tags" org-set-tags-command t]
18766 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
18767 "--"
18768 ["Set property" org-set-property t]
18769 ["Column view of properties" org-columns t]
18770 ["Insert Column View DBlock" org-insert-columns-dblock t])
18771 ("Dates and Scheduling"
18772 ["Timestamp" org-time-stamp t]
18773 ["Timestamp (inactive)" org-time-stamp-inactive t]
18774 ("Change Date"
18775 ["1 Day Later" org-shiftright t]
18776 ["1 Day Earlier" org-shiftleft t]
18777 ["1 ... Later" org-shiftup t]
18778 ["1 ... Earlier" org-shiftdown t])
18779 ["Compute Time Range" org-evaluate-time-range t]
18780 ["Schedule Item" org-schedule t]
18781 ["Deadline" org-deadline t]
18782 "--"
18783 ["Custom time format" org-toggle-time-stamp-overlays
18784 :style radio :selected org-display-custom-times]
18785 "--"
18786 ["Goto Calendar" org-goto-calendar t]
18787 ["Date from Calendar" org-date-from-calendar t]
18788 "--"
18789 ["Start/Restart Timer" org-timer-start t]
18790 ["Pause/Continue Timer" org-timer-pause-or-continue t]
18791 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
18792 ["Insert Timer String" org-timer t]
18793 ["Insert Timer Item" org-timer-item t])
18794 ("Logging work"
18795 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
18796 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
18797 ["Clock out" org-clock-out t]
18798 ["Clock cancel" org-clock-cancel t]
18799 "--"
18800 ["Mark as default task" org-clock-mark-default-task t]
18801 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
18802 ["Goto running clock" org-clock-goto t]
18803 "--"
18804 ["Display times" org-clock-display t]
18805 ["Create clock table" org-clock-report t]
18806 "--"
18807 ["Record DONE time"
18808 (progn (setq org-log-done (not org-log-done))
18809 (message "Switching to %s will %s record a timestamp"
18810 (car org-done-keywords)
18811 (if org-log-done "automatically" "not")))
18812 :style toggle :selected org-log-done])
18813 "--"
18814 ["Agenda Command..." org-agenda t]
18815 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
18816 ("File List for Agenda")
18817 ("Special views current file"
18818 ["TODO Tree" org-show-todo-tree t]
18819 ["Check Deadlines" org-check-deadlines t]
18820 ["Timeline" org-timeline t]
18821 ["Tags/Property tree" org-match-sparse-tree t])
18822 "--"
18823 ["Export/Publish..." org-export t]
18824 ("LaTeX"
18825 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
18826 :selected org-cdlatex-mode]
18827 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
18828 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
18829 ["Modify math symbol" org-cdlatex-math-modify
18830 (org-inside-LaTeX-fragment-p)]
18831 ["Insert citation" org-reftex-citation t]
18832 "--"
18833 ["Template for BEAMER" org-insert-beamer-options-template t])
18834 "--"
18835 ("MobileOrg"
18836 ["Push Files and Views" org-mobile-push t]
18837 ["Get Captured and Flagged" org-mobile-pull t]
18838 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
18839 "--"
18840 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
18841 "--"
18842 ("Documentation"
18843 ["Show Version" org-version t]
18844 ["Info Documentation" org-info t])
18845 ("Customize"
18846 ["Browse Org Group" org-customize t]
18847 "--"
18848 ["Expand This Menu" org-create-customize-menu
18849 (fboundp 'customize-menu-create)])
18850 ["Send bug report" org-submit-bug-report t]
18851 "--"
18852 ("Refresh/Reload"
18853 ["Refresh setup current buffer" org-mode-restart t]
18854 ["Reload Org (after update)" org-reload t]
18855 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
18858 (defun org-info (&optional node)
18859 "Read documentation for Org-mode in the info system.
18860 With optional NODE, go directly to that node."
18861 (interactive)
18862 (info (format "(org)%s" (or node ""))))
18864 ;;;###autoload
18865 (defun org-submit-bug-report ()
18866 "Submit a bug report on Org-mode via mail.
18868 Don't hesitate to report any problems or inaccurate documentation.
18870 If you don't have setup sending mail from (X)Emacs, please copy the
18871 output buffer into your mail program, as it gives us important
18872 information about your Org-mode version and configuration."
18873 (interactive)
18874 (require 'reporter)
18875 (org-load-modules-maybe)
18876 (org-require-autoloaded-modules)
18877 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
18878 (reporter-submit-bug-report
18879 "emacs-orgmode@gnu.org"
18880 (org-version)
18881 (let (list)
18882 (save-window-excursion
18883 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
18884 (delete-other-windows)
18885 (erase-buffer)
18886 (insert "You are about to submit a bug report to the Org-mode mailing list.
18888 We would like to add your full Org-mode and Outline configuration to the
18889 bug report. This greatly simplifies the work of the maintainer and
18890 other experts on the mailing list.
18892 HOWEVER, some variables you have customized may contain private
18893 information. The names of customers, colleagues, or friends, might
18894 appear in the form of file names, tags, todo states, or search strings.
18895 If you answer yes to the prompt, you might want to check and remove
18896 such private information before sending the email.")
18897 (add-text-properties (point-min) (point-max) '(face org-warning))
18898 (when (yes-or-no-p "Include your Org-mode configuration ")
18899 (mapatoms
18900 (lambda (v)
18901 (and (boundp v)
18902 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
18903 (or (and (symbol-value v)
18904 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
18905 (and
18906 (get v 'custom-type) (get v 'standard-value)
18907 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
18908 (push v list)))))
18909 (kill-buffer (get-buffer "*Warn about privacy*"))
18910 list))
18911 nil nil
18912 "Remember to cover the basics, that is, what you expected to happen and
18913 what in fact did happen. You don't know how to make a good report? See
18915 http://orgmode.org/manual/Feedback.html#Feedback
18917 Your bug report will be posted to the Org-mode mailing list.
18918 ------------------------------------------------------------------------")
18919 (save-excursion
18920 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
18921 (replace-match "\\1Bug: \\3 [\\2]")))))
18924 (defun org-install-agenda-files-menu ()
18925 (let ((bl (buffer-list)))
18926 (save-excursion
18927 (while bl
18928 (set-buffer (pop bl))
18929 (if (eq major-mode 'org-mode) (setq bl nil)))
18930 (when (eq major-mode 'org-mode)
18931 (easy-menu-change
18932 '("Org") "File List for Agenda"
18933 (append
18934 (list
18935 ["Edit File List" (org-edit-agenda-file-list) t]
18936 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
18937 ["Remove Current File from List" org-remove-file t]
18938 ["Cycle through agenda files" org-cycle-agenda-files t]
18939 ["Occur in all agenda files" org-occur-in-agenda-files t]
18940 "--")
18941 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
18943 ;;;; Documentation
18945 ;;;###autoload
18946 (defun org-require-autoloaded-modules ()
18947 (interactive)
18948 (mapc 'require
18949 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
18950 org-docbook org-exp org-html org-icalendar
18951 org-id org-latex
18952 org-publish org-remember org-table
18953 org-timer org-xoxo)))
18955 ;;;###autoload
18956 (defun org-reload (&optional uncompiled)
18957 "Reload all org lisp files.
18958 With prefix arg UNCOMPILED, load the uncompiled versions."
18959 (interactive "P")
18960 (require 'find-func)
18961 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
18962 (dir-org (file-name-directory (org-find-library-name "org")))
18963 (dir-org-contrib (ignore-errors
18964 (file-name-directory
18965 (org-find-library-name "org-contribdir"))))
18966 (babel-files
18967 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
18968 (append (list nil "comint" "eval" "exp" "keys"
18969 "lob" "ref" "table" "tangle")
18970 (delq nil
18971 (mapcar
18972 (lambda (lang)
18973 (when (cdr lang) (symbol-name (car lang))))
18974 org-babel-load-languages)))))
18975 (files
18976 (append (directory-files dir-org t file-re)
18977 babel-files
18978 (and dir-org-contrib
18979 (directory-files dir-org-contrib t file-re))))
18980 (remove-re (concat (if (featurep 'xemacs)
18981 "org-colview" "org-colview-xemacs")
18982 "\\'")))
18983 (setq files (mapcar 'file-name-sans-extension files))
18984 (setq files (mapcar
18985 (lambda (x) (if (string-match remove-re x) nil x))
18986 files))
18987 (setq files (delq nil files))
18988 (mapc
18989 (lambda (f)
18990 (when (featurep (intern (file-name-nondirectory f)))
18991 (if (and (not uncompiled)
18992 (file-exists-p (concat f ".elc")))
18993 (load (concat f ".elc") nil nil t)
18994 (load (concat f ".el") nil nil t))))
18995 files))
18996 (org-version))
18998 ;;;###autoload
18999 (defun org-customize ()
19000 "Call the customize function with org as argument."
19001 (interactive)
19002 (org-load-modules-maybe)
19003 (org-require-autoloaded-modules)
19004 (customize-browse 'org))
19006 (defun org-create-customize-menu ()
19007 "Create a full customization menu for Org-mode, insert it into the menu."
19008 (interactive)
19009 (org-load-modules-maybe)
19010 (org-require-autoloaded-modules)
19011 (if (fboundp 'customize-menu-create)
19012 (progn
19013 (easy-menu-change
19014 '("Org") "Customize"
19015 `(["Browse Org group" org-customize t]
19016 "--"
19017 ,(customize-menu-create 'org)
19018 ["Set" Custom-set t]
19019 ["Save" Custom-save t]
19020 ["Reset to Current" Custom-reset-current t]
19021 ["Reset to Saved" Custom-reset-saved t]
19022 ["Reset to Standard Settings" Custom-reset-standard t]))
19023 (message "\"Org\"-menu now contains full customization menu"))
19024 (error "Cannot expand menu (outdated version of cus-edit.el)")))
19026 ;;;; Miscellaneous stuff
19028 ;;; Generally useful functions
19030 (defun org-get-at-bol (property)
19031 "Get text property PROPERTY at beginning of line."
19032 (get-text-property (point-at-bol) property))
19034 (defun org-find-text-property-in-string (prop s)
19035 "Return the first non-nil value of property PROP in string S."
19036 (or (get-text-property 0 prop s)
19037 (get-text-property (or (next-single-property-change 0 prop s) 0)
19038 prop s)))
19040 (defun org-display-warning (message) ;; Copied from Emacs-Muse
19041 "Display the given MESSAGE as a warning."
19042 (if (fboundp 'display-warning)
19043 (display-warning 'org message
19044 (if (featurep 'xemacs) 'warning :warning))
19045 (let ((buf (get-buffer-create "*Org warnings*")))
19046 (with-current-buffer buf
19047 (goto-char (point-max))
19048 (insert "Warning (Org): " message)
19049 (unless (bolp)
19050 (newline)))
19051 (display-buffer buf)
19052 (sit-for 0))))
19054 (defun org-eval (form)
19055 "Eval FORM and return result."
19056 (condition-case error
19057 (eval form)
19058 (error (format "%%![Error: %s]" error))))
19060 (defun org-in-commented-line ()
19061 "Is point in a line starting with `#'?"
19062 (equal (char-after (point-at-bol)) ?#))
19064 (defun org-in-indented-comment-line ()
19065 "Is point in a line starting with `#' after some white space?"
19066 (save-excursion
19067 (save-match-data
19068 (goto-char (point-at-bol))
19069 (looking-at "[ \t]*#"))))
19071 (defun org-in-verbatim-emphasis ()
19072 (save-match-data
19073 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
19075 (defun org-goto-marker-or-bmk (marker &optional bookmark)
19076 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
19077 (if (and marker (marker-buffer marker)
19078 (buffer-live-p (marker-buffer marker)))
19079 (progn
19080 (org-pop-to-buffer-same-window (marker-buffer marker))
19081 (if (or (> marker (point-max)) (< marker (point-min)))
19082 (widen))
19083 (goto-char marker)
19084 (org-show-context 'org-goto))
19085 (if bookmark
19086 (bookmark-jump bookmark)
19087 (error "Cannot find location"))))
19089 (defun org-quote-csv-field (s)
19090 "Quote field for inclusion in CSV material."
19091 (if (string-match "[\",]" s)
19092 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
19095 (defun org-force-self-insert (N)
19096 "Needed to enforce self-insert under remapping."
19097 (interactive "p")
19098 (self-insert-command N))
19100 (defun org-string-width (s)
19101 "Compute width of string, ignoring invisible characters.
19102 This ignores character with invisibility property `org-link', and also
19103 characters with property `org-cwidth', because these will become invisible
19104 upon the next fontification round."
19105 (let (b l)
19106 (when (or (eq t buffer-invisibility-spec)
19107 (assq 'org-link buffer-invisibility-spec))
19108 (while (setq b (text-property-any 0 (length s)
19109 'invisible 'org-link s))
19110 (setq s (concat (substring s 0 b)
19111 (substring s (or (next-single-property-change
19112 b 'invisible s) (length s)))))))
19113 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
19114 (setq s (concat (substring s 0 b)
19115 (substring s (or (next-single-property-change
19116 b 'org-cwidth s) (length s))))))
19117 (setq l (string-width s) b -1)
19118 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
19119 (setq l (- l (get-text-property b 'org-dwidth-n s))))
19122 (defun org-shorten-string (s maxlength)
19123 "Shorten string S so tht it is no longer than MAXLENGTH characters.
19124 If the string is shorter or has length MAXLENGTH, just return the
19125 original string. If it is longer, the functions finds a space in the
19126 string, breaks this string off at that locations and adds three dots
19127 as ellipsis. Including the ellipsis, the string will not be longer
19128 than MAXLENGTH. If finding a good breaking point in the string does
19129 not work, the string is just chopped off in the middle of a word
19130 if necessary."
19131 (if (<= (length s) maxlength)
19133 (let* ((n (max (- maxlength 4) 1))
19134 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
19135 (if (string-match re s)
19136 (concat (match-string 1 s) "...")
19137 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
19139 (defun org-get-indentation (&optional line)
19140 "Get the indentation of the current line, interpreting tabs.
19141 When LINE is given, assume it represents a line and compute its indentation."
19142 (if line
19143 (if (string-match "^ *" (org-remove-tabs line))
19144 (match-end 0))
19145 (save-excursion
19146 (beginning-of-line 1)
19147 (skip-chars-forward " \t")
19148 (current-column))))
19150 (defun org-get-string-indentation (s)
19151 "What indentation has S due to SPACE and TAB at the beginning of the string?"
19152 (let ((n -1) (i 0) (w tab-width) c)
19153 (catch 'exit
19154 (while (< (setq n (1+ n)) (length s))
19155 (setq c (aref s n))
19156 (cond ((= c ?\ ) (setq i (1+ i)))
19157 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
19158 (t (throw 'exit t)))))
19161 (defun org-remove-tabs (s &optional width)
19162 "Replace tabulators in S with spaces.
19163 Assumes that s is a single line, starting in column 0."
19164 (setq width (or width tab-width))
19165 (while (string-match "\t" s)
19166 (setq s (replace-match
19167 (make-string
19168 (- (* width (/ (+ (match-beginning 0) width) width))
19169 (match-beginning 0)) ?\ )
19170 t t s)))
19173 (defun org-fix-indentation (line ind)
19174 "Fix indentation in LINE.
19175 IND is a cons cell with target and minimum indentation.
19176 If the current indentation in LINE is smaller than the minimum,
19177 leave it alone. If it is larger than ind, set it to the target."
19178 (let* ((l (org-remove-tabs line))
19179 (i (org-get-indentation l))
19180 (i1 (car ind)) (i2 (cdr ind)))
19181 (if (>= i i2) (setq l (substring line i2)))
19182 (if (> i1 0)
19183 (concat (make-string i1 ?\ ) l)
19184 l)))
19186 (defun org-remove-indentation (code &optional n)
19187 "Remove the maximum common indentation from the lines in CODE.
19188 N may optionally be the number of spaces to remove."
19189 (with-temp-buffer
19190 (insert code)
19191 (org-do-remove-indentation n)
19192 (buffer-string)))
19194 (defun org-do-remove-indentation (&optional n)
19195 "Remove the maximum common indentation from the buffer."
19196 (untabify (point-min) (point-max))
19197 (let ((min 10000) re)
19198 (if n
19199 (setq min n)
19200 (goto-char (point-min))
19201 (while (re-search-forward "^ *[^ \n]" nil t)
19202 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
19203 (unless (or (= min 0) (= min 10000))
19204 (setq re (format "^ \\{%d\\}" min))
19205 (goto-char (point-min))
19206 (while (re-search-forward re nil t)
19207 (replace-match "")
19208 (end-of-line 1))
19209 min)))
19211 (defun org-fill-template (template alist)
19212 "Find each %key of ALIST in TEMPLATE and replace it."
19213 (let ((case-fold-search nil)
19214 entry key value)
19215 (setq alist (sort (copy-sequence alist)
19216 (lambda (a b) (< (length (car a)) (length (car b))))))
19217 (while (setq entry (pop alist))
19218 (setq template
19219 (replace-regexp-in-string
19220 (concat "%" (regexp-quote (car entry)))
19221 (cdr entry) template t t)))
19222 template))
19224 (defun org-base-buffer (buffer)
19225 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
19226 (if (not buffer)
19227 buffer
19228 (or (buffer-base-buffer buffer)
19229 buffer)))
19231 (defun org-trim (s)
19232 "Remove whitespace at beginning and end of string."
19233 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
19234 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
19237 (defun org-wrap (string &optional width lines)
19238 "Wrap string to either a number of lines, or a width in characters.
19239 If WIDTH is non-nil, the string is wrapped to that width, however many lines
19240 that costs. If there is a word longer than WIDTH, the text is actually
19241 wrapped to the length of that word.
19242 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
19243 many lines, whatever width that takes.
19244 The return value is a list of lines, without newlines at the end."
19245 (let* ((words (org-split-string string "[ \t\n]+"))
19246 (maxword (apply 'max (mapcar 'org-string-width words)))
19247 w ll)
19248 (cond (width
19249 (org-do-wrap words (max maxword width)))
19250 (lines
19251 (setq w maxword)
19252 (setq ll (org-do-wrap words maxword))
19253 (if (<= (length ll) lines)
19255 (setq ll words)
19256 (while (> (length ll) lines)
19257 (setq w (1+ w))
19258 (setq ll (org-do-wrap words w)))
19259 ll))
19260 (t (error "Cannot wrap this")))))
19262 (defun org-do-wrap (words width)
19263 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
19264 (let (lines line)
19265 (while words
19266 (setq line (pop words))
19267 (while (and words (< (+ (length line) (length (car words))) width))
19268 (setq line (concat line " " (pop words))))
19269 (setq lines (push line lines)))
19270 (nreverse lines)))
19272 (defun org-split-string (string &optional separators)
19273 "Splits STRING into substrings at SEPARATORS.
19274 No empty strings are returned if there are matches at the beginning
19275 and end of string."
19276 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
19277 (start 0)
19278 notfirst
19279 (list nil))
19280 (while (and (string-match rexp string
19281 (if (and notfirst
19282 (= start (match-beginning 0))
19283 (< start (length string)))
19284 (1+ start) start))
19285 (< (match-beginning 0) (length string)))
19286 (setq notfirst t)
19287 (or (eq (match-beginning 0) 0)
19288 (and (eq (match-beginning 0) (match-end 0))
19289 (eq (match-beginning 0) start))
19290 (setq list
19291 (cons (substring string start (match-beginning 0))
19292 list)))
19293 (setq start (match-end 0)))
19294 (or (eq start (length string))
19295 (setq list
19296 (cons (substring string start)
19297 list)))
19298 (nreverse list)))
19300 (defun org-quote-vert (s)
19301 "Replace \"|\" with \"\\vert\"."
19302 (while (string-match "|" s)
19303 (setq s (replace-match "\\vert" t t s)))
19306 (defun org-uuidgen-p (s)
19307 "Is S an ID created by UUIDGEN?"
19308 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
19310 (defun org-context ()
19311 "Return a list of contexts of the current cursor position.
19312 If several contexts apply, all are returned.
19313 Each context entry is a list with a symbol naming the context, and
19314 two positions indicating start and end of the context. Possible
19315 contexts are:
19317 :headline anywhere in a headline
19318 :headline-stars on the leading stars in a headline
19319 :todo-keyword on a TODO keyword (including DONE) in a headline
19320 :tags on the TAGS in a headline
19321 :priority on the priority cookie in a headline
19322 :item on the first line of a plain list item
19323 :item-bullet on the bullet/number of a plain list item
19324 :checkbox on the checkbox in a plain list item
19325 :table in an org-mode table
19326 :table-special on a special filed in a table
19327 :table-table in a table.el table
19328 :link on a hyperlink
19329 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
19330 :target on a <<target>>
19331 :radio-target on a <<<radio-target>>>
19332 :latex-fragment on a LaTeX fragment
19333 :latex-preview on a LaTeX fragment with overlayed preview image
19335 This function expects the position to be visible because it uses font-lock
19336 faces as a help to recognize the following contexts: :table-special, :link,
19337 and :keyword."
19338 (let* ((f (get-text-property (point) 'face))
19339 (faces (if (listp f) f (list f)))
19340 (p (point)) clist o)
19341 ;; First the large context
19342 (cond
19343 ((org-on-heading-p t)
19344 (push (list :headline (point-at-bol) (point-at-eol)) clist)
19345 (when (progn
19346 (beginning-of-line 1)
19347 (looking-at org-todo-line-tags-regexp))
19348 (push (org-point-in-group p 1 :headline-stars) clist)
19349 (push (org-point-in-group p 2 :todo-keyword) clist)
19350 (push (org-point-in-group p 4 :tags) clist))
19351 (goto-char p)
19352 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
19353 (if (looking-at "\\[#[A-Z0-9]\\]")
19354 (push (org-point-in-group p 0 :priority) clist)))
19356 ((org-at-item-p)
19357 (push (org-point-in-group p 2 :item-bullet) clist)
19358 (push (list :item (point-at-bol)
19359 (save-excursion (org-end-of-item) (point)))
19360 clist)
19361 (and (org-at-item-checkbox-p)
19362 (push (org-point-in-group p 0 :checkbox) clist)))
19364 ((org-at-table-p)
19365 (push (list :table (org-table-begin) (org-table-end)) clist)
19366 (if (memq 'org-formula faces)
19367 (push (list :table-special
19368 (previous-single-property-change p 'face)
19369 (next-single-property-change p 'face)) clist)))
19370 ((org-at-table-p 'any)
19371 (push (list :table-table) clist)))
19372 (goto-char p)
19374 ;; Now the small context
19375 (cond
19376 ((org-at-timestamp-p)
19377 (push (org-point-in-group p 0 :timestamp) clist))
19378 ((memq 'org-link faces)
19379 (push (list :link
19380 (previous-single-property-change p 'face)
19381 (next-single-property-change p 'face)) clist))
19382 ((memq 'org-special-keyword faces)
19383 (push (list :keyword
19384 (previous-single-property-change p 'face)
19385 (next-single-property-change p 'face)) clist))
19386 ((org-on-target-p)
19387 (push (org-point-in-group p 0 :target) clist)
19388 (goto-char (1- (match-beginning 0)))
19389 (if (looking-at org-radio-target-regexp)
19390 (push (org-point-in-group p 0 :radio-target) clist))
19391 (goto-char p))
19392 ((setq o (car (delq nil
19393 (mapcar
19394 (lambda (x)
19395 (if (memq x org-latex-fragment-image-overlays) x))
19396 (overlays-at (point))))))
19397 (push (list :latex-fragment
19398 (overlay-start o) (overlay-end o)) clist)
19399 (push (list :latex-preview
19400 (overlay-start o) (overlay-end o)) clist))
19401 ((org-inside-LaTeX-fragment-p)
19402 ;; FIXME: positions wrong.
19403 (push (list :latex-fragment (point) (point)) clist)))
19405 (setq clist (nreverse (delq nil clist)))
19406 clist))
19408 ;; FIXME: Compare with at-regexp-p Do we need both?
19409 (defun org-in-regexp (re &optional nlines visually)
19410 "Check if point is inside a match of regexp.
19411 Normally only the current line is checked, but you can include NLINES extra
19412 lines both before and after point into the search.
19413 If VISUALLY is set, require that the cursor is not after the match but
19414 really on, so that the block visually is on the match."
19415 (catch 'exit
19416 (let ((pos (point))
19417 (eol (point-at-eol (+ 1 (or nlines 0))))
19418 (inc (if visually 1 0)))
19419 (save-excursion
19420 (beginning-of-line (- 1 (or nlines 0)))
19421 (while (re-search-forward re eol t)
19422 (if (and (<= (match-beginning 0) pos)
19423 (>= (+ inc (match-end 0)) pos))
19424 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
19426 (defun org-at-regexp-p (regexp)
19427 "Is point inside a match of REGEXP in the current line?"
19428 (catch 'exit
19429 (save-excursion
19430 (let ((pos (point)) (end (point-at-eol)))
19431 (beginning-of-line 1)
19432 (while (re-search-forward regexp end t)
19433 (if (and (<= (match-beginning 0) pos)
19434 (>= (match-end 0) pos))
19435 (throw 'exit t)))
19436 nil))))
19438 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
19439 "Non-nil when point is between matches of START-RE and END-RE.
19441 Also return a non-nil value when point is on one of the matches.
19443 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
19444 buffer positions. Default values are the positions of headlines
19445 surrounding the point.
19447 The functions returns a cons cell whose car (resp. cdr) is the
19448 position before START-RE (resp. after END-RE)."
19449 (save-match-data
19450 (let ((pos (point))
19451 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
19452 (limit-down (or lim-down (save-excursion (outline-next-heading))))
19453 beg end)
19454 (save-excursion
19455 ;; Point is on a block when on START-RE or if START-RE can be
19456 ;; found before it...
19457 (and (or (org-at-regexp-p start-re)
19458 (re-search-backward start-re limit-up t))
19459 (setq beg (match-beginning 0))
19460 ;; ... and END-RE after it...
19461 (goto-char (match-end 0))
19462 (re-search-forward end-re limit-down t)
19463 (> (setq end (match-end 0)) pos)
19464 ;; ... without another START-RE in-between.
19465 (goto-char (match-beginning 0))
19466 (not (re-search-backward start-re (1+ beg) t))
19467 ;; Return value.
19468 (cons beg end))))))
19470 (defun org-in-block-p (names)
19471 "Non-nil when point belongs to a block whose name belongs to NAMES.
19473 NAMES is a list of strings containing names of blocks.
19475 Return first block name matched, or nil. Beware that in case of
19476 nested blocks, the returned name may not belong to the closest
19477 block from point."
19478 (save-match-data
19479 (catch 'exit
19480 (let ((case-fold-search t)
19481 (lim-up (save-excursion (outline-previous-heading)))
19482 (lim-down (save-excursion (outline-next-heading))))
19483 (mapc (lambda (name)
19484 (let ((n (regexp-quote name)))
19485 (when (org-between-regexps-p
19486 (concat "^[ \t]*#\\+begin_" n)
19487 (concat "^[ \t]*#\\+end_" n)
19488 lim-up lim-down)
19489 (throw 'exit n))))
19490 names))
19491 nil)))
19493 (defun org-occur-in-agenda-files (regexp &optional nlines)
19494 "Call `multi-occur' with buffers for all agenda files."
19495 (interactive "sOrg-files matching: \np")
19496 (let* ((files (org-agenda-files))
19497 (tnames (mapcar 'file-truename files))
19498 (extra org-agenda-text-search-extra-files)
19500 (when (eq (car extra) 'agenda-archives)
19501 (setq extra (cdr extra))
19502 (setq files (org-add-archive-files files)))
19503 (while (setq f (pop extra))
19504 (unless (member (file-truename f) tnames)
19505 (add-to-list 'files f 'append)
19506 (add-to-list 'tnames (file-truename f) 'append)))
19507 (multi-occur
19508 (mapcar (lambda (x)
19509 (with-current-buffer
19510 (or (get-file-buffer x) (find-file-noselect x))
19511 (widen)
19512 (current-buffer)))
19513 files)
19514 regexp)))
19516 (if (boundp 'occur-mode-find-occurrence-hook)
19517 ;; Emacs 23
19518 (add-hook 'occur-mode-find-occurrence-hook
19519 (lambda ()
19520 (when (eq major-mode 'org-mode)
19521 (org-reveal))))
19522 ;; Emacs 22
19523 (defadvice occur-mode-goto-occurrence
19524 (after org-occur-reveal activate)
19525 (and (eq major-mode 'org-mode) (org-reveal)))
19526 (defadvice occur-mode-goto-occurrence-other-window
19527 (after org-occur-reveal activate)
19528 (and (eq major-mode 'org-mode) (org-reveal)))
19529 (defadvice occur-mode-display-occurrence
19530 (after org-occur-reveal activate)
19531 (when (eq major-mode 'org-mode)
19532 (let ((pos (occur-mode-find-occurrence)))
19533 (with-current-buffer (marker-buffer pos)
19534 (save-excursion
19535 (goto-char pos)
19536 (org-reveal)))))))
19538 (defun org-occur-link-in-agenda-files ()
19539 "Create a link and search for it in the agendas.
19540 The link is not stored in `org-stored-links', it is just created
19541 for the search purpose."
19542 (interactive)
19543 (let ((link (condition-case nil
19544 (org-store-link nil)
19545 (error "Unable to create a link to here"))))
19546 (org-occur-in-agenda-files (regexp-quote link))))
19548 (defun org-uniquify (list)
19549 "Remove duplicate elements from LIST."
19550 (let (res)
19551 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
19552 res))
19554 (defun org-delete-all (elts list)
19555 "Remove all elements in ELTS from LIST."
19556 (while elts
19557 (setq list (delete (pop elts) list)))
19558 list)
19560 (defun org-count (cl-item cl-seq)
19561 "Count the number of occurrences of ITEM in SEQ.
19562 Taken from `count' in cl-seq.el with all keyword arguments removed."
19563 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
19564 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
19565 (while (< cl-start cl-end)
19566 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
19567 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
19568 (setq cl-start (1+ cl-start)))
19569 cl-count))
19571 (defun org-remove-if (predicate seq)
19572 "Remove everything from SEQ that fulfills PREDICATE."
19573 (let (res e)
19574 (while seq
19575 (setq e (pop seq))
19576 (if (not (funcall predicate e)) (push e res)))
19577 (nreverse res)))
19579 (defun org-remove-if-not (predicate seq)
19580 "Remove everything from SEQ that does not fulfill PREDICATE."
19581 (let (res e)
19582 (while seq
19583 (setq e (pop seq))
19584 (if (funcall predicate e) (push e res)))
19585 (nreverse res)))
19587 (defun org-back-over-empty-lines ()
19588 "Move backwards over whitespace, to the beginning of the first empty line.
19589 Returns the number of empty lines passed."
19590 (let ((pos (point)))
19591 (if (cdr (assoc 'heading org-blank-before-new-entry))
19592 (skip-chars-backward " \t\n\r")
19593 (unless (eobp)
19594 (forward-line -1)))
19595 (beginning-of-line 2)
19596 (goto-char (min (point) pos))
19597 (count-lines (point) pos)))
19599 (defun org-skip-whitespace ()
19600 (skip-chars-forward " \t\n\r"))
19602 (defun org-point-in-group (point group &optional context)
19603 "Check if POINT is in match-group GROUP.
19604 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
19605 match. If the match group does not exist or point is not inside it,
19606 return nil."
19607 (and (match-beginning group)
19608 (>= point (match-beginning group))
19609 (<= point (match-end group))
19610 (if context
19611 (list context (match-beginning group) (match-end group))
19612 t)))
19614 (defun org-switch-to-buffer-other-window (&rest args)
19615 "Switch to buffer in a second window on the current frame.
19616 In particular, do not allow pop-up frames.
19617 Returns the newly created buffer."
19618 (let (pop-up-frames special-display-buffer-names special-display-regexps
19619 special-display-function)
19620 (apply 'switch-to-buffer-other-window args)))
19622 (defun org-combine-plists (&rest plists)
19623 "Create a single property list from all plists in PLISTS.
19624 The process starts by copying the first list, and then setting properties
19625 from the other lists. Settings in the last list are the most significant
19626 ones and overrule settings in the other lists."
19627 (let ((rtn (copy-sequence (pop plists)))
19628 p v ls)
19629 (while plists
19630 (setq ls (pop plists))
19631 (while ls
19632 (setq p (pop ls) v (pop ls))
19633 (setq rtn (plist-put rtn p v))))
19634 rtn))
19636 (defun org-move-line-down (arg)
19637 "Move the current line down. With prefix argument, move it past ARG lines."
19638 (interactive "p")
19639 (let ((col (current-column))
19640 beg end pos)
19641 (beginning-of-line 1) (setq beg (point))
19642 (beginning-of-line 2) (setq end (point))
19643 (beginning-of-line (+ 1 arg))
19644 (setq pos (move-marker (make-marker) (point)))
19645 (insert (delete-and-extract-region beg end))
19646 (goto-char pos)
19647 (org-move-to-column col)))
19649 (defun org-move-line-up (arg)
19650 "Move the current line up. With prefix argument, move it past ARG lines."
19651 (interactive "p")
19652 (let ((col (current-column))
19653 beg end pos)
19654 (beginning-of-line 1) (setq beg (point))
19655 (beginning-of-line 2) (setq end (point))
19656 (beginning-of-line (- arg))
19657 (setq pos (move-marker (make-marker) (point)))
19658 (insert (delete-and-extract-region beg end))
19659 (goto-char pos)
19660 (org-move-to-column col)))
19662 (defun org-replace-escapes (string table)
19663 "Replace %-escapes in STRING with values in TABLE.
19664 TABLE is an association list with keys like \"%a\" and string values.
19665 The sequences in STRING may contain normal field width and padding information,
19666 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
19667 so values can contain further %-escapes if they are define later in TABLE."
19668 (let ((tbl (copy-alist table))
19669 (case-fold-search nil)
19670 (pchg 0)
19671 e re rpl)
19672 (while (setq e (pop tbl))
19673 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
19674 (when (and (cdr e) (string-match re (cdr e)))
19675 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
19676 (safe "SREF"))
19677 (add-text-properties 0 3 (list 'sref sref) safe)
19678 (setcdr e (replace-match safe t t (cdr e)))))
19679 (while (string-match re string)
19680 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
19681 (cdr e)))
19682 (setq string (replace-match rpl t t string))))
19683 (while (setq pchg (next-property-change pchg string))
19684 (let ((sref (get-text-property pchg 'sref string)))
19685 (when (and sref (string-match "SREF" string pchg))
19686 (setq string (replace-match sref t t string)))))
19687 string))
19689 (defun org-sublist (list start end)
19690 "Return a section of LIST, from START to END.
19691 Counting starts at 1."
19692 (let (rtn (c start))
19693 (setq list (nthcdr (1- start) list))
19694 (while (and list (<= c end))
19695 (push (pop list) rtn)
19696 (setq c (1+ c)))
19697 (nreverse rtn)))
19699 (defun org-find-base-buffer-visiting (file)
19700 "Like `find-buffer-visiting' but always return the base buffer and
19701 not an indirect buffer."
19702 (let ((buf (or (get-file-buffer file)
19703 (find-buffer-visiting file))))
19704 (if buf
19705 (or (buffer-base-buffer buf) buf)
19706 nil)))
19708 (defun org-image-file-name-regexp (&optional extensions)
19709 "Return regexp matching the file names of images.
19710 If EXTENSIONS is given, only match these."
19711 (if (and (not extensions) (fboundp 'image-file-name-regexp))
19712 (image-file-name-regexp)
19713 (let ((image-file-name-extensions
19714 (or extensions
19715 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
19716 "xbm" "xpm" "pbm" "pgm" "ppm"))))
19717 (concat "\\."
19718 (regexp-opt (nconc (mapcar 'upcase
19719 image-file-name-extensions)
19720 image-file-name-extensions)
19722 "\\'"))))
19724 (defun org-file-image-p (file &optional extensions)
19725 "Return non-nil if FILE is an image."
19726 (save-match-data
19727 (string-match (org-image-file-name-regexp extensions) file)))
19729 (defun org-get-cursor-date ()
19730 "Return the date at cursor in as a time.
19731 This works in the calendar and in the agenda, anywhere else it just
19732 returns the current time."
19733 (let (date day defd)
19734 (cond
19735 ((eq major-mode 'calendar-mode)
19736 (setq date (calendar-cursor-to-date)
19737 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
19738 ((eq major-mode 'org-agenda-mode)
19739 (setq day (get-text-property (point) 'day))
19740 (if day
19741 (setq date (calendar-gregorian-from-absolute day)
19742 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
19743 (nth 2 date))))))
19744 (or defd (current-time))))
19746 (defvar org-agenda-action-marker (make-marker)
19747 "Marker pointing to the entry for the next agenda action.")
19749 (defun org-mark-entry-for-agenda-action ()
19750 "Mark the current entry as target of an agenda action.
19751 Agenda actions are actions executed from the agenda with the key `k',
19752 which make use of the date at the cursor."
19753 (interactive)
19754 (move-marker org-agenda-action-marker
19755 (save-excursion (org-back-to-heading t) (point))
19756 (current-buffer))
19757 (message
19758 "Entry marked for action; press `k' at desired date in agenda or calendar"))
19760 (defun org-mark-subtree ()
19761 "Mark the current subtree.
19762 This puts point at the start of the current subtree, and mark at the end.
19764 If point is in an inline task, mark that task instead."
19765 (interactive)
19766 (let ((inline-task-p
19767 (and (featurep 'org-inlinetask)
19768 (org-inlinetask-in-task-p)))
19769 (beg))
19770 ;; Get beginning of subtree
19771 (cond
19772 (inline-task-p (org-inlinetask-goto-beginning))
19773 ((org-at-heading-p) (beginning-of-line))
19774 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
19775 (setq beg (point))
19776 ;; Get end of it
19777 (if inline-task-p
19778 (org-inlinetask-goto-end)
19779 (org-end-of-subtree))
19780 ;; Mark zone
19781 (push-mark (point) nil t)
19782 (goto-char beg)))
19784 ;;; Paragraph filling stuff.
19785 ;; We want this to be just right, so use the full arsenal.
19787 (defun org-indent-line-function ()
19788 "Indent line depending on context."
19789 (interactive)
19790 (let* ((pos (point))
19791 (itemp (org-at-item-p))
19792 (case-fold-search t)
19793 (org-drawer-regexp (or org-drawer-regexp "\000"))
19794 (inline-task-p (and (featurep 'org-inlinetask)
19795 (org-inlinetask-in-task-p)))
19796 (inline-re (and inline-task-p
19797 (org-inlinetask-outline-regexp)))
19798 column)
19799 (beginning-of-line 1)
19800 (cond
19801 ;; Comments
19802 ((looking-at "# ") (setq column 0))
19803 ;; Headings
19804 ((looking-at org-outline-regexp) (setq column 0))
19805 ;; Included files
19806 ((looking-at "#\\+include:") (setq column 0))
19807 ;; Footnote definition
19808 ((looking-at org-footnote-definition-re) (setq column 0))
19809 ;; Literal examples
19810 ((looking-at "[ \t]*:\\( \\|$\\)")
19811 (setq column (org-get-indentation))) ; do nothing
19812 ;; Lists
19813 ((ignore-errors (goto-char (org-in-item-p)))
19814 (setq column (if itemp
19815 (org-get-indentation)
19816 (org-list-item-body-column (point))))
19817 (goto-char pos))
19818 ;; Drawers
19819 ((and (looking-at "[ \t]*:END:")
19820 (save-excursion (re-search-backward org-drawer-regexp nil t)))
19821 (save-excursion
19822 (goto-char (1- (match-beginning 1)))
19823 (setq column (current-column))))
19824 ;; Special blocks
19825 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
19826 (save-excursion
19827 (re-search-backward
19828 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
19829 (setq column (org-get-indentation (match-string 0))))
19830 ((and (not (looking-at "[ \t]*#\\+begin_"))
19831 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
19832 (save-excursion
19833 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
19834 (setq column
19835 (cond ((equal (downcase (match-string 1)) "src")
19836 ;; src blocks: let `org-edit-src-exit' handle them
19837 (org-get-indentation))
19838 ((equal (downcase (match-string 1)) "example")
19839 (max (org-get-indentation)
19840 (org-get-indentation (match-string 0))))
19842 (org-get-indentation (match-string 0))))))
19843 ;; This line has nothing special, look at the previous relevant
19844 ;; line to compute indentation
19846 (beginning-of-line 0)
19847 (while (and (not (bobp))
19848 (not (looking-at org-drawer-regexp))
19849 ;; When point started in an inline task, do not move
19850 ;; above task starting line.
19851 (not (and inline-task-p (looking-at inline-re)))
19852 ;; Skip drawers, blocks, empty lines, verbatim,
19853 ;; comments, tables, footnotes definitions, lists,
19854 ;; inline tasks.
19855 (or (and (looking-at "[ \t]*:END:")
19856 (re-search-backward org-drawer-regexp nil t))
19857 (and (looking-at "[ \t]*#\\+end_")
19858 (re-search-backward "[ \t]*#\\+begin_"nil t))
19859 (looking-at "[ \t]*[\n:#|]")
19860 (looking-at org-footnote-definition-re)
19861 (and (ignore-errors (goto-char (org-in-item-p)))
19862 (goto-char
19863 (org-list-get-top-point (org-list-struct))))
19864 (and (not inline-task-p)
19865 (featurep 'org-inlinetask)
19866 (org-inlinetask-in-task-p)
19867 (or (org-inlinetask-goto-beginning) t))))
19868 (beginning-of-line 0))
19869 (cond
19870 ;; There was an heading above.
19871 ((looking-at "\\*+[ \t]+")
19872 (if (not org-adapt-indentation)
19873 (setq column 0)
19874 (goto-char (match-end 0))
19875 (setq column (current-column))))
19876 ;; A drawer had started and is unfinished
19877 ((looking-at org-drawer-regexp)
19878 (goto-char (1- (match-beginning 1)))
19879 (setq column (current-column)))
19880 ;; Else, nothing noticeable found: get indentation and go on.
19881 (t (setq column (org-get-indentation))))))
19882 ;; Now apply indentation and move cursor accordingly
19883 (goto-char pos)
19884 (if (<= (current-column) (current-indentation))
19885 (org-indent-line-to column)
19886 (save-excursion (org-indent-line-to column)))
19887 ;; Special polishing for properties, see `org-property-format'
19888 (setq column (current-column))
19889 (beginning-of-line 1)
19890 (if (looking-at
19891 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
19892 (replace-match (concat (match-string 1)
19893 (format org-property-format
19894 (match-string 2) (match-string 3)))
19895 t t))
19896 (org-move-to-column column)))
19898 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
19899 "Variable to store copy of `adaptive-fill-regexp'.
19900 Since `adaptive-fill-regexp' is set to never match, we need to
19901 store a backup of its value before entering `org-mode' so that
19902 the functionality can be provided as a fall-back.")
19904 (defun org-set-autofill-regexps ()
19905 (interactive)
19906 ;; In the paragraph separator we include headlines, because filling
19907 ;; text in a line directly attached to a headline would otherwise
19908 ;; fill the headline as well.
19909 (org-set-local 'comment-start-skip "^#+[ \t]*")
19910 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
19911 ;; The paragraph starter includes hand-formatted lists.
19912 (org-set-local
19913 'paragraph-start
19914 (concat
19915 "\f" "\\|"
19916 "[ ]*$" "\\|"
19917 org-outline-regexp "\\|"
19918 "[ \t]*#" "\\|"
19919 (org-item-re) "\\|"
19920 "[ \t]*[:|]" "\\|"
19921 "\\$\\$" "\\|"
19922 "\\\\\\(begin\\|end\\|[][]\\)"))
19923 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
19924 ;; But only if the user has not turned off tables or fixed-width regions
19925 (org-set-local
19926 'auto-fill-inhibit-regexp
19927 (concat org-outline-regexp
19928 "\\|#\\+"
19929 "\\|[ \t]*" org-keyword-time-regexp
19930 (if (or org-enable-table-editor org-enable-fixed-width-editor)
19931 (concat
19932 "\\|[ \t]*["
19933 (if org-enable-table-editor "|" "")
19934 (if org-enable-fixed-width-editor ":" "")
19935 "]"))))
19936 ;; We use our own fill-paragraph function, to make sure that tables
19937 ;; and fixed-width regions are not wrapped. That function will pass
19938 ;; through to `fill-paragraph' when appropriate.
19939 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
19940 ;; Prevent auto-fill from inserting unwanted new items.
19941 (if (boundp 'fill-nobreak-predicate)
19942 (org-set-local 'fill-nobreak-predicate
19943 (if (memq 'org-fill-item-nobreak-p fill-nobreak-predicate)
19944 fill-nobreak-predicate
19945 (cons 'org-fill-item-nobreak-p fill-nobreak-predicate))))
19946 ;; Adaptive filling: To get full control, first make sure that
19947 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
19948 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
19949 (org-set-local 'org-adaptive-fill-regexp-backup
19950 adaptive-fill-regexp))
19951 (org-set-local 'adaptive-fill-regexp "\000")
19952 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
19953 (org-set-local 'adaptive-fill-function
19954 'org-adaptive-fill-function)
19955 (org-set-local
19956 'align-mode-rules-list
19957 '((org-in-buffer-settings
19958 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
19959 (modes . '(org-mode))))))
19961 (defun org-fill-item-nobreak-p ()
19962 "Non-nil when a line break at point would insert a new item."
19963 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
19965 (defun org-fill-paragraph (&optional justify)
19966 "Re-align a table, pass through to fill-paragraph if no table."
19967 (let ((table-p (org-at-table-p))
19968 (table.el-p (org-at-table.el-p))
19969 (itemp (org-in-item-p)))
19970 (cond ((and (equal (char-after (point-at-bol)) ?*)
19971 (save-excursion (goto-char (point-at-bol))
19972 (looking-at org-outline-regexp)))
19973 t) ; skip headlines
19974 (table.el-p t) ; skip table.el tables
19975 (table-p (org-table-align) t) ; align Org tables
19976 (itemp ; align text in items
19977 (let* ((struct (save-excursion (goto-char itemp)
19978 (org-list-struct)))
19979 (parents (org-list-parents-alist struct))
19980 (children (org-list-get-children itemp struct parents))
19981 beg end prev next prefix)
19982 ;; Determine in which part of item point is: before
19983 ;; first child, after last child, between two
19984 ;; sub-lists, or simply in item if there's no child.
19985 (cond
19986 ((not children)
19987 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
19988 beg itemp
19989 end (org-list-get-item-end itemp struct)))
19990 ((< (point) (setq next (car children)))
19991 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
19992 beg itemp
19993 end next))
19994 ((> (point) (setq prev (car (last children))))
19995 (setq beg (org-list-get-item-end prev struct)
19996 end (org-list-get-item-end itemp struct)
19997 prefix (save-excursion
19998 (goto-char beg)
19999 (skip-chars-forward " \t")
20000 (make-string (current-column) ?\ ))))
20001 (t (catch 'exit
20002 (while (setq next (pop children))
20003 (if (> (point) next)
20004 (setq prev next)
20005 (setq beg (org-list-get-item-end prev struct)
20006 end next
20007 prefix (save-excursion
20008 (goto-char beg)
20009 (skip-chars-forward " \t")
20010 (make-string (current-column) ?\ )))
20011 (throw 'exit nil))))))
20012 ;; Use `fill-paragraph' with buffer narrowed to item
20013 ;; without any child, and with our computed PREFIX.
20014 (flet ((fill-context-prefix (from to &optional flr) prefix))
20015 (save-restriction
20016 (narrow-to-region beg end)
20017 (save-excursion (fill-paragraph justify)))) t))
20018 ;; Special case where point is not in a list but is on
20019 ;; a paragraph adjacent to a list: make sure this paragraph
20020 ;; doesn't get merged with the end of the list by narrowing
20021 ;; buffer first.
20022 ((save-excursion (forward-paragraph -1)
20023 (setq itemp (org-in-item-p)))
20024 (let ((struct (save-excursion (goto-char itemp)
20025 (org-list-struct))))
20026 (save-restriction
20027 (narrow-to-region (org-list-get-bottom-point struct)
20028 (save-excursion (forward-paragraph 1)
20029 (point)))
20030 (fill-paragraph justify) t)))
20031 ;; Else simply call `fill-paragraph'.
20032 (t nil))))
20034 ;; For reference, this is the default value of adaptive-fill-regexp
20035 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
20037 (defun org-adaptive-fill-function ()
20038 "Return a fill prefix for org-mode files."
20039 (let (itemp)
20040 (save-excursion
20041 (cond
20042 ;; Comment line
20043 ((looking-at "#[ \t]+")
20044 (match-string-no-properties 0))
20045 ;; Plain list item
20046 ((org-at-item-p)
20047 (make-string (org-list-item-body-column (point-at-bol)) ?\ ))
20048 ;; Point is in a list after `backward-paragraph': original
20049 ;; point wasn't in the list, or filling would have been taken
20050 ;; care of by `org-auto-fill-function', but the list and the
20051 ;; real paragraph are not separated by a blank line. Thus, move
20052 ;; point after the list to go back to real paragraph and
20053 ;; determine fill-prefix.
20054 ((setq itemp (org-in-item-p))
20055 (goto-char itemp)
20056 (let* ((struct (org-list-struct))
20057 (bottom (org-list-get-bottom-point struct)))
20058 (goto-char bottom)
20059 (make-string (org-get-indentation) ?\ )))
20060 ;; Other text
20061 ((looking-at org-adaptive-fill-regexp-backup)
20062 (match-string-no-properties 0))))))
20064 (defun org-auto-fill-function ()
20065 "Auto-fill function."
20066 (let (itemp prefix)
20067 ;; When in a list, compute an appropriate fill-prefix and make
20068 ;; sure it will be used by `do-auto-fill'.
20069 (if (setq itemp (org-in-item-p))
20070 (progn
20071 (setq prefix (make-string (org-list-item-body-column itemp) ?\ ))
20072 (flet ((fill-context-prefix (from to &optional flr) prefix))
20073 (do-auto-fill)))
20074 ;; Else just use `do-auto-fill'.
20075 (do-auto-fill))))
20077 ;;; Other stuff.
20079 (defun org-toggle-fixed-width-section (arg)
20080 "Toggle the fixed-width export.
20081 If there is no active region, the QUOTE keyword at the current headline is
20082 inserted or removed. When present, it causes the text between this headline
20083 and the next to be exported as fixed-width text, and unmodified.
20084 If there is an active region, this command adds or removes a colon as the
20085 first character of this line. If the first character of a line is a colon,
20086 this line is also exported in fixed-width font."
20087 (interactive "P")
20088 (let* ((cc 0)
20089 (regionp (org-region-active-p))
20090 (beg (if regionp (region-beginning) (point)))
20091 (end (if regionp (region-end)))
20092 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
20093 (case-fold-search nil)
20094 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
20095 off)
20096 (if regionp
20097 (save-excursion
20098 (goto-char beg)
20099 (setq cc (current-column))
20100 (beginning-of-line 1)
20101 (setq off (looking-at re))
20102 (while (> nlines 0)
20103 (setq nlines (1- nlines))
20104 (beginning-of-line 1)
20105 (cond
20106 (arg
20107 (org-move-to-column cc t)
20108 (insert ": \n")
20109 (forward-line -1))
20110 ((and off (looking-at re))
20111 (replace-match "" t t nil 1))
20112 ((not off) (org-move-to-column cc t) (insert ": ")))
20113 (forward-line 1)))
20114 (save-excursion
20115 (org-back-to-heading)
20116 (cond
20117 ((looking-at (format org-heading-keyword-regexp-format
20118 org-quote-string))
20119 (goto-char (match-end 1))
20120 (looking-at (concat " +" org-quote-string))
20121 (replace-match "" t t)
20122 (when (eolp) (insert " ")))
20123 ((looking-at org-outline-regexp)
20124 (goto-char (match-end 0))
20125 (insert org-quote-string " ")))))))
20127 (defun org-reftex-citation ()
20128 "Use reftex-citation to insert a citation into the buffer.
20129 This looks for a line like
20131 #+BIBLIOGRAPHY: foo plain option:-d
20133 and derives from it that foo.bib is the bibliography file relevant
20134 for this document. It then installs the necessary environment for RefTeX
20135 to work in this buffer and calls `reftex-citation' to insert a citation
20136 into the buffer.
20138 Export of such citations to both LaTeX and HTML is handled by the contributed
20139 package org-exp-bibtex by Taru Karttunen."
20140 (interactive)
20141 (let ((reftex-docstruct-symbol 'rds)
20142 (reftex-cite-format "\\cite{%l}")
20143 rds bib)
20144 (save-excursion
20145 (save-restriction
20146 (widen)
20147 (let ((case-fold-search t)
20148 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
20149 (if (not (save-excursion
20150 (or (re-search-forward re nil t)
20151 (re-search-backward re nil t))))
20152 (error "No bibliography defined in file")
20153 (setq bib (concat (match-string 1) ".bib")
20154 rds (list (list 'bib bib)))))))
20155 (call-interactively 'reftex-citation)))
20157 ;;;; Functions extending outline functionality
20159 (defun org-beginning-of-line (&optional arg)
20160 "Go to the beginning of the current line. If that is invisible, continue
20161 to a visible line beginning. This makes the function of C-a more intuitive.
20162 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20163 first attempt, and only move to after the tags when the cursor is already
20164 beyond the end of the headline."
20165 (interactive "P")
20166 (let ((pos (point))
20167 (special (if (consp org-special-ctrl-a/e)
20168 (car org-special-ctrl-a/e)
20169 org-special-ctrl-a/e))
20170 refpos)
20171 (if (org-bound-and-true-p line-move-visual)
20172 (beginning-of-visual-line 1)
20173 (beginning-of-line 1))
20174 (if (and arg (fboundp 'move-beginning-of-line))
20175 (call-interactively 'move-beginning-of-line)
20176 (if (bobp)
20178 (backward-char 1)
20179 (if (org-truely-invisible-p)
20180 (while (and (not (bobp)) (org-truely-invisible-p))
20181 (backward-char 1)
20182 (beginning-of-line 1))
20183 (forward-char 1))))
20184 (when special
20185 (cond
20186 ((and (looking-at org-complex-heading-regexp)
20187 (= (char-after (match-end 1)) ?\ ))
20188 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
20189 (point-at-eol)))
20190 (goto-char
20191 (if (eq special t)
20192 (cond ((> pos refpos) refpos)
20193 ((= pos (point)) refpos)
20194 (t (point)))
20195 (cond ((> pos (point)) (point))
20196 ((not (eq last-command this-command)) (point))
20197 (t refpos)))))
20198 ((org-at-item-p)
20199 (goto-char
20200 (if (eq special t)
20201 (cond ((> pos (match-end 0)) (match-end 0))
20202 ((= pos (point)) (match-end 0))
20203 (t (point)))
20204 (cond ((> pos (point)) (point))
20205 ((not (eq last-command this-command)) (point))
20206 (t (match-end 0))))))))
20207 (org-no-warnings
20208 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20210 (defun org-end-of-line (&optional arg)
20211 "Go to the end of the line.
20212 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20213 first attempt, and only move to after the tags when the cursor is already
20214 beyond the end of the headline."
20215 (interactive "P")
20216 (let ((special (if (consp org-special-ctrl-a/e)
20217 (cdr org-special-ctrl-a/e)
20218 org-special-ctrl-a/e)))
20219 (cond
20220 ((or (not special) arg
20221 (not (or (org-on-heading-p) (org-at-item-p))))
20222 (call-interactively
20223 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
20224 ((fboundp 'move-end-of-line) 'move-end-of-line)
20225 (t 'end-of-line))))
20226 ((org-on-heading-p)
20227 (let ((pos (point)))
20228 (beginning-of-line 1)
20229 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
20230 (if (eq special t)
20231 (if (or (< pos (match-beginning 1))
20232 (= pos (match-end 0)))
20233 (goto-char (match-beginning 1))
20234 (goto-char (match-end 0)))
20235 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
20236 (goto-char (match-end 0))
20237 (goto-char (match-beginning 1))))
20238 (call-interactively (if (fboundp 'move-end-of-line)
20239 'move-end-of-line
20240 'end-of-line)))))
20241 ;; At an item: Move before any hidden text.
20242 (t (call-interactively 'end-of-line)))
20243 (org-no-warnings
20244 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20246 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
20247 (define-key org-mode-map "\C-e" 'org-end-of-line)
20249 (defun org-backward-sentence (&optional arg)
20250 "Go to beginning of sentence, or beginning of table field.
20251 This will call `backward-sentence' or `org-table-beginning-of-field',
20252 depending on context."
20253 (interactive "P")
20254 (cond
20255 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
20256 (t (call-interactively 'backward-sentence))))
20258 (defun org-forward-sentence (&optional arg)
20259 "Go to end of sentence, or end of table field.
20260 This will call `forward-sentence' or `org-table-end-of-field',
20261 depending on context."
20262 (interactive "P")
20263 (cond
20264 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
20265 (t (call-interactively 'forward-sentence))))
20267 (define-key org-mode-map "\M-a" 'org-backward-sentence)
20268 (define-key org-mode-map "\M-e" 'org-forward-sentence)
20270 (defun org-kill-line (&optional arg)
20271 "Kill line, to tags or end of line."
20272 (interactive "P")
20273 (cond
20274 ((or (not org-special-ctrl-k)
20275 (bolp)
20276 (not (org-on-heading-p)))
20277 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
20278 org-ctrl-k-protect-subtree)
20279 (if (or (eq org-ctrl-k-protect-subtree 'error)
20280 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
20281 (error "C-k aborted - would kill hidden subtree")))
20282 (call-interactively 'kill-line))
20283 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
20284 (kill-region (point) (match-beginning 1))
20285 (org-set-tags nil t))
20286 (t (kill-region (point) (point-at-eol)))))
20288 (define-key org-mode-map "\C-k" 'org-kill-line)
20290 (defun org-yank (&optional arg)
20291 "Yank. If the kill is a subtree, treat it specially.
20292 This command will look at the current kill and check if is a single
20293 subtree, or a series of subtrees[1]. If it passes the test, and if the
20294 cursor is at the beginning of a line or after the stars of a currently
20295 empty headline, then the yank is handled specially. How exactly depends
20296 on the value of the following variables, both set by default.
20298 org-yank-folded-subtrees
20299 When set, the subtree(s) will be folded after insertion, but only
20300 if doing so would now swallow text after the yanked text.
20302 org-yank-adjusted-subtrees
20303 When set, the subtree will be promoted or demoted in order to
20304 fit into the local outline tree structure, which means that the level
20305 will be adjusted so that it becomes the smaller one of the two
20306 *visible* surrounding headings.
20308 Any prefix to this command will cause `yank' to be called directly with
20309 no special treatment. In particular, a simple \\[universal-argument] prefix \
20310 will just
20311 plainly yank the text as it is.
20313 \[1] The test checks if the first non-white line is a heading
20314 and if there are no other headings with fewer stars."
20315 (interactive "P")
20316 (org-yank-generic 'yank arg))
20318 (defun org-yank-generic (command arg)
20319 "Perform some yank-like command.
20321 This function implements the behavior described in the `org-yank'
20322 documentation. However, it has been generalized to work for any
20323 interactive command with similar behavior."
20325 ;; pretend to be command COMMAND
20326 (setq this-command command)
20328 (if arg
20329 (call-interactively command)
20331 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
20332 (and (org-kill-is-subtree-p)
20333 (or (bolp)
20334 (and (looking-at "[ \t]*$")
20335 (string-match
20336 "\\`\\*+\\'"
20337 (buffer-substring (point-at-bol) (point)))))))
20338 swallowp)
20339 (cond
20340 ((and subtreep org-yank-folded-subtrees)
20341 (let ((beg (point))
20342 end)
20343 (if (and subtreep org-yank-adjusted-subtrees)
20344 (org-paste-subtree nil nil 'for-yank)
20345 (call-interactively command))
20347 (setq end (point))
20348 (goto-char beg)
20349 (when (and (bolp) subtreep
20350 (not (setq swallowp
20351 (org-yank-folding-would-swallow-text beg end))))
20352 (org-with-limited-levels
20353 (or (looking-at org-outline-regexp)
20354 (re-search-forward org-outline-regexp-bol end t))
20355 (while (and (< (point) end) (looking-at org-outline-regexp))
20356 (hide-subtree)
20357 (org-cycle-show-empty-lines 'folded)
20358 (condition-case nil
20359 (outline-forward-same-level 1)
20360 (error (goto-char end))))))
20361 (when swallowp
20362 (message
20363 "Inserted text not folded because that would swallow text"))
20365 (goto-char end)
20366 (skip-chars-forward " \t\n\r")
20367 (beginning-of-line 1)
20368 (push-mark beg 'nomsg)))
20369 ((and subtreep org-yank-adjusted-subtrees)
20370 (let ((beg (point-at-bol)))
20371 (org-paste-subtree nil nil 'for-yank)
20372 (push-mark beg 'nomsg)))
20374 (call-interactively command))))))
20376 (defun org-yank-folding-would-swallow-text (beg end)
20377 "Would hide-subtree at BEG swallow any text after END?"
20378 (let (level)
20379 (org-with-limited-levels
20380 (save-excursion
20381 (goto-char beg)
20382 (when (or (looking-at org-outline-regexp)
20383 (re-search-forward org-outline-regexp-bol end t))
20384 (setq level (org-outline-level)))
20385 (goto-char end)
20386 (skip-chars-forward " \t\r\n\v\f")
20387 (if (or (eobp)
20388 (and (bolp) (looking-at org-outline-regexp)
20389 (<= (org-outline-level) level)))
20390 nil ; Nothing would be swallowed
20391 t))))) ; something would swallow
20393 (define-key org-mode-map "\C-y" 'org-yank)
20395 (defun org-truely-invisible-p ()
20396 "Check if point is at a character currently not visible.
20397 This version does not only check the character property, but also
20398 `visible-mode'."
20399 ;; Early versions of noutline don't have `outline-invisible-p'.
20400 (if (org-bound-and-true-p visible-mode)
20402 (outline-invisible-p)))
20404 (defun org-invisible-p2 ()
20405 "Check if point is at a character currently not visible."
20406 (save-excursion
20407 (if (and (eolp) (not (bobp))) (backward-char 1))
20408 ;; Early versions of noutline don't have `outline-invisible-p'.
20409 (outline-invisible-p)))
20411 (defun org-back-to-heading (&optional invisible-ok)
20412 "Call `outline-back-to-heading', but provide a better error message."
20413 (condition-case nil
20414 (outline-back-to-heading invisible-ok)
20415 (error (error "Before first headline at position %d in buffer %s"
20416 (point) (current-buffer)))))
20418 (defun org-beginning-of-defun ()
20419 "Go to the beginning of the subtree, i.e. back to the heading."
20420 (org-back-to-heading))
20421 (defun org-end-of-defun ()
20422 "Go to the end of the subtree."
20423 (org-end-of-subtree nil t))
20425 (defun org-before-first-heading-p ()
20426 "Before first heading?"
20427 (save-excursion
20428 (end-of-line)
20429 (null (re-search-backward org-outline-regexp-bol nil t))))
20431 (defun org-on-heading-p (&optional ignored)
20432 (outline-on-heading-p t))
20433 (defun org-at-heading-p (&optional ignored)
20434 (outline-on-heading-p t))
20436 (defun org-point-at-end-of-empty-headline ()
20437 "If point is at the end of an empty headline, return t, else nil.
20438 If the heading only contains a TODO keyword, it is still still considered
20439 empty."
20440 (and (looking-at "[ \t]*$")
20441 (save-excursion
20442 (beginning-of-line 1)
20443 (let ((case-fold-search nil))
20444 (looking-at org-todo-line-regexp)))
20445 (string= (match-string 3) "")))
20447 (defun org-at-heading-or-item-p ()
20448 (or (org-on-heading-p) (org-at-item-p)))
20450 (defun org-on-target-p ()
20451 (or (org-in-regexp org-radio-target-regexp)
20452 (org-in-regexp org-target-regexp)))
20454 (defun org-up-heading-all (arg)
20455 "Move to the heading line of which the present line is a subheading.
20456 This function considers both visible and invisible heading lines.
20457 With argument, move up ARG levels."
20458 (if (fboundp 'outline-up-heading-all)
20459 (outline-up-heading-all arg) ; emacs 21 version of outline.el
20460 (outline-up-heading arg t))) ; emacs 22 version of outline.el
20462 (defun org-up-heading-safe ()
20463 "Move to the heading line of which the present line is a subheading.
20464 This version will not throw an error. It will return the level of the
20465 headline found, or nil if no higher level is found.
20467 Also, this function will be a lot faster than `outline-up-heading',
20468 because it relies on stars being the outline starters. This can really
20469 make a significant difference in outlines with very many siblings."
20470 (let (start-level re)
20471 (org-back-to-heading t)
20472 (setq start-level (funcall outline-level))
20473 (if (equal start-level 1)
20475 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
20476 (if (re-search-backward re nil t)
20477 (funcall outline-level)))))
20479 (defun org-first-sibling-p ()
20480 "Is this heading the first child of its parents?"
20481 (interactive)
20482 (let ((re org-outline-regexp-bol)
20483 level l)
20484 (unless (org-at-heading-p t)
20485 (error "Not at a heading"))
20486 (setq level (funcall outline-level))
20487 (save-excursion
20488 (if (not (re-search-backward re nil t))
20490 (setq l (funcall outline-level))
20491 (< l level)))))
20493 (defun org-goto-sibling (&optional previous)
20494 "Goto the next sibling, even if it is invisible.
20495 When PREVIOUS is set, go to the previous sibling instead. Returns t
20496 when a sibling was found. When none is found, return nil and don't
20497 move point."
20498 (let ((fun (if previous 're-search-backward 're-search-forward))
20499 (pos (point))
20500 (re org-outline-regexp-bol)
20501 level l)
20502 (when (condition-case nil (org-back-to-heading t) (error nil))
20503 (setq level (funcall outline-level))
20504 (catch 'exit
20505 (or previous (forward-char 1))
20506 (while (funcall fun re nil t)
20507 (setq l (funcall outline-level))
20508 (when (< l level) (goto-char pos) (throw 'exit nil))
20509 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
20510 (goto-char pos)
20511 nil))))
20513 (defun org-show-siblings ()
20514 "Show all siblings of the current headline."
20515 (save-excursion
20516 (while (org-goto-sibling) (org-flag-heading nil)))
20517 (save-excursion
20518 (while (org-goto-sibling 'previous)
20519 (org-flag-heading nil))))
20521 (defun org-goto-first-child ()
20522 "Goto the first child, even if it is invisible.
20523 Return t when a child was found. Otherwise don't move point and
20524 return nil."
20525 (let (level (pos (point)) (re org-outline-regexp-bol))
20526 (when (condition-case nil (org-back-to-heading t) (error nil))
20527 (setq level (outline-level))
20528 (forward-char 1)
20529 (if (and (re-search-forward re nil t) (> (outline-level) level))
20530 (progn (goto-char (match-beginning 0)) t)
20531 (goto-char pos) nil))))
20533 (defun org-show-hidden-entry ()
20534 "Show an entry where even the heading is hidden."
20535 (save-excursion
20536 (org-show-entry)))
20538 (defun org-flag-heading (flag &optional entry)
20539 "Flag the current heading. FLAG non-nil means make invisible.
20540 When ENTRY is non-nil, show the entire entry."
20541 (save-excursion
20542 (org-back-to-heading t)
20543 ;; Check if we should show the entire entry
20544 (if entry
20545 (progn
20546 (org-show-entry)
20547 (save-excursion
20548 (and (outline-next-heading)
20549 (org-flag-heading nil))))
20550 (outline-flag-region (max (point-min) (1- (point)))
20551 (save-excursion (outline-end-of-heading) (point))
20552 flag))))
20554 (defun org-get-next-sibling ()
20555 "Move to next heading of the same level, and return point.
20556 If there is no such heading, return nil.
20557 This is like outline-next-sibling, but invisible headings are ok."
20558 (let ((level (funcall outline-level)))
20559 (outline-next-heading)
20560 (while (and (not (eobp)) (> (funcall outline-level) level))
20561 (outline-next-heading))
20562 (if (or (eobp) (< (funcall outline-level) level))
20564 (point))))
20566 (defun org-get-last-sibling ()
20567 "Move to previous heading of the same level, and return point.
20568 If there is no such heading, return nil."
20569 (let ((opoint (point))
20570 (level (funcall outline-level)))
20571 (outline-previous-heading)
20572 (when (and (/= (point) opoint) (outline-on-heading-p t))
20573 (while (and (> (funcall outline-level) level)
20574 (not (bobp)))
20575 (outline-previous-heading))
20576 (if (< (funcall outline-level) level)
20578 (point)))))
20580 (defun org-end-of-subtree (&optional invisible-OK to-heading)
20581 ;; This contains an exact copy of the original function, but it uses
20582 ;; `org-back-to-heading', to make it work also in invisible
20583 ;; trees. And is uses an invisible-OK argument.
20584 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
20585 ;; Furthermore, when used inside Org, finding the end of a large subtree
20586 ;; with many children and grandchildren etc, this can be much faster
20587 ;; than the outline version.
20588 (org-back-to-heading invisible-OK)
20589 (let ((first t)
20590 (level (funcall outline-level)))
20591 (if (and (eq major-mode 'org-mode) (< level 1000))
20592 ;; A true heading (not a plain list item), in Org-mode
20593 ;; This means we can easily find the end by looking
20594 ;; only for the right number of stars. Using a regexp to do
20595 ;; this is so much faster than using a Lisp loop.
20596 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
20597 (forward-char 1)
20598 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
20599 ;; something else, do it the slow way
20600 (while (and (not (eobp))
20601 (or first (> (funcall outline-level) level)))
20602 (setq first nil)
20603 (outline-next-heading)))
20604 (unless to-heading
20605 (if (memq (preceding-char) '(?\n ?\^M))
20606 (progn
20607 ;; Go to end of line before heading
20608 (forward-char -1)
20609 (if (memq (preceding-char) '(?\n ?\^M))
20610 ;; leave blank line before heading
20611 (forward-char -1))))))
20612 (point))
20614 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
20615 "Use Org version in org-mode, for dramatic speed-up."
20616 (if (eq major-mode 'org-mode)
20617 (progn
20618 (org-end-of-subtree nil t)
20619 (unless (eobp) (backward-char 1)))
20620 ad-do-it))
20622 (defun org-end-of-meta-data-and-drawers ()
20623 "Jump to the first text after meta data and drawers in the current entry.
20624 This will move over empty lines, lines with planning time stamps,
20625 clocking lines, and drawers."
20626 (org-back-to-heading t)
20627 (let ((end (save-excursion (outline-next-heading) (point)))
20628 (re (concat "\\(" org-drawer-regexp "\\)"
20629 "\\|" "[ \t]*" org-keyword-time-regexp)))
20630 (forward-line 1)
20631 (while (re-search-forward re end t)
20632 (if (not (match-end 1))
20633 ;; empty or planning line
20634 (forward-line 1)
20635 ;; a drawer, find the end
20636 (re-search-forward "^[ \t]*:END:" end 'move)
20637 (forward-line 1)))
20638 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
20639 (point)))
20641 (defun org-forward-same-level (arg &optional invisible-ok)
20642 "Move forward to the arg'th subheading at same level as this one.
20643 Stop at the first and last subheadings of a superior heading.
20644 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
20645 it wil also look at invisible ones."
20646 (interactive "p")
20647 (org-back-to-heading invisible-ok)
20648 (org-on-heading-p)
20649 (let* ((level (- (match-end 0) (match-beginning 0) 1))
20650 (re (format "^\\*\\{1,%d\\} " level))
20652 (forward-char 1)
20653 (while (> arg 0)
20654 (while (and (re-search-forward re nil 'move)
20655 (setq l (- (match-end 0) (match-beginning 0) 1))
20656 (= l level)
20657 (not invisible-ok)
20658 (progn (backward-char 1) (outline-invisible-p)))
20659 (if (< l level) (setq arg 1)))
20660 (setq arg (1- arg)))
20661 (beginning-of-line 1)))
20663 (defun org-backward-same-level (arg &optional invisible-ok)
20664 "Move backward to the arg'th subheading at same level as this one.
20665 Stop at the first and last subheadings of a superior heading."
20666 (interactive "p")
20667 (org-back-to-heading)
20668 (org-on-heading-p)
20669 (let* ((level (- (match-end 0) (match-beginning 0) 1))
20670 (re (format "^\\*\\{1,%d\\} " level))
20672 (while (> arg 0)
20673 (while (and (re-search-backward re nil 'move)
20674 (setq l (- (match-end 0) (match-beginning 0) 1))
20675 (= l level)
20676 (not invisible-ok)
20677 (outline-invisible-p))
20678 (if (< l level) (setq arg 1)))
20679 (setq arg (1- arg)))))
20681 (defun org-show-subtree ()
20682 "Show everything after this heading at deeper levels."
20683 (outline-flag-region
20684 (point)
20685 (save-excursion
20686 (org-end-of-subtree t t))
20687 nil))
20689 (defun org-show-entry ()
20690 "Show the body directly following this heading.
20691 Show the heading too, if it is currently invisible."
20692 (interactive)
20693 (save-excursion
20694 (condition-case nil
20695 (progn
20696 (org-back-to-heading t)
20697 (outline-flag-region
20698 (max (point-min) (1- (point)))
20699 (save-excursion
20700 (if (re-search-forward
20701 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
20702 (match-beginning 1)
20703 (point-max)))
20704 nil)
20705 (org-cycle-hide-drawers 'children))
20706 (error nil))))
20708 (defun org-make-options-regexp (kwds &optional extra)
20709 "Make a regular expression for keyword lines."
20710 (concat
20712 "#?[ \t]*\\+\\("
20713 (mapconcat 'regexp-quote kwds "\\|")
20714 (if extra (concat "\\|" extra))
20715 "\\):[ \t]*"
20716 "\\(.*\\)"))
20718 ;; Make isearch reveal the necessary context
20719 (defun org-isearch-end ()
20720 "Reveal context after isearch exits."
20721 (when isearch-success ; only if search was successful
20722 (if (featurep 'xemacs)
20723 ;; Under XEmacs, the hook is run in the correct place,
20724 ;; we directly show the context.
20725 (org-show-context 'isearch)
20726 ;; In Emacs the hook runs *before* restoring the overlays.
20727 ;; So we have to use a one-time post-command-hook to do this.
20728 ;; (Emacs 22 has a special variable, see function `org-mode')
20729 (unless (and (boundp 'isearch-mode-end-hook-quit)
20730 isearch-mode-end-hook-quit)
20731 ;; Only when the isearch was not quitted.
20732 (org-add-hook 'post-command-hook 'org-isearch-post-command
20733 'append 'local)))))
20735 (defun org-isearch-post-command ()
20736 "Remove self from hook, and show context."
20737 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
20738 (org-show-context 'isearch))
20741 ;;;; Integration with and fixes for other packages
20743 ;;; Imenu support
20745 (defvar org-imenu-markers nil
20746 "All markers currently used by Imenu.")
20747 (make-variable-buffer-local 'org-imenu-markers)
20749 (defun org-imenu-new-marker (&optional pos)
20750 "Return a new marker for use by Imenu, and remember the marker."
20751 (let ((m (make-marker)))
20752 (move-marker m (or pos (point)))
20753 (push m org-imenu-markers)
20756 (defun org-imenu-get-tree ()
20757 "Produce the index for Imenu."
20758 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
20759 (setq org-imenu-markers nil)
20760 (let* ((n org-imenu-depth)
20761 (re (concat "^" (org-get-limited-outline-regexp)))
20762 (subs (make-vector (1+ n) nil))
20763 (last-level 0)
20764 m level head)
20765 (save-excursion
20766 (save-restriction
20767 (widen)
20768 (goto-char (point-max))
20769 (while (re-search-backward re nil t)
20770 (setq level (org-reduced-level (funcall outline-level)))
20771 (when (<= level n)
20772 (looking-at org-complex-heading-regexp)
20773 (setq head (org-link-display-format
20774 (org-match-string-no-properties 4))
20775 m (org-imenu-new-marker))
20776 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
20777 (if (>= level last-level)
20778 (push (cons head m) (aref subs level))
20779 (push (cons head (aref subs (1+ level))) (aref subs level))
20780 (loop for i from (1+ level) to n do (aset subs i nil)))
20781 (setq last-level level)))))
20782 (aref subs 1)))
20784 (eval-after-load "imenu"
20785 '(progn
20786 (add-hook 'imenu-after-jump-hook
20787 (lambda ()
20788 (if (eq major-mode 'org-mode)
20789 (org-show-context 'org-goto))))))
20791 (defun org-link-display-format (link)
20792 "Replace a link with either the description, or the link target
20793 if no description is present"
20794 (save-match-data
20795 (if (string-match org-bracket-link-analytic-regexp link)
20796 (replace-match (if (match-end 5)
20797 (match-string 5 link)
20798 (concat (match-string 1 link)
20799 (match-string 3 link)))
20800 nil t link)
20801 link)))
20803 (defun org-toggle-link-display ()
20804 "Toggle the literal or descriptive display of links."
20805 (interactive)
20806 (if org-descriptive-links
20807 (progn (org-remove-from-invisibility-spec '(org-link))
20808 (org-restart-font-lock)
20809 (setq org-descriptive-links nil))
20810 (progn (add-to-invisibility-spec '(org-link))
20811 (org-restart-font-lock)
20812 (setq org-descriptive-links t))))
20814 ;; Speedbar support
20816 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
20817 "Overlay marking the agenda restriction line in speedbar.")
20818 (overlay-put org-speedbar-restriction-lock-overlay
20819 'face 'org-agenda-restriction-lock)
20820 (overlay-put org-speedbar-restriction-lock-overlay
20821 'help-echo "Agendas are currently limited to this item.")
20822 (org-detach-overlay org-speedbar-restriction-lock-overlay)
20824 (defun org-speedbar-set-agenda-restriction ()
20825 "Restrict future agenda commands to the location at point in speedbar.
20826 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
20827 (interactive)
20828 (require 'org-agenda)
20829 (let (p m tp np dir txt)
20830 (cond
20831 ((setq p (text-property-any (point-at-bol) (point-at-eol)
20832 'org-imenu t))
20833 (setq m (get-text-property p 'org-imenu-marker))
20834 (with-current-buffer (marker-buffer m)
20835 (goto-char m)
20836 (org-agenda-set-restriction-lock 'subtree)))
20837 ((setq p (text-property-any (point-at-bol) (point-at-eol)
20838 'speedbar-function 'speedbar-find-file))
20839 (setq tp (previous-single-property-change
20840 (1+ p) 'speedbar-function)
20841 np (next-single-property-change
20842 tp 'speedbar-function)
20843 dir (speedbar-line-directory)
20844 txt (buffer-substring-no-properties (or tp (point-min))
20845 (or np (point-max))))
20846 (with-current-buffer (find-file-noselect
20847 (let ((default-directory dir))
20848 (expand-file-name txt)))
20849 (unless (eq major-mode 'org-mode)
20850 (error "Cannot restrict to non-Org-mode file"))
20851 (org-agenda-set-restriction-lock 'file)))
20852 (t (error "Don't know how to restrict Org-mode's agenda")))
20853 (move-overlay org-speedbar-restriction-lock-overlay
20854 (point-at-bol) (point-at-eol))
20855 (setq current-prefix-arg nil)
20856 (org-agenda-maybe-redo)))
20858 (eval-after-load "speedbar"
20859 '(progn
20860 (speedbar-add-supported-extension ".org")
20861 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
20862 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
20863 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
20864 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
20865 (add-hook 'speedbar-visiting-tag-hook
20866 (lambda () (and (eq major-mode 'org-mode) (org-show-context 'org-goto))))))
20868 ;;; Fixes and Hacks for problems with other packages
20870 ;; Make flyspell not check words in links, to not mess up our keymap
20871 (defun org-mode-flyspell-verify ()
20872 "Don't let flyspell put overlays at active buttons, or on
20873 {todo,all-time,additional-option-like}-keywords."
20874 (let ((pos (max (1- (point)) (point-min)))
20875 (word (thing-at-point 'word)))
20876 (and (not (get-text-property pos 'keymap))
20877 (not (get-text-property pos 'org-no-flyspell))
20878 (not (member word org-todo-keywords-1))
20879 (not (member word org-all-time-keywords))
20880 (not (member word org-additional-option-like-keywords)))))
20882 (defun org-remove-flyspell-overlays-in (beg end)
20883 "Remove flyspell overlays in region."
20884 (and (org-bound-and-true-p flyspell-mode)
20885 (fboundp 'flyspell-delete-region-overlays)
20886 (flyspell-delete-region-overlays beg end))
20887 (add-text-properties beg end '(org-no-flyspell t)))
20889 ;; Make `bookmark-jump' shows the jump location if it was hidden.
20890 (eval-after-load "bookmark"
20891 '(if (boundp 'bookmark-after-jump-hook)
20892 ;; We can use the hook
20893 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
20894 ;; Hook not available, use advice
20895 (defadvice bookmark-jump (after org-make-visible activate)
20896 "Make the position visible."
20897 (org-bookmark-jump-unhide))))
20899 ;; Make sure saveplace shows the location if it was hidden
20900 (eval-after-load "saveplace"
20901 '(defadvice save-place-find-file-hook (after org-make-visible activate)
20902 "Make the position visible."
20903 (org-bookmark-jump-unhide)))
20905 ;; Make sure ecb shows the location if it was hidden
20906 (eval-after-load "ecb"
20907 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
20908 "Make hierarchy visible when jumping into location from ECB tree buffer."
20909 (if (eq major-mode 'org-mode)
20910 (org-show-context))))
20912 (defun org-bookmark-jump-unhide ()
20913 "Unhide the current position, to show the bookmark location."
20914 (and (eq major-mode 'org-mode)
20915 (or (outline-invisible-p)
20916 (save-excursion (goto-char (max (point-min) (1- (point))))
20917 (outline-invisible-p)))
20918 (org-show-context 'bookmark-jump)))
20920 ;; Make session.el ignore our circular variable
20921 (eval-after-load "session"
20922 '(add-to-list 'session-globals-exclude 'org-mark-ring))
20924 ;;;; Experimental code
20926 (defun org-closed-in-range ()
20927 "Sparse tree of items closed in a certain time range.
20928 Still experimental, may disappear in the future."
20929 (interactive)
20930 ;; Get the time interval from the user.
20931 (let* ((time1 (org-float-time
20932 (org-read-date nil 'to-time nil "Starting date: ")))
20933 (time2 (org-float-time
20934 (org-read-date nil 'to-time nil "End date:")))
20935 ;; callback function
20936 (callback (lambda ()
20937 (let ((time
20938 (org-float-time
20939 (apply 'encode-time
20940 (org-parse-time-string
20941 (match-string 1))))))
20942 ;; check if time in interval
20943 (and (>= time time1) (<= time time2))))))
20944 ;; make tree, check each match with the callback
20945 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
20947 ;;;; Finish up
20949 (provide 'org)
20951 (run-hooks 'org-load-hook)
20953 ;;; org.el ends here