New allowed value 'start-level for `org-loop-over-headlines-in-active-region'.
[org-mode.git] / lisp / org.el
blobd5b75946bdf7805e6e7d2d22ae46674d52aeb817
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.8.02
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 "Fortran" fortran)
168 (const :tag "Gnuplot" gnuplot)
169 (const :tag "Haskell" haskell)
170 (const :tag "Java" java)
171 (const :tag "Javascript" js)
172 (const :tag "Latex" latex)
173 (const :tag "Ledger" ledger)
174 (const :tag "Lilypond" lilypond)
175 (const :tag "Maxima" maxima)
176 (const :tag "Matlab" matlab)
177 (const :tag "Mscgen" mscgen)
178 (const :tag "Ocaml" ocaml)
179 (const :tag "Octave" octave)
180 (const :tag "Org" org)
181 (const :tag "Perl" perl)
182 (const :tag "Pico Lisp" picolisp)
183 (const :tag "PlantUML" plantuml)
184 (const :tag "Python" python)
185 (const :tag "Ruby" ruby)
186 (const :tag "Sass" sass)
187 (const :tag "Scheme" scheme)
188 (const :tag "Screen" screen)
189 (const :tag "Shell Script" sh)
190 (const :tag "Shen" shen)
191 (const :tag "Sql" sql)
192 (const :tag "Sqlite" sqlite))
193 :value-type (boolean :tag "Activate" :value t)))
195 ;;;; Customization variables
196 (defcustom org-clone-delete-id nil
197 "Remove ID property of clones of a subtree.
198 When non-nil, clones of a subtree don't inherit the ID property.
199 Otherwise they inherit the ID property with a new unique
200 identifier."
201 :type 'boolean
202 :group 'org-id)
204 ;;; Version
206 (defconst org-version "7.8.02"
207 "The version number of the file org.el.")
209 (defun org-version (&optional here)
210 "Show the org-mode version in the echo area.
211 With prefix arg HERE, insert it at point."
212 (interactive "P")
213 (let* ((origin default-directory)
214 (version org-version)
215 (git-version)
216 (dir (concat (file-name-directory (locate-library "org")) "../" )))
217 (when (and (file-exists-p (expand-file-name ".git" dir))
218 (executable-find "git"))
219 (unwind-protect
220 (progn
221 (cd dir)
222 (when (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
223 (with-current-buffer "*Shell Command Output*"
224 (goto-char (point-min))
225 (setq git-version (buffer-substring (point) (point-at-eol))))
226 (subst-char-in-string ?- ?. git-version t)
227 (when (string-match "\\S-"
228 (shell-command-to-string
229 "git diff-index --name-only HEAD --"))
230 (setq git-version (concat git-version ".dirty")))
231 (setq version (concat version " (" git-version ")"))))
232 (cd origin)))
233 (setq version (format "Org-mode version %s" version))
234 (if here (insert version))
235 (message version)))
237 ;;; Compatibility constants
239 ;;; The custom variables
241 (defgroup org nil
242 "Outline-based notes management and organizer."
243 :tag "Org"
244 :group 'outlines
245 :group 'calendar)
247 (defcustom org-mode-hook nil
248 "Mode hook for Org-mode, run after the mode was turned on."
249 :group 'org
250 :type 'hook)
252 (defcustom org-load-hook nil
253 "Hook that is run after org.el has been loaded."
254 :group 'org
255 :type 'hook)
257 (defcustom org-log-buffer-setup-hook nil
258 "Hook that is run after an Org log buffer is created."
259 :group 'org
260 :type 'hook)
262 (defvar org-modules) ; defined below
263 (defvar org-modules-loaded nil
264 "Have the modules been loaded already?")
266 (defun org-load-modules-maybe (&optional force)
267 "Load all extensions listed in `org-modules'."
268 (when (or force (not org-modules-loaded))
269 (mapc (lambda (ext)
270 (condition-case nil (require ext)
271 (error (message "Problems while trying to load feature `%s'" ext))))
272 org-modules)
273 (setq org-modules-loaded t)))
275 (defun org-set-modules (var value)
276 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
277 (set var value)
278 (when (featurep 'org)
279 (org-load-modules-maybe 'force)))
281 (when (org-bound-and-true-p org-modules)
282 (let ((a (member 'org-infojs org-modules)))
283 (and a (setcar a 'org-jsinfo))))
285 (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)
286 "Modules that should always be loaded together with org.el.
287 If a description starts with <C>, the file is not part of Emacs
288 and loading it will require that you have downloaded and properly installed
289 the org-mode distribution.
291 You can also use this system to load external packages (i.e. neither Org
292 core modules, nor modules from the CONTRIB directory). Just add symbols
293 to the end of the list. If the package is called org-xyz.el, then you need
294 to add the symbol `xyz', and the package must have a call to
296 (provide 'org-xyz)"
297 :group 'org
298 :set 'org-set-modules
299 :type
300 '(set :greedy t
301 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
302 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
303 (const :tag " crypt: Encryption of subtrees" org-crypt)
304 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
305 (const :tag " docview: Links to doc-view buffers" org-docview)
306 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
307 (const :tag " id: Global IDs for identifying entries" org-id)
308 (const :tag " info: Links to Info nodes" org-info)
309 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
310 (const :tag " habit: Track your consistency with habits" org-habit)
311 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
312 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
313 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
314 (const :tag " mew Links to Mew folders/messages" org-mew)
315 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
316 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
317 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
318 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
319 (const :tag " vm: Links to VM folders/messages" org-vm)
320 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
321 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
322 (const :tag " mouse: Additional mouse support" org-mouse)
323 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
325 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
326 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
327 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
328 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
329 (const :tag "C collector: Collect properties into tables" org-collector)
330 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
331 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
332 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
333 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
334 (const :tag "C eval: Include command output as text" org-eval)
335 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
336 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
337 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
338 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
339 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
341 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
343 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
344 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
345 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
346 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
347 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
348 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
349 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
350 (const :tag "C mtags: Support for muse-like tags" org-mtags)
351 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
352 (const :tag "C registry: A registry for Org-mode links" org-registry)
353 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
354 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
355 (const :tag "C secretary: Team management with org-mode" org-secretary)
356 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
357 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
358 (const :tag "C track: Keep up with Org-mode development" org-track)
359 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
360 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
361 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
363 (defcustom org-support-shift-select nil
364 "Non-nil means make shift-cursor commands select text when possible.
366 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
367 start selecting a region, or enlarge regions started in this way.
368 In Org-mode, in special contexts, these same keys are used for
369 other purposes, important enough to compete with shift selection.
370 Org tries to balance these needs by supporting `shift-select-mode'
371 outside these special contexts, under control of this variable.
373 The default of this variable is nil, to avoid confusing behavior. Shifted
374 cursor keys will then execute Org commands in the following contexts:
375 - on a headline, changing TODO state (left/right) and priority (up/down)
376 - on a time stamp, changing the time
377 - in a plain list item, changing the bullet type
378 - in a property definition line, switching between allowed values
379 - in the BEGIN line of a clock table (changing the time block).
380 Outside these contexts, the commands will throw an error.
382 When this variable is t and the cursor is not in a special
383 context, Org-mode will support shift-selection for making and
384 enlarging regions. To make this more effective, the bullet
385 cycling will no longer happen anywhere in an item line, but only
386 if the cursor is exactly on the bullet.
388 If you set this variable to the symbol `always', then the keys
389 will not be special in headlines, property lines, and item lines,
390 to make shift selection work there as well. If this is what you
391 want, you can use the following alternative commands: `C-c C-t'
392 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
393 can be used to switch TODO sets, `C-c -' to cycle item bullet
394 types, and properties can be edited by hand or in column view.
396 However, when the cursor is on a timestamp, shift-cursor commands
397 will still edit the time stamp - this is just too good to give up.
399 XEmacs user should have this variable set to nil, because
400 `shift-select-mode' is in Emacs 23 or later only."
401 :group 'org
402 :type '(choice
403 (const :tag "Never" nil)
404 (const :tag "When outside special context" t)
405 (const :tag "Everywhere except timestamps" always)))
407 (defcustom org-loop-over-headlines-in-active-region nil
408 "Shall some commands act upon headlines in the active region?
410 When set to `t', some commands will be performed in all headlines
411 within the active region.
413 When set to `start-level', some commands will be performed in all
414 headlines within the active region, provided that these headlines
415 are of the same level than the first one.
417 When set to a string, those commands will be performed on the
418 matching headlines within the active region. Such string must be
419 a tags/property/todo match as it is used in the agenda tags view.
421 The list of commands is:
422 - `org-schedule'
423 - `org-deadline'"
424 :type '(choice (const :tag "Don't loop" nil)
425 (const :tag "All headlines in active region" t)
426 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
427 (string :tag "Tags/Property/Todo matcher"))
428 :group 'org-todo
429 :group 'org-archive)
431 (defgroup org-startup nil
432 "Options concerning startup of Org-mode."
433 :tag "Org Startup"
434 :group 'org)
436 (defcustom org-startup-folded t
437 "Non-nil means entering Org-mode will switch to OVERVIEW.
438 This can also be configured on a per-file basis by adding one of
439 the following lines anywhere in the buffer:
441 #+STARTUP: fold (or `overview', this is equivalent)
442 #+STARTUP: nofold (or `showall', this is equivalent)
443 #+STARTUP: content
444 #+STARTUP: showeverything"
445 :group 'org-startup
446 :type '(choice
447 (const :tag "nofold: show all" nil)
448 (const :tag "fold: overview" t)
449 (const :tag "content: all headlines" content)
450 (const :tag "show everything, even drawers" showeverything)))
452 (defcustom org-startup-truncated t
453 "Non-nil means entering Org-mode will set `truncate-lines'.
454 This is useful since some lines containing links can be very long and
455 uninteresting. Also tables look terrible when wrapped."
456 :group 'org-startup
457 :type 'boolean)
459 (defcustom org-startup-indented nil
460 "Non-nil means turn on `org-indent-mode' on startup.
461 This can also be configured on a per-file basis by adding one of
462 the following lines anywhere in the buffer:
464 #+STARTUP: indent
465 #+STARTUP: noindent"
466 :group 'org-structure
467 :type '(choice
468 (const :tag "Not" nil)
469 (const :tag "Globally (slow on startup in large files)" t)))
471 (defcustom org-use-sub-superscripts t
472 "Non-nil means interpret \"_\" and \"^\" for export.
473 When this option is turned on, you can use TeX-like syntax for sub- and
474 superscripts. Several characters after \"_\" or \"^\" will be
475 considered as a single item - so grouping with {} is normally not
476 needed. For example, the following things will be parsed as single
477 sub- or superscripts.
479 10^24 or 10^tau several digits will be considered 1 item.
480 10^-12 or 10^-tau a leading sign with digits or a word
481 x^2-y^3 will be read as x^2 - y^3, because items are
482 terminated by almost any nonword/nondigit char.
483 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
485 Still, ambiguity is possible - so when in doubt use {} to enclose the
486 sub/superscript. If you set this variable to the symbol `{}',
487 the braces are *required* in order to trigger interpretations as
488 sub/superscript. This can be helpful in documents that need \"_\"
489 frequently in plain text.
491 Not all export backends support this, but HTML does.
493 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
494 :group 'org-startup
495 :group 'org-export-translation
496 :type '(choice
497 (const :tag "Always interpret" t)
498 (const :tag "Only with braces" {})
499 (const :tag "Never interpret" nil)))
501 (if (fboundp 'defvaralias)
502 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
505 (defcustom org-startup-with-beamer-mode nil
506 "Non-nil means turn on `org-beamer-mode' on startup.
507 This can also be configured on a per-file basis by adding one of
508 the following lines anywhere in the buffer:
510 #+STARTUP: beamer"
511 :group 'org-startup
512 :type 'boolean)
514 (defcustom org-startup-align-all-tables nil
515 "Non-nil means align all tables when visiting a file.
516 This is useful when the column width in tables is forced with <N> cookies
517 in table fields. Such tables will look correct only after the first re-align.
518 This can also be configured on a per-file basis by adding one of
519 the following lines anywhere in the buffer:
520 #+STARTUP: align
521 #+STARTUP: noalign"
522 :group 'org-startup
523 :type 'boolean)
525 (defcustom org-startup-with-inline-images nil
526 "Non-nil means show inline images when loading a new Org file.
527 This can also be configured on a per-file basis by adding one of
528 the following lines anywhere in the buffer:
529 #+STARTUP: inlineimages
530 #+STARTUP: noinlineimages"
531 :group 'org-startup
532 :type 'boolean)
534 (defcustom org-insert-mode-line-in-empty-file nil
535 "Non-nil means insert the first line setting Org-mode in empty files.
536 When the function `org-mode' is called interactively in an empty file, this
537 normally means that the file name does not automatically trigger Org-mode.
538 To ensure that the file will always be in Org-mode in the future, a
539 line enforcing Org-mode will be inserted into the buffer, if this option
540 has been set."
541 :group 'org-startup
542 :type 'boolean)
544 (defcustom org-replace-disputed-keys nil
545 "Non-nil means use alternative key bindings for some keys.
546 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
547 These keys are also used by other packages like shift-selection-mode'
548 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
549 If you want to use Org-mode together with one of these other modes,
550 or more generally if you would like to move some Org-mode commands to
551 other keys, set this variable and configure the keys with the variable
552 `org-disputed-keys'.
554 This option is only relevant at load-time of Org-mode, and must be set
555 *before* org.el is loaded. Changing it requires a restart of Emacs to
556 become effective."
557 :group 'org-startup
558 :type 'boolean)
560 (defcustom org-use-extra-keys nil
561 "Non-nil means use extra key sequence definitions for certain commands.
562 This happens automatically if you run XEmacs or if `window-system'
563 is nil. This variable lets you do the same manually. You must
564 set it before loading org.
566 Example: on Carbon Emacs 22 running graphically, with an external
567 keyboard on a Powerbook, the default way of setting M-left might
568 not work for either Alt or ESC. Setting this variable will make
569 it work for ESC."
570 :group 'org-startup
571 :type 'boolean)
573 (if (fboundp 'defvaralias)
574 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
576 (defcustom org-disputed-keys
577 '(([(shift up)] . [(meta p)])
578 ([(shift down)] . [(meta n)])
579 ([(shift left)] . [(meta -)])
580 ([(shift right)] . [(meta +)])
581 ([(control shift right)] . [(meta shift +)])
582 ([(control shift left)] . [(meta shift -)]))
583 "Keys for which Org-mode and other modes compete.
584 This is an alist, cars are the default keys, second element specifies
585 the alternative to use when `org-replace-disputed-keys' is t.
587 Keys can be specified in any syntax supported by `define-key'.
588 The value of this option takes effect only at Org-mode's startup,
589 therefore you'll have to restart Emacs to apply it after changing."
590 :group 'org-startup
591 :type 'alist)
593 (defun org-key (key)
594 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
595 Or return the original if not disputed.
596 Also apply the translations defined in `org-xemacs-key-equivalents'."
597 (when org-replace-disputed-keys
598 (let* ((nkey (key-description key))
599 (x (org-find-if (lambda (x)
600 (equal (key-description (car x)) nkey))
601 org-disputed-keys)))
602 (setq key (if x (cdr x) key))))
603 (when (featurep 'xemacs)
604 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
605 key)
607 (defun org-find-if (predicate seq)
608 (catch 'exit
609 (while seq
610 (if (funcall predicate (car seq))
611 (throw 'exit (car seq))
612 (pop seq)))))
614 (defun org-defkey (keymap key def)
615 "Define a key, possibly translated, as returned by `org-key'."
616 (define-key keymap (org-key key) def))
618 (defcustom org-ellipsis nil
619 "The ellipsis to use in the Org-mode outline.
620 When nil, just use the standard three dots. When a string, use that instead,
621 When a face, use the standard 3 dots, but with the specified face.
622 The change affects only Org-mode (which will then use its own display table).
623 Changing this requires executing `M-x org-mode' in a buffer to become
624 effective."
625 :group 'org-startup
626 :type '(choice (const :tag "Default" nil)
627 (face :tag "Face" :value org-warning)
628 (string :tag "String" :value "...#")))
630 (defvar org-display-table nil
631 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
633 (defgroup org-keywords nil
634 "Keywords in Org-mode."
635 :tag "Org Keywords"
636 :group 'org)
638 (defcustom org-deadline-string "DEADLINE:"
639 "String to mark deadline entries.
640 A deadline is this string, followed by a time stamp. Should be a word,
641 terminated by a colon. You can insert a schedule keyword and
642 a timestamp with \\[org-deadline].
643 Changes become only effective after restarting Emacs."
644 :group 'org-keywords
645 :type 'string)
647 (defcustom org-scheduled-string "SCHEDULED:"
648 "String to mark scheduled TODO entries.
649 A schedule is this string, followed by a time stamp. Should be a word,
650 terminated by a colon. You can insert a schedule keyword and
651 a timestamp with \\[org-schedule].
652 Changes become only effective after restarting Emacs."
653 :group 'org-keywords
654 :type 'string)
656 (defcustom org-closed-string "CLOSED:"
657 "String used as the prefix for timestamps logging closing a TODO entry."
658 :group 'org-keywords
659 :type 'string)
661 (defcustom org-clock-string "CLOCK:"
662 "String used as prefix for timestamps clocking work hours on an item."
663 :group 'org-keywords
664 :type 'string)
666 (defcustom org-comment-string "COMMENT"
667 "Entries starting with this keyword will never be exported.
668 An entry can be toggled between COMMENT and normal with
669 \\[org-toggle-comment].
670 Changes become only effective after restarting Emacs."
671 :group 'org-keywords
672 :type 'string)
674 (defcustom org-quote-string "QUOTE"
675 "Entries starting with this keyword will be exported in fixed-width font.
676 Quoting applies only to the text in the entry following the headline, and does
677 not extend beyond the next headline, even if that is lower level.
678 An entry can be toggled between QUOTE and normal with
679 \\[org-toggle-fixed-width-section]."
680 :group 'org-keywords
681 :type 'string)
683 (defconst org-repeat-re
684 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
685 "Regular expression for specifying repeated events.
686 After a match, group 1 contains the repeat expression.")
688 (defgroup org-structure nil
689 "Options concerning the general structure of Org-mode files."
690 :tag "Org Structure"
691 :group 'org)
693 (defgroup org-reveal-location nil
694 "Options about how to make context of a location visible."
695 :tag "Org Reveal Location"
696 :group 'org-structure)
698 (defconst org-context-choice
699 '(choice
700 (const :tag "Always" t)
701 (const :tag "Never" nil)
702 (repeat :greedy t :tag "Individual contexts"
703 (cons
704 (choice :tag "Context"
705 (const agenda)
706 (const org-goto)
707 (const occur-tree)
708 (const tags-tree)
709 (const link-search)
710 (const mark-goto)
711 (const bookmark-jump)
712 (const isearch)
713 (const default))
714 (boolean))))
715 "Contexts for the reveal options.")
717 (defcustom org-show-hierarchy-above '((default . t))
718 "Non-nil means show full hierarchy when revealing a location.
719 Org-mode often shows locations in an org-mode file which might have
720 been invisible before. When this is set, the hierarchy of headings
721 above the exposed location is shown.
722 Turning this off for example for sparse trees makes them very compact.
723 Instead of t, this can also be an alist specifying this option for different
724 contexts. Valid contexts are
725 agenda when exposing an entry from the agenda
726 org-goto when using the command `org-goto' on key C-c C-j
727 occur-tree when using the command `org-occur' on key C-c /
728 tags-tree when constructing a sparse tree based on tags matches
729 link-search when exposing search matches associated with a link
730 mark-goto when exposing the jump goal of a mark
731 bookmark-jump when exposing a bookmark location
732 isearch when exiting from an incremental search
733 default default for all contexts not set explicitly"
734 :group 'org-reveal-location
735 :type org-context-choice)
737 (defcustom org-show-following-heading '((default . nil))
738 "Non-nil means show following heading when revealing a location.
739 Org-mode often shows locations in an org-mode file which might have
740 been invisible before. When this is set, the heading following the
741 match is shown.
742 Turning this off for example for sparse trees makes them very compact,
743 but makes it harder to edit the location of the match. In such a case,
744 use the command \\[org-reveal] to show more context.
745 Instead of t, this can also be an alist specifying this option for different
746 contexts. See `org-show-hierarchy-above' for valid contexts."
747 :group 'org-reveal-location
748 :type org-context-choice)
750 (defcustom org-show-siblings '((default . nil) (isearch t))
751 "Non-nil means show all sibling heading when revealing a location.
752 Org-mode often shows locations in an org-mode file which might have
753 been invisible before. When this is set, the sibling of the current entry
754 heading are all made visible. If `org-show-hierarchy-above' is t,
755 the same happens on each level of the hierarchy above the current entry.
757 By default this is on for the isearch context, off for all other contexts.
758 Turning this off for example for sparse trees makes them very compact,
759 but makes it harder to edit the location of the match. In such a case,
760 use the command \\[org-reveal] to show more context.
761 Instead of t, this can also be an alist specifying this option for different
762 contexts. See `org-show-hierarchy-above' for valid contexts."
763 :group 'org-reveal-location
764 :type org-context-choice)
766 (defcustom org-show-entry-below '((default . nil))
767 "Non-nil means show the entry below a headline when revealing a location.
768 Org-mode often shows locations in an org-mode file which might have
769 been invisible before. When this is set, the text below the headline that is
770 exposed is also shown.
772 By default this is off for all contexts.
773 Instead of t, this can also be an alist specifying this option for different
774 contexts. See `org-show-hierarchy-above' for valid contexts."
775 :group 'org-reveal-location
776 :type org-context-choice)
778 (defcustom org-indirect-buffer-display 'other-window
779 "How should indirect tree buffers be displayed?
780 This applies to indirect buffers created with the commands
781 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
782 Valid values are:
783 current-window Display in the current window
784 other-window Just display in another window.
785 dedicated-frame Create one new frame, and re-use it each time.
786 new-frame Make a new frame each time. Note that in this case
787 previously-made indirect buffers are kept, and you need to
788 kill these buffers yourself."
789 :group 'org-structure
790 :group 'org-agenda-windows
791 :type '(choice
792 (const :tag "In current window" current-window)
793 (const :tag "In current frame, other window" other-window)
794 (const :tag "Each time a new frame" new-frame)
795 (const :tag "One dedicated frame" dedicated-frame)))
797 (defcustom org-use-speed-commands nil
798 "Non-nil means activate single letter commands at beginning of a headline.
799 This may also be a function to test for appropriate locations where speed
800 commands should be active."
801 :group 'org-structure
802 :type '(choice
803 (const :tag "Never" nil)
804 (const :tag "At beginning of headline stars" t)
805 (function)))
807 (defcustom org-speed-commands-user nil
808 "Alist of additional speed commands.
809 This list will be checked before `org-speed-commands-default'
810 when the variable `org-use-speed-commands' is non-nil
811 and when the cursor is at the beginning of a headline.
812 The car if each entry is a string with a single letter, which must
813 be assigned to `self-insert-command' in the global map.
814 The cdr is either a command to be called interactively, a function
815 to be called, or a form to be evaluated.
816 An entry that is just a list with a single string will be interpreted
817 as a descriptive headline that will be added when listing the speed
818 commands in the Help buffer using the `?' speed command."
819 :group 'org-structure
820 :type '(repeat :value ("k" . ignore)
821 (choice :value ("k" . ignore)
822 (list :tag "Descriptive Headline" (string :tag "Headline"))
823 (cons :tag "Letter and Command"
824 (string :tag "Command letter")
825 (choice
826 (function)
827 (sexp))))))
829 (defgroup org-cycle nil
830 "Options concerning visibility cycling in Org-mode."
831 :tag "Org Cycle"
832 :group 'org-structure)
834 (defcustom org-cycle-skip-children-state-if-no-children t
835 "Non-nil means skip CHILDREN state in entries that don't have any."
836 :group 'org-cycle
837 :type 'boolean)
839 (defcustom org-cycle-max-level nil
840 "Maximum level which should still be subject to visibility cycling.
841 Levels higher than this will, for cycling, be treated as text, not a headline.
842 When `org-odd-levels-only' is set, a value of N in this variable actually
843 means 2N-1 stars as the limiting headline.
844 When nil, cycle all levels.
845 Note that the limiting level of cycling is also influenced by
846 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
847 `org-inlinetask-min-level' is, cycling will be limited to levels one less
848 than its value."
849 :group 'org-cycle
850 :type '(choice
851 (const :tag "No limit" nil)
852 (integer :tag "Maximum level")))
854 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
855 "Names of drawers. Drawers are not opened by cycling on the headline above.
856 Drawers only open with a TAB on the drawer line itself. A drawer looks like
857 this:
858 :DRAWERNAME:
859 .....
860 :END:
861 The drawer \"PROPERTIES\" is special for capturing properties through
862 the property API.
864 Drawers can be defined on the per-file basis with a line like:
866 #+DRAWERS: HIDDEN STATE PROPERTIES"
867 :group 'org-structure
868 :group 'org-cycle
869 :type '(repeat (string :tag "Drawer Name")))
871 (defcustom org-hide-block-startup nil
872 "Non-nil means entering Org-mode will fold all blocks.
873 This can also be set in on a per-file basis with
875 #+STARTUP: hideblocks
876 #+STARTUP: showblocks"
877 :group 'org-startup
878 :group 'org-cycle
879 :type 'boolean)
881 (defcustom org-cycle-global-at-bob nil
882 "Cycle globally if cursor is at beginning of buffer and not at a headline.
883 This makes it possible to do global cycling without having to use S-TAB or
884 \\[universal-argument] TAB. For this special case to work, the first line \
885 of the buffer
886 must not be a headline - it may be empty or some other text. When used in
887 this way, `org-cycle-hook' is disables temporarily, to make sure the
888 cursor stays at the beginning of the buffer.
889 When this option is nil, don't do anything special at the beginning
890 of the buffer."
891 :group 'org-cycle
892 :type 'boolean)
894 (defcustom org-cycle-level-after-item/entry-creation t
895 "Non-nil means cycle entry level or item indentation in new empty entries.
897 When the cursor is at the end of an empty headline, i.e with only stars
898 and maybe a TODO keyword, TAB will then switch the entry to become a child,
899 and then all possible ancestor states, before returning to the original state.
900 This makes data entry extremely fast: M-RET to create a new headline,
901 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
903 When the cursor is at the end of an empty plain list item, one TAB will
904 make it a subitem, two or more tabs will back up to make this an item
905 higher up in the item hierarchy."
906 :group 'org-cycle
907 :type 'boolean)
909 (defcustom org-cycle-emulate-tab t
910 "Where should `org-cycle' emulate TAB.
911 nil Never
912 white Only in completely white lines
913 whitestart Only at the beginning of lines, before the first non-white char
914 t Everywhere except in headlines
915 exc-hl-bol Everywhere except at the start of a headline
916 If TAB is used in a place where it does not emulate TAB, the current subtree
917 visibility is cycled."
918 :group 'org-cycle
919 :type '(choice (const :tag "Never" nil)
920 (const :tag "Only in completely white lines" white)
921 (const :tag "Before first char in a line" whitestart)
922 (const :tag "Everywhere except in headlines" t)
923 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
926 (defcustom org-cycle-separator-lines 2
927 "Number of empty lines needed to keep an empty line between collapsed trees.
928 If you leave an empty line between the end of a subtree and the following
929 headline, this empty line is hidden when the subtree is folded.
930 Org-mode will leave (exactly) one empty line visible if the number of
931 empty lines is equal or larger to the number given in this variable.
932 So the default 2 means at least 2 empty lines after the end of a subtree
933 are needed to produce free space between a collapsed subtree and the
934 following headline.
936 If the number is negative, and the number of empty lines is at least -N,
937 all empty lines are shown.
939 Special case: when 0, never leave empty lines in collapsed view."
940 :group 'org-cycle
941 :type 'integer)
942 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
944 (defcustom org-pre-cycle-hook nil
945 "Hook that is run before visibility cycling is happening.
946 The function(s) in this hook must accept a single argument which indicates
947 the new state that will be set right after running this hook. The
948 argument is a symbol. Before a global state change, it can have the values
949 `overview', `content', or `all'. Before a local state change, it can have
950 the values `folded', `children', or `subtree'."
951 :group 'org-cycle
952 :type 'hook)
954 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
955 org-cycle-hide-drawers
956 org-cycle-show-empty-lines
957 org-optimize-window-after-visibility-change)
958 "Hook that is run after `org-cycle' has changed the buffer visibility.
959 The function(s) in this hook must accept a single argument which indicates
960 the new state that was set by the most recent `org-cycle' command. The
961 argument is a symbol. After a global state change, it can have the values
962 `overview', `content', or `all'. After a local state change, it can have
963 the values `folded', `children', or `subtree'."
964 :group 'org-cycle
965 :type 'hook)
967 (defgroup org-edit-structure nil
968 "Options concerning structure editing in Org-mode."
969 :tag "Org Edit Structure"
970 :group 'org-structure)
972 (defcustom org-odd-levels-only nil
973 "Non-nil means skip even levels and only use odd levels for the outline.
974 This has the effect that two stars are being added/taken away in
975 promotion/demotion commands. It also influences how levels are
976 handled by the exporters.
977 Changing it requires restart of `font-lock-mode' to become effective
978 for fontification also in regions already fontified.
979 You may also set this on a per-file basis by adding one of the following
980 lines to the buffer:
982 #+STARTUP: odd
983 #+STARTUP: oddeven"
984 :group 'org-edit-structure
985 :group 'org-appearance
986 :type 'boolean)
988 (defcustom org-adapt-indentation t
989 "Non-nil means adapt indentation to outline node level.
991 When this variable is set, Org assumes that you write outlines by
992 indenting text in each node to align with the headline (after the stars).
993 The following issues are influenced by this variable:
995 - When this is set and the *entire* text in an entry is indented, the
996 indentation is increased by one space in a demotion command, and
997 decreased by one in a promotion command. If any line in the entry
998 body starts with text at column 0, indentation is not changed at all.
1000 - Property drawers and planning information is inserted indented when
1001 this variable s set. When nil, they will not be indented.
1003 - TAB indents a line relative to context. The lines below a headline
1004 will be indented when this variable is set.
1006 Note that this is all about true indentation, by adding and removing
1007 space characters. See also `org-indent.el' which does level-dependent
1008 indentation in a virtual way, i.e. at display time in Emacs."
1009 :group 'org-edit-structure
1010 :type 'boolean)
1012 (defcustom org-special-ctrl-a/e nil
1013 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1015 When t, `C-a' will bring back the cursor to the beginning of the
1016 headline text, i.e. after the stars and after a possible TODO keyword.
1017 In an item, this will be the position after the bullet.
1018 When the cursor is already at that position, another `C-a' will bring
1019 it to the beginning of the line.
1021 `C-e' will jump to the end of the headline, ignoring the presence of tags
1022 in the headline. A second `C-e' will then jump to the true end of the
1023 line, after any tags. This also means that, when this variable is
1024 non-nil, `C-e' also will never jump beyond the end of the heading of a
1025 folded section, i.e. not after the ellipses.
1027 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
1028 going to the true line boundary first. Only a directly following, identical
1029 keypress will bring the cursor to the special positions.
1031 This may also be a cons cell where the behavior for `C-a' and `C-e' is
1032 set separately."
1033 :group 'org-edit-structure
1034 :type '(choice
1035 (const :tag "off" nil)
1036 (const :tag "on: after stars/bullet and before tags first" t)
1037 (const :tag "reversed: true line boundary first" reversed)
1038 (cons :tag "Set C-a and C-e separately"
1039 (choice :tag "Special C-a"
1040 (const :tag "off" nil)
1041 (const :tag "on: after stars/bullet first" t)
1042 (const :tag "reversed: before stars/bullet first" reversed))
1043 (choice :tag "Special C-e"
1044 (const :tag "off" nil)
1045 (const :tag "on: before tags first" t)
1046 (const :tag "reversed: after tags first" reversed)))))
1047 (if (fboundp 'defvaralias)
1048 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1050 (defcustom org-special-ctrl-k nil
1051 "Non-nil means `C-k' will behave specially in headlines.
1052 When nil, `C-k' will call the default `kill-line' command.
1053 When t, the following will happen while the cursor is in the headline:
1055 - When the cursor is at the beginning of a headline, kill the entire
1056 line and possible the folded subtree below the line.
1057 - When in the middle of the headline text, kill the headline up to the tags.
1058 - When after the headline text, kill the tags."
1059 :group 'org-edit-structure
1060 :type 'boolean)
1062 (defcustom org-ctrl-k-protect-subtree nil
1063 "Non-nil means, do not delete a hidden subtree with C-k.
1064 When set to the symbol `error', simply throw an error when C-k is
1065 used to kill (part-of) a headline that has hidden text behind it.
1066 Any other non-nil value will result in a query to the user, if it is
1067 OK to kill that hidden subtree. When nil, kill without remorse."
1068 :group 'org-edit-structure
1069 :type '(choice
1070 (const :tag "Do not protect hidden subtrees" nil)
1071 (const :tag "Protect hidden subtrees with a security query" t)
1072 (const :tag "Never kill a hidden subtree with C-k" error)))
1074 (defcustom org-catch-invisible-edits nil
1075 "Check if in invisible region before inserting or deleting a character.
1076 Valid values are:
1078 nil Do not check, so just do invisible edits.
1079 error Throw an error and do nothing.
1080 show Make point visible, and do the requested edit.
1081 show-and-error Make point visible, then throw an error and abort the edit.
1082 smart Make point visible, and do insertion/deletion if it is
1083 adjacent to visible text and the change feels predictable.
1084 Never delete a previously invisible character or add in the
1085 middle or right after an invisible region. Basically, this
1086 allows insertion and backward-delete right before ellipses.
1087 FIXME: maybe in this case we should not even show?"
1088 :group 'org-edit-structure
1089 :type '(choice
1090 (const :tag "Do not check" nil)
1091 (const :tag "Throw error when trying to edit" error)
1092 (const :tag "Unhide, but do not do the edit" show-and-error)
1093 (const :tag "Show invisible part and do the edit" show)
1094 (const :tag "Be smart and do the right thing" smart)))
1096 (defcustom org-yank-folded-subtrees t
1097 "Non-nil means when yanking subtrees, fold them.
1098 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1099 it starts with a heading and all other headings in it are either children
1100 or siblings, then fold all the subtrees. However, do this only if no
1101 text after the yank would be swallowed into a folded tree by this action."
1102 :group 'org-edit-structure
1103 :type 'boolean)
1105 (defcustom org-yank-adjusted-subtrees nil
1106 "Non-nil means when yanking subtrees, adjust the level.
1107 With this setting, `org-paste-subtree' is used to insert the subtree, see
1108 this function for details."
1109 :group 'org-edit-structure
1110 :type 'boolean)
1112 (defcustom org-M-RET-may-split-line '((default . t))
1113 "Non-nil means M-RET will split the line at the cursor position.
1114 When nil, it will go to the end of the line before making a
1115 new line.
1116 You may also set this option in a different way for different
1117 contexts. Valid contexts are:
1119 headline when creating a new headline
1120 item when creating a new item
1121 table in a table field
1122 default the value to be used for all contexts not explicitly
1123 customized"
1124 :group 'org-structure
1125 :group 'org-table
1126 :type '(choice
1127 (const :tag "Always" t)
1128 (const :tag "Never" nil)
1129 (repeat :greedy t :tag "Individual contexts"
1130 (cons
1131 (choice :tag "Context"
1132 (const headline)
1133 (const item)
1134 (const table)
1135 (const default))
1136 (boolean)))))
1139 (defcustom org-insert-heading-respect-content nil
1140 "Non-nil means insert new headings after the current subtree.
1141 When nil, the new heading is created directly after the current line.
1142 The commands \\[org-insert-heading-respect-content] and
1143 \\[org-insert-todo-heading-respect-content] turn this variable on
1144 for the duration of the command."
1145 :group 'org-structure
1146 :type 'boolean)
1148 (defcustom org-blank-before-new-entry '((heading . auto)
1149 (plain-list-item . auto))
1150 "Should `org-insert-heading' leave a blank line before new heading/item?
1151 The value is an alist, with `heading' and `plain-list-item' as CAR,
1152 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1153 which case Org will look at the surrounding headings/items and try to
1154 make an intelligent decision whether to insert a blank line or not.
1156 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1157 set, the setting here is ignored and no empty line is inserted, to avoid
1158 breaking the list structure."
1159 :group 'org-edit-structure
1160 :type '(list
1161 (cons (const heading)
1162 (choice (const :tag "Never" nil)
1163 (const :tag "Always" t)
1164 (const :tag "Auto" auto)))
1165 (cons (const plain-list-item)
1166 (choice (const :tag "Never" nil)
1167 (const :tag "Always" t)
1168 (const :tag "Auto" auto)))))
1170 (defcustom org-insert-heading-hook nil
1171 "Hook being run after inserting a new heading."
1172 :group 'org-edit-structure
1173 :type 'hook)
1175 (defcustom org-enable-fixed-width-editor t
1176 "Non-nil means lines starting with \":\" are treated as fixed-width.
1177 This currently only means they are never auto-wrapped.
1178 When nil, such lines will be treated like ordinary lines.
1179 See also the QUOTE keyword."
1180 :group 'org-edit-structure
1181 :type 'boolean)
1183 (defcustom org-goto-auto-isearch t
1184 "Non-nil means typing characters in `org-goto' starts incremental search."
1185 :group 'org-edit-structure
1186 :type 'boolean)
1188 (defgroup org-sparse-trees nil
1189 "Options concerning sparse trees in Org-mode."
1190 :tag "Org Sparse Trees"
1191 :group 'org-structure)
1193 (defcustom org-highlight-sparse-tree-matches t
1194 "Non-nil means highlight all matches that define a sparse tree.
1195 The highlights will automatically disappear the next time the buffer is
1196 changed by an edit command."
1197 :group 'org-sparse-trees
1198 :type 'boolean)
1200 (defcustom org-remove-highlights-with-change t
1201 "Non-nil means any change to the buffer will remove temporary highlights.
1202 Such highlights are created by `org-occur' and `org-clock-display'.
1203 When nil, `C-c C-c needs to be used to get rid of the highlights.
1204 The highlights created by `org-preview-latex-fragment' always need
1205 `C-c C-c' to be removed."
1206 :group 'org-sparse-trees
1207 :group 'org-time
1208 :type 'boolean)
1211 (defcustom org-occur-hook '(org-first-headline-recenter)
1212 "Hook that is run after `org-occur' has constructed a sparse tree.
1213 This can be used to recenter the window to show as much of the structure
1214 as possible."
1215 :group 'org-sparse-trees
1216 :type 'hook)
1218 (defgroup org-imenu-and-speedbar nil
1219 "Options concerning imenu and speedbar in Org-mode."
1220 :tag "Org Imenu and Speedbar"
1221 :group 'org-structure)
1223 (defcustom org-imenu-depth 2
1224 "The maximum level for Imenu access to Org-mode headlines.
1225 This also applied for speedbar access."
1226 :group 'org-imenu-and-speedbar
1227 :type 'integer)
1229 (defgroup org-table nil
1230 "Options concerning tables in Org-mode."
1231 :tag "Org Table"
1232 :group 'org)
1234 (defcustom org-enable-table-editor 'optimized
1235 "Non-nil means lines starting with \"|\" are handled by the table editor.
1236 When nil, such lines will be treated like ordinary lines.
1238 When equal to the symbol `optimized', the table editor will be optimized to
1239 do the following:
1240 - Automatic overwrite mode in front of whitespace in table fields.
1241 This makes the structure of the table stay in tact as long as the edited
1242 field does not exceed the column width.
1243 - Minimize the number of realigns. Normally, the table is aligned each time
1244 TAB or RET are pressed to move to another field. With optimization this
1245 happens only if changes to a field might have changed the column width.
1246 Optimization requires replacing the functions `self-insert-command',
1247 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1248 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1249 very good at guessing when a re-align will be necessary, but you can always
1250 force one with \\[org-ctrl-c-ctrl-c].
1252 If you would like to use the optimized version in Org-mode, but the
1253 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1255 This variable can be used to turn on and off the table editor during a session,
1256 but in order to toggle optimization, a restart is required.
1258 See also the variable `org-table-auto-blank-field'."
1259 :group 'org-table
1260 :type '(choice
1261 (const :tag "off" nil)
1262 (const :tag "on" t)
1263 (const :tag "on, optimized" optimized)))
1265 (defcustom org-self-insert-cluster-for-undo t
1266 "Non-nil means cluster self-insert commands for undo when possible.
1267 If this is set, then, like in the Emacs command loop, 20 consecutive
1268 characters will be undone together.
1269 This is configurable, because there is some impact on typing performance."
1270 :group 'org-table
1271 :type 'boolean)
1273 (defcustom org-table-tab-recognizes-table.el t
1274 "Non-nil means TAB will automatically notice a table.el table.
1275 When it sees such a table, it moves point into it and - if necessary -
1276 calls `table-recognize-table'."
1277 :group 'org-table-editing
1278 :type 'boolean)
1280 (defgroup org-link nil
1281 "Options concerning links in Org-mode."
1282 :tag "Org Link"
1283 :group 'org)
1285 (defvar org-link-abbrev-alist-local nil
1286 "Buffer-local version of `org-link-abbrev-alist', which see.
1287 The value of this is taken from the #+LINK lines.")
1288 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1290 (defcustom org-link-abbrev-alist nil
1291 "Alist of link abbreviations.
1292 The car of each element is a string, to be replaced at the start of a link.
1293 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1294 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1296 [[linkkey:tag][description]]
1298 The 'linkkey' must be a word word, starting with a letter, followed
1299 by letters, numbers, '-' or '_'.
1301 If REPLACE is a string, the tag will simply be appended to create the link.
1302 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1303 the placeholder \"%h\" will cause a url-encoded version of the tag to
1304 be inserted at that point (see the function `url-hexify-string').
1306 REPLACE may also be a function that will be called with the tag as the
1307 only argument to create the link, which should be returned as a string.
1309 See the manual for examples."
1310 :group 'org-link
1311 :type '(repeat
1312 (cons
1313 (string :tag "Protocol")
1314 (choice
1315 (string :tag "Format")
1316 (function)))))
1318 (defcustom org-descriptive-links t
1319 "Non-nil means Org will display descriptive links.
1320 E.g. [[http://orgmode.org][Org website]] will be displayed as
1321 \"Org Website\", hiding the link itself and just displaying its
1322 description. When set to `nil', Org will display the full links
1323 literally.
1325 You can interactively set the value of this variable by calling
1326 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1327 :group 'org-link
1328 :type 'boolean)
1330 (defcustom org-link-file-path-type 'adaptive
1331 "How the path name in file links should be stored.
1332 Valid values are:
1334 relative Relative to the current directory, i.e. the directory of the file
1335 into which the link is being inserted.
1336 absolute Absolute path, if possible with ~ for home directory.
1337 noabbrev Absolute path, no abbreviation of home directory.
1338 adaptive Use relative path for files in the current directory and sub-
1339 directories of it. For other files, use an absolute path."
1340 :group 'org-link
1341 :type '(choice
1342 (const relative)
1343 (const absolute)
1344 (const noabbrev)
1345 (const adaptive)))
1347 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1348 "Types of links that should be activated in Org-mode files.
1349 This is a list of symbols, each leading to the activation of a certain link
1350 type. In principle, it does not hurt to turn on most link types - there may
1351 be a small gain when turning off unused link types. The types are:
1353 bracket The recommended [[link][description]] or [[link]] links with hiding.
1354 angle Links in angular brackets that may contain whitespace like
1355 <bbdb:Carsten Dominik>.
1356 plain Plain links in normal text, no whitespace, like http://google.com.
1357 radio Text that is matched by a radio target, see manual for details.
1358 tag Tag settings in a headline (link to tag search).
1359 date Time stamps (link to calendar).
1360 footnote Footnote labels.
1362 Changing this variable requires a restart of Emacs to become effective."
1363 :group 'org-link
1364 :type '(set :greedy t
1365 (const :tag "Double bracket links" bracket)
1366 (const :tag "Angular bracket links" angle)
1367 (const :tag "Plain text links" plain)
1368 (const :tag "Radio target matches" radio)
1369 (const :tag "Tags" tag)
1370 (const :tag "Timestamps" date)
1371 (const :tag "Footnotes" footnote)))
1373 (defcustom org-make-link-description-function nil
1374 "Function to use to generate link descriptions from links.
1375 If nil the link location will be used. This function must take
1376 two parameters; the first is the link and the second the
1377 description `org-insert-link' has generated, and should return the
1378 description to use."
1379 :group 'org-link
1380 :type 'function)
1382 (defgroup org-link-store nil
1383 "Options concerning storing links in Org-mode."
1384 :tag "Org Store Link"
1385 :group 'org-link)
1387 (defcustom org-email-link-description-format "Email %c: %.30s"
1388 "Format of the description part of a link to an email or usenet message.
1389 The following %-escapes will be replaced by corresponding information:
1391 %F full \"From\" field
1392 %f name, taken from \"From\" field, address if no name
1393 %T full \"To\" field
1394 %t first name in \"To\" field, address if no name
1395 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1396 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1397 %s subject
1398 %d date
1399 %m message-id.
1401 You may use normal field width specification between the % and the letter.
1402 This is for example useful to limit the length of the subject.
1404 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1405 :group 'org-link-store
1406 :type 'string)
1408 (defcustom org-from-is-user-regexp
1409 (let (r1 r2)
1410 (when (and user-mail-address (not (string= user-mail-address "")))
1411 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1412 (when (and user-full-name (not (string= user-full-name "")))
1413 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1414 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1415 "Regexp matched against the \"From:\" header of an email or usenet message.
1416 It should match if the message is from the user him/herself."
1417 :group 'org-link-store
1418 :type 'regexp)
1420 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1421 "Non-nil means storing a link to an Org file will use entry IDs.
1423 Note that before this variable is even considered, org-id must be loaded,
1424 so please customize `org-modules' and turn it on.
1426 The variable can have the following values:
1428 t Create an ID if needed to make a link to the current entry.
1430 create-if-interactive
1431 If `org-store-link' is called directly (interactively, as a user
1432 command), do create an ID to support the link. But when doing the
1433 job for remember, only use the ID if it already exists. The
1434 purpose of this setting is to avoid proliferation of unwanted
1435 IDs, just because you happen to be in an Org file when you
1436 call `org-remember' that automatically and preemptively
1437 creates a link. If you do want to get an ID link in a remember
1438 template to an entry not having an ID, create it first by
1439 explicitly creating a link to it, using `C-c C-l' first.
1441 create-if-interactive-and-no-custom-id
1442 Like create-if-interactive, but do not create an ID if there is
1443 a CUSTOM_ID property defined in the entry. This is the default.
1445 use-existing
1446 Use existing ID, do not create one.
1448 nil Never use an ID to make a link, instead link using a text search for
1449 the headline text."
1450 :group 'org-link-store
1451 :type '(choice
1452 (const :tag "Create ID to make link" t)
1453 (const :tag "Create if storing link interactively"
1454 create-if-interactive)
1455 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1456 create-if-interactive-and-no-custom-id)
1457 (const :tag "Only use existing" use-existing)
1458 (const :tag "Do not use ID to create link" nil)))
1460 (defcustom org-context-in-file-links t
1461 "Non-nil means file links from `org-store-link' contain context.
1462 A search string will be added to the file name with :: as separator and
1463 used to find the context when the link is activated by the command
1464 `org-open-at-point'. When this option is t, the entire active region
1465 will be placed in the search string of the file link. If set to a
1466 positive integer, only the first n lines of context will be stored.
1468 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1469 negates this setting for the duration of the command."
1470 :group 'org-link-store
1471 :type '(choice boolean integer))
1473 (defcustom org-keep-stored-link-after-insertion nil
1474 "Non-nil means keep link in list for entire session.
1476 The command `org-store-link' adds a link pointing to the current
1477 location to an internal list. These links accumulate during a session.
1478 The command `org-insert-link' can be used to insert links into any
1479 Org-mode file (offering completion for all stored links). When this
1480 option is nil, every link which has been inserted once using \\[org-insert-link]
1481 will be removed from the list, to make completing the unused links
1482 more efficient."
1483 :group 'org-link-store
1484 :type 'boolean)
1486 (defgroup org-link-follow nil
1487 "Options concerning following links in Org-mode."
1488 :tag "Org Follow Link"
1489 :group 'org-link)
1491 (defcustom org-link-translation-function nil
1492 "Function to translate links with different syntax to Org syntax.
1493 This can be used to translate links created for example by the Planner
1494 or emacs-wiki packages to Org syntax.
1495 The function must accept two parameters, a TYPE containing the link
1496 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1497 which is everything after the link protocol. It should return a cons
1498 with possibly modified values of type and path.
1499 Org contains a function for this, so if you set this variable to
1500 `org-translate-link-from-planner', you should be able follow many
1501 links created by planner."
1502 :group 'org-link-follow
1503 :type 'function)
1505 (defcustom org-follow-link-hook nil
1506 "Hook that is run after a link has been followed."
1507 :group 'org-link-follow
1508 :type 'hook)
1510 (defcustom org-tab-follows-link nil
1511 "Non-nil means on links TAB will follow the link.
1512 Needs to be set before org.el is loaded.
1513 This really should not be used, it does not make sense, and the
1514 implementation is bad."
1515 :group 'org-link-follow
1516 :type 'boolean)
1518 (defcustom org-return-follows-link nil
1519 "Non-nil means on links RET will follow the link."
1520 :group 'org-link-follow
1521 :type 'boolean)
1523 (defcustom org-mouse-1-follows-link
1524 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1525 "Non-nil means mouse-1 on a link will follow the link.
1526 A longer mouse click will still set point. Does not work on XEmacs.
1527 Needs to be set before org.el is loaded."
1528 :group 'org-link-follow
1529 :type 'boolean)
1531 (defcustom org-mark-ring-length 4
1532 "Number of different positions to be recorded in the ring.
1533 Changing this requires a restart of Emacs to work correctly."
1534 :group 'org-link-follow
1535 :type 'integer)
1537 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1538 "Non-nil means internal links in Org files must exactly match a headline.
1539 When nil, the link search tries to match a phrase with all words
1540 in the search text."
1541 :group 'org-link-follow
1542 :type '(choice
1543 (const :tag "Use fuzzy text search" nil)
1544 (const :tag "Match only exact headline" t)
1545 (const :tag "Match exact headline or query to create it"
1546 query-to-create)))
1548 (defcustom org-link-frame-setup
1549 '((vm . vm-visit-folder-other-frame)
1550 (gnus . org-gnus-no-new-news)
1551 (file . find-file-other-window)
1552 (wl . wl-other-frame))
1553 "Setup the frame configuration for following links.
1554 When following a link with Emacs, it may often be useful to display
1555 this link in another window or frame. This variable can be used to
1556 set this up for the different types of links.
1557 For VM, use any of
1558 `vm-visit-folder'
1559 `vm-visit-folder-other-window'
1560 `vm-visit-folder-other-frame'
1561 For Gnus, use any of
1562 `gnus'
1563 `gnus-other-frame'
1564 `org-gnus-no-new-news'
1565 For FILE, use any of
1566 `find-file'
1567 `find-file-other-window'
1568 `find-file-other-frame'
1569 For Wanderlust use any of
1570 `wl'
1571 `wl-other-frame'
1572 For the calendar, use the variable `calendar-setup'.
1573 For BBDB, it is currently only possible to display the matches in
1574 another window."
1575 :group 'org-link-follow
1576 :type '(list
1577 (cons (const vm)
1578 (choice
1579 (const vm-visit-folder)
1580 (const vm-visit-folder-other-window)
1581 (const vm-visit-folder-other-frame)))
1582 (cons (const gnus)
1583 (choice
1584 (const gnus)
1585 (const gnus-other-frame)
1586 (const org-gnus-no-new-news)))
1587 (cons (const file)
1588 (choice
1589 (const find-file)
1590 (const find-file-other-window)
1591 (const find-file-other-frame)))
1592 (cons (const wl)
1593 (choice
1594 (const wl)
1595 (const wl-other-frame)))))
1597 (defcustom org-display-internal-link-with-indirect-buffer nil
1598 "Non-nil means use indirect buffer to display infile links.
1599 Activating internal links (from one location in a file to another location
1600 in the same file) normally just jumps to the location. When the link is
1601 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1602 is displayed in
1603 another window. When this option is set, the other window actually displays
1604 an indirect buffer clone of the current buffer, to avoid any visibility
1605 changes to the current buffer."
1606 :group 'org-link-follow
1607 :type 'boolean)
1609 (defcustom org-open-non-existing-files nil
1610 "Non-nil means `org-open-file' will open non-existing files.
1611 When nil, an error will be generated.
1612 This variable applies only to external applications because they
1613 might choke on non-existing files. If the link is to a file that
1614 will be opened in Emacs, the variable is ignored."
1615 :group 'org-link-follow
1616 :type 'boolean)
1618 (defcustom org-open-directory-means-index-dot-org nil
1619 "Non-nil means a link to a directory really means to index.org.
1620 When nil, following a directory link will run dired or open a finder/explorer
1621 window on that directory."
1622 :group 'org-link-follow
1623 :type 'boolean)
1625 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1626 "Function and arguments to call for following mailto links.
1627 This is a list with the first element being a Lisp function, and the
1628 remaining elements being arguments to the function. In string arguments,
1629 %a will be replaced by the address, and %s will be replaced by the subject
1630 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1631 :group 'org-link-follow
1632 :type '(choice
1633 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1634 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1635 (const :tag "message-mail" (message-mail "%a" "%s"))
1636 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1638 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1639 "Non-nil means ask for confirmation before executing shell links.
1640 Shell links can be dangerous: just think about a link
1642 [[shell:rm -rf ~/*][Google Search]]
1644 This link would show up in your Org-mode document as \"Google Search\",
1645 but really it would remove your entire home directory.
1646 Therefore we advise against setting this variable to nil.
1647 Just change it to `y-or-n-p' if you want to confirm with a
1648 single keystroke rather than having to type \"yes\"."
1649 :group 'org-link-follow
1650 :type '(choice
1651 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1652 (const :tag "with y-or-n (faster)" y-or-n-p)
1653 (const :tag "no confirmation (dangerous)" nil)))
1654 (put 'org-confirm-shell-link-function
1655 'safe-local-variable
1656 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1658 (defcustom org-confirm-shell-link-not-regexp ""
1659 "A regexp to skip confirmation for shell links."
1660 :group 'org-link-follow
1661 :type 'regexp)
1663 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1664 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1665 Elisp links can be dangerous: just think about a link
1667 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1669 This link would show up in your Org-mode document as \"Google Search\",
1670 but really it would remove your entire home directory.
1671 Therefore we advise against setting this variable to nil.
1672 Just change it to `y-or-n-p' if you want to confirm with a
1673 single keystroke rather than having to type \"yes\"."
1674 :group 'org-link-follow
1675 :type '(choice
1676 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1677 (const :tag "with y-or-n (faster)" y-or-n-p)
1678 (const :tag "no confirmation (dangerous)" nil)))
1679 (put 'org-confirm-shell-link-function
1680 'safe-local-variable
1681 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1683 (defcustom org-confirm-elisp-link-not-regexp ""
1684 "A regexp to skip confirmation for Elisp links."
1685 :group 'org-link-follow
1686 :type 'regexp)
1688 (defconst org-file-apps-defaults-gnu
1689 '((remote . emacs)
1690 (system . mailcap)
1691 (t . mailcap))
1692 "Default file applications on a UNIX or GNU/Linux system.
1693 See `org-file-apps'.")
1695 (defconst org-file-apps-defaults-macosx
1696 '((remote . emacs)
1697 (t . "open %s")
1698 (system . "open %s")
1699 ("ps.gz" . "gv %s")
1700 ("eps.gz" . "gv %s")
1701 ("dvi" . "xdvi %s")
1702 ("fig" . "xfig %s"))
1703 "Default file applications on a MacOS X system.
1704 The system \"open\" is known as a default, but we use X11 applications
1705 for some files for which the OS does not have a good default.
1706 See `org-file-apps'.")
1708 (defconst org-file-apps-defaults-windowsnt
1709 (list
1710 '(remote . emacs)
1711 (cons t
1712 (list (if (featurep 'xemacs)
1713 'mswindows-shell-execute
1714 'w32-shell-execute)
1715 "open" 'file))
1716 (cons 'system
1717 (list (if (featurep 'xemacs)
1718 'mswindows-shell-execute
1719 'w32-shell-execute)
1720 "open" 'file)))
1721 "Default file applications on a Windows NT system.
1722 The system \"open\" is used for most files.
1723 See `org-file-apps'.")
1725 (defcustom org-file-apps
1727 (auto-mode . emacs)
1728 ("\\.mm\\'" . default)
1729 ("\\.x?html?\\'" . default)
1730 ("\\.pdf\\'" . default)
1732 "External applications for opening `file:path' items in a document.
1733 Org-mode uses system defaults for different file types, but
1734 you can use this variable to set the application for a given file
1735 extension. The entries in this list are cons cells where the car identifies
1736 files and the cdr the corresponding command. Possible values for the
1737 file identifier are
1738 \"string\" A string as a file identifier can be interpreted in different
1739 ways, depending on its contents:
1741 - Alphanumeric characters only:
1742 Match links with this file extension.
1743 Example: (\"pdf\" . \"evince %s\")
1744 to open PDFs with evince.
1746 - Regular expression: Match links where the
1747 filename matches the regexp. If you want to
1748 use groups here, use shy groups.
1750 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1751 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1752 to open *.html and *.xhtml with firefox.
1754 - Regular expression which contains (non-shy) groups:
1755 Match links where the whole link, including \"::\", and
1756 anything after that, matches the regexp.
1757 In a custom command string, %1, %2, etc. are replaced with
1758 the parts of the link that were matched by the groups.
1759 For backwards compatibility, if a command string is given
1760 that does not use any of the group matches, this case is
1761 handled identically to the second one (i.e. match against
1762 file name only).
1763 In a custom lisp form, you can access the group matches with
1764 (match-string n link).
1766 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1767 to open [[file:document.pdf::5]] with evince at page 5.
1769 `directory' Matches a directory
1770 `remote' Matches a remote file, accessible through tramp or efs.
1771 Remote files most likely should be visited through Emacs
1772 because external applications cannot handle such paths.
1773 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1774 so all files Emacs knows how to handle. Using this with
1775 command `emacs' will open most files in Emacs. Beware that this
1776 will also open html files inside Emacs, unless you add
1777 (\"html\" . default) to the list as well.
1778 t Default for files not matched by any of the other options.
1779 `system' The system command to open files, like `open' on Windows
1780 and Mac OS X, and mailcap under GNU/Linux. This is the command
1781 that will be selected if you call `C-c C-o' with a double
1782 \\[universal-argument] \\[universal-argument] prefix.
1784 Possible values for the command are:
1785 `emacs' The file will be visited by the current Emacs process.
1786 `default' Use the default application for this file type, which is the
1787 association for t in the list, most likely in the system-specific
1788 part.
1789 This can be used to overrule an unwanted setting in the
1790 system-specific variable.
1791 `system' Use the system command for opening files, like \"open\".
1792 This command is specified by the entry whose car is `system'.
1793 Most likely, the system-specific version of this variable
1794 does define this command, but you can overrule/replace it
1795 here.
1796 string A command to be executed by a shell; %s will be replaced
1797 by the path to the file.
1798 sexp A Lisp form which will be evaluated. The file path will
1799 be available in the Lisp variable `file'.
1800 For more examples, see the system specific constants
1801 `org-file-apps-defaults-macosx'
1802 `org-file-apps-defaults-windowsnt'
1803 `org-file-apps-defaults-gnu'."
1804 :group 'org-link-follow
1805 :type '(repeat
1806 (cons (choice :value ""
1807 (string :tag "Extension")
1808 (const :tag "System command to open files" system)
1809 (const :tag "Default for unrecognized files" t)
1810 (const :tag "Remote file" remote)
1811 (const :tag "Links to a directory" directory)
1812 (const :tag "Any files that have Emacs modes"
1813 auto-mode))
1814 (choice :value ""
1815 (const :tag "Visit with Emacs" emacs)
1816 (const :tag "Use default" default)
1817 (const :tag "Use the system command" system)
1818 (string :tag "Command")
1819 (sexp :tag "Lisp form")))))
1823 (defgroup org-refile nil
1824 "Options concerning refiling entries in Org-mode."
1825 :tag "Org Refile"
1826 :group 'org)
1828 (defcustom org-directory "~/org"
1829 "Directory with org files.
1830 This is just a default location to look for Org files. There is no need
1831 at all to put your files into this directory. It is only used in the
1832 following situations:
1834 1. When a remember template specifies a target file that is not an
1835 absolute path. The path will then be interpreted relative to
1836 `org-directory'
1837 2. When a remember note is filed away in an interactive way (when exiting the
1838 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1839 with `org-directory' as the default path."
1840 :group 'org-refile
1841 :group 'org-remember
1842 :type 'directory)
1844 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1845 "Default target for storing notes.
1846 Used as a fall back file for org-remember.el and org-capture.el, for
1847 templates that do not specify a target file."
1848 :group 'org-refile
1849 :group 'org-remember
1850 :type '(choice
1851 (const :tag "Default from remember-data-file" nil)
1852 file))
1854 (defcustom org-goto-interface 'outline
1855 "The default interface to be used for `org-goto'.
1856 Allowed values are:
1857 outline The interface shows an outline of the relevant file
1858 and the correct heading is found by moving through
1859 the outline or by searching with incremental search.
1860 outline-path-completion Headlines in the current buffer are offered via
1861 completion. This is the interface also used by
1862 the refile command."
1863 :group 'org-refile
1864 :type '(choice
1865 (const :tag "Outline" outline)
1866 (const :tag "Outline-path-completion" outline-path-completion)))
1868 (defcustom org-goto-max-level 5
1869 "Maximum target level when running `org-goto' with refile interface."
1870 :group 'org-refile
1871 :type 'integer)
1873 (defcustom org-reverse-note-order nil
1874 "Non-nil means store new notes at the beginning of a file or entry.
1875 When nil, new notes will be filed to the end of a file or entry.
1876 This can also be a list with cons cells of regular expressions that
1877 are matched against file names, and values."
1878 :group 'org-remember
1879 :group 'org-refile
1880 :type '(choice
1881 (const :tag "Reverse always" t)
1882 (const :tag "Reverse never" nil)
1883 (repeat :tag "By file name regexp"
1884 (cons regexp boolean))))
1886 (defcustom org-log-refile nil
1887 "Information to record when a task is refiled.
1889 Possible values are:
1891 nil Don't add anything
1892 time Add a time stamp to the task
1893 note Prompt for a note and add it with template `org-log-note-headings'
1895 This option can also be set with on a per-file-basis with
1897 #+STARTUP: nologrefile
1898 #+STARTUP: logrefile
1899 #+STARTUP: lognoterefile
1901 You can have local logging settings for a subtree by setting the LOGGING
1902 property to one or more of these keywords.
1904 When bulk-refiling from the agenda, the value `note' is forbidden and
1905 will temporarily be changed to `time'."
1906 :group 'org-refile
1907 :group 'org-progress
1908 :type '(choice
1909 (const :tag "No logging" nil)
1910 (const :tag "Record timestamp" time)
1911 (const :tag "Record timestamp with note." note)))
1913 (defcustom org-refile-targets nil
1914 "Targets for refiling entries with \\[org-refile].
1915 This is a list of cons cells. Each cell contains:
1916 - a specification of the files to be considered, either a list of files,
1917 or a symbol whose function or variable value will be used to retrieve
1918 a file name or a list of file names. If you use `org-agenda-files' for
1919 that, all agenda files will be scanned for targets. Nil means consider
1920 headings in the current buffer.
1921 - A specification of how to find candidate refile targets. This may be
1922 any of:
1923 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1924 This tag has to be present in all target headlines, inheritance will
1925 not be considered.
1926 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1927 todo keyword.
1928 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1929 headlines that are refiling targets.
1930 - a cons cell (:level . N). Any headline of level N is considered a target.
1931 Note that, when `org-odd-levels-only' is set, level corresponds to
1932 order in hierarchy, not to the number of stars.
1933 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1934 Note that, when `org-odd-levels-only' is set, level corresponds to
1935 order in hierarchy, not to the number of stars.
1937 Each element of this list generates a set of possible targets.
1938 The union of these sets is presented (with completion) to
1939 the user by `org-refile'.
1941 You can set the variable `org-refile-target-verify-function' to a function
1942 to verify each headline found by the simple criteria above.
1944 When this variable is nil, all top-level headlines in the current buffer
1945 are used, equivalent to the value `((nil . (:level . 1))'."
1946 :group 'org-refile
1947 :type '(repeat
1948 (cons
1949 (choice :value org-agenda-files
1950 (const :tag "All agenda files" org-agenda-files)
1951 (const :tag "Current buffer" nil)
1952 (function) (variable) (file))
1953 (choice :tag "Identify target headline by"
1954 (cons :tag "Specific tag" (const :value :tag) (string))
1955 (cons :tag "TODO keyword" (const :value :todo) (string))
1956 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1957 (cons :tag "Level number" (const :value :level) (integer))
1958 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1960 (defcustom org-refile-target-verify-function nil
1961 "Function to verify if the headline at point should be a refile target.
1962 The function will be called without arguments, with point at the
1963 beginning of the headline. It should return t and leave point
1964 where it is if the headline is a valid target for refiling.
1966 If the target should not be selected, the function must return nil.
1967 In addition to this, it may move point to a place from where the search
1968 should be continued. For example, the function may decide that the entire
1969 subtree of the current entry should be excluded and move point to the end
1970 of the subtree."
1971 :group 'org-refile
1972 :type 'function)
1974 (defcustom org-refile-use-cache nil
1975 "Non-nil means cache refile targets to speed up the process.
1976 The cache for a particular file will be updated automatically when
1977 the buffer has been killed, or when any of the marker used for flagging
1978 refile targets no longer points at a live buffer.
1979 If you have added new entries to a buffer that might themselves be targets,
1980 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
1981 find that easier, `C-u C-u C-u C-c C-w'."
1982 :group 'org-refile
1983 :type 'boolean)
1985 (defcustom org-refile-use-outline-path nil
1986 "Non-nil means provide refile targets as paths.
1987 So a level 3 headline will be available as level1/level2/level3.
1989 When the value is `file', also include the file name (without directory)
1990 into the path. In this case, you can also stop the completion after
1991 the file name, to get entries inserted as top level in the file.
1993 When `full-file-path', include the full file path."
1994 :group 'org-refile
1995 :type '(choice
1996 (const :tag "Not" nil)
1997 (const :tag "Yes" t)
1998 (const :tag "Start with file name" file)
1999 (const :tag "Start with full file path" full-file-path)))
2001 (defcustom org-outline-path-complete-in-steps t
2002 "Non-nil means complete the outline path in hierarchical steps.
2003 When Org-mode uses the refile interface to select an outline path
2004 \(see variable `org-refile-use-outline-path'), the completion of
2005 the path can be done is a single go, or if can be done in steps down
2006 the headline hierarchy. Going in steps is probably the best if you
2007 do not use a special completion package like `ido' or `icicles'.
2008 However, when using these packages, going in one step can be very
2009 fast, while still showing the whole path to the entry."
2010 :group 'org-refile
2011 :type 'boolean)
2013 (defcustom org-refile-allow-creating-parent-nodes nil
2014 "Non-nil means allow to create new nodes as refile targets.
2015 New nodes are then created by adding \"/new node name\" to the completion
2016 of an existing node. When the value of this variable is `confirm',
2017 new node creation must be confirmed by the user (recommended)
2018 When nil, the completion must match an existing entry.
2020 Note that, if the new heading is not seen by the criteria
2021 listed in `org-refile-targets', multiple instances of the same
2022 heading would be created by trying again to file under the new
2023 heading."
2024 :group 'org-refile
2025 :type '(choice
2026 (const :tag "Never" nil)
2027 (const :tag "Always" t)
2028 (const :tag "Prompt for confirmation" confirm)))
2030 (defcustom org-refile-active-region-within-subtree nil
2031 "Non-nil means also refile active region within a subtree.
2033 By default `org-refile' doesn't allow refiling regions if they
2034 don't contain a set of subtrees, but it might be convenient to
2035 do so sometimes: in that case, the first line of the region is
2036 converted to a headline before refiling."
2037 :group 'org-refile
2038 :type 'boolean)
2040 (defgroup org-todo nil
2041 "Options concerning TODO items in Org-mode."
2042 :tag "Org TODO"
2043 :group 'org)
2045 (defgroup org-progress nil
2046 "Options concerning Progress logging in Org-mode."
2047 :tag "Org Progress"
2048 :group 'org-time)
2050 (defvar org-todo-interpretation-widgets
2051 '((:tag "Sequence (cycling hits every state)" sequence)
2052 (:tag "Type (cycling directly to DONE)" type))
2053 "The available interpretation symbols for customizing `org-todo-keywords'.
2054 Interested libraries should add to this list.")
2056 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2057 "List of TODO entry keyword sequences and their interpretation.
2058 \\<org-mode-map>This is a list of sequences.
2060 Each sequence starts with a symbol, either `sequence' or `type',
2061 indicating if the keywords should be interpreted as a sequence of
2062 action steps, or as different types of TODO items. The first
2063 keywords are states requiring action - these states will select a headline
2064 for inclusion into the global TODO list Org-mode produces. If one of
2065 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2066 signify that no further action is necessary. If \"|\" is not found,
2067 the last keyword is treated as the only DONE state of the sequence.
2069 The command \\[org-todo] cycles an entry through these states, and one
2070 additional state where no keyword is present. For details about this
2071 cycling, see the manual.
2073 TODO keywords and interpretation can also be set on a per-file basis with
2074 the special #+SEQ_TODO and #+TYP_TODO lines.
2076 Each keyword can optionally specify a character for fast state selection
2077 \(in combination with the variable `org-use-fast-todo-selection')
2078 and specifiers for state change logging, using the same syntax
2079 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
2080 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2081 indicates to record a time stamp each time this state is selected.
2083 Each keyword may also specify if a timestamp or a note should be
2084 recorded when entering or leaving the state, by adding additional
2085 characters in the parenthesis after the keyword. This looks like this:
2086 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2087 record only the time of the state change. With X and Y being either
2088 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2089 Y when leaving the state if and only if the *target* state does not
2090 define X. You may omit any of the fast-selection key or X or /Y,
2091 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2093 For backward compatibility, this variable may also be just a list
2094 of keywords - in this case the interpretation (sequence or type) will be
2095 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2096 :group 'org-todo
2097 :group 'org-keywords
2098 :type '(choice
2099 (repeat :tag "Old syntax, just keywords"
2100 (string :tag "Keyword"))
2101 (repeat :tag "New syntax"
2102 (cons
2103 (choice
2104 :tag "Interpretation"
2105 ;;Quick and dirty way to see
2106 ;;`org-todo-interpretations'. This takes the
2107 ;;place of item arguments
2108 :convert-widget
2109 (lambda (widget)
2110 (widget-put widget
2111 :args (mapcar
2112 #'(lambda (x)
2113 (widget-convert
2114 (cons 'const x)))
2115 org-todo-interpretation-widgets))
2116 widget))
2117 (repeat
2118 (string :tag "Keyword"))))))
2120 (defvar org-todo-keywords-1 nil
2121 "All TODO and DONE keywords active in a buffer.")
2122 (make-variable-buffer-local 'org-todo-keywords-1)
2123 (defvar org-todo-keywords-for-agenda nil)
2124 (defvar org-done-keywords-for-agenda nil)
2125 (defvar org-drawers-for-agenda nil)
2126 (defvar org-todo-keyword-alist-for-agenda nil)
2127 (defvar org-tag-alist-for-agenda nil)
2128 (defvar org-agenda-contributing-files nil)
2129 (defvar org-not-done-keywords nil)
2130 (make-variable-buffer-local 'org-not-done-keywords)
2131 (defvar org-done-keywords nil)
2132 (make-variable-buffer-local 'org-done-keywords)
2133 (defvar org-todo-heads nil)
2134 (make-variable-buffer-local 'org-todo-heads)
2135 (defvar org-todo-sets nil)
2136 (make-variable-buffer-local 'org-todo-sets)
2137 (defvar org-todo-log-states nil)
2138 (make-variable-buffer-local 'org-todo-log-states)
2139 (defvar org-todo-kwd-alist nil)
2140 (make-variable-buffer-local 'org-todo-kwd-alist)
2141 (defvar org-todo-key-alist nil)
2142 (make-variable-buffer-local 'org-todo-key-alist)
2143 (defvar org-todo-key-trigger nil)
2144 (make-variable-buffer-local 'org-todo-key-trigger)
2146 (defcustom org-todo-interpretation 'sequence
2147 "Controls how TODO keywords are interpreted.
2148 This variable is in principle obsolete and is only used for
2149 backward compatibility, if the interpretation of todo keywords is
2150 not given already in `org-todo-keywords'. See that variable for
2151 more information."
2152 :group 'org-todo
2153 :group 'org-keywords
2154 :type '(choice (const sequence)
2155 (const type)))
2157 (defcustom org-use-fast-todo-selection t
2158 "Non-nil means use the fast todo selection scheme with C-c C-t.
2159 This variable describes if and under what circumstances the cycling
2160 mechanism for TODO keywords will be replaced by a single-key, direct
2161 selection scheme.
2163 When nil, fast selection is never used.
2165 When the symbol `prefix', it will be used when `org-todo' is called with
2166 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
2167 in an agenda buffer.
2169 When t, fast selection is used by default. In this case, the prefix
2170 argument forces cycling instead.
2172 In all cases, the special interface is only used if access keys have actually
2173 been assigned by the user, i.e. if keywords in the configuration are followed
2174 by a letter in parenthesis, like TODO(t)."
2175 :group 'org-todo
2176 :type '(choice
2177 (const :tag "Never" nil)
2178 (const :tag "By default" t)
2179 (const :tag "Only with C-u C-c C-t" prefix)))
2181 (defcustom org-provide-todo-statistics t
2182 "Non-nil means update todo statistics after insert and toggle.
2183 ALL-HEADLINES means update todo statistics by including headlines
2184 with no TODO keyword as well, counting them as not done.
2185 A list of TODO keywords means the same, but skip keywords that are
2186 not in this list.
2188 When this is set, todo statistics is updated in the parent of the
2189 current entry each time a todo state is changed."
2190 :group 'org-todo
2191 :type '(choice
2192 (const :tag "Yes, only for TODO entries" t)
2193 (const :tag "Yes, including all entries" 'all-headlines)
2194 (repeat :tag "Yes, for TODOs in this list"
2195 (string :tag "TODO keyword"))
2196 (other :tag "No TODO statistics" nil)))
2198 (defcustom org-hierarchical-todo-statistics t
2199 "Non-nil means TODO statistics covers just direct children.
2200 When nil, all entries in the subtree are considered.
2201 This has only an effect if `org-provide-todo-statistics' is set.
2202 To set this to nil for only a single subtree, use a COOKIE_DATA
2203 property and include the word \"recursive\" into the value."
2204 :group 'org-todo
2205 :type 'boolean)
2207 (defcustom org-after-todo-state-change-hook nil
2208 "Hook which is run after the state of a TODO item was changed.
2209 The new state (a string with a TODO keyword, or nil) is available in the
2210 Lisp variable `state'."
2211 :group 'org-todo
2212 :type 'hook)
2214 (defvar org-blocker-hook nil
2215 "Hook for functions that are allowed to block a state change.
2217 Each function gets as its single argument a property list, see
2218 `org-trigger-hook' for more information about this list.
2220 If any of the functions in this hook returns nil, the state change
2221 is blocked.")
2223 (defvar org-trigger-hook nil
2224 "Hook for functions that are triggered by a state change.
2226 Each function gets as its single argument a property list with at least
2227 the following elements:
2229 (:type type-of-change :position pos-at-entry-start
2230 :from old-state :to new-state)
2232 Depending on the type, more properties may be present.
2234 This mechanism is currently implemented for:
2236 TODO state changes
2237 ------------------
2238 :type todo-state-change
2239 :from previous state (keyword as a string), or nil, or a symbol
2240 'todo' or 'done', to indicate the general type of state.
2241 :to new state, like in :from")
2243 (defcustom org-enforce-todo-dependencies nil
2244 "Non-nil means undone TODO entries will block switching the parent to DONE.
2245 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2246 be blocked if any prior sibling is not yet done.
2247 Finally, if the parent is blocked because of ordered siblings of its own,
2248 the child will also be blocked.
2249 This variable needs to be set before org.el is loaded, and you need to
2250 restart Emacs after a change to make the change effective. The only way
2251 to change is while Emacs is running is through the customize interface."
2252 :set (lambda (var val)
2253 (set var val)
2254 (if val
2255 (add-hook 'org-blocker-hook
2256 'org-block-todo-from-children-or-siblings-or-parent)
2257 (remove-hook 'org-blocker-hook
2258 'org-block-todo-from-children-or-siblings-or-parent)))
2259 :group 'org-todo
2260 :type 'boolean)
2262 (defcustom org-enforce-todo-checkbox-dependencies nil
2263 "Non-nil means unchecked boxes will block switching the parent to DONE.
2264 When this is nil, checkboxes have no influence on switching TODO states.
2265 When non-nil, you first need to check off all check boxes before the TODO
2266 entry can be switched to DONE.
2267 This variable needs to be set before org.el is loaded, and you need to
2268 restart Emacs after a change to make the change effective. The only way
2269 to change is while Emacs is running is through the customize interface."
2270 :set (lambda (var val)
2271 (set var val)
2272 (if val
2273 (add-hook 'org-blocker-hook
2274 'org-block-todo-from-checkboxes)
2275 (remove-hook 'org-blocker-hook
2276 'org-block-todo-from-checkboxes)))
2277 :group 'org-todo
2278 :type 'boolean)
2280 (defcustom org-treat-insert-todo-heading-as-state-change nil
2281 "Non-nil means inserting a TODO heading is treated as state change.
2282 So when the command \\[org-insert-todo-heading] is used, state change
2283 logging will apply if appropriate. When nil, the new TODO item will
2284 be inserted directly, and no logging will take place."
2285 :group 'org-todo
2286 :type 'boolean)
2288 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2289 "Non-nil means switching TODO states with S-cursor counts as state change.
2290 This is the default behavior. However, setting this to nil allows a
2291 convenient way to select a TODO state and bypass any logging associated
2292 with that."
2293 :group 'org-todo
2294 :type 'boolean)
2296 (defcustom org-todo-state-tags-triggers nil
2297 "Tag changes that should be triggered by TODO state changes.
2298 This is a list. Each entry is
2300 (state-change (tag . flag) .......)
2302 State-change can be a string with a state, and empty string to indicate the
2303 state that has no TODO keyword, or it can be one of the symbols `todo'
2304 or `done', meaning any not-done or done state, respectively."
2305 :group 'org-todo
2306 :group 'org-tags
2307 :type '(repeat
2308 (cons (choice :tag "When changing to"
2309 (const :tag "Not-done state" todo)
2310 (const :tag "Done state" done)
2311 (string :tag "State"))
2312 (repeat
2313 (cons :tag "Tag action"
2314 (string :tag "Tag")
2315 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2317 (defcustom org-log-done nil
2318 "Information to record when a task moves to the DONE state.
2320 Possible values are:
2322 nil Don't add anything, just change the keyword
2323 time Add a time stamp to the task
2324 note Prompt for a note and add it with template `org-log-note-headings'
2326 This option can also be set with on a per-file-basis with
2328 #+STARTUP: nologdone
2329 #+STARTUP: logdone
2330 #+STARTUP: lognotedone
2332 You can have local logging settings for a subtree by setting the LOGGING
2333 property to one or more of these keywords."
2334 :group 'org-todo
2335 :group 'org-progress
2336 :type '(choice
2337 (const :tag "No logging" nil)
2338 (const :tag "Record CLOSED timestamp" time)
2339 (const :tag "Record CLOSED timestamp with note." note)))
2341 ;; Normalize old uses of org-log-done.
2342 (cond
2343 ((eq org-log-done t) (setq org-log-done 'time))
2344 ((and (listp org-log-done) (memq 'done org-log-done))
2345 (setq org-log-done 'note)))
2347 (defcustom org-log-reschedule nil
2348 "Information to record when the scheduling date of a tasks is modified.
2350 Possible values are:
2352 nil Don't add anything, just change the date
2353 time Add a time stamp to the task
2354 note Prompt for a note and add it with template `org-log-note-headings'
2356 This option can also be set with on a per-file-basis with
2358 #+STARTUP: nologreschedule
2359 #+STARTUP: logreschedule
2360 #+STARTUP: lognotereschedule"
2361 :group 'org-todo
2362 :group 'org-progress
2363 :type '(choice
2364 (const :tag "No logging" nil)
2365 (const :tag "Record timestamp" time)
2366 (const :tag "Record timestamp with note." note)))
2368 (defcustom org-log-redeadline nil
2369 "Information to record when the deadline date of a tasks is modified.
2371 Possible values are:
2373 nil Don't add anything, just change the date
2374 time Add a time stamp to the task
2375 note Prompt for a note and add it with template `org-log-note-headings'
2377 This option can also be set with on a per-file-basis with
2379 #+STARTUP: nologredeadline
2380 #+STARTUP: logredeadline
2381 #+STARTUP: lognoteredeadline
2383 You can have local logging settings for a subtree by setting the LOGGING
2384 property to one or more of these keywords."
2385 :group 'org-todo
2386 :group 'org-progress
2387 :type '(choice
2388 (const :tag "No logging" nil)
2389 (const :tag "Record timestamp" time)
2390 (const :tag "Record timestamp with note." note)))
2392 (defcustom org-log-note-clock-out nil
2393 "Non-nil means record a note when clocking out of an item.
2394 This can also be configured on a per-file basis by adding one of
2395 the following lines anywhere in the buffer:
2397 #+STARTUP: lognoteclock-out
2398 #+STARTUP: nolognoteclock-out"
2399 :group 'org-todo
2400 :group 'org-progress
2401 :type 'boolean)
2403 (defcustom org-log-done-with-time t
2404 "Non-nil means the CLOSED time stamp will contain date and time.
2405 When nil, only the date will be recorded."
2406 :group 'org-progress
2407 :type 'boolean)
2409 (defcustom org-log-note-headings
2410 '((done . "CLOSING NOTE %t")
2411 (state . "State %-12s from %-12S %t")
2412 (note . "Note taken on %t")
2413 (reschedule . "Rescheduled from %S on %t")
2414 (delschedule . "Not scheduled, was %S on %t")
2415 (redeadline . "New deadline from %S on %t")
2416 (deldeadline . "Removed deadline, was %S on %t")
2417 (refile . "Refiled on %t")
2418 (clock-out . ""))
2419 "Headings for notes added to entries.
2420 The value is an alist, with the car being a symbol indicating the note
2421 context, and the cdr is the heading to be used. The heading may also be the
2422 empty string.
2423 %t in the heading will be replaced by a time stamp.
2424 %T will be an active time stamp instead the default inactive one
2425 %d will be replaced by a short-format time stamp.
2426 %D will be replaced by an active short-format time stamp.
2427 %s will be replaced by the new TODO state, in double quotes.
2428 %S will be replaced by the old TODO state, in double quotes.
2429 %u will be replaced by the user name.
2430 %U will be replaced by the full user name.
2432 In fact, it is not a good idea to change the `state' entry, because
2433 agenda log mode depends on the format of these entries."
2434 :group 'org-todo
2435 :group 'org-progress
2436 :type '(list :greedy t
2437 (cons (const :tag "Heading when closing an item" done) string)
2438 (cons (const :tag
2439 "Heading when changing todo state (todo sequence only)"
2440 state) string)
2441 (cons (const :tag "Heading when just taking a note" note) string)
2442 (cons (const :tag "Heading when clocking out" clock-out) string)
2443 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2444 (cons (const :tag "Heading when rescheduling" reschedule) string)
2445 (cons (const :tag "Heading when changing deadline" redeadline) string)
2446 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2447 (cons (const :tag "Heading when refiling" refile) string)))
2449 (unless (assq 'note org-log-note-headings)
2450 (push '(note . "%t") org-log-note-headings))
2452 (defcustom org-log-into-drawer nil
2453 "Non-nil means insert state change notes and time stamps into a drawer.
2454 When nil, state changes notes will be inserted after the headline and
2455 any scheduling and clock lines, but not inside a drawer.
2457 The value of this variable should be the name of the drawer to use.
2458 LOGBOOK is proposed as the default drawer for this purpose, you can
2459 also set this to a string to define the drawer of your choice.
2461 A value of t is also allowed, representing \"LOGBOOK\".
2463 If this variable is set, `org-log-state-notes-insert-after-drawers'
2464 will be ignored.
2466 You can set the property LOG_INTO_DRAWER to overrule this setting for
2467 a subtree."
2468 :group 'org-todo
2469 :group 'org-progress
2470 :type '(choice
2471 (const :tag "Not into a drawer" nil)
2472 (const :tag "LOGBOOK" t)
2473 (string :tag "Other")))
2475 (if (fboundp 'defvaralias)
2476 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2478 (defun org-log-into-drawer ()
2479 "Return the value of `org-log-into-drawer', but let properties overrule.
2480 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2481 used instead of the default value."
2482 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2483 (cond
2484 ((or (not p) (equal p "nil")) org-log-into-drawer)
2485 ((equal p "t") "LOGBOOK")
2486 (t p))))
2488 (defcustom org-log-state-notes-insert-after-drawers nil
2489 "Non-nil means insert state change notes after any drawers in entry.
2490 Only the drawers that *immediately* follow the headline and the
2491 deadline/scheduled line are skipped.
2492 When nil, insert notes right after the heading and perhaps the line
2493 with deadline/scheduling if present.
2495 This variable will have no effect if `org-log-into-drawer' is
2496 set."
2497 :group 'org-todo
2498 :group 'org-progress
2499 :type 'boolean)
2501 (defcustom org-log-states-order-reversed t
2502 "Non-nil means the latest state note will be directly after heading.
2503 When nil, the state change notes will be ordered according to time."
2504 :group 'org-todo
2505 :group 'org-progress
2506 :type 'boolean)
2508 (defcustom org-todo-repeat-to-state nil
2509 "The TODO state to which a repeater should return the repeating task.
2510 By default this is the first task in a TODO sequence, or the previous state
2511 in a TODO_TYP set. But you can specify another task here.
2512 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2513 :group 'org-todo
2514 :type '(choice (const :tag "Head of sequence" nil)
2515 (string :tag "Specific state")))
2517 (defcustom org-log-repeat 'time
2518 "Non-nil means record moving through the DONE state when triggering repeat.
2519 An auto-repeating task is immediately switched back to TODO when
2520 marked DONE. If you are not logging state changes (by adding \"@\"
2521 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2522 record a closing note, there will be no record of the task moving
2523 through DONE. This variable forces taking a note anyway.
2525 nil Don't force a record
2526 time Record a time stamp
2527 note Record a note
2529 This option can also be set with on a per-file-basis with
2531 #+STARTUP: logrepeat
2532 #+STARTUP: lognoterepeat
2533 #+STARTUP: nologrepeat
2535 You can have local logging settings for a subtree by setting the LOGGING
2536 property to one or more of these keywords."
2537 :group 'org-todo
2538 :group 'org-progress
2539 :type '(choice
2540 (const :tag "Don't force a record" nil)
2541 (const :tag "Force recording the DONE state" time)
2542 (const :tag "Force recording a note with the DONE state" note)))
2545 (defgroup org-priorities nil
2546 "Priorities in Org-mode."
2547 :tag "Org Priorities"
2548 :group 'org-todo)
2550 (defcustom org-enable-priority-commands t
2551 "Non-nil means priority commands are active.
2552 When nil, these commands will be disabled, so that you never accidentally
2553 set a priority."
2554 :group 'org-priorities
2555 :type 'boolean)
2557 (defcustom org-highest-priority ?A
2558 "The highest priority of TODO items. A character like ?A, ?B etc.
2559 Must have a smaller ASCII number than `org-lowest-priority'."
2560 :group 'org-priorities
2561 :type 'character)
2563 (defcustom org-lowest-priority ?C
2564 "The lowest priority of TODO items. A character like ?A, ?B etc.
2565 Must have a larger ASCII number than `org-highest-priority'."
2566 :group 'org-priorities
2567 :type 'character)
2569 (defcustom org-default-priority ?B
2570 "The default priority of TODO items.
2571 This is the priority an item gets if no explicit priority is given.
2572 When starting to cycle on an empty priority the first step in the cycle
2573 depends on `org-priority-start-cycle-with-default'. The resulting first
2574 step priority must not exceed the range from `org-highest-priority' to
2575 `org-lowest-priority' which means that `org-default-priority' has to be
2576 in this range exclusive or inclusive the range boundaries. Else the
2577 first step refuses to set the default and the second will fall back
2578 to (depending on the command used) the highest or lowest priority."
2579 :group 'org-priorities
2580 :type 'character)
2582 (defcustom org-priority-start-cycle-with-default t
2583 "Non-nil means start with default priority when starting to cycle.
2584 When this is nil, the first step in the cycle will be (depending on the
2585 command used) one higher or lower than the default priority.
2586 See also `org-default-priority'."
2587 :group 'org-priorities
2588 :type 'boolean)
2590 (defcustom org-get-priority-function nil
2591 "Function to extract the priority from a string.
2592 The string is normally the headline. If this is nil Org computes the
2593 priority from the priority cookie like [#A] in the headline. It returns
2594 an integer, increasing by 1000 for each priority level.
2595 The user can set a different function here, which should take a string
2596 as an argument and return the numeric priority."
2597 :group 'org-priorities
2598 :type 'function)
2600 (defgroup org-time nil
2601 "Options concerning time stamps and deadlines in Org-mode."
2602 :tag "Org Time"
2603 :group 'org)
2605 (defcustom org-insert-labeled-timestamps-at-point nil
2606 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2607 When nil, these labeled time stamps are forces into the second line of an
2608 entry, just after the headline. When scheduling from the global TODO list,
2609 the time stamp will always be forced into the second line."
2610 :group 'org-time
2611 :type 'boolean)
2613 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2614 "Formats for `format-time-string' which are used for time stamps.
2615 It is not recommended to change this constant.")
2617 (defcustom org-time-stamp-rounding-minutes '(0 5)
2618 "Number of minutes to round time stamps to.
2619 These are two values, the first applies when first creating a time stamp.
2620 The second applies when changing it with the commands `S-up' and `S-down'.
2621 When changing the time stamp, this means that it will change in steps
2622 of N minutes, as given by the second value.
2624 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2625 numbers should be factors of 60, so for example 5, 10, 15.
2627 When this is larger than 1, you can still force an exact time stamp by using
2628 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2629 and by using a prefix arg to `S-up/down' to specify the exact number
2630 of minutes to shift."
2631 :group 'org-time
2632 :get #'(lambda (var) ; Make sure both elements are there
2633 (if (integerp (default-value var))
2634 (list (default-value var) 5)
2635 (default-value var)))
2636 :type '(list
2637 (integer :tag "when inserting times")
2638 (integer :tag "when modifying times")))
2640 ;; Normalize old customizations of this variable.
2641 (when (integerp org-time-stamp-rounding-minutes)
2642 (setq org-time-stamp-rounding-minutes
2643 (list org-time-stamp-rounding-minutes
2644 org-time-stamp-rounding-minutes)))
2646 (defcustom org-display-custom-times nil
2647 "Non-nil means overlay custom formats over all time stamps.
2648 The formats are defined through the variable `org-time-stamp-custom-formats'.
2649 To turn this on on a per-file basis, insert anywhere in the file:
2650 #+STARTUP: customtime"
2651 :group 'org-time
2652 :set 'set-default
2653 :type 'sexp)
2654 (make-variable-buffer-local 'org-display-custom-times)
2656 (defcustom org-time-stamp-custom-formats
2657 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2658 "Custom formats for time stamps. See `format-time-string' for the syntax.
2659 These are overlaid over the default ISO format if the variable
2660 `org-display-custom-times' is set. Time like %H:%M should be at the
2661 end of the second format. The custom formats are also honored by export
2662 commands, if custom time display is turned on at the time of export."
2663 :group 'org-time
2664 :type 'sexp)
2666 (defun org-time-stamp-format (&optional long inactive)
2667 "Get the right format for a time string."
2668 (let ((f (if long (cdr org-time-stamp-formats)
2669 (car org-time-stamp-formats))))
2670 (if inactive
2671 (concat "[" (substring f 1 -1) "]")
2672 f)))
2674 (defcustom org-time-clocksum-format "%d:%02d"
2675 "The format string used when creating CLOCKSUM lines.
2676 This is also used when org-mode generates a time duration."
2677 :group 'org-time
2678 :type 'string)
2680 (defcustom org-time-clocksum-use-fractional nil
2681 "If non-nil, \\[org-clock-display] uses fractional times.
2682 org-mode generates a time duration."
2683 :group 'org-time
2684 :type 'boolean)
2686 (defcustom org-time-clocksum-fractional-format "%.2f"
2687 "The format string used when creating CLOCKSUM lines, or when
2688 org-mode generates a time duration."
2689 :group 'org-time
2690 :type 'string)
2692 (defcustom org-deadline-warning-days 14
2693 "No. of days before expiration during which a deadline becomes active.
2694 This variable governs the display in sparse trees and in the agenda.
2695 When 0 or negative, it means use this number (the absolute value of it)
2696 even if a deadline has a different individual lead time specified.
2698 Custom commands can set this variable in the options section."
2699 :group 'org-time
2700 :group 'org-agenda-daily/weekly
2701 :type 'integer)
2703 (defcustom org-read-date-prefer-future t
2704 "Non-nil means assume future for incomplete date input from user.
2705 This affects the following situations:
2706 1. The user gives a month but not a year.
2707 For example, if it is April and you enter \"feb 2\", this will be read
2708 as Feb 2, *next* year. \"May 5\", however, will be this year.
2709 2. The user gives a day, but no month.
2710 For example, if today is the 15th, and you enter \"3\", Org-mode will
2711 read this as the third of *next* month. However, if you enter \"17\",
2712 it will be considered as *this* month.
2714 If you set this variable to the symbol `time', then also the following
2715 will work:
2717 3. If the user gives a time, but no day. If the time is before now,
2718 to will be interpreted as tomorrow.
2720 Currently none of this works for ISO week specifications.
2722 When this option is nil, the current day, month and year will always be
2723 used as defaults.
2725 See also `org-agenda-jump-prefer-future'."
2726 :group 'org-time
2727 :type '(choice
2728 (const :tag "Never" nil)
2729 (const :tag "Check month and day" t)
2730 (const :tag "Check month, day, and time" time)))
2732 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2733 "Should the agenda jump command prefer the future for incomplete dates?
2734 The default is to do the same as configured in `org-read-date-prefer-future'.
2735 But you can also set a deviating value here.
2736 This may t or nil, or the symbol `org-read-date-prefer-future'."
2737 :group 'org-agenda
2738 :group 'org-time
2739 :type '(choice
2740 (const :tag "Use org-read-date-prefer-future"
2741 org-read-date-prefer-future)
2742 (const :tag "Never" nil)
2743 (const :tag "Always" t)))
2745 (defcustom org-read-date-force-compatible-dates t
2746 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2748 Depending on the system Emacs is running on, certain dates cannot
2749 be represented with the type used internally to represent time.
2750 Dates between 1970-1-1 and 2038-1-1 can always be represented
2751 correctly. Some systems allow for earlier dates, some for later,
2752 some for both. One way to find out it to insert any date into an
2753 Org buffer, putting the cursor on the year and hitting S-up and
2754 S-down to test the range.
2756 When this variable is set to t, the date/time prompt will not let
2757 you specify dates outside the 1970-2037 range, so it is certain that
2758 these dates will work in whatever version of Emacs you are
2759 running, and also that you can move a file from one Emacs implementation
2760 to another. WHenever Org is forcing the year for you, it will display
2761 a message and beep.
2763 When this variable is nil, Org will check if the date is
2764 representable in the specific Emacs implementation you are using.
2765 If not, it will force a year, usually the current year, and beep
2766 to remind you. Currently this setting is not recommended because
2767 the likelihood that you will open your Org files in an Emacs that
2768 has limited date range is not negligible.
2770 A workaround for this problem is to use diary sexp dates for time
2771 stamps outside of this range."
2772 :group 'org-time
2773 :type 'boolean)
2775 (defcustom org-read-date-display-live t
2776 "Non-nil means display current interpretation of date prompt live.
2777 This display will be in an overlay, in the minibuffer."
2778 :group 'org-time
2779 :type 'boolean)
2781 (defcustom org-read-date-popup-calendar t
2782 "Non-nil means pop up a calendar when prompting for a date.
2783 In the calendar, the date can be selected with mouse-1. However, the
2784 minibuffer will also be active, and you can simply enter the date as well.
2785 When nil, only the minibuffer will be available."
2786 :group 'org-time
2787 :type 'boolean)
2788 (if (fboundp 'defvaralias)
2789 (defvaralias 'org-popup-calendar-for-date-prompt
2790 'org-read-date-popup-calendar))
2792 (defcustom org-read-date-minibuffer-setup-hook nil
2793 "Hook to be used to set up keys for the date/time interface.
2794 Add key definitions to `minibuffer-local-map', which will be a temporary
2795 copy."
2796 :group 'org-time
2797 :type 'hook)
2799 (defcustom org-extend-today-until 0
2800 "The hour when your day really ends. Must be an integer.
2801 This has influence for the following applications:
2802 - When switching the agenda to \"today\". It it is still earlier than
2803 the time given here, the day recognized as TODAY is actually yesterday.
2804 - When a date is read from the user and it is still before the time given
2805 here, the current date and time will be assumed to be yesterday, 23:59.
2806 Also, timestamps inserted in remember templates follow this rule.
2808 IMPORTANT: This is a feature whose implementation is and likely will
2809 remain incomplete. Really, it is only here because past midnight seems to
2810 be the favorite working time of John Wiegley :-)"
2811 :group 'org-time
2812 :type 'integer)
2814 (defcustom org-use-effective-time nil
2815 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2816 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2817 \"effective time\" of any timestamps between midnight and 8am will be
2818 23:59 of the previous day."
2819 :group 'boolean
2820 :type 'integer)
2822 (defcustom org-edit-timestamp-down-means-later nil
2823 "Non-nil means S-down will increase the time in a time stamp.
2824 When nil, S-up will increase."
2825 :group 'org-time
2826 :type 'boolean)
2828 (defcustom org-calendar-follow-timestamp-change t
2829 "Non-nil means make the calendar window follow timestamp changes.
2830 When a timestamp is modified and the calendar window is visible, it will be
2831 moved to the new date."
2832 :group 'org-time
2833 :type 'boolean)
2835 (defgroup org-tags nil
2836 "Options concerning tags in Org-mode."
2837 :tag "Org Tags"
2838 :group 'org)
2840 (defcustom org-tag-alist nil
2841 "List of tags allowed in Org-mode files.
2842 When this list is nil, Org-mode will base TAG input on what is already in the
2843 buffer.
2844 The value of this variable is an alist, the car of each entry must be a
2845 keyword as a string, the cdr may be a character that is used to select
2846 that tag through the fast-tag-selection interface.
2847 See the manual for details."
2848 :group 'org-tags
2849 :type '(repeat
2850 (choice
2851 (cons (string :tag "Tag name")
2852 (character :tag "Access char"))
2853 (list :tag "Start radio group"
2854 (const :startgroup)
2855 (option (string :tag "Group description")))
2856 (list :tag "End radio group"
2857 (const :endgroup)
2858 (option (string :tag "Group description")))
2859 (const :tag "New line" (:newline)))))
2861 (defcustom org-tag-persistent-alist nil
2862 "List of tags that will always appear in all Org-mode files.
2863 This is in addition to any in buffer settings or customizations
2864 of `org-tag-alist'.
2865 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2866 The value of this variable is an alist, the car of each entry must be a
2867 keyword as a string, the cdr may be a character that is used to select
2868 that tag through the fast-tag-selection interface.
2869 See the manual for details.
2870 To disable these tags on a per-file basis, insert anywhere in the file:
2871 #+STARTUP: noptag"
2872 :group 'org-tags
2873 :type '(repeat
2874 (choice
2875 (cons (string :tag "Tag name")
2876 (character :tag "Access char"))
2877 (const :tag "Start radio group" (:startgroup))
2878 (const :tag "End radio group" (:endgroup))
2879 (const :tag "New line" (:newline)))))
2881 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2882 "If non-nil, always offer completion for all tags of all agenda files.
2883 Instead of customizing this variable directly, you might want to
2884 set it locally for capture buffers, because there no list of
2885 tags in that file can be created dynamically (there are none).
2887 (add-hook 'org-capture-mode-hook
2888 (lambda ()
2889 (set (make-local-variable
2890 'org-complete-tags-always-offer-all-agenda-tags)
2891 t)))"
2892 :group 'org-tags
2893 :type 'boolean)
2895 (defvar org-file-tags nil
2896 "List of tags that can be inherited by all entries in the file.
2897 The tags will be inherited if the variable `org-use-tag-inheritance'
2898 says they should be.
2899 This variable is populated from #+FILETAGS lines.")
2901 (defcustom org-use-fast-tag-selection 'auto
2902 "Non-nil means use fast tag selection scheme.
2903 This is a special interface to select and deselect tags with single keys.
2904 When nil, fast selection is never used.
2905 When the symbol `auto', fast selection is used if and only if selection
2906 characters for tags have been configured, either through the variable
2907 `org-tag-alist' or through a #+TAGS line in the buffer.
2908 When t, fast selection is always used and selection keys are assigned
2909 automatically if necessary."
2910 :group 'org-tags
2911 :type '(choice
2912 (const :tag "Always" t)
2913 (const :tag "Never" nil)
2914 (const :tag "When selection characters are configured" 'auto)))
2916 (defcustom org-fast-tag-selection-single-key nil
2917 "Non-nil means fast tag selection exits after first change.
2918 When nil, you have to press RET to exit it.
2919 During fast tag selection, you can toggle this flag with `C-c'.
2920 This variable can also have the value `expert'. In this case, the window
2921 displaying the tags menu is not even shown, until you press C-c again."
2922 :group 'org-tags
2923 :type '(choice
2924 (const :tag "No" nil)
2925 (const :tag "Yes" t)
2926 (const :tag "Expert" expert)))
2928 (defvar org-fast-tag-selection-include-todo nil
2929 "Non-nil means fast tags selection interface will also offer TODO states.
2930 This is an undocumented feature, you should not rely on it.")
2932 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2933 "The column to which tags should be indented in a headline.
2934 If this number is positive, it specifies the column. If it is negative,
2935 it means that the tags should be flushright to that column. For example,
2936 -80 works well for a normal 80 character screen.
2937 When 0, place tags directly after headline text, with only one space in
2938 between."
2939 :group 'org-tags
2940 :type 'integer)
2942 (defcustom org-auto-align-tags t
2943 "Non-nil keeps tags aligned when modifying headlines.
2944 Some operations (i.e. demoting) change the length of a headline and
2945 therefore shift the tags around. With this option turned on, after
2946 each such operation the tags are again aligned to `org-tags-column'."
2947 :group 'org-tags
2948 :type 'boolean)
2950 (defcustom org-use-tag-inheritance t
2951 "Non-nil means tags in levels apply also for sublevels.
2952 When nil, only the tags directly given in a specific line apply there.
2953 This may also be a list of tags that should be inherited, or a regexp that
2954 matches tags that should be inherited. Additional control is possible
2955 with the variable `org-tags-exclude-from-inheritance' which gives an
2956 explicit list of tags to be excluded from inheritance., even if the value of
2957 `org-use-tag-inheritance' would select it for inheritance.
2959 If this option is t, a match early-on in a tree can lead to a large
2960 number of matches in the subtree when constructing the agenda or creating
2961 a sparse tree. If you only want to see the first match in a tree during
2962 a search, check out the variable `org-tags-match-list-sublevels'."
2963 :group 'org-tags
2964 :type '(choice
2965 (const :tag "Not" nil)
2966 (const :tag "Always" t)
2967 (repeat :tag "Specific tags" (string :tag "Tag"))
2968 (regexp :tag "Tags matched by regexp")))
2970 (defcustom org-tags-exclude-from-inheritance nil
2971 "List of tags that should never be inherited.
2972 This is a way to exclude a few tags from inheritance. For way to do
2973 the opposite, to actively allow inheritance for selected tags,
2974 see the variable `org-use-tag-inheritance'."
2975 :group 'org-tags
2976 :type '(repeat (string :tag "Tag")))
2978 (defun org-tag-inherit-p (tag)
2979 "Check if TAG is one that should be inherited."
2980 (cond
2981 ((member tag org-tags-exclude-from-inheritance) nil)
2982 ((eq org-use-tag-inheritance t) t)
2983 ((not org-use-tag-inheritance) nil)
2984 ((stringp org-use-tag-inheritance)
2985 (string-match org-use-tag-inheritance tag))
2986 ((listp org-use-tag-inheritance)
2987 (member tag org-use-tag-inheritance))
2988 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2990 (defcustom org-tags-match-list-sublevels t
2991 "Non-nil means list also sublevels of headlines matching a search.
2992 This variable applies to tags/property searches, and also to stuck
2993 projects because this search is based on a tags match as well.
2995 When set to the symbol `indented', sublevels are indented with
2996 leading dots.
2998 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2999 the sublevels of a headline matching a tag search often also match
3000 the same search. Listing all of them can create very long lists.
3001 Setting this variable to nil causes subtrees of a match to be skipped.
3003 This variable is semi-obsolete and probably should always be true. It
3004 is better to limit inheritance to certain tags using the variables
3005 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3006 :group 'org-tags
3007 :type '(choice
3008 (const :tag "No, don't list them" nil)
3009 (const :tag "Yes, do list them" t)
3010 (const :tag "List them, indented with leading dots" indented)))
3012 (defcustom org-tags-sort-function nil
3013 "When set, tags are sorted using this function as a comparator."
3014 :group 'org-tags
3015 :type '(choice
3016 (const :tag "No sorting" nil)
3017 (const :tag "Alphabetical" string<)
3018 (const :tag "Reverse alphabetical" string>)
3019 (function :tag "Custom function" nil)))
3021 (defvar org-tags-history nil
3022 "History of minibuffer reads for tags.")
3023 (defvar org-last-tags-completion-table nil
3024 "The last used completion table for tags.")
3025 (defvar org-after-tags-change-hook nil
3026 "Hook that is run after the tags in a line have changed.")
3028 (defgroup org-properties nil
3029 "Options concerning properties in Org-mode."
3030 :tag "Org Properties"
3031 :group 'org)
3033 (defcustom org-property-format "%-10s %s"
3034 "How property key/value pairs should be formatted by `indent-line'.
3035 When `indent-line' hits a property definition, it will format the line
3036 according to this format, mainly to make sure that the values are
3037 lined-up with respect to each other."
3038 :group 'org-properties
3039 :type 'string)
3041 (defcustom org-properties-postprocess-alist nil
3042 "Alist of properties and functions to adjust inserted values.
3043 Elements of this alist must be of the form
3045 ([string] [function])
3047 where [string] must be a property name and [function] must be a
3048 lambda expression: this lambda expression must take one argument,
3049 the value to adjust, and return the new value as a string.
3051 For example, this element will allow the property \"Remaining\"
3052 to be updated wrt the relation between the \"Effort\" property
3053 and the clock summary:
3055 ((\"Remaining\" (lambda(value)
3056 (let ((clocksum (org-clock-sum-current-item))
3057 (effort (org-duration-string-to-minutes
3058 (org-entry-get (point) \"Effort\"))))
3059 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3060 :group 'org-properties
3061 :type 'alist)
3063 (defcustom org-use-property-inheritance nil
3064 "Non-nil means properties apply also for sublevels.
3066 This setting is chiefly used during property searches. Turning it on can
3067 cause significant overhead when doing a search, which is why it is not
3068 on by default.
3070 When nil, only the properties directly given in the current entry count.
3071 When t, every property is inherited. The value may also be a list of
3072 properties that should have inheritance, or a regular expression matching
3073 properties that should be inherited.
3075 However, note that some special properties use inheritance under special
3076 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3077 and the properties ending in \"_ALL\" when they are used as descriptor
3078 for valid values of a property.
3080 Note for programmers:
3081 When querying an entry with `org-entry-get', you can control if inheritance
3082 should be used. By default, `org-entry-get' looks only at the local
3083 properties. You can request inheritance by setting the inherit argument
3084 to t (to force inheritance) or to `selective' (to respect the setting
3085 in this variable)."
3086 :group 'org-properties
3087 :type '(choice
3088 (const :tag "Not" nil)
3089 (const :tag "Always" t)
3090 (repeat :tag "Specific properties" (string :tag "Property"))
3091 (regexp :tag "Properties matched by regexp")))
3093 (defun org-property-inherit-p (property)
3094 "Check if PROPERTY is one that should be inherited."
3095 (cond
3096 ((eq org-use-property-inheritance t) t)
3097 ((not org-use-property-inheritance) nil)
3098 ((stringp org-use-property-inheritance)
3099 (string-match org-use-property-inheritance property))
3100 ((listp org-use-property-inheritance)
3101 (member property org-use-property-inheritance))
3102 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3104 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3105 "The default column format, if no other format has been defined.
3106 This variable can be set on the per-file basis by inserting a line
3108 #+COLUMNS: %25ITEM ....."
3109 :group 'org-properties
3110 :type 'string)
3112 (defcustom org-columns-ellipses ".."
3113 "The ellipses to be used when a field in column view is truncated.
3114 When this is the empty string, as many characters as possible are shown,
3115 but then there will be no visual indication that the field has been truncated.
3116 When this is a string of length N, the last N characters of a truncated
3117 field are replaced by this string. If the column is narrower than the
3118 ellipses string, only part of the ellipses string will be shown."
3119 :group 'org-properties
3120 :type 'string)
3122 (defcustom org-columns-modify-value-for-display-function nil
3123 "Function that modifies values for display in column view.
3124 For example, it can be used to cut out a certain part from a time stamp.
3125 The function must take 2 arguments:
3127 column-title The title of the column (*not* the property name)
3128 value The value that should be modified.
3130 The function should return the value that should be displayed,
3131 or nil if the normal value should be used."
3132 :group 'org-properties
3133 :type 'function)
3135 (defcustom org-effort-property "Effort"
3136 "The property that is being used to keep track of effort estimates.
3137 Effort estimates given in this property need to have the format H:MM."
3138 :group 'org-properties
3139 :group 'org-progress
3140 :type '(string :tag "Property"))
3142 (defconst org-global-properties-fixed
3143 '(("VISIBILITY_ALL" . "folded children content all")
3144 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3145 "List of property/value pairs that can be inherited by any entry.
3147 These are fixed values, for the preset properties. The user variable
3148 that can be used to add to this list is `org-global-properties'.
3150 The entries in this list are cons cells where the car is a property
3151 name and cdr is a string with the value. If the value represents
3152 multiple items like an \"_ALL\" property, separate the items by
3153 spaces.")
3155 (defcustom org-global-properties nil
3156 "List of property/value pairs that can be inherited by any entry.
3158 This list will be combined with the constant `org-global-properties-fixed'.
3160 The entries in this list are cons cells where the car is a property
3161 name and cdr is a string with the value.
3163 You can set buffer-local values for the same purpose in the variable
3164 `org-file-properties' this by adding lines like
3166 #+PROPERTY: NAME VALUE"
3167 :group 'org-properties
3168 :type '(repeat
3169 (cons (string :tag "Property")
3170 (string :tag "Value"))))
3172 (defvar org-file-properties nil
3173 "List of property/value pairs that can be inherited by any entry.
3174 Valid for the current buffer.
3175 This variable is populated from #+PROPERTY lines.")
3176 (make-variable-buffer-local 'org-file-properties)
3178 (defgroup org-agenda nil
3179 "Options concerning agenda views in Org-mode."
3180 :tag "Org Agenda"
3181 :group 'org)
3183 (defvar org-category nil
3184 "Variable used by org files to set a category for agenda display.
3185 Such files should use a file variable to set it, for example
3187 # -*- mode: org; org-category: \"ELisp\"
3189 or contain a special line
3191 #+CATEGORY: ELisp
3193 If the file does not specify a category, then file's base name
3194 is used instead.")
3195 (make-variable-buffer-local 'org-category)
3196 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3198 (defcustom org-agenda-files nil
3199 "The files to be used for agenda display.
3200 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3201 \\[org-remove-file]. You can also use customize to edit the list.
3203 If an entry is a directory, all files in that directory that are matched by
3204 `org-agenda-file-regexp' will be part of the file list.
3206 If the value of the variable is not a list but a single file name, then
3207 the list of agenda files is actually stored and maintained in that file, one
3208 agenda file per line. In this file paths can be given relative to
3209 `org-directory'. Tilde expansion and environment variable substitution
3210 are also made."
3211 :group 'org-agenda
3212 :type '(choice
3213 (repeat :tag "List of files and directories" file)
3214 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3216 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3217 "Regular expression to match files for `org-agenda-files'.
3218 If any element in the list in that variable contains a directory instead
3219 of a normal file, all files in that directory that are matched by this
3220 regular expression will be included."
3221 :group 'org-agenda
3222 :type 'regexp)
3224 (defcustom org-agenda-text-search-extra-files nil
3225 "List of extra files to be searched by text search commands.
3226 These files will be search in addition to the agenda files by the
3227 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3228 Note that these files will only be searched for text search commands,
3229 not for the other agenda views like todo lists, tag searches or the weekly
3230 agenda. This variable is intended to list notes and possibly archive files
3231 that should also be searched by these two commands.
3232 In fact, if the first element in the list is the symbol `agenda-archives',
3233 than all archive files of all agenda files will be added to the search
3234 scope."
3235 :group 'org-agenda
3236 :type '(set :greedy t
3237 (const :tag "Agenda Archives" agenda-archives)
3238 (repeat :inline t (file))))
3240 (if (fboundp 'defvaralias)
3241 (defvaralias 'org-agenda-multi-occur-extra-files
3242 'org-agenda-text-search-extra-files))
3244 (defcustom org-agenda-skip-unavailable-files nil
3245 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3246 A nil value means to remove them, after a query, from the list."
3247 :group 'org-agenda
3248 :type 'boolean)
3250 (defcustom org-calendar-to-agenda-key [?c]
3251 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3252 The command `org-calendar-goto-agenda' will be bound to this key. The
3253 default is the character `c' because then `c' can be used to switch back and
3254 forth between agenda and calendar."
3255 :group 'org-agenda
3256 :type 'sexp)
3258 (defcustom org-calendar-agenda-action-key [?k]
3259 "The key to be installed in `calendar-mode-map' for agenda-action.
3260 The command `org-agenda-action' will be bound to this key. The
3261 default is the character `k' because we use the same key in the agenda."
3262 :group 'org-agenda
3263 :type 'sexp)
3265 (defcustom org-calendar-insert-diary-entry-key [?i]
3266 "The key to be installed in `calendar-mode-map' for adding diary entries.
3267 This option is irrelevant until `org-agenda-diary-file' has been configured
3268 to point to an Org-mode file. When that is the case, the command
3269 `org-agenda-diary-entry' will be bound to the key given here, by default
3270 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3271 if you want to continue doing this, you need to change this to a different
3272 key."
3273 :group 'org-agenda
3274 :type 'sexp)
3276 (defcustom org-agenda-diary-file 'diary-file
3277 "File to which to add new entries with the `i' key in agenda and calendar.
3278 When this is the symbol `diary-file', the functionality in the Emacs
3279 calendar will be used to add entries to the `diary-file'. But when this
3280 points to a file, `org-agenda-diary-entry' will be used instead."
3281 :group 'org-agenda
3282 :type '(choice
3283 (const :tag "The standard Emacs diary file" diary-file)
3284 (file :tag "Special Org file diary entries")))
3286 (eval-after-load "calendar"
3287 '(progn
3288 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3289 'org-calendar-goto-agenda)
3290 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3291 'org-agenda-action)
3292 (add-hook 'calendar-mode-hook
3293 (lambda ()
3294 (unless (eq org-agenda-diary-file 'diary-file)
3295 (define-key calendar-mode-map
3296 org-calendar-insert-diary-entry-key
3297 'org-agenda-diary-entry))))))
3299 (defgroup org-latex nil
3300 "Options for embedding LaTeX code into Org-mode."
3301 :tag "Org LaTeX"
3302 :group 'org)
3304 (defcustom org-format-latex-options
3305 '(:foreground default :background default :scale 1.0
3306 :html-foreground "Black" :html-background "Transparent"
3307 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3308 "Options for creating images from LaTeX fragments.
3309 This is a property list with the following properties:
3310 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3311 `default' means use the foreground of the default face.
3312 :background the background color, or \"Transparent\".
3313 `default' means use the background of the default face.
3314 :scale a scaling factor for the size of the images, to get more pixels
3315 :html-foreground, :html-background, :html-scale
3316 the same numbers for HTML export.
3317 :matchers a list indicating which matchers should be used to
3318 find LaTeX fragments. Valid members of this list are:
3319 \"begin\" find environments
3320 \"$1\" find single characters surrounded by $.$
3321 \"$\" find math expressions surrounded by $...$
3322 \"$$\" find math expressions surrounded by $$....$$
3323 \"\\(\" find math expressions surrounded by \\(...\\)
3324 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3325 :group 'org-latex
3326 :type 'plist)
3328 (defcustom org-format-latex-signal-error t
3329 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3330 When nil, just push out a message."
3331 :group 'org-latex
3332 :type 'boolean)
3333 (defcustom org-latex-to-mathml-jar-file nil
3334 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3335 Use this to specify additional executable file say a jar file.
3337 When using MathToWeb as the converter, specify the full-path to
3338 your mathtoweb.jar file."
3339 :group 'org-latex
3340 :type '(choice
3341 (const :tag "None" nil)
3342 (file :tag "JAR file" :must-match t)))
3344 (defcustom org-latex-to-mathml-convert-command nil
3345 "Command to convert LaTeX fragments to MathML.
3346 Replace format-specifiers in the command as noted below and use
3347 `shell-command' to convert LaTeX to MathML.
3348 %j: Executable file in fully expanded form as specified by
3349 `org-latex-to-mathml-jar-file'.
3350 %I: Input LaTeX file in fully expanded form
3351 %o: Output MathML file
3352 This command is used by `org-create-math-formula'.
3354 When using MathToWeb as the converter, set this to
3355 \"java -jar %j -unicode -force -df %o %I\"."
3356 :group 'org-latex
3357 :type '(choice
3358 (const :tag "None" nil)
3359 (string :tag "\nShell command")))
3361 (defun org-format-latex-mathml-available-p ()
3362 "Return t if `org-latex-to-mathml-convert-command' is usable."
3363 (save-match-data
3364 (when (and (boundp 'org-latex-to-mathml-convert-command)
3365 org-latex-to-mathml-convert-command)
3366 (let ((executable (car (split-string
3367 org-latex-to-mathml-convert-command))))
3368 (when (executable-find executable)
3369 (if (string-match
3370 "%j" org-latex-to-mathml-convert-command)
3371 (file-readable-p org-latex-to-mathml-jar-file)
3372 t))))))
3374 (defcustom org-format-latex-header "\\documentclass{article}
3375 \\usepackage[usenames]{color}
3376 \\usepackage{amsmath}
3377 \\usepackage[mathscr]{eucal}
3378 \\pagestyle{empty} % do not remove
3379 \[PACKAGES]
3380 \[DEFAULT-PACKAGES]
3381 % The settings below are copied from fullpage.sty
3382 \\setlength{\\textwidth}{\\paperwidth}
3383 \\addtolength{\\textwidth}{-3cm}
3384 \\setlength{\\oddsidemargin}{1.5cm}
3385 \\addtolength{\\oddsidemargin}{-2.54cm}
3386 \\setlength{\\evensidemargin}{\\oddsidemargin}
3387 \\setlength{\\textheight}{\\paperheight}
3388 \\addtolength{\\textheight}{-\\headheight}
3389 \\addtolength{\\textheight}{-\\headsep}
3390 \\addtolength{\\textheight}{-\\footskip}
3391 \\addtolength{\\textheight}{-3cm}
3392 \\setlength{\\topmargin}{1.5cm}
3393 \\addtolength{\\topmargin}{-2.54cm}"
3394 "The document header used for processing LaTeX fragments.
3395 It is imperative that this header make sure that no page number
3396 appears on the page. The package defined in the variables
3397 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3398 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3399 will be appended."
3400 :group 'org-latex
3401 :type 'string)
3403 (defvar org-format-latex-header-extra nil)
3405 (defun org-set-packages-alist (var val)
3406 "Set the packages alist and make sure it has 3 elements per entry."
3407 (set var (mapcar (lambda (x)
3408 (if (and (consp x) (= (length x) 2))
3409 (list (car x) (nth 1 x) t)
3411 val)))
3413 (defun org-get-packages-alist (var)
3415 "Get the packages alist and make sure it has 3 elements per entry."
3416 (mapcar (lambda (x)
3417 (if (and (consp x) (= (length x) 2))
3418 (list (car x) (nth 1 x) t)
3420 (default-value var)))
3422 ;; The following variables are defined here because is it also used
3423 ;; when formatting latex fragments. Originally it was part of the
3424 ;; LaTeX exporter, which is why the name includes "export".
3425 (defcustom org-export-latex-default-packages-alist
3426 '(("AUTO" "inputenc" t)
3427 ("T1" "fontenc" t)
3428 ("" "fixltx2e" nil)
3429 ("" "graphicx" t)
3430 ("" "longtable" nil)
3431 ("" "float" nil)
3432 ("" "wrapfig" nil)
3433 ("" "soul" t)
3434 ("" "textcomp" t)
3435 ("" "marvosym" t)
3436 ("" "wasysym" t)
3437 ("" "latexsym" t)
3438 ("" "amssymb" t)
3439 ("" "hyperref" nil)
3440 "\\tolerance=1000"
3442 "Alist of default packages to be inserted in the header.
3443 Change this only if one of the packages here causes an incompatibility
3444 with another package you are using.
3445 The packages in this list are needed by one part or another of Org-mode
3446 to function properly.
3448 - inputenc, fontenc: for basic font and character selection
3449 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3450 for interpreting the entities in `org-entities'. You can skip some of these
3451 packages if you don't use any of the symbols in it.
3452 - graphicx: for including images
3453 - float, wrapfig: for figure placement
3454 - longtable: for long tables
3455 - hyperref: for cross references
3457 Therefore you should not modify this variable unless you know what you
3458 are doing. The one reason to change it anyway is that you might be loading
3459 some other package that conflicts with one of the default packages.
3460 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3461 If SNIPPET-FLAG is t, the package also needs to be included when
3462 compiling LaTeX snippets into images for inclusion into HTML."
3463 :group 'org-export-latex
3464 :set 'org-set-packages-alist
3465 :get 'org-get-packages-alist
3466 :type '(repeat
3467 (choice
3468 (list :tag "options/package pair"
3469 (string :tag "options")
3470 (string :tag "package")
3471 (boolean :tag "Snippet"))
3472 (string :tag "A line of LaTeX"))))
3474 (defcustom org-export-latex-packages-alist nil
3475 "Alist of packages to be inserted in every LaTeX header.
3476 These will be inserted after `org-export-latex-default-packages-alist'.
3477 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3478 SNIPPET-FLAG, when t, indicates that this package is also needed when
3479 turning LaTeX snippets into images for inclusion into HTML.
3480 Make sure that you only list packages here which:
3481 - you want in every file
3482 - do not conflict with the default packages in
3483 `org-export-latex-default-packages-alist'
3484 - do not conflict with the setup in `org-format-latex-header'."
3485 :group 'org-export-latex
3486 :set 'org-set-packages-alist
3487 :get 'org-get-packages-alist
3488 :type '(repeat
3489 (choice
3490 (list :tag "options/package pair"
3491 (string :tag "options")
3492 (string :tag "package")
3493 (boolean :tag "Snippet"))
3494 (string :tag "A line of LaTeX"))))
3497 (defgroup org-appearance nil
3498 "Settings for Org-mode appearance."
3499 :tag "Org Appearance"
3500 :group 'org)
3502 (defcustom org-level-color-stars-only nil
3503 "Non-nil means fontify only the stars in each headline.
3504 When nil, the entire headline is fontified.
3505 Changing it requires restart of `font-lock-mode' to become effective
3506 also in regions already fontified."
3507 :group 'org-appearance
3508 :type 'boolean)
3510 (defcustom org-hide-leading-stars nil
3511 "Non-nil means hide the first N-1 stars in a headline.
3512 This works by using the face `org-hide' for these stars. This
3513 face is white for a light background, and black for a dark
3514 background. You may have to customize the face `org-hide' to
3515 make this work.
3516 Changing it requires restart of `font-lock-mode' to become effective
3517 also in regions already fontified.
3518 You may also set this on a per-file basis by adding one of the following
3519 lines to the buffer:
3521 #+STARTUP: hidestars
3522 #+STARTUP: showstars"
3523 :group 'org-appearance
3524 :type 'boolean)
3526 (defcustom org-hidden-keywords nil
3527 "List of symbols corresponding to keywords to be hidden the org buffer.
3528 For example, a value '(title) for this list will make the document's title
3529 appear in the buffer without the initial #+TITLE: keyword."
3530 :group 'org-appearance
3531 :type '(set (const :tag "#+AUTHOR" author)
3532 (const :tag "#+DATE" date)
3533 (const :tag "#+EMAIL" email)
3534 (const :tag "#+TITLE" title)))
3536 (defcustom org-fontify-done-headline nil
3537 "Non-nil means change the face of a headline if it is marked DONE.
3538 Normally, only the TODO/DONE keyword indicates the state of a headline.
3539 When this is non-nil, the headline after the keyword is set to the
3540 `org-headline-done' as an additional indication."
3541 :group 'org-appearance
3542 :type 'boolean)
3544 (defcustom org-fontify-emphasized-text t
3545 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3546 Changing this variable requires a restart of Emacs to take effect."
3547 :group 'org-appearance
3548 :type 'boolean)
3550 (defcustom org-fontify-whole-heading-line nil
3551 "Non-nil means fontify the whole line for headings.
3552 This is useful when setting a background color for the
3553 org-level-* faces."
3554 :group 'org-appearance
3555 :type 'boolean)
3557 (defcustom org-highlight-latex-fragments-and-specials nil
3558 "Non-nil means fontify what is treated specially by the exporters."
3559 :group 'org-appearance
3560 :type 'boolean)
3562 (defcustom org-hide-emphasis-markers nil
3563 "Non-nil mean font-lock should hide the emphasis marker characters."
3564 :group 'org-appearance
3565 :type 'boolean)
3567 (defcustom org-pretty-entities nil
3568 "Non-nil means show entities as UTF8 characters.
3569 When nil, the \\name form remains in the buffer."
3570 :group 'org-appearance
3571 :type 'boolean)
3573 (defcustom org-pretty-entities-include-sub-superscripts t
3574 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3575 :group 'org-appearance
3576 :type 'boolean)
3578 (defvar org-emph-re nil
3579 "Regular expression for matching emphasis.
3580 After a match, the match groups contain these elements:
3581 0 The match of the full regular expression, including the characters
3582 before and after the proper match
3583 1 The character before the proper match, or empty at beginning of line
3584 2 The proper match, including the leading and trailing markers
3585 3 The leading marker like * or /, indicating the type of highlighting
3586 4 The text between the emphasis markers, not including the markers
3587 5 The character after the match, empty at the end of a line")
3588 (defvar org-verbatim-re nil
3589 "Regular expression for matching verbatim text.")
3590 (defvar org-emphasis-regexp-components) ; defined just below
3591 (defvar org-emphasis-alist) ; defined just below
3592 (defun org-set-emph-re (var val)
3593 "Set variable and compute the emphasis regular expression."
3594 (set var val)
3595 (when (and (boundp 'org-emphasis-alist)
3596 (boundp 'org-emphasis-regexp-components)
3597 org-emphasis-alist org-emphasis-regexp-components)
3598 (let* ((e org-emphasis-regexp-components)
3599 (pre (car e))
3600 (post (nth 1 e))
3601 (border (nth 2 e))
3602 (body (nth 3 e))
3603 (nl (nth 4 e))
3604 (body1 (concat body "*?"))
3605 (markers (mapconcat 'car org-emphasis-alist ""))
3606 (vmarkers (mapconcat
3607 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3608 org-emphasis-alist "")))
3609 ;; make sure special characters appear at the right position in the class
3610 (if (string-match "\\^" markers)
3611 (setq markers (concat (replace-match "" t t markers) "^")))
3612 (if (string-match "-" markers)
3613 (setq markers (concat (replace-match "" t t markers) "-")))
3614 (if (string-match "\\^" vmarkers)
3615 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3616 (if (string-match "-" vmarkers)
3617 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3618 (if (> nl 0)
3619 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3620 (int-to-string nl) "\\}")))
3621 ;; Make the regexp
3622 (setq org-emph-re
3623 (concat "\\([" pre "]\\|^\\)"
3624 "\\("
3625 "\\([" markers "]\\)"
3626 "\\("
3627 "[^" border "]\\|"
3628 "[^" border "]"
3629 body1
3630 "[^" border "]"
3631 "\\)"
3632 "\\3\\)"
3633 "\\([" post "]\\|$\\)"))
3634 (setq org-verbatim-re
3635 (concat "\\([" pre "]\\|^\\)"
3636 "\\("
3637 "\\([" vmarkers "]\\)"
3638 "\\("
3639 "[^" border "]\\|"
3640 "[^" border "]"
3641 body1
3642 "[^" border "]"
3643 "\\)"
3644 "\\3\\)"
3645 "\\([" post "]\\|$\\)")))))
3647 (defcustom org-emphasis-regexp-components
3648 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3649 "Components used to build the regular expression for emphasis.
3650 This is a list with five entries. Terminology: In an emphasis string
3651 like \" *strong word* \", we call the initial space PREMATCH, the final
3652 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3653 and \"trong wor\" is the body. The different components in this variable
3654 specify what is allowed/forbidden in each part:
3656 pre Chars allowed as prematch. Beginning of line will be allowed too.
3657 post Chars allowed as postmatch. End of line will be allowed too.
3658 border The chars *forbidden* as border characters.
3659 body-regexp A regexp like \".\" to match a body character. Don't use
3660 non-shy groups here, and don't allow newline here.
3661 newline The maximum number of newlines allowed in an emphasis exp.
3663 Use customize to modify this, or restart Emacs after changing it."
3664 :group 'org-appearance
3665 :set 'org-set-emph-re
3666 :type '(list
3667 (sexp :tag "Allowed chars in pre ")
3668 (sexp :tag "Allowed chars in post ")
3669 (sexp :tag "Forbidden chars in border ")
3670 (sexp :tag "Regexp for body ")
3671 (integer :tag "number of newlines allowed")
3672 (option (boolean :tag "Please ignore this button"))))
3674 (defcustom org-emphasis-alist
3675 `(("*" bold "<b>" "</b>")
3676 ("/" italic "<i>" "</i>")
3677 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3678 ("=" org-code "<code>" "</code>" verbatim)
3679 ("~" org-verbatim "<code>" "</code>" verbatim)
3680 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3681 "<del>" "</del>")
3683 "Special syntax for emphasized text.
3684 Text starting and ending with a special character will be emphasized, for
3685 example *bold*, _underlined_ and /italic/. This variable sets the marker
3686 characters, the face to be used by font-lock for highlighting in Org-mode
3687 Emacs buffers, and the HTML tags to be used for this.
3688 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3689 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3690 Use customize to modify this, or restart Emacs after changing it."
3691 :group 'org-appearance
3692 :set 'org-set-emph-re
3693 :type '(repeat
3694 (list
3695 (string :tag "Marker character")
3696 (choice
3697 (face :tag "Font-lock-face")
3698 (plist :tag "Face property list"))
3699 (string :tag "HTML start tag")
3700 (string :tag "HTML end tag")
3701 (option (const verbatim)))))
3703 (defvar org-protecting-blocks
3704 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3705 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3706 This is needed for font-lock setup.")
3708 ;;; Miscellaneous options
3710 (defgroup org-completion nil
3711 "Completion in Org-mode."
3712 :tag "Org Completion"
3713 :group 'org)
3715 (defcustom org-completion-use-ido nil
3716 "Non-nil means use ido completion wherever possible.
3717 Note that `ido-mode' must be active for this variable to be relevant.
3718 If you decide to turn this variable on, you might well want to turn off
3719 `org-outline-path-complete-in-steps'.
3720 See also `org-completion-use-iswitchb'."
3721 :group 'org-completion
3722 :type 'boolean)
3724 (defcustom org-completion-use-iswitchb nil
3725 "Non-nil means use iswitchb completion wherever possible.
3726 Note that `iswitchb-mode' must be active for this variable to be relevant.
3727 If you decide to turn this variable on, you might well want to turn off
3728 `org-outline-path-complete-in-steps'.
3729 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3730 :group 'org-completion
3731 :type 'boolean)
3733 (defcustom org-completion-fallback-command 'hippie-expand
3734 "The expansion command called by \\[pcomplete] in normal context.
3735 Normal means, no org-mode-specific context."
3736 :group 'org-completion
3737 :type 'function)
3739 ;;; Functions and variables from their packages
3740 ;; Declared here to avoid compiler warnings
3742 ;; XEmacs only
3743 (defvar outline-mode-menu-heading)
3744 (defvar outline-mode-menu-show)
3745 (defvar outline-mode-menu-hide)
3746 (defvar zmacs-regions) ; XEmacs regions
3748 ;; Emacs only
3749 (defvar mark-active)
3751 ;; Various packages
3752 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3753 (declare-function calendar-forward-day "cal-move" (arg))
3754 (declare-function calendar-goto-date "cal-move" (date))
3755 (declare-function calendar-goto-today "cal-move" ())
3756 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3757 (defvar calc-embedded-close-formula)
3758 (defvar calc-embedded-open-formula)
3759 (declare-function cdlatex-tab "ext:cdlatex" ())
3760 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3761 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3762 (defvar font-lock-unfontify-region-function)
3763 (declare-function iswitchb-read-buffer "iswitchb"
3764 (prompt &optional default require-match start matches-set))
3765 (defvar iswitchb-temp-buflist)
3766 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3767 (defvar org-agenda-tags-todo-honor-ignore-options)
3768 (declare-function org-agenda-skip "org-agenda" ())
3769 (declare-function
3770 org-agenda-format-item "org-agenda"
3771 (extra txt &optional category tags dotime noprefix remove-re habitp))
3772 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3773 (declare-function org-agenda-change-all-lines "org-agenda"
3774 (newhead hdmarker &optional fixface just-this))
3775 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3776 (declare-function org-agenda-maybe-redo "org-agenda" ())
3777 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3778 (beg end))
3779 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3780 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3781 "org-agenda" (&optional end))
3782 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3783 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3784 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3785 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3786 (declare-function org-indent-mode "org-indent" (&optional arg))
3787 (declare-function parse-time-string "parse-time" (string))
3788 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3789 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3790 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3791 (defvar remember-data-file)
3792 (defvar texmathp-why)
3793 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3794 (declare-function table--at-cell-p "table" (position &optional object at-column))
3796 (defvar w3m-current-url)
3797 (defvar w3m-current-title)
3799 (defvar org-latex-regexps)
3801 ;;; Autoload and prepare some org modules
3803 ;; Some table stuff that needs to be defined here, because it is used
3804 ;; by the functions setting up org-mode or checking for table context.
3806 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3807 "Detect an org-type or table-type table.")
3808 (defconst org-table-line-regexp "^[ \t]*|"
3809 "Detect an org-type table line.")
3810 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3811 "Detect an org-type table line.")
3812 (defconst org-table-hline-regexp "^[ \t]*|-"
3813 "Detect an org-type table hline.")
3814 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3815 "Detect a table-type table hline.")
3816 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3817 "Detect the first line outside a table when searching from within it.
3818 This works for both table types.")
3820 ;; Autoload the functions in org-table.el that are needed by functions here.
3822 (eval-and-compile
3823 (org-autoload "org-table"
3824 '(org-table-align org-table-begin org-table-blank-field
3825 org-table-convert org-table-convert-region org-table-copy-down
3826 org-table-copy-region org-table-create
3827 org-table-create-or-convert-from-region
3828 org-table-create-with-table.el org-table-current-dline
3829 org-table-cut-region org-table-delete-column org-table-edit-field
3830 org-table-edit-formulas org-table-end org-table-eval-formula
3831 org-table-export org-table-field-info
3832 org-table-get-stored-formulas org-table-goto-column
3833 org-table-hline-and-move org-table-import org-table-insert-column
3834 org-table-insert-hline org-table-insert-row org-table-iterate
3835 org-table-justify-field-maybe org-table-kill-row
3836 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3837 org-table-move-column org-table-move-column-left
3838 org-table-move-column-right org-table-move-row
3839 org-table-move-row-down org-table-move-row-up
3840 org-table-next-field org-table-next-row org-table-paste-rectangle
3841 org-table-previous-field org-table-recalculate
3842 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3843 org-table-toggle-coordinate-overlays
3844 org-table-toggle-formula-debugger org-table-wrap-region
3845 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3846 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3847 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3849 (defun org-at-table-p (&optional table-type)
3850 "Return t if the cursor is inside an org-type table.
3851 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3852 (if org-enable-table-editor
3853 (save-excursion
3854 (beginning-of-line 1)
3855 (looking-at (if table-type org-table-any-line-regexp
3856 org-table-line-regexp)))
3857 nil))
3858 (defsubst org-table-p () (org-at-table-p))
3860 (defun org-at-table.el-p ()
3861 "Return t if and only if we are at a table.el table."
3862 (and (org-at-table-p 'any)
3863 (save-excursion
3864 (goto-char (org-table-begin 'any))
3865 (looking-at org-table1-hline-regexp))))
3866 (defun org-table-recognize-table.el ()
3867 "If there is a table.el table nearby, recognize it and move into it."
3868 (if org-table-tab-recognizes-table.el
3869 (if (org-at-table.el-p)
3870 (progn
3871 (beginning-of-line 1)
3872 (if (looking-at org-table-dataline-regexp)
3874 (if (looking-at org-table1-hline-regexp)
3875 (progn
3876 (beginning-of-line 2)
3877 (if (looking-at org-table-any-border-regexp)
3878 (beginning-of-line -1)))))
3879 (if (re-search-forward "|" (org-table-end t) t)
3880 (progn
3881 (require 'table)
3882 (if (table--at-cell-p (point))
3884 (message "recognizing table.el table...")
3885 (table-recognize-table)
3886 (message "recognizing table.el table...done")))
3887 (error "This should not happen"))
3889 nil)
3890 nil))
3892 (defun org-at-table-hline-p ()
3893 "Return t if the cursor is inside a hline in a table."
3894 (if org-enable-table-editor
3895 (save-excursion
3896 (beginning-of-line 1)
3897 (looking-at org-table-hline-regexp))
3898 nil))
3900 (defvar org-table-clean-did-remove-column nil)
3902 (defun org-table-map-tables (function &optional quietly)
3903 "Apply FUNCTION to the start of all tables in the buffer."
3904 (save-excursion
3905 (save-restriction
3906 (widen)
3907 (goto-char (point-min))
3908 (while (re-search-forward org-table-any-line-regexp nil t)
3909 (unless quietly
3910 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3911 (beginning-of-line 1)
3912 (when (looking-at org-table-line-regexp)
3913 (save-excursion (funcall function))
3914 (or (looking-at org-table-line-regexp)
3915 (forward-char 1)))
3916 (re-search-forward org-table-any-border-regexp nil 1))))
3917 (unless quietly (message "Mapping tables: done")))
3919 ;; Declare and autoload functions from org-exp.el & Co
3921 (declare-function org-default-export-plist "org-exp")
3922 (declare-function org-infile-export-plist "org-exp")
3923 (declare-function org-get-current-options "org-exp")
3924 (eval-and-compile
3925 (org-autoload "org-exp"
3926 '(org-export org-export-visible
3927 org-insert-export-options-template
3928 org-table-clean-before-export))
3929 (org-autoload "org-ascii"
3930 '(org-export-as-ascii org-export-ascii-preprocess
3931 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3932 org-export-region-as-ascii))
3933 (org-autoload "org-latex"
3934 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3935 org-replace-region-by-latex org-export-region-as-latex
3936 org-export-as-latex org-export-as-pdf
3937 org-export-as-pdf-and-open))
3938 (org-autoload "org-html"
3939 '(org-export-as-html-and-open
3940 org-export-as-html-batch org-export-as-html-to-buffer
3941 org-replace-region-by-html org-export-region-as-html
3942 org-export-as-html))
3943 (org-autoload "org-docbook"
3944 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3945 org-replace-region-by-docbook org-export-region-as-docbook
3946 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3947 org-export-as-docbook))
3948 (org-autoload "org-icalendar"
3949 '(org-export-icalendar-this-file
3950 org-export-icalendar-all-agenda-files
3951 org-export-icalendar-combine-agenda-files))
3952 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3953 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3955 ;; Declare and autoload functions from org-agenda.el
3957 (eval-and-compile
3958 (org-autoload "org-agenda"
3959 '(org-agenda org-agenda-list org-search-view
3960 org-todo-list org-tags-view org-agenda-list-stuck-projects
3961 org-diary org-agenda-to-appt
3962 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3964 ;; Autoload org-remember
3966 (eval-and-compile
3967 (org-autoload "org-remember"
3968 '(org-remember-insinuate org-remember-annotation
3969 org-remember-apply-template org-remember org-remember-handler)))
3971 (eval-and-compile
3972 (org-autoload "org-capture"
3973 '(org-capture org-capture-insert-template-here
3974 org-capture-import-remember-templates)))
3976 ;; Autoload org-clock.el
3978 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3979 (beg end))
3980 (declare-function org-clock-update-mode-line "org-clock" ())
3981 (declare-function org-resolve-clocks "org-clock"
3982 (&optional also-non-dangling-p prompt last-valid))
3983 (defvar org-clock-start-time)
3984 (defvar org-clock-marker (make-marker)
3985 "Marker recording the last clock-in.")
3986 (defvar org-clock-hd-marker (make-marker)
3987 "Marker recording the last clock-in, but the headline position.")
3988 (defvar org-clock-heading ""
3989 "The heading of the current clock entry.")
3990 (defun org-clock-is-active ()
3991 "Return non-nil if clock is currently running.
3992 The return value is actually the clock marker."
3993 (marker-buffer org-clock-marker))
3995 (eval-and-compile
3996 (org-autoload
3997 "org-clock"
3998 '(org-clock-in org-clock-out org-clock-cancel
3999 org-clock-goto org-clock-sum org-clock-display
4000 org-clock-remove-overlays org-clock-report
4001 org-clocktable-shift org-dblock-write:clocktable
4002 org-get-clocktable org-resolve-clocks)))
4004 (defun org-clock-update-time-maybe ()
4005 "If this is a CLOCK line, update it and return t.
4006 Otherwise, return nil."
4007 (interactive)
4008 (save-excursion
4009 (beginning-of-line 1)
4010 (skip-chars-forward " \t")
4011 (when (looking-at org-clock-string)
4012 (let ((re (concat "[ \t]*" org-clock-string
4013 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
4014 "\\([ \t]*=>.*\\)?\\)?"))
4015 ts te h m s neg)
4016 (cond
4017 ((not (looking-at re))
4018 nil)
4019 ((not (match-end 2))
4020 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4021 (> org-clock-marker (point))
4022 (<= org-clock-marker (point-at-eol)))
4023 ;; The clock is running here
4024 (setq org-clock-start-time
4025 (apply 'encode-time
4026 (org-parse-time-string (match-string 1))))
4027 (org-clock-update-mode-line)))
4029 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
4030 (end-of-line 1)
4031 (setq ts (match-string 1)
4032 te (match-string 3))
4033 (setq s (- (org-float-time
4034 (apply 'encode-time (org-parse-time-string te)))
4035 (org-float-time
4036 (apply 'encode-time (org-parse-time-string ts))))
4037 neg (< s 0)
4038 s (abs s)
4039 h (floor (/ s 3600))
4040 s (- s (* 3600 h))
4041 m (floor (/ s 60))
4042 s (- s (* 60 s)))
4043 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
4044 t))))))
4046 (defun org-check-running-clock ()
4047 "Check if the current buffer contains the running clock.
4048 If yes, offer to stop it and to save the buffer with the changes."
4049 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4050 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4051 (buffer-name))))
4052 (org-clock-out)
4053 (when (y-or-n-p "Save changed buffer?")
4054 (save-buffer))))
4056 (defun org-clocktable-try-shift (dir n)
4057 "Check if this line starts a clock table, if yes, shift the time block."
4058 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4059 (org-clocktable-shift dir n)))
4061 ;; Autoload org-timer.el
4063 (eval-and-compile
4064 (org-autoload
4065 "org-timer"
4066 '(org-timer-start org-timer org-timer-item
4067 org-timer-change-times-in-region
4068 org-timer-set-timer
4069 org-timer-reset-timers
4070 org-timer-show-remaining-time)))
4072 ;; Autoload org-feed.el
4074 (eval-and-compile
4075 (org-autoload
4076 "org-feed"
4077 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
4080 ;; Autoload org-indent.el
4082 ;; Define the variable already here, to make sure we have it.
4083 (defvar org-indent-mode nil
4084 "Non-nil if Org-Indent mode is enabled.
4085 Use the command `org-indent-mode' to change this variable.")
4087 (eval-and-compile
4088 (org-autoload
4089 "org-indent"
4090 '(org-indent-mode)))
4092 ;; Autoload org-mobile.el
4094 (eval-and-compile
4095 (org-autoload
4096 "org-mobile"
4097 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
4099 ;; Autoload archiving code
4100 ;; The stuff that is needed for cycling and tags has to be defined here.
4102 (defgroup org-archive nil
4103 "Options concerning archiving in Org-mode."
4104 :tag "Org Archive"
4105 :group 'org-structure)
4107 (defcustom org-archive-location "%s_archive::"
4108 "The location where subtrees should be archived.
4110 The value of this variable is a string, consisting of two parts,
4111 separated by a double-colon. The first part is a filename and
4112 the second part is a headline.
4114 When the filename is omitted, archiving happens in the same file.
4115 %s in the filename will be replaced by the current file
4116 name (without the directory part). Archiving to a different file
4117 is useful to keep archived entries from contributing to the
4118 Org-mode Agenda.
4120 The archived entries will be filed as subtrees of the specified
4121 headline. When the headline is omitted, the subtrees are simply
4122 filed away at the end of the file, as top-level entries. Also in
4123 the heading you can use %s to represent the file name, this can be
4124 useful when using the same archive for a number of different files.
4126 Here are a few examples:
4127 \"%s_archive::\"
4128 If the current file is Projects.org, archive in file
4129 Projects.org_archive, as top-level trees. This is the default.
4131 \"::* Archived Tasks\"
4132 Archive in the current file, under the top-level headline
4133 \"* Archived Tasks\".
4135 \"~/org/archive.org::\"
4136 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4138 \"~/org/archive.org::* From %s\"
4139 Archive in file ~/org/archive.org (absolute path), under headlines
4140 \"From FILENAME\" where file name is the current file name.
4142 \"basement::** Finished Tasks\"
4143 Archive in file ./basement (relative path), as level 3 trees
4144 below the level 2 heading \"** Finished Tasks\".
4146 You may set this option on a per-file basis by adding to the buffer a
4147 line like
4149 #+ARCHIVE: basement::** Finished Tasks
4151 You may also define it locally for a subtree by setting an ARCHIVE property
4152 in the entry. If such a property is found in an entry, or anywhere up
4153 the hierarchy, it will be used."
4154 :group 'org-archive
4155 :type 'string)
4157 (defcustom org-archive-tag "ARCHIVE"
4158 "The tag that marks a subtree as archived.
4159 An archived subtree does not open during visibility cycling, and does
4160 not contribute to the agenda listings.
4161 After changing this, font-lock must be restarted in the relevant buffers to
4162 get the proper fontification."
4163 :group 'org-archive
4164 :group 'org-keywords
4165 :type 'string)
4167 (defcustom org-agenda-skip-archived-trees t
4168 "Non-nil means the agenda will skip any items located in archived trees.
4169 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4170 variable is no longer recommended, you should leave it at the value t.
4171 Instead, use the key `v' to cycle the archives-mode in the agenda."
4172 :group 'org-archive
4173 :group 'org-agenda-skip
4174 :type 'boolean)
4176 (defcustom org-columns-skip-archived-trees t
4177 "Non-nil means ignore archived trees when creating column view."
4178 :group 'org-archive
4179 :group 'org-properties
4180 :type 'boolean)
4182 (defcustom org-cycle-open-archived-trees nil
4183 "Non-nil means `org-cycle' will open archived trees.
4184 An archived tree is a tree marked with the tag ARCHIVE.
4185 When nil, archived trees will stay folded. You can still open them with
4186 normal outline commands like `show-all', but not with the cycling commands."
4187 :group 'org-archive
4188 :group 'org-cycle
4189 :type 'boolean)
4191 (defcustom org-sparse-tree-open-archived-trees nil
4192 "Non-nil means sparse tree construction shows matches in archived trees.
4193 When nil, matches in these trees are highlighted, but the trees are kept in
4194 collapsed state."
4195 :group 'org-archive
4196 :group 'org-sparse-trees
4197 :type 'boolean)
4199 (defun org-cycle-hide-archived-subtrees (state)
4200 "Re-hide all archived subtrees after a visibility state change."
4201 (when (and (not org-cycle-open-archived-trees)
4202 (not (memq state '(overview folded))))
4203 (save-excursion
4204 (let* ((globalp (memq state '(contents all)))
4205 (beg (if globalp (point-min) (point)))
4206 (end (if globalp (point-max) (org-end-of-subtree t))))
4207 (org-hide-archived-subtrees beg end)
4208 (goto-char beg)
4209 (if (looking-at (concat ".*:" org-archive-tag ":"))
4210 (message "%s" (substitute-command-keys
4211 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4213 (defun org-force-cycle-archived ()
4214 "Cycle subtree even if it is archived."
4215 (interactive)
4216 (setq this-command 'org-cycle)
4217 (let ((org-cycle-open-archived-trees t))
4218 (call-interactively 'org-cycle)))
4220 (defun org-hide-archived-subtrees (beg end)
4221 "Re-hide all archived subtrees after a visibility state change."
4222 (save-excursion
4223 (let* ((re (concat ":" org-archive-tag ":")))
4224 (goto-char beg)
4225 (while (re-search-forward re end t)
4226 (when (org-on-heading-p)
4227 (org-flag-subtree t)
4228 (org-end-of-subtree t))))))
4230 (defun org-flag-subtree (flag)
4231 (save-excursion
4232 (org-back-to-heading t)
4233 (outline-end-of-heading)
4234 (outline-flag-region (point)
4235 (progn (org-end-of-subtree t) (point))
4236 flag)))
4238 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4240 (eval-and-compile
4241 (org-autoload "org-archive"
4242 '(org-add-archive-files org-archive-subtree
4243 org-archive-to-archive-sibling org-toggle-archive-tag
4244 org-archive-subtree-default
4245 org-archive-subtree-default-with-confirmation)))
4247 ;; Autoload Column View Code
4249 (declare-function org-columns-number-to-string "org-colview")
4250 (declare-function org-columns-get-format-and-top-level "org-colview")
4251 (declare-function org-columns-compute "org-colview")
4253 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4254 '(org-columns-number-to-string org-columns-get-format-and-top-level
4255 org-columns-compute org-agenda-columns org-columns-remove-overlays
4256 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4258 ;; Autoload ID code
4260 (declare-function org-id-store-link "org-id")
4261 (declare-function org-id-locations-load "org-id")
4262 (declare-function org-id-locations-save "org-id")
4263 (defvar org-id-track-globally)
4264 (org-autoload "org-id"
4265 '(org-id-get-create org-id-new org-id-copy org-id-get
4266 org-id-get-with-outline-path-completion
4267 org-id-get-with-outline-drilling org-id-store-link
4268 org-id-goto org-id-find org-id-store-link))
4270 ;; Autoload Plotting Code
4272 (org-autoload "org-plot"
4273 '(org-plot/gnuplot))
4275 ;;; Variables for pre-computed regular expressions, all buffer local
4277 (defvar org-drawer-regexp nil
4278 "Matches first line of a hidden block.")
4279 (make-variable-buffer-local 'org-drawer-regexp)
4280 (defvar org-todo-regexp nil
4281 "Matches any of the TODO state keywords.")
4282 (make-variable-buffer-local 'org-todo-regexp)
4283 (defvar org-not-done-regexp nil
4284 "Matches any of the TODO state keywords except the last one.")
4285 (make-variable-buffer-local 'org-not-done-regexp)
4286 (defvar org-not-done-heading-regexp nil
4287 "Matches a TODO headline that is not done.")
4288 (make-variable-buffer-local 'org-not-done-regexp)
4289 (defvar org-todo-line-regexp nil
4290 "Matches a headline and puts TODO state into group 2 if present.")
4291 (make-variable-buffer-local 'org-todo-line-regexp)
4292 (defvar org-complex-heading-regexp nil
4293 "Matches a headline and puts everything into groups:
4294 group 1: the stars
4295 group 2: The todo keyword, maybe
4296 group 3: Priority cookie
4297 group 4: True headline
4298 group 5: Tags")
4299 (make-variable-buffer-local 'org-complex-heading-regexp)
4300 (defvar org-complex-heading-regexp-format nil
4301 "Printf format to make regexp to match an exact headline.
4302 This regexp will match the headline of any node which has the
4303 exact headline text that is put into the format, but may have any
4304 TODO state, priority and tags.")
4305 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4306 (defvar org-todo-line-tags-regexp nil
4307 "Matches a headline and puts TODO state into group 2 if present.
4308 Also put tags into group 4 if tags are present.")
4309 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4310 (defvar org-ds-keyword-length 12
4311 "Maximum length of the Deadline and SCHEDULED keywords.")
4312 (make-variable-buffer-local 'org-ds-keyword-length)
4313 (defvar org-deadline-regexp nil
4314 "Matches the DEADLINE keyword.")
4315 (make-variable-buffer-local 'org-deadline-regexp)
4316 (defvar org-deadline-time-regexp nil
4317 "Matches the DEADLINE keyword together with a time stamp.")
4318 (make-variable-buffer-local 'org-deadline-time-regexp)
4319 (defvar org-deadline-line-regexp nil
4320 "Matches the DEADLINE keyword and the rest of the line.")
4321 (make-variable-buffer-local 'org-deadline-line-regexp)
4322 (defvar org-scheduled-regexp nil
4323 "Matches the SCHEDULED keyword.")
4324 (make-variable-buffer-local 'org-scheduled-regexp)
4325 (defvar org-scheduled-time-regexp nil
4326 "Matches the SCHEDULED keyword together with a time stamp.")
4327 (make-variable-buffer-local 'org-scheduled-time-regexp)
4328 (defvar org-closed-time-regexp nil
4329 "Matches the CLOSED keyword together with a time stamp.")
4330 (make-variable-buffer-local 'org-closed-time-regexp)
4332 (defvar org-keyword-time-regexp nil
4333 "Matches any of the 4 keywords, together with the time stamp.")
4334 (make-variable-buffer-local 'org-keyword-time-regexp)
4335 (defvar org-keyword-time-not-clock-regexp nil
4336 "Matches any of the 3 keywords, together with the time stamp.")
4337 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4338 (defvar org-maybe-keyword-time-regexp nil
4339 "Matches a timestamp, possibly preceded by a keyword.")
4340 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4341 (defvar org-planning-or-clock-line-re nil
4342 "Matches a line with planning or clock info.")
4343 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4344 (defvar org-all-time-keywords nil
4345 "List of time keywords.")
4346 (make-variable-buffer-local 'org-all-time-keywords)
4348 (defconst org-plain-time-of-day-regexp
4349 (concat
4350 "\\(\\<[012]?[0-9]"
4351 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4352 "\\(--?"
4353 "\\(\\<[012]?[0-9]"
4354 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4355 "\\)?")
4356 "Regular expression to match a plain time or time range.
4357 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4358 groups carry important information:
4359 0 the full match
4360 1 the first time, range or not
4361 8 the second time, if it is a range.")
4363 (defconst org-plain-time-extension-regexp
4364 (concat
4365 "\\(\\<[012]?[0-9]"
4366 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4367 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4368 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4369 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4370 groups carry important information:
4371 0 the full match
4372 7 hours of duration
4373 9 minutes of duration")
4375 (defconst org-stamp-time-of-day-regexp
4376 (concat
4377 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4378 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4379 "\\(--?"
4380 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4381 "Regular expression to match a timestamp time or time range.
4382 After a match, the following groups carry important information:
4383 0 the full match
4384 1 date plus weekday, for back referencing to make sure both times are on the same day
4385 2 the first time, range or not
4386 4 the second time, if it is a range.")
4388 (defconst org-startup-options
4389 '(("fold" org-startup-folded t)
4390 ("overview" org-startup-folded t)
4391 ("nofold" org-startup-folded nil)
4392 ("showall" org-startup-folded nil)
4393 ("showeverything" org-startup-folded showeverything)
4394 ("content" org-startup-folded content)
4395 ("indent" org-startup-indented t)
4396 ("noindent" org-startup-indented nil)
4397 ("hidestars" org-hide-leading-stars t)
4398 ("showstars" org-hide-leading-stars nil)
4399 ("odd" org-odd-levels-only t)
4400 ("oddeven" org-odd-levels-only nil)
4401 ("align" org-startup-align-all-tables t)
4402 ("noalign" org-startup-align-all-tables nil)
4403 ("inlineimages" org-startup-with-inline-images t)
4404 ("noinlineimages" org-startup-with-inline-images nil)
4405 ("customtime" org-display-custom-times t)
4406 ("logdone" org-log-done time)
4407 ("lognotedone" org-log-done note)
4408 ("nologdone" org-log-done nil)
4409 ("lognoteclock-out" org-log-note-clock-out t)
4410 ("nolognoteclock-out" org-log-note-clock-out nil)
4411 ("logrepeat" org-log-repeat state)
4412 ("lognoterepeat" org-log-repeat note)
4413 ("nologrepeat" org-log-repeat nil)
4414 ("logreschedule" org-log-reschedule time)
4415 ("lognotereschedule" org-log-reschedule note)
4416 ("nologreschedule" org-log-reschedule nil)
4417 ("logredeadline" org-log-redeadline time)
4418 ("lognoteredeadline" org-log-redeadline note)
4419 ("nologredeadline" org-log-redeadline nil)
4420 ("logrefile" org-log-refile time)
4421 ("lognoterefile" org-log-refile note)
4422 ("nologrefile" org-log-refile nil)
4423 ("fninline" org-footnote-define-inline t)
4424 ("nofninline" org-footnote-define-inline nil)
4425 ("fnlocal" org-footnote-section nil)
4426 ("fnauto" org-footnote-auto-label t)
4427 ("fnprompt" org-footnote-auto-label nil)
4428 ("fnconfirm" org-footnote-auto-label confirm)
4429 ("fnplain" org-footnote-auto-label plain)
4430 ("fnadjust" org-footnote-auto-adjust t)
4431 ("nofnadjust" org-footnote-auto-adjust nil)
4432 ("constcgs" constants-unit-system cgs)
4433 ("constSI" constants-unit-system SI)
4434 ("noptag" org-tag-persistent-alist nil)
4435 ("hideblocks" org-hide-block-startup t)
4436 ("nohideblocks" org-hide-block-startup nil)
4437 ("beamer" org-startup-with-beamer-mode t)
4438 ("entitiespretty" org-pretty-entities t)
4439 ("entitiesplain" org-pretty-entities nil))
4440 "Variable associated with STARTUP options for org-mode.
4441 Each element is a list of three items: The startup options as written
4442 in the #+STARTUP line, the corresponding variable, and the value to
4443 set this variable to if the option is found. An optional forth element PUSH
4444 means to push this value onto the list in the variable.")
4446 (defun org-update-property-plist (key val props)
4447 "Update PROPS with KEY and VAL."
4448 (if (string= "+" (substring key (- (length key) 1)))
4449 (let* ((key (substring key 0 (- (length key) 1)))
4450 (previous (cdr (assoc key props))))
4451 (cons (cons key (concat previous " " val))
4452 (org-remove-if (lambda (p) (string= (car p) key)) props)))
4453 (cons (cons key val) props)))
4455 (defconst org-block-regexp
4456 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4457 "Regular expression for hiding blocks.")
4458 (defconst org-heading-keyword-regexp-format
4459 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4460 "Printf format for a regexp matching an headline with some keyword.
4461 This regexp will match the headline of any node which has the
4462 exact keyword that is put into the format. The keyword isn't in
4463 any group by default, but the stars and the body are.")
4464 (defconst org-heading-keyword-maybe-regexp-format
4465 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4466 "Printf format for a regexp matching an headline, possibly with some keyword.
4467 This regexp can match any headline with the specified keyword, or
4468 without a keyword. The keyword isn't in any group by default,
4469 but the stars and the body are.")
4471 (defun org-set-regexps-and-options ()
4472 "Precompute regular expressions for current buffer."
4473 (when (eq major-mode 'org-mode)
4474 (org-set-local 'org-todo-kwd-alist nil)
4475 (org-set-local 'org-todo-key-alist nil)
4476 (org-set-local 'org-todo-key-trigger nil)
4477 (org-set-local 'org-todo-keywords-1 nil)
4478 (org-set-local 'org-done-keywords nil)
4479 (org-set-local 'org-todo-heads nil)
4480 (org-set-local 'org-todo-sets nil)
4481 (org-set-local 'org-todo-log-states nil)
4482 (org-set-local 'org-file-properties nil)
4483 (org-set-local 'org-file-tags nil)
4484 (let ((re (org-make-options-regexp
4485 '("CATEGORY" "TODO" "COLUMNS"
4486 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4487 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4488 "OPTIONS")
4489 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4490 (splitre "[ \t]+")
4491 (scripts org-use-sub-superscripts)
4492 kwds kws0 kwsa key log value cat arch tags const links hw dws
4493 tail sep kws1 prio props ftags drawers beamer-p
4494 ext-setup-or-nil setup-contents (start 0))
4495 (save-excursion
4496 (save-restriction
4497 (widen)
4498 (goto-char (point-min))
4499 (while (or (and ext-setup-or-nil
4500 (string-match re ext-setup-or-nil start)
4501 (setq start (match-end 0)))
4502 (and (setq ext-setup-or-nil nil start 0)
4503 (re-search-forward re nil t)))
4504 (setq key (upcase (match-string 1 ext-setup-or-nil))
4505 value (org-match-string-no-properties 2 ext-setup-or-nil))
4506 (if (stringp value) (setq value (org-trim value)))
4507 (cond
4508 ((equal key "CATEGORY")
4509 (setq cat value))
4510 ((member key '("SEQ_TODO" "TODO"))
4511 (push (cons 'sequence (org-split-string value splitre)) kwds))
4512 ((equal key "TYP_TODO")
4513 (push (cons 'type (org-split-string value splitre)) kwds))
4514 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4515 ;; general TODO-like setup
4516 (push (cons (intern (downcase (match-string 1 key)))
4517 (org-split-string value splitre)) kwds))
4518 ((equal key "TAGS")
4519 (setq tags (append tags (if tags '("\\n") nil)
4520 (org-split-string value splitre))))
4521 ((equal key "COLUMNS")
4522 (org-set-local 'org-columns-default-format value))
4523 ((equal key "LINK")
4524 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4525 (push (cons (match-string 1 value)
4526 (org-trim (match-string 2 value)))
4527 links)))
4528 ((equal key "PRIORITIES")
4529 (setq prio (org-split-string value " +")))
4530 ((equal key "PROPERTY")
4531 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4532 (setq props (org-update-property-plist (match-string 1 value)
4533 (match-string 2 value)
4534 props))))
4535 ((equal key "FILETAGS")
4536 (when (string-match "\\S-" value)
4537 (setq ftags
4538 (append
4539 ftags
4540 (apply 'append
4541 (mapcar (lambda (x) (org-split-string x ":"))
4542 (org-split-string value)))))))
4543 ((equal key "DRAWERS")
4544 (setq drawers (org-split-string value splitre)))
4545 ((equal key "CONSTANTS")
4546 (setq const (append const (org-split-string value splitre))))
4547 ((equal key "STARTUP")
4548 (let ((opts (org-split-string value splitre))
4549 l var val)
4550 (while (setq l (pop opts))
4551 (when (setq l (assoc l org-startup-options))
4552 (setq var (nth 1 l) val (nth 2 l))
4553 (if (not (nth 3 l))
4554 (set (make-local-variable var) val)
4555 (if (not (listp (symbol-value var)))
4556 (set (make-local-variable var) nil))
4557 (set (make-local-variable var) (symbol-value var))
4558 (add-to-list var val))))))
4559 ((equal key "ARCHIVE")
4560 (setq arch value)
4561 (remove-text-properties 0 (length arch)
4562 '(face t fontified t) arch))
4563 ((equal key "LATEX_CLASS")
4564 (setq beamer-p (equal value "beamer")))
4565 ((equal key "OPTIONS")
4566 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4567 (setq scripts (read (match-string 2 value)))))
4568 ((equal key "SETUPFILE")
4569 (setq setup-contents (org-file-contents
4570 (expand-file-name
4571 (org-remove-double-quotes value))
4572 'noerror))
4573 (if (not ext-setup-or-nil)
4574 (setq ext-setup-or-nil setup-contents start 0)
4575 (setq ext-setup-or-nil
4576 (concat (substring ext-setup-or-nil 0 start)
4577 "\n" setup-contents "\n"
4578 (substring ext-setup-or-nil start)))))))
4579 ;; search for property blocks
4580 (goto-char (point-min))
4581 (while (re-search-forward org-block-regexp nil t)
4582 (when (equal "PROPERTY" (upcase (match-string 1)))
4583 (setq value (replace-regexp-in-string
4584 "[\n\r]" " " (match-string 4)))
4585 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4586 (setq props (org-update-property-plist (match-string 1 value)
4587 (match-string 2 value)
4588 props)))))))
4589 (org-set-local 'org-use-sub-superscripts scripts)
4590 (when cat
4591 (org-set-local 'org-category (intern cat))
4592 (push (cons "CATEGORY" cat) props))
4593 (when prio
4594 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4595 (setq prio (mapcar 'string-to-char prio))
4596 (org-set-local 'org-highest-priority (nth 0 prio))
4597 (org-set-local 'org-lowest-priority (nth 1 prio))
4598 (org-set-local 'org-default-priority (nth 2 prio)))
4599 (and props (org-set-local 'org-file-properties (nreverse props)))
4600 (and ftags (org-set-local 'org-file-tags
4601 (mapcar 'org-add-prop-inherited ftags)))
4602 (and drawers (org-set-local 'org-drawers drawers))
4603 (and arch (org-set-local 'org-archive-location arch))
4604 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4605 ;; Process the TODO keywords
4606 (unless kwds
4607 ;; Use the global values as if they had been given locally.
4608 (setq kwds (default-value 'org-todo-keywords))
4609 (if (stringp (car kwds))
4610 (setq kwds (list (cons org-todo-interpretation
4611 (default-value 'org-todo-keywords)))))
4612 (setq kwds (reverse kwds)))
4613 (setq kwds (nreverse kwds))
4614 (let (inter kws kw)
4615 (while (setq kws (pop kwds))
4616 (let ((kws (or
4617 (run-hook-with-args-until-success
4618 'org-todo-setup-filter-hook kws)
4619 kws)))
4620 (setq inter (pop kws) sep (member "|" kws)
4621 kws0 (delete "|" (copy-sequence kws))
4622 kwsa nil
4623 kws1 (mapcar
4624 (lambda (x)
4625 ;; 1 2
4626 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4627 (progn
4628 (setq kw (match-string 1 x)
4629 key (and (match-end 2) (match-string 2 x))
4630 log (org-extract-log-state-settings x))
4631 (push (cons kw (and key (string-to-char key))) kwsa)
4632 (and log (push log org-todo-log-states))
4634 (error "Invalid TODO keyword %s" x)))
4635 kws0)
4636 kwsa (if kwsa (append '((:startgroup))
4637 (nreverse kwsa)
4638 '((:endgroup))))
4639 hw (car kws1)
4640 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4641 tail (list inter hw (car dws) (org-last dws))))
4642 (add-to-list 'org-todo-heads hw 'append)
4643 (push kws1 org-todo-sets)
4644 (setq org-done-keywords (append org-done-keywords dws nil))
4645 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4646 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4647 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4648 (setq org-todo-sets (nreverse org-todo-sets)
4649 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4650 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4651 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4652 ;; Process the constants
4653 (when const
4654 (let (e cst)
4655 (while (setq e (pop const))
4656 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4657 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4658 (setq org-table-formula-constants-local cst)))
4660 ;; Process the tags.
4661 (when tags
4662 (let (e tgs)
4663 (while (setq e (pop tags))
4664 (cond
4665 ((equal e "{") (push '(:startgroup) tgs))
4666 ((equal e "}") (push '(:endgroup) tgs))
4667 ((equal e "\\n") (push '(:newline) tgs))
4668 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4669 (push (cons (match-string 1 e)
4670 (string-to-char (match-string 2 e)))
4671 tgs))
4672 (t (push (list e) tgs))))
4673 (org-set-local 'org-tag-alist nil)
4674 (while (setq e (pop tgs))
4675 (or (and (stringp (car e))
4676 (assoc (car e) org-tag-alist))
4677 (push e org-tag-alist)))))
4679 ;; Compute the regular expressions and other local variables.
4680 ;; Using `org-outline-regexp-bol' would complicate them much,
4681 ;; because of the fixed white space at the end of that string.
4682 (if (not org-done-keywords)
4683 (setq org-done-keywords (and org-todo-keywords-1
4684 (list (org-last org-todo-keywords-1)))))
4685 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4686 (length org-scheduled-string)
4687 (length org-clock-string)
4688 (length org-closed-string)))
4689 org-drawer-regexp
4690 (concat "^[ \t]*:\\("
4691 (mapconcat 'regexp-quote org-drawers "\\|")
4692 "\\):[ \t]*$")
4693 org-not-done-keywords
4694 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4695 org-todo-regexp
4696 (concat "\\("
4697 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4698 "\\)")
4699 org-not-done-regexp
4700 (concat "\\("
4701 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4702 "\\)")
4703 org-not-done-heading-regexp
4704 (format org-heading-keyword-regexp-format org-not-done-regexp)
4705 org-todo-line-regexp
4706 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4707 org-complex-heading-regexp
4708 (concat "^\\(\\*+\\)"
4709 "\\(?: +" org-todo-regexp "\\)?"
4710 "\\(?: +\\(\\[#.\\]\\)\\)?"
4711 "\\(?: +\\(.*?\\)\\)?"
4712 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4713 "[ \t]*$")
4714 org-complex-heading-regexp-format
4715 (concat "^\\(\\*+\\)"
4716 "\\(?: +" org-todo-regexp "\\)?"
4717 "\\(?: +\\(\\[#.\\]\\)\\)?"
4718 "\\(?: +"
4719 ;; Stats cookies can be sticked to body.
4720 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4721 "\\(%s\\)"
4722 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4723 "\\)"
4724 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4725 "[ \t]*$")
4726 org-todo-line-tags-regexp
4727 (concat "^\\(\\*+\\)"
4728 "\\(?: +" org-todo-regexp "\\)?"
4729 "\\(?: +\\(.*?\\)\\)?"
4730 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4731 "[ \t]*$")
4732 org-deadline-regexp (concat "\\<" org-deadline-string)
4733 org-deadline-time-regexp
4734 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4735 org-deadline-line-regexp
4736 (concat "\\<\\(" org-deadline-string "\\).*")
4737 org-scheduled-regexp
4738 (concat "\\<" org-scheduled-string)
4739 org-scheduled-time-regexp
4740 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4741 org-closed-time-regexp
4742 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4743 org-keyword-time-regexp
4744 (concat "\\<\\(" org-scheduled-string
4745 "\\|" org-deadline-string
4746 "\\|" org-closed-string
4747 "\\|" org-clock-string "\\)"
4748 " *[[<]\\([^]>]+\\)[]>]")
4749 org-keyword-time-not-clock-regexp
4750 (concat "\\<\\(" org-scheduled-string
4751 "\\|" org-deadline-string
4752 "\\|" org-closed-string
4753 "\\)"
4754 " *[[<]\\([^]>]+\\)[]>]")
4755 org-maybe-keyword-time-regexp
4756 (concat "\\(\\<\\(" org-scheduled-string
4757 "\\|" org-deadline-string
4758 "\\|" org-closed-string
4759 "\\|" org-clock-string "\\)\\)?"
4760 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4761 org-planning-or-clock-line-re
4762 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4763 "\\|" org-deadline-string
4764 "\\|" org-closed-string "\\|" org-clock-string
4765 "\\)\\>\\)")
4766 org-all-time-keywords
4767 (mapcar (lambda (w) (substring w 0 -1))
4768 (list org-scheduled-string org-deadline-string
4769 org-clock-string org-closed-string))
4771 (org-compute-latex-and-specials-regexp)
4772 (org-set-font-lock-defaults))))
4774 (defun org-file-contents (file &optional noerror)
4775 "Return the contents of FILE, as a string."
4776 (if (or (not file)
4777 (not (file-readable-p file)))
4778 (if noerror
4779 (progn
4780 (message "Cannot read file \"%s\"" file)
4781 (ding) (sit-for 2)
4783 (error "Cannot read file \"%s\"" file))
4784 (with-temp-buffer
4785 (insert-file-contents file)
4786 (buffer-string))))
4788 (defun org-extract-log-state-settings (x)
4789 "Extract the log state setting from a TODO keyword string.
4790 This will extract info from a string like \"WAIT(w@/!)\"."
4791 (let (kw key log1 log2)
4792 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4793 (setq kw (match-string 1 x)
4794 key (and (match-end 2) (match-string 2 x))
4795 log1 (and (match-end 3) (match-string 3 x))
4796 log2 (and (match-end 4) (match-string 4 x)))
4797 (and (or log1 log2)
4798 (list kw
4799 (and log1 (if (equal log1 "!") 'time 'note))
4800 (and log2 (if (equal log2 "!") 'time 'note)))))))
4802 (defun org-remove-keyword-keys (list)
4803 "Remove a pair of parenthesis at the end of each string in LIST."
4804 (mapcar (lambda (x)
4805 (if (string-match "(.*)$" x)
4806 (substring x 0 (match-beginning 0))
4808 list))
4810 (defun org-assign-fast-keys (alist)
4811 "Assign fast keys to a keyword-key alist.
4812 Respect keys that are already there."
4813 (let (new e (alt ?0))
4814 (while (setq e (pop alist))
4815 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4816 (cdr e)) ;; Key already assigned.
4817 (push e new)
4818 (let ((clist (string-to-list (downcase (car e))))
4819 (used (append new alist)))
4820 (when (= (car clist) ?@)
4821 (pop clist))
4822 (while (and clist (rassoc (car clist) used))
4823 (pop clist))
4824 (unless clist
4825 (while (rassoc alt used)
4826 (incf alt)))
4827 (push (cons (car e) (or (car clist) alt)) new))))
4828 (nreverse new)))
4830 ;;; Some variables used in various places
4832 (defvar org-window-configuration nil
4833 "Used in various places to store a window configuration.")
4834 (defvar org-selected-window nil
4835 "Used in various places to store a window configuration.")
4836 (defvar org-finish-function nil
4837 "Function to be called when `C-c C-c' is used.
4838 This is for getting out of special buffers like remember.")
4841 ;; FIXME: Occasionally check by commenting these, to make sure
4842 ;; no other functions uses these, forgetting to let-bind them.
4843 (defvar entry)
4844 (defvar last-state)
4845 (defvar date)
4847 ;; Defined somewhere in this file, but used before definition.
4848 (defvar org-entities) ;; defined in org-entities.el
4849 (defvar org-struct-menu)
4850 (defvar org-org-menu)
4851 (defvar org-tbl-menu)
4853 ;;;; Define the Org-mode
4855 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4856 (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"))
4859 ;; We use a before-change function to check if a table might need
4860 ;; an update.
4861 (defvar org-table-may-need-update t
4862 "Indicates that a table might need an update.
4863 This variable is set by `org-before-change-function'.
4864 `org-table-align' sets it back to nil.")
4865 (defun org-before-change-function (beg end)
4866 "Every change indicates that a table might need an update."
4867 (setq org-table-may-need-update t))
4868 (defvar org-mode-map)
4869 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4870 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4871 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4872 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4873 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4874 (defvar org-table-buffer-is-an nil)
4876 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
4877 ;; some places -- e.g. see the macro org-with-limited-levels.
4879 ;; In Org buffers, the value of `outline-regexp' is that of
4880 ;; `org-outline-regexp'. The only function still directly relying on
4881 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
4882 ;; job when `orgstruct-mode' is active.
4883 (defvar org-outline-regexp "\\*+ "
4884 "Regexp to match Org headlines.")
4885 (defconst org-outline-regexp-bol "^\\*+ "
4886 "Regexp to match Org headlines.
4887 This is similar to `org-outline-regexp' but additionally makes
4888 sure that we are at the beginning of the line.")
4890 (defconst org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4891 "Matches an headline, putting stars and text into groups.
4892 Stars are put in group 1 and the trimmed body in group 2.")
4894 ;;;###autoload
4895 (define-derived-mode org-mode outline-mode "Org"
4896 "Outline-based notes management and organizer, alias
4897 \"Carsten's outline-mode for keeping track of everything.\"
4899 Org-mode develops organizational tasks around a NOTES file which
4900 contains information about projects as plain text. Org-mode is
4901 implemented on top of outline-mode, which is ideal to keep the content
4902 of large files well structured. It supports ToDo items, deadlines and
4903 time stamps, which magically appear in the diary listing of the Emacs
4904 calendar. Tables are easily created with a built-in table editor.
4905 Plain text URL-like links connect to websites, emails (VM), Usenet
4906 messages (Gnus), BBDB entries, and any files related to the project.
4907 For printing and sharing of notes, an Org-mode file (or a part of it)
4908 can be exported as a structured ASCII or HTML file.
4910 The following commands are available:
4912 \\{org-mode-map}"
4914 ;; Get rid of Outline menus, they are not needed
4915 ;; Need to do this here because define-derived-mode sets up
4916 ;; the keymap so late. Still, it is a waste to call this each time
4917 ;; we switch another buffer into org-mode.
4918 (if (featurep 'xemacs)
4919 (when (boundp 'outline-mode-menu-heading)
4920 ;; Assume this is Greg's port, it uses easymenu
4921 (easy-menu-remove outline-mode-menu-heading)
4922 (easy-menu-remove outline-mode-menu-show)
4923 (easy-menu-remove outline-mode-menu-hide))
4924 (define-key org-mode-map [menu-bar headings] 'undefined)
4925 (define-key org-mode-map [menu-bar hide] 'undefined)
4926 (define-key org-mode-map [menu-bar show] 'undefined))
4928 (org-load-modules-maybe)
4929 (easy-menu-add org-org-menu)
4930 (easy-menu-add org-tbl-menu)
4931 (org-install-agenda-files-menu)
4932 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4933 (add-to-invisibility-spec '(org-cwidth))
4934 (add-to-invisibility-spec '(org-hide-block . t))
4935 (when (featurep 'xemacs)
4936 (org-set-local 'line-move-ignore-invisible t))
4937 (org-set-local 'outline-regexp org-outline-regexp)
4938 (org-set-local 'outline-level 'org-outline-level)
4939 (setq bidi-paragraph-direction 'left-to-right)
4940 (when (and org-ellipsis
4941 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4942 (fboundp 'make-glyph-code))
4943 (unless org-display-table
4944 (setq org-display-table (make-display-table)))
4945 (set-display-table-slot
4946 org-display-table 4
4947 (vconcat (mapcar
4948 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4949 org-ellipsis)))
4950 (if (stringp org-ellipsis) org-ellipsis "..."))))
4951 (setq buffer-display-table org-display-table))
4952 (org-set-regexps-and-options)
4953 (when (and org-tag-faces (not org-tags-special-faces-re))
4954 ;; tag faces set outside customize.... force initialization.
4955 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4956 ;; Calc embedded
4957 (org-set-local 'calc-embedded-open-mode "# ")
4958 (modify-syntax-entry ?@ "w")
4959 (if org-startup-truncated (setq truncate-lines t))
4960 (org-set-local 'font-lock-unfontify-region-function
4961 'org-unfontify-region)
4962 ;; Activate before-change-function
4963 (org-set-local 'org-table-may-need-update t)
4964 (org-add-hook 'before-change-functions 'org-before-change-function nil
4965 'local)
4966 ;; Check for running clock before killing a buffer
4967 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4968 ;; Paragraphs and auto-filling
4969 (org-set-autofill-regexps)
4970 (setq indent-line-function 'org-indent-line-function)
4971 (org-update-radio-target-regexp)
4972 ;; Beginning/end of defun
4973 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
4974 (org-set-local 'end-of-defun-function 'org-end-of-defun)
4975 ;; Next error for sparse trees
4976 (org-set-local 'next-error-function 'org-occur-next-match)
4977 ;; Make sure dependence stuff works reliably, even for users who set it
4978 ;; too late :-(
4979 (if org-enforce-todo-dependencies
4980 (add-hook 'org-blocker-hook
4981 'org-block-todo-from-children-or-siblings-or-parent)
4982 (remove-hook 'org-blocker-hook
4983 'org-block-todo-from-children-or-siblings-or-parent))
4984 (if org-enforce-todo-checkbox-dependencies
4985 (add-hook 'org-blocker-hook
4986 'org-block-todo-from-checkboxes)
4987 (remove-hook 'org-blocker-hook
4988 'org-block-todo-from-checkboxes))
4990 ;; Comment characters
4991 (org-set-local 'comment-start "#")
4992 (org-set-local 'comment-padding " ")
4994 ;; Align options lines
4995 (org-set-local
4996 'align-mode-rules-list
4997 '((org-in-buffer-settings
4998 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4999 (modes . '(org-mode)))))
5001 ;; Imenu
5002 (org-set-local 'imenu-create-index-function
5003 'org-imenu-get-tree)
5005 ;; Make isearch reveal context
5006 (if (or (featurep 'xemacs)
5007 (not (boundp 'outline-isearch-open-invisible-function)))
5008 ;; Emacs 21 and XEmacs make use of the hook
5009 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5010 ;; Emacs 22 deals with this through a special variable
5011 (org-set-local 'outline-isearch-open-invisible-function
5012 (lambda (&rest ignore) (org-show-context 'isearch))))
5014 ;; Turn on org-beamer-mode?
5015 (and org-startup-with-beamer-mode (org-beamer-mode 1))
5017 ;; Setup the pcomplete hooks
5018 (set (make-local-variable 'pcomplete-command-completion-function)
5019 'org-pcomplete-initial)
5020 (set (make-local-variable 'pcomplete-command-name-function)
5021 'org-command-at-point)
5022 (set (make-local-variable 'pcomplete-default-completion-function)
5023 'ignore)
5024 (set (make-local-variable 'pcomplete-parse-arguments-function)
5025 'org-parse-arguments)
5026 (set (make-local-variable 'pcomplete-termination-string) "")
5027 (set (make-local-variable 'face-remapping-alist)
5028 '((default org-default)))
5030 ;; If empty file that did not turn on org-mode automatically, make it to.
5031 (if (and org-insert-mode-line-in-empty-file
5032 (org-called-interactively-p 'any)
5033 (= (point-min) (point-max)))
5034 (insert "# -*- mode: org -*-\n\n"))
5035 (unless org-inhibit-startup
5036 (when org-startup-align-all-tables
5037 (let ((bmp (buffer-modified-p)))
5038 (org-table-map-tables 'org-table-align 'quietly)
5039 (set-buffer-modified-p bmp)))
5040 (when org-startup-with-inline-images
5041 (org-display-inline-images))
5042 (when org-startup-indented
5043 (require 'org-indent)
5044 (org-indent-mode 1))
5045 (unless org-inhibit-startup-visibility-stuff
5046 (org-set-startup-visibility))))
5048 (when (fboundp 'abbrev-table-put)
5049 (abbrev-table-put org-mode-abbrev-table
5050 :parents (list text-mode-abbrev-table)))
5052 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5054 (defun org-current-time ()
5055 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5056 (if (> (car org-time-stamp-rounding-minutes) 1)
5057 (let ((r (car org-time-stamp-rounding-minutes))
5058 (time (decode-time)))
5059 (apply 'encode-time
5060 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5061 (nthcdr 2 time))))
5062 (current-time)))
5064 (defun org-today ()
5065 "Return today date, considering `org-extend-today-until'."
5066 (time-to-days
5067 (time-subtract (current-time)
5068 (list 0 (* 3600 org-extend-today-until) 0))))
5070 ;;;; Font-Lock stuff, including the activators
5072 (defvar org-mouse-map (make-sparse-keymap))
5073 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5074 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5075 (when org-mouse-1-follows-link
5076 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5077 (when org-tab-follows-link
5078 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5079 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5081 (require 'font-lock)
5083 (defconst org-non-link-chars "]\t\n\r<>")
5084 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5085 "shell" "elisp" "doi" "message"))
5086 (defvar org-link-types-re nil
5087 "Matches a link that has a url-like prefix like \"http:\"")
5088 (defvar org-link-re-with-space nil
5089 "Matches a link with spaces, optional angular brackets around it.")
5090 (defvar org-link-re-with-space2 nil
5091 "Matches a link with spaces, optional angular brackets around it.")
5092 (defvar org-link-re-with-space3 nil
5093 "Matches a link with spaces, only for internal part in bracket links.")
5094 (defvar org-angle-link-re nil
5095 "Matches link with angular brackets, spaces are allowed.")
5096 (defvar org-plain-link-re nil
5097 "Matches plain link, without spaces.")
5098 (defvar org-bracket-link-regexp nil
5099 "Matches a link in double brackets.")
5100 (defvar org-bracket-link-analytic-regexp nil
5101 "Regular expression used to analyze links.
5102 Here is what the match groups contain after a match:
5103 1: http:
5104 2: http
5105 3: path
5106 4: [desc]
5107 5: desc")
5108 (defvar org-bracket-link-analytic-regexp++ nil
5109 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5110 (defvar org-any-link-re nil
5111 "Regular expression matching any link.")
5113 (defcustom org-match-sexp-depth 3
5114 "Number of stacked braces for sub/superscript matching.
5115 This has to be set before loading org.el to be effective."
5116 :group 'org-export-translation ; ??????????????????????????/
5117 :type 'integer)
5119 (defun org-create-multibrace-regexp (left right n)
5120 "Create a regular expression which will match a balanced sexp.
5121 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5122 as single character strings.
5123 The regexp returned will match the entire expression including the
5124 delimiters. It will also define a single group which contains the
5125 match except for the outermost delimiters. The maximum depth of
5126 stacked delimiters is N. Escaping delimiters is not possible."
5127 (let* ((nothing (concat "[^" left right "]*?"))
5128 (or "\\|")
5129 (re nothing)
5130 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5131 (while (> n 1)
5132 (setq n (1- n)
5133 re (concat re or next)
5134 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5135 (concat left "\\(" re "\\)" right)))
5137 (defvar org-match-substring-regexp
5138 (concat
5139 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5140 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5141 "\\|"
5142 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5143 "\\|"
5144 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5145 "The regular expression matching a sub- or superscript.")
5147 (defvar org-match-substring-with-braces-regexp
5148 (concat
5149 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5150 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5151 "\\)")
5152 "The regular expression matching a sub- or superscript, forcing braces.")
5154 (defun org-make-link-regexps ()
5155 "Update the link regular expressions.
5156 This should be called after the variable `org-link-types' has changed."
5157 (setq org-link-types-re
5158 (concat
5159 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5160 org-link-re-with-space
5161 (concat
5162 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5163 "\\([^" org-non-link-chars " ]"
5164 "[^" org-non-link-chars "]*"
5165 "[^" org-non-link-chars " ]\\)>?")
5166 org-link-re-with-space2
5167 (concat
5168 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5169 "\\([^" org-non-link-chars " ]"
5170 "[^\t\n\r]*"
5171 "[^" org-non-link-chars " ]\\)>?")
5172 org-link-re-with-space3
5173 (concat
5174 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5175 "\\([^" org-non-link-chars " ]"
5176 "[^\t\n\r]*\\)")
5177 org-angle-link-re
5178 (concat
5179 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5180 "\\([^" org-non-link-chars " ]"
5181 "[^" org-non-link-chars "]*"
5182 "\\)>")
5183 org-plain-link-re
5184 (concat
5185 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5186 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5187 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5188 org-bracket-link-regexp
5189 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5190 org-bracket-link-analytic-regexp
5191 (concat
5192 "\\[\\["
5193 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5194 "\\([^]]+\\)"
5195 "\\]"
5196 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5197 "\\]")
5198 org-bracket-link-analytic-regexp++
5199 (concat
5200 "\\[\\["
5201 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5202 "\\([^]]+\\)"
5203 "\\]"
5204 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5205 "\\]")
5206 org-any-link-re
5207 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5208 org-angle-link-re "\\)\\|\\("
5209 org-plain-link-re "\\)")))
5211 (org-make-link-regexps)
5213 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5214 "Regular expression for fast time stamp matching.")
5215 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5216 "Regular expression for fast time stamp matching.")
5217 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5218 "Regular expression matching time strings for analysis.
5219 This one does not require the space after the date, so it can be used
5220 on a string that terminates immediately after the date.")
5221 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5222 "Regular expression matching time strings for analysis.")
5223 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5224 "Regular expression matching time stamps, with groups.")
5225 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5226 "Regular expression matching time stamps (also [..]), with groups.")
5227 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5228 "Regular expression matching a time stamp range.")
5229 (defconst org-tr-regexp-both
5230 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5231 "Regular expression matching a time stamp range.")
5232 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5233 org-ts-regexp "\\)?")
5234 "Regular expression matching a time stamp or time stamp range.")
5235 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5236 org-ts-regexp-both "\\)?")
5237 "Regular expression matching a time stamp or time stamp range.
5238 The time stamps may be either active or inactive.")
5240 (defvar org-emph-face nil)
5242 (defun org-do-emphasis-faces (limit)
5243 "Run through the buffer and add overlays to emphasised strings."
5244 (let (rtn a)
5245 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5246 (if (not (= (char-after (match-beginning 3))
5247 (char-after (match-beginning 4))))
5248 (progn
5249 (setq rtn t)
5250 (setq a (assoc (match-string 3) org-emphasis-alist))
5251 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5252 'face
5253 (nth 1 a))
5254 (and (nth 4 a)
5255 (org-remove-flyspell-overlays-in
5256 (match-beginning 0) (match-end 0)))
5257 (add-text-properties (match-beginning 2) (match-end 2)
5258 '(font-lock-multiline t org-emphasis t))
5259 (when org-hide-emphasis-markers
5260 (add-text-properties (match-end 4) (match-beginning 5)
5261 '(invisible org-link))
5262 (add-text-properties (match-beginning 3) (match-end 3)
5263 '(invisible org-link)))))
5264 (backward-char 1))
5265 rtn))
5267 (defun org-emphasize (&optional char)
5268 "Insert or change an emphasis, i.e. a font like bold or italic.
5269 If there is an active region, change that region to a new emphasis.
5270 If there is no region, just insert the marker characters and position
5271 the cursor between them.
5272 CHAR should be either the marker character, or the first character of the
5273 HTML tag associated with that emphasis. If CHAR is a space, the means
5274 to remove the emphasis of the selected region.
5275 If char is not given (for example in an interactive call) it
5276 will be prompted for."
5277 (interactive)
5278 (let ((eal org-emphasis-alist) e det
5279 (erc org-emphasis-regexp-components)
5280 (prompt "")
5281 (string "") beg end move tag c s)
5282 (if (org-region-active-p)
5283 (setq beg (region-beginning) end (region-end)
5284 string (buffer-substring beg end))
5285 (setq move t))
5287 (while (setq e (pop eal))
5288 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5289 c (aref tag 0))
5290 (push (cons c (string-to-char (car e))) det)
5291 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5292 (substring tag 1)))))
5293 (setq det (nreverse det))
5294 (unless char
5295 (message "%s" (concat "Emphasis marker or tag:" prompt))
5296 (setq char (read-char-exclusive)))
5297 (setq char (or (cdr (assoc char det)) char))
5298 (if (equal char ?\ )
5299 (setq s "" move nil)
5300 (unless (assoc (char-to-string char) org-emphasis-alist)
5301 (error "No such emphasis marker: \"%c\"" char))
5302 (setq s (char-to-string char)))
5303 (while (and (> (length string) 1)
5304 (equal (substring string 0 1) (substring string -1))
5305 (assoc (substring string 0 1) org-emphasis-alist))
5306 (setq string (substring string 1 -1)))
5307 (setq string (concat s string s))
5308 (if beg (delete-region beg end))
5309 (unless (or (bolp)
5310 (string-match (concat "[" (nth 0 erc) "\n]")
5311 (char-to-string (char-before (point)))))
5312 (insert " "))
5313 (unless (or (eobp)
5314 (string-match (concat "[" (nth 1 erc) "\n]")
5315 (char-to-string (char-after (point)))))
5316 (insert " ") (backward-char 1))
5317 (insert string)
5318 (and move (backward-char 1))))
5320 (defconst org-nonsticky-props
5321 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5323 (defsubst org-rear-nonsticky-at (pos)
5324 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5326 (defun org-activate-plain-links (limit)
5327 "Run through the buffer and add overlays to links."
5328 (catch 'exit
5329 (let (f)
5330 (if (re-search-forward org-plain-link-re limit t)
5331 (progn
5332 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5333 (setq f (get-text-property (match-beginning 0) 'face))
5334 (if (or (eq f 'org-tag)
5335 (and (listp f) (memq 'org-tag f)))
5337 (add-text-properties (match-beginning 0) (match-end 0)
5338 (list 'mouse-face 'highlight
5339 'face 'org-link
5340 'keymap org-mouse-map))
5341 (org-rear-nonsticky-at (match-end 0)))
5342 t)))))
5344 (defun org-activate-code (limit)
5345 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5346 (progn
5347 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5348 (remove-text-properties (match-beginning 0) (match-end 0)
5349 '(display t invisible t intangible t))
5350 t)))
5352 (defcustom org-src-fontify-natively nil
5353 "When non-nil, fontify code in code blocks."
5354 :type 'boolean
5355 :group 'org-appearance
5356 :group 'org-babel)
5358 (defun org-fontify-meta-lines-and-blocks (limit)
5359 (condition-case nil
5360 (org-fontify-meta-lines-and-blocks-1 limit)
5361 (error (message "org-mode fontification error"))))
5363 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5364 "Fontify #+ lines and blocks, in the correct ways."
5365 (let ((case-fold-search t))
5366 (if (re-search-forward
5367 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5368 limit t)
5369 (let ((beg (match-beginning 0))
5370 (block-start (match-end 0))
5371 (block-end nil)
5372 (lang (match-string 7))
5373 (beg1 (line-beginning-position 2))
5374 (dc1 (downcase (match-string 2)))
5375 (dc3 (downcase (match-string 3)))
5376 end end1 quoting block-type ovl)
5377 (cond
5378 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
5379 ;; a single line of backend-specific content
5380 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5381 (remove-text-properties (match-beginning 0) (match-end 0)
5382 '(display t invisible t intangible t))
5383 (add-text-properties (match-beginning 1) (match-end 3)
5384 '(font-lock-fontified t face org-meta-line))
5385 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5386 '(font-lock-fontified t face org-block))
5387 ; for backend-specific code
5389 ((and (match-end 4) (equal dc3 "begin"))
5390 ;; Truly a block
5391 (setq block-type (downcase (match-string 5))
5392 quoting (member block-type org-protecting-blocks))
5393 (when (re-search-forward
5394 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5395 nil t) ;; on purpose, we look further than LIMIT
5396 (setq end (match-end 0) end1 (1- (match-beginning 0)))
5397 (setq block-end (match-beginning 0))
5398 (when quoting
5399 (remove-text-properties beg end
5400 '(display t invisible t intangible t)))
5401 (add-text-properties
5402 beg end
5403 '(font-lock-fontified t font-lock-multiline t))
5404 (add-text-properties beg beg1 '(face org-meta-line))
5405 (add-text-properties end1 (min (point-max) (1+ end))
5406 '(face org-meta-line)) ; for end_src
5407 (cond
5408 ((and lang (not (string= lang "")) org-src-fontify-natively)
5409 (org-src-font-lock-fontify-block lang block-start block-end)
5410 ;; remove old background overlays
5411 (mapc (lambda (ov)
5412 (if (eq (overlay-get ov 'face) 'org-block-background)
5413 (delete-overlay ov)))
5414 (overlays-at (/ (+ beg1 block-end) 2)))
5415 ;; add a background overlay
5416 (setq ovl (make-overlay beg1 block-end))
5417 (overlay-put ovl 'face 'org-block-background)
5418 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5419 (quoting
5420 (add-text-properties beg1 (min (point-max) (1+ end1))
5421 '(face org-block))) ; end of source block
5422 ((not org-fontify-quote-and-verse-blocks))
5423 ((string= block-type "quote")
5424 (add-text-properties beg1 (1+ end1) '(face org-quote)))
5425 ((string= block-type "verse")
5426 (add-text-properties beg1 (1+ end1) '(face org-verse))))
5427 (add-text-properties beg beg1 '(face org-block-begin-line))
5428 (add-text-properties (1+ end) (1+ end1) '(face org-block-end-line))
5430 ((member dc1 '("title:" "author:" "email:" "date:"))
5431 (add-text-properties
5432 beg (match-end 3)
5433 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5434 '(font-lock-fontified t invisible t)
5435 '(font-lock-fontified t face org-document-info-keyword)))
5436 (add-text-properties
5437 (match-beginning 6) (match-end 6)
5438 (if (string-equal dc1 "title:")
5439 '(font-lock-fontified t face org-document-title)
5440 '(font-lock-fontified t face org-document-info))))
5441 ((not (member (char-after beg) '(?\ ?\t)))
5442 ;; just any other in-buffer setting, but not indented
5443 (add-text-properties
5444 beg (1+ (match-end 0))
5445 '(font-lock-fontified t face org-meta-line))
5447 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
5448 "orgtbl:" "tblfm:" "tblname:" "results:"
5449 "call:" "header:" "headers:" "name:"))
5450 (and (match-end 4) (equal dc3 "attr")))
5451 (add-text-properties
5452 beg (match-end 0)
5453 '(font-lock-fontified t face org-meta-line))
5455 ((member dc3 '(" " ""))
5456 (add-text-properties
5457 beg (match-end 0)
5458 '(font-lock-fontified t face font-lock-comment-face)))
5459 (t nil))))))
5461 (defun org-activate-angle-links (limit)
5462 "Run through the buffer and add overlays to links."
5463 (if (re-search-forward org-angle-link-re limit t)
5464 (progn
5465 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5466 (add-text-properties (match-beginning 0) (match-end 0)
5467 (list 'mouse-face 'highlight
5468 'keymap org-mouse-map))
5469 (org-rear-nonsticky-at (match-end 0))
5470 t)))
5472 (defun org-activate-footnote-links (limit)
5473 "Run through the buffer and add overlays to footnotes."
5474 (let ((fn (org-footnote-next-reference-or-definition limit)))
5475 (when fn
5476 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5477 (org-remove-flyspell-overlays-in beg end)
5478 (add-text-properties beg end
5479 (list 'mouse-face 'highlight
5480 'keymap org-mouse-map
5481 'help-echo
5482 (if (= (point-at-bol) beg)
5483 "Footnote definition"
5484 "Footnote reference")
5485 'font-lock-fontified t
5486 'font-lock-multiline t
5487 'face 'org-footnote))))))
5489 (defun org-activate-bracket-links (limit)
5490 "Run through the buffer and add overlays to bracketed links."
5491 (if (re-search-forward org-bracket-link-regexp limit t)
5492 (let* ((help (concat "LINK: "
5493 (org-match-string-no-properties 1)))
5494 ;; FIXME: above we should remove the escapes.
5495 ;; but that requires another match, protecting match data,
5496 ;; a lot of overhead for font-lock.
5497 (ip (org-maybe-intangible
5498 (list 'invisible 'org-link
5499 'keymap org-mouse-map 'mouse-face 'highlight
5500 'font-lock-multiline t 'help-echo help)))
5501 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5502 'font-lock-multiline t 'help-echo help)))
5503 ;; We need to remove the invisible property here. Table narrowing
5504 ;; may have made some of this invisible.
5505 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5506 (remove-text-properties (match-beginning 0) (match-end 0)
5507 '(invisible nil))
5508 (if (match-end 3)
5509 (progn
5510 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5511 (org-rear-nonsticky-at (match-beginning 3))
5512 (add-text-properties (match-beginning 3) (match-end 3) vp)
5513 (org-rear-nonsticky-at (match-end 3))
5514 (add-text-properties (match-end 3) (match-end 0) ip)
5515 (org-rear-nonsticky-at (match-end 0)))
5516 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5517 (org-rear-nonsticky-at (match-beginning 1))
5518 (add-text-properties (match-beginning 1) (match-end 1) vp)
5519 (org-rear-nonsticky-at (match-end 1))
5520 (add-text-properties (match-end 1) (match-end 0) ip)
5521 (org-rear-nonsticky-at (match-end 0)))
5522 t)))
5524 (defun org-activate-dates (limit)
5525 "Run through the buffer and add overlays to dates."
5526 (if (re-search-forward org-tsr-regexp-both limit t)
5527 (progn
5528 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5529 (add-text-properties (match-beginning 0) (match-end 0)
5530 (list 'mouse-face 'highlight
5531 'keymap org-mouse-map))
5532 (org-rear-nonsticky-at (match-end 0))
5533 (when org-display-custom-times
5534 (if (match-end 3)
5535 (org-display-custom-time (match-beginning 3) (match-end 3)))
5536 (org-display-custom-time (match-beginning 1) (match-end 1)))
5537 t)))
5539 (defvar org-target-link-regexp nil
5540 "Regular expression matching radio targets in plain text.")
5541 (make-variable-buffer-local 'org-target-link-regexp)
5542 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5543 "Regular expression matching a link target.")
5544 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5545 "Regular expression matching a radio target.")
5546 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5547 "Regular expression matching any target.")
5549 (defun org-activate-target-links (limit)
5550 "Run through the buffer and add overlays to target matches."
5551 (when org-target-link-regexp
5552 (let ((case-fold-search t))
5553 (if (re-search-forward org-target-link-regexp limit t)
5554 (progn
5555 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5556 (add-text-properties (match-beginning 0) (match-end 0)
5557 (list 'mouse-face 'highlight
5558 'keymap org-mouse-map
5559 'help-echo "Radio target link"
5560 'org-linked-text t))
5561 (org-rear-nonsticky-at (match-end 0))
5562 t)))))
5564 (defun org-update-radio-target-regexp ()
5565 "Find all radio targets in this file and update the regular expression."
5566 (interactive)
5567 (when (memq 'radio org-activate-links)
5568 (setq org-target-link-regexp
5569 (org-make-target-link-regexp (org-all-targets 'radio)))
5570 (org-restart-font-lock)))
5572 (defun org-hide-wide-columns (limit)
5573 (let (s e)
5574 (setq s (text-property-any (point) (or limit (point-max))
5575 'org-cwidth t))
5576 (when s
5577 (setq e (next-single-property-change s 'org-cwidth))
5578 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5579 (goto-char e)
5580 t)))
5582 (defvar org-latex-and-specials-regexp nil
5583 "Regular expression for highlighting export special stuff.")
5584 (defvar org-match-substring-regexp)
5585 (defvar org-match-substring-with-braces-regexp)
5587 ;; This should be with the exporter code, but we also use if for font-locking
5588 (defconst org-export-html-special-string-regexps
5589 '(("\\\\-" . "&shy;")
5590 ("---\\([^-]\\)" . "&mdash;\\1")
5591 ("--\\([^-]\\)" . "&ndash;\\1")
5592 ("\\.\\.\\." . "&hellip;"))
5593 "Regular expressions for special string conversion.")
5596 (defun org-compute-latex-and-specials-regexp ()
5597 "Compute regular expression for stuff treated specially by exporters."
5598 (if (not org-highlight-latex-fragments-and-specials)
5599 (org-set-local 'org-latex-and-specials-regexp nil)
5600 (require 'org-exp)
5601 (let*
5602 ((matchers (plist-get org-format-latex-options :matchers))
5603 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5604 org-latex-regexps)))
5605 (org-export-allow-BIND nil)
5606 (options (org-combine-plists (org-default-export-plist)
5607 (org-infile-export-plist)))
5608 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5609 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5610 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5611 (org-export-html-expand (plist-get options :expand-quoted-html))
5612 (org-export-with-special-strings (plist-get options :special-strings))
5613 (re-sub
5614 (cond
5615 ((equal org-export-with-sub-superscripts '{})
5616 (list org-match-substring-with-braces-regexp))
5617 (org-export-with-sub-superscripts
5618 (list org-match-substring-regexp))
5619 (t nil)))
5620 (re-latex
5621 (if org-export-with-LaTeX-fragments
5622 (mapcar (lambda (x) (nth 1 x)) latexs)))
5623 (re-macros
5624 (if org-export-with-TeX-macros
5625 (list (concat "\\\\"
5626 (regexp-opt
5627 (append
5629 (delq nil
5630 (mapcar 'car-safe
5631 (append org-entities-user
5632 org-entities)))
5633 (if (boundp 'org-latex-entities)
5634 (mapcar (lambda (x)
5635 (or (car-safe x) x))
5636 org-latex-entities)
5637 nil))
5638 'words))) ; FIXME
5640 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5641 (re-special (if org-export-with-special-strings
5642 (mapcar (lambda (x) (car x))
5643 org-export-html-special-string-regexps)))
5644 (re-rest
5645 (delq nil
5646 (list
5647 (if org-export-html-expand "@<[^>\n]+>")
5648 ))))
5649 (org-set-local
5650 'org-latex-and-specials-regexp
5651 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5652 re-rest) "\\|")))))
5654 (defun org-do-latex-and-special-faces (limit)
5655 "Run through the buffer and add overlays to links."
5656 (when org-latex-and-specials-regexp
5657 (let (rtn d)
5658 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5659 limit t))
5660 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5661 'face))
5662 '(org-code org-verbatim underline)))
5663 (progn
5664 (setq rtn t
5665 d (cond ((member (char-after (1+ (match-beginning 0)))
5666 '(?_ ?^)) 1)
5667 (t 0)))
5668 (font-lock-prepend-text-property
5669 (+ d (match-beginning 0)) (match-end 0)
5670 'face 'org-latex-and-export-specials)
5671 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5672 '(font-lock-multiline t)))))
5673 rtn)))
5675 (defun org-restart-font-lock ()
5676 "Restart `font-lock-mode', to force refontification."
5677 (when (and (boundp 'font-lock-mode) font-lock-mode)
5678 (font-lock-mode -1)
5679 (font-lock-mode 1)))
5681 (defun org-all-targets (&optional radio)
5682 "Return a list of all targets in this file.
5683 With optional argument RADIO, only find radio targets."
5684 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5685 rtn)
5686 (save-excursion
5687 (goto-char (point-min))
5688 (while (re-search-forward re nil t)
5689 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5690 rtn)))
5692 (defun org-make-target-link-regexp (targets)
5693 "Make regular expression matching all strings in TARGETS.
5694 The regular expression finds the targets also if there is a line break
5695 between words."
5696 (and targets
5697 (concat
5698 "\\<\\("
5699 (mapconcat
5700 (lambda (x)
5701 (setq x (regexp-quote x))
5702 (while (string-match " +" x)
5703 (setq x (replace-match "\\s-+" t t x)))
5705 targets
5706 "\\|")
5707 "\\)\\>")))
5709 (defun org-activate-tags (limit)
5710 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5711 (progn
5712 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5713 (add-text-properties (match-beginning 1) (match-end 1)
5714 (list 'mouse-face 'highlight
5715 'keymap org-mouse-map))
5716 (org-rear-nonsticky-at (match-end 1))
5717 t)))
5719 (defun org-outline-level ()
5720 "Compute the outline level of the heading at point.
5721 This function assumes that the cursor is at the beginning of a line matched
5722 by `outline-regexp'. Otherwise it returns garbage.
5723 If this is called at a normal headline, the level is the number of stars.
5724 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5725 (save-excursion
5726 (looking-at org-outline-regexp)
5727 (1- (- (match-end 0) (match-beginning 0)))))
5729 (defvar org-font-lock-keywords nil)
5731 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5732 "Regular expression matching a property line.")
5734 (defvar org-font-lock-hook nil
5735 "Functions to be called for special font lock stuff.")
5737 (defvar org-font-lock-set-keywords-hook nil
5738 "Functions that can manipulate `org-font-lock-extra-keywords'.
5739 This is calles after `org-font-lock-extra-keywords' is defined, but before
5740 it is installed to be used by font lock. This can be useful if something
5741 needs to be inserted at a specific position in the font-lock sequence.")
5743 (defun org-font-lock-hook (limit)
5744 (run-hook-with-args 'org-font-lock-hook limit))
5746 (defun org-set-font-lock-defaults ()
5747 (let* ((em org-fontify-emphasized-text)
5748 (lk org-activate-links)
5749 (org-font-lock-extra-keywords
5750 (list
5751 ;; Call the hook
5752 '(org-font-lock-hook)
5753 ;; Headlines
5754 `(,(if org-fontify-whole-heading-line
5755 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5756 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5757 (1 (org-get-level-face 1))
5758 (2 (org-get-level-face 2))
5759 (3 (org-get-level-face 3)))
5760 ;; Table lines
5761 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5762 (1 'org-table t))
5763 ;; Table internals
5764 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5765 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5766 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5767 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5768 ;; Drawers
5769 (list org-drawer-regexp '(0 'org-special-keyword t))
5770 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5771 ;; Properties
5772 (list org-property-re
5773 '(1 'org-special-keyword t)
5774 '(3 'org-property-value t))
5775 ;; Links
5776 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5777 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5778 (if (memq 'plain lk) '(org-activate-plain-links))
5779 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5780 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5781 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5782 (if (memq 'footnote lk) '(org-activate-footnote-links))
5783 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5784 '(org-hide-wide-columns (0 nil append))
5785 ;; TODO keyword
5786 (list (format org-heading-keyword-regexp-format
5787 org-todo-regexp)
5788 '(2 (org-get-todo-face 2) t))
5789 ;; DONE
5790 (if org-fontify-done-headline
5791 (list (format org-heading-keyword-regexp-format
5792 (concat
5793 "\\("
5794 (mapconcat 'regexp-quote org-done-keywords "\\|")
5795 "\\)"))
5796 '(2 'org-headline-done t))
5797 nil)
5798 ;; Priorities
5799 '(org-font-lock-add-priority-faces)
5800 ;; Tags
5801 '(org-font-lock-add-tag-faces)
5802 ;; Special keywords
5803 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5804 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5805 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5806 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5807 ;; Emphasis
5808 (if em
5809 (if (featurep 'xemacs)
5810 '(org-do-emphasis-faces (0 nil append))
5811 '(org-do-emphasis-faces)))
5812 ;; Checkboxes
5813 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5814 1 'org-checkbox prepend)
5815 (if (cdr (assq 'checkbox org-list-automatic-rules))
5816 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5817 (0 (org-get-checkbox-statistics-face) t)))
5818 ;; Description list items
5819 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5820 1 'bold prepend)
5821 ;; ARCHIVEd headings
5822 (list (concat
5823 org-outline-regexp-bol
5824 "\\(.*:" org-archive-tag ":.*\\)")
5825 '(1 'org-archived prepend))
5826 ;; Specials
5827 '(org-do-latex-and-special-faces)
5828 '(org-fontify-entities)
5829 '(org-raise-scripts)
5830 ;; Code
5831 '(org-activate-code (1 'org-code t))
5832 ;; COMMENT
5833 (list (format org-heading-keyword-regexp-format
5834 (concat "\\("
5835 org-comment-string "\\|" org-quote-string
5836 "\\)"))
5837 '(2 'org-special-keyword t))
5838 '("^#.*" (0 'font-lock-comment-face t))
5839 ;; Blocks and meta lines
5840 '(org-fontify-meta-lines-and-blocks)
5842 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5843 (run-hooks 'org-font-lock-set-keywords-hook)
5844 ;; Now set the full font-lock-keywords
5845 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5846 (org-set-local 'font-lock-defaults
5847 '(org-font-lock-keywords t nil nil backward-paragraph))
5848 (kill-local-variable 'font-lock-keywords) nil))
5850 (defun org-toggle-pretty-entities ()
5851 "Toggle the composition display of entities as UTF8 characters."
5852 (interactive)
5853 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5854 (org-restart-font-lock)
5855 (if org-pretty-entities
5856 (message "Entities are displayed as UTF8 characers")
5857 (save-restriction
5858 (widen)
5859 (org-decompose-region (point-min) (point-max))
5860 (message "Entities are displayed plain"))))
5862 (defun org-fontify-entities (limit)
5863 "Find an entity to fontify."
5864 (let (ee)
5865 (when org-pretty-entities
5866 (catch 'match
5867 (while (re-search-forward
5868 "\\\\\\(frac[13][24]\\|[a-zA-Z]+\\)\\($\\|[^[:alpha:]\n]\\)"
5869 limit t)
5870 (if (and (not (org-in-indented-comment-line))
5871 (setq ee (org-entity-get (match-string 1)))
5872 (= (length (nth 6 ee)) 1))
5873 (progn
5874 (add-text-properties
5875 (match-beginning 0) (match-end 1)
5876 (list 'font-lock-fontified t))
5877 (compose-region (match-beginning 0) (match-end 1)
5878 (nth 6 ee) nil)
5879 (backward-char 1)
5880 (throw 'match t))))
5881 nil))))
5883 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5884 "Fontify string S like in Org-mode."
5885 (with-temp-buffer
5886 (insert s)
5887 (let ((org-odd-levels-only odd-levels))
5888 (org-mode)
5889 (font-lock-fontify-buffer)
5890 (buffer-string))))
5892 (defvar org-m nil)
5893 (defvar org-l nil)
5894 (defvar org-f nil)
5895 (defun org-get-level-face (n)
5896 "Get the right face for match N in font-lock matching of headlines."
5897 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5898 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5899 (if org-cycle-level-faces
5900 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5901 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5902 (cond
5903 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5904 ((eq n 2) org-f)
5905 (t (if org-level-color-stars-only nil org-f))))
5908 (defun org-get-todo-face (kwd)
5909 "Get the right face for a TODO keyword KWD.
5910 If KWD is a number, get the corresponding match group."
5911 (if (numberp kwd) (setq kwd (match-string kwd)))
5912 (or (org-face-from-face-or-color
5913 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5914 (and (member kwd org-done-keywords) 'org-done)
5915 'org-todo))
5917 (defun org-face-from-face-or-color (context inherit face-or-color)
5918 "Create a face list that inherits INHERIT, but sets the foreground color.
5919 When FACE-OR-COLOR is not a string, just return it."
5920 (if (stringp face-or-color)
5921 (list :inherit inherit
5922 (cdr (assoc context org-faces-easy-properties))
5923 face-or-color)
5924 face-or-color))
5926 (defun org-font-lock-add-tag-faces (limit)
5927 "Add the special tag faces."
5928 (when (and org-tag-faces org-tags-special-faces-re)
5929 (while (re-search-forward org-tags-special-faces-re limit t)
5930 (add-text-properties (match-beginning 1) (match-end 1)
5931 (list 'face (org-get-tag-face 1)
5932 'font-lock-fontified t))
5933 (backward-char 1))))
5935 (defun org-font-lock-add-priority-faces (limit)
5936 "Add the special priority faces."
5937 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5938 (add-text-properties
5939 (match-beginning 0) (match-end 0)
5940 (list 'face (or (org-face-from-face-or-color
5941 'priority 'org-special-keyword
5942 (cdr (assoc (char-after (match-beginning 1))
5943 org-priority-faces)))
5944 'org-special-keyword)
5945 'font-lock-fontified t))))
5947 (defun org-get-tag-face (kwd)
5948 "Get the right face for a TODO keyword KWD.
5949 If KWD is a number, get the corresponding match group."
5950 (if (numberp kwd) (setq kwd (match-string kwd)))
5951 (or (org-face-from-face-or-color
5952 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5953 'org-tag))
5955 (defun org-unfontify-region (beg end &optional maybe_loudly)
5956 "Remove fontification and activation overlays from links."
5957 (font-lock-default-unfontify-region beg end)
5958 (let* ((buffer-undo-list t)
5959 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5960 (inhibit-modification-hooks t)
5961 deactivate-mark buffer-file-name buffer-file-truename)
5962 (org-decompose-region beg end)
5963 (remove-text-properties beg end
5964 '(mouse-face t keymap t org-linked-text t
5965 invisible t intangible t
5966 org-no-flyspell t org-emphasis t))
5967 (org-remove-font-lock-display-properties beg end)))
5969 (defconst org-script-display '(((raise -0.3) (height 0.7))
5970 ((raise 0.3) (height 0.7))
5971 ((raise -0.5))
5972 ((raise 0.5)))
5973 "Display properties for showing superscripts and subscripts.")
5975 (defun org-remove-font-lock-display-properties (beg end)
5976 "Remove specific display properties that have been added by font lock.
5977 The will remove the raise properties that are used to show superscripts
5978 and subscripts."
5979 (let (next prop)
5980 (while (< beg end)
5981 (setq next (next-single-property-change beg 'display nil end)
5982 prop (get-text-property beg 'display))
5983 (if (member prop org-script-display)
5984 (put-text-property beg next 'display nil))
5985 (setq beg next))))
5987 (defun org-raise-scripts (limit)
5988 "Add raise properties to sub/superscripts."
5989 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
5990 (if (re-search-forward
5991 (if (eq org-use-sub-superscripts t)
5992 org-match-substring-regexp
5993 org-match-substring-with-braces-regexp)
5994 limit t)
5995 (let* ((pos (point)) table-p comment-p
5996 (mpos (match-beginning 3))
5997 (emph-p (get-text-property mpos 'org-emphasis))
5998 (link-p (get-text-property mpos 'mouse-face))
5999 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6000 (goto-char (point-at-bol))
6001 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6002 comment-p (org-looking-at-p "[ \t]*#"))
6003 (goto-char pos)
6004 ;; FIXME: Should we go back one character here, for a_b^c
6005 ;; (goto-char (1- pos)) ;????????????????????
6006 (if (or comment-p emph-p link-p keyw-p)
6008 (put-text-property (match-beginning 3) (match-end 0)
6009 'display
6010 (if (equal (char-after (match-beginning 2)) ?^)
6011 (nth (if table-p 3 1) org-script-display)
6012 (nth (if table-p 2 0) org-script-display)))
6013 (add-text-properties (match-beginning 2) (match-end 2)
6014 (list 'invisible t
6015 'org-dwidth t 'org-dwidth-n 1))
6016 (if (and (eq (char-after (match-beginning 3)) ?{)
6017 (eq (char-before (match-end 3)) ?}))
6018 (progn
6019 (add-text-properties
6020 (match-beginning 3) (1+ (match-beginning 3))
6021 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6022 (add-text-properties
6023 (1- (match-end 3)) (match-end 3)
6024 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6025 t)))))
6027 ;;;; Visibility cycling, including org-goto and indirect buffer
6029 ;;; Cycling
6031 (defvar org-cycle-global-status nil)
6032 (make-variable-buffer-local 'org-cycle-global-status)
6033 (defvar org-cycle-subtree-status nil)
6034 (make-variable-buffer-local 'org-cycle-subtree-status)
6036 ;;;###autoload
6038 (defvar org-inlinetask-min-level)
6040 (defun org-cycle (&optional arg)
6041 "TAB-action and visibility cycling for Org-mode.
6043 This is the command invoked in Org-mode by the TAB key. Its main purpose
6044 is outline visibility cycling, but it also invokes other actions
6045 in special contexts.
6047 - When this function is called with a prefix argument, rotate the entire
6048 buffer through 3 states (global cycling)
6049 1. OVERVIEW: Show only top-level headlines.
6050 2. CONTENTS: Show all headlines of all levels, but no body text.
6051 3. SHOW ALL: Show everything.
6052 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6053 determined by the variable `org-startup-folded', and by any VISIBILITY
6054 properties in the buffer.
6055 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6056 including any drawers.
6058 - When inside a table, re-align the table and move to the next field.
6060 - When point is at the beginning of a headline, rotate the subtree started
6061 by this line through 3 different states (local cycling)
6062 1. FOLDED: Only the main headline is shown.
6063 2. CHILDREN: The main headline and the direct children are shown.
6064 From this state, you can move to one of the children
6065 and zoom in further.
6066 3. SUBTREE: Show the entire subtree, including body text.
6067 If there is no subtree, switch directly from CHILDREN to FOLDED.
6069 - When point is at the beginning of an empty headline and the variable
6070 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6071 of the headline by demoting and promoting it to likely levels. This
6072 speeds up creation document structure by pressing TAB once or several
6073 times right after creating a new headline.
6075 - When there is a numeric prefix, go up to a heading with level ARG, do
6076 a `show-subtree' and return to the previous cursor position. If ARG
6077 is negative, go up that many levels.
6079 - When point is not at the beginning of a headline, execute the global
6080 binding for TAB, which is re-indenting the line. See the option
6081 `org-cycle-emulate-tab' for details.
6083 - Special case: if point is at the beginning of the buffer and there is
6084 no headline in line 1, this function will act as if called with prefix arg
6085 (C-u TAB, same as S-TAB) also when called without prefix arg.
6086 But only if also the variable `org-cycle-global-at-bob' is t."
6087 (interactive "P")
6088 (org-load-modules-maybe)
6089 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6090 (and org-cycle-level-after-item/entry-creation
6091 (or (org-cycle-level)
6092 (org-cycle-item-indentation))))
6093 (let* ((limit-level
6094 (or org-cycle-max-level
6095 (and (boundp 'org-inlinetask-min-level)
6096 org-inlinetask-min-level
6097 (1- org-inlinetask-min-level))))
6098 (nstars (and limit-level
6099 (if org-odd-levels-only
6100 (and limit-level (1- (* limit-level 2)))
6101 limit-level)))
6102 (org-outline-regexp
6103 (if (not (eq major-mode 'org-mode))
6104 outline-regexp
6105 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6106 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6107 (not (looking-at org-outline-regexp))))
6108 (org-cycle-hook
6109 (if bob-special
6110 (delq 'org-optimize-window-after-visibility-change
6111 (copy-sequence org-cycle-hook))
6112 org-cycle-hook))
6113 (pos (point)))
6115 (if (or bob-special (equal arg '(4)))
6116 ;; special case: use global cycling
6117 (setq arg t))
6119 (cond
6121 ((equal arg '(16))
6122 (setq last-command 'dummy)
6123 (org-set-startup-visibility)
6124 (message "Startup visibility, plus VISIBILITY properties"))
6126 ((equal arg '(64))
6127 (show-all)
6128 (message "Entire buffer visible, including drawers"))
6130 ;; Table: enter it or move to the next field.
6131 ((org-at-table-p 'any)
6132 (if (org-at-table.el-p)
6133 (message "Use C-c ' to edit table.el tables")
6134 (if arg (org-table-edit-field t)
6135 (org-table-justify-field-maybe)
6136 (call-interactively 'org-table-next-field))))
6138 ((run-hook-with-args-until-success
6139 'org-tab-after-check-for-table-hook))
6141 ;; Global cycling: delegate to `org-cycle-internal-global'.
6142 ((eq arg t) (org-cycle-internal-global))
6144 ;; Drawers: delegate to `org-flag-drawer'.
6145 ((and org-drawers org-drawer-regexp
6146 (save-excursion
6147 (beginning-of-line 1)
6148 (looking-at org-drawer-regexp)))
6149 (org-flag-drawer ; toggle block visibility
6150 (not (get-char-property (match-end 0) 'invisible))))
6152 ;; Show-subtree, ARG levels up from here.
6153 ((integerp arg)
6154 (save-excursion
6155 (org-back-to-heading)
6156 (outline-up-heading (if (< arg 0) (- arg)
6157 (- (funcall outline-level) arg)))
6158 (org-show-subtree)))
6160 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6161 ((and (featurep 'org-inlinetask)
6162 (org-inlinetask-at-task-p)
6163 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6164 (org-inlinetask-toggle-visibility))
6166 ((org-try-cdlatex-tab))
6168 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6169 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6170 (save-excursion (beginning-of-line 1)
6171 (looking-at org-outline-regexp)))
6172 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6173 (org-cycle-internal-local))
6175 ;; From there: TAB emulation and template completion.
6176 (buffer-read-only (org-back-to-heading))
6178 ((run-hook-with-args-until-success
6179 'org-tab-after-check-for-cycling-hook))
6181 ((org-try-structure-completion))
6183 ((run-hook-with-args-until-success
6184 'org-tab-before-tab-emulation-hook))
6186 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6187 (or (not (bolp))
6188 (not (looking-at org-outline-regexp))))
6189 (call-interactively (global-key-binding "\t")))
6191 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6192 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6193 (or (and (eq org-cycle-emulate-tab 'white)
6194 (= (match-end 0) (point-at-eol)))
6195 (and (eq org-cycle-emulate-tab 'whitestart)
6196 (>= (match-end 0) pos))))
6198 (eq org-cycle-emulate-tab t))
6199 (call-interactively (global-key-binding "\t")))
6201 (t (save-excursion
6202 (org-back-to-heading)
6203 (org-cycle)))))))
6205 (defun org-cycle-internal-global ()
6206 "Do the global cycling action."
6207 (cond
6208 ((and (eq last-command this-command)
6209 (eq org-cycle-global-status 'overview))
6210 ;; We just created the overview - now do table of contents
6211 ;; This can be slow in very large buffers, so indicate action
6212 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6213 (message "CONTENTS...")
6214 (org-content)
6215 (message "CONTENTS...done")
6216 (setq org-cycle-global-status 'contents)
6217 (run-hook-with-args 'org-cycle-hook 'contents))
6219 ((and (eq last-command this-command)
6220 (eq org-cycle-global-status 'contents))
6221 ;; We just showed the table of contents - now show everything
6222 (run-hook-with-args 'org-pre-cycle-hook 'all)
6223 (show-all)
6224 (message "SHOW ALL")
6225 (setq org-cycle-global-status 'all)
6226 (run-hook-with-args 'org-cycle-hook 'all))
6229 ;; Default action: go to overview
6230 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6231 (org-overview)
6232 (message "OVERVIEW")
6233 (setq org-cycle-global-status 'overview)
6234 (run-hook-with-args 'org-cycle-hook 'overview))))
6236 (defun org-cycle-internal-local ()
6237 "Do the local cycling action."
6238 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6239 ;; First, determine end of headline (EOH), end of subtree or item
6240 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6241 (save-excursion
6242 (if (org-at-item-p)
6243 (progn
6244 (beginning-of-line)
6245 (setq struct (org-list-struct))
6246 (setq eoh (point-at-eol))
6247 (setq eos (org-list-get-item-end-before-blank (point) struct))
6248 (setq has-children (org-list-has-child-p (point) struct)))
6249 (org-back-to-heading)
6250 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6251 (setq eos (save-excursion
6252 (org-end-of-subtree t)
6253 (unless (eobp)
6254 (skip-chars-forward " \t\n"))
6255 (if (eobp) (point) (1- (point)))))
6256 (setq has-children
6257 (or (save-excursion
6258 (let ((level (funcall outline-level)))
6259 (outline-next-heading)
6260 (and (org-at-heading-p t)
6261 (> (funcall outline-level) level))))
6262 (save-excursion
6263 (org-list-search-forward (org-item-beginning-re) eos t)))))
6264 ;; Determine end invisible part of buffer (EOL)
6265 (beginning-of-line 2)
6266 ;; XEmacs doesn't have `next-single-char-property-change'
6267 (if (featurep 'xemacs)
6268 (while (and (not (eobp)) ;; this is like `next-line'
6269 (get-char-property (1- (point)) 'invisible))
6270 (beginning-of-line 2))
6271 (while (and (not (eobp)) ;; this is like `next-line'
6272 (get-char-property (1- (point)) 'invisible))
6273 (goto-char (next-single-char-property-change (point) 'invisible))
6274 (and (eolp) (beginning-of-line 2))))
6275 (setq eol (point)))
6276 ;; Find out what to do next and set `this-command'
6277 (cond
6278 ((= eos eoh)
6279 ;; Nothing is hidden behind this heading
6280 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6281 (message "EMPTY ENTRY")
6282 (setq org-cycle-subtree-status nil)
6283 (save-excursion
6284 (goto-char eos)
6285 (outline-next-heading)
6286 (if (outline-invisible-p) (org-flag-heading nil))))
6287 ((and (or (>= eol eos)
6288 (not (string-match "\\S-" (buffer-substring eol eos))))
6289 (or has-children
6290 (not (setq children-skipped
6291 org-cycle-skip-children-state-if-no-children))))
6292 ;; Entire subtree is hidden in one line: children view
6293 (run-hook-with-args 'org-pre-cycle-hook 'children)
6294 (if (org-at-item-p)
6295 (org-list-set-item-visibility (point-at-bol) struct 'children)
6296 (org-show-entry)
6297 (show-children)
6298 ;; Fold every list in subtree to top-level items.
6299 (when (eq org-cycle-include-plain-lists 'integrate)
6300 (save-excursion
6301 (org-back-to-heading)
6302 (while (org-list-search-forward (org-item-beginning-re) eos t)
6303 (beginning-of-line 1)
6304 (let* ((struct (org-list-struct))
6305 (prevs (org-list-prevs-alist struct))
6306 (end (org-list-get-bottom-point struct)))
6307 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6308 (org-list-get-all-items (point) struct prevs))
6309 (goto-char end))))))
6310 (message "CHILDREN")
6311 (save-excursion
6312 (goto-char eos)
6313 (outline-next-heading)
6314 (if (outline-invisible-p) (org-flag-heading nil)))
6315 (setq org-cycle-subtree-status 'children)
6316 (run-hook-with-args 'org-cycle-hook 'children))
6317 ((or children-skipped
6318 (and (eq last-command this-command)
6319 (eq org-cycle-subtree-status 'children)))
6320 ;; We just showed the children, or no children are there,
6321 ;; now show everything.
6322 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6323 (outline-flag-region eoh eos nil)
6324 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6325 (setq org-cycle-subtree-status 'subtree)
6326 (run-hook-with-args 'org-cycle-hook 'subtree))
6328 ;; Default action: hide the subtree.
6329 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6330 (outline-flag-region eoh eos t)
6331 (message "FOLDED")
6332 (setq org-cycle-subtree-status 'folded)
6333 (run-hook-with-args 'org-cycle-hook 'folded)))))
6335 ;;;###autoload
6336 (defun org-global-cycle (&optional arg)
6337 "Cycle the global visibility. For details see `org-cycle'.
6338 With \\[universal-argument] prefix arg, switch to startup visibility.
6339 With a numeric prefix, show all headlines up to that level."
6340 (interactive "P")
6341 (let ((org-cycle-include-plain-lists
6342 (if (eq major-mode 'org-mode) org-cycle-include-plain-lists nil)))
6343 (cond
6344 ((integerp arg)
6345 (show-all)
6346 (hide-sublevels arg)
6347 (setq org-cycle-global-status 'contents))
6348 ((equal arg '(4))
6349 (org-set-startup-visibility)
6350 (message "Startup visibility, plus VISIBILITY properties."))
6352 (org-cycle '(4))))))
6354 (defun org-set-startup-visibility ()
6355 "Set the visibility required by startup options and properties."
6356 (cond
6357 ((eq org-startup-folded t)
6358 (org-cycle '(4)))
6359 ((eq org-startup-folded 'content)
6360 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6361 (org-cycle '(4)) (org-cycle '(4)))))
6362 (unless (eq org-startup-folded 'showeverything)
6363 (if org-hide-block-startup (org-hide-block-all))
6364 (org-set-visibility-according-to-property 'no-cleanup)
6365 (org-cycle-hide-archived-subtrees 'all)
6366 (org-cycle-hide-drawers 'all)
6367 (org-cycle-show-empty-lines t)))
6369 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6370 "Switch subtree visibilities according to :VISIBILITY: property."
6371 (interactive)
6372 (let (org-show-entry-below state)
6373 (save-excursion
6374 (goto-char (point-min))
6375 (while (re-search-forward
6376 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6377 nil t)
6378 (setq state (match-string 1))
6379 (save-excursion
6380 (org-back-to-heading t)
6381 (hide-subtree)
6382 (org-reveal)
6383 (cond
6384 ((equal state '("fold" "folded"))
6385 (hide-subtree))
6386 ((equal state "children")
6387 (org-show-hidden-entry)
6388 (show-children))
6389 ((equal state "content")
6390 (save-excursion
6391 (save-restriction
6392 (org-narrow-to-subtree)
6393 (org-content))))
6394 ((member state '("all" "showall"))
6395 (show-subtree)))))
6396 (unless no-cleanup
6397 (org-cycle-hide-archived-subtrees 'all)
6398 (org-cycle-hide-drawers 'all)
6399 (org-cycle-show-empty-lines 'all)))))
6401 ;; This function uses outline-regexp instead of the more fundamental
6402 ;; org-outline-regexp so that org-cycle-global works outside of Org
6403 ;; buffers, where outline-regexp is needed.
6404 (defun org-overview ()
6405 "Switch to overview mode, showing only top-level headlines.
6406 Really, this shows all headlines with level equal or greater than the level
6407 of the first headline in the buffer. This is important, because if the
6408 first headline is not level one, then (hide-sublevels 1) gives confusing
6409 results."
6410 (interactive)
6411 (let ((level (save-excursion
6412 (goto-char (point-min))
6413 (if (re-search-forward (concat "^" outline-regexp) nil t)
6414 (progn
6415 (goto-char (match-beginning 0))
6416 (funcall outline-level))))))
6417 (and level (hide-sublevels level))))
6419 (defun org-content (&optional arg)
6420 "Show all headlines in the buffer, like a table of contents.
6421 With numerical argument N, show content up to level N."
6422 (interactive "P")
6423 (save-excursion
6424 ;; Visit all headings and show their offspring
6425 (and (integerp arg) (org-overview))
6426 (goto-char (point-max))
6427 (catch 'exit
6428 (while (and (progn (condition-case nil
6429 (outline-previous-visible-heading 1)
6430 (error (goto-char (point-min))))
6432 (looking-at org-outline-regexp))
6433 (if (integerp arg)
6434 (show-children (1- arg))
6435 (show-branches))
6436 (if (bobp) (throw 'exit nil))))))
6439 (defun org-optimize-window-after-visibility-change (state)
6440 "Adjust the window after a change in outline visibility.
6441 This function is the default value of the hook `org-cycle-hook'."
6442 (when (get-buffer-window (current-buffer))
6443 (cond
6444 ((eq state 'content) nil)
6445 ((eq state 'all) nil)
6446 ((eq state 'folded) nil)
6447 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6448 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6450 (defun org-remove-empty-overlays-at (pos)
6451 "Remove outline overlays that do not contain non-white stuff."
6452 (mapc
6453 (lambda (o)
6454 (and (eq 'outline (overlay-get o 'invisible))
6455 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6456 (overlay-end o))))
6457 (delete-overlay o)))
6458 (overlays-at pos)))
6460 (defun org-clean-visibility-after-subtree-move ()
6461 "Fix visibility issues after moving a subtree."
6462 ;; First, find a reasonable region to look at:
6463 ;; Start two siblings above, end three below
6464 (let* ((beg (save-excursion
6465 (and (org-get-last-sibling)
6466 (org-get-last-sibling))
6467 (point)))
6468 (end (save-excursion
6469 (and (org-get-next-sibling)
6470 (org-get-next-sibling)
6471 (org-get-next-sibling))
6472 (if (org-at-heading-p)
6473 (point-at-eol)
6474 (point))))
6475 (level (looking-at "\\*+"))
6476 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6477 (save-excursion
6478 (save-restriction
6479 (narrow-to-region beg end)
6480 (when re
6481 ;; Properly fold already folded siblings
6482 (goto-char (point-min))
6483 (while (re-search-forward re nil t)
6484 (if (and (not (outline-invisible-p))
6485 (save-excursion
6486 (goto-char (point-at-eol)) (outline-invisible-p)))
6487 (hide-entry))))
6488 (org-cycle-show-empty-lines 'overview)
6489 (org-cycle-hide-drawers 'overview)))))
6491 (defun org-cycle-show-empty-lines (state)
6492 "Show empty lines above all visible headlines.
6493 The region to be covered depends on STATE when called through
6494 `org-cycle-hook'. Lisp program can use t for STATE to get the
6495 entire buffer covered. Note that an empty line is only shown if there
6496 are at least `org-cycle-separator-lines' empty lines before the headline."
6497 (when (not (= org-cycle-separator-lines 0))
6498 (save-excursion
6499 (let* ((n (abs org-cycle-separator-lines))
6500 (re (cond
6501 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6502 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6503 (t (let ((ns (number-to-string (- n 2))))
6504 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6505 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6506 beg end b e)
6507 (cond
6508 ((memq state '(overview contents t))
6509 (setq beg (point-min) end (point-max)))
6510 ((memq state '(children folded))
6511 (setq beg (point) end (progn (org-end-of-subtree t t)
6512 (beginning-of-line 2)
6513 (point)))))
6514 (when beg
6515 (goto-char beg)
6516 (while (re-search-forward re end t)
6517 (unless (get-char-property (match-end 1) 'invisible)
6518 (setq e (match-end 1))
6519 (if (< org-cycle-separator-lines 0)
6520 (setq b (save-excursion
6521 (goto-char (match-beginning 0))
6522 (org-back-over-empty-lines)
6523 (if (save-excursion
6524 (goto-char (max (point-min) (1- (point))))
6525 (org-on-heading-p))
6526 (1- (point))
6527 (point))))
6528 (setq b (match-beginning 1)))
6529 (outline-flag-region b e nil)))))))
6530 ;; Never hide empty lines at the end of the file.
6531 (save-excursion
6532 (goto-char (point-max))
6533 (outline-previous-heading)
6534 (outline-end-of-heading)
6535 (if (and (looking-at "[ \t\n]+")
6536 (= (match-end 0) (point-max)))
6537 (outline-flag-region (point) (match-end 0) nil))))
6539 (defun org-show-empty-lines-in-parent ()
6540 "Move to the parent and re-show empty lines before visible headlines."
6541 (save-excursion
6542 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6543 (org-cycle-show-empty-lines context))))
6545 (defun org-files-list ()
6546 "Return `org-agenda-files' list, plus all open org-mode files.
6547 This is useful for operations that need to scan all of a user's
6548 open and agenda-wise Org files."
6549 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6550 (dolist (buf (buffer-list))
6551 (with-current-buffer buf
6552 (if (and (eq major-mode 'org-mode) (buffer-file-name))
6553 (let ((file (expand-file-name (buffer-file-name))))
6554 (unless (member file files)
6555 (push file files))))))
6556 files))
6558 (defsubst org-entry-beginning-position ()
6559 "Return the beginning position of the current entry."
6560 (save-excursion (outline-back-to-heading t) (point)))
6562 (defsubst org-entry-end-position ()
6563 "Return the end position of the current entry."
6564 (save-excursion (outline-next-heading) (point)))
6566 (defun org-cycle-hide-drawers (state)
6567 "Re-hide all drawers after a visibility state change."
6568 (when (and (eq major-mode 'org-mode)
6569 (not (memq state '(overview folded contents))))
6570 (save-excursion
6571 (let* ((globalp (memq state '(contents all)))
6572 (beg (if globalp (point-min) (point)))
6573 (end (if globalp (point-max)
6574 (if (eq state 'children)
6575 (save-excursion (outline-next-heading) (point))
6576 (org-end-of-subtree t)))))
6577 (goto-char beg)
6578 (while (re-search-forward org-drawer-regexp end t)
6579 (org-flag-drawer t))))))
6581 (defun org-flag-drawer (flag)
6582 (save-excursion
6583 (beginning-of-line 1)
6584 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6585 (let ((b (match-end 0)))
6586 (if (re-search-forward
6587 "^[ \t]*:END:"
6588 (save-excursion (outline-next-heading) (point)) t)
6589 (outline-flag-region b (point-at-eol) flag)
6590 (error ":END: line missing at position %s" b))))))
6592 (defun org-subtree-end-visible-p ()
6593 "Is the end of the current subtree visible?"
6594 (pos-visible-in-window-p
6595 (save-excursion (org-end-of-subtree t) (point))))
6597 (defun org-first-headline-recenter (&optional N)
6598 "Move cursor to the first headline and recenter the headline.
6599 Optional argument N means put the headline into the Nth line of the window."
6600 (goto-char (point-min))
6601 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6602 (beginning-of-line)
6603 (recenter (prefix-numeric-value N))))
6605 ;;; Saving and restoring visibility
6607 (defun org-outline-overlay-data (&optional use-markers)
6608 "Return a list of the locations of all outline overlays.
6609 These are overlays with the `invisible' property value `outline'.
6610 The return value is a list of cons cells, with start and stop
6611 positions for each overlay.
6612 If USE-MARKERS is set, return the positions as markers."
6613 (let (beg end)
6614 (save-excursion
6615 (save-restriction
6616 (widen)
6617 (delq nil
6618 (mapcar (lambda (o)
6619 (when (eq (overlay-get o 'invisible) 'outline)
6620 (setq beg (overlay-start o)
6621 end (overlay-end o))
6622 (and beg end (> end beg)
6623 (if use-markers
6624 (cons (move-marker (make-marker) beg)
6625 (move-marker (make-marker) end))
6626 (cons beg end)))))
6627 (overlays-in (point-min) (point-max))))))))
6629 (defun org-set-outline-overlay-data (data)
6630 "Create visibility overlays for all positions in DATA.
6631 DATA should have been made by `org-outline-overlay-data'."
6632 (let (o)
6633 (save-excursion
6634 (save-restriction
6635 (widen)
6636 (show-all)
6637 (mapc (lambda (c)
6638 (outline-flag-region (car c) (cdr c) t))
6639 data)))))
6641 ;;; Folding of blocks
6643 (defvar org-hide-block-overlays nil
6644 "Overlays hiding blocks.")
6645 (make-variable-buffer-local 'org-hide-block-overlays)
6647 (defun org-block-map (function &optional start end)
6648 "Call FUNCTION at the head of all source blocks in the current buffer.
6649 Optional arguments START and END can be used to limit the range."
6650 (let ((start (or start (point-min)))
6651 (end (or end (point-max))))
6652 (save-excursion
6653 (goto-char start)
6654 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6655 (save-excursion
6656 (save-match-data
6657 (goto-char (match-beginning 0))
6658 (funcall function)))))))
6660 (defun org-hide-block-toggle-all ()
6661 "Toggle the visibility of all blocks in the current buffer."
6662 (org-block-map #'org-hide-block-toggle))
6664 (defun org-hide-block-all ()
6665 "Fold all blocks in the current buffer."
6666 (interactive)
6667 (org-show-block-all)
6668 (org-block-map #'org-hide-block-toggle-maybe))
6670 (defun org-show-block-all ()
6671 "Unfold all blocks in the current buffer."
6672 (interactive)
6673 (mapc 'delete-overlay org-hide-block-overlays)
6674 (setq org-hide-block-overlays nil))
6676 (defun org-hide-block-toggle-maybe ()
6677 "Toggle visibility of block at point."
6678 (interactive)
6679 (let ((case-fold-search t))
6680 (if (save-excursion
6681 (beginning-of-line 1)
6682 (looking-at org-block-regexp))
6683 (progn (org-hide-block-toggle)
6684 t) ;; to signal that we took action
6685 nil))) ;; to signal that we did not
6687 (defun org-hide-block-toggle (&optional force)
6688 "Toggle the visibility of the current block."
6689 (interactive)
6690 (save-excursion
6691 (beginning-of-line)
6692 (if (re-search-forward org-block-regexp nil t)
6693 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6694 (end (match-end 0)) ;; end of entire body
6696 (if (memq t (mapcar (lambda (overlay)
6697 (eq (overlay-get overlay 'invisible)
6698 'org-hide-block))
6699 (overlays-at start)))
6700 (if (or (not force) (eq force 'off))
6701 (mapc (lambda (ov)
6702 (when (member ov org-hide-block-overlays)
6703 (setq org-hide-block-overlays
6704 (delq ov org-hide-block-overlays)))
6705 (when (eq (overlay-get ov 'invisible)
6706 'org-hide-block)
6707 (delete-overlay ov)))
6708 (overlays-at start)))
6709 (setq ov (make-overlay start end))
6710 (overlay-put ov 'invisible 'org-hide-block)
6711 ;; make the block accessible to isearch
6712 (overlay-put
6713 ov 'isearch-open-invisible
6714 (lambda (ov)
6715 (when (member ov org-hide-block-overlays)
6716 (setq org-hide-block-overlays
6717 (delq ov org-hide-block-overlays)))
6718 (when (eq (overlay-get ov 'invisible)
6719 'org-hide-block)
6720 (delete-overlay ov))))
6721 (push ov org-hide-block-overlays)))
6722 (error "Not looking at a source block"))))
6724 ;; org-tab-after-check-for-cycling-hook
6725 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6726 ;; Remove overlays when changing major mode
6727 (add-hook 'org-mode-hook
6728 (lambda () (org-add-hook 'change-major-mode-hook
6729 'org-show-block-all 'append 'local)))
6731 ;;; Org-goto
6733 (defvar org-goto-window-configuration nil)
6734 (defvar org-goto-marker nil)
6735 (defvar org-goto-map
6736 (let ((map (make-sparse-keymap)))
6737 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6738 (while (setq cmd (pop cmds))
6739 (substitute-key-definition cmd cmd map global-map)))
6740 (suppress-keymap map)
6741 (org-defkey map "\C-m" 'org-goto-ret)
6742 (org-defkey map [(return)] 'org-goto-ret)
6743 (org-defkey map [(left)] 'org-goto-left)
6744 (org-defkey map [(right)] 'org-goto-right)
6745 (org-defkey map [(control ?g)] 'org-goto-quit)
6746 (org-defkey map "\C-i" 'org-cycle)
6747 (org-defkey map [(tab)] 'org-cycle)
6748 (org-defkey map [(down)] 'outline-next-visible-heading)
6749 (org-defkey map [(up)] 'outline-previous-visible-heading)
6750 (if org-goto-auto-isearch
6751 (if (fboundp 'define-key-after)
6752 (define-key-after map [t] 'org-goto-local-auto-isearch)
6753 nil)
6754 (org-defkey map "q" 'org-goto-quit)
6755 (org-defkey map "n" 'outline-next-visible-heading)
6756 (org-defkey map "p" 'outline-previous-visible-heading)
6757 (org-defkey map "f" 'outline-forward-same-level)
6758 (org-defkey map "b" 'outline-backward-same-level)
6759 (org-defkey map "u" 'outline-up-heading))
6760 (org-defkey map "/" 'org-occur)
6761 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6762 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6763 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6764 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6765 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6766 map))
6768 (defconst org-goto-help
6769 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6770 RET=jump to location [Q]uit and return to previous location
6771 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6773 (defvar org-goto-start-pos) ; dynamically scoped parameter
6775 ;; FIXME: Docstring does not mention both interfaces
6776 (defun org-goto (&optional alternative-interface)
6777 "Look up a different location in the current file, keeping current visibility.
6779 When you want look-up or go to a different location in a document, the
6780 fastest way is often to fold the entire buffer and then dive into the tree.
6781 This method has the disadvantage, that the previous location will be folded,
6782 which may not be what you want.
6784 This command works around this by showing a copy of the current buffer
6785 in an indirect buffer, in overview mode. You can dive into the tree in
6786 that copy, use org-occur and incremental search to find a location.
6787 When pressing RET or `Q', the command returns to the original buffer in
6788 which the visibility is still unchanged. After RET is will also jump to
6789 the location selected in the indirect buffer and expose the headline
6790 hierarchy above."
6791 (interactive "P")
6792 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6793 (org-refile-use-outline-path t)
6794 (org-refile-target-verify-function nil)
6795 (interface
6796 (if (not alternative-interface)
6797 org-goto-interface
6798 (if (eq org-goto-interface 'outline)
6799 'outline-path-completion
6800 'outline)))
6801 (org-goto-start-pos (point))
6802 (selected-point
6803 (if (eq interface 'outline)
6804 (car (org-get-location (current-buffer) org-goto-help))
6805 (let ((pa (org-refile-get-location "Goto")))
6806 (org-refile-check-position pa)
6807 (nth 3 pa)))))
6808 (if selected-point
6809 (progn
6810 (org-mark-ring-push org-goto-start-pos)
6811 (goto-char selected-point)
6812 (if (or (outline-invisible-p) (org-invisible-p2))
6813 (org-show-context 'org-goto)))
6814 (message "Quit"))))
6816 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6817 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6818 (defvar org-goto-local-auto-isearch-map) ; defined below
6820 (defun org-get-location (buf help)
6821 "Let the user select a location in the Org-mode buffer BUF.
6822 This function uses a recursive edit. It returns the selected position
6823 or nil."
6824 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6825 (isearch-hide-immediately nil)
6826 (isearch-search-fun-function
6827 (lambda () 'org-goto-local-search-headings))
6828 (org-goto-selected-point org-goto-exit-command)
6829 (pop-up-frames nil)
6830 (special-display-buffer-names nil)
6831 (special-display-regexps nil)
6832 (special-display-function nil))
6833 (save-excursion
6834 (save-window-excursion
6835 (delete-other-windows)
6836 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6837 (org-pop-to-buffer-same-window
6838 (condition-case nil
6839 (make-indirect-buffer (current-buffer) "*org-goto*")
6840 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6841 (with-output-to-temp-buffer "*Help*"
6842 (princ help))
6843 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6844 (setq buffer-read-only nil)
6845 (let ((org-startup-truncated t)
6846 (org-startup-folded nil)
6847 (org-startup-align-all-tables nil))
6848 (org-mode)
6849 (org-overview))
6850 (setq buffer-read-only t)
6851 (if (and (boundp 'org-goto-start-pos)
6852 (integer-or-marker-p org-goto-start-pos))
6853 (let ((org-show-hierarchy-above t)
6854 (org-show-siblings t)
6855 (org-show-following-heading t))
6856 (goto-char org-goto-start-pos)
6857 (and (outline-invisible-p) (org-show-context)))
6858 (goto-char (point-min)))
6859 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6860 (message "Select location and press RET")
6861 (use-local-map org-goto-map)
6862 (recursive-edit)
6864 (kill-buffer "*org-goto*")
6865 (cons org-goto-selected-point org-goto-exit-command)))
6867 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6868 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6869 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6870 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6872 (defun org-goto-local-search-headings (string bound noerror)
6873 "Search and make sure that any matches are in headlines."
6874 (catch 'return
6875 (while (if isearch-forward
6876 (search-forward string bound noerror)
6877 (search-backward string bound noerror))
6878 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6879 (and (member :headline context)
6880 (not (member :tags context))))
6881 (throw 'return (point))))))
6883 (defun org-goto-local-auto-isearch ()
6884 "Start isearch."
6885 (interactive)
6886 (goto-char (point-min))
6887 (let ((keys (this-command-keys)))
6888 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6889 (isearch-mode t)
6890 (isearch-process-search-char (string-to-char keys)))))
6892 (defun org-goto-ret (&optional arg)
6893 "Finish `org-goto' by going to the new location."
6894 (interactive "P")
6895 (setq org-goto-selected-point (point)
6896 org-goto-exit-command 'return)
6897 (throw 'exit nil))
6899 (defun org-goto-left ()
6900 "Finish `org-goto' by going to the new location."
6901 (interactive)
6902 (if (org-on-heading-p)
6903 (progn
6904 (beginning-of-line 1)
6905 (setq org-goto-selected-point (point)
6906 org-goto-exit-command 'left)
6907 (throw 'exit nil))
6908 (error "Not on a heading")))
6910 (defun org-goto-right ()
6911 "Finish `org-goto' by going to the new location."
6912 (interactive)
6913 (if (org-on-heading-p)
6914 (progn
6915 (setq org-goto-selected-point (point)
6916 org-goto-exit-command 'right)
6917 (throw 'exit nil))
6918 (error "Not on a heading")))
6920 (defun org-goto-quit ()
6921 "Finish `org-goto' without cursor motion."
6922 (interactive)
6923 (setq org-goto-selected-point nil)
6924 (setq org-goto-exit-command 'quit)
6925 (throw 'exit nil))
6927 ;;; Indirect buffer display of subtrees
6929 (defvar org-indirect-dedicated-frame nil
6930 "This is the frame being used for indirect tree display.")
6931 (defvar org-last-indirect-buffer nil)
6933 (defun org-tree-to-indirect-buffer (&optional arg)
6934 "Create indirect buffer and narrow it to current subtree.
6935 With numerical prefix ARG, go up to this level and then take that tree.
6936 If ARG is negative, go up that many levels.
6937 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6938 indirect buffer previously made with this command, to avoid proliferation of
6939 indirect buffers. However, when you call the command with a \
6940 \\[universal-argument] prefix, or
6941 when `org-indirect-buffer-display' is `new-frame', the last buffer
6942 is kept so that you can work with several indirect buffers at the same time.
6943 If `org-indirect-buffer-display' is `dedicated-frame', the \
6944 \\[universal-argument] prefix also
6945 requests that a new frame be made for the new buffer, so that the dedicated
6946 frame is not changed."
6947 (interactive "P")
6948 (let ((cbuf (current-buffer))
6949 (cwin (selected-window))
6950 (pos (point))
6951 beg end level heading ibuf)
6952 (save-excursion
6953 (org-back-to-heading t)
6954 (when (numberp arg)
6955 (setq level (org-outline-level))
6956 (if (< arg 0) (setq arg (+ level arg)))
6957 (while (> (setq level (org-outline-level)) arg)
6958 (outline-up-heading 1 t)))
6959 (setq beg (point)
6960 heading (org-get-heading))
6961 (org-end-of-subtree t t)
6962 (if (org-on-heading-p) (backward-char 1))
6963 (setq end (point)))
6964 (if (and (buffer-live-p org-last-indirect-buffer)
6965 (not (eq org-indirect-buffer-display 'new-frame))
6966 (not arg))
6967 (kill-buffer org-last-indirect-buffer))
6968 (setq ibuf (org-get-indirect-buffer cbuf)
6969 org-last-indirect-buffer ibuf)
6970 (cond
6971 ((or (eq org-indirect-buffer-display 'new-frame)
6972 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6973 (select-frame (make-frame))
6974 (delete-other-windows)
6975 (org-pop-to-buffer-same-window ibuf)
6976 (org-set-frame-title heading))
6977 ((eq org-indirect-buffer-display 'dedicated-frame)
6978 (raise-frame
6979 (select-frame (or (and org-indirect-dedicated-frame
6980 (frame-live-p org-indirect-dedicated-frame)
6981 org-indirect-dedicated-frame)
6982 (setq org-indirect-dedicated-frame (make-frame)))))
6983 (delete-other-windows)
6984 (org-pop-to-buffer-same-window ibuf)
6985 (org-set-frame-title (concat "Indirect: " heading)))
6986 ((eq org-indirect-buffer-display 'current-window)
6987 (org-pop-to-buffer-same-window ibuf))
6988 ((eq org-indirect-buffer-display 'other-window)
6989 (pop-to-buffer ibuf))
6990 (t (error "Invalid value")))
6991 (if (featurep 'xemacs)
6992 (save-excursion (org-mode) (turn-on-font-lock)))
6993 (narrow-to-region beg end)
6994 (show-all)
6995 (goto-char pos)
6996 (run-hook-with-args 'org-cycle-hook 'all)
6997 (and (window-live-p cwin) (select-window cwin))))
6999 (defun org-get-indirect-buffer (&optional buffer)
7000 (setq buffer (or buffer (current-buffer)))
7001 (let ((n 1) (base (buffer-name buffer)) bname)
7002 (while (buffer-live-p
7003 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7004 (setq n (1+ n)))
7005 (condition-case nil
7006 (make-indirect-buffer buffer bname 'clone)
7007 (error (make-indirect-buffer buffer bname)))))
7009 (defun org-set-frame-title (title)
7010 "Set the title of the current frame to the string TITLE."
7011 ;; FIXME: how to name a single frame in XEmacs???
7012 (unless (featurep 'xemacs)
7013 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7015 ;;;; Structure editing
7017 ;;; Inserting headlines
7019 (defun org-previous-line-empty-p ()
7020 (save-excursion
7021 (and (not (bobp))
7022 (or (beginning-of-line 0) t)
7023 (save-match-data
7024 (looking-at "[ \t]*$")))))
7026 (defun org-insert-heading (&optional force-heading invisible-ok)
7027 "Insert a new heading or item with same depth at point.
7028 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7029 If point is at the beginning of a headline, insert a sibling before the
7030 current headline. If point is not at the beginning, split the line,
7031 create the new headline with the text in the current line after point
7032 \(but see also the variable `org-M-RET-may-split-line').
7034 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7035 This is important for non-interactive uses of the command."
7036 (interactive "P")
7037 (if (or (= (buffer-size) 0)
7038 (and (not (save-excursion
7039 (and (ignore-errors (org-back-to-heading invisible-ok))
7040 (org-on-heading-p))))
7041 (or force-heading (not (org-in-item-p)))))
7042 (progn
7043 (insert "\n* ")
7044 (run-hooks 'org-insert-heading-hook))
7045 (when (or force-heading (not (org-insert-item)))
7046 (let* ((empty-line-p nil)
7047 (level nil)
7048 (on-heading (org-on-heading-p))
7049 (head (save-excursion
7050 (condition-case nil
7051 (progn
7052 (org-back-to-heading invisible-ok)
7053 (when (and (not on-heading)
7054 (featurep 'org-inlinetask)
7055 (integerp org-inlinetask-min-level)
7056 (>= (length (match-string 0))
7057 org-inlinetask-min-level))
7058 ;; Find a heading level before the inline task
7059 (while (and (setq level (org-up-heading-safe))
7060 (>= level org-inlinetask-min-level)))
7061 (if (org-on-heading-p)
7062 (org-back-to-heading invisible-ok)
7063 (error "This should not happen")))
7064 (setq empty-line-p (org-previous-line-empty-p))
7065 (match-string 0))
7066 (error "*"))))
7067 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7068 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7069 pos hide-previous previous-pos)
7070 (cond
7071 ((and (org-on-heading-p) (bolp)
7072 (or (bobp)
7073 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7074 ;; insert before the current line
7075 (open-line (if blank 2 1)))
7076 ((and (bolp)
7077 (not org-insert-heading-respect-content)
7078 (or (bobp)
7079 (save-excursion
7080 (backward-char 1) (not (outline-invisible-p)))))
7081 ;; insert right here
7082 nil)
7084 ;; somewhere in the line
7085 (save-excursion
7086 (setq previous-pos (point-at-bol))
7087 (end-of-line)
7088 (setq hide-previous (outline-invisible-p)))
7089 (and org-insert-heading-respect-content (org-show-subtree))
7090 (let ((split
7091 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7092 (save-excursion
7093 (let ((p (point)))
7094 (goto-char (point-at-bol))
7095 (and (looking-at org-complex-heading-regexp)
7096 (match-beginning 4)
7097 (> p (match-beginning 4)))))))
7098 tags pos)
7099 (cond
7100 (org-insert-heading-respect-content
7101 (org-end-of-subtree nil t)
7102 (when (featurep 'org-inlinetask)
7103 (while (and (not (eobp))
7104 (looking-at "\\(\\*+\\)[ \t]+")
7105 (>= (length (match-string 1))
7106 org-inlinetask-min-level))
7107 (org-end-of-subtree nil t)))
7108 (or (bolp) (newline))
7109 (or (org-previous-line-empty-p)
7110 (and blank (newline)))
7111 (open-line 1))
7112 ((org-on-heading-p)
7113 (when hide-previous
7114 (show-children)
7115 (org-show-entry))
7116 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7117 (setq tags (and (match-end 2) (match-string 2)))
7118 (and (match-end 1)
7119 (delete-region (match-beginning 1) (match-end 1)))
7120 (setq pos (point-at-bol))
7121 (or split (end-of-line 1))
7122 (delete-horizontal-space)
7123 (if (string-match "\\`\\*+\\'"
7124 (buffer-substring (point-at-bol) (point)))
7125 (insert " "))
7126 (newline (if blank 2 1))
7127 (when tags
7128 (save-excursion
7129 (goto-char pos)
7130 (end-of-line 1)
7131 (insert " " tags)
7132 (org-set-tags nil 'align))))
7134 (or split (end-of-line 1))
7135 (newline (if blank 2 1)))))))
7136 (insert head) (just-one-space)
7137 (setq pos (point))
7138 (end-of-line 1)
7139 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7140 (when (and org-insert-heading-respect-content hide-previous)
7141 (save-excursion
7142 (goto-char previous-pos)
7143 (hide-subtree)))
7144 (run-hooks 'org-insert-heading-hook)))))
7146 (defun org-get-heading (&optional no-tags no-todo)
7147 "Return the heading of the current entry, without the stars.
7148 When NO-TAGS is non-nil, don't include tags.
7149 When NO-TODO is non-nil, don't include TODO keywords."
7150 (save-excursion
7151 (org-back-to-heading t)
7152 (cond
7153 ((and no-tags no-todo)
7154 (looking-at org-complex-heading-regexp)
7155 (match-string 4))
7156 (no-tags
7157 (looking-at (concat org-outline-regexp
7158 "\\(.*?\\)"
7159 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7160 (match-string 1))
7161 (no-todo
7162 (looking-at org-todo-line-regexp)
7163 (match-string 3))
7164 (t (looking-at org-heading-regexp)
7165 (match-string 2)))))
7167 (defun org-heading-components ()
7168 "Return the components of the current heading.
7169 This is a list with the following elements:
7170 - the level as an integer
7171 - the reduced level, different if `org-odd-levels-only' is set.
7172 - the TODO keyword, or nil
7173 - the priority character, like ?A, or nil if no priority is given
7174 - the headline text itself, or the tags string if no headline text
7175 - the tags string, or nil."
7176 (save-excursion
7177 (org-back-to-heading t)
7178 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7179 (list (length (match-string 1))
7180 (org-reduced-level (length (match-string 1)))
7181 (org-match-string-no-properties 2)
7182 (and (match-end 3) (aref (match-string 3) 2))
7183 (org-match-string-no-properties 4)
7184 (org-match-string-no-properties 5)))))
7186 (defun org-get-entry ()
7187 "Get the entry text, after heading, entire subtree."
7188 (save-excursion
7189 (org-back-to-heading t)
7190 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7192 (defun org-insert-heading-after-current ()
7193 "Insert a new heading with same level as current, after current subtree."
7194 (interactive)
7195 (org-back-to-heading)
7196 (org-insert-heading)
7197 (org-move-subtree-down)
7198 (end-of-line 1))
7200 (defun org-insert-heading-respect-content ()
7201 (interactive)
7202 (let ((org-insert-heading-respect-content t))
7203 (org-insert-heading t)))
7205 (defun org-insert-todo-heading-respect-content (&optional force-state)
7206 (interactive "P")
7207 (let ((org-insert-heading-respect-content t))
7208 (org-insert-todo-heading force-state t)))
7210 (defun org-insert-todo-heading (arg &optional force-heading)
7211 "Insert a new heading with the same level and TODO state as current heading.
7212 If the heading has no TODO state, or if the state is DONE, use the first
7213 state (TODO by default). Also with prefix arg, force first state."
7214 (interactive "P")
7215 (when (or force-heading (not (org-insert-item 'checkbox)))
7216 (org-insert-heading force-heading)
7217 (save-excursion
7218 (org-back-to-heading)
7219 (outline-previous-heading)
7220 (looking-at org-todo-line-regexp))
7221 (let*
7222 ((new-mark-x
7223 (if (or arg
7224 (not (match-beginning 2))
7225 (member (match-string 2) org-done-keywords))
7226 (car org-todo-keywords-1)
7227 (match-string 2)))
7228 (new-mark
7230 (run-hook-with-args-until-success
7231 'org-todo-get-default-hook new-mark-x nil)
7232 new-mark-x)))
7233 (beginning-of-line 1)
7234 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7235 (if org-treat-insert-todo-heading-as-state-change
7236 (org-todo new-mark)
7237 (insert new-mark " "))))
7238 (when org-provide-todo-statistics
7239 (org-update-parent-todo-statistics))))
7241 (defun org-insert-subheading (arg)
7242 "Insert a new subheading and demote it.
7243 Works for outline headings and for plain lists alike."
7244 (interactive "P")
7245 (org-insert-heading arg)
7246 (cond
7247 ((org-on-heading-p) (org-do-demote))
7248 ((org-at-item-p) (org-indent-item))))
7250 (defun org-insert-todo-subheading (arg)
7251 "Insert a new subheading with TODO keyword or checkbox and demote it.
7252 Works for outline headings and for plain lists alike."
7253 (interactive "P")
7254 (org-insert-todo-heading arg)
7255 (cond
7256 ((org-on-heading-p) (org-do-demote))
7257 ((org-at-item-p) (org-indent-item))))
7259 ;;; Promotion and Demotion
7261 (defvar org-after-demote-entry-hook nil
7262 "Hook run after an entry has been demoted.
7263 The cursor will be at the beginning of the entry.
7264 When a subtree is being demoted, the hook will be called for each node.")
7266 (defvar org-after-promote-entry-hook nil
7267 "Hook run after an entry has been promoted.
7268 The cursor will be at the beginning of the entry.
7269 When a subtree is being promoted, the hook will be called for each node.")
7271 (defun org-promote-subtree ()
7272 "Promote the entire subtree.
7273 See also `org-promote'."
7274 (interactive)
7275 (save-excursion
7276 (org-with-limited-levels (org-map-tree 'org-promote)))
7277 (org-fix-position-after-promote))
7279 (defun org-demote-subtree ()
7280 "Demote the entire subtree. See `org-demote'.
7281 See also `org-promote'."
7282 (interactive)
7283 (save-excursion
7284 (org-with-limited-levels (org-map-tree 'org-demote)))
7285 (org-fix-position-after-promote))
7288 (defun org-do-promote ()
7289 "Promote the current heading higher up the tree.
7290 If the region is active in `transient-mark-mode', promote all headings
7291 in the region."
7292 (interactive)
7293 (save-excursion
7294 (if (org-region-active-p)
7295 (org-map-region 'org-promote (region-beginning) (region-end))
7296 (org-promote)))
7297 (org-fix-position-after-promote))
7299 (defun org-do-demote ()
7300 "Demote the current heading lower down the tree.
7301 If the region is active in `transient-mark-mode', demote all headings
7302 in the region."
7303 (interactive)
7304 (save-excursion
7305 (if (org-region-active-p)
7306 (org-map-region 'org-demote (region-beginning) (region-end))
7307 (org-demote)))
7308 (org-fix-position-after-promote))
7310 (defun org-fix-position-after-promote ()
7311 "Make sure that after pro/demotion cursor position is right."
7312 (let ((pos (point)))
7313 (when (save-excursion
7314 (beginning-of-line 1)
7315 (looking-at org-todo-line-regexp)
7316 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7317 (cond ((eobp) (insert " "))
7318 ((eolp) (insert " "))
7319 ((equal (char-after) ?\ ) (forward-char 1))))))
7321 (defun org-current-level ()
7322 "Return the level of the current entry, or nil if before the first headline.
7323 The level is the number of stars at the beginning of the headline."
7324 (save-excursion
7325 (org-with-limited-levels
7326 (if (ignore-errors (org-back-to-heading t))
7327 (funcall outline-level)))))
7329 (defun org-get-previous-line-level ()
7330 "Return the outline depth of the last headline before the current line.
7331 Returns 0 for the first headline in the buffer, and nil if before the
7332 first headline."
7333 (let ((current-level (org-current-level))
7334 (prev-level (when (> (line-number-at-pos) 1)
7335 (save-excursion
7336 (beginning-of-line 0)
7337 (org-current-level)))))
7338 (cond ((null current-level) nil) ; Before first headline
7339 ((null prev-level) 0) ; At first headline
7340 (prev-level))))
7342 (defun org-reduced-level (l)
7343 "Compute the effective level of a heading.
7344 This takes into account the setting of `org-odd-levels-only'."
7345 (cond
7346 ((zerop l) 0)
7347 (org-odd-levels-only (1+ (floor (/ l 2))))
7348 (t l)))
7350 (defun org-level-increment ()
7351 "Return the number of stars that will be added or removed at a
7352 time to headlines when structure editing, based on the value of
7353 `org-odd-levels-only'."
7354 (if org-odd-levels-only 2 1))
7356 (defun org-get-valid-level (level &optional change)
7357 "Rectify a level change under the influence of `org-odd-levels-only'
7358 LEVEL is a current level, CHANGE is by how much the level should be
7359 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7360 even level numbers will become the next higher odd number."
7361 (if org-odd-levels-only
7362 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7363 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7364 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7365 (max 1 (+ level (or change 0)))))
7367 (if (boundp 'define-obsolete-function-alias)
7368 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7369 (define-obsolete-function-alias 'org-get-legal-level
7370 'org-get-valid-level)
7371 (define-obsolete-function-alias 'org-get-legal-level
7372 'org-get-valid-level "23.1")))
7374 (defun org-promote ()
7375 "Promote the current heading higher up the tree.
7376 If the region is active in `transient-mark-mode', promote all headings
7377 in the region."
7378 (org-back-to-heading t)
7379 (let* ((level (save-match-data (funcall outline-level)))
7380 (after-change-functions (remove 'flyspell-after-change-function
7381 after-change-functions))
7382 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7383 (diff (abs (- level (length up-head) -1))))
7384 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
7385 (replace-match up-head nil t)
7386 ;; Fixup tag positioning
7387 (and org-auto-align-tags (org-set-tags nil t))
7388 (if org-adapt-indentation (org-fixup-indentation (- diff)))
7389 (run-hooks 'org-after-promote-entry-hook)))
7391 (defun org-demote ()
7392 "Demote the current heading lower down the tree.
7393 If the region is active in `transient-mark-mode', demote all headings
7394 in the region."
7395 (org-back-to-heading t)
7396 (let* ((level (save-match-data (funcall outline-level)))
7397 (after-change-functions (remove 'flyspell-after-change-function
7398 after-change-functions))
7399 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7400 (diff (abs (- level (length down-head) -1))))
7401 (replace-match down-head nil t)
7402 ;; Fixup tag positioning
7403 (and org-auto-align-tags (org-set-tags nil t))
7404 (if org-adapt-indentation (org-fixup-indentation diff))
7405 (run-hooks 'org-after-demote-entry-hook)))
7407 (defun org-cycle-level ()
7408 "Cycle the level of an empty headline through possible states.
7409 This goes first to child, then to parent, level, then up the hierarchy.
7410 After top level, it switches back to sibling level."
7411 (interactive)
7412 (let ((org-adapt-indentation nil))
7413 (when (org-point-at-end-of-empty-headline)
7414 (setq this-command 'org-cycle-level) ; Only needed for caching
7415 (let ((cur-level (org-current-level))
7416 (prev-level (org-get-previous-line-level)))
7417 (cond
7418 ;; If first headline in file, promote to top-level.
7419 ((= prev-level 0)
7420 (loop repeat (/ (- cur-level 1) (org-level-increment))
7421 do (org-do-promote)))
7422 ;; If same level as prev, demote one.
7423 ((= prev-level cur-level)
7424 (org-do-demote))
7425 ;; If parent is top-level, promote to top level if not already.
7426 ((= prev-level 1)
7427 (loop repeat (/ (- cur-level 1) (org-level-increment))
7428 do (org-do-promote)))
7429 ;; If top-level, return to prev-level.
7430 ((= cur-level 1)
7431 (loop repeat (/ (- prev-level 1) (org-level-increment))
7432 do (org-do-demote)))
7433 ;; If less than prev-level, promote one.
7434 ((< cur-level prev-level)
7435 (org-do-promote))
7436 ;; If deeper than prev-level, promote until higher than
7437 ;; prev-level.
7438 ((> cur-level prev-level)
7439 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7440 do (org-do-promote))))
7441 t))))
7443 (defun org-map-tree (fun)
7444 "Call FUN for every heading underneath the current one."
7445 (org-back-to-heading)
7446 (let ((level (funcall outline-level)))
7447 (save-excursion
7448 (funcall fun)
7449 (while (and (progn
7450 (outline-next-heading)
7451 (> (funcall outline-level) level))
7452 (not (eobp)))
7453 (funcall fun)))))
7455 (defun org-map-region (fun beg end)
7456 "Call FUN for every heading between BEG and END."
7457 (let ((org-ignore-region t))
7458 (save-excursion
7459 (setq end (copy-marker end))
7460 (goto-char beg)
7461 (if (and (re-search-forward org-outline-regexp-bol nil t)
7462 (< (point) end))
7463 (funcall fun))
7464 (while (and (progn
7465 (outline-next-heading)
7466 (< (point) end))
7467 (not (eobp)))
7468 (funcall fun)))))
7470 (defvar org-property-end-re) ; silence byte-compiler
7471 (defun org-fixup-indentation (diff)
7472 "Change the indentation in the current entry by DIFF.
7473 However, if any line in the current entry has no indentation, or if it
7474 would end up with no indentation after the change, nothing at all is done."
7475 (save-excursion
7476 (let ((end (save-excursion (outline-next-heading)
7477 (point-marker)))
7478 (prohibit (if (> diff 0)
7479 "^\\S-"
7480 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7481 col)
7482 (unless (save-excursion (end-of-line 1)
7483 (re-search-forward prohibit end t))
7484 (while (and (< (point) end)
7485 (re-search-forward "^[ \t]+" end t))
7486 (goto-char (match-end 0))
7487 (setq col (current-column))
7488 (if (< diff 0) (replace-match ""))
7489 (org-indent-to-column (+ diff col))))
7490 (move-marker end nil))))
7492 (defun org-convert-to-odd-levels ()
7493 "Convert an org-mode file with all levels allowed to one with odd levels.
7494 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7495 level 5 etc."
7496 (interactive)
7497 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7498 (let ((outline-level 'org-outline-level)
7499 (org-odd-levels-only nil) n)
7500 (save-excursion
7501 (goto-char (point-min))
7502 (while (re-search-forward "^\\*\\*+ " nil t)
7503 (setq n (- (length (match-string 0)) 2))
7504 (while (>= (setq n (1- n)) 0)
7505 (org-demote))
7506 (end-of-line 1))))))
7508 (defun org-convert-to-oddeven-levels ()
7509 "Convert an org-mode file with only odd levels to one with odd/even levels.
7510 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7511 file contains a section with an even level, conversion would
7512 destroy the structure of the file. An error is signaled in this
7513 case."
7514 (interactive)
7515 (goto-char (point-min))
7516 ;; First check if there are no even levels
7517 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7518 (org-show-context t)
7519 (error "Not all levels are odd in this file. Conversion not possible"))
7520 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7521 (let ((outline-regexp org-outline-regexp)
7522 (outline-level 'org-outline-level)
7523 (org-odd-levels-only nil) n)
7524 (save-excursion
7525 (goto-char (point-min))
7526 (while (re-search-forward "^\\*\\*+ " nil t)
7527 (setq n (/ (1- (length (match-string 0))) 2))
7528 (while (>= (setq n (1- n)) 0)
7529 (org-promote))
7530 (end-of-line 1))))))
7532 (defun org-tr-level (n)
7533 "Make N odd if required."
7534 (if org-odd-levels-only (1+ (/ n 2)) n))
7536 ;;; Vertical tree motion, cutting and pasting of subtrees
7538 (defun org-move-subtree-up (&optional arg)
7539 "Move the current subtree up past ARG headlines of the same level."
7540 (interactive "p")
7541 (org-move-subtree-down (- (prefix-numeric-value arg))))
7543 (defun org-move-subtree-down (&optional arg)
7544 "Move the current subtree down past ARG headlines of the same level."
7545 (interactive "p")
7546 (setq arg (prefix-numeric-value arg))
7547 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7548 'org-get-last-sibling))
7549 (ins-point (make-marker))
7550 (cnt (abs arg))
7551 (col (current-column))
7552 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7553 ;; Select the tree
7554 (org-back-to-heading)
7555 (setq beg0 (point))
7556 (save-excursion
7557 (setq ne-beg (org-back-over-empty-lines))
7558 (setq beg (point)))
7559 (save-match-data
7560 (save-excursion (outline-end-of-heading)
7561 (setq folded (outline-invisible-p)))
7562 (outline-end-of-subtree))
7563 (outline-next-heading)
7564 (setq ne-end (org-back-over-empty-lines))
7565 (setq end (point))
7566 (goto-char beg0)
7567 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7568 ;; include less whitespace
7569 (save-excursion
7570 (goto-char beg)
7571 (forward-line (- ne-beg ne-end))
7572 (setq beg (point))))
7573 ;; Find insertion point, with error handling
7574 (while (> cnt 0)
7575 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7576 (progn (goto-char beg0)
7577 (error "Cannot move past superior level or buffer limit")))
7578 (setq cnt (1- cnt)))
7579 (if (> arg 0)
7580 ;; Moving forward - still need to move over subtree
7581 (progn (org-end-of-subtree t t)
7582 (save-excursion
7583 (org-back-over-empty-lines)
7584 (or (bolp) (newline)))))
7585 (setq ne-ins (org-back-over-empty-lines))
7586 (move-marker ins-point (point))
7587 (setq txt (buffer-substring beg end))
7588 (org-save-markers-in-region beg end)
7589 (delete-region beg end)
7590 (org-remove-empty-overlays-at beg)
7591 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7592 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7593 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7594 (let ((bbb (point)))
7595 (insert-before-markers txt)
7596 (org-reinstall-markers-in-region bbb)
7597 (move-marker ins-point bbb))
7598 (or (bolp) (insert "\n"))
7599 (setq ins-end (point))
7600 (goto-char ins-point)
7601 (org-skip-whitespace)
7602 (when (and (< arg 0)
7603 (org-first-sibling-p)
7604 (> ne-ins ne-beg))
7605 ;; Move whitespace back to beginning
7606 (save-excursion
7607 (goto-char ins-end)
7608 (let ((kill-whole-line t))
7609 (kill-line (- ne-ins ne-beg)) (point)))
7610 (insert (make-string (- ne-ins ne-beg) ?\n)))
7611 (move-marker ins-point nil)
7612 (if folded
7613 (hide-subtree)
7614 (org-show-entry)
7615 (show-children)
7616 (org-cycle-hide-drawers 'children))
7617 (org-clean-visibility-after-subtree-move)
7618 ;; move back to the initial column we were at
7619 (move-to-column col)))
7621 (defvar org-subtree-clip ""
7622 "Clipboard for cut and paste of subtrees.
7623 This is actually only a copy of the kill, because we use the normal kill
7624 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7626 (defvar org-subtree-clip-folded nil
7627 "Was the last copied subtree folded?
7628 This is used to fold the tree back after pasting.")
7630 (defun org-cut-subtree (&optional n)
7631 "Cut the current subtree into the clipboard.
7632 With prefix arg N, cut this many sequential subtrees.
7633 This is a short-hand for marking the subtree and then cutting it."
7634 (interactive "p")
7635 (org-copy-subtree n 'cut))
7637 (defun org-copy-subtree (&optional n cut force-store-markers)
7638 "Cut the current subtree into the clipboard.
7639 With prefix arg N, cut this many sequential subtrees.
7640 This is a short-hand for marking the subtree and then copying it.
7641 If CUT is non-nil, actually cut the subtree.
7642 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7643 of some markers in the region, even if CUT is non-nil. This is
7644 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7645 (interactive "p")
7646 (let (beg end folded (beg0 (point)))
7647 (if (org-called-interactively-p 'any)
7648 (org-back-to-heading nil) ; take what looks like a subtree
7649 (org-back-to-heading t)) ; take what is really there
7650 (org-back-over-empty-lines)
7651 (setq beg (point))
7652 (skip-chars-forward " \t\r\n")
7653 (save-match-data
7654 (save-excursion (outline-end-of-heading)
7655 (setq folded (outline-invisible-p)))
7656 (condition-case nil
7657 (org-forward-same-level (1- n) t)
7658 (error nil))
7659 (org-end-of-subtree t t))
7660 (org-back-over-empty-lines)
7661 (setq end (point))
7662 (goto-char beg0)
7663 (when (> end beg)
7664 (setq org-subtree-clip-folded folded)
7665 (when (or cut force-store-markers)
7666 (org-save-markers-in-region beg end))
7667 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7668 (setq org-subtree-clip (current-kill 0))
7669 (message "%s: Subtree(s) with %d characters"
7670 (if cut "Cut" "Copied")
7671 (length org-subtree-clip)))))
7673 (defun org-paste-subtree (&optional level tree for-yank)
7674 "Paste the clipboard as a subtree, with modification of headline level.
7675 The entire subtree is promoted or demoted in order to match a new headline
7676 level.
7678 If the cursor is at the beginning of a headline, the same level as
7679 that headline is used to paste the tree
7681 If not, the new level is derived from the *visible* headings
7682 before and after the insertion point, and taken to be the inferior headline
7683 level of the two. So if the previous visible heading is level 3 and the
7684 next is level 4 (or vice versa), level 4 will be used for insertion.
7685 This makes sure that the subtree remains an independent subtree and does
7686 not swallow low level entries.
7688 You can also force a different level, either by using a numeric prefix
7689 argument, or by inserting the heading marker by hand. For example, if the
7690 cursor is after \"*****\", then the tree will be shifted to level 5.
7692 If optional TREE is given, use this text instead of the kill ring.
7694 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7695 move back over whitespace before inserting, and move point to the end of
7696 the inserted text when done."
7697 (interactive "P")
7698 (setq tree (or tree (and kill-ring (current-kill 0))))
7699 (unless (org-kill-is-subtree-p tree)
7700 (error "%s"
7701 (substitute-command-keys
7702 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7703 (org-with-limited-levels
7704 (let* ((visp (not (outline-invisible-p)))
7705 (txt tree)
7706 (^re_ "\\(\\*+\\)[ \t]*")
7707 (old-level (if (string-match org-outline-regexp-bol txt)
7708 (- (match-end 0) (match-beginning 0) 1)
7709 -1))
7710 (force-level (cond (level (prefix-numeric-value level))
7711 ((and (looking-at "[ \t]*$")
7712 (string-match
7713 "^\\*+$" (buffer-substring
7714 (point-at-bol) (point))))
7715 (- (match-end 1) (match-beginning 1)))
7716 ((and (bolp)
7717 (looking-at org-outline-regexp))
7718 (- (match-end 0) (point) 1))
7719 (t nil)))
7720 (previous-level (save-excursion
7721 (condition-case nil
7722 (progn
7723 (outline-previous-visible-heading 1)
7724 (if (looking-at ^re_)
7725 (- (match-end 0) (match-beginning 0) 1)
7727 (error 1))))
7728 (next-level (save-excursion
7729 (condition-case nil
7730 (progn
7731 (or (looking-at org-outline-regexp)
7732 (outline-next-visible-heading 1))
7733 (if (looking-at ^re_)
7734 (- (match-end 0) (match-beginning 0) 1)
7736 (error 1))))
7737 (new-level (or force-level (max previous-level next-level)))
7738 (shift (if (or (= old-level -1)
7739 (= new-level -1)
7740 (= old-level new-level))
7742 (- new-level old-level)))
7743 (delta (if (> shift 0) -1 1))
7744 (func (if (> shift 0) 'org-demote 'org-promote))
7745 (org-odd-levels-only nil)
7746 beg end newend)
7747 ;; Remove the forced level indicator
7748 (if force-level
7749 (delete-region (point-at-bol) (point)))
7750 ;; Paste
7751 (beginning-of-line (if (bolp) 1 2))
7752 (unless for-yank (org-back-over-empty-lines))
7753 (setq beg (point))
7754 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7755 (insert-before-markers txt)
7756 (unless (string-match "\n\\'" txt) (insert "\n"))
7757 (setq newend (point))
7758 (org-reinstall-markers-in-region beg)
7759 (setq end (point))
7760 (goto-char beg)
7761 (skip-chars-forward " \t\n\r")
7762 (setq beg (point))
7763 (if (and (outline-invisible-p) visp)
7764 (save-excursion (outline-show-heading)))
7765 ;; Shift if necessary
7766 (unless (= shift 0)
7767 (save-restriction
7768 (narrow-to-region beg end)
7769 (while (not (= shift 0))
7770 (org-map-region func (point-min) (point-max))
7771 (setq shift (+ delta shift)))
7772 (goto-char (point-min))
7773 (setq newend (point-max))))
7774 (when (or (org-called-interactively-p 'interactive) for-yank)
7775 (message "Clipboard pasted as level %d subtree" new-level))
7776 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7777 kill-ring
7778 (eq org-subtree-clip (current-kill 0))
7779 org-subtree-clip-folded)
7780 ;; The tree was folded before it was killed/copied
7781 (hide-subtree))
7782 (and for-yank (goto-char newend)))))
7784 (defun org-kill-is-subtree-p (&optional txt)
7785 "Check if the current kill is an outline subtree, or a set of trees.
7786 Returns nil if kill does not start with a headline, or if the first
7787 headline level is not the largest headline level in the tree.
7788 So this will actually accept several entries of equal levels as well,
7789 which is OK for `org-paste-subtree'.
7790 If optional TXT is given, check this string instead of the current kill."
7791 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7792 (re (org-get-limited-outline-regexp))
7793 (^re (concat "^" re))
7794 (start-level (and kill
7795 (string-match
7796 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7797 kill)
7798 (- (match-end 2) (match-beginning 2) 1)))
7799 (start (1+ (or (match-beginning 2) -1))))
7800 (if (not start-level)
7801 (progn
7802 nil) ;; does not even start with a heading
7803 (catch 'exit
7804 (while (setq start (string-match ^re kill (1+ start)))
7805 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7806 (throw 'exit nil)))
7807 t))))
7809 (defvar org-markers-to-move nil
7810 "Markers that should be moved with a cut-and-paste operation.
7811 Those markers are stored together with their positions relative to
7812 the start of the region.")
7814 (defun org-save-markers-in-region (beg end)
7815 "Check markers in region.
7816 If these markers are between BEG and END, record their position relative
7817 to BEG, so that after moving the block of text, we can put the markers back
7818 into place.
7819 This function gets called just before an entry or tree gets cut from the
7820 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7821 called immediately, to move the markers with the entries."
7822 (setq org-markers-to-move nil)
7823 (when (featurep 'org-clock)
7824 (org-clock-save-markers-for-cut-and-paste beg end))
7825 (when (featurep 'org-agenda)
7826 (org-agenda-save-markers-for-cut-and-paste beg end)))
7828 (defun org-check-and-save-marker (marker beg end)
7829 "Check if MARKER is between BEG and END.
7830 If yes, remember the marker and the distance to BEG."
7831 (when (and (marker-buffer marker)
7832 (equal (marker-buffer marker) (current-buffer)))
7833 (if (and (>= marker beg) (< marker end))
7834 (push (cons marker (- marker beg)) org-markers-to-move))))
7836 (defun org-reinstall-markers-in-region (beg)
7837 "Move all remembered markers to their position relative to BEG."
7838 (mapc (lambda (x)
7839 (move-marker (car x) (+ beg (cdr x))))
7840 org-markers-to-move)
7841 (setq org-markers-to-move nil))
7843 (defun org-narrow-to-subtree ()
7844 "Narrow buffer to the current subtree."
7845 (interactive)
7846 (save-excursion
7847 (save-match-data
7848 (org-with-limited-levels
7849 (narrow-to-region
7850 (progn (org-back-to-heading t) (point))
7851 (progn (org-end-of-subtree t t)
7852 (if (and (org-on-heading-p) (not (eobp))) (backward-char 1))
7853 (point)))))))
7855 (defun org-narrow-to-block ()
7856 "Narrow buffer to the current block."
7857 (interactive)
7858 (let* ((case-fold-search t)
7859 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7860 "^[ \t]*#\\+end_.*")))
7861 (if blockp
7862 (narrow-to-region (car blockp) (cdr blockp))
7863 (error "Not in a block"))))
7865 (eval-when-compile
7866 (defvar org-property-drawer-re))
7868 (defvar org-property-start-re) ;; defined below
7869 (defun org-clone-subtree-with-time-shift (n &optional shift)
7870 "Clone the task (subtree) at point N times.
7871 The clones will be inserted as siblings.
7873 In interactive use, the user will be prompted for the number of
7874 clones to be produced, and for a time SHIFT, which may be a
7875 repeater as used in time stamps, for example `+3d'.
7877 When a valid repeater is given and the entry contains any time
7878 stamps, the clones will become a sequence in time, with time
7879 stamps in the subtree shifted for each clone produced. If SHIFT
7880 is nil or the empty string, time stamps will be left alone. The
7881 ID property of the original subtree is removed.
7883 If the original subtree did contain time stamps with a repeater,
7884 the following will happen:
7885 - the repeater will be removed in each clone
7886 - an additional clone will be produced, with the current, unshifted
7887 date(s) in the entry.
7888 - the original entry will be placed *after* all the clones, with
7889 repeater intact.
7890 - the start days in the repeater in the original entry will be shifted
7891 to past the last clone.
7892 I this way you can spell out a number of instances of a repeating task,
7893 and still retain the repeater to cover future instances of the task."
7894 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7895 (let (beg end template task idprop
7896 shift-n shift-what doshift nmin nmax (n-no-remove -1)
7897 (drawer-re org-drawer-regexp))
7898 (if (not (and (integerp n) (> n 0)))
7899 (error "Invalid number of replications %s" n))
7900 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7901 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
7902 shift)))
7903 (error "Invalid shift specification %s" shift))
7904 (when doshift
7905 (setq shift-n (string-to-number (match-string 1 shift))
7906 shift-what (cdr (assoc (match-string 2 shift)
7907 '(("d" . day) ("w" . week)
7908 ("m" . month) ("y" . year))))))
7909 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7910 (setq nmin 1 nmax n)
7911 (org-back-to-heading t)
7912 (setq beg (point))
7913 (setq idprop (org-entry-get nil "ID"))
7914 (org-end-of-subtree t t)
7915 (or (bolp) (insert "\n"))
7916 (setq end (point))
7917 (setq template (buffer-substring beg end))
7918 (when (and doshift
7919 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
7920 (delete-region beg end)
7921 (setq end beg)
7922 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7923 (goto-char end)
7924 (loop for n from nmin to nmax do
7925 ;; prepare clone
7926 (with-temp-buffer
7927 (insert template)
7928 (org-mode)
7929 (goto-char (point-min))
7930 (org-show-subtree)
7931 (and idprop (if org-clone-delete-id
7932 (org-entry-delete nil "ID")
7933 (org-id-get-create t)))
7934 (unless (= n 0)
7935 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
7936 (kill-whole-line))
7937 (goto-char (point-min))
7938 (while (re-search-forward drawer-re nil t)
7939 (mapc (lambda (d)
7940 (org-remove-empty-drawer-at d (point))) org-drawers)))
7941 (goto-char (point-min))
7942 (when doshift
7943 (while (re-search-forward org-ts-regexp-both nil t)
7944 (org-timestamp-change (* n shift-n) shift-what))
7945 (unless (= n n-no-remove)
7946 (goto-char (point-min))
7947 (while (re-search-forward org-ts-regexp nil t)
7948 (save-excursion
7949 (goto-char (match-beginning 0))
7950 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
7951 (delete-region (match-beginning 1) (match-end 1)))))))
7952 (setq task (buffer-string)))
7953 (insert task))
7954 (goto-char beg)))
7956 ;;; Outline Sorting
7958 (defun org-sort (with-case)
7959 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
7960 Optional argument WITH-CASE means sort case-sensitively.
7961 With a double prefix argument, also remove duplicate entries."
7962 (interactive "P")
7963 (cond
7964 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
7965 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
7967 (org-call-with-arg 'org-sort-entries with-case))))
7969 (defun org-sort-remove-invisible (s)
7970 (remove-text-properties 0 (length s) org-rm-props s)
7971 (while (string-match org-bracket-link-regexp s)
7972 (setq s (replace-match (if (match-end 2)
7973 (match-string 3 s)
7974 (match-string 1 s)) t t s)))
7977 (defvar org-priority-regexp) ; defined later in the file
7979 (defvar org-after-sorting-entries-or-items-hook nil
7980 "Hook that is run after a bunch of entries or items have been sorted.
7981 When children are sorted, the cursor is in the parent line when this
7982 hook gets called. When a region or a plain list is sorted, the cursor
7983 will be in the first entry of the sorted region/list.")
7985 (defun org-sort-entries
7986 (&optional with-case sorting-type getkey-func compare-func property)
7987 "Sort entries on a certain level of an outline tree.
7988 If there is an active region, the entries in the region are sorted.
7989 Else, if the cursor is before the first entry, sort the top-level items.
7990 Else, the children of the entry at point are sorted.
7992 Sorting can be alphabetically, numerically, by date/time as given by
7993 a time stamp, by a property or by priority.
7995 The command prompts for the sorting type unless it has been given to the
7996 function through the SORTING-TYPE argument, which needs to be a character,
7997 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
7998 precise meaning of each character:
8000 n Numerically, by converting the beginning of the entry/item to a number.
8001 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8002 t By date/time, either the first active time stamp in the entry, or, if
8003 none exist, by the first inactive one.
8004 s By the scheduled date/time.
8005 d By deadline date/time.
8006 c By creation time, which is assumed to be the first inactive time stamp
8007 at the beginning of a line.
8008 p By priority according to the cookie.
8009 r By the value of a property.
8011 Capital letters will reverse the sort order.
8013 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8014 called with point at the beginning of the record. It must return either
8015 a string or a number that should serve as the sorting key for that record.
8017 Comparing entries ignores case by default. However, with an optional argument
8018 WITH-CASE, the sorting considers case as well."
8019 (interactive "P")
8020 (let ((case-func (if with-case 'identity 'downcase))
8021 start beg end stars re re2
8022 txt what tmp)
8023 ;; Find beginning and end of region to sort
8024 (cond
8025 ((org-region-active-p)
8026 ;; we will sort the region
8027 (setq end (region-end)
8028 what "region")
8029 (goto-char (region-beginning))
8030 (if (not (org-on-heading-p)) (outline-next-heading))
8031 (setq start (point)))
8032 ((or (org-on-heading-p)
8033 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8034 ;; we will sort the children of the current headline
8035 (org-back-to-heading)
8036 (setq start (point)
8037 end (progn (org-end-of-subtree t t)
8038 (or (bolp) (insert "\n"))
8039 (org-back-over-empty-lines)
8040 (point))
8041 what "children")
8042 (goto-char start)
8043 (show-subtree)
8044 (outline-next-heading))
8046 ;; we will sort the top-level entries in this file
8047 (goto-char (point-min))
8048 (or (org-on-heading-p) (outline-next-heading))
8049 (setq start (point))
8050 (goto-char (point-max))
8051 (beginning-of-line 1)
8052 (when (looking-at ".*?\\S-")
8053 ;; File ends in a non-white line
8054 (end-of-line 1)
8055 (insert "\n"))
8056 (setq end (point-max))
8057 (setq what "top-level")
8058 (goto-char start)
8059 (show-all)))
8061 (setq beg (point))
8062 (if (>= beg end) (error "Nothing to sort"))
8064 (looking-at "\\(\\*+\\)")
8065 (setq stars (match-string 1)
8066 re (concat "^" (regexp-quote stars) " +")
8067 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8068 txt (buffer-substring beg end))
8069 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8070 (if (and (not (equal stars "*")) (string-match re2 txt))
8071 (error "Region to sort contains a level above the first entry"))
8073 (unless sorting-type
8074 (message
8075 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8076 [t]ime [s]cheduled [d]eadline [c]reated
8077 A/N/T/S/D/C/P/O/F means reversed:"
8078 what)
8079 (setq sorting-type (read-char-exclusive))
8081 (and (= (downcase sorting-type) ?f)
8082 (setq getkey-func
8083 (org-icompleting-read "Sort using function: "
8084 obarray 'fboundp t nil nil))
8085 (setq getkey-func (intern getkey-func)))
8087 (and (= (downcase sorting-type) ?r)
8088 (setq property
8089 (org-icompleting-read "Property: "
8090 (mapcar 'list (org-buffer-property-keys t))
8091 nil t))))
8093 (message "Sorting entries...")
8095 (save-restriction
8096 (narrow-to-region start end)
8097 (let ((dcst (downcase sorting-type))
8098 (case-fold-search nil)
8099 (now (current-time)))
8100 (sort-subr
8101 (/= dcst sorting-type)
8102 ;; This function moves to the beginning character of the "record" to
8103 ;; be sorted.
8104 (lambda nil
8105 (if (re-search-forward re nil t)
8106 (goto-char (match-beginning 0))
8107 (goto-char (point-max))))
8108 ;; This function moves to the last character of the "record" being
8109 ;; sorted.
8110 (lambda nil
8111 (save-match-data
8112 (condition-case nil
8113 (outline-forward-same-level 1)
8114 (error
8115 (goto-char (point-max))))))
8116 ;; This function returns the value that gets sorted against.
8117 (lambda nil
8118 (cond
8119 ((= dcst ?n)
8120 (if (looking-at org-complex-heading-regexp)
8121 (string-to-number (match-string 4))
8122 nil))
8123 ((= dcst ?a)
8124 (if (looking-at org-complex-heading-regexp)
8125 (funcall case-func (match-string 4))
8126 nil))
8127 ((= dcst ?t)
8128 (let ((end (save-excursion (outline-next-heading) (point))))
8129 (if (or (re-search-forward org-ts-regexp end t)
8130 (re-search-forward org-ts-regexp-both end t))
8131 (org-time-string-to-seconds (match-string 0))
8132 (org-float-time now))))
8133 ((= dcst ?c)
8134 (let ((end (save-excursion (outline-next-heading) (point))))
8135 (if (re-search-forward
8136 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8137 end t)
8138 (org-time-string-to-seconds (match-string 0))
8139 (org-float-time now))))
8140 ((= dcst ?s)
8141 (let ((end (save-excursion (outline-next-heading) (point))))
8142 (if (re-search-forward org-scheduled-time-regexp end t)
8143 (org-time-string-to-seconds (match-string 1))
8144 (org-float-time now))))
8145 ((= dcst ?d)
8146 (let ((end (save-excursion (outline-next-heading) (point))))
8147 (if (re-search-forward org-deadline-time-regexp end t)
8148 (org-time-string-to-seconds (match-string 1))
8149 (org-float-time now))))
8150 ((= dcst ?p)
8151 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8152 (string-to-char (match-string 2))
8153 org-default-priority))
8154 ((= dcst ?r)
8155 (or (org-entry-get nil property) ""))
8156 ((= dcst ?o)
8157 (if (looking-at org-complex-heading-regexp)
8158 (- 9999 (length (member (match-string 2)
8159 org-todo-keywords-1)))))
8160 ((= dcst ?f)
8161 (if getkey-func
8162 (progn
8163 (setq tmp (funcall getkey-func))
8164 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8165 tmp)
8166 (error "Invalid key function `%s'" getkey-func)))
8167 (t (error "Invalid sorting type `%c'" sorting-type))))
8169 (cond
8170 ((= dcst ?a) 'string<)
8171 ((= dcst ?f) compare-func)
8172 ((member dcst '(?p ?t ?s ?d ?c)) '<)
8173 (t nil)))))
8174 (run-hooks 'org-after-sorting-entries-or-items-hook)
8175 (message "Sorting entries...done")))
8177 (defun org-do-sort (table what &optional with-case sorting-type)
8178 "Sort TABLE of WHAT according to SORTING-TYPE.
8179 The user will be prompted for the SORTING-TYPE if the call to this
8180 function does not specify it. WHAT is only for the prompt, to indicate
8181 what is being sorted. The sorting key will be extracted from
8182 the car of the elements of the table.
8183 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8184 (unless sorting-type
8185 (message
8186 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8187 what)
8188 (setq sorting-type (read-char-exclusive)))
8189 (let ((dcst (downcase sorting-type))
8190 extractfun comparefun)
8191 ;; Define the appropriate functions
8192 (cond
8193 ((= dcst ?n)
8194 (setq extractfun 'string-to-number
8195 comparefun (if (= dcst sorting-type) '< '>)))
8196 ((= dcst ?a)
8197 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8198 (lambda(x) (downcase (org-sort-remove-invisible x))))
8199 comparefun (if (= dcst sorting-type)
8200 'string<
8201 (lambda (a b) (and (not (string< a b))
8202 (not (string= a b)))))))
8203 ((= dcst ?t)
8204 (setq extractfun
8205 (lambda (x)
8206 (if (or (string-match org-ts-regexp x)
8207 (string-match org-ts-regexp-both x))
8208 (org-float-time
8209 (org-time-string-to-time (match-string 0 x)))
8211 comparefun (if (= dcst sorting-type) '< '>)))
8212 (t (error "Invalid sorting type `%c'" sorting-type)))
8214 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8215 table)
8216 (lambda (a b) (funcall comparefun (car a) (car b))))))
8219 ;;; The orgstruct minor mode
8221 ;; Define a minor mode which can be used in other modes in order to
8222 ;; integrate the org-mode structure editing commands.
8224 ;; This is really a hack, because the org-mode structure commands use
8225 ;; keys which normally belong to the major mode. Here is how it
8226 ;; works: The minor mode defines all the keys necessary to operate the
8227 ;; structure commands, but wraps the commands into a function which
8228 ;; tests if the cursor is currently at a headline or a plain list
8229 ;; item. If that is the case, the structure command is used,
8230 ;; temporarily setting many Org-mode variables like regular
8231 ;; expressions for filling etc. However, when any of those keys is
8232 ;; used at a different location, function uses `key-binding' to look
8233 ;; up if the key has an associated command in another currently active
8234 ;; keymap (minor modes, major mode, global), and executes that
8235 ;; command. There might be problems if any of the keys is otherwise
8236 ;; used as a prefix key.
8238 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8239 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8240 ;; addresses this by checking explicitly for both bindings.
8242 (defvar orgstruct-mode-map (make-sparse-keymap)
8243 "Keymap for the minor `orgstruct-mode'.")
8245 (defvar org-local-vars nil
8246 "List of local variables, for use by `orgstruct-mode'.")
8248 ;;;###autoload
8249 (define-minor-mode orgstruct-mode
8250 "Toggle the minor mode `orgstruct-mode'.
8251 This mode is for using Org-mode structure commands in other
8252 modes. The following keys behave as if Org-mode were active, if
8253 the cursor is on a headline, or on a plain list item (both as
8254 defined by Org-mode).
8256 M-up Move entry/item up
8257 M-down Move entry/item down
8258 M-left Promote
8259 M-right Demote
8260 M-S-up Move entry/item up
8261 M-S-down Move entry/item down
8262 M-S-left Promote subtree
8263 M-S-right Demote subtree
8264 M-q Fill paragraph and items like in Org-mode
8265 C-c ^ Sort entries
8266 C-c - Cycle list bullet
8267 TAB Cycle item visibility
8268 M-RET Insert new heading/item
8269 S-M-RET Insert new TODO heading / Checkbox item
8270 C-c C-c Set tags / toggle checkbox"
8271 nil " OrgStruct" nil
8272 (org-load-modules-maybe)
8273 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8275 ;;;###autoload
8276 (defun turn-on-orgstruct ()
8277 "Unconditionally turn on `orgstruct-mode'."
8278 (orgstruct-mode 1))
8280 (defun orgstruct++-mode (&optional arg)
8281 "Toggle `orgstruct-mode', the enhanced version of it.
8282 In addition to setting orgstruct-mode, this also exports all indentation
8283 and autofilling variables from org-mode into the buffer. It will also
8284 recognize item context in multiline items.
8285 Note that turning off orgstruct-mode will *not* remove the
8286 indentation/paragraph settings. This can only be done by refreshing the
8287 major mode, for example with \\[normal-mode]."
8288 (interactive "P")
8289 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8290 (if (< arg 1)
8291 (orgstruct-mode -1)
8292 (orgstruct-mode 1)
8293 (let (var val)
8294 (mapc
8295 (lambda (x)
8296 (when (string-match
8297 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8298 (symbol-name (car x)))
8299 (setq var (car x) val (nth 1 x))
8300 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8301 org-local-vars)
8302 (org-set-local 'orgstruct-is-++ t))))
8304 (defvar orgstruct-is-++ nil
8305 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8306 (make-variable-buffer-local 'orgstruct-is-++)
8308 ;;;###autoload
8309 (defun turn-on-orgstruct++ ()
8310 "Unconditionally turn on `orgstruct++-mode'."
8311 (orgstruct++-mode 1))
8313 (defun orgstruct-error ()
8314 "Error when there is no default binding for a structure key."
8315 (interactive)
8316 (error "This key has no function outside structure elements"))
8318 (defun orgstruct-setup ()
8319 "Setup orgstruct keymaps."
8320 (let ((nfunc 0)
8321 (bindings
8322 (list
8323 '([(meta up)] org-metaup)
8324 '([(meta down)] org-metadown)
8325 '([(meta left)] org-metaleft)
8326 '([(meta right)] org-metaright)
8327 '([(meta shift up)] org-shiftmetaup)
8328 '([(meta shift down)] org-shiftmetadown)
8329 '([(meta shift left)] org-shiftmetaleft)
8330 '([(meta shift right)] org-shiftmetaright)
8331 '([?\e (up)] org-metaup)
8332 '([?\e (down)] org-metadown)
8333 '([?\e (left)] org-metaleft)
8334 '([?\e (right)] org-metaright)
8335 '([?\e (shift up)] org-shiftmetaup)
8336 '([?\e (shift down)] org-shiftmetadown)
8337 '([?\e (shift left)] org-shiftmetaleft)
8338 '([?\e (shift right)] org-shiftmetaright)
8339 '([(shift up)] org-shiftup)
8340 '([(shift down)] org-shiftdown)
8341 '([(shift left)] org-shiftleft)
8342 '([(shift right)] org-shiftright)
8343 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8344 '("\M-q" fill-paragraph)
8345 '("\C-c^" org-sort)
8346 '("\C-c-" org-cycle-list-bullet)))
8347 elt key fun cmd)
8348 (while (setq elt (pop bindings))
8349 (setq nfunc (1+ nfunc))
8350 (setq key (org-key (car elt))
8351 fun (nth 1 elt)
8352 cmd (orgstruct-make-binding fun nfunc key))
8353 (org-defkey orgstruct-mode-map key cmd))
8355 ;; Special treatment needed for TAB and RET
8356 (org-defkey orgstruct-mode-map [(tab)]
8357 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8358 (org-defkey orgstruct-mode-map "\C-i"
8359 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8361 (org-defkey orgstruct-mode-map "\M-\C-m"
8362 (orgstruct-make-binding 'org-insert-heading 105
8363 "\M-\C-m" [(meta return)]))
8364 (org-defkey orgstruct-mode-map [(meta return)]
8365 (orgstruct-make-binding 'org-insert-heading 106
8366 [(meta return)] "\M-\C-m"))
8368 (org-defkey orgstruct-mode-map [(shift meta return)]
8369 (orgstruct-make-binding 'org-insert-todo-heading 107
8370 [(meta return)] "\M-\C-m"))
8372 (org-defkey orgstruct-mode-map "\e\C-m"
8373 (orgstruct-make-binding 'org-insert-heading 108
8374 "\e\C-m" [?\e (return)]))
8375 (org-defkey orgstruct-mode-map [?\e (return)]
8376 (orgstruct-make-binding 'org-insert-heading 109
8377 [?\e (return)] "\e\C-m"))
8378 (org-defkey orgstruct-mode-map [?\e (shift return)]
8379 (orgstruct-make-binding 'org-insert-todo-heading 110
8380 [?\e (return)] "\e\C-m"))
8382 (unless org-local-vars
8383 (setq org-local-vars (org-get-local-variables)))
8387 (defun orgstruct-make-binding (fun n &rest keys)
8388 "Create a function for binding in the structure minor mode.
8389 FUN is the command to call inside a table. N is used to create a unique
8390 command name. KEYS are keys that should be checked in for a command
8391 to execute outside of tables."
8392 (eval
8393 (list 'defun
8394 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8395 '(arg)
8396 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8397 "Outside of structure, run the binding of `"
8398 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8399 "'.")
8400 '(interactive "p")
8401 (list 'if
8402 `(org-context-p 'headline 'item
8403 (and orgstruct-is-++
8404 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8405 'item-body))
8406 (list 'org-run-like-in-org-mode (list 'quote fun))
8407 (list 'let '(orgstruct-mode)
8408 (list 'call-interactively
8409 (append '(or)
8410 (mapcar (lambda (k)
8411 (list 'key-binding k))
8412 keys)
8413 '('orgstruct-error))))))))
8415 (defun org-context-p (&rest contexts)
8416 "Check if local context is any of CONTEXTS.
8417 Possible values in the list of contexts are `table', `headline', and `item'."
8418 (let ((pos (point)))
8419 (goto-char (point-at-bol))
8420 (prog1 (or (and (memq 'table contexts)
8421 (looking-at "[ \t]*|"))
8422 (and (memq 'headline contexts)
8423 (looking-at org-outline-regexp))
8424 (and (memq 'item contexts)
8425 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8426 (and (memq 'item-body contexts)
8427 (org-in-item-p)))
8428 (goto-char pos))))
8430 (defun org-get-local-variables ()
8431 "Return a list of all local variables in an org-mode buffer."
8432 (let (varlist)
8433 (with-current-buffer (get-buffer-create "*Org tmp*")
8434 (erase-buffer)
8435 (org-mode)
8436 (setq varlist (buffer-local-variables)))
8437 (kill-buffer "*Org tmp*")
8438 (delq nil
8439 (mapcar
8440 (lambda (x)
8441 (setq x
8442 (if (symbolp x)
8443 (list x)
8444 (list (car x) (list 'quote (cdr x)))))
8445 (if (string-match
8446 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8447 (symbol-name (car x)))
8448 x nil))
8449 varlist))))
8451 (defun org-clone-local-variables (from-buffer &optional regexp)
8452 "Clone local variables from FROM-BUFFER.
8453 Optional argument REGEXP selects variables to clone."
8454 (mapc
8455 (lambda (pair)
8456 (and (symbolp (car pair))
8457 (or (null regexp)
8458 (string-match regexp (symbol-name (car pair))))
8459 (set (make-local-variable (car pair))
8460 (cdr pair))))
8461 (buffer-local-variables from-buffer)))
8463 ;;;###autoload
8464 (defun org-run-like-in-org-mode (cmd)
8465 "Run a command, pretending that the current buffer is in Org-mode.
8466 This will temporarily bind local variables that are typically bound in
8467 Org-mode to the values they have in Org-mode, and then interactively
8468 call CMD."
8469 (org-load-modules-maybe)
8470 (unless org-local-vars
8471 (setq org-local-vars (org-get-local-variables)))
8472 (eval (list 'let org-local-vars
8473 (list 'call-interactively (list 'quote cmd)))))
8475 ;;;; Archiving
8477 (defun org-get-category (&optional pos force-refresh)
8478 "Get the category applying to position POS."
8479 (if force-refresh (org-refresh-category-properties))
8480 (let ((pos (or pos (point))))
8481 (or (get-text-property pos 'org-category)
8482 (progn (org-refresh-category-properties)
8483 (get-text-property pos 'org-category)))))
8485 (defun org-refresh-category-properties ()
8486 "Refresh category text properties in the buffer."
8487 (let ((def-cat (cond
8488 ((null org-category)
8489 (if buffer-file-name
8490 (file-name-sans-extension
8491 (file-name-nondirectory buffer-file-name))
8492 "???"))
8493 ((symbolp org-category) (symbol-name org-category))
8494 (t org-category)))
8495 beg end cat pos optionp)
8496 (org-unmodified
8497 (save-excursion
8498 (save-restriction
8499 (widen)
8500 (goto-char (point-min))
8501 (put-text-property (point) (point-max) 'org-category def-cat)
8502 (while (re-search-forward
8503 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8504 (setq pos (match-end 0)
8505 optionp (equal (char-after (match-beginning 0)) ?#)
8506 cat (org-trim (match-string 2)))
8507 (if optionp
8508 (setq beg (point-at-bol) end (point-max))
8509 (org-back-to-heading t)
8510 (setq beg (point) end (org-end-of-subtree t t)))
8511 (put-text-property beg end 'org-category cat)
8512 (put-text-property beg end 'org-category-position beg)
8513 (goto-char pos)))))))
8516 ;;;; Link Stuff
8518 ;;; Link abbreviations
8520 (defun org-link-expand-abbrev (link)
8521 "Apply replacements as defined in `org-link-abbrev-alist."
8522 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8523 (let* ((key (match-string 1 link))
8524 (as (or (assoc key org-link-abbrev-alist-local)
8525 (assoc key org-link-abbrev-alist)))
8526 (tag (and (match-end 2) (match-string 3 link)))
8527 rpl)
8528 (if (not as)
8529 link
8530 (setq rpl (cdr as))
8531 (cond
8532 ((symbolp rpl) (funcall rpl tag))
8533 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8534 ((string-match "%h" rpl)
8535 (replace-match (url-hexify-string (or tag "")) t t rpl))
8536 (t (concat rpl tag)))))
8537 link))
8539 ;;; Storing and inserting links
8541 (defvar org-insert-link-history nil
8542 "Minibuffer history for links inserted with `org-insert-link'.")
8544 (defvar org-stored-links nil
8545 "Contains the links stored with `org-store-link'.")
8547 (defvar org-store-link-plist nil
8548 "Plist with info about the most recently link created with `org-store-link'.")
8550 (defvar org-link-protocols nil
8551 "Link protocols added to Org-mode using `org-add-link-type'.")
8553 (defvar org-store-link-functions nil
8554 "List of functions that are called to create and store a link.
8555 Each function will be called in turn until one returns a non-nil
8556 value. Each function should check if it is responsible for creating
8557 this link (for example by looking at the major mode).
8558 If not, it must exit and return nil.
8559 If yes, it should return a non-nil value after a calling
8560 `org-store-link-props' with a list of properties and values.
8561 Special properties are:
8563 :type The link prefix, like \"http\". This must be given.
8564 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8565 This is obligatory as well.
8566 :description Optional default description for the second pair
8567 of brackets in an Org-mode link. The user can still change
8568 this when inserting this link into an Org-mode buffer.
8570 In addition to these, any additional properties can be specified
8571 and then used in remember templates.")
8573 (defun org-add-link-type (type &optional follow export)
8574 "Add TYPE to the list of `org-link-types'.
8575 Re-compute all regular expressions depending on `org-link-types'
8577 FOLLOW and EXPORT are two functions.
8579 FOLLOW should take the link path as the single argument and do whatever
8580 is necessary to follow the link, for example find a file or display
8581 a mail message.
8583 EXPORT should format the link path for export to one of the export formats.
8584 It should be a function accepting three arguments:
8586 path the path of the link, the text after the prefix (like \"http:\")
8587 desc the description of the link, if any, or a description added by
8588 org-export-normalize-links if there is none
8589 format the export format, a symbol like `html' or `latex' or `ascii'..
8591 The function may use the FORMAT information to return different values
8592 depending on the format. The return value will be put literally into
8593 the exported file. If the return value is nil, this means Org should
8594 do what it normally does with links which do not have EXPORT defined.
8596 Org-mode has a built-in default for exporting links. If you are happy with
8597 this default, there is no need to define an export function for the link
8598 type. For a simple example of an export function, see `org-bbdb.el'."
8599 (add-to-list 'org-link-types type t)
8600 (org-make-link-regexps)
8601 (if (assoc type org-link-protocols)
8602 (setcdr (assoc type org-link-protocols) (list follow export))
8603 (push (list type follow export) org-link-protocols)))
8605 (defvar org-agenda-buffer-name)
8607 ;;;###autoload
8608 (defun org-store-link (arg)
8609 "\\<org-mode-map>Store an org-link to the current location.
8610 This link is added to `org-stored-links' and can later be inserted
8611 into an org-buffer with \\[org-insert-link].
8613 For some link types, a prefix arg is interpreted:
8614 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8615 For file links, arg negates `org-context-in-file-links'."
8616 (interactive "P")
8617 (org-load-modules-maybe)
8618 (setq org-store-link-plist nil) ; reset
8619 (org-with-limited-levels
8620 (let (link cpltxt desc description search txt custom-id agenda-link)
8621 (cond
8623 ((run-hook-with-args-until-success 'org-store-link-functions)
8624 (setq link (plist-get org-store-link-plist :link)
8625 desc (or (plist-get org-store-link-plist :description) link)))
8627 ((equal (buffer-name) "*Org Edit Src Example*")
8628 (let (label gc)
8629 (while (or (not label)
8630 (save-excursion
8631 (save-restriction
8632 (widen)
8633 (goto-char (point-min))
8634 (re-search-forward
8635 (regexp-quote (format org-coderef-label-format label))
8636 nil t))))
8637 (when label (message "Label exists already") (sit-for 2))
8638 (setq label (read-string "Code line label: " label)))
8639 (end-of-line 1)
8640 (setq link (format org-coderef-label-format label))
8641 (setq gc (- 79 (length link)))
8642 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8643 (insert link)
8644 (setq link (concat "(" label ")") desc nil)))
8646 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8647 ;; We are in the agenda, link to referenced location
8648 (let ((m (or (get-text-property (point) 'org-hd-marker)
8649 (get-text-property (point) 'org-marker))))
8650 (when m
8651 (org-with-point-at m
8652 (setq agenda-link
8653 (if (org-called-interactively-p 'any)
8654 (call-interactively 'org-store-link)
8655 (org-store-link nil)))))))
8657 ((eq major-mode 'calendar-mode)
8658 (let ((cd (calendar-cursor-to-date)))
8659 (setq link
8660 (format-time-string
8661 (car org-time-stamp-formats)
8662 (apply 'encode-time
8663 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8664 nil nil nil))))
8665 (org-store-link-props :type "calendar" :date cd)))
8667 ((eq major-mode 'w3-mode)
8668 (setq cpltxt (if (and (buffer-name)
8669 (not (string-match "Untitled" (buffer-name))))
8670 (buffer-name)
8671 (url-view-url t))
8672 link (org-make-link (url-view-url t)))
8673 (org-store-link-props :type "w3" :url (url-view-url t)))
8675 ((eq major-mode 'w3m-mode)
8676 (setq cpltxt (or w3m-current-title w3m-current-url)
8677 link (org-make-link w3m-current-url))
8678 (org-store-link-props :type "w3m" :url (url-view-url t)))
8680 ((setq search (run-hook-with-args-until-success
8681 'org-create-file-search-functions))
8682 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8683 "::" search))
8684 (setq cpltxt (or description link)))
8686 ((eq major-mode 'image-mode)
8687 (setq cpltxt (concat "file:"
8688 (abbreviate-file-name buffer-file-name))
8689 link (org-make-link cpltxt))
8690 (org-store-link-props :type "image" :file buffer-file-name))
8692 ((eq major-mode 'dired-mode)
8693 ;; link to the file in the current line
8694 (let ((file (dired-get-filename nil t)))
8695 (setq file (if file
8696 (abbreviate-file-name
8697 (expand-file-name (dired-get-filename nil t)))
8698 ;; otherwise, no file so use current directory.
8699 default-directory))
8700 (setq cpltxt (concat "file:" file)
8701 link (org-make-link cpltxt))))
8703 ((and (buffer-file-name (buffer-base-buffer)) (eq major-mode 'org-mode))
8704 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8705 (cond
8706 ((org-in-regexp "<<\\(.*?\\)>>")
8707 (setq cpltxt
8708 (concat "file:"
8709 (abbreviate-file-name
8710 (buffer-file-name (buffer-base-buffer)))
8711 "::" (match-string 1))
8712 link (org-make-link cpltxt)))
8713 ((and (featurep 'org-id)
8714 (or (eq org-link-to-org-use-id t)
8715 (and (eq org-link-to-org-use-id 'create-if-interactive)
8716 (org-called-interactively-p 'any))
8717 (and (eq org-link-to-org-use-id
8718 'create-if-interactive-and-no-custom-id)
8719 (org-called-interactively-p 'any)
8720 (not custom-id))
8721 (and org-link-to-org-use-id
8722 (org-entry-get nil "ID"))))
8723 ;; We can make a link using the ID.
8724 (setq link (condition-case nil
8725 (prog1 (org-id-store-link)
8726 (setq desc (plist-get org-store-link-plist
8727 :description)))
8728 (error
8729 ;; probably before first headline, link to file only
8730 (concat "file:"
8731 (abbreviate-file-name
8732 (buffer-file-name (buffer-base-buffer))))))))
8734 ;; Just link to current headline
8735 (setq cpltxt (concat "file:"
8736 (abbreviate-file-name
8737 (buffer-file-name (buffer-base-buffer)))))
8738 ;; Add a context search string
8739 (when (org-xor org-context-in-file-links arg)
8740 (setq txt (cond
8741 ((org-on-heading-p) nil)
8742 ((org-region-active-p)
8743 (buffer-substring (region-beginning) (region-end)))
8744 (t nil)))
8745 (when (or (null txt) (string-match "\\S-" txt))
8746 (setq cpltxt
8747 (concat cpltxt "::"
8748 (condition-case nil
8749 (org-make-org-heading-search-string txt)
8750 (error "")))
8751 desc (or (nth 4 (ignore-errors
8752 (org-heading-components))) "NONE"))))
8753 (if (string-match "::\\'" cpltxt)
8754 (setq cpltxt (substring cpltxt 0 -2)))
8755 (setq link (org-make-link cpltxt)))))
8757 ((buffer-file-name (buffer-base-buffer))
8758 ;; Just link to this file here.
8759 (setq cpltxt (concat "file:"
8760 (abbreviate-file-name
8761 (buffer-file-name (buffer-base-buffer)))))
8762 ;; Add a context string
8763 (when (org-xor org-context-in-file-links arg)
8764 (setq txt (if (org-region-active-p)
8765 (buffer-substring (region-beginning) (region-end))
8766 (buffer-substring (point-at-bol) (point-at-eol))))
8767 ;; Only use search option if there is some text.
8768 (when (string-match "\\S-" txt)
8769 (setq cpltxt
8770 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8771 desc "NONE")))
8772 (setq link (org-make-link cpltxt)))
8774 ((org-called-interactively-p 'interactive)
8775 (error "Cannot link to a buffer which is not visiting a file"))
8777 (t (setq link nil)))
8779 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8780 (setq link (or link cpltxt)
8781 desc (or desc cpltxt))
8782 (if (equal desc "NONE") (setq desc nil))
8784 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8785 (progn
8786 (setq org-stored-links
8787 (cons (list link desc) org-stored-links))
8788 (message "Stored: %s" (or desc link))
8789 (when custom-id
8790 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8791 "::#" custom-id))
8792 (setq org-stored-links
8793 (cons (list link desc) org-stored-links))))
8794 (or agenda-link (and link (org-make-link-string link desc)))))))
8796 (defun org-store-link-props (&rest plist)
8797 "Store link properties, extract names and addresses."
8798 (let (x adr)
8799 (when (setq x (plist-get plist :from))
8800 (setq adr (mail-extract-address-components x))
8801 (setq plist (plist-put plist :fromname (car adr)))
8802 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8803 (when (setq x (plist-get plist :to))
8804 (setq adr (mail-extract-address-components x))
8805 (setq plist (plist-put plist :toname (car adr)))
8806 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8807 (let ((from (plist-get plist :from))
8808 (to (plist-get plist :to)))
8809 (when (and from to org-from-is-user-regexp)
8810 (setq plist
8811 (plist-put plist :fromto
8812 (if (string-match org-from-is-user-regexp from)
8813 (concat "to %t")
8814 (concat "from %f"))))))
8815 (setq org-store-link-plist plist))
8817 (defun org-add-link-props (&rest plist)
8818 "Add these properties to the link property list."
8819 (let (key value)
8820 (while plist
8821 (setq key (pop plist) value (pop plist))
8822 (setq org-store-link-plist
8823 (plist-put org-store-link-plist key value)))))
8825 (defun org-email-link-description (&optional fmt)
8826 "Return the description part of an email link.
8827 This takes information from `org-store-link-plist' and formats it
8828 according to FMT (default from `org-email-link-description-format')."
8829 (setq fmt (or fmt org-email-link-description-format))
8830 (let* ((p org-store-link-plist)
8831 (to (plist-get p :toaddress))
8832 (from (plist-get p :fromaddress))
8833 (table
8834 (list
8835 (cons "%c" (plist-get p :fromto))
8836 (cons "%F" (plist-get p :from))
8837 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8838 (cons "%T" (plist-get p :to))
8839 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8840 (cons "%s" (plist-get p :subject))
8841 (cons "%d" (plist-get p :date))
8842 (cons "%m" (plist-get p :message-id)))))
8843 (when (string-match "%c" fmt)
8844 ;; Check if the user wrote this message
8845 (if (and org-from-is-user-regexp from to
8846 (save-match-data (string-match org-from-is-user-regexp from)))
8847 (setq fmt (replace-match "to %t" t t fmt))
8848 (setq fmt (replace-match "from %f" t t fmt))))
8849 (org-replace-escapes fmt table)))
8851 (defun org-make-org-heading-search-string (&optional string heading)
8852 "Make search string for STRING or current headline."
8853 (interactive)
8854 (let ((s (or string (org-get-heading)))
8855 (lines org-context-in-file-links))
8856 (unless (and string (not heading))
8857 ;; We are using a headline, clean up garbage in there.
8858 (if (string-match org-todo-regexp s)
8859 (setq s (replace-match "" t t s)))
8860 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8861 (setq s (replace-match "" t t s)))
8862 (setq s (org-trim s))
8863 (if (string-match (concat "^\\(" org-quote-string "\\|"
8864 org-comment-string "\\)") s)
8865 (setq s (replace-match "" t t s)))
8866 (while (string-match org-ts-regexp s)
8867 (setq s (replace-match "" t t s))))
8868 (or string (setq s (concat "*" s))) ; Add * for headlines
8869 (when (and string (integerp lines) (> lines 0))
8870 (let ((slines (org-split-string s "\n")))
8871 (when (< lines (length slines))
8872 (setq s (mapconcat
8873 'identity
8874 (reverse (nthcdr (- (length slines) lines)
8875 (reverse slines))) "\n")))))
8876 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8878 (defun org-make-link (&rest strings)
8879 "Concatenate STRINGS."
8880 (apply 'concat strings))
8882 (defun org-make-link-string (link &optional description)
8883 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8884 (unless (string-match "\\S-" link)
8885 (error "Empty link"))
8886 (when (and description
8887 (stringp description)
8888 (not (string-match "\\S-" description)))
8889 (setq description nil))
8890 (when (stringp description)
8891 ;; Remove brackets from the description, they are fatal.
8892 (while (string-match "\\[" description)
8893 (setq description (replace-match "{" t t description)))
8894 (while (string-match "\\]" description)
8895 (setq description (replace-match "}" t t description))))
8896 (when (equal link description)
8897 ;; No description needed, it is identical
8898 (setq description nil))
8899 (when (and (not description)
8900 (not (string-match (org-image-file-name-regexp) link))
8901 (not (equal link (org-link-escape link))))
8902 (setq description (org-extract-attributes link)))
8903 (setq link
8904 (cond ((string-match (org-image-file-name-regexp) link) link)
8905 ((string-match org-link-types-re link)
8906 (concat (match-string 1 link)
8907 (org-link-escape (substring link (match-end 1)))))
8908 (t (org-link-escape link))))
8909 (concat "[[" link "]"
8910 (if description (concat "[" description "]") "")
8911 "]"))
8913 (defconst org-link-escape-chars
8914 '(?\ ?\[ ?\] ?\; ?\= ?\+)
8915 "List of characters that should be escaped in link.
8916 This is the list that is used for internal purposes.")
8918 (defvar org-url-encoding-use-url-hexify nil)
8920 (defconst org-link-escape-chars-browser
8921 '(?\ )
8922 "List of escapes for characters that are problematic in links.
8923 This is the list that is used before handing over to the browser.")
8925 (defun org-link-escape (text &optional table merge)
8926 "Return percent escaped representation of TEXT.
8927 TEXT is a string with the text to escape.
8928 Optional argument TABLE is a list with characters that should be
8929 escaped. When nil, `org-link-escape-chars' is used.
8930 If optional argument MERGE is set, merge TABLE into
8931 `org-link-escape-chars'."
8932 (if (and org-url-encoding-use-url-hexify (not table))
8933 (url-hexify-string text)
8934 (cond
8935 ((and table merge)
8936 (mapc (lambda (defchr)
8937 (unless (member defchr table)
8938 (setq table (cons defchr table)))) org-link-escape-chars))
8939 ((null table)
8940 (setq table org-link-escape-chars)))
8941 (mapconcat
8942 (lambda (char)
8943 (if (or (member char table)
8944 (< char 32) (= char 37) (> char 126))
8945 (mapconcat (lambda (sequence-element)
8946 (format "%%%.2X" sequence-element))
8947 (or (encode-coding-char char 'utf-8)
8948 (error "Unable to percent escape character: %s"
8949 (char-to-string char))) "")
8950 (char-to-string char))) text "")))
8952 (defun org-link-unescape (str)
8953 "Unhex hexified Unicode strings as returned from the JavaScript function
8954 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
8955 (unless (and (null str) (string= "" str))
8956 (let ((pos 0) (case-fold-search t) unhexed)
8957 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
8958 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
8959 (setq str (replace-match unhexed t t str))
8960 (setq pos (+ pos (length unhexed))))))
8961 str)
8963 (defun org-link-unescape-compound (hex)
8964 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
8965 Note: this function also decodes single byte encodings like
8966 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
8967 (save-match-data
8968 (let* ((bytes (cdr (split-string hex "%")))
8969 (ret "")
8970 (eat 0)
8971 (sum 0))
8972 (while bytes
8973 (let* ((val (string-to-number (pop bytes) 16))
8974 (shift-xor
8975 (if (= 0 eat)
8976 (cond
8977 ((>= val 252) (cons 6 252))
8978 ((>= val 248) (cons 5 248))
8979 ((>= val 240) (cons 4 240))
8980 ((>= val 224) (cons 3 224))
8981 ((>= val 192) (cons 2 192))
8982 (t (cons 0 0)))
8983 (cons 6 128))))
8984 (if (>= val 192) (setq eat (car shift-xor)))
8985 (setq val (logxor val (cdr shift-xor)))
8986 (setq sum (+ (lsh sum (car shift-xor)) val))
8987 (if (> eat 0) (setq eat (- eat 1)))
8988 (cond
8989 ((= 0 eat) ;multi byte
8990 (setq ret (concat ret (org-char-to-string sum)))
8991 (setq sum 0))
8992 ((not bytes) ; single byte(s)
8993 (setq ret (org-link-unescape-single-byte-sequence hex))))
8994 )) ;; end (while bytes
8995 ret )))
8997 (defun org-link-unescape-single-byte-sequence (hex)
8998 "Unhexify hex-encoded single byte character sequences."
8999 (mapconcat (lambda (byte)
9000 (char-to-string (string-to-number byte 16)))
9001 (cdr (split-string hex "%")) ""))
9003 (defun org-xor (a b)
9004 "Exclusive or."
9005 (if a (not b) b))
9007 (defun org-fixup-message-id-for-http (s)
9008 "Replace special characters in a message id, so it can be used in an http query."
9009 (when (string-match "%" s)
9010 (setq s (mapconcat (lambda (c)
9011 (if (eq c ?%)
9012 "%25"
9013 (char-to-string c)))
9014 s "")))
9015 (while (string-match "<" s)
9016 (setq s (replace-match "%3C" t t s)))
9017 (while (string-match ">" s)
9018 (setq s (replace-match "%3E" t t s)))
9019 (while (string-match "@" s)
9020 (setq s (replace-match "%40" t t s)))
9023 ;;;###autoload
9024 (defun org-insert-link-global ()
9025 "Insert a link like Org-mode does.
9026 This command can be called in any mode to insert a link in Org-mode syntax."
9027 (interactive)
9028 (org-load-modules-maybe)
9029 (org-run-like-in-org-mode 'org-insert-link))
9031 (defun org-insert-link (&optional complete-file link-location default-description)
9032 "Insert a link. At the prompt, enter the link.
9034 Completion can be used to insert any of the link protocol prefixes like
9035 http or ftp in use.
9037 The history can be used to select a link previously stored with
9038 `org-store-link'. When the empty string is entered (i.e. if you just
9039 press RET at the prompt), the link defaults to the most recently
9040 stored link. As SPC triggers completion in the minibuffer, you need to
9041 use M-SPC or C-q SPC to force the insertion of a space character.
9043 You will also be prompted for a description, and if one is given, it will
9044 be displayed in the buffer instead of the link.
9046 If there is already a link at point, this command will allow you to edit link
9047 and description parts.
9049 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9050 be selected using completion. The path to the file will be relative to the
9051 current directory if the file is in the current directory or a subdirectory.
9052 Otherwise, the link will be the absolute path as completed in the minibuffer
9053 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9054 option `org-link-file-path-type'.
9056 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9057 the current directory or below.
9059 With three \\[universal-argument] prefixes, negate the meaning of
9060 `org-keep-stored-link-after-insertion'.
9062 If `org-make-link-description-function' is non-nil, this function will be
9063 called with the link target, and the result will be the default
9064 link description.
9066 If the LINK-LOCATION parameter is non-nil, this value will be
9067 used as the link location instead of reading one interactively.
9069 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9070 be used as the default description."
9071 (interactive "P")
9072 (let* ((wcf (current-window-configuration))
9073 (region (if (org-region-active-p)
9074 (buffer-substring (region-beginning) (region-end))))
9075 (remove (and region (list (region-beginning) (region-end))))
9076 (desc region)
9077 tmphist ; byte-compile incorrectly complains about this
9078 (link link-location)
9079 entry file all-prefixes)
9080 (cond
9081 (link-location) ; specified by arg, just use it.
9082 ((org-in-regexp org-bracket-link-regexp 1)
9083 ;; We do have a link at point, and we are going to edit it.
9084 (setq remove (list (match-beginning 0) (match-end 0)))
9085 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9086 (setq link (read-string "Link: "
9087 (org-link-unescape
9088 (org-match-string-no-properties 1)))))
9089 ((or (org-in-regexp org-angle-link-re)
9090 (org-in-regexp org-plain-link-re))
9091 ;; Convert to bracket link
9092 (setq remove (list (match-beginning 0) (match-end 0))
9093 link (read-string "Link: "
9094 (org-remove-angle-brackets (match-string 0)))))
9095 ((member complete-file '((4) (16)))
9096 ;; Completing read for file names.
9097 (setq link (org-file-complete-link complete-file)))
9099 ;; Read link, with completion for stored links.
9100 (with-output-to-temp-buffer "*Org Links*"
9101 (princ "Insert a link.
9102 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9103 (when org-stored-links
9104 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9105 (princ (mapconcat
9106 (lambda (x)
9107 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
9108 (reverse org-stored-links) "\n"))))
9109 (let ((cw (selected-window)))
9110 (select-window (get-buffer-window "*Org Links*" 'visible))
9111 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9112 (unless (pos-visible-in-window-p (point-max))
9113 (org-fit-window-to-buffer))
9114 (and (window-live-p cw) (select-window cw)))
9115 ;; Fake a link history, containing the stored links.
9116 (setq tmphist (append (mapcar 'car org-stored-links)
9117 org-insert-link-history))
9118 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
9119 (mapcar 'car org-link-abbrev-alist)
9120 org-link-types))
9121 (unwind-protect
9122 (progn
9123 (setq link
9124 (let ((org-completion-use-ido nil)
9125 (org-completion-use-iswitchb nil))
9126 (org-completing-read
9127 "Link: "
9128 (append
9129 (mapcar (lambda (x) (list (concat x ":")))
9130 all-prefixes)
9131 (mapcar 'car org-stored-links))
9132 nil nil nil
9133 'tmphist
9134 (car (car org-stored-links)))))
9135 (if (not (string-match "\\S-" link))
9136 (error "No link selected"))
9137 (if (or (member link all-prefixes)
9138 (and (equal ":" (substring link -1))
9139 (member (substring link 0 -1) all-prefixes)
9140 (setq link (substring link 0 -1))))
9141 (setq link (org-link-try-special-completion link))))
9142 (set-window-configuration wcf)
9143 (kill-buffer "*Org Links*"))
9144 (setq entry (assoc link org-stored-links))
9145 (or entry (push link org-insert-link-history))
9146 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9147 (not org-keep-stored-link-after-insertion))
9148 (setq org-stored-links (delq (assoc link org-stored-links)
9149 org-stored-links)))
9150 (setq desc (or desc (nth 1 entry)))))
9152 (if (string-match org-plain-link-re link)
9153 ;; URL-like link, normalize the use of angular brackets.
9154 (setq link (org-make-link (org-remove-angle-brackets link))))
9156 ;; Check if we are linking to the current file with a search option
9157 ;; If yes, simplify the link by using only the search option.
9158 (when (and buffer-file-name
9159 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9160 (let* ((path (match-string 1 link))
9161 (case-fold-search nil)
9162 (search (match-string 2 link)))
9163 (save-match-data
9164 (if (equal (file-truename buffer-file-name) (file-truename path))
9165 ;; We are linking to this same file, with a search option
9166 (setq link search)))))
9168 ;; Check if we can/should use a relative path. If yes, simplify the link
9169 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9170 (let* ((type (match-string 1 link))
9171 (path (match-string 2 link))
9172 (origpath path)
9173 (case-fold-search nil))
9174 (cond
9175 ((or (eq org-link-file-path-type 'absolute)
9176 (equal complete-file '(16)))
9177 (setq path (abbreviate-file-name (expand-file-name path))))
9178 ((eq org-link-file-path-type 'noabbrev)
9179 (setq path (expand-file-name path)))
9180 ((eq org-link-file-path-type 'relative)
9181 (setq path (file-relative-name path)))
9183 (save-match-data
9184 (if (string-match (concat "^" (regexp-quote
9185 (expand-file-name
9186 (file-name-as-directory
9187 default-directory))))
9188 (expand-file-name path))
9189 ;; We are linking a file with relative path name.
9190 (setq path (substring (expand-file-name path)
9191 (match-end 0)))
9192 (setq path (abbreviate-file-name (expand-file-name path)))))))
9193 (setq link (concat type path))
9194 (if (equal desc origpath)
9195 (setq desc path))))
9197 (if org-make-link-description-function
9198 (setq desc (funcall org-make-link-description-function link desc))
9199 (if default-description (setq desc default-description)))
9201 (setq desc (read-string "Description: " desc))
9202 (unless (string-match "\\S-" desc) (setq desc nil))
9203 (if remove (apply 'delete-region remove))
9204 (insert (org-make-link-string link desc))))
9206 (defun org-link-try-special-completion (type)
9207 "If there is completion support for link type TYPE, offer it."
9208 (let ((fun (intern (concat "org-" type "-complete-link"))))
9209 (if (functionp fun)
9210 (funcall fun)
9211 (read-string "Link (no completion support): " (concat type ":")))))
9213 (defun org-file-complete-link (&optional arg)
9214 "Create a file link using completion."
9215 (let (file link)
9216 (setq file (read-file-name "File: "))
9217 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9218 (pwd1 (file-name-as-directory (abbreviate-file-name
9219 (expand-file-name ".")))))
9220 (cond
9221 ((equal arg '(16))
9222 (setq link (org-make-link
9223 "file:"
9224 (abbreviate-file-name (expand-file-name file)))))
9225 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9226 (setq link (org-make-link "file:" (match-string 1 file))))
9227 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9228 (expand-file-name file))
9229 (setq link (org-make-link
9230 "file:" (match-string 1 (expand-file-name file)))))
9231 (t (setq link (org-make-link "file:" file)))))
9232 link))
9234 (defun org-completing-read (&rest args)
9235 "Completing-read with SPACE being a normal character."
9236 (let ((enable-recursive-minibuffers t)
9237 (minibuffer-local-completion-map
9238 (copy-keymap minibuffer-local-completion-map)))
9239 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9240 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9241 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9242 (apply 'org-icompleting-read args)))
9244 (defun org-completing-read-no-i (&rest args)
9245 (let (org-completion-use-ido org-completion-use-iswitchb)
9246 (apply 'org-completing-read args)))
9248 (defun org-iswitchb-completing-read (prompt choices &rest args)
9249 "Use iswitch as a completing-read replacement to choose from choices.
9250 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9251 from."
9252 (let* ((iswitchb-use-virtual-buffers nil)
9253 (iswitchb-make-buflist-hook
9254 (lambda ()
9255 (setq iswitchb-temp-buflist choices))))
9256 (iswitchb-read-buffer prompt)))
9258 (defun org-icompleting-read (&rest args)
9259 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9260 (org-without-partial-completion
9261 (if (and org-completion-use-ido
9262 (fboundp 'ido-completing-read)
9263 (boundp 'ido-mode) ido-mode
9264 (listp (second args)))
9265 (let ((ido-enter-matching-directory nil))
9266 (apply 'ido-completing-read (concat (car args))
9267 (if (consp (car (nth 1 args)))
9268 (mapcar 'car (nth 1 args))
9269 (nth 1 args))
9270 (cddr args)))
9271 (if (and org-completion-use-iswitchb
9272 (boundp 'iswitchb-mode) iswitchb-mode
9273 (listp (second args)))
9274 (apply 'org-iswitchb-completing-read (concat (car args))
9275 (if (consp (car (nth 1 args)))
9276 (mapcar 'car (nth 1 args))
9277 (nth 1 args))
9278 (cddr args))
9279 (apply 'completing-read args)))))
9281 (defun org-extract-attributes (s)
9282 "Extract the attributes cookie from a string and set as text property."
9283 (let (a attr (start 0) key value)
9284 (save-match-data
9285 (when (string-match "{{\\([^}]+\\)}}$" s)
9286 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9287 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9288 (setq key (match-string 1 a) value (match-string 2 a)
9289 start (match-end 0)
9290 attr (plist-put attr (intern key) value))))
9291 (org-add-props s nil 'org-attr attr))
9294 (defun org-extract-attributes-from-string (tag)
9295 (let (key value attr)
9296 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9297 (setq key (match-string 1 tag) value (match-string 2 tag)
9298 tag (replace-match "" t t tag)
9299 attr (plist-put attr (intern key) value)))
9300 (cons tag attr)))
9302 (defun org-attributes-to-string (plist)
9303 "Format a property list into an HTML attribute list."
9304 (let ((s "") key value)
9305 (while plist
9306 (setq key (pop plist) value (pop plist))
9307 (and value
9308 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9311 ;;; Opening/following a link
9313 (defvar org-link-search-failed nil)
9315 (defvar org-open-link-functions nil
9316 "Hook for functions finding a plain text link.
9317 These functions must take a single argument, the link content.
9318 They will be called for links that look like [[link text][description]]
9319 when LINK TEXT does not have a protocol like \"http:\" and does not look
9320 like a filename (e.g. \"./blue.png\").
9322 These functions will be called *before* Org attempts to resolve the
9323 link by doing text searches in the current buffer - so if you want a
9324 link \"[[target]]\" to still find \"<<target>>\", your function should
9325 handle this as a special case.
9327 When the function does handle the link, it must return a non-nil value.
9328 If it decides that it is not responsible for this link, it must return
9329 nil to indicate that that Org-mode can continue with other options
9330 like exact and fuzzy text search.")
9332 (defun org-next-link ()
9333 "Move forward to the next link.
9334 If the link is in hidden text, expose it."
9335 (interactive)
9336 (when (and org-link-search-failed (eq this-command last-command))
9337 (goto-char (point-min))
9338 (message "Link search wrapped back to beginning of buffer"))
9339 (setq org-link-search-failed nil)
9340 (let* ((pos (point))
9341 (ct (org-context))
9342 (a (assoc :link ct)))
9343 (if a (goto-char (nth 2 a)))
9344 (if (re-search-forward org-any-link-re nil t)
9345 (progn
9346 (goto-char (match-beginning 0))
9347 (if (outline-invisible-p) (org-show-context)))
9348 (goto-char pos)
9349 (setq org-link-search-failed t)
9350 (error "No further link found"))))
9352 (defun org-previous-link ()
9353 "Move backward to the previous link.
9354 If the link is in hidden text, expose it."
9355 (interactive)
9356 (when (and org-link-search-failed (eq this-command last-command))
9357 (goto-char (point-max))
9358 (message "Link search wrapped back to end of buffer"))
9359 (setq org-link-search-failed nil)
9360 (let* ((pos (point))
9361 (ct (org-context))
9362 (a (assoc :link ct)))
9363 (if a (goto-char (nth 1 a)))
9364 (if (re-search-backward org-any-link-re nil t)
9365 (progn
9366 (goto-char (match-beginning 0))
9367 (if (outline-invisible-p) (org-show-context)))
9368 (goto-char pos)
9369 (setq org-link-search-failed t)
9370 (error "No further link found"))))
9372 (defun org-translate-link (s)
9373 "Translate a link string if a translation function has been defined."
9374 (if (and org-link-translation-function
9375 (fboundp org-link-translation-function)
9376 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9377 (progn
9378 (setq s (funcall org-link-translation-function
9379 (match-string 1) (match-string 2)))
9380 (concat (car s) ":" (cdr s)))
9383 (defun org-translate-link-from-planner (type path)
9384 "Translate a link from Emacs Planner syntax so that Org can follow it.
9385 This is still an experimental function, your mileage may vary."
9386 (cond
9387 ((member type '("http" "https" "news" "ftp"))
9388 ;; standard Internet links are the same.
9389 nil)
9390 ((and (equal type "irc") (string-match "^//" path))
9391 ;; Planner has two / at the beginning of an irc link, we have 1.
9392 ;; We should have zero, actually....
9393 (setq path (substring path 1)))
9394 ((and (equal type "lisp") (string-match "^/" path))
9395 ;; Planner has a slash, we do not.
9396 (setq type "elisp" path (substring path 1)))
9397 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9398 ;; A typical message link. Planner has the id after the final slash,
9399 ;; we separate it with a hash mark
9400 (setq path (concat (match-string 1 path) "#"
9401 (org-remove-angle-brackets (match-string 2 path)))))
9403 (cons type path))
9405 (defun org-find-file-at-mouse (ev)
9406 "Open file link or URL at mouse."
9407 (interactive "e")
9408 (mouse-set-point ev)
9409 (org-open-at-point 'in-emacs))
9411 (defun org-open-at-mouse (ev)
9412 "Open file link or URL at mouse.
9413 See the docstring of `org-open-file' for details."
9414 (interactive "e")
9415 (mouse-set-point ev)
9416 (if (eq major-mode 'org-agenda-mode)
9417 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9418 (org-open-at-point))
9420 (defvar org-window-config-before-follow-link nil
9421 "The window configuration before following a link.
9422 This is saved in case the need arises to restore it.")
9424 (defvar org-open-link-marker (make-marker)
9425 "Marker pointing to the location where `org-open-at-point; was called.")
9427 ;;;###autoload
9428 (defun org-open-at-point-global ()
9429 "Follow a link like Org-mode does.
9430 This command can be called in any mode to follow a link that has
9431 Org-mode syntax."
9432 (interactive)
9433 (org-run-like-in-org-mode 'org-open-at-point))
9435 ;;;###autoload
9436 (defun org-open-link-from-string (s &optional arg reference-buffer)
9437 "Open a link in the string S, as if it was in Org-mode."
9438 (interactive "sLink: \nP")
9439 (let ((reference-buffer (or reference-buffer (current-buffer))))
9440 (with-temp-buffer
9441 (let ((org-inhibit-startup t))
9442 (org-mode)
9443 (insert s)
9444 (goto-char (point-min))
9445 (when reference-buffer
9446 (setq org-link-abbrev-alist-local
9447 (with-current-buffer reference-buffer
9448 org-link-abbrev-alist-local)))
9449 (org-open-at-point arg reference-buffer)))))
9451 (defvar org-open-at-point-functions nil
9452 "Hook that is run when following a link at point.
9454 Functions in this hook must return t if they identify and follow
9455 a link at point. If they don't find anything interesting at point,
9456 they must return nil.")
9458 (defun org-open-at-point (&optional arg reference-buffer)
9459 "Open link at or after point.
9460 If there is no link at point, this function will search forward up to
9461 the end of the current line.
9462 Normally, files will be opened by an appropriate application. If the
9463 optional prefix argument ARG is non-nil, Emacs will visit the file.
9464 With a double prefix argument, try to open outside of Emacs, in the
9465 application the system uses for this file type."
9466 (interactive "P")
9467 ;; if in a code block, then open the block's results
9468 (unless (call-interactively #'org-babel-open-src-block-result)
9469 (org-load-modules-maybe)
9470 (move-marker org-open-link-marker (point))
9471 (setq org-window-config-before-follow-link (current-window-configuration))
9472 (org-remove-occur-highlights nil nil t)
9473 (cond
9474 ((and (org-on-heading-p)
9475 (not (org-in-regexp
9476 (concat org-plain-link-re "\\|"
9477 org-bracket-link-regexp "\\|"
9478 org-angle-link-re "\\|"
9479 "[ \t]:[^ \t\n]+:[ \t]*$")))
9480 (not (get-text-property (point) 'org-linked-text)))
9481 (or (org-offer-links-in-entry arg)
9482 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9483 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9484 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9485 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9486 (not (org-in-regexp org-bracket-link-regexp)))
9487 (org-footnote-action))
9489 (let (type path link line search (pos (point)))
9490 (catch 'match
9491 (save-excursion
9492 (skip-chars-forward "^]\n\r")
9493 (when (org-in-regexp org-bracket-link-regexp 1)
9494 (setq link (org-extract-attributes
9495 (org-link-unescape (org-match-string-no-properties 1))))
9496 (while (string-match " *\n *" link)
9497 (setq link (replace-match " " t t link)))
9498 (setq link (org-link-expand-abbrev link))
9499 (cond
9500 ((or (file-name-absolute-p link)
9501 (string-match "^\\.\\.?/" link))
9502 (setq type "file" path link))
9503 ((string-match org-link-re-with-space3 link)
9504 (setq type (match-string 1 link) path (match-string 2 link)))
9505 (t (setq type "thisfile" path link)))
9506 (throw 'match t)))
9508 (when (get-text-property (point) 'org-linked-text)
9509 (setq type "thisfile"
9510 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9511 (1+ (point)) (point))
9512 path (buffer-substring
9513 (or (previous-single-property-change pos 'org-linked-text)
9514 (point-min))
9515 (or (next-single-property-change pos 'org-linked-text)
9516 (point-max))))
9517 (throw 'match t))
9519 (save-excursion
9520 (when (or (org-in-regexp org-angle-link-re)
9521 (org-in-regexp org-plain-link-re))
9522 (setq type (match-string 1)
9523 path (org-link-unescape (match-string 2)))
9524 (throw 'match t)))
9525 (save-excursion
9526 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9527 (setq type "tags"
9528 path (match-string 1))
9529 (while (string-match ":" path)
9530 (setq path (replace-match "+" t t path)))
9531 (throw 'match t)))
9532 (when (org-in-regexp "<\\([^><\n]+\\)>")
9533 (setq type "tree-match"
9534 path (match-string 1))
9535 (throw 'match t)))
9536 (unless path
9537 (error "No link found"))
9539 ;; switch back to reference buffer
9540 ;; needed when if called in a temporary buffer through
9541 ;; org-open-link-from-string
9542 (with-current-buffer (or reference-buffer (current-buffer))
9544 ;; Remove any trailing spaces in path
9545 (if (string-match " +\\'" path)
9546 (setq path (replace-match "" t t path)))
9547 (if (and org-link-translation-function
9548 (fboundp org-link-translation-function))
9549 ;; Check if we need to translate the link
9550 (let ((tmp (funcall org-link-translation-function type path)))
9551 (setq type (car tmp) path (cdr tmp))))
9553 (cond
9555 ((assoc type org-link-protocols)
9556 (funcall (nth 1 (assoc type org-link-protocols)) path))
9558 ((equal type "mailto")
9559 (let ((cmd (car org-link-mailto-program))
9560 (args (cdr org-link-mailto-program)) args1
9561 (address path) (subject "") a)
9562 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9563 (setq address (match-string 1 path)
9564 subject (org-link-escape (match-string 2 path))))
9565 (while args
9566 (cond
9567 ((not (stringp (car args))) (push (pop args) args1))
9568 (t (setq a (pop args))
9569 (if (string-match "%a" a)
9570 (setq a (replace-match address t t a)))
9571 (if (string-match "%s" a)
9572 (setq a (replace-match subject t t a)))
9573 (push a args1))))
9574 (apply cmd (nreverse args1))))
9576 ((member type '("http" "https" "ftp" "news"))
9577 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9578 (org-link-escape
9579 path org-link-escape-chars-browser)
9580 path))))
9582 ((string= type "doi")
9583 (browse-url (concat "http://dx.doi.org/" (if (org-string-match-p "[[:nonascii:] ]" path)
9584 (org-link-escape
9585 path org-link-escape-chars-browser)
9586 path))))
9588 ((member type '("message"))
9589 (browse-url (concat type ":" path)))
9591 ((string= type "tags")
9592 (org-tags-view arg path))
9594 ((string= type "tree-match")
9595 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9597 ((string= type "file")
9598 (if (string-match "::\\([0-9]+\\)\\'" path)
9599 (setq line (string-to-number (match-string 1 path))
9600 path (substring path 0 (match-beginning 0)))
9601 (if (string-match "::\\(.+\\)\\'" path)
9602 (setq search (match-string 1 path)
9603 path (substring path 0 (match-beginning 0)))))
9604 (if (string-match "[*?{]" (file-name-nondirectory path))
9605 (dired path)
9606 (org-open-file path arg line search)))
9608 ((string= type "shell")
9609 (let ((cmd path))
9610 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9611 (string-match org-confirm-shell-link-not-regexp cmd))
9612 (not org-confirm-shell-link-function)
9613 (funcall org-confirm-shell-link-function
9614 (format "Execute \"%s\" in shell? "
9615 (org-add-props cmd nil
9616 'face 'org-warning))))
9617 (progn
9618 (message "Executing %s" cmd)
9619 (shell-command cmd))
9620 (error "Abort"))))
9622 ((string= type "elisp")
9623 (let ((cmd path))
9624 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9625 (string-match org-confirm-elisp-link-not-regexp cmd))
9626 (not org-confirm-elisp-link-function)
9627 (funcall org-confirm-elisp-link-function
9628 (format "Execute \"%s\" as elisp? "
9629 (org-add-props cmd nil
9630 'face 'org-warning))))
9631 (message "%s => %s" cmd
9632 (if (equal (string-to-char cmd) ?\()
9633 (eval (read cmd))
9634 (call-interactively (read cmd))))
9635 (error "Abort"))))
9637 ((and (string= type "thisfile")
9638 (run-hook-with-args-until-success
9639 'org-open-link-functions path)))
9641 ((string= type "thisfile")
9642 (if arg
9643 (switch-to-buffer-other-window
9644 (org-get-buffer-for-internal-link (current-buffer)))
9645 (org-mark-ring-push))
9646 (let ((cmd `(org-link-search
9647 ,path
9648 ,(cond ((equal arg '(4)) ''occur)
9649 ((equal arg '(16)) ''org-occur)
9650 (t nil))
9651 ,pos)))
9652 (condition-case nil (let ((org-link-search-inhibit-query t))
9653 (eval cmd))
9654 (error (progn (widen) (eval cmd))))))
9657 (browse-url-at-point)))))))
9658 (move-marker org-open-link-marker nil)
9659 (run-hook-with-args 'org-follow-link-hook)))
9661 (defun org-offer-links-in-entry (&optional nth zero)
9662 "Offer links in the current entry and follow the selected link.
9663 If there is only one link, follow it immediately as well.
9664 If NTH is an integer, immediately pick the NTH link found.
9665 If ZERO is a string, check also this string for a link, and if
9666 there is one, offer it as link number zero."
9667 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9668 "\\(" org-angle-link-re "\\)\\|"
9669 "\\(" org-plain-link-re "\\)"))
9670 (cnt ?0)
9671 (in-emacs (if (integerp nth) nil nth))
9672 have-zero end links link c)
9673 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9674 (push (match-string 0 zero) links)
9675 (setq cnt (1- cnt) have-zero t))
9676 (save-excursion
9677 (org-back-to-heading t)
9678 (setq end (save-excursion (outline-next-heading) (point)))
9679 (while (re-search-forward re end t)
9680 (push (match-string 0) links))
9681 (setq links (org-uniquify (reverse links))))
9683 (cond
9684 ((null links)
9685 (message "No links"))
9686 ((equal (length links) 1)
9687 (setq link (list (car links))))
9688 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9689 (setq link (list (nth (if have-zero nth (1- nth)) links))))
9690 (t ; we have to select a link
9691 (save-excursion
9692 (save-window-excursion
9693 (delete-other-windows)
9694 (with-output-to-temp-buffer "*Select Link*"
9695 (mapc (lambda (l)
9696 (if (not (string-match org-bracket-link-regexp l))
9697 (princ (format "[%c] %s\n" (incf cnt)
9698 (org-remove-angle-brackets l)))
9699 (if (match-end 3)
9700 (princ (format "[%c] %s (%s)\n" (incf cnt)
9701 (match-string 3 l) (match-string 1 l)))
9702 (princ (format "[%c] %s\n" (incf cnt)
9703 (match-string 1 l))))))
9704 links))
9705 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9706 (message "Select link to open, RET to open all:")
9707 (setq c (read-char-exclusive))
9708 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9709 (when (equal c ?q) (error "Abort"))
9710 (if (equal c ?\C-m)
9711 (setq link links)
9712 (setq nth (- c ?0))
9713 (if have-zero (setq nth (1+ nth)))
9714 (unless (and (integerp nth) (>= (length links) nth))
9715 (error "Invalid link selection"))
9716 (setq link (list (nth (1- nth) links))))))
9717 (if link
9718 (let ((buf (current-buffer)))
9719 (dolist (l link)
9720 (org-open-link-from-string l in-emacs buf))
9722 nil)))
9724 ;; Add special file links that specify the way of opening
9726 (org-add-link-type "file+sys" 'org-open-file-with-system)
9727 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9728 (defun org-open-file-with-system (path)
9729 "Open file at PATH using the system way of opening it."
9730 (org-open-file path 'system))
9731 (defun org-open-file-with-emacs (path)
9732 "Open file at PATH in Emacs."
9733 (org-open-file path 'emacs))
9734 (defun org-remove-file-link-modifiers ()
9735 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9736 (goto-char (point-min))
9737 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9738 (org-if-unprotected
9739 (replace-match "file:" t t))))
9740 (eval-after-load "org-exp"
9741 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9742 'org-remove-file-link-modifiers))
9744 ;;;; Time estimates
9746 (defun org-get-effort (&optional pom)
9747 "Get the effort estimate for the current entry."
9748 (org-entry-get pom org-effort-property))
9750 ;;; File search
9752 (defvar org-create-file-search-functions nil
9753 "List of functions to construct the right search string for a file link.
9754 These functions are called in turn with point at the location to
9755 which the link should point.
9757 A function in the hook should first test if it would like to
9758 handle this file type, for example by checking the `major-mode'
9759 or the file extension. If it decides not to handle this file, it
9760 should just return nil to give other functions a chance. If it
9761 does handle the file, it must return the search string to be used
9762 when following the link. The search string will be part of the
9763 file link, given after a double colon, and `org-open-at-point'
9764 will automatically search for it. If special measures must be
9765 taken to make the search successful, another function should be
9766 added to the companion hook `org-execute-file-search-functions',
9767 which see.
9769 A function in this hook may also use `setq' to set the variable
9770 `description' to provide a suggestion for the descriptive text to
9771 be used for this link when it gets inserted into an Org-mode
9772 buffer with \\[org-insert-link].")
9774 (defvar org-execute-file-search-functions nil
9775 "List of functions to execute a file search triggered by a link.
9777 Functions added to this hook must accept a single argument, the
9778 search string that was part of the file link, the part after the
9779 double colon. The function must first check if it would like to
9780 handle this search, for example by checking the `major-mode' or
9781 the file extension. If it decides not to handle this search, it
9782 should just return nil to give other functions a chance. If it
9783 does handle the search, it must return a non-nil value to keep
9784 other functions from trying.
9786 Each function can access the current prefix argument through the
9787 variable `current-prefix-argument'. Note that a single prefix is
9788 used to force opening a link in Emacs, so it may be good to only
9789 use a numeric or double prefix to guide the search function.
9791 In case this is needed, a function in this hook can also restore
9792 the window configuration before `org-open-at-point' was called using:
9794 (set-window-configuration org-window-config-before-follow-link)")
9796 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9797 (defun org-link-search (s &optional type avoid-pos stealth)
9798 "Search for a link search option.
9799 If S is surrounded by forward slashes, it is interpreted as a
9800 regular expression. In org-mode files, this will create an `org-occur'
9801 sparse tree. In ordinary files, `occur' will be used to list matches.
9802 If the current buffer is in `dired-mode', grep will be used to search
9803 in all files. If AVOID-POS is given, ignore matches near that position.
9805 When optional argument STEALTH is non-nil, do not modify
9806 visibility around point, thus ignoring
9807 `org-show-hierarchy-above', `org-show-following-heading' and
9808 `org-show-siblings' variables."
9809 (let ((case-fold-search t)
9810 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9811 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9812 (append '(("") (" ") ("\t") ("\n"))
9813 org-emphasis-alist)
9814 "\\|") "\\)"))
9815 (pos (point))
9816 (pre nil) (post nil)
9817 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9818 (cond
9819 ;; First check if there are any special search functions
9820 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9821 ;; Now try the builtin stuff
9822 ((and (equal (string-to-char s0) ?#)
9823 (> (length s0) 1)
9824 (save-excursion
9825 (goto-char (point-min))
9826 (and
9827 (re-search-forward
9828 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9829 (setq type 'dedicated
9830 pos (match-beginning 0))))
9831 ;; There is an exact target for this
9832 (goto-char pos)
9833 (org-back-to-heading t)))
9834 ((save-excursion
9835 (goto-char (point-min))
9836 (and
9837 (re-search-forward
9838 (concat "<<" (regexp-quote s0) ">>") nil t)
9839 (setq type 'dedicated
9840 pos (match-beginning 0))))
9841 ;; There is an exact target for this
9842 (goto-char pos))
9843 ((and (string-match "^(\\(.*\\))$" s0)
9844 (save-excursion
9845 (goto-char (point-min))
9846 (and
9847 (re-search-forward
9848 (concat "[^[]" (regexp-quote
9849 (format org-coderef-label-format
9850 (match-string 1 s0))))
9851 nil t)
9852 (setq type 'dedicated
9853 pos (1+ (match-beginning 0))))))
9854 ;; There is a coderef target for this
9855 (goto-char pos))
9856 ((string-match "^/\\(.*\\)/$" s)
9857 ;; A regular expression
9858 (cond
9859 ((eq major-mode 'org-mode)
9860 (org-occur (match-string 1 s)))
9861 ;;((eq major-mode 'dired-mode)
9862 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9863 (t (org-do-occur (match-string 1 s)))))
9864 ((and (eq major-mode 'org-mode) org-link-search-must-match-exact-headline)
9865 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
9866 (goto-char (point-min))
9867 (cond
9868 ((let (case-fold-search)
9869 (re-search-forward (format org-complex-heading-regexp-format
9870 (regexp-quote s))
9871 nil t))
9872 ;; OK, found a match
9873 (setq type 'dedicated)
9874 (goto-char (match-beginning 0)))
9875 ((and (not org-link-search-inhibit-query)
9876 (eq org-link-search-must-match-exact-headline 'query-to-create)
9877 (y-or-n-p "No match - create this as a new heading? "))
9878 (goto-char (point-max))
9879 (or (bolp) (newline))
9880 (insert "* " s "\n")
9881 (beginning-of-line 0))
9883 (goto-char pos)
9884 (error "No match"))))
9886 ;; A normal search string
9887 (when (equal (string-to-char s) ?*)
9888 ;; Anchor on headlines, post may include tags.
9889 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
9890 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
9891 s (substring s 1)))
9892 (remove-text-properties
9893 0 (length s)
9894 '(face nil mouse-face nil keymap nil fontified nil) s)
9895 ;; Make a series of regular expressions to find a match
9896 (setq words (org-split-string s "[ \n\r\t]+")
9898 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9899 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
9900 "\\)" markers)
9901 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9902 re2a (concat "[ \t\r\n]" re2a_)
9903 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9904 re4 (concat "[^a-zA-Z_]" re4_)
9906 re1 (concat pre re2 post)
9907 re3 (concat pre (if pre re4_ re4) post)
9908 re5 (concat pre ".*" re4)
9909 re2 (concat pre re2)
9910 re2a (concat pre (if pre re2a_ re2a))
9911 re4 (concat pre (if pre re4_ re4))
9912 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9913 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9914 re5 "\\)"
9916 (cond
9917 ((eq type 'org-occur) (org-occur reall))
9918 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9919 (t (goto-char (point-min))
9920 (setq type 'fuzzy)
9921 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
9922 (org-search-not-self 1 re1 nil t)
9923 (org-search-not-self 1 re2 nil t)
9924 (org-search-not-self 1 re2a nil t)
9925 (org-search-not-self 1 re3 nil t)
9926 (org-search-not-self 1 re4 nil t)
9927 (org-search-not-self 1 re5 nil t)
9929 (goto-char (match-beginning 1))
9930 (goto-char pos)
9931 (error "No match"))))))
9932 (and (eq major-mode 'org-mode)
9933 (not stealth)
9934 (org-show-context 'link-search))
9935 type))
9937 (defun org-search-not-self (group &rest args)
9938 "Execute `re-search-forward', but only accept matches that do not
9939 enclose the position of `org-open-link-marker'."
9940 (let ((m org-open-link-marker))
9941 (catch 'exit
9942 (while (apply 're-search-forward args)
9943 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
9944 (goto-char (match-end group))
9945 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
9946 (> (match-beginning 0) (marker-position m))
9947 (< (match-end 0) (marker-position m)))
9948 (save-match-data
9949 (or (not (org-in-regexp
9950 org-bracket-link-analytic-regexp 1))
9951 (not (match-end 4)) ; no description
9952 (and (<= (match-beginning 4) (point))
9953 (>= (match-end 4) (point))))))
9954 (throw 'exit (point))))))))
9956 (defun org-get-buffer-for-internal-link (buffer)
9957 "Return a buffer to be used for displaying the link target of internal links."
9958 (cond
9959 ((not org-display-internal-link-with-indirect-buffer)
9960 buffer)
9961 ((string-match "(Clone)$" (buffer-name buffer))
9962 (message "Buffer is already a clone, not making another one")
9963 ;; we also do not modify visibility in this case
9964 buffer)
9965 (t ; make a new indirect buffer for displaying the link
9966 (let* ((bn (buffer-name buffer))
9967 (ibn (concat bn "(Clone)"))
9968 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
9969 (with-current-buffer ib (org-overview))
9970 ib))))
9972 (defun org-do-occur (regexp &optional cleanup)
9973 "Call the Emacs command `occur'.
9974 If CLEANUP is non-nil, remove the printout of the regular expression
9975 in the *Occur* buffer. This is useful if the regex is long and not useful
9976 to read."
9977 (occur regexp)
9978 (when cleanup
9979 (let ((cwin (selected-window)) win beg end)
9980 (when (setq win (get-buffer-window "*Occur*"))
9981 (select-window win))
9982 (goto-char (point-min))
9983 (when (re-search-forward "match[a-z]+" nil t)
9984 (setq beg (match-end 0))
9985 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9986 (setq end (1- (match-beginning 0)))))
9987 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
9988 (goto-char (point-min))
9989 (select-window cwin))))
9991 ;;; The mark ring for links jumps
9993 (defvar org-mark-ring nil
9994 "Mark ring for positions before jumps in Org-mode.")
9995 (defvar org-mark-ring-last-goto nil
9996 "Last position in the mark ring used to go back.")
9997 ;; Fill and close the ring
9998 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9999 (loop for i from 1 to org-mark-ring-length do
10000 (push (make-marker) org-mark-ring))
10001 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10002 org-mark-ring)
10004 (defun org-mark-ring-push (&optional pos buffer)
10005 "Put the current position or POS into the mark ring and rotate it."
10006 (interactive)
10007 (setq pos (or pos (point)))
10008 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10009 (move-marker (car org-mark-ring)
10010 (or pos (point))
10011 (or buffer (current-buffer)))
10012 (message "%s"
10013 (substitute-command-keys
10014 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10016 (defun org-mark-ring-goto (&optional n)
10017 "Jump to the previous position in the mark ring.
10018 With prefix arg N, jump back that many stored positions. When
10019 called several times in succession, walk through the entire ring.
10020 Org-mode commands jumping to a different position in the current file,
10021 or to another Org-mode file, automatically push the old position
10022 onto the ring."
10023 (interactive "p")
10024 (let (p m)
10025 (if (eq last-command this-command)
10026 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10027 (setq p org-mark-ring))
10028 (setq org-mark-ring-last-goto p)
10029 (setq m (car p))
10030 (org-pop-to-buffer-same-window (marker-buffer m))
10031 (goto-char m)
10032 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10034 (defun org-remove-angle-brackets (s)
10035 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10036 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10038 (defun org-add-angle-brackets (s)
10039 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10040 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10042 (defun org-remove-double-quotes (s)
10043 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10044 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10047 ;;; Following specific links
10049 (defun org-follow-timestamp-link ()
10050 (cond
10051 ((org-at-date-range-p t)
10052 (let ((org-agenda-start-on-weekday)
10053 (t1 (match-string 1))
10054 (t2 (match-string 2)))
10055 (setq t1 (time-to-days (org-time-string-to-time t1))
10056 t2 (time-to-days (org-time-string-to-time t2)))
10057 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10058 ((org-at-timestamp-p t)
10059 (org-agenda-list nil (time-to-days (org-time-string-to-time
10060 (substring (match-string 1) 0 10)))
10062 (t (error "This should not happen"))))
10065 ;;; Following file links
10066 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10067 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10068 (declare-function mailcap-mime-info
10069 "mailcap" (string &optional request no-decode))
10070 (defvar org-wait nil)
10071 (defun org-open-file (path &optional in-emacs line search)
10072 "Open the file at PATH.
10073 First, this expands any special file name abbreviations. Then the
10074 configuration variable `org-file-apps' is checked if it contains an
10075 entry for this file type, and if yes, the corresponding command is launched.
10077 If no application is found, Emacs simply visits the file.
10079 With optional prefix argument IN-EMACS, Emacs will visit the file.
10080 With a double \\[universal-argument] \\[universal-argument] \
10081 prefix arg, Org tries to avoid opening in Emacs
10082 and to use an external application to visit the file.
10084 Optional LINE specifies a line to go to, optional SEARCH a string
10085 to search for. If LINE or SEARCH is given, the file will be
10086 opened in Emacs, unless an entry from org-file-apps that makes
10087 use of groups in a regexp matches.
10089 If you want to change the way frames are used when following a
10090 link, please customize `org-link-frame-setup'.
10092 If the file does not exist, an error is thrown."
10093 (let* ((file (if (equal path "")
10094 buffer-file-name
10095 (substitute-in-file-name (expand-file-name path))))
10096 (file-apps (append org-file-apps (org-default-apps)))
10097 (apps (org-remove-if
10098 'org-file-apps-entry-match-against-dlink-p file-apps))
10099 (apps-dlink (org-remove-if-not
10100 'org-file-apps-entry-match-against-dlink-p file-apps))
10101 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10102 (dirp (if remp nil (file-directory-p file)))
10103 (file (if (and dirp org-open-directory-means-index-dot-org)
10104 (concat (file-name-as-directory file) "index.org")
10105 file))
10106 (a-m-a-p (assq 'auto-mode apps))
10107 (dfile (downcase file))
10108 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10109 (link (cond ((and (eq line nil)
10110 (eq search nil))
10111 file)
10112 (line
10113 (concat file "::" (number-to-string line)))
10114 (search
10115 (concat file "::" search))))
10116 (dlink (downcase link))
10117 (old-buffer (current-buffer))
10118 (old-pos (point))
10119 (old-mode major-mode)
10120 ext cmd link-match-data)
10121 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10122 (setq ext (match-string 1 dfile))
10123 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10124 (setq ext (match-string 1 dfile))))
10125 (cond
10126 ((member in-emacs '((16) system))
10127 (setq cmd (cdr (assoc 'system apps))))
10128 (in-emacs (setq cmd 'emacs))
10130 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10131 (and dirp (cdr (assoc 'directory apps)))
10132 ; first, try matching against apps-dlink
10133 ; if we get a match here, store the match data for later
10134 (let ((match (assoc-default dlink apps-dlink
10135 'string-match)))
10136 (if match
10137 (progn (setq link-match-data (match-data))
10138 match)
10139 (progn (setq in-emacs (or in-emacs line search))
10140 nil))) ; if we have no match in apps-dlink,
10141 ; always open the file in emacs if line or search
10142 ; is given (for backwards compatibility)
10143 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10144 'string-match)
10145 (cdr (assoc ext apps))
10146 (cdr (assoc t apps))))))
10147 (when (eq cmd 'system)
10148 (setq cmd (cdr (assoc 'system apps))))
10149 (when (eq cmd 'default)
10150 (setq cmd (cdr (assoc t apps))))
10151 (when (eq cmd 'mailcap)
10152 (require 'mailcap)
10153 (mailcap-parse-mailcaps)
10154 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10155 (command (mailcap-mime-info mime-type)))
10156 (if (stringp command)
10157 (setq cmd command)
10158 (setq cmd 'emacs))))
10159 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10160 (not (file-exists-p file))
10161 (not org-open-non-existing-files))
10162 (error "No such file: %s" file))
10163 (cond
10164 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10165 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10166 (while (string-match "['\"]%s['\"]" cmd)
10167 (setq cmd (replace-match "%s" t t cmd)))
10168 (while (string-match "%s" cmd)
10169 (setq cmd (replace-match
10170 (save-match-data
10171 (shell-quote-argument
10172 (convert-standard-filename file)))
10173 t t cmd)))
10175 ;; Replace "%1", "%2" etc. in command with group matches from regex
10176 (save-match-data
10177 (let ((match-index 1)
10178 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10179 (set-match-data link-match-data)
10180 (while (<= match-index number-of-groups)
10181 (let ((regex (concat "%" (number-to-string match-index)))
10182 (replace-with (match-string match-index dlink)))
10183 (while (string-match regex cmd)
10184 (setq cmd (replace-match replace-with t t cmd))))
10185 (setq match-index (+ match-index 1)))))
10187 (save-window-excursion
10188 (start-process-shell-command cmd nil cmd)
10189 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10191 ((or (stringp cmd)
10192 (eq cmd 'emacs))
10193 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10194 (widen)
10195 (if line (org-goto-line line)
10196 (if search (org-link-search search))))
10197 ((consp cmd)
10198 (let ((file (convert-standard-filename file)))
10199 (save-match-data
10200 (set-match-data link-match-data)
10201 (eval cmd))))
10202 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10203 (and (eq major-mode 'org-mode) (eq old-mode 'org-mode)
10204 (or (not (equal old-buffer (current-buffer)))
10205 (not (equal old-pos (point))))
10206 (org-mark-ring-push old-pos old-buffer))))
10208 (defun org-file-apps-entry-match-against-dlink-p (entry)
10209 "This function returns non-nil if `entry' uses a regular
10210 expression which should be matched against the whole link by
10211 org-open-file.
10213 It assumes that is the case when the entry uses a regular
10214 expression which has at least one grouping construct and the
10215 action is either a lisp form or a command string containing
10216 '%1', i.e. using at least one subexpression match as a
10217 parameter."
10218 (let ((selector (car entry))
10219 (action (cdr entry)))
10220 (if (stringp selector)
10221 (and (> (regexp-opt-depth selector) 0)
10222 (or (and (stringp action)
10223 (string-match "%[0-9]" action))
10224 (consp action)))
10225 nil)))
10227 (defun org-default-apps ()
10228 "Return the default applications for this operating system."
10229 (cond
10230 ((eq system-type 'darwin)
10231 org-file-apps-defaults-macosx)
10232 ((eq system-type 'windows-nt)
10233 org-file-apps-defaults-windowsnt)
10234 (t org-file-apps-defaults-gnu)))
10236 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10237 "Convert extensions to regular expressions in the cars of LIST.
10238 Also, weed out any non-string entries, because the return value is used
10239 only for regexp matching.
10240 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10241 point to the symbol `emacs', indicating that the file should
10242 be opened in Emacs."
10243 (append
10244 (delq nil
10245 (mapcar (lambda (x)
10246 (if (not (stringp (car x)))
10248 (if (string-match "\\W" (car x))
10250 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10251 list))
10252 (if add-auto-mode
10253 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10255 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10256 (defun org-file-remote-p (file)
10257 "Test whether FILE specifies a location on a remote system.
10258 Return non-nil if the location is indeed remote.
10260 For example, the filename \"/user@host:/foo\" specifies a location
10261 on the system \"/user@host:\"."
10262 (cond ((fboundp 'file-remote-p)
10263 (file-remote-p file))
10264 ((fboundp 'tramp-handle-file-remote-p)
10265 (tramp-handle-file-remote-p file))
10266 ((and (boundp 'ange-ftp-name-format)
10267 (string-match (car ange-ftp-name-format) file))
10269 (t nil)))
10272 ;;;; Refiling
10274 (defun org-get-org-file ()
10275 "Read a filename, with default directory `org-directory'."
10276 (let ((default (or org-default-notes-file remember-data-file)))
10277 (read-file-name (format "File name [%s]: " default)
10278 (file-name-as-directory org-directory)
10279 default)))
10281 (defun org-notes-order-reversed-p ()
10282 "Check if the current file should receive notes in reversed order."
10283 (cond
10284 ((not org-reverse-note-order) nil)
10285 ((eq t org-reverse-note-order) t)
10286 ((not (listp org-reverse-note-order)) nil)
10287 (t (catch 'exit
10288 (let ((all org-reverse-note-order)
10289 entry)
10290 (while (setq entry (pop all))
10291 (if (string-match (car entry) buffer-file-name)
10292 (throw 'exit (cdr entry))))
10293 nil)))))
10295 (defvar org-refile-target-table nil
10296 "The list of refile targets, created by `org-refile'.")
10298 (defvar org-agenda-new-buffers nil
10299 "Buffers created to visit agenda files.")
10301 (defvar org-refile-cache nil
10302 "Cache for refile targets.")
10304 (defvar org-refile-markers nil
10305 "All the markers used for caching refile locations.")
10307 (defun org-refile-marker (pos)
10308 "Get a new refile marker, but only if caching is in use."
10309 (if (not org-refile-use-cache)
10311 (let ((m (make-marker)))
10312 (move-marker m pos)
10313 (push m org-refile-markers)
10314 m)))
10316 (defun org-refile-cache-clear ()
10317 "Clear the refile cache and disable all the markers."
10318 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10319 (setq org-refile-markers nil)
10320 (setq org-refile-cache nil)
10321 (message "Refile cache has been cleared"))
10323 (defun org-refile-cache-check-set (set)
10324 "Check if all the markers in the cache still have live buffers."
10325 (let (marker)
10326 (catch 'exit
10327 (while (and set (setq marker (nth 3 (pop set))))
10328 ;; if org-refile-use-outline-path is 'file, marker may be nil
10329 (when (and marker (null (marker-buffer marker)))
10330 (message "not found") (sit-for 3)
10331 (throw 'exit nil)))
10332 t)))
10334 (defun org-refile-cache-put (set &rest identifiers)
10335 "Push the refile targets SET into the cache, under IDENTIFIERS."
10336 (let* ((key (sha1 (prin1-to-string identifiers)))
10337 (entry (assoc key org-refile-cache)))
10338 (if entry
10339 (setcdr entry set)
10340 (push (cons key set) org-refile-cache))))
10342 (defun org-refile-cache-get (&rest identifiers)
10343 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10344 (cond
10345 ((not org-refile-cache) nil)
10346 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10348 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10349 org-refile-cache))))
10350 (and set (org-refile-cache-check-set set) set)))))
10352 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10353 "Produce a table with refile targets."
10354 (let ((case-fold-search nil)
10355 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10356 (entries (or org-refile-targets '((nil . (:level . 1)))))
10357 targets tgs txt re files f desc descre fast-path-p level pos0)
10358 (message "Getting targets...")
10359 (with-current-buffer (or default-buffer (current-buffer))
10360 (while (setq entry (pop entries))
10361 (setq files (car entry) desc (cdr entry))
10362 (setq fast-path-p nil)
10363 (cond
10364 ((null files) (setq files (list (current-buffer))))
10365 ((eq files 'org-agenda-files)
10366 (setq files (org-agenda-files 'unrestricted)))
10367 ((and (symbolp files) (fboundp files))
10368 (setq files (funcall files)))
10369 ((and (symbolp files) (boundp files))
10370 (setq files (symbol-value files))))
10371 (if (stringp files) (setq files (list files)))
10372 (cond
10373 ((eq (car desc) :tag)
10374 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10375 ((eq (car desc) :todo)
10376 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10377 ((eq (car desc) :regexp)
10378 (setq descre (cdr desc)))
10379 ((eq (car desc) :level)
10380 (setq descre (concat "^\\*\\{" (number-to-string
10381 (if org-odd-levels-only
10382 (1- (* 2 (cdr desc)))
10383 (cdr desc)))
10384 "\\}[ \t]")))
10385 ((eq (car desc) :maxlevel)
10386 (setq fast-path-p t)
10387 (setq descre (concat "^\\*\\{1," (number-to-string
10388 (if org-odd-levels-only
10389 (1- (* 2 (cdr desc)))
10390 (cdr desc)))
10391 "\\}[ \t]")))
10392 (t (error "Bad refiling target description %s" desc)))
10393 (while (setq f (pop files))
10394 (with-current-buffer
10395 (if (bufferp f) f (org-get-agenda-file-buffer f))
10397 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10398 (progn
10399 (if (bufferp f) (setq f (buffer-file-name
10400 (buffer-base-buffer f))))
10401 (setq f (and f (expand-file-name f)))
10402 (if (eq org-refile-use-outline-path 'file)
10403 (push (list (file-name-nondirectory f) f nil nil) tgs))
10404 (save-excursion
10405 (save-restriction
10406 (widen)
10407 (goto-char (point-min))
10408 (while (re-search-forward descre nil t)
10409 (goto-char (setq pos0 (point-at-bol)))
10410 (catch 'next
10411 (when org-refile-target-verify-function
10412 (save-match-data
10413 (or (funcall org-refile-target-verify-function)
10414 (throw 'next t))))
10415 (when (and (looking-at org-complex-heading-regexp)
10416 (not (member (match-string 4) excluded-entries))
10417 (match-string 4))
10418 (setq level (org-reduced-level
10419 (- (match-end 1) (match-beginning 1)))
10420 txt (org-link-display-format (match-string 4))
10421 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10422 re (format org-complex-heading-regexp-format
10423 (regexp-quote (match-string 4))))
10424 (when org-refile-use-outline-path
10425 (setq txt (mapconcat
10426 'org-protect-slash
10427 (append
10428 (if (eq org-refile-use-outline-path
10429 'file)
10430 (list (file-name-nondirectory
10431 (buffer-file-name
10432 (buffer-base-buffer))))
10433 (if (eq org-refile-use-outline-path
10434 'full-file-path)
10435 (list (buffer-file-name
10436 (buffer-base-buffer)))))
10437 (org-get-outline-path fast-path-p
10438 level txt)
10439 (list txt))
10440 "/")))
10441 (push (list txt f re (org-refile-marker (point)))
10442 tgs)))
10443 (when (= (point) pos0)
10444 ;; verification function has not moved point
10445 (goto-char (point-at-eol))))))))
10446 (when org-refile-use-cache
10447 (org-refile-cache-put tgs (buffer-file-name) descre))
10448 (setq targets (append tgs targets))
10449 ))))
10450 (message "Getting targets...done")
10451 (nreverse targets)))
10453 (defun org-protect-slash (s)
10454 (while (string-match "/" s)
10455 (setq s (replace-match "\\" t t s)))
10458 (defvar org-olpa (make-vector 20 nil))
10460 (defun org-get-outline-path (&optional fastp level heading)
10461 "Return the outline path to the current entry, as a list.
10463 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10464 routine which makes outline path derivations for an entire file,
10465 avoiding backtracing. Refile target collection makes use of that."
10466 (if fastp
10467 (progn
10468 (if (> level 19)
10469 (error "Outline path failure, more than 19 levels"))
10470 (loop for i from level upto 19 do
10471 (aset org-olpa i nil))
10472 (prog1
10473 (delq nil (append org-olpa nil))
10474 (aset org-olpa level heading)))
10475 (let (rtn case-fold-search)
10476 (save-excursion
10477 (save-restriction
10478 (widen)
10479 (while (org-up-heading-safe)
10480 (when (looking-at org-complex-heading-regexp)
10481 (push (org-match-string-no-properties 4) rtn)))
10482 rtn)))))
10484 (defun org-format-outline-path (path &optional width prefix)
10485 "Format the outline path PATH for display.
10486 Width is the maximum number of characters that is available.
10487 Prefix is a prefix to be included in the returned string,
10488 such as the file name."
10489 (setq width (or width 79))
10490 (if prefix (setq width (- width (length prefix))))
10491 (if (not path)
10492 (or prefix "")
10493 (let* ((nsteps (length path))
10494 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10495 (maxwidth (if (<= total-width width)
10496 10000 ;; everything fits
10497 ;; we need to shorten the level headings
10498 (/ (- width nsteps) nsteps)))
10499 (org-odd-levels-only nil)
10500 (n 0)
10501 (total (1+ (length prefix))))
10502 (setq maxwidth (max maxwidth 10))
10503 (concat prefix
10504 (mapconcat
10505 (lambda (h)
10506 (setq n (1+ n))
10507 (if (and (= n nsteps) (< maxwidth 10000))
10508 (setq maxwidth (- total-width total)))
10509 (if (< (length h) maxwidth)
10510 (progn (setq total (+ total (length h) 1)) h)
10511 (setq h (substring h 0 (- maxwidth 2))
10512 total (+ total maxwidth 1))
10513 (if (string-match "[ \t]+\\'" h)
10514 (setq h (substring h 0 (match-beginning 0))))
10515 (setq h (concat h "..")))
10516 (org-add-props h nil 'face
10517 (nth (% (1- n) org-n-level-faces)
10518 org-level-faces))
10520 path "/")))))
10522 (defun org-display-outline-path (&optional file current)
10523 "Display the current outline path in the echo area."
10524 (interactive "P")
10525 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10526 (case-fold-search nil)
10527 (path (and (eq major-mode 'org-mode) (org-get-outline-path))))
10528 (if current (setq path (append path
10529 (save-excursion
10530 (org-back-to-heading t)
10531 (if (looking-at org-complex-heading-regexp)
10532 (list (match-string 4)))))))
10533 (message "%s"
10534 (org-format-outline-path
10535 path
10536 (1- (frame-width))
10537 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10539 (defvar org-refile-history nil
10540 "History for refiling operations.")
10542 (defvar org-after-refile-insert-hook nil
10543 "Hook run after `org-refile' has inserted its stuff at the new location.
10544 Note that this is still *before* the stuff will be removed from
10545 the *old* location.")
10547 (defvar org-capture-last-stored-marker)
10548 (defun org-refile (&optional goto default-buffer rfloc)
10549 "Move the entry or entries at point to another heading.
10550 The list of target headings is compiled using the information in
10551 `org-refile-targets', which see.
10553 At the target location, the entry is filed as a subitem of the target
10554 heading. Depending on `org-reverse-note-order', the new subitem will
10555 either be the first or the last subitem.
10557 If there is an active region, all entries in that region will be moved.
10558 However, the region must fulfill the requirement that the first heading
10559 is the first one sets the top-level of the moved text - at most siblings
10560 below it are allowed.
10562 With prefix arg GOTO, the command will only visit the target location
10563 and not actually move anything.
10565 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10566 go to the location where the last refiling operation has put the subtree.
10567 With a prefix argument of `2', refile to the running clock.
10569 RFLOC can be a refile location obtained in a different way.
10571 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10573 If you are using target caching (see `org-refile-use-cache'),
10574 You have to clear the target cache in order to find new targets.
10575 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10576 prefix argument (`C-u C-u C-u C-c C-w')."
10578 (interactive "P")
10579 (if (member goto '(0 (64)))
10580 (org-refile-cache-clear)
10581 (let* ((cbuf (current-buffer))
10582 (regionp (org-region-active-p))
10583 (region-start (and regionp (region-beginning)))
10584 (region-end (and regionp (region-end)))
10585 (region-length (and regionp (- region-end region-start)))
10586 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10587 pos it nbuf file re level reversed)
10588 (setq last-command nil)
10589 (when regionp
10590 (goto-char region-start)
10591 (or (bolp) (goto-char (point-at-bol)))
10592 (setq region-start (point))
10593 (unless (or (org-kill-is-subtree-p
10594 (buffer-substring region-start region-end))
10595 (prog1 org-refile-active-region-within-subtree
10596 (org-toggle-heading)))
10597 (error "The region is not a (sequence of) subtree(s)")))
10598 (if (equal goto '(16))
10599 (org-refile-goto-last-stored)
10600 (when (or
10601 (and (equal goto 2)
10602 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10603 (prog1
10604 (setq it (list (or org-clock-heading "running clock")
10605 (buffer-file-name
10606 (marker-buffer org-clock-hd-marker))
10608 (marker-position org-clock-hd-marker)))
10609 (setq goto nil)))
10610 (setq it (or rfloc
10611 (let (heading-text)
10612 (save-excursion
10613 (unless goto
10614 (org-back-to-heading t)
10615 (setq heading-text
10616 (nth 4 (org-heading-components))))
10617 (org-refile-get-location
10618 (cond (goto "Goto")
10619 (regionp "Refile region to")
10620 (t (concat "Refile subtree \""
10621 heading-text "\" to")))
10622 default-buffer
10623 org-refile-allow-creating-parent-nodes
10624 goto))))))
10625 (setq file (nth 1 it)
10626 re (nth 2 it)
10627 pos (nth 3 it))
10628 (if (and (not goto)
10630 (equal (buffer-file-name) file)
10631 (if regionp
10632 (and (>= pos region-start)
10633 (<= pos region-end))
10634 (and (>= pos (point))
10635 (< pos (save-excursion
10636 (org-end-of-subtree t t))))))
10637 (error "Cannot refile to position inside the tree or region"))
10639 (setq nbuf (or (find-buffer-visiting file)
10640 (find-file-noselect file)))
10641 (if goto
10642 (progn
10643 (org-pop-to-buffer-same-window nbuf)
10644 (goto-char pos)
10645 (org-show-context 'org-goto))
10646 (if regionp
10647 (progn
10648 (org-kill-new (buffer-substring region-start region-end))
10649 (org-save-markers-in-region region-start region-end))
10650 (org-copy-subtree 1 nil t))
10651 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10652 (find-file-noselect file)))
10653 (setq reversed (org-notes-order-reversed-p))
10654 (save-excursion
10655 (save-restriction
10656 (widen)
10657 (if pos
10658 (progn
10659 (goto-char pos)
10660 (looking-at org-outline-regexp)
10661 (setq level (org-get-valid-level (funcall outline-level) 1))
10662 (goto-char
10663 (if reversed
10664 (or (outline-next-heading) (point-max))
10665 (or (save-excursion (org-get-next-sibling))
10666 (org-end-of-subtree t t)
10667 (point-max)))))
10668 (setq level 1)
10669 (if (not reversed)
10670 (goto-char (point-max))
10671 (goto-char (point-min))
10672 (or (outline-next-heading) (goto-char (point-max)))))
10673 (if (not (bolp)) (newline))
10674 (org-paste-subtree level)
10675 (when org-log-refile
10676 (org-add-log-setup 'refile nil nil 'findpos
10677 org-log-refile)
10678 (unless (eq org-log-refile 'note)
10679 (save-excursion (org-add-log-note))))
10680 (and org-auto-align-tags (org-set-tags nil t))
10681 (bookmark-set "org-refile-last-stored")
10682 ;; If we are refiling for capture, make sure that the
10683 ;; last-capture pointers point here
10684 (when (org-bound-and-true-p org-refile-for-capture)
10685 (bookmark-set "org-capture-last-stored-marker")
10686 (move-marker org-capture-last-stored-marker (point)))
10687 (if (fboundp 'deactivate-mark) (deactivate-mark))
10688 (run-hooks 'org-after-refile-insert-hook))))
10689 (if regionp
10690 (delete-region (point) (+ (point) region-length))
10691 (org-cut-subtree))
10692 (when (featurep 'org-inlinetask)
10693 (org-inlinetask-remove-END-maybe))
10694 (setq org-markers-to-move nil)
10695 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10697 (defun org-refile-goto-last-stored ()
10698 "Go to the location where the last refile was stored."
10699 (interactive)
10700 (bookmark-jump "org-refile-last-stored")
10701 (message "This is the location of the last refile"))
10703 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10704 no-exclude)
10705 "Prompt the user for a refile location, using PROMPT.
10706 PROMPT should not be suffixed with a colon and a space, because
10707 this function appends the default value from
10708 `org-refile-history' automatically, if that is not empty.
10709 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10710 this is used for the GOTO interface."
10711 (let ((org-refile-targets org-refile-targets)
10712 (org-refile-use-outline-path org-refile-use-outline-path)
10713 excluded-entries)
10714 (when (and (eq major-mode 'org-mode)
10715 (not org-refile-use-cache)
10716 (not no-exclude))
10717 (org-map-tree
10718 (lambda()
10719 (setq excluded-entries
10720 (append excluded-entries (list (org-get-heading t t)))))))
10721 (setq org-refile-target-table
10722 (org-refile-get-targets default-buffer excluded-entries)))
10723 (unless org-refile-target-table
10724 (error "No refile targets"))
10725 (let* ((prompt (concat prompt
10726 (and (car org-refile-history)
10727 (concat " (default " (car org-refile-history) ")"))
10728 ": "))
10729 (cbuf (current-buffer))
10730 (partial-completion-mode nil)
10731 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10732 (cfunc (if (and org-refile-use-outline-path
10733 org-outline-path-complete-in-steps)
10734 'org-olpath-completing-read
10735 'org-icompleting-read))
10736 (extra (if org-refile-use-outline-path "/" ""))
10737 (filename (and cfn (expand-file-name cfn)))
10738 (tbl (mapcar
10739 (lambda (x)
10740 (if (and (not (member org-refile-use-outline-path
10741 '(file full-file-path)))
10742 (not (equal filename (nth 1 x))))
10743 (cons (concat (car x) extra " ("
10744 (file-name-nondirectory (nth 1 x)) ")")
10745 (cdr x))
10746 (cons (concat (car x) extra) (cdr x))))
10747 org-refile-target-table))
10748 (completion-ignore-case t)
10749 pa answ parent-target child parent old-hist)
10750 (setq old-hist org-refile-history)
10751 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10752 nil 'org-refile-history (car org-refile-history)))
10753 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10754 (org-refile-check-position pa)
10755 (if pa
10756 (progn
10757 (when (or (not org-refile-history)
10758 (not (eq old-hist org-refile-history))
10759 (not (equal (car pa) (car org-refile-history))))
10760 (setq org-refile-history
10761 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10762 org-refile-history
10763 (cdr org-refile-history))))
10764 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10765 (pop org-refile-history)))
10767 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10768 (progn
10769 (setq parent (match-string 1 answ)
10770 child (match-string 2 answ))
10771 (setq parent-target (or (assoc parent tbl)
10772 (assoc (concat parent "/") tbl)))
10773 (when (and parent-target
10774 (or (eq new-nodes t)
10775 (and (eq new-nodes 'confirm)
10776 (y-or-n-p (format "Create new node \"%s\"? "
10777 child)))))
10778 (org-refile-new-child parent-target child)))
10779 (error "Invalid target location")))))
10781 (defun org-refile-check-position (refile-pointer)
10782 "Check if the refile pointer matches the readline to which it points."
10783 (let* ((file (nth 1 refile-pointer))
10784 (re (nth 2 refile-pointer))
10785 (pos (nth 3 refile-pointer))
10786 buffer)
10787 (when (org-string-nw-p re)
10788 (setq buffer (if (markerp pos)
10789 (marker-buffer pos)
10790 (or (find-buffer-visiting file)
10791 (find-file-noselect file))))
10792 (with-current-buffer buffer
10793 (save-excursion
10794 (save-restriction
10795 (widen)
10796 (goto-char pos)
10797 (beginning-of-line 1)
10798 (unless (org-looking-at-p re)
10799 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
10801 (defun org-refile-new-child (parent-target child)
10802 "Use refile target PARENT-TARGET to add new CHILD below it."
10803 (unless parent-target
10804 (error "Cannot find parent for new node"))
10805 (let ((file (nth 1 parent-target))
10806 (pos (nth 3 parent-target))
10807 level)
10808 (with-current-buffer (or (find-buffer-visiting file)
10809 (find-file-noselect file))
10810 (save-excursion
10811 (save-restriction
10812 (widen)
10813 (if pos
10814 (goto-char pos)
10815 (goto-char (point-max))
10816 (if (not (bolp)) (newline)))
10817 (when (looking-at org-outline-regexp)
10818 (setq level (funcall outline-level))
10819 (org-end-of-subtree t t))
10820 (org-back-over-empty-lines)
10821 (insert "\n" (make-string
10822 (if pos (org-get-valid-level level 1) 1) ?*)
10823 " " child "\n")
10824 (beginning-of-line 0)
10825 (list (concat (car parent-target) "/" child) file "" (point)))))))
10827 (defun org-olpath-completing-read (prompt collection &rest args)
10828 "Read an outline path like a file name."
10829 (let ((thetable collection)
10830 (org-completion-use-ido nil) ; does not work with ido.
10831 (org-completion-use-iswitchb nil)) ; or iswitchb
10832 (apply
10833 'org-icompleting-read prompt
10834 (lambda (string predicate &optional flag)
10835 (let (rtn r f (l (length string)))
10836 (cond
10837 ((eq flag nil)
10838 ;; try completion
10839 (try-completion string thetable))
10840 ((eq flag t)
10841 ;; all-completions
10842 (setq rtn (all-completions string thetable predicate))
10843 (mapcar
10844 (lambda (x)
10845 (setq r (substring x l))
10846 (if (string-match " ([^)]*)$" x)
10847 (setq f (match-string 0 x))
10848 (setq f ""))
10849 (if (string-match "/" r)
10850 (concat string (substring r 0 (match-end 0)) f)
10852 rtn))
10853 ((eq flag 'lambda)
10854 ;; exact match?
10855 (assoc string thetable)))
10857 args)))
10859 ;;;; Dynamic blocks
10861 (defun org-find-dblock (name)
10862 "Find the first dynamic block with name NAME in the buffer.
10863 If not found, stay at current position and return nil."
10864 (let (pos)
10865 (save-excursion
10866 (goto-char (point-min))
10867 (setq pos (and (re-search-forward (concat "^[ \t]*#\\+BEGIN:[ \t]+" name "\\>")
10868 nil t)
10869 (match-beginning 0))))
10870 (if pos (goto-char pos))
10871 pos))
10873 (defconst org-dblock-start-re
10874 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10875 "Matches the start line of a dynamic block, with parameters.")
10877 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
10878 "Matches the end of a dynamic block.")
10880 (defun org-create-dblock (plist)
10881 "Create a dynamic block section, with parameters taken from PLIST.
10882 PLIST must contain a :name entry which is used as name of the block."
10883 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
10884 (end-of-line 1)
10885 (newline))
10886 (let ((col (current-column))
10887 (name (plist-get plist :name)))
10888 (insert "#+BEGIN: " name)
10889 (while plist
10890 (if (eq (car plist) :name)
10891 (setq plist (cddr plist))
10892 (insert " " (prin1-to-string (pop plist)))))
10893 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
10894 (beginning-of-line -2)))
10896 (defun org-prepare-dblock ()
10897 "Prepare dynamic block for refresh.
10898 This empties the block, puts the cursor at the insert position and returns
10899 the property list including an extra property :name with the block name."
10900 (unless (looking-at org-dblock-start-re)
10901 (error "Not at a dynamic block"))
10902 (let* ((begdel (1+ (match-end 0)))
10903 (name (org-no-properties (match-string 1)))
10904 (params (append (list :name name)
10905 (read (concat "(" (match-string 3) ")")))))
10906 (save-excursion
10907 (beginning-of-line 1)
10908 (skip-chars-forward " \t")
10909 (setq params (plist-put params :indentation-column (current-column))))
10910 (unless (re-search-forward org-dblock-end-re nil t)
10911 (error "Dynamic block not terminated"))
10912 (setq params
10913 (append params
10914 (list :content (buffer-substring
10915 begdel (match-beginning 0)))))
10916 (delete-region begdel (match-beginning 0))
10917 (goto-char begdel)
10918 (open-line 1)
10919 params))
10921 (defun org-map-dblocks (&optional command)
10922 "Apply COMMAND to all dynamic blocks in the current buffer.
10923 If COMMAND is not given, use `org-update-dblock'."
10924 (let ((cmd (or command 'org-update-dblock)))
10925 (save-excursion
10926 (goto-char (point-min))
10927 (while (re-search-forward org-dblock-start-re nil t)
10928 (goto-char (match-beginning 0))
10929 (save-excursion
10930 (condition-case nil
10931 (funcall cmd)
10932 (error (message "Error during update of dynamic block"))))
10933 (unless (re-search-forward org-dblock-end-re nil t)
10934 (error "Dynamic block not terminated"))))))
10936 (defun org-dblock-update (&optional arg)
10937 "User command for updating dynamic blocks.
10938 Update the dynamic block at point. With prefix ARG, update all dynamic
10939 blocks in the buffer."
10940 (interactive "P")
10941 (if arg
10942 (org-update-all-dblocks)
10943 (or (looking-at org-dblock-start-re)
10944 (org-beginning-of-dblock))
10945 (org-update-dblock)))
10947 (defun org-update-dblock ()
10948 "Update the dynamic block at point.
10949 This means to empty the block, parse for parameters and then call
10950 the correct writing function."
10951 (interactive)
10952 (save-window-excursion
10953 (let* ((pos (point))
10954 (line (org-current-line))
10955 (params (org-prepare-dblock))
10956 (name (plist-get params :name))
10957 (indent (plist-get params :indentation-column))
10958 (cmd (intern (concat "org-dblock-write:" name))))
10959 (message "Updating dynamic block `%s' at line %d..." name line)
10960 (funcall cmd params)
10961 (message "Updating dynamic block `%s' at line %d...done" name line)
10962 (goto-char pos)
10963 (when (and indent (> indent 0))
10964 (setq indent (make-string indent ?\ ))
10965 (save-excursion
10966 (org-beginning-of-dblock)
10967 (forward-line 1)
10968 (while (not (looking-at org-dblock-end-re))
10969 (insert indent)
10970 (beginning-of-line 2))
10971 (when (looking-at org-dblock-end-re)
10972 (and (looking-at "[ \t]+")
10973 (replace-match ""))
10974 (insert indent)))))))
10976 (defun org-beginning-of-dblock ()
10977 "Find the beginning of the dynamic block at point.
10978 Error if there is no such block at point."
10979 (let ((pos (point))
10980 beg)
10981 (end-of-line 1)
10982 (if (and (re-search-backward org-dblock-start-re nil t)
10983 (setq beg (match-beginning 0))
10984 (re-search-forward org-dblock-end-re nil t)
10985 (> (match-end 0) pos))
10986 (goto-char beg)
10987 (goto-char pos)
10988 (error "Not in a dynamic block"))))
10990 (defun org-update-all-dblocks ()
10991 "Update all dynamic blocks in the buffer.
10992 This function can be used in a hook."
10993 (interactive)
10994 (when (eq major-mode 'org-mode)
10995 (org-map-dblocks 'org-update-dblock)))
10998 ;;;; Completion
11000 (defconst org-additional-option-like-keywords
11001 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11002 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11003 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11004 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11005 "BEGIN:" "END:"
11006 "ORGTBL" "TBLFM:" "TBLNAME:"
11007 "BEGIN_EXAMPLE" "END_EXAMPLE"
11008 "BEGIN_QUOTE" "END_QUOTE"
11009 "BEGIN_VERSE" "END_VERSE"
11010 "BEGIN_CENTER" "END_CENTER"
11011 "BEGIN_SRC" "END_SRC"
11012 "BEGIN_RESULT" "END_RESULT"
11013 "NAME:" "RESULTS:"
11014 "HEADER:" "HEADERS:"
11015 "CATEGORY:" "COLUMNS:" "PROPERTY:"
11016 "CAPTION:" "LABEL:"
11017 "SETUPFILE:"
11018 "INCLUDE:"
11019 "BIND:"
11020 "MACRO:"))
11022 (defcustom org-structure-template-alist
11024 ("s" "#+begin_src ?\n\n#+end_src"
11025 "<src lang=\"?\">\n\n</src>")
11026 ("e" "#+begin_example\n?\n#+end_example"
11027 "<example>\n?\n</example>")
11028 ("q" "#+begin_quote\n?\n#+end_quote"
11029 "<quote>\n?\n</quote>")
11030 ("v" "#+begin_verse\n?\n#+end_verse"
11031 "<verse>\n?\n/verse>")
11032 ("c" "#+begin_center\n?\n#+end_center"
11033 "<center>\n?\n/center>")
11034 ("l" "#+begin_latex\n?\n#+end_latex"
11035 "<literal style=\"latex\">\n?\n</literal>")
11036 ("L" "#+latex: "
11037 "<literal style=\"latex\">?</literal>")
11038 ("h" "#+begin_html\n?\n#+end_html"
11039 "<literal style=\"html\">\n?\n</literal>")
11040 ("H" "#+html: "
11041 "<literal style=\"html\">?</literal>")
11042 ("a" "#+begin_ascii\n?\n#+end_ascii")
11043 ("A" "#+ascii: ")
11044 ("i" "#+index: ?"
11045 "#+index: ?")
11046 ("I" "#+include %file ?"
11047 "<include file=%file markup=\"?\">")
11049 "Structure completion elements.
11050 This is a list of abbreviation keys and values. The value gets inserted
11051 if you type `<' followed by the key and then press the completion key,
11052 usually `M-TAB'. %file will be replaced by a file name after prompting
11053 for the file using completion. The cursor will be placed at the position
11054 of the `?` in the template.
11055 There are two templates for each key, the first uses the original Org syntax,
11056 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11057 the default when the /org-mtags.el/ module has been loaded. See also the
11058 variable `org-mtags-prefer-muse-templates'.
11059 This is an experimental feature, it is undecided if it is going to stay in."
11060 :group 'org-completion
11061 :type '(repeat
11062 (string :tag "Key")
11063 (string :tag "Template")
11064 (string :tag "Muse Template")))
11066 (defun org-try-structure-completion ()
11067 "Try to complete a structure template before point.
11068 This looks for strings like \"<e\" on an otherwise empty line and
11069 expands them."
11070 (let ((l (buffer-substring (point-at-bol) (point)))
11072 (when (and (looking-at "[ \t]*$")
11073 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11074 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11075 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11076 (match-beginning 1)) a)
11077 t)))
11079 (defun org-complete-expand-structure-template (start cell)
11080 "Expand a structure template."
11081 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11082 (rpl (nth (if musep 2 1) cell))
11083 (ind ""))
11084 (delete-region start (point))
11085 (when (string-match "\\`#\\+" rpl)
11086 (cond
11087 ((bolp))
11088 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11089 (setq ind (buffer-substring (point-at-bol) (point))))
11090 (t (newline))))
11091 (setq start (point))
11092 (if (string-match "%file" rpl)
11093 (setq rpl (replace-match
11094 (concat
11095 "\""
11096 (save-match-data
11097 (abbreviate-file-name (read-file-name "Include file: ")))
11098 "\"")
11099 t t rpl)))
11100 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11101 (concat "\n" ind)))
11102 (insert rpl)
11103 (if (re-search-backward "\\?" start t) (delete-char 1))))
11105 ;;;; TODO, DEADLINE, Comments
11107 (defun org-toggle-comment ()
11108 "Change the COMMENT state of an entry."
11109 (interactive)
11110 (save-excursion
11111 (org-back-to-heading)
11112 (let (case-fold-search)
11113 (cond
11114 ((looking-at (format org-heading-keyword-regexp-format
11115 org-comment-string))
11116 (goto-char (match-end 1))
11117 (looking-at (concat " +" org-comment-string))
11118 (replace-match "" t t)
11119 (when (eolp) (insert " ")))
11120 ((looking-at org-outline-regexp)
11121 (goto-char (match-end 0))
11122 (insert org-comment-string " "))))))
11124 (defvar org-last-todo-state-is-todo nil
11125 "This is non-nil when the last TODO state change led to a TODO state.
11126 If the last change removed the TODO tag or switched to DONE, then
11127 this is nil.")
11129 (defvar org-setting-tags nil) ; dynamically skipped
11131 (defvar org-todo-setup-filter-hook nil
11132 "Hook for functions that pre-filter todo specs.
11133 Each function takes a todo spec and returns either nil or the spec
11134 transformed into canonical form." )
11136 (defvar org-todo-get-default-hook nil
11137 "Hook for functions that get a default item for todo.
11138 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11139 nil or a string to be used for the todo mark." )
11141 (defvar org-agenda-headline-snapshot-before-repeat)
11143 (defun org-current-effective-time ()
11144 "Return current time adjusted for `org-extend-today-until' variable"
11145 (let* ((ct (org-current-time))
11146 (dct (decode-time ct))
11147 (ct1
11148 (if (and org-use-effective-time
11149 (< (nth 2 dct) org-extend-today-until))
11150 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11151 ct)))
11152 ct1))
11154 (defun org-todo-yesterday (&optional arg)
11155 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11156 (interactive "P")
11157 (if (eq major-mode 'org-agenda-mode)
11158 (apply 'org-agenda-todo-yesterday arg)
11159 (let* ((hour (third (decode-time
11160 (org-current-time))))
11161 (org-extend-today-until (1+ hour)))
11162 (org-todo arg))))
11164 (defun org-todo (&optional arg)
11165 "Change the TODO state of an item.
11166 The state of an item is given by a keyword at the start of the heading,
11167 like
11168 *** TODO Write paper
11169 *** DONE Call mom
11171 The different keywords are specified in the variable `org-todo-keywords'.
11172 By default the available states are \"TODO\" and \"DONE\".
11173 So for this example: when the item starts with TODO, it is changed to DONE.
11174 When it starts with DONE, the DONE is removed. And when neither TODO nor
11175 DONE are present, add TODO at the beginning of the heading.
11177 With \\[universal-argument] prefix arg, use completion to determine the new \
11178 state.
11179 With numeric prefix arg, switch to that state.
11180 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11181 keywords (nextset).
11182 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11183 With a numeric prefix arg of 0, inhibit note taking for the change.
11185 For calling through lisp, arg is also interpreted in the following way:
11186 'none -> empty state
11187 \"\"(empty string) -> switch to empty state
11188 'done -> switch to DONE
11189 'nextset -> switch to the next set of keywords
11190 'previousset -> switch to the previous set of keywords
11191 \"WAITING\" -> switch to the specified keyword, but only if it
11192 really is a member of `org-todo-keywords'."
11193 (interactive "P")
11194 (if (equal arg '(16)) (setq arg 'nextset))
11195 (let ((org-blocker-hook org-blocker-hook)
11196 (case-fold-search nil))
11197 (when (equal arg '(64))
11198 (setq arg nil org-blocker-hook nil))
11199 (when (and org-blocker-hook
11200 (or org-inhibit-blocking
11201 (org-entry-get nil "NOBLOCKING")))
11202 (setq org-blocker-hook nil))
11203 (save-excursion
11204 (catch 'exit
11205 (org-back-to-heading t)
11206 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11207 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11208 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11209 (let* ((match-data (match-data))
11210 (startpos (point-at-bol))
11211 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11212 (org-log-done org-log-done)
11213 (org-log-repeat org-log-repeat)
11214 (org-todo-log-states org-todo-log-states)
11215 (org-inhibit-logging
11216 (if (equal arg 0)
11217 (progn (setq arg nil) 'note) org-inhibit-logging))
11218 (this (match-string 1))
11219 (hl-pos (match-beginning 0))
11220 (head (org-get-todo-sequence-head this))
11221 (ass (assoc head org-todo-kwd-alist))
11222 (interpret (nth 1 ass))
11223 (done-word (nth 3 ass))
11224 (final-done-word (nth 4 ass))
11225 (last-state (or this ""))
11226 (completion-ignore-case t)
11227 (member (member this org-todo-keywords-1))
11228 (tail (cdr member))
11229 (state (cond
11230 ((and org-todo-key-trigger
11231 (or (and (equal arg '(4))
11232 (eq org-use-fast-todo-selection 'prefix))
11233 (and (not arg) org-use-fast-todo-selection
11234 (not (eq org-use-fast-todo-selection
11235 'prefix)))))
11236 ;; Use fast selection
11237 (org-fast-todo-selection))
11238 ((and (equal arg '(4))
11239 (or (not org-use-fast-todo-selection)
11240 (not org-todo-key-trigger)))
11241 ;; Read a state with completion
11242 (org-icompleting-read
11243 "State: " (mapcar (lambda(x) (list x))
11244 org-todo-keywords-1)
11245 nil t))
11246 ((eq arg 'right)
11247 (if this
11248 (if tail (car tail) nil)
11249 (car org-todo-keywords-1)))
11250 ((eq arg 'left)
11251 (if (equal member org-todo-keywords-1)
11253 (if this
11254 (nth (- (length org-todo-keywords-1)
11255 (length tail) 2)
11256 org-todo-keywords-1)
11257 (org-last org-todo-keywords-1))))
11258 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11259 (setq arg nil))) ; hack to fall back to cycling
11260 (arg
11261 ;; user or caller requests a specific state
11262 (cond
11263 ((equal arg "") nil)
11264 ((eq arg 'none) nil)
11265 ((eq arg 'done) (or done-word (car org-done-keywords)))
11266 ((eq arg 'nextset)
11267 (or (car (cdr (member head org-todo-heads)))
11268 (car org-todo-heads)))
11269 ((eq arg 'previousset)
11270 (let ((org-todo-heads (reverse org-todo-heads)))
11271 (or (car (cdr (member head org-todo-heads)))
11272 (car org-todo-heads))))
11273 ((car (member arg org-todo-keywords-1)))
11274 ((stringp arg)
11275 (error "State `%s' not valid in this file" arg))
11276 ((nth (1- (prefix-numeric-value arg))
11277 org-todo-keywords-1))))
11278 ((null member) (or head (car org-todo-keywords-1)))
11279 ((equal this final-done-word) nil) ;; -> make empty
11280 ((null tail) nil) ;; -> first entry
11281 ((memq interpret '(type priority))
11282 (if (eq this-command last-command)
11283 (car tail)
11284 (if (> (length tail) 0)
11285 (or done-word (car org-done-keywords))
11286 nil)))
11288 (car tail))))
11289 (state (or
11290 (run-hook-with-args-until-success
11291 'org-todo-get-default-hook state last-state)
11292 state))
11293 (next (if state (concat " " state " ") " "))
11294 (change-plist (list :type 'todo-state-change :from this :to state
11295 :position startpos))
11296 dolog now-done-p)
11297 (when org-blocker-hook
11298 (setq org-last-todo-state-is-todo
11299 (not (member this org-done-keywords)))
11300 (unless (save-excursion
11301 (save-match-data
11302 (org-with-wide-buffer
11303 (run-hook-with-args-until-failure
11304 'org-blocker-hook change-plist))))
11305 (if (org-called-interactively-p 'interactive)
11306 (error "TODO state change from %s to %s blocked" this state)
11307 ;; fail silently
11308 (message "TODO state change from %s to %s blocked" this state)
11309 (throw 'exit nil))))
11310 (store-match-data match-data)
11311 (replace-match next t t)
11312 (unless (pos-visible-in-window-p hl-pos)
11313 (message "TODO state changed to %s" (org-trim next)))
11314 (unless head
11315 (setq head (org-get-todo-sequence-head state)
11316 ass (assoc head org-todo-kwd-alist)
11317 interpret (nth 1 ass)
11318 done-word (nth 3 ass)
11319 final-done-word (nth 4 ass)))
11320 (when (memq arg '(nextset previousset))
11321 (message "Keyword-Set %d/%d: %s"
11322 (- (length org-todo-sets) -1
11323 (length (memq (assoc state org-todo-sets) org-todo-sets)))
11324 (length org-todo-sets)
11325 (mapconcat 'identity (assoc state org-todo-sets) " ")))
11326 (setq org-last-todo-state-is-todo
11327 (not (member state org-done-keywords)))
11328 (setq now-done-p (and (member state org-done-keywords)
11329 (not (member this org-done-keywords))))
11330 (and logging (org-local-logging logging))
11331 (when (and (or org-todo-log-states org-log-done)
11332 (not (eq org-inhibit-logging t))
11333 (not (memq arg '(nextset previousset))))
11334 ;; we need to look at recording a time and note
11335 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
11336 (nth 2 (assoc this org-todo-log-states))))
11337 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11338 (setq dolog 'time))
11339 (when (and state
11340 (member state org-not-done-keywords)
11341 (not (member this org-not-done-keywords)))
11342 ;; This is now a todo state and was not one before
11343 ;; If there was a CLOSED time stamp, get rid of it.
11344 (org-add-planning-info nil nil 'closed))
11345 (when (and now-done-p org-log-done)
11346 ;; It is now done, and it was not done before
11347 (org-add-planning-info 'closed (org-current-effective-time))
11348 (if (and (not dolog) (eq 'note org-log-done))
11349 (org-add-log-setup 'done state this 'findpos 'note)))
11350 (when (and state dolog)
11351 ;; This is a non-nil state, and we need to log it
11352 (org-add-log-setup 'state state this 'findpos dolog)))
11353 ;; Fixup tag positioning
11354 (org-todo-trigger-tag-changes state)
11355 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11356 (when org-provide-todo-statistics
11357 (org-update-parent-todo-statistics))
11358 (run-hooks 'org-after-todo-state-change-hook)
11359 (if (and arg (not (member state org-done-keywords)))
11360 (setq head (org-get-todo-sequence-head state)))
11361 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11362 ;; Do we need to trigger a repeat?
11363 (when now-done-p
11364 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11365 ;; This is for the agenda, take a snapshot of the headline.
11366 (save-match-data
11367 (setq org-agenda-headline-snapshot-before-repeat
11368 (org-get-heading))))
11369 (org-auto-repeat-maybe state))
11370 ;; Fixup cursor location if close to the keyword
11371 (if (and (outline-on-heading-p)
11372 (not (bolp))
11373 (save-excursion (beginning-of-line 1)
11374 (looking-at org-todo-line-regexp))
11375 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11376 (progn
11377 (goto-char (or (match-end 2) (match-end 1)))
11378 (and (looking-at " ") (just-one-space))))
11379 (when org-trigger-hook
11380 (save-excursion
11381 (run-hook-with-args 'org-trigger-hook change-plist))))))))
11383 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11384 "Block turning an entry into a TODO, using the hierarchy.
11385 This checks whether the current task should be blocked from state
11386 changes. Such blocking occurs when:
11388 1. The task has children which are not all in a completed state.
11390 2. A task has a parent with the property :ORDERED:, and there
11391 are siblings prior to the current task with incomplete
11392 status.
11394 3. The parent of the task is blocked because it has siblings that should
11395 be done first, or is child of a block grandparent TODO entry."
11397 (if (not org-enforce-todo-dependencies)
11398 t ; if locally turned off don't block
11399 (catch 'dont-block
11400 ;; If this is not a todo state change, or if this entry is already DONE,
11401 ;; do not block
11402 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11403 (member (plist-get change-plist :from)
11404 (cons 'done org-done-keywords))
11405 (member (plist-get change-plist :to)
11406 (cons 'todo org-not-done-keywords))
11407 (not (plist-get change-plist :to)))
11408 (throw 'dont-block t))
11409 ;; If this task has children, and any are undone, it's blocked
11410 (save-excursion
11411 (org-back-to-heading t)
11412 (let ((this-level (funcall outline-level)))
11413 (outline-next-heading)
11414 (let ((child-level (funcall outline-level)))
11415 (while (and (not (eobp))
11416 (> child-level this-level))
11417 ;; this todo has children, check whether they are all
11418 ;; completed
11419 (if (and (not (org-entry-is-done-p))
11420 (org-entry-is-todo-p))
11421 (throw 'dont-block nil))
11422 (outline-next-heading)
11423 (setq child-level (funcall outline-level))))))
11424 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11425 ;; any previous siblings are undone, it's blocked
11426 (save-excursion
11427 (org-back-to-heading t)
11428 (let* ((pos (point))
11429 (parent-pos (and (org-up-heading-safe) (point))))
11430 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11431 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11432 (forward-line 1)
11433 (re-search-forward org-not-done-heading-regexp pos t))
11434 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11435 ;; Search further up the hierarchy, to see if an anchestor is blocked
11436 (while t
11437 (goto-char parent-pos)
11438 (if (not (looking-at org-not-done-heading-regexp))
11439 (throw 'dont-block t)) ; do not block, parent is not a TODO
11440 (setq pos (point))
11441 (setq parent-pos (and (org-up-heading-safe) (point)))
11442 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11443 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11444 (forward-line 1)
11445 (re-search-forward org-not-done-heading-regexp pos t))
11446 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11448 (defcustom org-track-ordered-property-with-tag nil
11449 "Should the ORDERED property also be shown as a tag?
11450 The ORDERED property decides if an entry should require subtasks to be
11451 completed in sequence. Since a property is not very visible, setting
11452 this option means that toggling the ORDERED property with the command
11453 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11454 not relevant for the behavior, but it makes things more visible.
11456 Note that toggling the tag with tags commands will not change the property
11457 and therefore not influence behavior!
11459 This can be t, meaning the tag ORDERED should be used, It can also be a
11460 string to select a different tag for this task."
11461 :group 'org-todo
11462 :type '(choice
11463 (const :tag "No tracking" nil)
11464 (const :tag "Track with ORDERED tag" t)
11465 (string :tag "Use other tag")))
11467 (defun org-toggle-ordered-property ()
11468 "Toggle the ORDERED property of the current entry.
11469 For better visibility, you can track the value of this property with a tag.
11470 See variable `org-track-ordered-property-with-tag'."
11471 (interactive)
11472 (let* ((t1 org-track-ordered-property-with-tag)
11473 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11474 (save-excursion
11475 (org-back-to-heading)
11476 (if (org-entry-get nil "ORDERED")
11477 (progn
11478 (org-delete-property "ORDERED")
11479 (and tag (org-toggle-tag tag 'off))
11480 (message "Subtasks can be completed in arbitrary order"))
11481 (org-entry-put nil "ORDERED" "t")
11482 (and tag (org-toggle-tag tag 'on))
11483 (message "Subtasks must be completed in sequence")))))
11485 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11486 (defun org-block-todo-from-checkboxes (change-plist)
11487 "Block turning an entry into a TODO, using checkboxes.
11488 This checks whether the current task should be blocked from state
11489 changes because there are unchecked boxes in this entry."
11490 (if (not org-enforce-todo-checkbox-dependencies)
11491 t ; if locally turned off don't block
11492 (catch 'dont-block
11493 ;; If this is not a todo state change, or if this entry is already DONE,
11494 ;; do not block
11495 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11496 (member (plist-get change-plist :from)
11497 (cons 'done org-done-keywords))
11498 (member (plist-get change-plist :to)
11499 (cons 'todo org-not-done-keywords))
11500 (not (plist-get change-plist :to)))
11501 (throw 'dont-block t))
11502 ;; If this task has checkboxes that are not checked, it's blocked
11503 (save-excursion
11504 (org-back-to-heading t)
11505 (let ((beg (point)) end)
11506 (outline-next-heading)
11507 (setq end (point))
11508 (goto-char beg)
11509 (if (org-list-search-forward
11510 (concat (org-item-beginning-re)
11511 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11512 "\\[[- ]\\]")
11513 end t)
11514 (progn
11515 (if (boundp 'org-blocked-by-checkboxes)
11516 (setq org-blocked-by-checkboxes t))
11517 (throw 'dont-block nil)))))
11518 t))) ; do not block
11520 (defun org-entry-blocked-p ()
11521 "Is the current entry blocked?"
11522 (if (org-entry-get nil "NOBLOCKING")
11523 nil ;; Never block this entry
11524 (not
11525 (run-hook-with-args-until-failure
11526 'org-blocker-hook
11527 (list :type 'todo-state-change
11528 :position (point)
11529 :from 'todo
11530 :to 'done)))))
11532 (defun org-update-statistics-cookies (all)
11533 "Update the statistics cookie, either from TODO or from checkboxes.
11534 This should be called with the cursor in a line with a statistics cookie."
11535 (interactive "P")
11536 (if all
11537 (progn
11538 (org-update-checkbox-count 'all)
11539 (org-map-entries 'org-update-parent-todo-statistics))
11540 (if (not (org-on-heading-p))
11541 (org-update-checkbox-count)
11542 (let ((pos (move-marker (make-marker) (point)))
11543 end l1 l2)
11544 (ignore-errors (org-back-to-heading t))
11545 (if (not (org-on-heading-p))
11546 (org-update-checkbox-count)
11547 (setq l1 (org-outline-level))
11548 (setq end (save-excursion
11549 (outline-next-heading)
11550 (if (org-on-heading-p) (setq l2 (org-outline-level)))
11551 (point)))
11552 (if (and (save-excursion
11553 (re-search-forward
11554 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11555 (not (save-excursion (re-search-forward
11556 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11557 (org-update-checkbox-count)
11558 (if (and l2 (> l2 l1))
11559 (progn
11560 (goto-char end)
11561 (org-update-parent-todo-statistics))
11562 (goto-char pos)
11563 (beginning-of-line 1)
11564 (while (re-search-forward
11565 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11566 (point-at-eol) t)
11567 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11568 (goto-char pos)
11569 (move-marker pos nil)))))
11571 (defvar org-entry-property-inherited-from) ;; defined below
11572 (defun org-update-parent-todo-statistics ()
11573 "Update any statistics cookie in the parent of the current headline.
11574 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11575 the entire subtree and this will travel up the hierarchy and update
11576 statistics everywhere."
11577 (let* ((prop (save-excursion (org-up-heading-safe)
11578 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11579 (recursive (or (not org-hierarchical-todo-statistics)
11580 (and prop (string-match "\\<recursive\\>" prop))))
11581 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11583 (first t)
11584 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11585 level ltoggle l1 new ndel
11586 (cnt-all 0) (cnt-done 0) is-percent kwd
11587 checkbox-beg ov ovs ove cookie-present)
11588 (catch 'exit
11589 (save-excursion
11590 (beginning-of-line 1)
11591 (setq ltoggle (funcall outline-level))
11592 ;; Three situations are to consider:
11594 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11595 ;; to the top-level ancestor on the headline;
11597 ;; 2. If parent has "recursive" property, repeat up to the
11598 ;; headline setting that property, taking inheritance into
11599 ;; account;
11601 ;; 3. Else, move up to direct parent and proceed only once.
11602 (while (and (setq level (org-up-heading-safe))
11603 (or recursive first)
11604 (>= (point) lim))
11605 (setq first nil cookie-present nil)
11606 (unless (and level
11607 (not (string-match
11608 "\\<checkbox\\>"
11609 (downcase (or (org-entry-get nil "COOKIE_DATA")
11610 "")))))
11611 (throw 'exit nil))
11612 (while (re-search-forward box-re (point-at-eol) t)
11613 (setq cnt-all 0 cnt-done 0 cookie-present t)
11614 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11615 (save-match-data
11616 (unless (outline-next-heading) (throw 'exit nil))
11617 (while (and (looking-at org-complex-heading-regexp)
11618 (> (setq l1 (length (match-string 1))) level))
11619 (setq kwd (and (or recursive (= l1 ltoggle))
11620 (match-string 2)))
11621 (if (or (eq org-provide-todo-statistics 'all-headlines)
11622 (and (listp org-provide-todo-statistics)
11623 (or (member kwd org-provide-todo-statistics)
11624 (member kwd org-done-keywords))))
11625 (setq cnt-all (1+ cnt-all))
11626 (if (eq org-provide-todo-statistics t)
11627 (and kwd (setq cnt-all (1+ cnt-all)))))
11628 (and (member kwd org-done-keywords)
11629 (setq cnt-done (1+ cnt-done)))
11630 (outline-next-heading)))
11631 (setq new
11632 (if is-percent
11633 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11634 (format "[%d/%d]" cnt-done cnt-all))
11635 ndel (- (match-end 0) checkbox-beg))
11636 ;; handle overlays when updating cookie from column view
11637 (when (setq ov (car (overlays-at checkbox-beg)))
11638 (setq ovs (overlay-start ov) ove (overlay-end ov))
11639 (delete-overlay ov))
11640 (goto-char checkbox-beg)
11641 (insert new)
11642 (delete-region (point) (+ (point) ndel))
11643 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11644 (when ov (move-overlay ov ovs ove)))
11645 (when cookie-present
11646 (run-hook-with-args 'org-after-todo-statistics-hook
11647 cnt-done (- cnt-all cnt-done))))))
11648 (run-hooks 'org-todo-statistics-hook)))
11650 (defvar org-after-todo-statistics-hook nil
11651 "Hook that is called after a TODO statistics cookie has been updated.
11652 Each function is called with two arguments: the number of not-done entries
11653 and the number of done entries.
11655 For example, the following function, when added to this hook, will switch
11656 an entry to DONE when all children are done, and back to TODO when new
11657 entries are set to a TODO status. Note that this hook is only called
11658 when there is a statistics cookie in the headline!
11660 (defun org-summary-todo (n-done n-not-done)
11661 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11662 (let (org-log-done org-log-states) ; turn off logging
11663 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11666 (defvar org-todo-statistics-hook nil
11667 "Hook that is run whenever Org thinks TODO statistics should be updated.
11668 This hook runs even if there is no statistics cookie present, in which case
11669 `org-after-todo-statistics-hook' would not run.")
11671 (defun org-todo-trigger-tag-changes (state)
11672 "Apply the changes defined in `org-todo-state-tags-triggers'."
11673 (let ((l org-todo-state-tags-triggers)
11674 changes)
11675 (when (or (not state) (equal state ""))
11676 (setq changes (append changes (cdr (assoc "" l)))))
11677 (when (and (stringp state) (> (length state) 0))
11678 (setq changes (append changes (cdr (assoc state l)))))
11679 (when (member state org-not-done-keywords)
11680 (setq changes (append changes (cdr (assoc 'todo l)))))
11681 (when (member state org-done-keywords)
11682 (setq changes (append changes (cdr (assoc 'done l)))))
11683 (dolist (c changes)
11684 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11686 (defun org-local-logging (value)
11687 "Get logging settings from a property VALUE."
11688 (let* (words w a)
11689 ;; directly set the variables, they are already local.
11690 (setq org-log-done nil
11691 org-log-repeat nil
11692 org-todo-log-states nil)
11693 (setq words (org-split-string value))
11694 (while (setq w (pop words))
11695 (cond
11696 ((setq a (assoc w org-startup-options))
11697 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11698 (set (nth 1 a) (nth 2 a))))
11699 ((setq a (org-extract-log-state-settings w))
11700 (and (member (car a) org-todo-keywords-1)
11701 (push a org-todo-log-states)))))))
11703 (defun org-get-todo-sequence-head (kwd)
11704 "Return the head of the TODO sequence to which KWD belongs.
11705 If KWD is not set, check if there is a text property remembering the
11706 right sequence."
11707 (let (p)
11708 (cond
11709 ((not kwd)
11710 (or (get-text-property (point-at-bol) 'org-todo-head)
11711 (progn
11712 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11713 nil (point-at-eol)))
11714 (get-text-property p 'org-todo-head))))
11715 ((not (member kwd org-todo-keywords-1))
11716 (car org-todo-keywords-1))
11717 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11719 (defun org-fast-todo-selection ()
11720 "Fast TODO keyword selection with single keys.
11721 Returns the new TODO keyword, or nil if no state change should occur."
11722 (let* ((fulltable org-todo-key-alist)
11723 (done-keywords org-done-keywords) ;; needed for the faces.
11724 (maxlen (apply 'max (mapcar
11725 (lambda (x)
11726 (if (stringp (car x)) (string-width (car x)) 0))
11727 fulltable)))
11728 (expert nil)
11729 (fwidth (+ maxlen 3 1 3))
11730 (ncol (/ (- (window-width) 4) fwidth))
11731 tg cnt e c tbl
11732 groups ingroup)
11733 (save-excursion
11734 (save-window-excursion
11735 (if expert
11736 (set-buffer (get-buffer-create " *Org todo*"))
11737 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11738 (erase-buffer)
11739 (org-set-local 'org-done-keywords done-keywords)
11740 (setq tbl fulltable cnt 0)
11741 (while (setq e (pop tbl))
11742 (cond
11743 ((equal e '(:startgroup))
11744 (push '() groups) (setq ingroup t)
11745 (when (not (= cnt 0))
11746 (setq cnt 0)
11747 (insert "\n"))
11748 (insert "{ "))
11749 ((equal e '(:endgroup))
11750 (setq ingroup nil cnt 0)
11751 (insert "}\n"))
11752 ((equal e '(:newline))
11753 (when (not (= cnt 0))
11754 (setq cnt 0)
11755 (insert "\n")
11756 (setq e (car tbl))
11757 (while (equal (car tbl) '(:newline))
11758 (insert "\n")
11759 (setq tbl (cdr tbl)))))
11761 (setq tg (car e) c (cdr e))
11762 (if ingroup (push tg (car groups)))
11763 (setq tg (org-add-props tg nil 'face
11764 (org-get-todo-face tg)))
11765 (if (and (= cnt 0) (not ingroup)) (insert " "))
11766 (insert "[" c "] " tg (make-string
11767 (- fwidth 4 (length tg)) ?\ ))
11768 (when (= (setq cnt (1+ cnt)) ncol)
11769 (insert "\n")
11770 (if ingroup (insert " "))
11771 (setq cnt 0)))))
11772 (insert "\n")
11773 (goto-char (point-min))
11774 (if (not expert) (org-fit-window-to-buffer))
11775 (message "[a-z..]:Set [SPC]:clear")
11776 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11777 (cond
11778 ((or (= c ?\C-g)
11779 (and (= c ?q) (not (rassoc c fulltable))))
11780 (setq quit-flag t))
11781 ((= c ?\ ) nil)
11782 ((setq e (rassoc c fulltable) tg (car e))
11784 (t (setq quit-flag t)))))))
11786 (defun org-entry-is-todo-p ()
11787 (member (org-get-todo-state) org-not-done-keywords))
11789 (defun org-entry-is-done-p ()
11790 (member (org-get-todo-state) org-done-keywords))
11792 (defun org-get-todo-state ()
11793 (save-excursion
11794 (org-back-to-heading t)
11795 (and (looking-at org-todo-line-regexp)
11796 (match-end 2)
11797 (match-string 2))))
11799 (defun org-at-date-range-p (&optional inactive-ok)
11800 "Is the cursor inside a date range?"
11801 (interactive)
11802 (save-excursion
11803 (catch 'exit
11804 (let ((pos (point)))
11805 (skip-chars-backward "^[<\r\n")
11806 (skip-chars-backward "<[")
11807 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11808 (>= (match-end 0) pos)
11809 (throw 'exit t))
11810 (skip-chars-backward "^<[\r\n")
11811 (skip-chars-backward "<[")
11812 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11813 (>= (match-end 0) pos)
11814 (throw 'exit t)))
11815 nil)))
11817 (defun org-get-repeat (&optional tagline)
11818 "Check if there is a deadline/schedule with repeater in this entry."
11819 (save-match-data
11820 (save-excursion
11821 (org-back-to-heading t)
11822 (and (re-search-forward (if tagline
11823 (concat tagline "\\s-*" org-repeat-re)
11824 org-repeat-re)
11825 (org-entry-end-position) t)
11826 (match-string-no-properties 1)))))
11828 (defvar org-last-changed-timestamp)
11829 (defvar org-last-inserted-timestamp)
11830 (defvar org-log-post-message)
11831 (defvar org-log-note-purpose)
11832 (defvar org-log-note-how)
11833 (defvar org-log-note-extra)
11834 (defun org-auto-repeat-maybe (done-word)
11835 "Check if the current headline contains a repeated deadline/schedule.
11836 If yes, set TODO state back to what it was and change the base date
11837 of repeating deadline/scheduled time stamps to new date.
11838 This function is run automatically after each state change to a DONE state."
11839 ;; last-state is dynamically scoped into this function
11840 (let* ((repeat (org-get-repeat))
11841 (aa (assoc last-state org-todo-kwd-alist))
11842 (interpret (nth 1 aa))
11843 (head (nth 2 aa))
11844 (whata '(("d" . day) ("m" . month) ("y" . year)))
11845 (msg "Entry repeats: ")
11846 (org-log-done nil)
11847 (org-todo-log-states nil)
11848 re type n what ts time to-state)
11849 (when repeat
11850 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11851 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11852 org-todo-repeat-to-state))
11853 (unless (and to-state (member to-state org-todo-keywords-1))
11854 (setq to-state (if (eq interpret 'type) last-state head)))
11855 (org-todo to-state)
11856 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11857 (org-entry-put nil "LAST_REPEAT" (format-time-string
11858 (org-time-stamp-format t t))))
11859 (when org-log-repeat
11860 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11861 (memq 'org-add-log-note post-command-hook))
11862 ;; OK, we are already setup for some record
11863 (if (eq org-log-repeat 'note)
11864 ;; make sure we take a note, not only a time stamp
11865 (setq org-log-note-how 'note))
11866 ;; Set up for taking a record
11867 (org-add-log-setup 'state (or done-word (car org-done-keywords))
11868 last-state
11869 'findpos org-log-repeat)))
11870 (org-back-to-heading t)
11871 (org-add-planning-info nil nil 'closed)
11872 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11873 org-deadline-time-regexp "\\)\\|\\("
11874 org-ts-regexp "\\)"))
11875 (while (re-search-forward
11876 re (save-excursion (outline-next-heading) (point)) t)
11877 (setq type (if (match-end 1) org-scheduled-string
11878 (if (match-end 3) org-deadline-string "Plain:"))
11879 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
11880 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
11881 (setq n (string-to-number (match-string 2 ts))
11882 what (match-string 3 ts))
11883 (if (equal what "w") (setq n (* n 7) what "d"))
11884 ;; Preparation, see if we need to modify the start date for the change
11885 (when (match-end 1)
11886 (setq time (save-match-data (org-time-string-to-time ts)))
11887 (cond
11888 ((equal (match-string 1 ts) ".")
11889 ;; Shift starting date to today
11890 (org-timestamp-change
11891 (- (org-today) (time-to-days time))
11892 'day))
11893 ((equal (match-string 1 ts) "+")
11894 (let ((nshiftmax 10) (nshift 0))
11895 (while (or (= nshift 0)
11896 (<= (time-to-days time)
11897 (time-to-days (current-time))))
11898 (when (= (incf nshift) nshiftmax)
11899 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
11900 (error "Abort")))
11901 (org-timestamp-change n (cdr (assoc what whata)))
11902 (org-at-timestamp-p t)
11903 (setq ts (match-string 1))
11904 (setq time (save-match-data (org-time-string-to-time ts)))))
11905 (org-timestamp-change (- n) (cdr (assoc what whata)))
11906 ;; rematch, so that we have everything in place for the real shift
11907 (org-at-timestamp-p t)
11908 (setq ts (match-string 1))
11909 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
11910 (org-timestamp-change n (cdr (assoc what whata)))
11911 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
11912 (setq org-log-post-message msg)
11913 (message "%s" msg))))
11915 (defun org-show-todo-tree (arg)
11916 "Make a compact tree which shows all headlines marked with TODO.
11917 The tree will show the lines where the regexp matches, and all higher
11918 headlines above the match.
11919 With a \\[universal-argument] prefix, prompt for a regexp to match.
11920 With a numeric prefix N, construct a sparse tree for the Nth element
11921 of `org-todo-keywords-1'."
11922 (interactive "P")
11923 (let ((case-fold-search nil)
11924 (kwd-re
11925 (cond ((null arg) org-not-done-regexp)
11926 ((equal arg '(4))
11927 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
11928 (mapcar 'list org-todo-keywords-1))))
11929 (concat "\\("
11930 (mapconcat 'identity (org-split-string kwd "|") "\\|")
11931 "\\)\\>")))
11932 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
11933 (regexp-quote (nth (1- (prefix-numeric-value arg))
11934 org-todo-keywords-1)))
11935 (t (error "Invalid prefix argument: %s" arg)))))
11936 (message "%d TODO entries found"
11937 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
11939 (defun org-deadline (&optional remove time)
11940 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
11941 With argument REMOVE, remove any deadline from the item.
11942 With argument TIME, set the deadline at the corresponding date. TIME
11943 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
11944 (interactive "P")
11945 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11946 (let (org-loop-over-headlines-in-active-region)
11947 (org-map-entries
11948 `(org-deadline ',remove ,time) org-loop-over-headlines-in-active-region 'region (if (outline-invisible-p) (org-end-of-subtree nil t))))
11949 (let* ((old-date (org-entry-get nil "DEADLINE"))
11950 (repeater (and old-date
11951 (string-match
11952 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
11953 old-date)
11954 (match-string 1 old-date))))
11955 (if remove
11956 (progn
11957 (when (and old-date org-log-redeadline)
11958 (org-add-log-setup 'deldeadline nil old-date 'findpos
11959 org-log-redeadline))
11960 (org-remove-timestamp-with-keyword org-deadline-string)
11961 (message "Item no longer has a deadline."))
11962 (org-add-planning-info 'deadline time 'closed)
11963 (when (and old-date org-log-redeadline
11964 (not (equal old-date
11965 (substring org-last-inserted-timestamp 1 -1))))
11966 (org-add-log-setup 'redeadline nil old-date 'findpos
11967 org-log-redeadline))
11968 (when repeater
11969 (save-excursion
11970 (org-back-to-heading t)
11971 (when (re-search-forward (concat org-deadline-string " "
11972 org-last-inserted-timestamp)
11973 (save-excursion
11974 (outline-next-heading) (point)) t)
11975 (goto-char (1- (match-end 0)))
11976 (insert " " repeater)
11977 (setq org-last-inserted-timestamp
11978 (concat (substring org-last-inserted-timestamp 0 -1)
11979 " " repeater
11980 (substring org-last-inserted-timestamp -1))))))
11981 (message "Deadline on %s" org-last-inserted-timestamp)))))
11983 (defun org-schedule (&optional remove time)
11984 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
11985 With argument REMOVE, remove any scheduling date from the item.
11986 With argument TIME, scheduled at the corresponding date. TIME can
11987 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
11988 (interactive "P")
11989 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11990 (let (org-loop-over-headlines-in-active-region)
11991 (org-map-entries
11992 `(org-schedule ',remove ,time) org-loop-over-headlines-in-active-region 'region (if (outline-invisible-p) (org-end-of-subtree nil t))))
11993 (let* ((old-date (org-entry-get nil "SCHEDULED"))
11994 (repeater (and old-date
11995 (string-match
11996 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
11997 old-date)
11998 (match-string 1 old-date))))
11999 (if remove
12000 (progn
12001 (when (and old-date org-log-reschedule)
12002 (org-add-log-setup 'delschedule nil old-date 'findpos
12003 org-log-reschedule))
12004 (org-remove-timestamp-with-keyword org-scheduled-string)
12005 (message "Item is no longer scheduled."))
12006 (org-add-planning-info 'scheduled time 'closed)
12007 (when (and old-date org-log-reschedule
12008 (not (equal old-date
12009 (substring org-last-inserted-timestamp 1 -1))))
12010 (org-add-log-setup 'reschedule nil old-date 'findpos
12011 org-log-reschedule))
12012 (when repeater
12013 (save-excursion
12014 (org-back-to-heading t)
12015 (when (re-search-forward (concat org-scheduled-string " "
12016 org-last-inserted-timestamp)
12017 (save-excursion
12018 (outline-next-heading) (point)) t)
12019 (goto-char (1- (match-end 0)))
12020 (insert " " repeater)
12021 (setq org-last-inserted-timestamp
12022 (concat (substring org-last-inserted-timestamp 0 -1)
12023 " " repeater
12024 (substring org-last-inserted-timestamp -1))))))
12025 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12027 (defun org-get-scheduled-time (pom &optional inherit)
12028 "Get the scheduled time as a time tuple, of a format suitable
12029 for calling org-schedule with, or if there is no scheduling,
12030 returns nil."
12031 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12032 (when time
12033 (apply 'encode-time (org-parse-time-string time)))))
12035 (defun org-get-deadline-time (pom &optional inherit)
12036 "Get the deadline as a time tuple, of a format suitable for
12037 calling org-deadline with, or if there is no scheduling, returns
12038 nil."
12039 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12040 (when time
12041 (apply 'encode-time (org-parse-time-string time)))))
12043 (defun org-remove-timestamp-with-keyword (keyword)
12044 "Remove all time stamps with KEYWORD in the current entry."
12045 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12046 beg)
12047 (save-excursion
12048 (org-back-to-heading t)
12049 (setq beg (point))
12050 (outline-next-heading)
12051 (while (re-search-backward re beg t)
12052 (replace-match "")
12053 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12054 (equal (char-before) ?\ ))
12055 (backward-delete-char 1)
12056 (if (string-match "^[ \t]*$" (buffer-substring
12057 (point-at-bol) (point-at-eol)))
12058 (delete-region (point-at-bol)
12059 (min (point-max) (1+ (point-at-eol))))))))))
12061 (defun org-add-planning-info (what &optional time &rest remove)
12062 "Insert new timestamp with keyword in the line directly after the headline.
12063 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12064 If non is given, the user is prompted for a date.
12065 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12066 be removed."
12067 (interactive)
12068 (let (org-time-was-given org-end-time-was-given ts
12069 end default-time default-input)
12071 (catch 'exit
12072 (when (and (memq what '(scheduled deadline))
12073 (or (not time)
12074 (and (stringp time)
12075 (string-match "^[-+]+[0-9]" time))))
12076 ;; Try to get a default date/time from existing timestamp
12077 (save-excursion
12078 (org-back-to-heading t)
12079 (setq end (save-excursion (outline-next-heading) (point)))
12080 (when (re-search-forward (if (eq what 'scheduled)
12081 org-scheduled-time-regexp
12082 org-deadline-time-regexp)
12083 end t)
12084 (setq ts (match-string 1)
12085 default-time
12086 (apply 'encode-time (org-parse-time-string ts))
12087 default-input (and ts (org-get-compact-tod ts))))))
12088 (when what
12089 (setq time
12090 (if (stringp time)
12091 ;; This is a string (relative or absolute), set proper date
12092 (apply 'encode-time
12093 (org-read-date-analyze
12094 time default-time (decode-time default-time)))
12095 ;; If necessary, get the time from the user
12096 (or time (org-read-date nil 'to-time nil nil
12097 default-time default-input)))))
12099 (when (and org-insert-labeled-timestamps-at-point
12100 (member what '(scheduled deadline)))
12101 (insert
12102 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12103 (org-insert-time-stamp time org-time-was-given
12104 nil nil nil (list org-end-time-was-given))
12105 (setq what nil))
12106 (save-excursion
12107 (save-restriction
12108 (let (col list elt ts buffer-invisibility-spec)
12109 (org-back-to-heading t)
12110 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12111 (goto-char (match-end 1))
12112 (setq col (current-column))
12113 (goto-char (match-end 0))
12114 (if (eobp) (insert "\n") (forward-char 1))
12115 (when (and (not what)
12116 (not (looking-at
12117 (concat "[ \t]*"
12118 org-keyword-time-not-clock-regexp))))
12119 ;; Nothing to add, nothing to remove...... :-)
12120 (throw 'exit nil))
12121 (if (and (not (looking-at org-outline-regexp))
12122 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12123 "[^\r\n]*"))
12124 (not (equal (match-string 1) org-clock-string)))
12125 (narrow-to-region (match-beginning 0) (match-end 0))
12126 (insert-before-markers "\n")
12127 (backward-char 1)
12128 (narrow-to-region (point) (point))
12129 (and org-adapt-indentation (org-indent-to-column col)))
12130 ;; Check if we have to remove something.
12131 (setq list (cons what remove))
12132 (while list
12133 (setq elt (pop list))
12134 (when (or (and (eq elt 'scheduled)
12135 (re-search-forward org-scheduled-time-regexp nil t))
12136 (and (eq elt 'deadline)
12137 (re-search-forward org-deadline-time-regexp nil t))
12138 (and (eq elt 'closed)
12139 (re-search-forward org-closed-time-regexp nil t)))
12140 (replace-match "")
12141 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12142 (and (looking-at "[ \t]+") (replace-match ""))
12143 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12144 (when what
12145 (insert
12146 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12147 (cond ((eq what 'scheduled) org-scheduled-string)
12148 ((eq what 'deadline) org-deadline-string)
12149 ((eq what 'closed) org-closed-string))
12150 " ")
12151 (setq ts (org-insert-time-stamp
12152 time
12153 (or org-time-was-given
12154 (and (eq what 'closed) org-log-done-with-time))
12155 (eq what 'closed)
12156 nil nil (list org-end-time-was-given)))
12157 (insert
12158 (if (not (or (bolp) (eq (char-before) ?\ )
12159 (memq (char-after) '(32 10))
12160 (eobp))) " " ""))
12161 (end-of-line 1))
12162 (goto-char (point-min))
12163 (widen)
12164 (if (and (looking-at "[ \t]*\n")
12165 (equal (char-before) ?\n))
12166 (delete-region (1- (point)) (point-at-eol)))
12167 ts))))))
12169 (defvar org-log-note-marker (make-marker))
12170 (defvar org-log-note-purpose nil)
12171 (defvar org-log-note-state nil)
12172 (defvar org-log-note-previous-state nil)
12173 (defvar org-log-note-how nil)
12174 (defvar org-log-note-extra nil)
12175 (defvar org-log-note-window-configuration nil)
12176 (defvar org-log-note-return-to (make-marker))
12177 (defvar org-log-note-effective-time nil
12178 "Remembered current time so that dynamically scoped
12179 `org-extend-today-until' affects tha timestamps in state change
12180 log")
12182 (defvar org-log-post-message nil
12183 "Message to be displayed after a log note has been stored.
12184 The auto-repeater uses this.")
12186 (defun org-add-note ()
12187 "Add a note to the current entry.
12188 This is done in the same way as adding a state change note."
12189 (interactive)
12190 (org-add-log-setup 'note nil nil 'findpos nil))
12192 (defvar org-property-end-re)
12193 (defun org-add-log-setup (&optional purpose state prev-state
12194 findpos how extra)
12195 "Set up the post command hook to take a note.
12196 If this is about to TODO state change, the new state is expected in STATE.
12197 When FINDPOS is non-nil, find the correct position for the note in
12198 the current entry. If not, assume that it can be inserted at point.
12199 HOW is an indicator what kind of note should be created.
12200 EXTRA is additional text that will be inserted into the notes buffer."
12201 (let* ((org-log-into-drawer (org-log-into-drawer))
12202 (drawer (cond ((stringp org-log-into-drawer)
12203 org-log-into-drawer)
12204 (org-log-into-drawer "LOGBOOK")
12205 (t nil))))
12206 (save-restriction
12207 (save-excursion
12208 (when findpos
12209 (org-back-to-heading t)
12210 (narrow-to-region (point) (save-excursion
12211 (outline-next-heading) (point)))
12212 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12213 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12214 "[^\r\n]*\\)?"))
12215 (goto-char (match-end 0))
12216 (cond
12217 (drawer
12218 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12219 nil t)
12220 (progn
12221 (goto-char (match-end 0))
12222 (or org-log-states-order-reversed
12223 (and (re-search-forward org-property-end-re nil t)
12224 (goto-char (1- (match-beginning 0))))))
12225 (insert "\n:" drawer ":\n:END:")
12226 (beginning-of-line 0)
12227 (org-indent-line-function)
12228 (beginning-of-line 2)
12229 (org-indent-line-function)
12230 (end-of-line 0)))
12231 ((and org-log-state-notes-insert-after-drawers
12232 (save-excursion
12233 (forward-line) (looking-at org-drawer-regexp)))
12234 (forward-line)
12235 (while (looking-at org-drawer-regexp)
12236 (goto-char (match-end 0))
12237 (re-search-forward org-property-end-re (point-max) t)
12238 (forward-line))
12239 (forward-line -1)))
12240 (unless org-log-states-order-reversed
12241 (and (= (char-after) ?\n) (forward-char 1))
12242 (org-skip-over-state-notes)
12243 (skip-chars-backward " \t\n\r")))
12244 (move-marker org-log-note-marker (point))
12245 (setq org-log-note-purpose purpose
12246 org-log-note-state state
12247 org-log-note-previous-state prev-state
12248 org-log-note-how how
12249 org-log-note-extra extra
12250 org-log-note-effective-time (org-current-effective-time))
12251 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12253 (defun org-skip-over-state-notes ()
12254 "Skip past the list of State notes in an entry."
12255 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12256 (when (ignore-errors (goto-char (org-in-item-p)))
12257 (let* ((struct (org-list-struct))
12258 (prevs (org-list-prevs-alist struct)))
12259 (while (looking-at "[ \t]*- State")
12260 (goto-char (or (org-list-get-next-item (point) struct prevs)
12261 (org-list-get-item-end (point) struct)))))))
12263 (defun org-add-log-note (&optional purpose)
12264 "Pop up a window for taking a note, and add this note later at point."
12265 (remove-hook 'post-command-hook 'org-add-log-note)
12266 (setq org-log-note-window-configuration (current-window-configuration))
12267 (delete-other-windows)
12268 (move-marker org-log-note-return-to (point))
12269 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12270 (goto-char org-log-note-marker)
12271 (org-switch-to-buffer-other-window "*Org Note*")
12272 (erase-buffer)
12273 (if (memq org-log-note-how '(time state))
12274 (let (current-prefix-arg) (org-store-log-note))
12275 (let ((org-inhibit-startup t)) (org-mode))
12276 (insert (format "# Insert note for %s.
12277 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12278 (cond
12279 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12280 ((eq org-log-note-purpose 'done) "closed todo item")
12281 ((eq org-log-note-purpose 'state)
12282 (format "state change from \"%s\" to \"%s\""
12283 (or org-log-note-previous-state "")
12284 (or org-log-note-state "")))
12285 ((eq org-log-note-purpose 'reschedule)
12286 "rescheduling")
12287 ((eq org-log-note-purpose 'delschedule)
12288 "no longer scheduled")
12289 ((eq org-log-note-purpose 'redeadline)
12290 "changing deadline")
12291 ((eq org-log-note-purpose 'deldeadline)
12292 "removing deadline")
12293 ((eq org-log-note-purpose 'refile)
12294 "refiling")
12295 ((eq org-log-note-purpose 'note)
12296 "this entry")
12297 (t (error "This should not happen")))))
12298 (if org-log-note-extra (insert org-log-note-extra))
12299 (org-set-local 'org-finish-function 'org-store-log-note)
12300 (run-hooks 'org-log-buffer-setup-hook)))
12302 (defvar org-note-abort nil) ; dynamically scoped
12303 (defun org-store-log-note ()
12304 "Finish taking a log note, and insert it to where it belongs."
12305 (let ((txt (buffer-string))
12306 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12307 lines ind bul)
12308 (kill-buffer (current-buffer))
12309 (while (string-match "\\`#.*\n[ \t\n]*" txt)
12310 (setq txt (replace-match "" t t txt)))
12311 (if (string-match "\\s-+\\'" txt)
12312 (setq txt (replace-match "" t t txt)))
12313 (setq lines (org-split-string txt "\n"))
12314 (when (and note (string-match "\\S-" note))
12315 (setq note
12316 (org-replace-escapes
12317 note
12318 (list (cons "%u" (user-login-name))
12319 (cons "%U" user-full-name)
12320 (cons "%t" (format-time-string
12321 (org-time-stamp-format 'long 'inactive)
12322 org-log-note-effective-time))
12323 (cons "%T" (format-time-string
12324 (org-time-stamp-format 'long nil)
12325 org-log-note-effective-time))
12326 (cons "%d" (format-time-string
12327 (org-time-stamp-format nil 'inactive)
12328 org-log-note-effective-time))
12329 (cons "%D" (format-time-string
12330 (org-time-stamp-format nil nil)
12331 org-log-note-effective-time))
12332 (cons "%s" (if org-log-note-state
12333 (concat "\"" org-log-note-state "\"")
12334 ""))
12335 (cons "%S" (if org-log-note-previous-state
12336 (concat "\"" org-log-note-previous-state "\"")
12337 "\"\"")))))
12338 (if lines (setq note (concat note " \\\\")))
12339 (push note lines))
12340 (when (or current-prefix-arg org-note-abort)
12341 (when org-log-into-drawer
12342 (org-remove-empty-drawer-at
12343 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12344 org-log-note-marker))
12345 (setq lines nil))
12346 (when lines
12347 (with-current-buffer (marker-buffer org-log-note-marker)
12348 (save-excursion
12349 (goto-char org-log-note-marker)
12350 (move-marker org-log-note-marker nil)
12351 (end-of-line 1)
12352 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12353 (setq ind (save-excursion
12354 (if (ignore-errors (goto-char (org-in-item-p)))
12355 (let ((struct (org-list-struct)))
12356 (org-list-get-ind
12357 (org-list-get-top-point struct) struct))
12358 (skip-chars-backward " \r\t\n")
12359 (cond
12360 ((and (org-at-heading-p)
12361 org-adapt-indentation)
12362 (1+ (org-current-level)))
12363 ((org-at-heading-p) 0)
12364 (t (org-get-indentation))))))
12365 (setq bul (org-list-bullet-string "-"))
12366 (org-indent-line-to ind)
12367 (insert bul (pop lines))
12368 (let ((ind-body (+ (length bul) ind)))
12369 (while lines
12370 (insert "\n")
12371 (org-indent-line-to ind-body)
12372 (insert (pop lines))))
12373 (message "Note stored")
12374 (org-back-to-heading t)
12375 (org-cycle-hide-drawers 'children)))))
12376 (set-window-configuration org-log-note-window-configuration)
12377 (with-current-buffer (marker-buffer org-log-note-return-to)
12378 (goto-char org-log-note-return-to))
12379 (move-marker org-log-note-return-to nil)
12380 (and org-log-post-message (message "%s" org-log-post-message)))
12382 (defun org-remove-empty-drawer-at (drawer pos)
12383 "Remove an empty drawer DRAWER at position POS.
12384 POS may also be a marker."
12385 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12386 (save-excursion
12387 (save-restriction
12388 (widen)
12389 (goto-char pos)
12390 (if (org-in-regexp
12391 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12392 (replace-match ""))))))
12394 (defun org-sparse-tree (&optional arg)
12395 "Create a sparse tree, prompt for the details.
12396 This command can create sparse trees. You first need to select the type
12397 of match used to create the tree:
12399 t Show all TODO entries.
12400 T Show entries with a specific TODO keyword.
12401 m Show entries selected by a tags/property match.
12402 p Enter a property name and its value (both with completion on existing
12403 names/values) and show entries with that property.
12404 r Show entries matching a regular expression (`/' can be used as well)
12405 d Show deadlines due within `org-deadline-warning-days'.
12406 b Show deadlines and scheduled items before a date.
12407 a Show deadlines and scheduled items after a date."
12408 (interactive "P")
12409 (let (ans kwd value)
12410 (message "Sparse tree: [r]egexp [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty\n [d]eadlines [b]efore-date [a]fter-date")
12411 (setq ans (read-char-exclusive))
12412 (cond
12413 ((equal ans ?d)
12414 (call-interactively 'org-check-deadlines))
12415 ((equal ans ?b)
12416 (call-interactively 'org-check-before-date))
12417 ((equal ans ?a)
12418 (call-interactively 'org-check-after-date))
12419 ((equal ans ?t)
12420 (org-show-todo-tree nil))
12421 ((equal ans ?T)
12422 (org-show-todo-tree '(4)))
12423 ((member ans '(?T ?m))
12424 (call-interactively 'org-match-sparse-tree))
12425 ((member ans '(?p ?P))
12426 (setq kwd (org-icompleting-read "Property: "
12427 (mapcar 'list (org-buffer-property-keys))))
12428 (setq value (org-icompleting-read "Value: "
12429 (mapcar 'list (org-property-values kwd))))
12430 (unless (string-match "\\`{.*}\\'" value)
12431 (setq value (concat "\"" value "\"")))
12432 (org-match-sparse-tree arg (concat kwd "=" value)))
12433 ((member ans '(?r ?R ?/))
12434 (call-interactively 'org-occur))
12435 (t (error "No such sparse tree command \"%c\"" ans)))))
12437 (defvar org-occur-highlights nil
12438 "List of overlays used for occur matches.")
12439 (make-variable-buffer-local 'org-occur-highlights)
12440 (defvar org-occur-parameters nil
12441 "Parameters of the active org-occur calls.
12442 This is a list, each call to org-occur pushes as cons cell,
12443 containing the regular expression and the callback, onto the list.
12444 The list can contain several entries if `org-occur' has been called
12445 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12446 will only contain one set of parameters. When the highlights are
12447 removed (for example with `C-c C-c', or with the next edit (depending
12448 on `org-remove-highlights-with-change'), this variable is emptied
12449 as well.")
12450 (make-variable-buffer-local 'org-occur-parameters)
12452 (defun org-occur (regexp &optional keep-previous callback)
12453 "Make a compact tree which shows all matches of REGEXP.
12454 The tree will show the lines where the regexp matches, and all higher
12455 headlines above the match. It will also show the heading after the match,
12456 to make sure editing the matching entry is easy.
12457 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12458 call to `org-occur' will be kept, to allow stacking of calls to this
12459 command.
12460 If CALLBACK is non-nil, it is a function which is called to confirm
12461 that the match should indeed be shown."
12462 (interactive "sRegexp: \nP")
12463 (when (equal regexp "")
12464 (error "Regexp cannot be empty"))
12465 (unless keep-previous
12466 (org-remove-occur-highlights nil nil t))
12467 (push (cons regexp callback) org-occur-parameters)
12468 (let ((cnt 0))
12469 (save-excursion
12470 (goto-char (point-min))
12471 (if (or (not keep-previous) ; do not want to keep
12472 (not org-occur-highlights)) ; no previous matches
12473 ;; hide everything
12474 (org-overview))
12475 (while (re-search-forward regexp nil t)
12476 (when (or (not callback)
12477 (save-match-data (funcall callback)))
12478 (setq cnt (1+ cnt))
12479 (when org-highlight-sparse-tree-matches
12480 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12481 (org-show-context 'occur-tree))))
12482 (when org-remove-highlights-with-change
12483 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12484 nil 'local))
12485 (unless org-sparse-tree-open-archived-trees
12486 (org-hide-archived-subtrees (point-min) (point-max)))
12487 (run-hooks 'org-occur-hook)
12488 (if (org-called-interactively-p 'interactive)
12489 (message "%d match(es) for regexp %s" cnt regexp))
12490 cnt))
12492 (defun org-occur-next-match (&optional n reset)
12493 "Function for `next-error-function' to find sparse tree matches.
12494 N is the number of matches to move, when negative move backwards.
12495 RESET is entirely ignored - this function always goes back to the
12496 starting point when no match is found."
12497 (let* ((limit (if (< n 0) (point-min) (point-max)))
12498 (search-func (if (< n 0)
12499 'previous-single-char-property-change
12500 'next-single-char-property-change))
12501 (n (abs n))
12502 (pos (point))
12504 (catch 'exit
12505 (while (setq p1 (funcall search-func (point) 'org-type))
12506 (when (equal p1 limit)
12507 (goto-char pos)
12508 (error "No more matches"))
12509 (when (equal (get-char-property p1 'org-type) 'org-occur)
12510 (setq n (1- n))
12511 (when (= n 0)
12512 (goto-char p1)
12513 (throw 'exit (point))))
12514 (goto-char p1))
12515 (goto-char p1)
12516 (error "No more matches"))))
12518 (defun org-show-context (&optional key)
12519 "Make sure point and context are visible.
12520 How much context is shown depends upon the variables
12521 `org-show-hierarchy-above', `org-show-following-heading'. and
12522 `org-show-siblings'."
12523 (let ((heading-p (org-on-heading-p t))
12524 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12525 (following-p (org-get-alist-option org-show-following-heading key))
12526 (entry-p (org-get-alist-option org-show-entry-below key))
12527 (siblings-p (org-get-alist-option org-show-siblings key)))
12528 (catch 'exit
12529 ;; Show heading or entry text
12530 (if (and heading-p (not entry-p))
12531 (org-flag-heading nil) ; only show the heading
12532 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12533 (org-show-hidden-entry))) ; show entire entry
12534 (when following-p
12535 ;; Show next sibling, or heading below text
12536 (save-excursion
12537 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12538 (org-flag-heading nil))))
12539 (when siblings-p (org-show-siblings))
12540 (when hierarchy-p
12541 ;; show all higher headings, possibly with siblings
12542 (save-excursion
12543 (while (and (condition-case nil
12544 (progn (org-up-heading-all 1) t)
12545 (error nil))
12546 (not (bobp)))
12547 (org-flag-heading nil)
12548 (when siblings-p (org-show-siblings))))))))
12550 (defvar org-reveal-start-hook nil
12551 "Hook run before revealing a location.")
12553 (defun org-reveal (&optional siblings)
12554 "Show current entry, hierarchy above it, and the following headline.
12555 This can be used to show a consistent set of context around locations
12556 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12557 not t for the search context.
12559 With optional argument SIBLINGS, on each level of the hierarchy all
12560 siblings are shown. This repairs the tree structure to what it would
12561 look like when opened with hierarchical calls to `org-cycle'.
12562 With double optional argument \\[universal-argument] \\[universal-argument], \
12563 go to the parent and show the
12564 entire tree."
12565 (interactive "P")
12566 (run-hooks 'org-reveal-start-hook)
12567 (let ((org-show-hierarchy-above t)
12568 (org-show-following-heading t)
12569 (org-show-siblings (if siblings t org-show-siblings)))
12570 (org-show-context nil))
12571 (when (equal siblings '(16))
12572 (save-excursion
12573 (when (org-up-heading-safe)
12574 (org-show-subtree)
12575 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12577 (defun org-highlight-new-match (beg end)
12578 "Highlight from BEG to END and mark the highlight is an occur headline."
12579 (let ((ov (make-overlay beg end)))
12580 (overlay-put ov 'face 'secondary-selection)
12581 (overlay-put ov 'org-type 'org-occur)
12582 (push ov org-occur-highlights)))
12584 (defun org-remove-occur-highlights (&optional beg end noremove)
12585 "Remove the occur highlights from the buffer.
12586 BEG and END are ignored. If NOREMOVE is nil, remove this function
12587 from the `before-change-functions' in the current buffer."
12588 (interactive)
12589 (unless org-inhibit-highlight-removal
12590 (mapc 'delete-overlay org-occur-highlights)
12591 (setq org-occur-highlights nil)
12592 (setq org-occur-parameters nil)
12593 (unless noremove
12594 (remove-hook 'before-change-functions
12595 'org-remove-occur-highlights 'local))))
12597 ;;;; Priorities
12599 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12600 "Regular expression matching the priority indicator.")
12602 (defvar org-remove-priority-next-time nil)
12604 (defun org-priority-up ()
12605 "Increase the priority of the current item."
12606 (interactive)
12607 (org-priority 'up))
12609 (defun org-priority-down ()
12610 "Decrease the priority of the current item."
12611 (interactive)
12612 (org-priority 'down))
12614 (defun org-priority (&optional action)
12615 "Change the priority of an item by ARG.
12616 ACTION can be `set', `up', `down', or a character."
12617 (interactive)
12618 (unless org-enable-priority-commands
12619 (error "Priority commands are disabled"))
12620 (setq action (or action 'set))
12621 (let (current new news have remove)
12622 (save-excursion
12623 (org-back-to-heading t)
12624 (if (looking-at org-priority-regexp)
12625 (setq current (string-to-char (match-string 2))
12626 have t))
12627 (cond
12628 ((eq action 'remove)
12629 (setq remove t new ?\ ))
12630 ((or (eq action 'set)
12631 (if (featurep 'xemacs) (characterp action) (integerp action)))
12632 (if (not (eq action 'set))
12633 (setq new action)
12634 (message "Priority %c-%c, SPC to remove: "
12635 org-highest-priority org-lowest-priority)
12636 (save-match-data
12637 (setq new (read-char-exclusive))))
12638 (if (and (= (upcase org-highest-priority) org-highest-priority)
12639 (= (upcase org-lowest-priority) org-lowest-priority))
12640 (setq new (upcase new)))
12641 (cond ((equal new ?\ ) (setq remove t))
12642 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12643 (error "Priority must be between `%c' and `%c'"
12644 org-highest-priority org-lowest-priority))))
12645 ((eq action 'up)
12646 (setq new (if have
12647 (1- current) ; normal cycling
12648 ;; last priority was empty
12649 (if (eq last-command this-command)
12650 org-lowest-priority ; wrap around empty to lowest
12651 ;; default
12652 (if org-priority-start-cycle-with-default
12653 org-default-priority
12654 (1- org-default-priority))))))
12655 ((eq action 'down)
12656 (setq new (if have
12657 (1+ current) ; normal cycling
12658 ;; last priority was empty
12659 (if (eq last-command this-command)
12660 org-highest-priority ; wrap around empty to highest
12661 ;; default
12662 (if org-priority-start-cycle-with-default
12663 org-default-priority
12664 (1+ org-default-priority))))))
12665 (t (error "Invalid action")))
12666 (if (or (< (upcase new) org-highest-priority)
12667 (> (upcase new) org-lowest-priority))
12668 (if (and (memq action '(up down))
12669 (not have) (not (eq last-command this-command)))
12670 ;; `new' is from default priority
12671 (error
12672 "The default can not be set, see `org-default-priority' why")
12673 ;; normal cycling: `new' is beyond highest/lowest priority
12674 ;; and is wrapped around to the empty priority
12675 (setq remove t)))
12676 (setq news (format "%c" new))
12677 (if have
12678 (if remove
12679 (replace-match "" t t nil 1)
12680 (replace-match news t t nil 2))
12681 (if remove
12682 (error "No priority cookie found in line")
12683 (let ((case-fold-search nil))
12684 (looking-at org-todo-line-regexp))
12685 (if (match-end 2)
12686 (progn
12687 (goto-char (match-end 2))
12688 (insert " [#" news "]"))
12689 (goto-char (match-beginning 3))
12690 (insert "[#" news "] "))))
12691 (org-preserve-lc (org-set-tags nil 'align)))
12692 (if remove
12693 (message "Priority removed")
12694 (message "Priority of current item set to %s" news))))
12696 (defun org-get-priority (s)
12697 "Find priority cookie and return priority."
12698 (if (functionp org-get-priority-function)
12699 (funcall org-get-priority-function)
12700 (save-match-data
12701 (if (not (string-match org-priority-regexp s))
12702 (* 1000 (- org-lowest-priority org-default-priority))
12703 (* 1000 (- org-lowest-priority
12704 (string-to-char (match-string 2 s))))))))
12706 ;;;; Tags
12708 (defvar org-agenda-archives-mode)
12709 (defvar org-map-continue-from nil
12710 "Position from where mapping should continue.
12711 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
12713 (defvar org-scanner-tags nil
12714 "The current tag list while the tags scanner is running.")
12715 (defvar org-trust-scanner-tags nil
12716 "Should `org-get-tags-at' use the tags for the scanner.
12717 This is for internal dynamical scoping only.
12718 When this is non-nil, the function `org-get-tags-at' will return the value
12719 of `org-scanner-tags' instead of building the list by itself. This
12720 can lead to large speed-ups when the tags scanner is used in a file with
12721 many entries, and when the list of tags is retrieved, for example to
12722 obtain a list of properties. Building the tags list for each entry in such
12723 a file becomes an N^2 operation - but with this variable set, it scales
12724 as N.")
12726 (defun org-scan-tags (action matcher &optional todo-only start-level)
12727 "Scan headline tags with inheritance and produce output ACTION.
12729 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12730 or `agenda' to produce an entry list for an agenda view. It can also be
12731 a Lisp form or a function that should be called at each matched headline, in
12732 this case the return value is a list of all return values from these calls.
12734 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12735 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12736 only lines with a TODO keyword are included in the output.
12738 START-LEVEL can be a string with asterisks, reducing the scope to
12739 headlines matching this string."
12740 (require 'org-agenda)
12741 (let* ((re (concat "^"
12742 (if start-level
12743 ;; Get the correct level to match
12744 (concat "\\*\\{" (number-to-string start-level) "\\} ")
12745 org-outline-regexp)
12746 " *\\(\\<\\("
12747 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12748 (org-re
12749 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
12750 (props (list 'face 'default
12751 'done-face 'org-agenda-done
12752 'undone-face 'default
12753 'mouse-face 'highlight
12754 'org-not-done-regexp org-not-done-regexp
12755 'org-todo-regexp org-todo-regexp
12756 'org-complex-heading-regexp org-complex-heading-regexp
12757 'help-echo
12758 (format "mouse-2 or RET jump to org file %s"
12759 (abbreviate-file-name
12760 (or (buffer-file-name (buffer-base-buffer))
12761 (buffer-name (buffer-base-buffer)))))))
12762 (case-fold-search nil)
12763 (org-map-continue-from nil)
12764 lspos tags tags-list
12765 (tags-alist (list (cons 0 org-file-tags)))
12766 (llast 0) rtn rtn1 level category i txt
12767 todo marker entry priority)
12768 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12769 (setq action (list 'lambda nil action)))
12770 (save-excursion
12771 (goto-char (point-min))
12772 (when (eq action 'sparse-tree)
12773 (org-overview)
12774 (org-remove-occur-highlights))
12775 (while (re-search-forward re nil t)
12776 (catch :skip
12777 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12778 tags (if (match-end 4) (org-match-string-no-properties 4)))
12779 (goto-char (setq lspos (match-beginning 0)))
12780 (setq level (org-reduced-level (funcall outline-level))
12781 category (org-get-category))
12782 (setq i llast llast level)
12783 ;; remove tag lists from same and sublevels
12784 (while (>= i level)
12785 (when (setq entry (assoc i tags-alist))
12786 (setq tags-alist (delete entry tags-alist)))
12787 (setq i (1- i)))
12788 ;; add the next tags
12789 (when tags
12790 (setq tags (org-split-string tags ":")
12791 tags-alist
12792 (cons (cons level tags) tags-alist)))
12793 ;; compile tags for current headline
12794 (setq tags-list
12795 (if org-use-tag-inheritance
12796 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12797 tags)
12798 org-scanner-tags tags-list)
12799 (when org-use-tag-inheritance
12800 (setcdr (car tags-alist)
12801 (mapcar (lambda (x)
12802 (setq x (copy-sequence x))
12803 (org-add-prop-inherited x))
12804 (cdar tags-alist))))
12805 (when (and tags org-use-tag-inheritance
12806 (or (not (eq t org-use-tag-inheritance))
12807 org-tags-exclude-from-inheritance))
12808 ;; selective inheritance, remove uninherited ones
12809 (setcdr (car tags-alist)
12810 (org-remove-uninherited-tags (cdar tags-alist))))
12811 (when (and
12813 ;; eval matcher only when the todo condition is OK
12814 (and (or (not todo-only) (member todo org-not-done-keywords))
12815 (let ((case-fold-search t)) (eval matcher)))
12817 ;; Call the skipper, but return t if it does not skip,
12818 ;; so that the `and' form continues evaluating
12819 (progn
12820 (unless (eq action 'sparse-tree) (org-agenda-skip))
12823 ;; Check if timestamps are deselecting this entry
12824 (or (not todo-only)
12825 (and (member todo org-not-done-keywords)
12826 (or (not org-agenda-tags-todo-honor-ignore-options)
12827 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
12829 ;; Extra check for the archive tag
12830 ;; FIXME: Does the skipper already do this????
12832 (not (member org-archive-tag tags-list))
12833 ;; we have an archive tag, should we use this anyway?
12834 (or (not org-agenda-skip-archived-trees)
12835 (and (eq action 'agenda) org-agenda-archives-mode))))
12837 ;; select this headline
12839 (cond
12840 ((eq action 'sparse-tree)
12841 (and org-highlight-sparse-tree-matches
12842 (org-get-heading) (match-end 0)
12843 (org-highlight-new-match
12844 (match-beginning 0) (match-beginning 1)))
12845 (org-show-context 'tags-tree))
12846 ((eq action 'agenda)
12847 (setq txt (org-agenda-format-item
12849 (concat
12850 (if (eq org-tags-match-list-sublevels 'indented)
12851 (make-string (1- level) ?.) "")
12852 (org-get-heading))
12853 category
12854 tags-list
12856 priority (org-get-priority txt))
12857 (goto-char lspos)
12858 (setq marker (org-agenda-new-marker))
12859 (org-add-props txt props
12860 'org-marker marker 'org-hd-marker marker 'org-category category
12861 'todo-state todo
12862 'priority priority 'type "tagsmatch")
12863 (push txt rtn))
12864 ((functionp action)
12865 (setq org-map-continue-from nil)
12866 (save-excursion
12867 (setq rtn1 (funcall action))
12868 (push rtn1 rtn)))
12869 (t (error "Invalid action")))
12871 ;; if we are to skip sublevels, jump to end of subtree
12872 (unless org-tags-match-list-sublevels
12873 (org-end-of-subtree t)
12874 (backward-char 1))))
12875 ;; Get the correct position from where to continue
12876 (if org-map-continue-from
12877 (goto-char org-map-continue-from)
12878 (and (= (point) lspos) (end-of-line 1)))))
12879 (when (and (eq action 'sparse-tree)
12880 (not org-sparse-tree-open-archived-trees))
12881 (org-hide-archived-subtrees (point-min) (point-max)))
12882 (nreverse rtn)))
12884 (defun org-remove-uninherited-tags (tags)
12885 "Remove all tags that are not inherited from the list TAGS."
12886 (cond
12887 ((eq org-use-tag-inheritance t)
12888 (if org-tags-exclude-from-inheritance
12889 (org-delete-all org-tags-exclude-from-inheritance tags)
12890 tags))
12891 ((not org-use-tag-inheritance) nil)
12892 ((stringp org-use-tag-inheritance)
12893 (delq nil (mapcar
12894 (lambda (x)
12895 (if (and (string-match org-use-tag-inheritance x)
12896 (not (member x org-tags-exclude-from-inheritance)))
12897 x nil))
12898 tags)))
12899 ((listp org-use-tag-inheritance)
12900 (delq nil (mapcar
12901 (lambda (x)
12902 (if (member x org-use-tag-inheritance) x nil))
12903 tags)))))
12905 (defvar todo-only) ;; dynamically scoped
12907 (defun org-match-sparse-tree (&optional todo-only match)
12908 "Create a sparse tree according to tags string MATCH.
12909 MATCH can contain positive and negative selection of tags, like
12910 \"+WORK+URGENT-WITHBOSS\".
12911 If optional argument TODO-ONLY is non-nil, only select lines that are
12912 also TODO lines."
12913 (interactive "P")
12914 (org-prepare-agenda-buffers (list (current-buffer)))
12915 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
12917 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
12919 (defvar org-cached-props nil)
12920 (defun org-cached-entry-get (pom property)
12921 (if (or (eq t org-use-property-inheritance)
12922 (and (stringp org-use-property-inheritance)
12923 (string-match org-use-property-inheritance property))
12924 (and (listp org-use-property-inheritance)
12925 (member property org-use-property-inheritance)))
12926 ;; Caching is not possible, check it directly
12927 (org-entry-get pom property 'inherit)
12928 ;; Get all properties, so that we can do complicated checks easily
12929 (cdr (assoc property (or org-cached-props
12930 (setq org-cached-props
12931 (org-entry-properties pom)))))))
12933 (defun org-global-tags-completion-table (&optional files)
12934 "Return the list of all tags in all agenda buffer/files.
12935 Optional FILES argument is a list of files to which can be used
12936 instead of the agenda files."
12937 (save-excursion
12938 (org-uniquify
12939 (delq nil
12940 (apply 'append
12941 (mapcar
12942 (lambda (file)
12943 (set-buffer (find-file-noselect file))
12944 (append (org-get-buffer-tags)
12945 (mapcar (lambda (x) (if (stringp (car-safe x))
12946 (list (car-safe x)) nil))
12947 org-tag-alist)))
12948 (if (and files (car files))
12949 files
12950 (org-agenda-files))))))))
12952 (defun org-make-tags-matcher (match)
12953 "Create the TAGS/TODO matcher form for the selection string MATCH."
12954 ;; todo-only is scoped dynamically into this function, and the function
12955 ;; may change it if the matcher asks for it.
12956 (unless match
12957 ;; Get a new match request, with completion
12958 (let ((org-last-tags-completion-table
12959 (org-global-tags-completion-table)))
12960 (setq match (org-completing-read-no-i
12961 "Match: " 'org-tags-completion-function nil nil nil
12962 'org-tags-history))))
12964 ;; Parse the string and create a lisp form
12965 (let ((match0 match)
12966 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
12967 minus tag mm
12968 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
12969 orterms term orlist re-p str-p level-p level-op time-p
12970 prop-p pn pv po gv rest)
12971 (if (string-match "/+" match)
12972 ;; match contains also a todo-matching request
12973 (progn
12974 (setq tagsmatch (substring match 0 (match-beginning 0))
12975 todomatch (substring match (match-end 0)))
12976 (if (string-match "^!" todomatch)
12977 (setq todo-only t todomatch (substring todomatch 1)))
12978 (if (string-match "^\\s-*$" todomatch)
12979 (setq todomatch nil)))
12980 ;; only matching tags
12981 (setq tagsmatch match todomatch nil))
12983 ;; Make the tags matcher
12984 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
12985 (setq tagsmatcher t)
12986 (setq orterms (org-split-string tagsmatch "|") orlist nil)
12987 (while (setq term (pop orterms))
12988 (while (and (equal (substring term -1) "\\") orterms)
12989 (setq term (concat term "|" (pop orterms)))) ; repair bad split
12990 (while (string-match re term)
12991 (setq rest (substring term (match-end 0))
12992 minus (and (match-end 1)
12993 (equal (match-string 1 term) "-"))
12994 tag (save-match-data (replace-regexp-in-string
12995 "\\\\-" "-"
12996 (match-string 2 term)))
12997 re-p (equal (string-to-char tag) ?{)
12998 level-p (match-end 4)
12999 prop-p (match-end 5)
13000 mm (cond
13001 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13002 (level-p
13003 (setq level-op (org-op-to-function (match-string 3 term)))
13004 `(,level-op level ,(string-to-number
13005 (match-string 4 term))))
13006 (prop-p
13007 (setq pn (match-string 5 term)
13008 po (match-string 6 term)
13009 pv (match-string 7 term)
13010 re-p (equal (string-to-char pv) ?{)
13011 str-p (equal (string-to-char pv) ?\")
13012 time-p (save-match-data
13013 (string-match "^\"[[<].*[]>]\"$" pv))
13014 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13015 (if time-p (setq pv (org-matcher-time pv)))
13016 (setq po (org-op-to-function po (if time-p 'time str-p)))
13017 (cond
13018 ((equal pn "CATEGORY")
13019 (setq gv '(get-text-property (point) 'org-category)))
13020 ((equal pn "TODO")
13021 (setq gv 'todo))
13023 (setq gv `(org-cached-entry-get nil ,pn))))
13024 (if re-p
13025 (if (eq po 'org<>)
13026 `(not (string-match ,pv (or ,gv "")))
13027 `(string-match ,pv (or ,gv "")))
13028 (if str-p
13029 `(,po (or ,gv "") ,pv)
13030 `(,po (string-to-number (or ,gv ""))
13031 ,(string-to-number pv) ))))
13032 (t `(member ,tag tags-list)))
13033 mm (if minus (list 'not mm) mm)
13034 term rest)
13035 (push mm tagsmatcher))
13036 (push (if (> (length tagsmatcher) 1)
13037 (cons 'and tagsmatcher)
13038 (car tagsmatcher))
13039 orlist)
13040 (setq tagsmatcher nil))
13041 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13042 (setq tagsmatcher
13043 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13044 ;; Make the todo matcher
13045 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13046 (setq todomatcher t)
13047 (setq orterms (org-split-string todomatch "|") orlist nil)
13048 (while (setq term (pop orterms))
13049 (while (string-match re term)
13050 (setq minus (and (match-end 1)
13051 (equal (match-string 1 term) "-"))
13052 kwd (match-string 2 term)
13053 re-p (equal (string-to-char kwd) ?{)
13054 term (substring term (match-end 0))
13055 mm (if re-p
13056 `(string-match ,(substring kwd 1 -1) todo)
13057 (list 'equal 'todo kwd))
13058 mm (if minus (list 'not mm) mm))
13059 (push mm todomatcher))
13060 (push (if (> (length todomatcher) 1)
13061 (cons 'and todomatcher)
13062 (car todomatcher))
13063 orlist)
13064 (setq todomatcher nil))
13065 (setq todomatcher (if (> (length orlist) 1)
13066 (cons 'or orlist) (car orlist))))
13068 ;; Return the string and lisp forms of the matcher
13069 (setq matcher (if todomatcher
13070 (list 'and tagsmatcher todomatcher)
13071 tagsmatcher))
13072 (cons match0 matcher)))
13074 (defun org-op-to-function (op &optional stringp)
13075 "Turn an operator into the appropriate function."
13076 (setq op
13077 (cond
13078 ((equal op "<" ) '(< string< org-time<))
13079 ((equal op ">" ) '(> org-string> org-time>))
13080 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13081 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13082 ((member op '("=" "==")) '(= string= org-time=))
13083 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13084 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13086 (defun org<> (a b) (not (= a b)))
13087 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13088 (defun org-string>= (a b) (not (string< a b)))
13089 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13090 (defun org-string<> (a b) (not (string= a b)))
13091 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13092 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13093 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13094 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13095 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13096 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13097 (defun org-2ft (s)
13098 "Convert S to a floating point time.
13099 If S is already a number, just return it. If it is a string, parse
13100 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13101 (cond
13102 ((numberp s) s)
13103 ((stringp s)
13104 (condition-case nil
13105 (float-time (apply 'encode-time (org-parse-time-string s)))
13106 (error 0.)))
13107 (t 0.)))
13109 (defun org-time-today ()
13110 "Time in seconds today at 0:00.
13111 Returns the float number of seconds since the beginning of the
13112 epoch to the beginning of today (00:00)."
13113 (float-time (apply 'encode-time
13114 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13116 (defun org-matcher-time (s)
13117 "Interpret a time comparison value."
13118 (save-match-data
13119 (cond
13120 ((string= s "<now>") (float-time))
13121 ((string= s "<today>") (org-time-today))
13122 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13123 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13124 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
13125 (+ (org-time-today)
13126 (* (string-to-number (match-string 1 s))
13127 (cdr (assoc (match-string 2 s)
13128 '(("d" . 86400.0) ("w" . 604800.0)
13129 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13130 (t (org-2ft s)))))
13132 (defun org-match-any-p (re list)
13133 "Does re match any element of list?"
13134 (setq list (mapcar (lambda (x) (string-match re x)) list))
13135 (delq nil list))
13137 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13138 (defvar org-tags-overlay (make-overlay 1 1))
13139 (org-detach-overlay org-tags-overlay)
13141 (defun org-get-local-tags-at (&optional pos)
13142 "Get a list of tags defined in the current headline."
13143 (org-get-tags-at pos 'local))
13145 (defun org-get-local-tags ()
13146 "Get a list of tags defined in the current headline."
13147 (org-get-tags-at nil 'local))
13149 (defun org-get-tags-at (&optional pos local)
13150 "Get a list of all headline tags applicable at POS.
13151 POS defaults to point. If tags are inherited, the list contains
13152 the targets in the same sequence as the headlines appear, i.e.
13153 the tags of the current headline come last.
13154 When LOCAL is non-nil, only return tags from the current headline,
13155 ignore inherited ones."
13156 (interactive)
13157 (if (and org-trust-scanner-tags
13158 (or (not pos) (equal pos (point)))
13159 (not local))
13160 org-scanner-tags
13161 (let (tags ltags lastpos parent)
13162 (save-excursion
13163 (save-restriction
13164 (widen)
13165 (goto-char (or pos (point)))
13166 (save-match-data
13167 (catch 'done
13168 (condition-case nil
13169 (progn
13170 (org-back-to-heading t)
13171 (while (not (equal lastpos (point)))
13172 (setq lastpos (point))
13173 (when (looking-at
13174 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13175 (setq ltags (org-split-string
13176 (org-match-string-no-properties 1) ":"))
13177 (when parent
13178 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13179 (setq tags (append
13180 (if parent
13181 (org-remove-uninherited-tags ltags)
13182 ltags)
13183 tags)))
13184 (or org-use-tag-inheritance (throw 'done t))
13185 (if local (throw 'done t))
13186 (or (org-up-heading-safe) (error nil))
13187 (setq parent t)))
13188 (error nil)))))
13189 (if local
13190 tags
13191 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13193 (defun org-add-prop-inherited (s)
13194 (add-text-properties 0 (length s) '(inherited t) s)
13197 (defun org-toggle-tag (tag &optional onoff)
13198 "Toggle the tag TAG for the current line.
13199 If ONOFF is `on' or `off', don't toggle but set to this state."
13200 (let (res current)
13201 (save-excursion
13202 (org-back-to-heading t)
13203 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13204 (point-at-eol) t)
13205 (progn
13206 (setq current (match-string 1))
13207 (replace-match ""))
13208 (setq current ""))
13209 (setq current (nreverse (org-split-string current ":")))
13210 (cond
13211 ((eq onoff 'on)
13212 (setq res t)
13213 (or (member tag current) (push tag current)))
13214 ((eq onoff 'off)
13215 (or (not (member tag current)) (setq current (delete tag current))))
13216 (t (if (member tag current)
13217 (setq current (delete tag current))
13218 (setq res t)
13219 (push tag current))))
13220 (end-of-line 1)
13221 (if current
13222 (progn
13223 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13224 (org-set-tags nil t))
13225 (delete-horizontal-space))
13226 (run-hooks 'org-after-tags-change-hook))
13227 res))
13229 (defun org-align-tags-here (to-col)
13230 ;; Assumes that this is a headline
13231 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13232 (beginning-of-line 1)
13233 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13234 (< pos (match-beginning 2)))
13235 (progn
13236 (setq tags-l (- (match-end 2) (match-beginning 2)))
13237 (goto-char (match-beginning 1))
13238 (insert " ")
13239 (delete-region (point) (1+ (match-beginning 2)))
13240 (setq ncol (max (current-column)
13241 (1+ col)
13242 (if (> to-col 0)
13243 to-col
13244 (- (abs to-col) tags-l))))
13245 (setq p (point))
13246 (insert (make-string (- ncol (current-column)) ?\ ))
13247 (setq ncol (current-column))
13248 (when indent-tabs-mode (tabify p (point-at-eol)))
13249 (org-move-to-column (min ncol col) t))
13250 (goto-char pos))))
13252 (defun org-set-tags-command (&optional arg just-align)
13253 "Call the set-tags command for the current entry."
13254 (interactive "P")
13255 (if (org-on-heading-p)
13256 (org-set-tags arg just-align)
13257 (save-excursion
13258 (org-back-to-heading t)
13259 (org-set-tags arg just-align))))
13261 (defun org-set-tags-to (data)
13262 "Set the tags of the current entry to DATA, replacing the current tags.
13263 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13264 If DATA is nil or the empty string, any tags will be removed."
13265 (interactive "sTags: ")
13266 (setq data
13267 (cond
13268 ((eq data nil) "")
13269 ((equal data "") "")
13270 ((stringp data)
13271 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13272 ":"))
13273 ((listp data)
13274 (concat ":" (mapconcat 'identity data ":") ":"))
13275 (t nil)))
13276 (when data
13277 (save-excursion
13278 (org-back-to-heading t)
13279 (when (looking-at org-complex-heading-regexp)
13280 (if (match-end 5)
13281 (progn
13282 (goto-char (match-beginning 5))
13283 (insert data)
13284 (delete-region (point) (point-at-eol))
13285 (org-set-tags nil 'align))
13286 (goto-char (point-at-eol))
13287 (insert " " data)
13288 (org-set-tags nil 'align)))
13289 (beginning-of-line 1)
13290 (if (looking-at ".*?\\([ \t]+\\)$")
13291 (delete-region (match-beginning 1) (match-end 1))))))
13293 (defun org-align-all-tags ()
13294 "Align the tags i all headings."
13295 (interactive)
13296 (save-excursion
13297 (or (ignore-errors (org-back-to-heading t))
13298 (outline-next-heading))
13299 (if (org-on-heading-p)
13300 (org-set-tags t)
13301 (message "No headings"))))
13303 (defvar org-indent-indentation-per-level)
13304 (defun org-set-tags (&optional arg just-align)
13305 "Set the tags for the current headline.
13306 With prefix ARG, realign all tags in headings in the current buffer."
13307 (interactive "P")
13308 (let* ((re org-outline-regexp-bol)
13309 (current (org-get-tags-string))
13310 (col (current-column))
13311 (org-setting-tags t)
13312 table current-tags inherited-tags ; computed below when needed
13313 tags p0 c0 c1 rpl di tc level)
13314 (if arg
13315 (save-excursion
13316 (goto-char (point-min))
13317 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13318 (while (re-search-forward re nil t)
13319 (org-set-tags nil t)
13320 (end-of-line 1)))
13321 (message "All tags realigned to column %d" org-tags-column))
13322 (if just-align
13323 (setq tags current)
13324 ;; Get a new set of tags from the user
13325 (save-excursion
13326 (setq table (append org-tag-persistent-alist
13327 (or org-tag-alist (org-get-buffer-tags))
13328 (and
13329 org-complete-tags-always-offer-all-agenda-tags
13330 (org-global-tags-completion-table
13331 (org-agenda-files))))
13332 org-last-tags-completion-table table
13333 current-tags (org-split-string current ":")
13334 inherited-tags (nreverse
13335 (nthcdr (length current-tags)
13336 (nreverse (org-get-tags-at))))
13337 tags
13338 (if (or (eq t org-use-fast-tag-selection)
13339 (and org-use-fast-tag-selection
13340 (delq nil (mapcar 'cdr table))))
13341 (org-fast-tag-selection
13342 current-tags inherited-tags table
13343 (if org-fast-tag-selection-include-todo
13344 org-todo-key-alist))
13345 (let ((org-add-colon-after-tag-completion t))
13346 (org-trim
13347 (org-icompleting-read "Tags: "
13348 'org-tags-completion-function
13349 nil nil current 'org-tags-history))))))
13350 (while (string-match "[-+&]+" tags)
13351 ;; No boolean logic, just a list
13352 (setq tags (replace-match ":" t t tags))))
13354 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13356 (if org-tags-sort-function
13357 (setq tags (mapconcat 'identity
13358 (sort (org-split-string
13359 tags (org-re "[^[:alnum:]_@#%]+"))
13360 org-tags-sort-function) ":")))
13362 (if (string-match "\\`[\t ]*\\'" tags)
13363 (setq tags "")
13364 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13365 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13367 ;; Insert new tags at the correct column
13368 (beginning-of-line 1)
13369 (setq level (or (and (looking-at org-outline-regexp)
13370 (- (match-end 0) (point) 1))
13372 (cond
13373 ((and (equal current "") (equal tags "")))
13374 ((re-search-forward
13375 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13376 (point-at-eol) t)
13377 (if (equal tags "")
13378 (setq rpl "")
13379 (goto-char (match-beginning 0))
13380 (setq c0 (current-column)
13381 ;; compute offset for the case of org-indent-mode active
13382 di (if org-indent-mode
13383 (* (1- org-indent-indentation-per-level) (1- level))
13385 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13386 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13387 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13388 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13389 (replace-match rpl t t)
13390 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13391 tags)
13392 (t (error "Tags alignment failed")))
13393 (org-move-to-column col)
13394 (unless just-align
13395 (run-hooks 'org-after-tags-change-hook)))))
13397 (defun org-change-tag-in-region (beg end tag off)
13398 "Add or remove TAG for each entry in the region.
13399 This works in the agenda, and also in an org-mode buffer."
13400 (interactive
13401 (list (region-beginning) (region-end)
13402 (let ((org-last-tags-completion-table
13403 (if (eq major-mode 'org-mode)
13404 (org-get-buffer-tags)
13405 (org-global-tags-completion-table))))
13406 (org-icompleting-read
13407 "Tag: " 'org-tags-completion-function nil nil nil
13408 'org-tags-history))
13409 (progn
13410 (message "[s]et or [r]emove? ")
13411 (equal (read-char-exclusive) ?r))))
13412 (if (fboundp 'deactivate-mark) (deactivate-mark))
13413 (let ((agendap (equal major-mode 'org-agenda-mode))
13414 l1 l2 m buf pos newhead (cnt 0))
13415 (goto-char end)
13416 (setq l2 (1- (org-current-line)))
13417 (goto-char beg)
13418 (setq l1 (org-current-line))
13419 (loop for l from l1 to l2 do
13420 (org-goto-line l)
13421 (setq m (get-text-property (point) 'org-hd-marker))
13422 (when (or (and (eq major-mode 'org-mode) (org-on-heading-p))
13423 (and agendap m))
13424 (setq buf (if agendap (marker-buffer m) (current-buffer))
13425 pos (if agendap m (point)))
13426 (with-current-buffer buf
13427 (save-excursion
13428 (save-restriction
13429 (goto-char pos)
13430 (setq cnt (1+ cnt))
13431 (org-toggle-tag tag (if off 'off 'on))
13432 (setq newhead (org-get-heading)))))
13433 (and agendap (org-agenda-change-all-lines newhead m))))
13434 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13436 (defun org-tags-completion-function (string predicate &optional flag)
13437 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13438 (confirm (lambda (x) (stringp (car x)))))
13439 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13440 (setq s1 (match-string 1 string)
13441 s2 (match-string 2 string))
13442 (setq s1 "" s2 string))
13443 (cond
13444 ((eq flag nil)
13445 ;; try completion
13446 (setq rtn (try-completion s2 ctable confirm))
13447 (if (stringp rtn)
13448 (setq rtn
13449 (concat s1 s2 (substring rtn (length s2))
13450 (if (and org-add-colon-after-tag-completion
13451 (assoc rtn ctable))
13452 ":" ""))))
13453 rtn)
13454 ((eq flag t)
13455 ;; all-completions
13456 (all-completions s2 ctable confirm)
13458 ((eq flag 'lambda)
13459 ;; exact match?
13460 (assoc s2 ctable)))
13463 (defun org-fast-tag-insert (kwd tags face &optional end)
13464 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13465 (insert (format "%-12s" (concat kwd ":"))
13466 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13467 (or end "")))
13469 (defun org-fast-tag-show-exit (flag)
13470 (save-excursion
13471 (org-goto-line 3)
13472 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13473 (replace-match ""))
13474 (when flag
13475 (end-of-line 1)
13476 (org-move-to-column (- (window-width) 19) t)
13477 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13479 (defun org-set-current-tags-overlay (current prefix)
13480 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13481 (if (featurep 'xemacs)
13482 (org-overlay-display org-tags-overlay (concat prefix s)
13483 'secondary-selection)
13484 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13485 (org-overlay-display org-tags-overlay (concat prefix s)))))
13487 (defvar org-last-tag-selection-key nil)
13488 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13489 "Fast tag selection with single keys.
13490 CURRENT is the current list of tags in the headline, INHERITED is the
13491 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13492 possibly with grouping information. TODO-TABLE is a similar table with
13493 TODO keywords, should these have keys assigned to them.
13494 If the keys are nil, a-z are automatically assigned.
13495 Returns the new tags string, or nil to not change the current settings."
13496 (let* ((fulltable (append table todo-table))
13497 (maxlen (apply 'max (mapcar
13498 (lambda (x)
13499 (if (stringp (car x)) (string-width (car x)) 0))
13500 fulltable)))
13501 (buf (current-buffer))
13502 (expert (eq org-fast-tag-selection-single-key 'expert))
13503 (buffer-tags nil)
13504 (fwidth (+ maxlen 3 1 3))
13505 (ncol (/ (- (window-width) 4) fwidth))
13506 (i-face 'org-done)
13507 (c-face 'org-todo)
13508 tg cnt e c char c1 c2 ntable tbl rtn
13509 ov-start ov-end ov-prefix
13510 (exit-after-next org-fast-tag-selection-single-key)
13511 (done-keywords org-done-keywords)
13512 groups ingroup)
13513 (save-excursion
13514 (beginning-of-line 1)
13515 (if (looking-at
13516 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13517 (setq ov-start (match-beginning 1)
13518 ov-end (match-end 1)
13519 ov-prefix "")
13520 (setq ov-start (1- (point-at-eol))
13521 ov-end (1+ ov-start))
13522 (skip-chars-forward "^\n\r")
13523 (setq ov-prefix
13524 (concat
13525 (buffer-substring (1- (point)) (point))
13526 (if (> (current-column) org-tags-column)
13528 (make-string (- org-tags-column (current-column)) ?\ ))))))
13529 (move-overlay org-tags-overlay ov-start ov-end)
13530 (save-window-excursion
13531 (if expert
13532 (set-buffer (get-buffer-create " *Org tags*"))
13533 (delete-other-windows)
13534 (split-window-vertically)
13535 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13536 (erase-buffer)
13537 (org-set-local 'org-done-keywords done-keywords)
13538 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13539 (org-fast-tag-insert "Current" current c-face "\n\n")
13540 (org-fast-tag-show-exit exit-after-next)
13541 (org-set-current-tags-overlay current ov-prefix)
13542 (setq tbl fulltable char ?a cnt 0)
13543 (while (setq e (pop tbl))
13544 (cond
13545 ((equal (car e) :startgroup)
13546 (push '() groups) (setq ingroup t)
13547 (when (not (= cnt 0))
13548 (setq cnt 0)
13549 (insert "\n"))
13550 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13551 ((equal (car e) :endgroup)
13552 (setq ingroup nil cnt 0)
13553 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13554 ((equal e '(:newline))
13555 (when (not (= cnt 0))
13556 (setq cnt 0)
13557 (insert "\n")
13558 (setq e (car tbl))
13559 (while (equal (car tbl) '(:newline))
13560 (insert "\n")
13561 (setq tbl (cdr tbl)))))
13563 (setq tg (copy-sequence (car e)) c2 nil)
13564 (if (cdr e)
13565 (setq c (cdr e))
13566 ;; automatically assign a character.
13567 (setq c1 (string-to-char
13568 (downcase (substring
13569 tg (if (= (string-to-char tg) ?@) 1 0)))))
13570 (if (or (rassoc c1 ntable) (rassoc c1 table))
13571 (while (or (rassoc char ntable) (rassoc char table))
13572 (setq char (1+ char)))
13573 (setq c2 c1))
13574 (setq c (or c2 char)))
13575 (if ingroup (push tg (car groups)))
13576 (setq tg (org-add-props tg nil 'face
13577 (cond
13578 ((not (assoc tg table))
13579 (org-get-todo-face tg))
13580 ((member tg current) c-face)
13581 ((member tg inherited) i-face)
13582 (t nil))))
13583 (if (and (= cnt 0) (not ingroup)) (insert " "))
13584 (insert "[" c "] " tg (make-string
13585 (- fwidth 4 (length tg)) ?\ ))
13586 (push (cons tg c) ntable)
13587 (when (= (setq cnt (1+ cnt)) ncol)
13588 (insert "\n")
13589 (if ingroup (insert " "))
13590 (setq cnt 0)))))
13591 (setq ntable (nreverse ntable))
13592 (insert "\n")
13593 (goto-char (point-min))
13594 (if (not expert) (org-fit-window-to-buffer))
13595 (setq rtn
13596 (catch 'exit
13597 (while t
13598 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13599 (if (not groups) "no " "")
13600 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13601 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13602 (setq org-last-tag-selection-key c)
13603 (cond
13604 ((= c ?\r) (throw 'exit t))
13605 ((= c ?!)
13606 (setq groups (not groups))
13607 (goto-char (point-min))
13608 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13609 ((= c ?\C-c)
13610 (if (not expert)
13611 (org-fast-tag-show-exit
13612 (setq exit-after-next (not exit-after-next)))
13613 (setq expert nil)
13614 (delete-other-windows)
13615 (set-window-buffer (split-window-vertically) " *Org tags*")
13616 (org-switch-to-buffer-other-window " *Org tags*")
13617 (org-fit-window-to-buffer)))
13618 ((or (= c ?\C-g)
13619 (and (= c ?q) (not (rassoc c ntable))))
13620 (org-detach-overlay org-tags-overlay)
13621 (setq quit-flag t))
13622 ((= c ?\ )
13623 (setq current nil)
13624 (if exit-after-next (setq exit-after-next 'now)))
13625 ((= c ?\t)
13626 (condition-case nil
13627 (setq tg (org-icompleting-read
13628 "Tag: "
13629 (or buffer-tags
13630 (with-current-buffer buf
13631 (org-get-buffer-tags)))))
13632 (quit (setq tg "")))
13633 (when (string-match "\\S-" tg)
13634 (add-to-list 'buffer-tags (list tg))
13635 (if (member tg current)
13636 (setq current (delete tg current))
13637 (push tg current)))
13638 (if exit-after-next (setq exit-after-next 'now)))
13639 ((setq e (rassoc c todo-table) tg (car e))
13640 (with-current-buffer buf
13641 (save-excursion (org-todo tg)))
13642 (if exit-after-next (setq exit-after-next 'now)))
13643 ((setq e (rassoc c ntable) tg (car e))
13644 (if (member tg current)
13645 (setq current (delete tg current))
13646 (loop for g in groups do
13647 (if (member tg g)
13648 (mapc (lambda (x)
13649 (setq current (delete x current)))
13650 g)))
13651 (push tg current))
13652 (if exit-after-next (setq exit-after-next 'now))))
13654 ;; Create a sorted list
13655 (setq current
13656 (sort current
13657 (lambda (a b)
13658 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13659 (if (eq exit-after-next 'now) (throw 'exit t))
13660 (goto-char (point-min))
13661 (beginning-of-line 2)
13662 (delete-region (point) (point-at-eol))
13663 (org-fast-tag-insert "Current" current c-face)
13664 (org-set-current-tags-overlay current ov-prefix)
13665 (while (re-search-forward
13666 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13667 (setq tg (match-string 1))
13668 (add-text-properties
13669 (match-beginning 1) (match-end 1)
13670 (list 'face
13671 (cond
13672 ((member tg current) c-face)
13673 ((member tg inherited) i-face)
13674 (t (get-text-property (match-beginning 1) 'face))))))
13675 (goto-char (point-min)))))
13676 (org-detach-overlay org-tags-overlay)
13677 (if rtn
13678 (mapconcat 'identity current ":")
13679 nil))))
13681 (defun org-get-tags-string ()
13682 "Get the TAGS string in the current headline."
13683 (unless (org-on-heading-p t)
13684 (error "Not on a heading"))
13685 (save-excursion
13686 (beginning-of-line 1)
13687 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13688 (org-match-string-no-properties 1)
13689 "")))
13691 (defun org-get-tags ()
13692 "Get the list of tags specified in the current headline."
13693 (org-split-string (org-get-tags-string) ":"))
13695 (defun org-get-buffer-tags ()
13696 "Get a table of all tags used in the buffer, for completion."
13697 (let (tags)
13698 (save-excursion
13699 (goto-char (point-min))
13700 (while (re-search-forward
13701 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13702 (when (equal (char-after (point-at-bol 0)) ?*)
13703 (mapc (lambda (x) (add-to-list 'tags x))
13704 (org-split-string (org-match-string-no-properties 1) ":")))))
13705 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13706 (mapcar 'list tags)))
13708 ;;;; The mapping API
13710 ;;;###autoload
13711 (defun org-map-entries (func &optional match scope &rest skip)
13712 "Call FUNC at each headline selected by MATCH in SCOPE.
13714 FUNC is a function or a lisp form. The function will be called without
13715 arguments, with the cursor positioned at the beginning of the headline.
13716 The return values of all calls to the function will be collected and
13717 returned as a list.
13719 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13720 does not need to preserve point. After evaluation, the cursor will be
13721 moved to the end of the line (presumably of the headline of the
13722 processed entry) and search continues from there. Under some
13723 circumstances, this may not produce the wanted results. For example,
13724 if you have removed (e.g. archived) the current (sub)tree it could
13725 mean that the next entry will be skipped entirely. In such cases, you
13726 can specify the position from where search should continue by making
13727 FUNC set the variable `org-map-continue-from' to the desired buffer
13728 position.
13730 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13731 Only headlines that are matched by this query will be considered during
13732 the iteration. When MATCH is nil or t, all headlines will be
13733 visited by the iteration.
13735 SCOPE determines the scope of this command. It can be any of:
13737 nil The current buffer, respecting the restriction if any
13738 tree The subtree started with the entry at point
13739 region The entries within the active region, if any
13740 region-start-level
13741 The entries within the active region, but only those at
13742 the same level than the first one.
13743 file The current buffer, without restriction
13744 file-with-archives
13745 The current buffer, and any archives associated with it
13746 agenda All agenda files
13747 agenda-with-archives
13748 All agenda files with any archive files associated with them
13749 \(file1 file2 ...)
13750 If this is a list, all files in the list will be scanned
13752 The remaining args are treated as settings for the skipping facilities of
13753 the scanner. The following items can be given here:
13755 archive skip trees with the archive tag.
13756 comment skip trees with the COMMENT keyword
13757 function or Emacs Lisp form:
13758 will be used as value for `org-agenda-skip-function', so whenever
13759 the function returns t, FUNC will not be called for that
13760 entry and search will continue from the point where the
13761 function leaves it.
13763 If your function needs to retrieve the tags including inherited tags
13764 at the *current* entry, you can use the value of the variable
13765 `org-scanner-tags' which will be much faster than getting the value
13766 with `org-get-tags-at'. If your function gets properties with
13767 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13768 to t around the call to `org-entry-properties' to get the same speedup.
13769 Note that if your function moves around to retrieve tags and properties at
13770 a *different* entry, you cannot use these techniques."
13771 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
13772 (not (org-region-active-p)))
13773 (let* ((org-agenda-archives-mode nil) ; just to make sure
13774 (org-agenda-skip-archived-trees (memq 'archive skip))
13775 (org-agenda-skip-comment-trees (memq 'comment skip))
13776 (org-agenda-skip-function
13777 (car (org-delete-all '(comment archive) skip)))
13778 (org-tags-match-list-sublevels t)
13779 (start-level (eq scope 'region-start-level))
13780 matcher file res
13781 org-todo-keywords-for-agenda
13782 org-done-keywords-for-agenda
13783 org-todo-keyword-alist-for-agenda
13784 org-drawers-for-agenda
13785 org-tag-alist-for-agenda)
13787 (cond
13788 ((eq match t) (setq matcher t))
13789 ((eq match nil) (setq matcher t))
13790 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13792 (save-excursion
13793 (save-restriction
13794 (cond ((eq scope 'tree)
13795 (org-back-to-heading t)
13796 (org-narrow-to-subtree)
13797 (setq scope nil))
13798 ((and (or (eq scope 'region) (eq scope 'region-start-level))
13799 (org-region-active-p))
13800 ;; If needed, set start-level to a string like "2"
13801 (when start-level
13802 (save-excursion
13803 (goto-char (region-beginning))
13804 (unless (org-at-heading-p) (outline-next-heading))
13805 (setq start-level (org-current-level))))
13806 (narrow-to-region (region-beginning)
13807 (save-excursion
13808 (goto-char (region-end))
13809 (unless (and (bolp) (org-at-heading-p))
13810 (outline-next-heading))
13811 (point)))
13812 (setq scope nil)))
13814 (if (not scope)
13815 (progn
13816 (org-prepare-agenda-buffers
13817 (list (buffer-file-name (current-buffer))))
13818 (setq res (org-scan-tags func matcher nil start-level)))
13819 ;; Get the right scope
13820 (cond
13821 ((and scope (listp scope) (symbolp (car scope)))
13822 (setq scope (eval scope)))
13823 ((eq scope 'agenda)
13824 (setq scope (org-agenda-files t)))
13825 ((eq scope 'agenda-with-archives)
13826 (setq scope (org-agenda-files t))
13827 (setq scope (org-add-archive-files scope)))
13828 ((eq scope 'file)
13829 (setq scope (list (buffer-file-name))))
13830 ((eq scope 'file-with-archives)
13831 (setq scope (org-add-archive-files (list (buffer-file-name))))))
13832 (org-prepare-agenda-buffers scope)
13833 (while (setq file (pop scope))
13834 (with-current-buffer (org-find-base-buffer-visiting file)
13835 (save-excursion
13836 (save-restriction
13837 (widen)
13838 (goto-char (point-min))
13839 (setq res (append res (org-scan-tags func matcher))))))))))
13840 res)))
13842 ;;;; Properties
13844 ;;; Setting and retrieving properties
13846 (defconst org-special-properties
13847 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
13848 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM")
13849 "The special properties valid in Org-mode.
13851 These are properties that are not defined in the property drawer,
13852 but in some other way.")
13854 (defconst org-default-properties
13855 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
13856 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
13857 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
13858 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
13859 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
13860 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
13861 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
13862 "Some properties that are used by Org-mode for various purposes.
13863 Being in this list makes sure that they are offered for completion.")
13865 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
13866 "Regular expression matching the first line of a property drawer.")
13868 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
13869 "Regular expression matching the last line of a property drawer.")
13871 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
13872 "Regular expression matching the first line of a property drawer.")
13874 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
13875 "Regular expression matching the first line of a property drawer.")
13877 (defconst org-property-drawer-re
13878 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
13879 org-property-end-re "\\)\n?")
13880 "Matches an entire property drawer.")
13882 (defconst org-clock-drawer-re
13883 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
13884 org-property-end-re "\\)\n?")
13885 "Matches an entire clock drawer.")
13887 (defsubst org-re-property (property)
13888 "Return a regexp matching PROPERTY.
13889 Match group 1 will be set to the value "
13890 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
13892 (defun org-property-action ()
13893 "Do an action on properties."
13894 (interactive)
13895 (let (c)
13896 (org-at-property-p)
13897 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
13898 (setq c (read-char-exclusive))
13899 (cond
13900 ((equal c ?s)
13901 (call-interactively 'org-set-property))
13902 ((equal c ?d)
13903 (call-interactively 'org-delete-property))
13904 ((equal c ?D)
13905 (call-interactively 'org-delete-property-globally))
13906 ((equal c ?c)
13907 (call-interactively 'org-compute-property-at-point))
13908 (t (error "No such property action %c" c)))))
13910 (defun org-set-effort (&optional value)
13911 "Set the effort property of the current entry.
13912 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
13913 allowed value."
13914 (interactive "P")
13915 (if (equal value 0) (setq value 10))
13916 (let* ((completion-ignore-case t)
13917 (prop org-effort-property)
13918 (cur (org-entry-get nil prop))
13919 (allowed (org-property-get-allowed-values nil prop 'table))
13920 (existing (mapcar 'list (org-property-values prop)))
13922 (val (cond
13923 ((stringp value) value)
13924 ((and allowed (integerp value))
13925 (or (car (nth (1- value) allowed))
13926 (car (org-last allowed))))
13927 (allowed
13928 (message "Select 1-9,0, [RET%s]: %s"
13929 (if cur (concat "=" cur) "")
13930 (mapconcat 'car allowed " "))
13931 (setq rpl (read-char-exclusive))
13932 (if (equal rpl ?\r)
13934 (setq rpl (- rpl ?0))
13935 (if (equal rpl 0) (setq rpl 10))
13936 (if (and (> rpl 0) (<= rpl (length allowed)))
13937 (car (nth (1- rpl) allowed))
13938 (org-completing-read "Effort: " allowed nil))))
13940 (let (org-completion-use-ido org-completion-use-iswitchb)
13941 (org-completing-read
13942 (concat "Effort " (if (and cur (string-match "\\S-" cur))
13943 (concat "[" cur "]") "")
13944 ": ")
13945 existing nil nil "" nil cur))))))
13946 (unless (equal (org-entry-get nil prop) val)
13947 (org-entry-put nil prop val))
13948 (message "%s is now %s" prop val)))
13950 (defun org-at-property-p ()
13951 "Is cursor inside a property drawer?"
13952 (save-excursion
13953 (beginning-of-line 1)
13954 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
13955 (save-match-data ;; Used by calling procedures
13956 (let ((p (point))
13957 (range (unless (org-before-first-heading-p)
13958 (org-get-property-block))))
13959 (and range (<= (car range) p) (< p (cdr range))))))))
13961 (defun org-get-property-block (&optional beg end force)
13962 "Return the (beg . end) range of the body of the property drawer.
13963 BEG and END can be beginning and end of subtree, if not given
13964 they will be found.
13965 If the drawer does not exist and FORCE is non-nil, create the drawer."
13966 (catch 'exit
13967 (save-excursion
13968 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
13969 (end (or end (progn (outline-next-heading) (point)))))
13970 (goto-char beg)
13971 (if (re-search-forward org-property-start-re end t)
13972 (setq beg (1+ (match-end 0)))
13973 (if force
13974 (save-excursion
13975 (org-insert-property-drawer)
13976 (setq end (progn (outline-next-heading) (point))))
13977 (throw 'exit nil))
13978 (goto-char beg)
13979 (if (re-search-forward org-property-start-re end t)
13980 (setq beg (1+ (match-end 0)))))
13981 (if (re-search-forward org-property-end-re end t)
13982 (setq end (match-beginning 0))
13983 (or force (throw 'exit nil))
13984 (goto-char beg)
13985 (setq end beg)
13986 (org-indent-line-function)
13987 (insert ":END:\n"))
13988 (cons beg end)))))
13990 (defun org-entry-properties (&optional pom which specific)
13991 "Get all properties of the entry at point-or-marker POM.
13992 This includes the TODO keyword, the tags, time strings for deadline,
13993 scheduled, and clocking, and any additional properties defined in the
13994 entry. The return value is an alist, keys may occur multiple times
13995 if the property key was used several times.
13996 POM may also be nil, in which case the current entry is used.
13997 If WHICH is nil or `all', get all properties. If WHICH is
13998 `special' or `standard', only get that subclass. If WHICH
13999 is a string only get exactly this property. SPECIFIC can be a string, the
14000 specific property we are interested in. Specifying it can speed
14001 things up because then unnecessary parsing is avoided."
14002 (setq which (or which 'all))
14003 (org-with-point-at pom
14004 (let ((clockstr (substring org-clock-string 0 -1))
14005 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14006 (case-fold-search nil)
14007 beg end range props sum-props key key1 value string clocksum)
14008 (save-excursion
14009 (when (condition-case nil
14010 (and (eq major-mode 'org-mode) (org-back-to-heading t))
14011 (error nil))
14012 (setq beg (point))
14013 (setq sum-props (get-text-property (point) 'org-summaries))
14014 (setq clocksum (get-text-property (point) :org-clock-minutes))
14015 (outline-next-heading)
14016 (setq end (point))
14017 (when (memq which '(all special))
14018 ;; Get the special properties, like TODO and tags
14019 (goto-char beg)
14020 (when (and (or (not specific) (string= specific "TODO"))
14021 (looking-at org-todo-line-regexp) (match-end 2))
14022 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14023 (when (and (or (not specific) (string= specific "PRIORITY"))
14024 (looking-at org-priority-regexp))
14025 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14026 (when (or (not specific) (string= specific "FILE"))
14027 (push (cons "FILE" buffer-file-name) props))
14028 (when (and (or (not specific) (string= specific "TAGS"))
14029 (setq value (org-get-tags-string))
14030 (string-match "\\S-" value))
14031 (push (cons "TAGS" value) props))
14032 (when (and (or (not specific) (string= specific "ALLTAGS"))
14033 (setq value (org-get-tags-at)))
14034 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14035 ":"))
14036 props))
14037 (when (or (not specific) (string= specific "BLOCKED"))
14038 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14039 (when (or (not specific)
14040 (member specific
14041 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14042 "TIMESTAMP" "TIMESTAMP_IA")))
14043 (catch 'match
14044 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14045 (setq key (if (match-end 1)
14046 (substring (org-match-string-no-properties 1)
14047 0 -1))
14048 string (if (equal key clockstr)
14049 (org-no-properties
14050 (org-trim
14051 (buffer-substring
14052 (match-beginning 3) (goto-char
14053 (point-at-eol)))))
14054 (substring (org-match-string-no-properties 3)
14055 1 -1)))
14056 ;; Get the correct property name from the key. This is
14057 ;; necessary if the user has configured time keywords.
14058 (setq key1 (concat key ":"))
14059 (cond
14060 ((not key)
14061 (setq key
14062 (if (= (char-after (match-beginning 3)) ?\[)
14063 "TIMESTAMP_IA" "TIMESTAMP")))
14064 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14065 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14066 ((equal key1 org-closed-string) (setq key "CLOSED"))
14067 ((equal key1 org-clock-string) (setq key "CLOCK")))
14068 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14069 (progn
14070 (push (cons key string) props)
14071 ;; no need to search further if match is found
14072 (throw 'match t))
14073 (when (or (equal key "CLOCK") (not (assoc key props)))
14074 (push (cons key string) props))))))
14077 (when (memq which '(all standard))
14078 ;; Get the standard properties, like :PROP: ...
14079 (setq range (org-get-property-block beg end))
14080 (when range
14081 (goto-char (car range))
14082 (while (re-search-forward
14083 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14084 (cdr range) t)
14085 (setq key (org-match-string-no-properties 1)
14086 value (org-trim (or (org-match-string-no-properties 2) "")))
14087 (unless (member key excluded)
14088 (push (cons key (or value "")) props)))))
14089 (if clocksum
14090 (push (cons "CLOCKSUM"
14091 (org-columns-number-to-string (/ (float clocksum) 60.)
14092 'add_times))
14093 props))
14094 (unless (assoc "CATEGORY" props)
14095 (push (cons "CATEGORY" (org-get-category)) props))
14096 (append sum-props (nreverse props)))))))
14098 (defun org-entry-get (pom property &optional inherit literal-nil)
14099 "Get value of PROPERTY for entry at point-or-marker POM.
14100 If INHERIT is non-nil and the entry does not have the property,
14101 then also check higher levels of the hierarchy.
14102 If INHERIT is the symbol `selective', use inheritance only if the setting
14103 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14104 If the property is present but empty, the return value is the empty string.
14105 If the property is not present at all, nil is returned.
14107 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14108 do not interpret it as the list atom nil. This is used for inheritance
14109 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14110 (org-with-point-at pom
14111 (if (and inherit (if (eq inherit 'selective)
14112 (org-property-inherit-p property)
14114 (org-entry-get-with-inheritance property literal-nil)
14115 (if (member property org-special-properties)
14116 ;; We need a special property. Use `org-entry-properties' to
14117 ;; retrieve it, but specify the wanted property
14118 (cdr (assoc property (org-entry-properties nil 'special property)))
14119 (let ((range (unless (org-before-first-heading-p)
14120 (org-get-property-block))))
14121 (when (and range (goto-char (car range)))
14122 ((lambda (val) (when val (if literal-nil val (org-not-nil val))))
14123 (cond
14124 ((re-search-forward
14125 (org-re-property property) (cdr range) t)
14126 (if (match-end 1) (org-match-string-no-properties 1) ""))
14127 ((re-search-forward
14128 (org-re-property (concat property "+")) (cdr range) t)
14129 (cdr (assoc
14130 property
14131 (org-update-property-plist
14132 (concat property "+")
14133 (if (match-end 1) (org-match-string-no-properties 1) "")
14134 (list (or (assoc property org-file-properties)
14135 (assoc property org-global-properties)
14136 (assoc property org-global-properties-fixed)
14137 ))))))))))))))
14139 (defun org-property-or-variable-value (var &optional inherit)
14140 "Check if there is a property fixing the value of VAR.
14141 If yes, return this value. If not, return the current value of the variable."
14142 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14143 (if (and prop (stringp prop) (string-match "\\S-" prop))
14144 (read prop)
14145 (symbol-value var))))
14147 (defun org-entry-delete (pom property)
14148 "Delete the property PROPERTY from entry at point-or-marker POM."
14149 (org-with-point-at pom
14150 (if (member property org-special-properties)
14151 nil ; cannot delete these properties.
14152 (let ((range (org-get-property-block)))
14153 (if (and range
14154 (goto-char (car range))
14155 (re-search-forward
14156 (org-re-property property)
14157 (cdr range) t))
14158 (progn
14159 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14161 nil)))))
14163 ;; Multi-values properties are properties that contain multiple values
14164 ;; These values are assumed to be single words, separated by whitespace.
14165 (defun org-entry-add-to-multivalued-property (pom property value)
14166 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14167 (let* ((old (org-entry-get pom property))
14168 (values (and old (org-split-string old "[ \t]"))))
14169 (setq value (org-entry-protect-space value))
14170 (unless (member value values)
14171 (setq values (cons value values))
14172 (org-entry-put pom property
14173 (mapconcat 'identity values " ")))))
14175 (defun org-entry-remove-from-multivalued-property (pom property value)
14176 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14177 (let* ((old (org-entry-get pom property))
14178 (values (and old (org-split-string old "[ \t]"))))
14179 (setq value (org-entry-protect-space value))
14180 (when (member value values)
14181 (setq values (delete value values))
14182 (org-entry-put pom property
14183 (mapconcat 'identity values " ")))))
14185 (defun org-entry-member-in-multivalued-property (pom property value)
14186 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14187 (let* ((old (org-entry-get pom property))
14188 (values (and old (org-split-string old "[ \t]"))))
14189 (setq value (org-entry-protect-space value))
14190 (member value values)))
14192 (defun org-entry-get-multivalued-property (pom property)
14193 "Return a list of values in a multivalued property."
14194 (let* ((value (org-entry-get pom property))
14195 (values (and value (org-split-string value "[ \t]"))))
14196 (mapcar 'org-entry-restore-space values)))
14198 (defun org-entry-put-multivalued-property (pom property &rest values)
14199 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14200 VALUES should be a list of strings. Spaces will be protected."
14201 (org-entry-put pom property
14202 (mapconcat 'org-entry-protect-space values " "))
14203 (let* ((value (org-entry-get pom property))
14204 (values (and value (org-split-string value "[ \t]"))))
14205 (mapcar 'org-entry-restore-space values)))
14207 (defun org-entry-protect-space (s)
14208 "Protect spaces and newline in string S."
14209 (while (string-match " " s)
14210 (setq s (replace-match "%20" t t s)))
14211 (while (string-match "\n" s)
14212 (setq s (replace-match "%0A" t t s)))
14215 (defun org-entry-restore-space (s)
14216 "Restore spaces and newline in string S."
14217 (while (string-match "%20" s)
14218 (setq s (replace-match " " t t s)))
14219 (while (string-match "%0A" s)
14220 (setq s (replace-match "\n" t t s)))
14223 (defvar org-entry-property-inherited-from (make-marker)
14224 "Marker pointing to the entry from where a property was inherited.
14225 Each call to `org-entry-get-with-inheritance' will set this marker to the
14226 location of the entry where the inheritance search matched. If there was
14227 no match, the marker will point nowhere.
14228 Note that also `org-entry-get' calls this function, if the INHERIT flag
14229 is set.")
14231 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14232 "Get entry property, and search higher levels if not present.
14233 The search will stop at the first ancestor which has the property defined.
14234 If the value found is \"nil\", return nil to show that the property
14235 should be considered as undefined (this is the meaning of nil here).
14236 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14237 (move-marker org-entry-property-inherited-from nil)
14238 (let (tmp)
14239 (unless (org-before-first-heading-p)
14240 (save-excursion
14241 (save-restriction
14242 (widen)
14243 (catch 'ex
14244 (while t
14245 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14246 (org-back-to-heading t)
14247 (move-marker org-entry-property-inherited-from (point))
14248 (throw 'ex tmp))
14249 (or (org-up-heading-safe) (throw 'ex nil)))))))
14250 (setq tmp (or tmp
14251 (cdr (assoc property org-file-properties))
14252 (cdr (assoc property org-global-properties))
14253 (cdr (assoc property org-global-properties-fixed))))
14254 (if literal-nil tmp (org-not-nil tmp))))
14256 (defvar org-property-changed-functions nil
14257 "Hook called when the value of a property has changed.
14258 Each hook function should accept two arguments, the name of the property
14259 and the new value.")
14261 (defun org-entry-put (pom property value)
14262 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14263 (org-with-point-at pom
14264 (org-back-to-heading t)
14265 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14266 range)
14267 (cond
14268 ((equal property "TODO")
14269 (when (and (stringp value) (string-match "\\S-" value)
14270 (not (member value org-todo-keywords-1)))
14271 (error "\"%s\" is not a valid TODO state" value))
14272 (if (or (not value)
14273 (not (string-match "\\S-" value)))
14274 (setq value 'none))
14275 (org-todo value)
14276 (org-set-tags nil 'align))
14277 ((equal property "PRIORITY")
14278 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14279 (string-to-char value) ?\ ))
14280 (org-set-tags nil 'align))
14281 ((equal property "SCHEDULED")
14282 (if (re-search-forward org-scheduled-time-regexp end t)
14283 (cond
14284 ((eq value 'earlier) (org-timestamp-change -1 'day))
14285 ((eq value 'later) (org-timestamp-change 1 'day))
14286 (t (call-interactively 'org-schedule)))
14287 (call-interactively 'org-schedule)))
14288 ((equal property "DEADLINE")
14289 (if (re-search-forward org-deadline-time-regexp end t)
14290 (cond
14291 ((eq value 'earlier) (org-timestamp-change -1 'day))
14292 ((eq value 'later) (org-timestamp-change 1 'day))
14293 (t (call-interactively 'org-deadline)))
14294 (call-interactively 'org-deadline)))
14295 ((member property org-special-properties)
14296 (error "The %s property can not yet be set with `org-entry-put'"
14297 property))
14298 (t ; a non-special property
14299 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14300 (setq range (org-get-property-block beg end 'force))
14301 (goto-char (car range))
14302 (if (re-search-forward
14303 (org-re-property property) (cdr range) t)
14304 (progn
14305 (delete-region (match-beginning 0) (match-end 0))
14306 (goto-char (match-beginning 0)))
14307 (goto-char (cdr range))
14308 (insert "\n")
14309 (backward-char 1)
14310 (org-indent-line-function))
14311 (insert ":" property ":")
14312 (and value (insert " " value))
14313 (org-indent-line-function)))))
14314 (run-hook-with-args 'org-property-changed-functions property value)))
14316 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14317 "Get all property keys in the current buffer.
14318 With INCLUDE-SPECIALS, also list the special properties that reflect things
14319 like tags and TODO state.
14320 With INCLUDE-DEFAULTS, also include properties that has special meaning
14321 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14322 and others.
14323 With INCLUDE-COLUMNS, also include property names given in COLUMN
14324 formats in the current buffer."
14325 (let (rtn range cfmt s p)
14326 (save-excursion
14327 (save-restriction
14328 (widen)
14329 (goto-char (point-min))
14330 (while (re-search-forward org-property-start-re nil t)
14331 (setq range (org-get-property-block))
14332 (goto-char (car range))
14333 (while (re-search-forward
14334 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14335 (cdr range) t)
14336 (add-to-list 'rtn (org-match-string-no-properties 1)))
14337 (outline-next-heading))))
14339 (when include-specials
14340 (setq rtn (append org-special-properties rtn)))
14342 (when include-defaults
14343 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14344 (add-to-list 'rtn org-effort-property))
14346 (when include-columns
14347 (save-excursion
14348 (save-restriction
14349 (widen)
14350 (goto-char (point-min))
14351 (while (re-search-forward
14352 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14353 nil t)
14354 (setq cfmt (match-string 2) s 0)
14355 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14356 cfmt s)
14357 (setq s (match-end 0)
14358 p (match-string 1 cfmt))
14359 (unless (or (equal p "ITEM")
14360 (member p org-special-properties))
14361 (add-to-list 'rtn (match-string 1 cfmt))))))))
14363 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14365 (defun org-property-values (key)
14366 "Return a list of all values of property KEY in the current buffer."
14367 (save-excursion
14368 (save-restriction
14369 (widen)
14370 (goto-char (point-min))
14371 (let ((re (org-re-property key))
14372 values)
14373 (while (re-search-forward re nil t)
14374 (add-to-list 'values (org-trim (match-string 1))))
14375 (delete "" values)))))
14377 (defun org-insert-property-drawer ()
14378 "Insert a property drawer into the current entry."
14379 (interactive)
14380 (org-back-to-heading t)
14381 (looking-at org-outline-regexp)
14382 (let ((indent (if org-adapt-indentation
14383 (- (match-end 0)(match-beginning 0))
14385 (beg (point))
14386 (re (concat "^[ \t]*" org-keyword-time-regexp))
14387 end hiddenp)
14388 (outline-next-heading)
14389 (setq end (point))
14390 (goto-char beg)
14391 (while (re-search-forward re end t))
14392 (setq hiddenp (outline-invisible-p))
14393 (end-of-line 1)
14394 (and (equal (char-after) ?\n) (forward-char 1))
14395 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14396 (if (member (match-string 1) '("CLOCK:" ":END:"))
14397 ;; just skip this line
14398 (beginning-of-line 2)
14399 ;; Drawer start, find the end
14400 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14401 (beginning-of-line 1)))
14402 (org-skip-over-state-notes)
14403 (skip-chars-backward " \t\n\r")
14404 (if (eq (char-before) ?*) (forward-char 1))
14405 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14406 (beginning-of-line 0)
14407 (org-indent-to-column indent)
14408 (beginning-of-line 2)
14409 (org-indent-to-column indent)
14410 (beginning-of-line 0)
14411 (if hiddenp
14412 (save-excursion
14413 (org-back-to-heading t)
14414 (hide-entry))
14415 (org-flag-drawer t))))
14417 (defvar org-property-set-functions-alist nil
14418 "Property set function alist.
14419 Each entry should have the following format:
14421 (PROPERTY . READ-FUNCTION)
14423 The read function will be called with the same argument as
14424 `org-completing-read'.")
14426 (defun org-set-property-function (property)
14427 "Get the function that should be used to set PROPERTY.
14428 This is computed according to `org-property-set-functions-alist'."
14429 (or (cdr (assoc property org-property-set-functions-alist))
14430 'org-completing-read))
14432 (defun org-read-property-value (property)
14433 "Read PROPERTY value from user."
14434 (let* ((completion-ignore-case t)
14435 (allowed (org-property-get-allowed-values nil property 'table))
14436 (cur (org-entry-get nil property))
14437 (prompt (concat property " value"
14438 (if (and cur (string-match "\\S-" cur))
14439 (concat " [" cur "]") "") ": "))
14440 (set-function (org-set-property-function property))
14441 (val (if allowed
14442 (funcall set-function prompt allowed nil
14443 (not (get-text-property 0 'org-unrestricted
14444 (caar allowed))))
14445 (let (org-completion-use-ido org-completion-use-iswitchb)
14446 (funcall set-function prompt
14447 (mapcar 'list (org-property-values property))
14448 nil nil "" nil cur)))))
14449 (if (equal val "")
14451 val)))
14453 (defvar org-last-set-property nil)
14454 (defun org-read-property-name ()
14455 "Read a property name."
14456 (let* ((completion-ignore-case t)
14457 (keys (org-buffer-property-keys nil t t))
14458 (default-prop (or (save-excursion
14459 (save-match-data
14460 (beginning-of-line)
14461 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14462 (null (string= (match-string 1) "END"))
14463 (match-string 1))))
14464 org-last-set-property))
14465 (property (org-icompleting-read
14466 (concat "Property"
14467 (if default-prop (concat " [" default-prop "]") "")
14468 ": ")
14469 (mapcar 'list keys)
14470 nil nil nil nil
14471 default-prop
14473 (if (member property keys)
14474 property
14475 (or (cdr (assoc (downcase property)
14476 (mapcar (lambda (x) (cons (downcase x) x))
14477 keys)))
14478 property))))
14480 (defun org-set-property (property value)
14481 "In the current entry, set PROPERTY to VALUE.
14482 When called interactively, this will prompt for a property name, offering
14483 completion on existing and default properties. And then it will prompt
14484 for a value, offering completion either on allowed values (via an inherited
14485 xxx_ALL property) or on existing values in other instances of this property
14486 in the current file."
14487 (interactive (list nil nil))
14488 (let* ((property (or property (org-read-property-name)))
14489 (value (or value (org-read-property-value property)))
14490 (fn (assoc property org-properties-postprocess-alist)))
14491 (setq org-last-set-property property)
14492 ;; Possibly postprocess the inserted value:
14493 (when fn (setq value (funcall (cadr fn) value)))
14494 (unless (equal (org-entry-get nil property) value)
14495 (org-entry-put nil property value))))
14497 (defun org-delete-property (property)
14498 "In the current entry, delete PROPERTY."
14499 (interactive
14500 (let* ((completion-ignore-case t)
14501 (prop (org-icompleting-read "Property: "
14502 (org-entry-properties nil 'standard))))
14503 (list prop)))
14504 (message "Property %s %s" property
14505 (if (org-entry-delete nil property)
14506 "deleted"
14507 "was not present in the entry")))
14509 (defun org-delete-property-globally (property)
14510 "Remove PROPERTY globally, from all entries."
14511 (interactive
14512 (let* ((completion-ignore-case t)
14513 (prop (org-icompleting-read
14514 "Globally remove property: "
14515 (mapcar 'list (org-buffer-property-keys)))))
14516 (list prop)))
14517 (save-excursion
14518 (save-restriction
14519 (widen)
14520 (goto-char (point-min))
14521 (let ((cnt 0))
14522 (while (re-search-forward
14523 (org-re-property property)
14524 nil t)
14525 (setq cnt (1+ cnt))
14526 (replace-match ""))
14527 (message "Property \"%s\" removed from %d entries" property cnt)))))
14529 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14531 (defun org-compute-property-at-point ()
14532 "Compute the property at point.
14533 This looks for an enclosing column format, extracts the operator and
14534 then applies it to the property in the column format's scope."
14535 (interactive)
14536 (unless (org-at-property-p)
14537 (error "Not at a property"))
14538 (let ((prop (org-match-string-no-properties 2)))
14539 (org-columns-get-format-and-top-level)
14540 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14541 (error "No operator defined for property %s" prop))
14542 (org-columns-compute prop)))
14544 (defvar org-property-allowed-value-functions nil
14545 "Hook for functions supplying allowed values for a specific property.
14546 The functions must take a single argument, the name of the property, and
14547 return a flat list of allowed values. If \":ETC\" is one of
14548 the values, this means that these values are intended as defaults for
14549 completion, but that other values should be allowed too.
14550 The functions must return nil if they are not responsible for this
14551 property.")
14553 (defun org-property-get-allowed-values (pom property &optional table)
14554 "Get allowed values for the property PROPERTY.
14555 When TABLE is non-nil, return an alist that can directly be used for
14556 completion."
14557 (let (vals)
14558 (cond
14559 ((equal property "TODO")
14560 (setq vals (org-with-point-at pom
14561 (append org-todo-keywords-1 '("")))))
14562 ((equal property "PRIORITY")
14563 (let ((n org-lowest-priority))
14564 (while (>= n org-highest-priority)
14565 (push (char-to-string n) vals)
14566 (setq n (1- n)))))
14567 ((member property org-special-properties))
14568 ((setq vals (run-hook-with-args-until-success
14569 'org-property-allowed-value-functions property)))
14571 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14572 (when (and vals (string-match "\\S-" vals))
14573 (setq vals (car (read-from-string (concat "(" vals ")"))))
14574 (setq vals (mapcar (lambda (x)
14575 (cond ((stringp x) x)
14576 ((numberp x) (number-to-string x))
14577 ((symbolp x) (symbol-name x))
14578 (t "???")))
14579 vals)))))
14580 (when (member ":ETC" vals)
14581 (setq vals (remove ":ETC" vals))
14582 (org-add-props (car vals) '(org-unrestricted t)))
14583 (if table (mapcar 'list vals) vals)))
14585 (defun org-property-previous-allowed-value (&optional previous)
14586 "Switch to the next allowed value for this property."
14587 (interactive)
14588 (org-property-next-allowed-value t))
14590 (defun org-property-next-allowed-value (&optional previous)
14591 "Switch to the next allowed value for this property."
14592 (interactive)
14593 (unless (org-at-property-p)
14594 (error "Not at a property"))
14595 (let* ((key (match-string 2))
14596 (value (match-string 3))
14597 (allowed (or (org-property-get-allowed-values (point) key)
14598 (and (member value '("[ ]" "[-]" "[X]"))
14599 '("[ ]" "[X]"))))
14600 nval)
14601 (unless allowed
14602 (error "Allowed values for this property have not been defined"))
14603 (if previous (setq allowed (reverse allowed)))
14604 (if (member value allowed)
14605 (setq nval (car (cdr (member value allowed)))))
14606 (setq nval (or nval (car allowed)))
14607 (if (equal nval value)
14608 (error "Only one allowed value for this property"))
14609 (org-at-property-p)
14610 (replace-match (concat " :" key ": " nval) t t)
14611 (org-indent-line-function)
14612 (beginning-of-line 1)
14613 (skip-chars-forward " \t")
14614 (run-hook-with-args 'org-property-changed-functions key nval)))
14616 (defun org-find-olp (path &optional this-buffer)
14617 "Return a marker pointing to the entry at outline path OLP.
14618 If anything goes wrong, throw an error.
14619 You can wrap this call to catch the error like this:
14621 (condition-case msg
14622 (org-mobile-locate-entry (match-string 4))
14623 (error (nth 1 msg)))
14625 The return value will then be either a string with the error message,
14626 or a marker if everything is OK.
14628 If THIS-BUFFER is set, the outline path does not contain a file,
14629 only headings."
14630 (let* ((file (if this-buffer buffer-file-name (pop path)))
14631 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14632 (level 1)
14633 (lmin 1)
14634 (lmax 1)
14635 limit re end found pos heading cnt flevel)
14636 (unless buffer (error "File not found :%s" file))
14637 (with-current-buffer buffer
14638 (save-excursion
14639 (save-restriction
14640 (widen)
14641 (setq limit (point-max))
14642 (goto-char (point-min))
14643 (while (setq heading (pop path))
14644 (setq re (format org-complex-heading-regexp-format
14645 (regexp-quote heading)))
14646 (setq cnt 0 pos (point))
14647 (while (re-search-forward re end t)
14648 (setq level (- (match-end 1) (match-beginning 1)))
14649 (if (and (>= level lmin) (<= level lmax))
14650 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
14651 (when (= cnt 0) (error "Heading not found on level %d: %s"
14652 lmax heading))
14653 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14654 lmax heading))
14655 (goto-char found)
14656 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
14657 (setq end (save-excursion (org-end-of-subtree t t))))
14658 (when (org-on-heading-p)
14659 (move-marker (make-marker) (point))))))))
14661 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14662 "Find node HEADING in BUFFER.
14663 Return a marker to the heading if it was found, or nil if not.
14664 If POS-ONLY is set, return just the position instead of a marker.
14666 The heading text must match exact, but it may have a TODO keyword,
14667 a priority cookie and tags in the standard locations."
14668 (with-current-buffer (or buffer (current-buffer))
14669 (save-excursion
14670 (save-restriction
14671 (widen)
14672 (goto-char (point-min))
14673 (let (case-fold-search)
14674 (if (re-search-forward
14675 (format org-complex-heading-regexp-format
14676 (regexp-quote heading)) nil t)
14677 (if pos-only
14678 (match-beginning 0)
14679 (move-marker (make-marker) (match-beginning 0)))))))))
14681 (defun org-find-exact-heading-in-directory (heading &optional dir)
14682 "Find Org node headline HEADING in all .org files in directory DIR.
14683 When the target headline is found, return a marker to this location."
14684 (let ((files (directory-files (or dir default-directory)
14685 nil "\\`[^.#].*\\.org\\'"))
14686 file visiting m buffer)
14687 (catch 'found
14688 (while (setq file (pop files))
14689 (message "trying %s" file)
14690 (setq visiting (org-find-base-buffer-visiting file))
14691 (setq buffer (or visiting (find-file-noselect file)))
14692 (setq m (org-find-exact-headline-in-buffer
14693 heading buffer))
14694 (when (and (not m) (not visiting)) (kill-buffer buffer))
14695 (and m (throw 'found m))))))
14697 (defun org-find-entry-with-id (ident)
14698 "Locate the entry that contains the ID property with exact value IDENT.
14699 IDENT can be a string, a symbol or a number, this function will search for
14700 the string representation of it.
14701 Return the position where this entry starts, or nil if there is no such entry."
14702 (interactive "sID: ")
14703 (let ((id (cond
14704 ((stringp ident) ident)
14705 ((symbol-name ident) (symbol-name ident))
14706 ((numberp ident) (number-to-string ident))
14707 (t (error "IDENT %s must be a string, symbol or number" ident))))
14708 (case-fold-search nil))
14709 (save-excursion
14710 (save-restriction
14711 (widen)
14712 (goto-char (point-min))
14713 (when (re-search-forward
14714 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
14715 nil t)
14716 (org-back-to-heading t)
14717 (point))))))
14719 ;;;; Timestamps
14721 (defvar org-last-changed-timestamp nil)
14722 (defvar org-last-inserted-timestamp nil
14723 "The last time stamp inserted with `org-insert-time-stamp'.")
14724 (defvar org-time-was-given) ; dynamically scoped parameter
14725 (defvar org-end-time-was-given) ; dynamically scoped parameter
14726 (defvar org-ts-what) ; dynamically scoped parameter
14728 (defun org-time-stamp (arg &optional inactive)
14729 "Prompt for a date/time and insert a time stamp.
14730 If the user specifies a time like HH:MM, or if this command is called
14731 with a prefix argument, the time stamp will contain date and time.
14732 Otherwise, only the date will be included. All parts of a date not
14733 specified by the user will be filled in from the current date/time.
14734 So if you press just return without typing anything, the time stamp
14735 will represent the current date/time. If there is already a timestamp
14736 at the cursor, it will be modified."
14737 (interactive "P")
14738 (let* ((ts nil)
14739 (default-time
14740 ;; Default time is either today, or, when entering a range,
14741 ;; the range start.
14742 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
14743 (save-excursion
14744 (re-search-backward
14745 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
14746 (- (point) 20) t)))
14747 (apply 'encode-time (org-parse-time-string (match-string 1)))
14748 (current-time)))
14749 (default-input (and ts (org-get-compact-tod ts)))
14750 (repeater (save-excursion
14751 (save-match-data
14752 (beginning-of-line)
14753 (when (re-search-forward
14754 "\\([.+-]+[0-9]+[dwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
14755 (save-excursion (progn (end-of-line) (point))) t)
14756 (match-string 0)))))
14757 org-time-was-given org-end-time-was-given time)
14758 (cond
14759 ((and (org-at-timestamp-p t)
14760 (memq last-command '(org-time-stamp org-time-stamp-inactive))
14761 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
14762 (insert "--")
14763 (setq time (let ((this-command this-command))
14764 (org-read-date arg 'totime nil nil
14765 default-time default-input)))
14766 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
14767 ((org-at-timestamp-p t)
14768 (setq time (let ((this-command this-command))
14769 (org-read-date arg 'totime nil nil default-time default-input)))
14770 (when (org-at-timestamp-p t) ; just to get the match data
14771 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
14772 (replace-match "")
14773 (setq org-last-changed-timestamp
14774 (org-insert-time-stamp
14775 time (or org-time-was-given arg)
14776 inactive nil nil (list org-end-time-was-given)))
14777 (when repeater (goto-char (1- (point))) (insert " " repeater)
14778 (setq org-last-changed-timestamp
14779 (concat (substring org-last-inserted-timestamp 0 -1)
14780 " " repeater ">"))))
14781 (message "Timestamp updated"))
14783 (setq time (let ((this-command this-command))
14784 (org-read-date arg 'totime nil nil default-time default-input)))
14785 (org-insert-time-stamp time (or org-time-was-given arg) inactive
14786 nil nil (list org-end-time-was-given))))))
14788 ;; FIXME: can we use this for something else, like computing time differences?
14789 (defun org-get-compact-tod (s)
14790 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
14791 (let* ((t1 (match-string 1 s))
14792 (h1 (string-to-number (match-string 2 s)))
14793 (m1 (string-to-number (match-string 3 s)))
14794 (t2 (and (match-end 4) (match-string 5 s)))
14795 (h2 (and t2 (string-to-number (match-string 6 s))))
14796 (m2 (and t2 (string-to-number (match-string 7 s))))
14797 dh dm)
14798 (if (not t2)
14800 (setq dh (- h2 h1) dm (- m2 m1))
14801 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
14802 (concat t1 "+" (number-to-string dh)
14803 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
14805 (defun org-time-stamp-inactive (&optional arg)
14806 "Insert an inactive time stamp.
14807 An inactive time stamp is enclosed in square brackets instead of angle
14808 brackets. It is inactive in the sense that it does not trigger agenda entries,
14809 does not link to the calendar and cannot be changed with the S-cursor keys.
14810 So these are more for recording a certain time/date."
14811 (interactive "P")
14812 (org-time-stamp arg 'inactive))
14814 (defvar org-date-ovl (make-overlay 1 1))
14815 (overlay-put org-date-ovl 'face 'org-warning)
14816 (org-detach-overlay org-date-ovl)
14818 (defvar org-ans1) ; dynamically scoped parameter
14819 (defvar org-ans2) ; dynamically scoped parameter
14821 (defvar org-plain-time-of-day-regexp) ; defined below
14823 (defvar org-overriding-default-time nil) ; dynamically scoped
14824 (defvar org-read-date-overlay nil)
14825 (defvar org-dcst nil) ; dynamically scoped
14826 (defvar org-read-date-history nil)
14827 (defvar org-read-date-final-answer nil)
14828 (defvar org-read-date-analyze-futurep nil)
14829 (defvar org-read-date-analyze-forced-year nil)
14831 (defun org-read-date (&optional with-time to-time from-string prompt
14832 default-time default-input)
14833 "Read a date, possibly a time, and make things smooth for the user.
14834 The prompt will suggest to enter an ISO date, but you can also enter anything
14835 which will at least partially be understood by `parse-time-string'.
14836 Unrecognized parts of the date will default to the current day, month, year,
14837 hour and minute. If this command is called to replace a timestamp at point,
14838 or to enter the second timestamp of a range, the default time is taken
14839 from the existing stamp. Furthermore, the command prefers the future,
14840 so if you are giving a date where the year is not given, and the day-month
14841 combination is already past in the current year, it will assume you
14842 mean next year. For details, see the manual. A few examples:
14844 3-2-5 --> 2003-02-05
14845 feb 15 --> currentyear-02-15
14846 2/15 --> currentyear-02-15
14847 sep 12 9 --> 2009-09-12
14848 12:45 --> today 12:45
14849 22 sept 0:34 --> currentyear-09-22 0:34
14850 12 --> currentyear-currentmonth-12
14851 Fri --> nearest Friday (today or later)
14852 etc.
14854 Furthermore you can specify a relative date by giving, as the *first* thing
14855 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
14856 change in days weeks, months, years.
14857 With a single plus or minus, the date is relative to today. With a double
14858 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
14859 +4d --> four days from today
14860 +4 --> same as above
14861 +2w --> two weeks from today
14862 ++5 --> five days from default date
14864 The function understands only English month and weekday abbreviations,
14865 but this can be configured with the variables `parse-time-months' and
14866 `parse-time-weekdays'.
14868 While prompting, a calendar is popped up - you can also select the
14869 date with the mouse (button 1). The calendar shows a period of three
14870 months. To scroll it to other months, use the keys `>' and `<'.
14871 If you don't like the calendar, turn it off with
14872 \(setq org-read-date-popup-calendar nil)
14874 With optional argument TO-TIME, the date will immediately be converted
14875 to an internal time.
14876 With an optional argument WITH-TIME, the prompt will suggest to also
14877 insert a time. Note that when WITH-TIME is not set, you can still
14878 enter a time, and this function will inform the calling routine about
14879 this change. The calling routine may then choose to change the format
14880 used to insert the time stamp into the buffer to include the time.
14881 With optional argument FROM-STRING, read from this string instead from
14882 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
14883 the time/date that is used for everything that is not specified by the
14884 user."
14885 (require 'parse-time)
14886 (let* ((org-time-stamp-rounding-minutes
14887 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
14888 (org-dcst org-display-custom-times)
14889 (ct (org-current-time))
14890 (def (or org-overriding-default-time default-time ct))
14891 (defdecode (decode-time def))
14892 (dummy (progn
14893 (when (< (nth 2 defdecode) org-extend-today-until)
14894 (setcar (nthcdr 2 defdecode) -1)
14895 (setcar (nthcdr 1 defdecode) 59)
14896 (setq def (apply 'encode-time defdecode)
14897 defdecode (decode-time def)))))
14898 (calendar-frame-setup nil)
14899 (calendar-setup nil)
14900 (calendar-move-hook nil)
14901 (calendar-view-diary-initially-flag nil)
14902 (calendar-view-holidays-initially-flag nil)
14903 (timestr (format-time-string
14904 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
14905 (prompt (concat (if prompt (concat prompt " ") "")
14906 (format "Date+time [%s]: " timestr)))
14907 ans (org-ans0 "") org-ans1 org-ans2 final)
14909 (cond
14910 (from-string (setq ans from-string))
14911 (org-read-date-popup-calendar
14912 (save-excursion
14913 (save-window-excursion
14914 (calendar)
14915 (unwind-protect
14916 (progn
14917 (calendar-forward-day (- (time-to-days def)
14918 (calendar-absolute-from-gregorian
14919 (calendar-current-date))))
14920 (org-eval-in-calendar nil t)
14921 (let* ((old-map (current-local-map))
14922 (map (copy-keymap calendar-mode-map))
14923 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
14924 (org-defkey map (kbd "RET") 'org-calendar-select)
14925 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
14926 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
14927 (org-defkey minibuffer-local-map [(meta shift left)]
14928 (lambda () (interactive)
14929 (org-eval-in-calendar '(calendar-backward-month 1))))
14930 (org-defkey minibuffer-local-map [(meta shift right)]
14931 (lambda () (interactive)
14932 (org-eval-in-calendar '(calendar-forward-month 1))))
14933 (org-defkey minibuffer-local-map [(meta shift up)]
14934 (lambda () (interactive)
14935 (org-eval-in-calendar '(calendar-backward-year 1))))
14936 (org-defkey minibuffer-local-map [(meta shift down)]
14937 (lambda () (interactive)
14938 (org-eval-in-calendar '(calendar-forward-year 1))))
14939 (org-defkey minibuffer-local-map [?\e (shift left)]
14940 (lambda () (interactive)
14941 (org-eval-in-calendar '(calendar-backward-month 1))))
14942 (org-defkey minibuffer-local-map [?\e (shift right)]
14943 (lambda () (interactive)
14944 (org-eval-in-calendar '(calendar-forward-month 1))))
14945 (org-defkey minibuffer-local-map [?\e (shift up)]
14946 (lambda () (interactive)
14947 (org-eval-in-calendar '(calendar-backward-year 1))))
14948 (org-defkey minibuffer-local-map [?\e (shift down)]
14949 (lambda () (interactive)
14950 (org-eval-in-calendar '(calendar-forward-year 1))))
14951 (org-defkey minibuffer-local-map [(shift up)]
14952 (lambda () (interactive)
14953 (org-eval-in-calendar '(calendar-backward-week 1))))
14954 (org-defkey minibuffer-local-map [(shift down)]
14955 (lambda () (interactive)
14956 (org-eval-in-calendar '(calendar-forward-week 1))))
14957 (org-defkey minibuffer-local-map [(shift left)]
14958 (lambda () (interactive)
14959 (org-eval-in-calendar '(calendar-backward-day 1))))
14960 (org-defkey minibuffer-local-map [(shift right)]
14961 (lambda () (interactive)
14962 (org-eval-in-calendar '(calendar-forward-day 1))))
14963 (org-defkey minibuffer-local-map ">"
14964 (lambda () (interactive)
14965 (org-eval-in-calendar '(scroll-calendar-left 1))))
14966 (org-defkey minibuffer-local-map "<"
14967 (lambda () (interactive)
14968 (org-eval-in-calendar '(scroll-calendar-right 1))))
14969 (org-defkey minibuffer-local-map "\C-v"
14970 (lambda () (interactive)
14971 (org-eval-in-calendar
14972 '(calendar-scroll-left-three-months 1))))
14973 (org-defkey minibuffer-local-map "\M-v"
14974 (lambda () (interactive)
14975 (org-eval-in-calendar
14976 '(calendar-scroll-right-three-months 1))))
14977 (run-hooks 'org-read-date-minibuffer-setup-hook)
14978 (unwind-protect
14979 (progn
14980 (use-local-map map)
14981 (add-hook 'post-command-hook 'org-read-date-display)
14982 (setq org-ans0 (read-string prompt default-input
14983 'org-read-date-history nil))
14984 ;; org-ans0: from prompt
14985 ;; org-ans1: from mouse click
14986 ;; org-ans2: from calendar motion
14987 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
14988 (remove-hook 'post-command-hook 'org-read-date-display)
14989 (use-local-map old-map)
14990 (when org-read-date-overlay
14991 (delete-overlay org-read-date-overlay)
14992 (setq org-read-date-overlay nil)))))
14993 (bury-buffer "*Calendar*")))))
14995 (t ; Naked prompt only
14996 (unwind-protect
14997 (setq ans (read-string prompt default-input
14998 'org-read-date-history timestr))
14999 (when org-read-date-overlay
15000 (delete-overlay org-read-date-overlay)
15001 (setq org-read-date-overlay nil)))))
15003 (setq final (org-read-date-analyze ans def defdecode))
15005 (when org-read-date-analyze-forced-year
15006 (message "Year was forced into %s"
15007 (if org-read-date-force-compatible-dates
15008 "compatible range (1970-2037)"
15009 "range representable on this machine"))
15010 (ding))
15012 ;; One round trip to get rid of 34th of August and stuff like that....
15013 (setq final (decode-time (apply 'encode-time final)))
15015 (setq org-read-date-final-answer ans)
15017 (if to-time
15018 (apply 'encode-time final)
15019 (if (and (boundp 'org-time-was-given) org-time-was-given)
15020 (format "%04d-%02d-%02d %02d:%02d"
15021 (nth 5 final) (nth 4 final) (nth 3 final)
15022 (nth 2 final) (nth 1 final))
15023 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15025 (defvar def)
15026 (defvar defdecode)
15027 (defvar with-time)
15028 (defun org-read-date-display ()
15029 "Display the current date prompt interpretation in the minibuffer."
15030 (when org-read-date-display-live
15031 (when org-read-date-overlay
15032 (delete-overlay org-read-date-overlay))
15033 (let ((p (point)))
15034 (end-of-line 1)
15035 (while (not (equal (buffer-substring
15036 (max (point-min) (- (point) 4)) (point))
15037 " "))
15038 (insert " "))
15039 (goto-char p))
15040 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15041 " " (or org-ans1 org-ans2)))
15042 (org-end-time-was-given nil)
15043 (f (org-read-date-analyze ans def defdecode))
15044 (fmts (if org-dcst
15045 org-time-stamp-custom-formats
15046 org-time-stamp-formats))
15047 (fmt (if (or with-time
15048 (and (boundp 'org-time-was-given) org-time-was-given))
15049 (cdr fmts)
15050 (car fmts)))
15051 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
15052 (when (and org-end-time-was-given
15053 (string-match org-plain-time-of-day-regexp txt))
15054 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15055 org-end-time-was-given
15056 (substring txt (match-end 0)))))
15057 (when org-read-date-analyze-futurep
15058 (setq txt (concat txt " (=>F)")))
15059 (setq org-read-date-overlay
15060 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15061 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
15063 (defun org-read-date-analyze (ans def defdecode)
15064 "Analyze the combined answer of the date prompt."
15065 ;; FIXME: cleanup and comment
15066 (let ((nowdecode (decode-time (current-time)))
15067 delta deltan deltaw deltadef year month day
15068 hour minute second wday pm h2 m2 tl wday1
15069 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15070 (setq org-read-date-analyze-futurep nil
15071 org-read-date-analyze-forced-year nil)
15072 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15073 (setq ans "+0"))
15075 (when (setq delta (org-read-date-get-relative ans (current-time) def))
15076 (setq ans (replace-match "" t t ans)
15077 deltan (car delta)
15078 deltaw (nth 1 delta)
15079 deltadef (nth 2 delta)))
15081 ;; Check if there is an iso week date in there
15082 ;; If yes, store the info and postpone interpreting it until the rest
15083 ;; of the parsing is done
15084 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15085 (setq iso-year (if (match-end 1)
15086 (org-small-year-to-year
15087 (string-to-number (match-string 1 ans))))
15088 iso-weekday (if (match-end 3)
15089 (string-to-number (match-string 3 ans)))
15090 iso-week (string-to-number (match-string 2 ans)))
15091 (setq ans (replace-match "" t t ans)))
15093 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15094 (when (string-match
15095 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15096 (setq year (if (match-end 2)
15097 (string-to-number (match-string 2 ans))
15098 (progn (setq kill-year t)
15099 (string-to-number (format-time-string "%Y"))))
15100 month (string-to-number (match-string 3 ans))
15101 day (string-to-number (match-string 4 ans)))
15102 (if (< year 100) (setq year (+ 2000 year)))
15103 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15104 t nil ans)))
15106 ;; Help matching dottet european dates
15107 (when (string-match
15108 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15109 (setq year (if (match-end 3)
15110 (string-to-number (match-string 3 ans))
15111 (progn (setq kill-year t)
15112 (string-to-number (format-time-string "%Y"))))
15113 day (string-to-number (match-string 1 ans))
15114 month (string-to-number (match-string 2 ans))
15115 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15116 t nil ans)))
15118 ;; Help matching american dates, like 5/30 or 5/30/7
15119 (when (string-match
15120 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15121 (setq year (if (match-end 4)
15122 (string-to-number (match-string 4 ans))
15123 (progn (setq kill-year t)
15124 (string-to-number (format-time-string "%Y"))))
15125 month (string-to-number (match-string 1 ans))
15126 day (string-to-number (match-string 2 ans)))
15127 (if (< year 100) (setq year (+ 2000 year)))
15128 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15129 t nil ans)))
15130 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15131 ;; If there is a time with am/pm, and *no* time without it, we convert
15132 ;; so that matching will be successful.
15133 (loop for i from 1 to 2 do ; twice, for end time as well
15134 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15135 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15136 (setq hour (string-to-number (match-string 1 ans))
15137 minute (if (match-end 3)
15138 (string-to-number (match-string 3 ans))
15140 pm (equal ?p
15141 (string-to-char (downcase (match-string 4 ans)))))
15142 (if (and (= hour 12) (not pm))
15143 (setq hour 0)
15144 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15145 (setq ans (replace-match (format "%02d:%02d" hour minute)
15146 t t ans))))
15148 ;; Check if a time range is given as a duration
15149 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15150 (setq hour (string-to-number (match-string 1 ans))
15151 h2 (+ hour (string-to-number (match-string 3 ans)))
15152 minute (string-to-number (match-string 2 ans))
15153 m2 (+ minute (if (match-end 5) (string-to-number
15154 (match-string 5 ans))0)))
15155 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15156 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15157 t t ans)))
15159 ;; Check if there is a time range
15160 (when (boundp 'org-end-time-was-given)
15161 (setq org-time-was-given nil)
15162 (when (and (string-match org-plain-time-of-day-regexp ans)
15163 (match-end 8))
15164 (setq org-end-time-was-given (match-string 8 ans))
15165 (setq ans (concat (substring ans 0 (match-beginning 7))
15166 (substring ans (match-end 7))))))
15168 (setq tl (parse-time-string ans)
15169 day (or (nth 3 tl) (nth 3 defdecode))
15170 month (or (nth 4 tl)
15171 (if (and org-read-date-prefer-future
15172 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15173 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15174 (nth 4 defdecode)))
15175 year (or (and (not kill-year) (nth 5 tl))
15176 (if (and org-read-date-prefer-future
15177 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15178 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15179 (nth 5 defdecode)))
15180 hour (or (nth 2 tl) (nth 2 defdecode))
15181 minute (or (nth 1 tl) (nth 1 defdecode))
15182 second (or (nth 0 tl) 0)
15183 wday (nth 6 tl))
15185 (when (and (eq org-read-date-prefer-future 'time)
15186 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15187 (equal day (nth 3 nowdecode))
15188 (equal month (nth 4 nowdecode))
15189 (equal year (nth 5 nowdecode))
15190 (nth 2 tl)
15191 (or (< (nth 2 tl) (nth 2 nowdecode))
15192 (and (= (nth 2 tl) (nth 2 nowdecode))
15193 (nth 1 tl)
15194 (< (nth 1 tl) (nth 1 nowdecode)))))
15195 (setq day (1+ day)
15196 futurep t))
15198 ;; Special date definitions below
15199 (cond
15200 (iso-week
15201 ;; There was an iso week
15202 (require 'cal-iso)
15203 (setq futurep nil)
15204 (setq year (or iso-year year)
15205 day (or iso-weekday wday 1)
15206 wday nil ; to make sure that the trigger below does not match
15207 iso-date (calendar-gregorian-from-absolute
15208 (calendar-absolute-from-iso
15209 (list iso-week day year))))
15210 ; FIXME: Should we also push ISO weeks into the future?
15211 ; (when (and org-read-date-prefer-future
15212 ; (not iso-year)
15213 ; (< (calendar-absolute-from-gregorian iso-date)
15214 ; (time-to-days (current-time))))
15215 ; (setq year (1+ year)
15216 ; iso-date (calendar-gregorian-from-absolute
15217 ; (calendar-absolute-from-iso
15218 ; (list iso-week day year)))))
15219 (setq month (car iso-date)
15220 year (nth 2 iso-date)
15221 day (nth 1 iso-date)))
15222 (deltan
15223 (setq futurep nil)
15224 (unless deltadef
15225 (let ((now (decode-time (current-time))))
15226 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15227 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15228 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15229 ((equal deltaw "m") (setq month (+ month deltan)))
15230 ((equal deltaw "y") (setq year (+ year deltan)))))
15231 ((and wday (not (nth 3 tl)))
15232 (setq futurep nil)
15233 ;; Weekday was given, but no day, so pick that day in the week
15234 ;; on or after the derived date.
15235 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15236 (unless (equal wday wday1)
15237 (setq day (+ day (% (- wday wday1 -7) 7))))))
15238 (if (and (boundp 'org-time-was-given)
15239 (nth 2 tl))
15240 (setq org-time-was-given t))
15241 (if (< year 100) (setq year (+ 2000 year)))
15242 ;; Check of the date is representable
15243 (if org-read-date-force-compatible-dates
15244 (progn
15245 (if (< year 1970)
15246 (setq year 1970 org-read-date-analyze-forced-year t))
15247 (if (> year 2037)
15248 (setq year 2037 org-read-date-analyze-forced-year t)))
15249 (condition-case nil
15250 (ignore (encode-time second minute hour day month year))
15251 (error
15252 (setq year (nth 5 defdecode))
15253 (setq org-read-date-analyze-forced-year t))))
15254 (setq org-read-date-analyze-futurep futurep)
15255 (list second minute hour day month year)))
15257 (defvar parse-time-weekdays)
15259 (defun org-read-date-get-relative (s today default)
15260 "Check string S for special relative date string.
15261 TODAY and DEFAULT are internal times, for today and for a default.
15262 Return shift list (N what def-flag)
15263 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15264 N is the number of WHATs to shift.
15265 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15266 the DEFAULT date rather than TODAY."
15267 (require 'parse-time)
15268 (when (and
15269 (string-match
15270 (concat
15271 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15272 "\\([0-9]+\\)?"
15273 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15274 "\\([ \t]\\|$\\)") s)
15275 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15276 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15277 (string-to-char (substring (match-string 1 s) -1))
15278 ?+))
15279 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15280 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15281 (what (if (match-end 3) (match-string 3 s) "d"))
15282 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15283 (date (if rel default today))
15284 (wday (nth 6 (decode-time date)))
15285 delta)
15286 (if wday1
15287 (progn
15288 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15289 (if (= dir ?-) (setq delta (- delta 7)))
15290 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15291 (list delta "d" rel))
15292 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15294 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15295 "Turn a user-specified date into the internal representation.
15296 The internal representation needed by the calendar is (month day year).
15297 This is a wrapper to handle the brain-dead convention in calendar that
15298 user function argument order change dependent on argument order."
15299 (if (boundp 'calendar-date-style)
15300 (cond
15301 ((eq calendar-date-style 'american)
15302 (list arg1 arg2 arg3))
15303 ((eq calendar-date-style 'european)
15304 (list arg2 arg1 arg3))
15305 ((eq calendar-date-style 'iso)
15306 (list arg2 arg3 arg1)))
15307 (with-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15308 (if (org-bound-and-true-p european-calendar-style)
15309 (list arg2 arg1 arg3)
15310 (list arg1 arg2 arg3)))))
15312 (defun org-eval-in-calendar (form &optional keepdate)
15313 "Eval FORM in the calendar window and return to current window.
15314 Also, store the cursor date in variable org-ans2."
15315 (let ((sf (selected-frame))
15316 (sw (selected-window)))
15317 (select-window (get-buffer-window "*Calendar*" t))
15318 (eval form)
15319 (when (and (not keepdate) (calendar-cursor-to-date))
15320 (let* ((date (calendar-cursor-to-date))
15321 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15322 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15323 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15324 (select-window sw)
15325 (org-select-frame-set-input-focus sf)))
15327 (defun org-calendar-select ()
15328 "Return to `org-read-date' with the date currently selected.
15329 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15330 (interactive)
15331 (when (calendar-cursor-to-date)
15332 (let* ((date (calendar-cursor-to-date))
15333 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15334 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15335 (if (active-minibuffer-window) (exit-minibuffer))))
15337 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15338 "Insert a date stamp for the date given by the internal TIME.
15339 WITH-HM means use the stamp format that includes the time of the day.
15340 INACTIVE means use square brackets instead of angular ones, so that the
15341 stamp will not contribute to the agenda.
15342 PRE and POST are optional strings to be inserted before and after the
15343 stamp.
15344 The command returns the inserted time stamp."
15345 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15346 stamp)
15347 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15348 (insert-before-markers (or pre ""))
15349 (when (listp extra)
15350 (setq extra (car extra))
15351 (if (and (stringp extra)
15352 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15353 (setq extra (format "-%02d:%02d"
15354 (string-to-number (match-string 1 extra))
15355 (string-to-number (match-string 2 extra))))
15356 (setq extra nil)))
15357 (when extra
15358 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15359 (insert-before-markers (setq stamp (format-time-string fmt time)))
15360 (insert-before-markers (or post ""))
15361 (setq org-last-inserted-timestamp stamp)))
15363 (defun org-toggle-time-stamp-overlays ()
15364 "Toggle the use of custom time stamp formats."
15365 (interactive)
15366 (setq org-display-custom-times (not org-display-custom-times))
15367 (unless org-display-custom-times
15368 (let ((p (point-min)) (bmp (buffer-modified-p)))
15369 (while (setq p (next-single-property-change p 'display))
15370 (if (and (get-text-property p 'display)
15371 (eq (get-text-property p 'face) 'org-date))
15372 (remove-text-properties
15373 p (setq p (next-single-property-change p 'display))
15374 '(display t))))
15375 (set-buffer-modified-p bmp)))
15376 (if (featurep 'xemacs)
15377 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15378 (org-restart-font-lock)
15379 (setq org-table-may-need-update t)
15380 (if org-display-custom-times
15381 (message "Time stamps are overlaid with custom format")
15382 (message "Time stamp overlays removed")))
15384 (defun org-display-custom-time (beg end)
15385 "Overlay modified time stamp format over timestamp between BEG and END."
15386 (let* ((ts (buffer-substring beg end))
15387 t1 w1 with-hm tf time str w2 (off 0))
15388 (save-match-data
15389 (setq t1 (org-parse-time-string ts t))
15390 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
15391 (setq off (- (match-end 0) (match-beginning 0)))))
15392 (setq end (- end off))
15393 (setq w1 (- end beg)
15394 with-hm (and (nth 1 t1) (nth 2 t1))
15395 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15396 time (org-fix-decoded-time t1)
15397 str (org-add-props
15398 (format-time-string
15399 (substring tf 1 -1) (apply 'encode-time time))
15400 nil 'mouse-face 'highlight)
15401 w2 (length str))
15402 (if (not (= w2 w1))
15403 (add-text-properties (1+ beg) (+ 2 beg)
15404 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15405 (if (featurep 'xemacs)
15406 (progn
15407 (put-text-property beg end 'invisible t)
15408 (put-text-property beg end 'end-glyph (make-glyph str)))
15409 (put-text-property beg end 'display str))))
15411 (defun org-translate-time (string)
15412 "Translate all timestamps in STRING to custom format.
15413 But do this only if the variable `org-display-custom-times' is set."
15414 (when org-display-custom-times
15415 (save-match-data
15416 (let* ((start 0)
15417 (re org-ts-regexp-both)
15418 t1 with-hm inactive tf time str beg end)
15419 (while (setq start (string-match re string start))
15420 (setq beg (match-beginning 0)
15421 end (match-end 0)
15422 t1 (save-match-data
15423 (org-parse-time-string (substring string beg end) t))
15424 with-hm (and (nth 1 t1) (nth 2 t1))
15425 inactive (equal (substring string beg (1+ beg)) "[")
15426 tf (funcall (if with-hm 'cdr 'car)
15427 org-time-stamp-custom-formats)
15428 time (org-fix-decoded-time t1)
15429 str (format-time-string
15430 (concat
15431 (if inactive "[" "<") (substring tf 1 -1)
15432 (if inactive "]" ">"))
15433 (apply 'encode-time time))
15434 string (replace-match str t t string)
15435 start (+ start (length str)))))))
15436 string)
15438 (defun org-fix-decoded-time (time)
15439 "Set 0 instead of nil for the first 6 elements of time.
15440 Don't touch the rest."
15441 (let ((n 0))
15442 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15444 (defun org-days-to-time (timestamp-string)
15445 "Difference between TIMESTAMP-STRING and now in days."
15446 (- (time-to-days (org-time-string-to-time timestamp-string))
15447 (time-to-days (current-time))))
15449 (defun org-deadline-close (timestamp-string &optional ndays)
15450 "Is the time in TIMESTAMP-STRING close to the current date?"
15451 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15452 (and (< (org-days-to-time timestamp-string) ndays)
15453 (not (org-entry-is-done-p))))
15455 (defun org-get-wdays (ts)
15456 "Get the deadline lead time appropriate for timestring TS."
15457 (cond
15458 ((<= org-deadline-warning-days 0)
15459 ;; 0 or negative, enforce this value no matter what
15460 (- org-deadline-warning-days))
15461 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
15462 ;; lead time is specified.
15463 (floor (* (string-to-number (match-string 1 ts))
15464 (cdr (assoc (match-string 2 ts)
15465 '(("d" . 1) ("w" . 7)
15466 ("m" . 30.4) ("y" . 365.25)))))))
15467 ;; go for the default.
15468 (t org-deadline-warning-days)))
15470 (defun org-calendar-select-mouse (ev)
15471 "Return to `org-read-date' with the date currently selected.
15472 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15473 (interactive "e")
15474 (mouse-set-point ev)
15475 (when (calendar-cursor-to-date)
15476 (let* ((date (calendar-cursor-to-date))
15477 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15478 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15479 (if (active-minibuffer-window) (exit-minibuffer))))
15481 (defun org-check-deadlines (ndays)
15482 "Check if there are any deadlines due or past due.
15483 A deadline is considered due if it happens within `org-deadline-warning-days'
15484 days from today's date. If the deadline appears in an entry marked DONE,
15485 it is not shown. The prefix arg NDAYS can be used to test that many
15486 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15487 (interactive "P")
15488 (let* ((org-warn-days
15489 (cond
15490 ((equal ndays '(4)) 100000)
15491 (ndays (prefix-numeric-value ndays))
15492 (t (abs org-deadline-warning-days))))
15493 (case-fold-search nil)
15494 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15495 (callback
15496 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15498 (message "%d deadlines past-due or due within %d days"
15499 (org-occur regexp nil callback)
15500 org-warn-days)))
15502 (defun org-check-before-date (date)
15503 "Check if there are deadlines or scheduled entries before DATE."
15504 (interactive (list (org-read-date)))
15505 (let ((case-fold-search nil)
15506 (regexp (concat "\\<\\(" org-deadline-string
15507 "\\|" org-scheduled-string
15508 "\\) *<\\([^>]+\\)>"))
15509 (callback
15510 (lambda () (time-less-p
15511 (org-time-string-to-time (match-string 2))
15512 (org-time-string-to-time date)))))
15513 (message "%d entries before %s"
15514 (org-occur regexp nil callback) date)))
15516 (defun org-check-after-date (date)
15517 "Check if there are deadlines or scheduled entries after DATE."
15518 (interactive (list (org-read-date)))
15519 (let ((case-fold-search nil)
15520 (regexp (concat "\\<\\(" org-deadline-string
15521 "\\|" org-scheduled-string
15522 "\\) *<\\([^>]+\\)>"))
15523 (callback
15524 (lambda () (not
15525 (time-less-p
15526 (org-time-string-to-time (match-string 2))
15527 (org-time-string-to-time date))))))
15528 (message "%d entries after %s"
15529 (org-occur regexp nil callback) date)))
15531 (defun org-evaluate-time-range (&optional to-buffer)
15532 "Evaluate a time range by computing the difference between start and end.
15533 Normally the result is just printed in the echo area, but with prefix arg
15534 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15535 If the time range is actually in a table, the result is inserted into the
15536 next column.
15537 For time difference computation, a year is assumed to be exactly 365
15538 days in order to avoid rounding problems."
15539 (interactive "P")
15541 (org-clock-update-time-maybe)
15542 (save-excursion
15543 (unless (org-at-date-range-p t)
15544 (goto-char (point-at-bol))
15545 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15546 (if (not (org-at-date-range-p t))
15547 (error "Not at a time-stamp range, and none found in current line")))
15548 (let* ((ts1 (match-string 1))
15549 (ts2 (match-string 2))
15550 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15551 (match-end (match-end 0))
15552 (time1 (org-time-string-to-time ts1))
15553 (time2 (org-time-string-to-time ts2))
15554 (t1 (org-float-time time1))
15555 (t2 (org-float-time time2))
15556 (diff (abs (- t2 t1)))
15557 (negative (< (- t2 t1) 0))
15558 ;; (ys (floor (* 365 24 60 60)))
15559 (ds (* 24 60 60))
15560 (hs (* 60 60))
15561 (fy "%dy %dd %02d:%02d")
15562 (fy1 "%dy %dd")
15563 (fd "%dd %02d:%02d")
15564 (fd1 "%dd")
15565 (fh "%02d:%02d")
15566 y d h m align)
15567 (if havetime
15568 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15570 d (floor (/ diff ds)) diff (mod diff ds)
15571 h (floor (/ diff hs)) diff (mod diff hs)
15572 m (floor (/ diff 60)))
15573 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15575 d (floor (+ (/ diff ds) 0.5))
15576 h 0 m 0))
15577 (if (not to-buffer)
15578 (message "%s" (org-make-tdiff-string y d h m))
15579 (if (org-at-table-p)
15580 (progn
15581 (goto-char match-end)
15582 (setq align t)
15583 (and (looking-at " *|") (goto-char (match-end 0))))
15584 (goto-char match-end))
15585 (if (looking-at
15586 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15587 (replace-match ""))
15588 (if negative (insert " -"))
15589 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15590 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15591 (insert " " (format fh h m))))
15592 (if align (org-table-align))
15593 (message "Time difference inserted")))))
15595 (defun org-make-tdiff-string (y d h m)
15596 (let ((fmt "")
15597 (l nil))
15598 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15599 l (push y l)))
15600 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15601 l (push d l)))
15602 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15603 l (push h l)))
15604 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15605 l (push m l)))
15606 (apply 'format fmt (nreverse l))))
15608 (defun org-time-string-to-time (s &optional buffer pos)
15609 (condition-case errdata
15610 (apply 'encode-time (org-parse-time-string s))
15611 (error (error "Bad timestamp `%s'%s\nError was: %s"
15612 s (if (not (and buffer pos))
15614 (format " at %d in buffer `%s'" pos buffer))
15615 (cdr errdata)))))
15617 (defun org-time-string-to-seconds (s)
15618 (org-float-time (org-time-string-to-time s)))
15620 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
15621 "Convert a time stamp to an absolute day number.
15622 If there is a specifier for a cyclic time stamp, get the closest date to
15623 DAYNR.
15624 PREFER and SHOW-ALL are passed through to `org-closest-date'.
15625 The variable date is bound by the calendar when this is called."
15626 (cond
15627 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15628 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15629 daynr
15630 (+ daynr 1000)))
15631 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
15632 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15633 (time-to-days (current-time))) (match-string 0 s)
15634 prefer show-all))
15635 (t (time-to-days
15636 (condition-case errdata
15637 (apply 'encode-time (org-parse-time-string s))
15638 (error (error "Bad timestamp `%s'%s\nError was: %s"
15639 s (if (not (and buffer pos))
15641 (format " at %d in buffer `%s'" pos buffer))
15642 (cdr errdata))))))))
15644 (defun org-days-to-iso-week (days)
15645 "Return the iso week number."
15646 (require 'cal-iso)
15647 (car (calendar-iso-from-absolute days)))
15649 (defun org-small-year-to-year (year)
15650 "Convert 2-digit years into 4-digit years.
15651 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15652 The year 2000 cannot be abbreviated. Any year larger than 99
15653 is returned unchanged."
15654 (if (< year 38)
15655 (setq year (+ 2000 year))
15656 (if (< year 100)
15657 (setq year (+ 1900 year))))
15658 year)
15660 (defun org-time-from-absolute (d)
15661 "Return the time corresponding to date D.
15662 D may be an absolute day number, or a calendar-type list (month day year)."
15663 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15664 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15666 (defun org-calendar-holiday ()
15667 "List of holidays, for Diary display in Org-mode."
15668 (require 'holidays)
15669 (let ((hl (funcall
15670 (if (fboundp 'calendar-check-holidays)
15671 'calendar-check-holidays 'check-calendar-holidays) date)))
15672 (if hl (mapconcat 'identity hl "; "))))
15674 (defun org-diary-sexp-entry (sexp entry date)
15675 "Process a SEXP diary ENTRY for DATE."
15676 (require 'diary-lib)
15677 (let ((result (if calendar-debug-sexp
15678 (let ((stack-trace-on-error t))
15679 (eval (car (read-from-string sexp))))
15680 (condition-case nil
15681 (eval (car (read-from-string sexp)))
15682 (error
15683 (beep)
15684 (message "Bad sexp at line %d in %s: %s"
15685 (org-current-line)
15686 (buffer-file-name) sexp)
15687 (sleep-for 2))))))
15688 (cond ((stringp result) (split-string result "; "))
15689 ((and (consp result)
15690 (not (consp (cdr result)))
15691 (stringp (cdr result))) (cdr result))
15692 ((and (consp result)
15693 (stringp (car result))) result)
15694 (result entry)
15695 (t nil))))
15697 (defun org-diary-to-ical-string (frombuf)
15698 "Get iCalendar entries from diary entries in buffer FROMBUF.
15699 This uses the icalendar.el library."
15700 (let* ((tmpdir (if (featurep 'xemacs)
15701 (temp-directory)
15702 temporary-file-directory))
15703 (tmpfile (make-temp-name
15704 (expand-file-name "orgics" tmpdir)))
15705 buf rtn b e)
15706 (with-current-buffer frombuf
15707 (icalendar-export-region (point-min) (point-max) tmpfile)
15708 (setq buf (find-buffer-visiting tmpfile))
15709 (set-buffer buf)
15710 (goto-char (point-min))
15711 (if (re-search-forward "^BEGIN:VEVENT" nil t)
15712 (setq b (match-beginning 0)))
15713 (goto-char (point-max))
15714 (if (re-search-backward "^END:VEVENT" nil t)
15715 (setq e (match-end 0)))
15716 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
15717 (kill-buffer buf)
15718 (delete-file tmpfile)
15719 rtn))
15721 (defun org-closest-date (start current change prefer show-all)
15722 "Find the date closest to CURRENT that is consistent with START and CHANGE.
15723 When PREFER is `past', return a date that is either CURRENT or past.
15724 When PREFER is `future', return a date that is either CURRENT or future.
15725 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
15726 ;; Make the proper lists from the dates
15727 (catch 'exit
15728 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
15729 dn dw sday cday n1 n2 n0
15730 d m y y1 y2 date1 date2 nmonths nm ny m2)
15732 (setq start (org-date-to-gregorian start)
15733 current (org-date-to-gregorian
15734 (if show-all
15735 current
15736 (time-to-days (current-time))))
15737 sday (calendar-absolute-from-gregorian start)
15738 cday (calendar-absolute-from-gregorian current))
15740 (if (<= cday sday) (throw 'exit sday))
15742 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
15743 (setq dn (string-to-number (match-string 1 change))
15744 dw (cdr (assoc (match-string 2 change) a1)))
15745 (error "Invalid change specifier: %s" change))
15746 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
15747 (cond
15748 ((eq dw 'day)
15749 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
15750 n2 (+ n1 dn)))
15751 ((eq dw 'year)
15752 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
15753 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
15754 (setq date1 (list m d y1)
15755 n1 (calendar-absolute-from-gregorian date1)
15756 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
15757 n2 (calendar-absolute-from-gregorian date2)))
15758 ((eq dw 'month)
15759 ;; approx number of month between the two dates
15760 (setq nmonths (floor (/ (- cday sday) 30.436875)))
15761 ;; How often does dn fit in there?
15762 (setq d (nth 1 start) m (car start) y (nth 2 start)
15763 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
15764 m (+ m nm)
15765 ny (floor (/ m 12))
15766 y (+ y ny)
15767 m (- m (* ny 12)))
15768 (while (> m 12) (setq m (- m 12) y (1+ y)))
15769 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
15770 (setq m2 (+ m dn) y2 y)
15771 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15772 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
15773 (while (<= n2 cday)
15774 (setq n1 n2 m m2 y y2)
15775 (setq m2 (+ m dn) y2 y)
15776 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15777 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
15778 ;; Make sure n1 is the earlier date
15779 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
15780 (if show-all
15781 (cond
15782 ((eq prefer 'past) (if (= cday n2) n2 n1))
15783 ((eq prefer 'future) (if (= cday n1) n1 n2))
15784 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
15785 (cond
15786 ((eq prefer 'past) (if (= cday n2) n2 n1))
15787 ((eq prefer 'future) (if (= cday n1) n1 n2))
15788 (t (if (= cday n1) n1 n2)))))))
15790 (defun org-date-to-gregorian (date)
15791 "Turn any specification of DATE into a Gregorian date for the calendar."
15792 (cond ((integerp date) (calendar-gregorian-from-absolute date))
15793 ((and (listp date) (= (length date) 3)) date)
15794 ((stringp date)
15795 (setq date (org-parse-time-string date))
15796 (list (nth 4 date) (nth 3 date) (nth 5 date)))
15797 ((listp date)
15798 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
15800 (defun org-parse-time-string (s &optional nodefault)
15801 "Parse the standard Org-mode time string.
15802 This should be a lot faster than the normal `parse-time-string'.
15803 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
15804 hour and minute fields will be nil if not given."
15805 (if (string-match org-ts-regexp0 s)
15806 (list 0
15807 (if (or (match-beginning 8) (not nodefault))
15808 (string-to-number (or (match-string 8 s) "0")))
15809 (if (or (match-beginning 7) (not nodefault))
15810 (string-to-number (or (match-string 7 s) "0")))
15811 (string-to-number (match-string 4 s))
15812 (string-to-number (match-string 3 s))
15813 (string-to-number (match-string 2 s))
15814 nil nil nil)
15815 (error "Not a standard Org-mode time string: %s" s)))
15817 (defun org-timestamp-up (&optional arg)
15818 "Increase the date item at the cursor by one.
15819 If the cursor is on the year, change the year. If it is on the month,
15820 the day or the time, change that.
15821 With prefix ARG, change by that many units."
15822 (interactive "p")
15823 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
15825 (defun org-timestamp-down (&optional arg)
15826 "Decrease the date item at the cursor by one.
15827 If the cursor is on the year, change the year. If it is on the month,
15828 the day or the time, change that.
15829 With prefix ARG, change by that many units."
15830 (interactive "p")
15831 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
15833 (defun org-timestamp-up-day (&optional arg)
15834 "Increase the date in the time stamp by one day.
15835 With prefix ARG, change that many days."
15836 (interactive "p")
15837 (if (and (not (org-at-timestamp-p t))
15838 (org-on-heading-p))
15839 (org-todo 'up)
15840 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
15842 (defun org-timestamp-down-day (&optional arg)
15843 "Decrease the date in the time stamp by one day.
15844 With prefix ARG, change that many days."
15845 (interactive "p")
15846 (if (and (not (org-at-timestamp-p t))
15847 (org-on-heading-p))
15848 (org-todo 'down)
15849 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
15851 (defun org-at-timestamp-p (&optional inactive-ok)
15852 "Determine if the cursor is in or at a timestamp."
15853 (interactive)
15854 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
15855 (pos (point))
15856 (ans (or (looking-at tsr)
15857 (save-excursion
15858 (skip-chars-backward "^[<\n\r\t")
15859 (if (> (point) (point-min)) (backward-char 1))
15860 (and (looking-at tsr)
15861 (> (- (match-end 0) pos) -1))))))
15862 (and ans
15863 (boundp 'org-ts-what)
15864 (setq org-ts-what
15865 (cond
15866 ((= pos (match-beginning 0)) 'bracket)
15867 ;; Point is considered to be "on the bracket" whether
15868 ;; it's really on it or right after it.
15869 ((or (= pos (1- (match-end 0)))
15870 (= pos (match-end 0))) 'bracket)
15871 ((org-pos-in-match-range pos 2) 'year)
15872 ((org-pos-in-match-range pos 3) 'month)
15873 ((org-pos-in-match-range pos 7) 'hour)
15874 ((org-pos-in-match-range pos 8) 'minute)
15875 ((or (org-pos-in-match-range pos 4)
15876 (org-pos-in-match-range pos 5)) 'day)
15877 ((and (> pos (or (match-end 8) (match-end 5)))
15878 (< pos (match-end 0)))
15879 (- pos (or (match-end 8) (match-end 5))))
15880 (t 'day))))
15881 ans))
15883 (defun org-toggle-timestamp-type ()
15884 "Toggle the type (<active> or [inactive]) of a time stamp."
15885 (interactive)
15886 (when (org-at-timestamp-p t)
15887 (let ((beg (match-beginning 0)) (end (match-end 0))
15888 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
15889 (save-excursion
15890 (goto-char beg)
15891 (while (re-search-forward "[][<>]" end t)
15892 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
15893 t t)))
15894 (message "Timestamp is now %sactive"
15895 (if (equal (char-after beg) ?<) "" "in")))))
15897 (defun org-timestamp-change (n &optional what updown)
15898 "Change the date in the time stamp at point.
15899 The date will be changed by N times WHAT. WHAT can be `day', `month',
15900 `year', `minute', `second'. If WHAT is not given, the cursor position
15901 in the timestamp determines what will be changed."
15902 (let ((origin (point)) origin-cat
15903 with-hm inactive
15904 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
15905 org-ts-what
15906 extra rem
15907 ts time time0)
15908 (if (not (org-at-timestamp-p t))
15909 (error "Not at a timestamp"))
15910 (if (and (not what) (eq org-ts-what 'bracket))
15911 (org-toggle-timestamp-type)
15912 ;; Point isn't on brackets. Remember the part of the time-stamp
15913 ;; the point was in. Indeed, size of time-stamps may change,
15914 ;; but point must be kept in the same category nonetheless.
15915 (setq origin-cat org-ts-what)
15916 (if (and (not what) (not (eq org-ts-what 'day))
15917 org-display-custom-times
15918 (get-text-property (point) 'display)
15919 (not (get-text-property (1- (point)) 'display)))
15920 (setq org-ts-what 'day))
15921 (setq org-ts-what (or what org-ts-what)
15922 inactive (= (char-after (match-beginning 0)) ?\[)
15923 ts (match-string 0))
15924 (replace-match "")
15925 (if (string-match
15926 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
15928 (setq extra (match-string 1 ts)))
15929 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
15930 (setq with-hm t))
15931 (setq time0 (org-parse-time-string ts))
15932 (when (and updown
15933 (eq org-ts-what 'minute)
15934 (not current-prefix-arg))
15935 ;; This looks like s-up and s-down. Change by one rounding step.
15936 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
15937 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
15938 (setcar (cdr time0) (+ (nth 1 time0)
15939 (if (> n 0) (- rem) (- dm rem))))))
15940 (setq time
15941 (encode-time (or (car time0) 0)
15942 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
15943 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
15944 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
15945 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
15946 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
15947 (nthcdr 6 time0)))
15948 (when (and (member org-ts-what '(hour minute))
15949 extra
15950 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
15951 (setq extra (org-modify-ts-extra
15952 extra
15953 (if (eq org-ts-what 'hour) 2 5)
15954 n dm)))
15955 (when (integerp org-ts-what)
15956 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
15957 (if (eq what 'calendar)
15958 (let ((cal-date (org-get-date-from-calendar)))
15959 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
15960 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
15961 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
15962 (setcar time0 (or (car time0) 0))
15963 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
15964 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
15965 (setq time (apply 'encode-time time0))))
15966 ;; Insert the new time-stamp, and ensure point stays in the same
15967 ;; category as before (i.e. not after the last position in that
15968 ;; category).
15969 (let ((pos (point)))
15970 ;; Stay before inserted string. `save-excursion' is of no use.
15971 (setq org-last-changed-timestamp
15972 (org-insert-time-stamp time with-hm inactive nil nil extra))
15973 (goto-char pos))
15974 (save-match-data
15975 (looking-at org-ts-regexp3)
15976 (goto-char (cond
15977 ;; `day' category ends before `hour' if any, or at
15978 ;; the end of the day name.
15979 ((eq origin-cat 'day)
15980 (min (or (match-beginning 7) (1- (match-end 5))) origin))
15981 ((eq origin-cat 'hour) (min (match-end 7) origin))
15982 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
15983 ((integerp origin-cat) (min (1- (match-end 0)) origin))
15984 ;; `year' and `month' have both fixed size: point
15985 ;; couldn't have moved into another part.
15986 (t origin))))
15987 ;; Update clock if on a CLOCK line.
15988 (org-clock-update-time-maybe)
15989 ;; Try to recenter the calendar window, if any.
15990 (if (and org-calendar-follow-timestamp-change
15991 (get-buffer-window "*Calendar*" t)
15992 (memq org-ts-what '(day month year)))
15993 (org-recenter-calendar (time-to-days time))))))
15995 (defun org-modify-ts-extra (s pos n dm)
15996 "Change the different parts of the lead-time and repeat fields in timestamp."
15997 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
15998 ng h m new rem)
15999 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16000 (cond
16001 ((or (org-pos-in-match-range pos 2)
16002 (org-pos-in-match-range pos 3))
16003 (setq m (string-to-number (match-string 3 s))
16004 h (string-to-number (match-string 2 s)))
16005 (if (org-pos-in-match-range pos 2)
16006 (setq h (+ h n))
16007 (setq n (* dm (org-no-warnings (signum n))))
16008 (when (not (= 0 (setq rem (% m dm))))
16009 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16010 (setq m (+ m n)))
16011 (if (< m 0) (setq m (+ m 60) h (1- h)))
16012 (if (> m 59) (setq m (- m 60) h (1+ h)))
16013 (setq h (min 24 (max 0 h)))
16014 (setq ng 1 new (format "-%02d:%02d" h m)))
16015 ((org-pos-in-match-range pos 6)
16016 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16017 ((org-pos-in-match-range pos 5)
16018 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16020 ((org-pos-in-match-range pos 9)
16021 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16022 ((org-pos-in-match-range pos 8)
16023 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16025 (when ng
16026 (setq s (concat
16027 (substring s 0 (match-beginning ng))
16029 (substring s (match-end ng))))))
16032 (defun org-recenter-calendar (date)
16033 "If the calendar is visible, recenter it to DATE."
16034 (let* ((win (selected-window))
16035 (cwin (get-buffer-window "*Calendar*" t))
16036 (calendar-move-hook nil))
16037 (when cwin
16038 (select-window cwin)
16039 (calendar-goto-date (if (listp date) date
16040 (calendar-gregorian-from-absolute date)))
16041 (select-window win))))
16043 (defun org-goto-calendar (&optional arg)
16044 "Go to the Emacs calendar at the current date.
16045 If there is a time stamp in the current line, go to that date.
16046 A prefix ARG can be used to force the current date."
16047 (interactive "P")
16048 (let ((tsr org-ts-regexp) diff
16049 (calendar-move-hook nil)
16050 (calendar-view-holidays-initially-flag nil)
16051 (calendar-view-diary-initially-flag nil))
16052 (if (or (org-at-timestamp-p)
16053 (save-excursion
16054 (beginning-of-line 1)
16055 (looking-at (concat ".*" tsr))))
16056 (let ((d1 (time-to-days (current-time)))
16057 (d2 (time-to-days
16058 (org-time-string-to-time (match-string 1)))))
16059 (setq diff (- d2 d1))))
16060 (calendar)
16061 (calendar-goto-today)
16062 (if (and diff (not arg)) (calendar-forward-day diff))))
16064 (defun org-get-date-from-calendar ()
16065 "Return a list (month day year) of date at point in calendar."
16066 (with-current-buffer "*Calendar*"
16067 (save-match-data
16068 (calendar-cursor-to-date))))
16070 (defun org-date-from-calendar ()
16071 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16072 If there is already a time stamp at the cursor position, update it."
16073 (interactive)
16074 (if (org-at-timestamp-p t)
16075 (org-timestamp-change 0 'calendar)
16076 (let ((cal-date (org-get-date-from-calendar)))
16077 (org-insert-time-stamp
16078 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16080 (defun org-minutes-to-hh:mm-string (m)
16081 "Compute H:MM from a number of minutes."
16082 (let ((h (/ m 60)))
16083 (setq m (- m (* 60 h)))
16084 (format org-time-clocksum-format h m)))
16086 (defun org-hh:mm-string-to-minutes (s)
16087 "Convert a string H:MM to a number of minutes.
16088 If the string is just a number, interpret it as minutes.
16089 In fact, the first hh:mm or number in the string will be taken,
16090 there can be extra stuff in the string.
16091 If no number is found, the return value is 0."
16092 (cond
16093 ((integerp s) s)
16094 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16095 (+ (* (string-to-number (match-string 1 s)) 60)
16096 (string-to-number (match-string 2 s))))
16097 ((string-match "\\([0-9]+\\)" s)
16098 (string-to-number (match-string 1 s)))
16099 (t 0)))
16101 (defcustom org-effort-durations
16102 `(("h" . 60)
16103 ("d" . ,(* 60 8))
16104 ("w" . ,(* 60 8 5))
16105 ("m" . ,(* 60 8 5 4))
16106 ("y" . ,(* 60 8 5 40)))
16107 "Conversion factor to minutes for an effort modifier.
16109 Each entry has the form (MODIFIER . MINUTES).
16111 In an effort string, a number followed by MODIFIER is multiplied
16112 by the specified number of MINUTES to obtain an effort in
16113 minutes.
16115 For example, if the value of this variable is ((\"hours\" . 60)), then an
16116 effort string \"2hours\" is equivalent to 120 minutes."
16117 :group 'org-agenda
16118 :type '(alist :key-type (string :tag "Modifier")
16119 :value-type (number :tag "Minutes")))
16121 (defun org-duration-string-to-minutes (s)
16122 "Convert a duration string S to minutes.
16124 A bare number is interpreted as minutes, modifiers can be set by
16125 customizing `org-effort-durations' (which see).
16127 Entries containing a colon are interpreted as H:MM by
16128 `org-hh:mm-string-to-minutes'."
16129 (let ((result 0)
16130 (re (concat "\\([0-9]+\\) *\\("
16131 (regexp-opt (mapcar 'car org-effort-durations))
16132 "\\)")))
16133 (while (string-match re s)
16134 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16135 (string-to-number (match-string 1 s))))
16136 (setq s (replace-match "" nil t s)))
16137 (incf result (org-hh:mm-string-to-minutes s))
16138 result))
16140 ;;;; Files
16142 (defun org-save-all-org-buffers ()
16143 "Save all Org-mode buffers without user confirmation."
16144 (interactive)
16145 (message "Saving all Org-mode buffers...")
16146 (save-some-buffers t (lambda () (eq major-mode 'org-mode)))
16147 (when (featurep 'org-id) (org-id-locations-save))
16148 (message "Saving all Org-mode buffers... done"))
16150 (defun org-revert-all-org-buffers ()
16151 "Revert all Org-mode buffers.
16152 Prompt for confirmation when there are unsaved changes.
16153 Be sure you know what you are doing before letting this function
16154 overwrite your changes.
16156 This function is useful in a setup where one tracks org files
16157 with a version control system, to revert on one machine after pulling
16158 changes from another. I believe the procedure must be like this:
16160 1. M-x org-save-all-org-buffers
16161 2. Pull changes from the other machine, resolve conflicts
16162 3. M-x org-revert-all-org-buffers"
16163 (interactive)
16164 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16165 (error "Abort"))
16166 (save-excursion
16167 (save-window-excursion
16168 (mapc
16169 (lambda (b)
16170 (when (and (with-current-buffer b (eq major-mode 'org-mode))
16171 (with-current-buffer b buffer-file-name))
16172 (org-pop-to-buffer-same-window b)
16173 (revert-buffer t 'no-confirm)))
16174 (buffer-list))
16175 (when (and (featurep 'org-id) org-id-track-globally)
16176 (org-id-locations-load)))))
16178 ;;;; Agenda files
16180 ;;;###autoload
16181 (defun org-switchb (&optional arg)
16182 "Switch between Org buffers.
16183 With one prefix argument, restrict available buffers to files.
16184 With two prefix arguments, restrict available buffers to agenda files.
16186 Defaults to `iswitchb' for buffer name completion.
16187 Set `org-completion-use-ido' to make it use ido instead."
16188 (interactive "P")
16189 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16190 ((equal arg '(16)) (org-buffer-list 'agenda))
16191 (t (org-buffer-list))))
16192 (org-completion-use-iswitchb org-completion-use-iswitchb)
16193 (org-completion-use-ido org-completion-use-ido))
16194 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16195 (setq org-completion-use-iswitchb t))
16196 (org-pop-to-buffer-same-window
16197 (org-icompleting-read "Org buffer: "
16198 (mapcar 'list (mapcar 'buffer-name blist))
16199 nil t))))
16201 ;;; Define some older names previously used for this functionality
16202 ;;;###autoload
16203 (defalias 'org-ido-switchb 'org-switchb)
16204 ;;;###autoload
16205 (defalias 'org-iswitchb 'org-switchb)
16207 (defun org-buffer-list (&optional predicate exclude-tmp)
16208 "Return a list of Org buffers.
16209 PREDICATE can be `export', `files' or `agenda'.
16211 export restrict the list to Export buffers.
16212 files restrict the list to buffers visiting Org files.
16213 agenda restrict the list to buffers visiting agenda files.
16215 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16216 (let* ((bfn nil)
16217 (agenda-files (and (eq predicate 'agenda)
16218 (mapcar 'file-truename (org-agenda-files t))))
16219 (filter
16220 (cond
16221 ((eq predicate 'files)
16222 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
16223 ((eq predicate 'export)
16224 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16225 ((eq predicate 'agenda)
16226 (lambda (b)
16227 (with-current-buffer b
16228 (and (eq major-mode 'org-mode)
16229 (setq bfn (buffer-file-name b))
16230 (member (file-truename bfn) agenda-files)))))
16231 (t (lambda (b) (with-current-buffer b
16232 (or (eq major-mode 'org-mode)
16233 (string-match "\*Org .*Export"
16234 (buffer-name b)))))))))
16235 (delq nil
16236 (mapcar
16237 (lambda(b)
16238 (if (and (funcall filter b)
16239 (or (not exclude-tmp)
16240 (not (string-match "tmp" (buffer-name b)))))
16242 nil))
16243 (buffer-list)))))
16245 (defun org-agenda-files (&optional unrestricted archives)
16246 "Get the list of agenda files.
16247 Optional UNRESTRICTED means return the full list even if a restriction
16248 is currently in place.
16249 When ARCHIVES is t, include all archive files that are really being
16250 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16251 `org-agenda-archives-mode' is t."
16252 (let ((files
16253 (cond
16254 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16255 ((stringp org-agenda-files) (org-read-agenda-file-list))
16256 ((listp org-agenda-files) org-agenda-files)
16257 (t (error "Invalid value of `org-agenda-files'")))))
16258 (setq files (apply 'append
16259 (mapcar (lambda (f)
16260 (if (file-directory-p f)
16261 (directory-files
16262 f t org-agenda-file-regexp)
16263 (list f)))
16264 files)))
16265 (when org-agenda-skip-unavailable-files
16266 (setq files (delq nil
16267 (mapcar (function
16268 (lambda (file)
16269 (and (file-readable-p file) file)))
16270 files))))
16271 (when (or (eq archives t)
16272 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16273 (setq files (org-add-archive-files files)))
16274 files))
16276 (defun org-agenda-file-p (&optional file)
16277 "Return non-nil, if FILE is an agenda file.
16278 If FILE is omitted, use the file associated with the current
16279 buffer."
16280 (member (or file (buffer-file-name))
16281 (org-agenda-files t)))
16283 (defun org-edit-agenda-file-list ()
16284 "Edit the list of agenda files.
16285 Depending on setup, this either uses customize to edit the variable
16286 `org-agenda-files', or it visits the file that is holding the list. In the
16287 latter case, the buffer is set up in a way that saving it automatically kills
16288 the buffer and restores the previous window configuration."
16289 (interactive)
16290 (if (stringp org-agenda-files)
16291 (let ((cw (current-window-configuration)))
16292 (find-file org-agenda-files)
16293 (org-set-local 'org-window-configuration cw)
16294 (org-add-hook 'after-save-hook
16295 (lambda ()
16296 (set-window-configuration
16297 (prog1 org-window-configuration
16298 (kill-buffer (current-buffer))))
16299 (org-install-agenda-files-menu)
16300 (message "New agenda file list installed"))
16301 nil 'local)
16302 (message "%s" (substitute-command-keys
16303 "Edit list and finish with \\[save-buffer]")))
16304 (customize-variable 'org-agenda-files)))
16306 (defun org-store-new-agenda-file-list (list)
16307 "Set new value for the agenda file list and save it correctly."
16308 (if (stringp org-agenda-files)
16309 (let ((fe (org-read-agenda-file-list t)) b u)
16310 (while (setq b (find-buffer-visiting org-agenda-files))
16311 (kill-buffer b))
16312 (with-temp-file org-agenda-files
16313 (insert
16314 (mapconcat
16315 (lambda (f) ;; Keep un-expanded entries.
16316 (if (setq u (assoc f fe))
16317 (cdr u)
16319 list "\n")
16320 "\n")))
16321 (let ((org-mode-hook nil) (org-inhibit-startup t)
16322 (org-insert-mode-line-in-empty-file nil))
16323 (setq org-agenda-files list)
16324 (customize-save-variable 'org-agenda-files org-agenda-files))))
16326 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16327 "Read the list of agenda files from a file.
16328 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16329 filenames, used by `org-store-new-agenda-file-list' to write back
16330 un-expanded file names."
16331 (when (file-directory-p org-agenda-files)
16332 (error "`org-agenda-files' cannot be a single directory"))
16333 (when (stringp org-agenda-files)
16334 (with-temp-buffer
16335 (insert-file-contents org-agenda-files)
16336 (mapcar
16337 (lambda (f)
16338 (let ((e (expand-file-name (substitute-in-file-name f)
16339 org-directory)))
16340 (if pair-with-expansion
16341 (cons e f)
16342 e)))
16343 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16345 ;;;###autoload
16346 (defun org-cycle-agenda-files ()
16347 "Cycle through the files in `org-agenda-files'.
16348 If the current buffer visits an agenda file, find the next one in the list.
16349 If the current buffer does not, find the first agenda file."
16350 (interactive)
16351 (let* ((fs (org-agenda-files t))
16352 (files (append fs (list (car fs))))
16353 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16354 file)
16355 (unless files (error "No agenda files"))
16356 (catch 'exit
16357 (while (setq file (pop files))
16358 (if (equal (file-truename file) tcf)
16359 (when (car files)
16360 (find-file (car files))
16361 (throw 'exit t))))
16362 (find-file (car fs)))
16363 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16365 (defun org-agenda-file-to-front (&optional to-end)
16366 "Move/add the current file to the top of the agenda file list.
16367 If the file is not present in the list, it is added to the front. If it is
16368 present, it is moved there. With optional argument TO-END, add/move to the
16369 end of the list."
16370 (interactive "P")
16371 (let ((org-agenda-skip-unavailable-files nil)
16372 (file-alist (mapcar (lambda (x)
16373 (cons (file-truename x) x))
16374 (org-agenda-files t)))
16375 (ctf (file-truename buffer-file-name))
16376 x had)
16377 (setq x (assoc ctf file-alist) had x)
16379 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16380 (if to-end
16381 (setq file-alist (append (delq x file-alist) (list x)))
16382 (setq file-alist (cons x (delq x file-alist))))
16383 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16384 (org-install-agenda-files-menu)
16385 (message "File %s to %s of agenda file list"
16386 (if had "moved" "added") (if to-end "end" "front"))))
16388 (defun org-remove-file (&optional file)
16389 "Remove current file from the list of files in variable `org-agenda-files'.
16390 These are the files which are being checked for agenda entries.
16391 Optional argument FILE means use this file instead of the current."
16392 (interactive)
16393 (let* ((org-agenda-skip-unavailable-files nil)
16394 (file (or file buffer-file-name))
16395 (true-file (file-truename file))
16396 (afile (abbreviate-file-name file))
16397 (files (delq nil (mapcar
16398 (lambda (x)
16399 (if (equal true-file
16400 (file-truename x))
16401 nil x))
16402 (org-agenda-files t)))))
16403 (if (not (= (length files) (length (org-agenda-files t))))
16404 (progn
16405 (org-store-new-agenda-file-list files)
16406 (org-install-agenda-files-menu)
16407 (message "Removed file: %s" afile))
16408 (message "File was not in list: %s (not removed)" afile))))
16410 (defun org-file-menu-entry (file)
16411 (vector file (list 'find-file file) t))
16413 (defun org-check-agenda-file (file)
16414 "Make sure FILE exists. If not, ask user what to do."
16415 (when (not (file-exists-p file))
16416 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16417 (abbreviate-file-name file))
16418 (let ((r (downcase (read-char-exclusive))))
16419 (cond
16420 ((equal r ?r)
16421 (org-remove-file file)
16422 (throw 'nextfile t))
16423 (t (error "Abort"))))))
16425 (defun org-get-agenda-file-buffer (file)
16426 "Get a buffer visiting FILE. If the buffer needs to be created, add
16427 it to the list of buffers which might be released later."
16428 (let ((buf (org-find-base-buffer-visiting file)))
16429 (if buf
16430 buf ; just return it
16431 ;; Make a new buffer and remember it
16432 (setq buf (find-file-noselect file))
16433 (if buf (push buf org-agenda-new-buffers))
16434 buf)))
16436 (defun org-release-buffers (blist)
16437 "Release all buffers in list, asking the user for confirmation when needed.
16438 When a buffer is unmodified, it is just killed. When modified, it is saved
16439 \(if the user agrees) and then killed."
16440 (let (buf file)
16441 (while (setq buf (pop blist))
16442 (setq file (buffer-file-name buf))
16443 (when (and (buffer-modified-p buf)
16444 file
16445 (y-or-n-p (format "Save file %s? " file)))
16446 (with-current-buffer buf (save-buffer)))
16447 (kill-buffer buf))))
16449 (defun org-prepare-agenda-buffers (files)
16450 "Create buffers for all agenda files, protect archived trees and comments."
16451 (interactive)
16452 (let ((pa '(:org-archived t))
16453 (pc '(:org-comment t))
16454 (pall '(:org-archived t :org-comment t))
16455 (inhibit-read-only t)
16456 (rea (concat ":" org-archive-tag ":"))
16457 bmp file re)
16458 (save-excursion
16459 (save-restriction
16460 (while (setq file (pop files))
16461 (catch 'nextfile
16462 (if (bufferp file)
16463 (set-buffer file)
16464 (org-check-agenda-file file)
16465 (set-buffer (org-get-agenda-file-buffer file)))
16466 (widen)
16467 (setq bmp (buffer-modified-p))
16468 (org-refresh-category-properties)
16469 (setq org-todo-keywords-for-agenda
16470 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16471 (setq org-done-keywords-for-agenda
16472 (append org-done-keywords-for-agenda org-done-keywords))
16473 (setq org-todo-keyword-alist-for-agenda
16474 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16475 (setq org-drawers-for-agenda
16476 (append org-drawers-for-agenda org-drawers))
16477 (setq org-tag-alist-for-agenda
16478 (append org-tag-alist-for-agenda org-tag-alist))
16480 (save-excursion
16481 (remove-text-properties (point-min) (point-max) pall)
16482 (when org-agenda-skip-archived-trees
16483 (goto-char (point-min))
16484 (while (re-search-forward rea nil t)
16485 (if (org-on-heading-p t)
16486 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16487 (goto-char (point-min))
16488 (setq re (format org-heading-keyword-regexp-format
16489 org-comment-string))
16490 (while (re-search-forward re nil t)
16491 (add-text-properties
16492 (match-beginning 0) (org-end-of-subtree t) pc)))
16493 (set-buffer-modified-p bmp)))))
16494 (setq org-todo-keywords-for-agenda
16495 (org-uniquify org-todo-keywords-for-agenda))
16496 (setq org-todo-keyword-alist-for-agenda
16497 (org-uniquify org-todo-keyword-alist-for-agenda)
16498 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16500 ;;;; Embedded LaTeX
16502 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16503 "Keymap for the minor `org-cdlatex-mode'.")
16505 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16506 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16507 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16508 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16509 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16511 (defvar org-cdlatex-texmathp-advice-is-done nil
16512 "Flag remembering if we have applied the advice to texmathp already.")
16514 (define-minor-mode org-cdlatex-mode
16515 "Toggle the minor `org-cdlatex-mode'.
16516 This mode supports entering LaTeX environment and math in LaTeX fragments
16517 in Org-mode.
16518 \\{org-cdlatex-mode-map}"
16519 nil " OCDL" nil
16520 (when org-cdlatex-mode
16521 (require 'cdlatex)
16522 (run-hooks 'cdlatex-mode-hook)
16523 (cdlatex-compute-tables))
16524 (unless org-cdlatex-texmathp-advice-is-done
16525 (setq org-cdlatex-texmathp-advice-is-done t)
16526 (defadvice texmathp (around org-math-always-on activate)
16527 "Always return t in org-mode buffers.
16528 This is because we want to insert math symbols without dollars even outside
16529 the LaTeX math segments. If Orgmode thinks that point is actually inside
16530 an embedded LaTeX fragment, let texmathp do its job.
16531 \\[org-cdlatex-mode-map]"
16532 (interactive)
16533 (let (p)
16534 (cond
16535 ((not (eq major-mode 'org-mode)) ad-do-it)
16536 ((eq this-command 'cdlatex-math-symbol)
16537 (setq ad-return-value t
16538 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16540 (let ((p (org-inside-LaTeX-fragment-p)))
16541 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16542 (setq ad-return-value t
16543 texmathp-why '("Org-mode embedded math" . 0))
16544 (if p ad-do-it)))))))))
16546 (defun turn-on-org-cdlatex ()
16547 "Unconditionally turn on `org-cdlatex-mode'."
16548 (org-cdlatex-mode 1))
16550 (defun org-inside-LaTeX-fragment-p ()
16551 "Test if point is inside a LaTeX fragment.
16552 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16553 sequence appearing also before point.
16554 Even though the matchers for math are configurable, this function assumes
16555 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16556 delimiters are skipped when they have been removed by customization.
16557 The return value is nil, or a cons cell with the delimiter and the
16558 position of this delimiter.
16560 This function does a reasonably good job, but can locally be fooled by
16561 for example currency specifications. For example it will assume being in
16562 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16563 fragments that are properly closed, but during editing, we have to live
16564 with the uncertainty caused by missing closing delimiters. This function
16565 looks only before point, not after."
16566 (catch 'exit
16567 (let ((pos (point))
16568 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16569 (lim (progn
16570 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16571 (point)))
16572 dd-on str (start 0) m re)
16573 (goto-char pos)
16574 (when dodollar
16575 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16576 re (nth 1 (assoc "$" org-latex-regexps)))
16577 (while (string-match re str start)
16578 (cond
16579 ((= (match-end 0) (length str))
16580 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16581 ((= (match-end 0) (- (length str) 5))
16582 (throw 'exit nil))
16583 (t (setq start (match-end 0))))))
16584 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16585 (goto-char pos)
16586 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16587 (and (match-beginning 2) (throw 'exit nil))
16588 ;; count $$
16589 (while (re-search-backward "\\$\\$" lim t)
16590 (setq dd-on (not dd-on)))
16591 (goto-char pos)
16592 (if dd-on (cons "$$" m))))))
16594 (defun org-inside-latex-macro-p ()
16595 "Is point inside a LaTeX macro or its arguments?"
16596 (save-match-data
16597 (org-in-regexp
16598 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16600 (defun org-try-cdlatex-tab ()
16601 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16602 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16603 - inside a LaTeX fragment, or
16604 - after the first word in a line, where an abbreviation expansion could
16605 insert a LaTeX environment."
16606 (when org-cdlatex-mode
16607 (cond
16608 ;; Before any word on the line: No expansion possible.
16609 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
16610 ;; Just after first word on the line: Expand it. Make sure it
16611 ;; cannot happen on headlines, though.
16612 ((save-excursion
16613 (skip-chars-backward "a-zA-Z0-9*")
16614 (skip-chars-backward " \t")
16615 (and (bolp) (not (org-at-heading-p))))
16616 (cdlatex-tab) t)
16617 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
16619 (defun org-cdlatex-underscore-caret (&optional arg)
16620 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16621 Revert to the normal definition outside of these fragments."
16622 (interactive "P")
16623 (if (org-inside-LaTeX-fragment-p)
16624 (call-interactively 'cdlatex-sub-superscript)
16625 (let (org-cdlatex-mode)
16626 (call-interactively (key-binding (vector last-input-event))))))
16628 (defun org-cdlatex-math-modify (&optional arg)
16629 "Execute `cdlatex-math-modify' in LaTeX fragments.
16630 Revert to the normal definition outside of these fragments."
16631 (interactive "P")
16632 (if (org-inside-LaTeX-fragment-p)
16633 (call-interactively 'cdlatex-math-modify)
16634 (let (org-cdlatex-mode)
16635 (call-interactively (key-binding (vector last-input-event))))))
16637 (defvar org-latex-fragment-image-overlays nil
16638 "List of overlays carrying the images of latex fragments.")
16639 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16641 (defun org-remove-latex-fragment-image-overlays ()
16642 "Remove all overlays with LaTeX fragment images in current buffer."
16643 (mapc 'delete-overlay org-latex-fragment-image-overlays)
16644 (setq org-latex-fragment-image-overlays nil))
16646 (defun org-preview-latex-fragment (&optional subtree)
16647 "Preview the LaTeX fragment at point, or all locally or globally.
16648 If the cursor is in a LaTeX fragment, create the image and overlay
16649 it over the source code. If there is no fragment at point, display
16650 all fragments in the current text, from one headline to the next. With
16651 prefix SUBTREE, display all fragments in the current subtree. With a
16652 double prefix arg \\[universal-argument] \\[universal-argument], or when \
16653 the cursor is before the first headline,
16654 display all fragments in the buffer.
16655 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16656 (interactive "P")
16657 (org-remove-latex-fragment-image-overlays)
16658 (save-excursion
16659 (save-restriction
16660 (let (beg end at msg)
16661 (cond
16662 ((or (equal subtree '(16))
16663 (not (save-excursion
16664 (re-search-backward org-outline-regexp-bol nil t))))
16665 (setq beg (point-min) end (point-max)
16666 msg "Creating images for buffer...%s"))
16667 ((equal subtree '(4))
16668 (org-back-to-heading)
16669 (setq beg (point) end (org-end-of-subtree t)
16670 msg "Creating images for subtree...%s"))
16672 (if (setq at (org-inside-LaTeX-fragment-p))
16673 (goto-char (max (point-min) (- (cdr at) 2)))
16674 (org-back-to-heading))
16675 (setq beg (point) end (progn (outline-next-heading) (point))
16676 msg (if at "Creating image...%s"
16677 "Creating images for entry...%s"))))
16678 (message msg "")
16679 (narrow-to-region beg end)
16680 (goto-char beg)
16681 (org-format-latex
16682 (concat "ltxpng/" (file-name-sans-extension
16683 (file-name-nondirectory
16684 buffer-file-name)))
16685 default-directory 'overlays msg at 'forbuffer 'dvipng)
16686 (message msg "done. Use `C-c C-c' to remove images.")))))
16688 (defvar org-latex-regexps
16689 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16690 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16691 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16692 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16693 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16694 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16695 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
16696 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
16697 "Regular expressions for matching embedded LaTeX.")
16699 (defvar org-export-have-math nil) ;; dynamic scoping
16700 (defun org-format-latex (prefix &optional dir overlays msg at
16701 forbuffer processing-type)
16702 "Replace LaTeX fragments with links to an image, and produce images.
16703 Some of the options can be changed using the variable
16704 `org-format-latex-options'."
16705 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16706 (let* ((prefixnodir (file-name-nondirectory prefix))
16707 (absprefix (expand-file-name prefix dir))
16708 (todir (file-name-directory absprefix))
16709 (opt org-format-latex-options)
16710 (matchers (plist-get opt :matchers))
16711 (re-list org-latex-regexps)
16712 (org-format-latex-header-extra
16713 (plist-get (org-infile-export-plist) :latex-header-extra))
16714 (cnt 0) txt hash link beg end re e checkdir
16715 executables-checked string
16716 m n block-type block linkfile movefile ov)
16717 ;; Check the different regular expressions
16718 (while (setq e (pop re-list))
16719 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
16720 block (if block-type "\n\n" ""))
16721 (when (member m matchers)
16722 (goto-char (point-min))
16723 (while (re-search-forward re nil t)
16724 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
16725 (not (get-text-property (match-beginning n)
16726 'org-protected))
16727 (or (not overlays)
16728 (not (eq (get-char-property (match-beginning n)
16729 'org-overlay-type)
16730 'org-latex-overlay))))
16731 (setq org-export-have-math t)
16732 (cond
16733 ((eq processing-type 'verbatim)
16734 ;; Leave the text verbatim, just protect it
16735 (add-text-properties (match-beginning n) (match-end n)
16736 '(org-protected t)))
16737 ((eq processing-type 'mathjax)
16738 ;; Prepare for MathJax processing
16739 (setq string (match-string n))
16740 (if (member m '("$" "$1"))
16741 (save-excursion
16742 (delete-region (match-beginning n) (match-end n))
16743 (goto-char (match-beginning n))
16744 (insert (org-add-props (concat "\\(" (substring string 1 -1)
16745 "\\)")
16746 '(org-protected t))))
16747 (add-text-properties (match-beginning n) (match-end n)
16748 '(org-protected t))))
16749 ((eq processing-type 'dvipng)
16750 ;; Process to an image
16751 (setq txt (match-string n)
16752 beg (match-beginning n) end (match-end n)
16753 cnt (1+ cnt))
16754 (let (print-length print-level) ; make sure full list is printed
16755 (setq hash (sha1 (prin1-to-string
16756 (list org-format-latex-header
16757 org-format-latex-header-extra
16758 org-export-latex-default-packages-alist
16759 org-export-latex-packages-alist
16760 org-format-latex-options
16761 forbuffer txt)))
16762 linkfile (format "%s_%s.png" prefix hash)
16763 movefile (format "%s_%s.png" absprefix hash)))
16764 (setq link (concat block "[[file:" linkfile "]]" block))
16765 (if msg (message msg cnt))
16766 (goto-char beg)
16767 (unless checkdir ; make sure the directory exists
16768 (setq checkdir t)
16769 (or (file-directory-p todir) (make-directory todir t)))
16771 (unless executables-checked
16772 (org-check-external-command
16773 "latex" "needed to convert LaTeX fragments to images")
16774 (org-check-external-command
16775 "dvipng" "needed to convert LaTeX fragments to images")
16776 (setq executables-checked t))
16778 (unless (file-exists-p movefile)
16779 (org-create-formula-image
16780 txt movefile opt forbuffer))
16781 (if overlays
16782 (progn
16783 (mapc (lambda (o)
16784 (if (eq (overlay-get o 'org-overlay-type)
16785 'org-latex-overlay)
16786 (delete-overlay o)))
16787 (overlays-in beg end))
16788 (setq ov (make-overlay beg end))
16789 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
16790 (if (featurep 'xemacs)
16791 (progn
16792 (overlay-put ov 'invisible t)
16793 (overlay-put
16794 ov 'end-glyph
16795 (make-glyph (vector 'png :file movefile))))
16796 (overlay-put
16797 ov 'display
16798 (list 'image :type 'png :file movefile :ascent 'center)))
16799 (push ov org-latex-fragment-image-overlays)
16800 (goto-char end))
16801 (delete-region beg end)
16802 (insert (org-add-props link
16803 (list 'org-latex-src
16804 (replace-regexp-in-string
16805 "\"" "" txt)
16806 'org-latex-src-embed-type
16807 (if block-type 'paragraph 'character))))))
16808 ((eq processing-type 'mathml)
16809 ;; Process to MathML
16810 (unless executables-checked
16811 (unless (save-match-data (org-format-latex-mathml-available-p))
16812 (error "LaTeX to MathML converter not configured"))
16813 (setq executables-checked t))
16814 (setq txt (match-string n)
16815 beg (match-beginning n) end (match-end n)
16816 cnt (1+ cnt))
16817 (if msg (message msg cnt))
16818 (goto-char beg)
16819 (delete-region beg end)
16820 (insert (org-format-latex-as-mathml
16821 txt block-type prefix dir)))
16823 (error "Unknown conversion type %s for latex fragments"
16824 processing-type)))))))))
16826 (defun org-create-math-formula (latex-frag &optional mathml-file)
16827 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
16828 Use `org-latex-to-mathml-convert-command'. If the conversion is
16829 sucessful, return the portion between \"<math...> </math>\"
16830 elements otherwise return nil. When MATHML-FILE is specified,
16831 write the results in to that file. When invoked as an
16832 interactive command, prompt for LATEX-FRAG, with initial value
16833 set to the current active region and echo the results for user
16834 inspection."
16835 (interactive (list (let ((frag (when (region-active-p)
16836 (buffer-substring-no-properties
16837 (region-beginning) (region-end)))))
16838 (read-string "LaTeX Fragment: " frag nil frag))))
16839 (unless latex-frag (error "Invalid latex-frag"))
16840 (let* ((tmp-in-file (file-relative-name
16841 (make-temp-name (expand-file-name "ltxmathml-in"))))
16842 (ignore (write-region latex-frag nil tmp-in-file))
16843 (tmp-out-file (file-relative-name
16844 (make-temp-name (expand-file-name "ltxmathml-out"))))
16845 (cmd (format-spec
16846 org-latex-to-mathml-convert-command
16847 `((?j . ,(shell-quote-argument
16848 (expand-file-name org-latex-to-mathml-jar-file)))
16849 (?I . ,(shell-quote-argument tmp-in-file))
16850 (?o . ,(shell-quote-argument tmp-out-file)))))
16851 mathml shell-command-output)
16852 (when (org-called-interactively-p 'any)
16853 (unless (org-format-latex-mathml-available-p)
16854 (error "LaTeX to MathML converter not configured")))
16855 (message "Running %s" cmd)
16856 (setq shell-command-output (shell-command-to-string cmd))
16857 (setq mathml
16858 (when (file-readable-p tmp-out-file)
16859 (with-current-buffer (find-file-noselect tmp-out-file t)
16860 (goto-char (point-min))
16861 (when (re-search-forward
16862 (concat
16863 (regexp-quote
16864 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
16865 "\\(.\\|\n\\)*"
16866 (regexp-quote "</math>")) nil t)
16867 (prog1 (match-string 0) (kill-buffer))))))
16868 (cond
16869 (mathml
16870 (setq mathml
16871 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
16872 (when mathml-file
16873 (write-region mathml nil mathml-file))
16874 (when (org-called-interactively-p 'any)
16875 (message mathml)))
16876 ((message "LaTeX to MathML conversion failed")
16877 (message shell-command-output)))
16878 (delete-file tmp-in-file)
16879 (when (file-exists-p tmp-out-file)
16880 (delete-file tmp-out-file))
16881 mathml))
16883 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
16884 prefix &optional dir)
16885 "Use `org-create-math-formula' but check local cache first."
16886 (let* ((absprefix (expand-file-name prefix dir))
16887 (print-length nil) (print-level nil)
16888 (formula-id (concat
16889 "formula-"
16890 (sha1
16891 (prin1-to-string
16892 (list latex-frag
16893 org-latex-to-mathml-convert-command)))))
16894 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
16895 (formula-cache-dir (file-name-directory formula-cache)))
16897 (unless (file-directory-p formula-cache-dir)
16898 (make-directory formula-cache-dir t))
16900 (unless (file-exists-p formula-cache)
16901 (org-create-math-formula latex-frag formula-cache))
16903 (if (file-exists-p formula-cache)
16904 ;; Successful conversion. Return the link to MathML file.
16905 (org-add-props
16906 (format "[[file:%s]]" (file-relative-name formula-cache dir))
16907 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
16908 'org-latex-src-embed-type (if latex-frag-type
16909 'paragraph 'character)))
16910 ;; Failed conversion. Return the LaTeX fragment verbatim
16911 (add-text-properties
16912 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
16913 latex-frag)))
16915 ;; This function borrows from Ganesh Swami's latex2png.el
16916 (defun org-create-formula-image (string tofile options buffer)
16917 "This calls dvipng."
16918 (require 'org-latex)
16919 (let* ((tmpdir (if (featurep 'xemacs)
16920 (temp-directory)
16921 temporary-file-directory))
16922 (texfilebase (make-temp-name
16923 (expand-file-name "orgtex" tmpdir)))
16924 (texfile (concat texfilebase ".tex"))
16925 (dvifile (concat texfilebase ".dvi"))
16926 (pngfile (concat texfilebase ".png"))
16927 (fnh (if (featurep 'xemacs)
16928 (font-height (get-face-font 'default))
16929 (face-attribute 'default :height nil)))
16930 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
16931 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
16932 (fg (or (plist-get options (if buffer :foreground :html-foreground))
16933 "Black"))
16934 (bg (or (plist-get options (if buffer :background :html-background))
16935 "Transparent")))
16936 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
16937 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
16938 (with-temp-file texfile
16939 (insert (org-splice-latex-header
16940 org-format-latex-header
16941 org-export-latex-default-packages-alist
16942 org-export-latex-packages-alist t
16943 org-format-latex-header-extra))
16944 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
16945 (require 'org-latex)
16946 (org-export-latex-fix-inputenc))
16947 (let ((dir default-directory))
16948 (condition-case nil
16949 (progn
16950 (cd tmpdir)
16951 (call-process "latex" nil nil nil texfile))
16952 (error nil))
16953 (cd dir))
16954 (if (not (file-exists-p dvifile))
16955 (progn (message "Failed to create dvi file from %s" texfile) nil)
16956 (condition-case nil
16957 (call-process "dvipng" nil nil nil
16958 "-fg" fg "-bg" bg
16959 "-D" dpi
16960 ;;"-x" scale "-y" scale
16961 "-T" "tight"
16962 "-o" pngfile
16963 dvifile)
16964 (error nil))
16965 (if (not (file-exists-p pngfile))
16966 (if org-format-latex-signal-error
16967 (error "Failed to create png file from %s" texfile)
16968 (message "Failed to create png file from %s" texfile)
16969 nil)
16970 ;; Use the requested file name and clean up
16971 (copy-file pngfile tofile 'replace)
16972 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
16973 (delete-file (concat texfilebase e)))
16974 pngfile))))
16976 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
16977 "Fill a LaTeX header template TPL.
16978 In the template, the following place holders will be recognized:
16980 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
16981 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
16982 [PACKAGES] \\usepackage statements for PKG
16983 [NO-PACKAGES] do not include PKG
16984 [EXTRA] the string EXTRA
16985 [NO-EXTRA] do not include EXTRA
16987 For backward compatibility, if both the positive and the negative place
16988 holder is missing, the positive one (without the \"NO-\") will be
16989 assumed to be present at the end of the template.
16990 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
16991 EXTRA is a string.
16992 SNIPPETS-P indicates if this is run to create snippet images for HTML."
16993 (let (rpl (end ""))
16994 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
16995 (setq rpl (if (or (match-end 1) (not def-pkg))
16996 "" (org-latex-packages-to-string def-pkg snippets-p t))
16997 tpl (replace-match rpl t t tpl))
16998 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17000 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17001 (setq rpl (if (or (match-end 1) (not pkg))
17002 "" (org-latex-packages-to-string pkg snippets-p t))
17003 tpl (replace-match rpl t t tpl))
17004 (if pkg (setq end
17005 (concat end "\n"
17006 (org-latex-packages-to-string pkg snippets-p)))))
17008 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17009 (setq rpl (if (or (match-end 1) (not extra))
17010 "" (concat extra "\n"))
17011 tpl (replace-match rpl t t tpl))
17012 (if (and extra (string-match "\\S-" extra))
17013 (setq end (concat end "\n" extra))))
17015 (if (string-match "\\S-" end)
17016 (concat tpl "\n" end)
17017 tpl)))
17019 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17020 "Turn an alist of packages into a string with the \\usepackage macros."
17021 (setq pkg (mapconcat (lambda(p)
17022 (cond
17023 ((stringp p) p)
17024 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17025 (format "%% Package %s omitted" (cadr p)))
17026 ((equal "" (car p))
17027 (format "\\usepackage{%s}" (cadr p)))
17029 (format "\\usepackage[%s]{%s}"
17030 (car p) (cadr p)))))
17032 "\n"))
17033 (if newline (concat pkg "\n") pkg))
17035 (defun org-dvipng-color (attr)
17036 "Return an rgb color specification for dvipng."
17037 (apply 'format "rgb %s %s %s"
17038 (mapcar 'org-normalize-color
17039 (color-values (face-attribute 'default attr nil)))))
17041 (defun org-normalize-color (value)
17042 "Return string to be used as color value for an RGB component."
17043 (format "%g" (/ value 65535.0)))
17045 ;; Image display
17048 (defvar org-inline-image-overlays nil)
17049 (make-variable-buffer-local 'org-inline-image-overlays)
17051 (defun org-toggle-inline-images (&optional include-linked)
17052 "Toggle the display of inline images.
17053 INCLUDE-LINKED is passed to `org-display-inline-images'."
17054 (interactive "P")
17055 (if org-inline-image-overlays
17056 (progn
17057 (org-remove-inline-images)
17058 (message "Inline image display turned off"))
17059 (org-display-inline-images include-linked)
17060 (if org-inline-image-overlays
17061 (message "%d images displayed inline"
17062 (length org-inline-image-overlays))
17063 (message "No images to display inline"))))
17065 (defun org-display-inline-images (&optional include-linked refresh beg end)
17066 "Display inline images.
17067 Normally only links without a description part are inlined, because this
17068 is how it will work for export. When INCLUDE-LINKED is set, also links
17069 with a description part will be inlined. This can be nice for a quick
17070 look at those images, but it does not reflect what exported files will look
17071 like.
17072 When REFRESH is set, refresh existing images between BEG and END.
17073 This will create new image displays only if necessary.
17074 BEG and END default to the buffer boundaries."
17075 (interactive "P")
17076 (unless refresh
17077 (org-remove-inline-images)
17078 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17079 (save-excursion
17080 (save-restriction
17081 (widen)
17082 (setq beg (or beg (point-min)) end (or end (point-max)))
17083 (goto-char (point-min))
17084 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17085 (substring (org-image-file-name-regexp) 0 -2)
17086 "\\)\\]" (if include-linked "" "\\]")))
17087 old file ov img)
17088 (while (re-search-forward re end t)
17089 (setq old (get-char-property-and-overlay (match-beginning 1)
17090 'org-image-overlay))
17091 (setq file (expand-file-name
17092 (concat (or (match-string 3) "") (match-string 4))))
17093 (when (file-exists-p file)
17094 (if (and (car-safe old) refresh)
17095 (image-refresh (overlay-get (cdr old) 'display))
17096 (setq img (save-match-data (create-image file)))
17097 (when img
17098 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17099 (overlay-put ov 'display img)
17100 (overlay-put ov 'face 'default)
17101 (overlay-put ov 'org-image-overlay t)
17102 (overlay-put ov 'modification-hooks
17103 (list 'org-display-inline-modification-hook))
17104 (push ov org-inline-image-overlays)))))))))
17106 (defun org-display-inline-modification-hook (ov after beg end &optional len)
17107 "Remove inline-display overlay if a corresponding region is modified."
17108 (let ((inhibit-modification-hooks t))
17109 (when (and ov after)
17110 (delete ov org-inline-image-overlays)
17111 (delete-overlay ov))))
17113 (defun org-remove-inline-images ()
17114 "Remove inline display of images."
17115 (interactive)
17116 (mapc 'delete-overlay org-inline-image-overlays)
17117 (setq org-inline-image-overlays nil))
17119 ;;;; Key bindings
17121 ;; Outline functions from `outline-mode-prefix-map'
17122 ;; that can be remapped in Org:
17123 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17124 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17125 (define-key org-mode-map [remap outline-forward-same-level]
17126 'org-forward-same-level)
17127 (define-key org-mode-map [remap outline-backward-same-level]
17128 'org-backward-same-level)
17129 (define-key org-mode-map [remap show-branches]
17130 'org-kill-note-or-show-branches)
17131 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17132 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17133 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17135 ;; Outline functions from `outline-mode-prefix-map'
17136 ;; that can not be remapped in Org:
17137 ;; - the column "key binding" shows whether the Outline function is still
17138 ;; available in Org mode on the same key that it has been bound to in
17139 ;; Outline mode:
17140 ;; - "overridden": key used for a different functionality in Org mode
17141 ;; - else: key still bound to the same Outline function in Org mode
17142 ;; | Outline function | key binding | Org replacement |
17143 ;; |------------------------------------+-------------+-----------------------|
17144 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17145 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17146 ;; | `show-children' | `C-c C-i' | visibility cycling |
17147 ;; | `hide-subtree' | overridden | visibility cycling |
17148 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17149 ;; | `hide-body' | overridden | no replacement |
17150 ;; | `show-all' | overridden | no replacement |
17151 ;; | `hide-entry' | overridden | visibility cycling |
17152 ;; | `show-entry' | overridden | no replacement |
17153 ;; | `hide-leaves' | overridden | no replacement |
17154 ;; | `hide-sublevels' | overridden | no replacement |
17155 ;; | `hide-other' | overridden | no replacement |
17156 ;; | `outline-move-subtree-up' | `C-c C-^' | better: org-shiftup |
17157 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17159 ;; Make `C-c C-x' a prefix key
17160 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17162 ;; TAB key with modifiers
17163 (org-defkey org-mode-map "\C-i" 'org-cycle)
17164 (org-defkey org-mode-map [(tab)] 'org-cycle)
17165 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17166 (org-defkey org-mode-map [(meta tab)] 'pcomplete)
17167 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17168 (org-defkey org-mode-map "\M-\C-i" 'pcomplete)
17169 ;; The following line is necessary under Suse GNU/Linux
17170 (unless (featurep 'xemacs)
17171 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17172 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17173 (define-key org-mode-map [backtab] 'org-shifttab)
17175 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17176 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17177 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17179 ;; Cursor keys with modifiers
17180 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17181 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17182 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17183 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17185 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17186 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17187 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17188 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17190 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17191 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17192 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17193 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17195 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17196 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17197 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17198 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17200 ;; Babel keys
17201 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17202 (mapc (lambda (pair)
17203 (define-key org-babel-map (car pair) (cdr pair)))
17204 org-babel-key-bindings)
17206 ;;; Extra keys for tty access.
17207 ;; We only set them when really needed because otherwise the
17208 ;; menus don't show the simple keys
17210 (when (or org-use-extra-keys
17211 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17212 (not window-system))
17213 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17214 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17215 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17216 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17217 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17218 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17219 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17220 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17221 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17222 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17223 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17224 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17225 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17226 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17227 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17228 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17229 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17230 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17231 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17232 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17233 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17234 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17235 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17236 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17237 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17238 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17239 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17240 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17242 ;; All the other keys
17244 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17245 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17246 (if (boundp 'narrow-map)
17247 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17248 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17249 (if (boundp 'narrow-map)
17250 (org-defkey narrow-map "b" 'org-narrow-to-block)
17251 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17252 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
17253 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
17254 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17255 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17256 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17257 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17258 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17259 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17260 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17261 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17262 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17263 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17264 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17265 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17266 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17267 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17268 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17269 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17270 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17271 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17272 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17273 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17274 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
17275 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
17276 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
17277 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
17278 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
17279 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
17280 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
17281 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
17282 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17283 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17284 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17285 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17286 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
17287 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
17288 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17289 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
17290 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
17291 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
17292 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
17293 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17294 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
17295 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
17296 (org-defkey org-mode-map "\C-c^" 'org-sort)
17297 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
17298 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
17299 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
17300 (org-defkey org-mode-map "\C-m" 'org-return)
17301 (org-defkey org-mode-map "\C-j" 'org-return-indent)
17302 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
17303 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
17304 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
17305 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
17306 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
17307 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
17308 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
17309 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
17310 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
17311 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
17312 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
17313 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
17314 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
17315 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
17316 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
17317 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
17318 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
17319 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
17320 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
17321 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
17322 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
17324 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
17325 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
17326 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
17327 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
17329 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
17330 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
17331 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
17332 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
17333 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
17334 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
17335 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
17336 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
17337 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
17338 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
17339 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
17340 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
17341 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
17342 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
17343 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
17344 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
17345 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
17346 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
17348 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
17349 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
17350 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
17351 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
17352 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
17354 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
17356 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
17358 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
17359 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
17361 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
17364 (when (featurep 'xemacs)
17365 (org-defkey org-mode-map 'button3 'popup-mode-menu))
17368 (defconst org-speed-commands-default
17370 ("Outline Navigation")
17371 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
17372 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
17373 ("f" . (org-speed-move-safe 'org-forward-same-level))
17374 ("b" . (org-speed-move-safe 'org-backward-same-level))
17375 ("u" . (org-speed-move-safe 'outline-up-heading))
17376 ("j" . org-goto)
17377 ("g" . (org-refile t))
17378 ("Outline Visibility")
17379 ("c" . org-cycle)
17380 ("C" . org-shifttab)
17381 (" " . org-display-outline-path)
17382 ("Outline Structure Editing")
17383 ("U" . org-shiftmetaup)
17384 ("D" . org-shiftmetadown)
17385 ("r" . org-metaright)
17386 ("l" . org-metaleft)
17387 ("R" . org-shiftmetaright)
17388 ("L" . org-shiftmetaleft)
17389 ("i" . (progn (forward-char 1) (call-interactively
17390 'org-insert-heading-respect-content)))
17391 ("^" . org-sort)
17392 ("w" . org-refile)
17393 ("a" . org-archive-subtree-default-with-confirmation)
17394 ("." . org-mark-subtree)
17395 ("Clock Commands")
17396 ("I" . org-clock-in)
17397 ("O" . org-clock-out)
17398 ("Meta Data Editing")
17399 ("t" . org-todo)
17400 ("0" . (org-priority ?\ ))
17401 ("1" . (org-priority ?A))
17402 ("2" . (org-priority ?B))
17403 ("3" . (org-priority ?C))
17404 (";" . org-set-tags-command)
17405 ("e" . org-set-effort)
17406 ("Agenda Views etc")
17407 ("v" . org-agenda)
17408 ("/" . org-sparse-tree)
17409 ("Misc")
17410 ("o" . org-open-at-point)
17411 ("?" . org-speed-command-help)
17412 ("<" . (org-agenda-set-restriction-lock 'subtree))
17413 (">" . (org-agenda-remove-restriction-lock))
17415 "The default speed commands.")
17417 (defun org-print-speed-command (e)
17418 (if (> (length (car e)) 1)
17419 (progn
17420 (princ "\n")
17421 (princ (car e))
17422 (princ "\n")
17423 (princ (make-string (length (car e)) ?-))
17424 (princ "\n"))
17425 (princ (car e))
17426 (princ " ")
17427 (if (symbolp (cdr e))
17428 (princ (symbol-name (cdr e)))
17429 (prin1 (cdr e)))
17430 (princ "\n")))
17432 (defun org-speed-command-help ()
17433 "Show the available speed commands."
17434 (interactive)
17435 (if (not org-use-speed-commands)
17436 (error "Speed commands are not activated, customize `org-use-speed-commands'")
17437 (with-output-to-temp-buffer "*Help*"
17438 (princ "User-defined Speed commands\n===========================\n")
17439 (mapc 'org-print-speed-command org-speed-commands-user)
17440 (princ "\n")
17441 (princ "Built-in Speed commands\n=======================\n")
17442 (mapc 'org-print-speed-command org-speed-commands-default))
17443 (with-current-buffer "*Help*"
17444 (setq truncate-lines t))))
17446 (defun org-speed-move-safe (cmd)
17447 "Execute CMD, but make sure that the cursor always ends up in a headline.
17448 If not, return to the original position and throw an error."
17449 (interactive)
17450 (let ((pos (point)))
17451 (call-interactively cmd)
17452 (unless (and (bolp) (org-on-heading-p))
17453 (goto-char pos)
17454 (error "Boundary reached while executing %s" cmd))))
17456 (defvar org-self-insert-command-undo-counter 0)
17458 (defvar org-table-auto-blank-field) ; defined in org-table.el
17459 (defvar org-speed-command nil)
17461 (defun org-speed-command-default-hook (keys)
17462 "Hook for activating single-letter speed commands.
17463 `org-speed-commands-default' specifies a minimal command set.
17464 Use `org-speed-commands-user' for further customization."
17465 (when (or (and (bolp) (looking-at org-outline-regexp))
17466 (and (functionp org-use-speed-commands)
17467 (funcall org-use-speed-commands)))
17468 (cdr (assoc keys (append org-speed-commands-user
17469 org-speed-commands-default)))))
17471 (defun org-babel-speed-command-hook (keys)
17472 "Hook for activating single-letter code block commands."
17473 (when (and (bolp) (looking-at org-babel-src-block-regexp))
17474 (cdr (assoc keys org-babel-key-bindings))))
17476 (defcustom org-speed-command-hook
17477 '(org-speed-command-default-hook org-babel-speed-command-hook)
17478 "Hook for activating speed commands at strategic locations.
17479 Hook functions are called in sequence until a valid handler is
17480 found.
17482 Each hook takes a single argument, a user-pressed command key
17483 which is also a `self-insert-command' from the global map.
17485 Within the hook, examine the cursor position and the command key
17486 and return nil or a valid handler as appropriate. Handler could
17487 be one of an interactive command, a function, or a form.
17489 Set `org-use-speed-commands' to non-nil value to enable this
17490 hook. The default setting is `org-speed-command-default-hook'."
17491 :group 'org-structure
17492 :type 'hook)
17494 (defun org-self-insert-command (N)
17495 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
17496 If the cursor is in a table looking at whitespace, the whitespace is
17497 overwritten, and the table is not marked as requiring realignment."
17498 (interactive "p")
17499 (org-check-before-invisible-edit 'insert)
17500 (cond
17501 ((and org-use-speed-commands
17502 (setq org-speed-command
17503 (run-hook-with-args-until-success
17504 'org-speed-command-hook (this-command-keys))))
17505 (cond
17506 ((commandp org-speed-command)
17507 (setq this-command org-speed-command)
17508 (call-interactively org-speed-command))
17509 ((functionp org-speed-command)
17510 (funcall org-speed-command))
17511 ((and org-speed-command (listp org-speed-command))
17512 (eval org-speed-command))
17513 (t (let (org-use-speed-commands)
17514 (call-interactively 'org-self-insert-command)))))
17515 ((and
17516 (org-table-p)
17517 (progn
17518 ;; check if we blank the field, and if that triggers align
17519 (and (featurep 'org-table) org-table-auto-blank-field
17520 (member last-command
17521 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
17522 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
17523 ;; got extra space, this field does not determine column width
17524 (let (org-table-may-need-update) (org-table-blank-field))
17525 ;; no extra space, this field may determine column width
17526 (org-table-blank-field)))
17528 (eq N 1)
17529 (looking-at "[^|\n]* |"))
17530 (let (org-table-may-need-update)
17531 (goto-char (1- (match-end 0)))
17532 (delete-char -1)
17533 (goto-char (match-beginning 0))
17534 (self-insert-command N)))
17536 (setq org-table-may-need-update t)
17537 (self-insert-command N)
17538 (org-fix-tags-on-the-fly)
17539 (if org-self-insert-cluster-for-undo
17540 (if (not (eq last-command 'org-self-insert-command))
17541 (setq org-self-insert-command-undo-counter 1)
17542 (if (>= org-self-insert-command-undo-counter 20)
17543 (setq org-self-insert-command-undo-counter 1)
17544 (and (> org-self-insert-command-undo-counter 0)
17545 buffer-undo-list (listp buffer-undo-list)
17546 (not (cadr buffer-undo-list)) ; remove nil entry
17547 (setcdr buffer-undo-list (cddr buffer-undo-list)))
17548 (setq org-self-insert-command-undo-counter
17549 (1+ org-self-insert-command-undo-counter))))))))
17551 (defun org-check-before-invisible-edit (kind)
17552 "Check is editing if kind KIND would be dangerous with invisible text around.
17553 The detailed reaction depends on the user option `org-catch-invisible-edits'."
17554 ;; First, try to get out of here as quickly as possible, to reduce overhead
17555 (if (and org-catch-invisible-edits
17556 (or (not (boundp 'visible-mode)) (not visible-mode))
17557 (or (get-char-property (point) 'invisible)
17558 (get-char-property (max (point-min) (1- (point))) 'invisible)))
17559 ;; OK, we need to take a closer look
17560 (let* ((invisible-at-point (get-char-property (point) 'invisible))
17561 (invisible-before-point (if (bobp) nil (get-char-property
17562 (1- (point)) 'invisible)))
17563 (border-and-ok-direction
17565 ;; Check if we are acting predictably before invisible text
17566 (and invisible-at-point (not invisible-before-point)
17567 (memq kind '(insert delete-backward)))
17568 ;; Check if we are acting predictably after invisible text
17569 ;; This works not well, and I have turned it off. It seems
17570 ;; better to always show and stop after invisible text.
17571 ;; (and (not invisible-at-point) invisible-before-point
17572 ;; (memq kind '(insert delete)))
17575 (when (or (memq invisible-at-point '(outline org-hide-block))
17576 (memq invisible-before-point '(outline org-hide-block)))
17577 (if (eq org-catch-invisible-edits 'error)
17578 (error "Editing in invisible areas is prohibited - make visible first"))
17579 ;; Make the area visible
17580 (save-excursion
17581 (if invisible-before-point
17582 (goto-char (previous-single-char-property-change
17583 (point) 'invisible)))
17584 (org-cycle))
17585 (cond
17586 ((eq org-catch-invisible-edits 'show)
17587 ;; That's it, we do the edit after showing
17588 (message
17589 "Unfolding invisible region around point before editing")
17590 (sit-for 1))
17591 ((and (eq org-catch-invisible-edits 'smart)
17592 border-and-ok-direction)
17593 (message "Unfolding invisible region around point before editing"))
17595 ;; Don't do the edit, make the user repeat it in full visibility
17596 (error "Edit in invisible region aborted, repeat to confirm with text visible")))))))
17598 (defun org-fix-tags-on-the-fly ()
17599 (when (and (equal (char-after (point-at-bol)) ?*)
17600 (org-on-heading-p))
17601 (org-align-tags-here org-tags-column)))
17603 (defun org-delete-backward-char (N)
17604 "Like `delete-backward-char', insert whitespace at field end in tables.
17605 When deleting backwards, in tables this function will insert whitespace in
17606 front of the next \"|\" separator, to keep the table aligned. The table will
17607 still be marked for re-alignment if the field did fill the entire column,
17608 because, in this case the deletion might narrow the column."
17609 (interactive "p")
17610 (org-check-before-invisible-edit 'delete-backward)
17611 (if (and (org-table-p)
17612 (eq N 1)
17613 (string-match "|" (buffer-substring (point-at-bol) (point)))
17614 (looking-at ".*?|"))
17615 (let ((pos (point))
17616 (noalign (looking-at "[^|\n\r]* |"))
17617 (c org-table-may-need-update))
17618 (backward-delete-char N)
17619 (if (not overwrite-mode)
17620 (progn
17621 (skip-chars-forward "^|")
17622 (insert " ")
17623 (goto-char (1- pos))))
17624 ;; noalign: if there were two spaces at the end, this field
17625 ;; does not determine the width of the column.
17626 (if noalign (setq org-table-may-need-update c)))
17627 (backward-delete-char N)
17628 (org-fix-tags-on-the-fly)))
17630 (defun org-delete-char (N)
17631 "Like `delete-char', but insert whitespace at field end in tables.
17632 When deleting characters, in tables this function will insert whitespace in
17633 front of the next \"|\" separator, to keep the table aligned. The table will
17634 still be marked for re-alignment if the field did fill the entire column,
17635 because, in this case the deletion might narrow the column."
17636 (interactive "p")
17637 (org-check-before-invisible-edit 'delete)
17638 (if (and (org-table-p)
17639 (not (bolp))
17640 (not (= (char-after) ?|))
17641 (eq N 1))
17642 (if (looking-at ".*?|")
17643 (let ((pos (point))
17644 (noalign (looking-at "[^|\n\r]* |"))
17645 (c org-table-may-need-update))
17646 (replace-match (concat
17647 (substring (match-string 0) 1 -1)
17648 " |"))
17649 (goto-char pos)
17650 ;; noalign: if there were two spaces at the end, this field
17651 ;; does not determine the width of the column.
17652 (if noalign (setq org-table-may-need-update c)))
17653 (delete-char N))
17654 (delete-char N)
17655 (org-fix-tags-on-the-fly)))
17657 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
17658 (put 'org-self-insert-command 'delete-selection t)
17659 (put 'orgtbl-self-insert-command 'delete-selection t)
17660 (put 'org-delete-char 'delete-selection 'supersede)
17661 (put 'org-delete-backward-char 'delete-selection 'supersede)
17662 (put 'org-yank 'delete-selection 'yank)
17664 ;; Make `flyspell-mode' delay after some commands
17665 (put 'org-self-insert-command 'flyspell-delayed t)
17666 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
17667 (put 'org-delete-char 'flyspell-delayed t)
17668 (put 'org-delete-backward-char 'flyspell-delayed t)
17670 ;; Make pabbrev-mode expand after org-mode commands
17671 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
17672 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
17674 ;; How to do this: Measure non-white length of current string
17675 ;; If equal to column width, we should realign.
17677 (defun org-remap (map &rest commands)
17678 "In MAP, remap the functions given in COMMANDS.
17679 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
17680 (let (new old)
17681 (while commands
17682 (setq old (pop commands) new (pop commands))
17683 (if (fboundp 'command-remapping)
17684 (org-defkey map (vector 'remap old) new)
17685 (substitute-key-definition old new map global-map)))))
17687 (when (eq org-enable-table-editor 'optimized)
17688 ;; If the user wants maximum table support, we need to hijack
17689 ;; some standard editing functions
17690 (org-remap org-mode-map
17691 'self-insert-command 'org-self-insert-command
17692 'delete-char 'org-delete-char
17693 'delete-backward-char 'org-delete-backward-char)
17694 (org-defkey org-mode-map "|" 'org-force-self-insert))
17696 (defvar org-ctrl-c-ctrl-c-hook nil
17697 "Hook for functions attaching themselves to `C-c C-c'.
17699 This can be used to add additional functionality to the C-c C-c
17700 key which executes context-dependent commands. This hook is run
17701 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
17702 run after the last test.
17704 Each function will be called with no arguments. The function
17705 must check if the context is appropriate for it to act. If yes,
17706 it should do its thing and then return a non-nil value. If the
17707 context is wrong, just do nothing and return nil.")
17709 (defvar org-ctrl-c-ctrl-c-final-hook nil
17710 "Hook for functions attaching themselves to `C-c C-c'.
17712 This can be used to add additional functionality to the C-c C-c
17713 key which executes context-dependent commands. This hook is run
17714 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
17715 before the first test.
17717 Each function will be called with no arguments. The function
17718 must check if the context is appropriate for it to act. If yes,
17719 it should do its thing and then return a non-nil value. If the
17720 context is wrong, just do nothing and return nil.")
17722 (defvar org-tab-first-hook nil
17723 "Hook for functions to attach themselves to TAB.
17724 See `org-ctrl-c-ctrl-c-hook' for more information.
17725 This hook runs as the first action when TAB is pressed, even before
17726 `org-cycle' messes around with the `outline-regexp' to cater for
17727 inline tasks and plain list item folding.
17728 If any function in this hook returns t, any other actions that
17729 would have been caused by TAB (such as table field motion or visibility
17730 cycling) will not occur.")
17732 (defvar org-tab-after-check-for-table-hook nil
17733 "Hook for functions to attach themselves to TAB.
17734 See `org-ctrl-c-ctrl-c-hook' for more information.
17735 This hook runs after it has been established that the cursor is not in a
17736 table, but before checking if the cursor is in a headline or if global cycling
17737 should be done.
17738 If any function in this hook returns t, not other actions like visibility
17739 cycling will be done.")
17741 (defvar org-tab-after-check-for-cycling-hook nil
17742 "Hook for functions to attach themselves to TAB.
17743 See `org-ctrl-c-ctrl-c-hook' for more information.
17744 This hook runs after it has been established that not table field motion and
17745 not visibility should be done because of current context. This is probably
17746 the place where a package like yasnippets can hook in.")
17748 (defvar org-tab-before-tab-emulation-hook nil
17749 "Hook for functions to attach themselves to TAB.
17750 See `org-ctrl-c-ctrl-c-hook' for more information.
17751 This hook runs after every other options for TAB have been exhausted, but
17752 before indentation and \t insertion takes place.")
17754 (defvar org-metaleft-hook nil
17755 "Hook for functions attaching themselves to `M-left'.
17756 See `org-ctrl-c-ctrl-c-hook' for more information.")
17757 (defvar org-metaright-hook nil
17758 "Hook for functions attaching themselves to `M-right'.
17759 See `org-ctrl-c-ctrl-c-hook' for more information.")
17760 (defvar org-metaup-hook nil
17761 "Hook for functions attaching themselves to `M-up'.
17762 See `org-ctrl-c-ctrl-c-hook' for more information.")
17763 (defvar org-metadown-hook nil
17764 "Hook for functions attaching themselves to `M-down'.
17765 See `org-ctrl-c-ctrl-c-hook' for more information.")
17766 (defvar org-shiftmetaleft-hook nil
17767 "Hook for functions attaching themselves to `M-S-left'.
17768 See `org-ctrl-c-ctrl-c-hook' for more information.")
17769 (defvar org-shiftmetaright-hook nil
17770 "Hook for functions attaching themselves to `M-S-right'.
17771 See `org-ctrl-c-ctrl-c-hook' for more information.")
17772 (defvar org-shiftmetaup-hook nil
17773 "Hook for functions attaching themselves to `M-S-up'.
17774 See `org-ctrl-c-ctrl-c-hook' for more information.")
17775 (defvar org-shiftmetadown-hook nil
17776 "Hook for functions attaching themselves to `M-S-down'.
17777 See `org-ctrl-c-ctrl-c-hook' for more information.")
17778 (defvar org-metareturn-hook nil
17779 "Hook for functions attaching themselves to `M-RET'.
17780 See `org-ctrl-c-ctrl-c-hook' for more information.")
17781 (defvar org-shiftup-hook nil
17782 "Hook for functions attaching themselves to `S-up'.
17783 See `org-ctrl-c-ctrl-c-hook' for more information.")
17784 (defvar org-shiftup-final-hook nil
17785 "Hook for functions attaching themselves to `S-up'.
17786 This one runs after all other options except shift-select have been excluded.
17787 See `org-ctrl-c-ctrl-c-hook' for more information.")
17788 (defvar org-shiftdown-hook nil
17789 "Hook for functions attaching themselves to `S-down'.
17790 See `org-ctrl-c-ctrl-c-hook' for more information.")
17791 (defvar org-shiftdown-final-hook nil
17792 "Hook for functions attaching themselves to `S-down'.
17793 This one runs after all other options except shift-select have been excluded.
17794 See `org-ctrl-c-ctrl-c-hook' for more information.")
17795 (defvar org-shiftleft-hook nil
17796 "Hook for functions attaching themselves to `S-left'.
17797 See `org-ctrl-c-ctrl-c-hook' for more information.")
17798 (defvar org-shiftleft-final-hook nil
17799 "Hook for functions attaching themselves to `S-left'.
17800 This one runs after all other options except shift-select have been excluded.
17801 See `org-ctrl-c-ctrl-c-hook' for more information.")
17802 (defvar org-shiftright-hook nil
17803 "Hook for functions attaching themselves to `S-right'.
17804 See `org-ctrl-c-ctrl-c-hook' for more information.")
17805 (defvar org-shiftright-final-hook nil
17806 "Hook for functions attaching themselves to `S-right'.
17807 This one runs after all other options except shift-select have been excluded.
17808 See `org-ctrl-c-ctrl-c-hook' for more information.")
17810 (defun org-modifier-cursor-error ()
17811 "Throw an error, a modified cursor command was applied in wrong context."
17812 (error "This command is active in special context like tables, headlines or items"))
17814 (defun org-shiftselect-error ()
17815 "Throw an error because Shift-Cursor command was applied in wrong context."
17816 (if (and (boundp 'shift-select-mode) shift-select-mode)
17817 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
17818 (error "This command works only in special context like headlines or timestamps")))
17820 (defun org-call-for-shift-select (cmd)
17821 (let ((this-command-keys-shift-translated t))
17822 (call-interactively cmd)))
17824 (defun org-shifttab (&optional arg)
17825 "Global visibility cycling or move to previous table field.
17826 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
17827 on context.
17828 See the individual commands for more information."
17829 (interactive "P")
17830 (cond
17831 ((org-at-table-p) (call-interactively 'org-table-previous-field))
17832 ((integerp arg)
17833 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
17834 (message "Content view to level: %d" arg)
17835 (org-content (prefix-numeric-value arg2))
17836 (setq org-cycle-global-status 'overview)))
17837 (t (call-interactively 'org-global-cycle))))
17839 (defun org-shiftmetaleft ()
17840 "Promote subtree or delete table column.
17841 Calls `org-promote-subtree', `org-outdent-item',
17842 or `org-table-delete-column', depending on context.
17843 See the individual commands for more information."
17844 (interactive)
17845 (cond
17846 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
17847 ((org-at-table-p) (call-interactively 'org-table-delete-column))
17848 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
17849 ((org-at-item-p) (call-interactively 'org-outdent-item-tree))
17850 (t (org-modifier-cursor-error))))
17852 (defun org-shiftmetaright ()
17853 "Demote subtree or insert table column.
17854 Calls `org-demote-subtree', `org-indent-item',
17855 or `org-table-insert-column', depending on context.
17856 See the individual commands for more information."
17857 (interactive)
17858 (cond
17859 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
17860 ((org-at-table-p) (call-interactively 'org-table-insert-column))
17861 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
17862 ((org-at-item-p) (call-interactively 'org-indent-item-tree))
17863 (t (org-modifier-cursor-error))))
17865 (defun org-shiftmetaup (&optional arg)
17866 "Move subtree up or kill table row.
17867 Calls `org-move-subtree-up' or `org-table-kill-row' or
17868 `org-move-item-up' depending on context. See the individual commands
17869 for more information."
17870 (interactive "P")
17871 (cond
17872 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
17873 ((org-at-table-p) (call-interactively 'org-table-kill-row))
17874 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17875 ((org-at-item-p) (call-interactively 'org-move-item-up))
17876 (t (org-modifier-cursor-error))))
17878 (defun org-shiftmetadown (&optional arg)
17879 "Move subtree down or insert table row.
17880 Calls `org-move-subtree-down' or `org-table-insert-row' or
17881 `org-move-item-down', depending on context. See the individual
17882 commands for more information."
17883 (interactive "P")
17884 (cond
17885 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
17886 ((org-at-table-p) (call-interactively 'org-table-insert-row))
17887 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17888 ((org-at-item-p) (call-interactively 'org-move-item-down))
17889 (t (org-modifier-cursor-error))))
17891 (defsubst org-hidden-tree-error ()
17892 (error
17893 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
17895 (defun org-metaleft (&optional arg)
17896 "Promote heading or move table column to left.
17897 Calls `org-do-promote' or `org-table-move-column', depending on context.
17898 With no specific context, calls the Emacs default `backward-word'.
17899 See the individual commands for more information."
17900 (interactive "P")
17901 (cond
17902 ((run-hook-with-args-until-success 'org-metaleft-hook))
17903 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
17904 ((org-with-limited-levels
17905 (or (org-on-heading-p)
17906 (and (org-region-active-p)
17907 (save-excursion
17908 (goto-char (region-beginning))
17909 (org-on-heading-p)))))
17910 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17911 (call-interactively 'org-do-promote))
17912 ;; At an inline task.
17913 ((org-on-heading-p)
17914 (call-interactively 'org-inlinetask-promote))
17915 ((or (org-at-item-p)
17916 (and (org-region-active-p)
17917 (save-excursion
17918 (goto-char (region-beginning))
17919 (org-at-item-p))))
17920 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17921 (call-interactively 'org-outdent-item))
17922 (t (call-interactively 'backward-word))))
17924 (defun org-metaright (&optional arg)
17925 "Demote subtree or move table column to right.
17926 Calls `org-do-demote' or `org-table-move-column', depending on context.
17927 With no specific context, calls the Emacs default `forward-word'.
17928 See the individual commands for more information."
17929 (interactive "P")
17930 (cond
17931 ((run-hook-with-args-until-success 'org-metaright-hook))
17932 ((org-at-table-p) (call-interactively 'org-table-move-column))
17933 ((org-with-limited-levels
17934 (or (org-on-heading-p)
17935 (and (org-region-active-p)
17936 (save-excursion
17937 (goto-char (region-beginning))
17938 (org-on-heading-p)))))
17939 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17940 (call-interactively 'org-do-demote))
17941 ;; At an inline task.
17942 ((org-on-heading-p)
17943 (call-interactively 'org-inlinetask-demote))
17944 ((or (org-at-item-p)
17945 (and (org-region-active-p)
17946 (save-excursion
17947 (goto-char (region-beginning))
17948 (org-at-item-p))))
17949 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17950 (call-interactively 'org-indent-item))
17951 (t (call-interactively 'forward-word))))
17953 (defun org-check-for-hidden (what)
17954 "Check if there are hidden headlines/items in the current visual line.
17955 WHAT can be either `headlines' or `items'. If the current line is
17956 an outline or item heading and it has a folded subtree below it,
17957 this function returns t, nil otherwise."
17958 (let ((re (cond
17959 ((eq what 'headlines) org-outline-regexp-bol)
17960 ((eq what 'items) (org-item-beginning-re))
17961 (t (error "This should not happen"))))
17962 beg end)
17963 (save-excursion
17964 (catch 'exit
17965 (unless (org-region-active-p)
17966 (setq beg (point-at-bol))
17967 (beginning-of-line 2)
17968 (while (and (not (eobp)) ;; this is like `next-line'
17969 (get-char-property (1- (point)) 'invisible))
17970 (beginning-of-line 2))
17971 (setq end (point))
17972 (goto-char beg)
17973 (goto-char (point-at-eol))
17974 (setq end (max end (point)))
17975 (while (re-search-forward re end t)
17976 (if (get-char-property (match-beginning 0) 'invisible)
17977 (throw 'exit t))))
17978 nil))))
17980 (defun org-metaup (&optional arg)
17981 "Move subtree up or move table row up.
17982 Calls `org-move-subtree-up' or `org-table-move-row' or
17983 `org-move-item-up', depending on context. See the individual commands
17984 for more information."
17985 (interactive "P")
17986 (cond
17987 ((run-hook-with-args-until-success 'org-metaup-hook))
17988 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
17989 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17990 ((org-at-item-p) (call-interactively 'org-move-item-up))
17991 (t (transpose-lines 1) (beginning-of-line -1))))
17993 (defun org-metadown (&optional arg)
17994 "Move subtree down or move table row down.
17995 Calls `org-move-subtree-down' or `org-table-move-row' or
17996 `org-move-item-down', depending on context. See the individual
17997 commands for more information."
17998 (interactive "P")
17999 (cond
18000 ((run-hook-with-args-until-success 'org-metadown-hook))
18001 ((org-at-table-p) (call-interactively 'org-table-move-row))
18002 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
18003 ((org-at-item-p) (call-interactively 'org-move-item-down))
18004 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
18006 (defun org-shiftup (&optional arg)
18007 "Increase item in timestamp or increase priority of current headline.
18008 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18009 depending on context. See the individual commands for more information."
18010 (interactive "P")
18011 (cond
18012 ((run-hook-with-args-until-success 'org-shiftup-hook))
18013 ((and org-support-shift-select (org-region-active-p))
18014 (org-call-for-shift-select 'previous-line))
18015 ((org-at-timestamp-p t)
18016 (call-interactively (if org-edit-timestamp-down-means-later
18017 'org-timestamp-down 'org-timestamp-up)))
18018 ((and (not (eq org-support-shift-select 'always))
18019 org-enable-priority-commands
18020 (org-on-heading-p))
18021 (call-interactively 'org-priority-up))
18022 ((and (not org-support-shift-select) (org-at-item-p))
18023 (call-interactively 'org-previous-item))
18024 ((org-clocktable-try-shift 'up arg))
18025 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18026 (org-support-shift-select
18027 (org-call-for-shift-select 'previous-line))
18028 (t (org-shiftselect-error))))
18030 (defun org-shiftdown (&optional arg)
18031 "Decrease item in timestamp or decrease priority of current headline.
18032 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18033 depending on context. See the individual commands for more information."
18034 (interactive "P")
18035 (cond
18036 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18037 ((and org-support-shift-select (org-region-active-p))
18038 (org-call-for-shift-select 'next-line))
18039 ((org-at-timestamp-p t)
18040 (call-interactively (if org-edit-timestamp-down-means-later
18041 'org-timestamp-up 'org-timestamp-down)))
18042 ((and (not (eq org-support-shift-select 'always))
18043 org-enable-priority-commands
18044 (org-on-heading-p))
18045 (call-interactively 'org-priority-down))
18046 ((and (not org-support-shift-select) (org-at-item-p))
18047 (call-interactively 'org-next-item))
18048 ((org-clocktable-try-shift 'down arg))
18049 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18050 (org-support-shift-select
18051 (org-call-for-shift-select 'next-line))
18052 (t (org-shiftselect-error))))
18054 (defun org-shiftright (&optional arg)
18055 "Cycle the thing at point or in the current line, depending on context.
18056 Depending on context, this does one of the following:
18058 - switch a timestamp at point one day into the future
18059 - on a headline, switch to the next TODO keyword.
18060 - on an item, switch entire list to the next bullet type
18061 - on a property line, switch to the next allowed value
18062 - on a clocktable definition line, move time block into the future"
18063 (interactive "P")
18064 (cond
18065 ((run-hook-with-args-until-success 'org-shiftright-hook))
18066 ((and org-support-shift-select (org-region-active-p))
18067 (org-call-for-shift-select 'forward-char))
18068 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18069 ((and (not (eq org-support-shift-select 'always))
18070 (org-on-heading-p))
18071 (let ((org-inhibit-logging
18072 (not org-treat-S-cursor-todo-selection-as-state-change))
18073 (org-inhibit-blocking
18074 (not org-treat-S-cursor-todo-selection-as-state-change)))
18075 (org-call-with-arg 'org-todo 'right)))
18076 ((or (and org-support-shift-select
18077 (not (eq org-support-shift-select 'always))
18078 (org-at-item-bullet-p))
18079 (and (not org-support-shift-select) (org-at-item-p)))
18080 (org-call-with-arg 'org-cycle-list-bullet nil))
18081 ((and (not (eq org-support-shift-select 'always))
18082 (org-at-property-p))
18083 (call-interactively 'org-property-next-allowed-value))
18084 ((org-clocktable-try-shift 'right arg))
18085 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18086 (org-support-shift-select
18087 (org-call-for-shift-select 'forward-char))
18088 (t (org-shiftselect-error))))
18090 (defun org-shiftleft (&optional arg)
18091 "Cycle the thing at point or in the current line, depending on context.
18092 Depending on context, this does one of the following:
18094 - switch a timestamp at point one day into the past
18095 - on a headline, switch to the previous TODO keyword.
18096 - on an item, switch entire list to the previous bullet type
18097 - on a property line, switch to the previous allowed value
18098 - on a clocktable definition line, move time block into the past"
18099 (interactive "P")
18100 (cond
18101 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18102 ((and org-support-shift-select (org-region-active-p))
18103 (org-call-for-shift-select 'backward-char))
18104 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18105 ((and (not (eq org-support-shift-select 'always))
18106 (org-on-heading-p))
18107 (let ((org-inhibit-logging
18108 (not org-treat-S-cursor-todo-selection-as-state-change))
18109 (org-inhibit-blocking
18110 (not org-treat-S-cursor-todo-selection-as-state-change)))
18111 (org-call-with-arg 'org-todo 'left)))
18112 ((or (and org-support-shift-select
18113 (not (eq org-support-shift-select 'always))
18114 (org-at-item-bullet-p))
18115 (and (not org-support-shift-select) (org-at-item-p)))
18116 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18117 ((and (not (eq org-support-shift-select 'always))
18118 (org-at-property-p))
18119 (call-interactively 'org-property-previous-allowed-value))
18120 ((org-clocktable-try-shift 'left arg))
18121 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18122 (org-support-shift-select
18123 (org-call-for-shift-select 'backward-char))
18124 (t (org-shiftselect-error))))
18126 (defun org-shiftcontrolright ()
18127 "Switch to next TODO set."
18128 (interactive)
18129 (cond
18130 ((and org-support-shift-select (org-region-active-p))
18131 (org-call-for-shift-select 'forward-word))
18132 ((and (not (eq org-support-shift-select 'always))
18133 (org-on-heading-p))
18134 (org-call-with-arg 'org-todo 'nextset))
18135 (org-support-shift-select
18136 (org-call-for-shift-select 'forward-word))
18137 (t (org-shiftselect-error))))
18139 (defun org-shiftcontrolleft ()
18140 "Switch to previous TODO set."
18141 (interactive)
18142 (cond
18143 ((and org-support-shift-select (org-region-active-p))
18144 (org-call-for-shift-select 'backward-word))
18145 ((and (not (eq org-support-shift-select 'always))
18146 (org-on-heading-p))
18147 (org-call-with-arg 'org-todo 'previousset))
18148 (org-support-shift-select
18149 (org-call-for-shift-select 'backward-word))
18150 (t (org-shiftselect-error))))
18152 (defun org-shiftcontrolup ()
18153 "Change timestamps synchronously up in CLOCK log lines."
18154 (interactive)
18155 (cond ((and (not org-support-shift-select)
18156 (org-at-clock-log-p)
18157 (org-at-timestamp-p t))
18158 (org-clock-timestamps-up))
18159 (t (org-shiftselect-error))))
18161 (defun org-shiftcontroldown ()
18162 "Change timestamps synchronously down in CLOCK log lines."
18163 (interactive)
18164 (cond ((and (not org-support-shift-select)
18165 (org-at-clock-log-p)
18166 (org-at-timestamp-p t))
18167 (org-clock-timestamps-down))
18168 (t (org-shiftselect-error))))
18170 (defun org-ctrl-c-ret ()
18171 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18172 (interactive)
18173 (cond
18174 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18175 (t (call-interactively 'org-insert-heading))))
18177 (defun org-find-visible ()
18178 (let ((s (point)))
18179 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18180 (get-char-property s 'invisible)))
18182 (defun org-find-invisible ()
18183 (let ((s (point)))
18184 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18185 (not (get-char-property s 'invisible))))
18188 (defun org-copy-visible (beg end)
18189 "Copy the visible parts of the region."
18190 (interactive "r")
18191 (let (snippets s)
18192 (save-excursion
18193 (save-restriction
18194 (narrow-to-region beg end)
18195 (setq s (goto-char (point-min)))
18196 (while (not (= (point) (point-max)))
18197 (goto-char (org-find-invisible))
18198 (push (buffer-substring s (point)) snippets)
18199 (setq s (goto-char (org-find-visible))))))
18200 (kill-new (apply 'concat (nreverse snippets)))))
18202 (defun org-copy-special ()
18203 "Copy region in table or copy current subtree.
18204 Calls `org-table-copy' or `org-copy-subtree', depending on context.
18205 See the individual commands for more information."
18206 (interactive)
18207 (call-interactively
18208 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
18210 (defun org-cut-special ()
18211 "Cut region in table or cut current subtree.
18212 Calls `org-table-copy' or `org-cut-subtree', depending on context.
18213 See the individual commands for more information."
18214 (interactive)
18215 (call-interactively
18216 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
18218 (defun org-paste-special (arg)
18219 "Paste rectangular region into table, or past subtree relative to level.
18220 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
18221 See the individual commands for more information."
18222 (interactive "P")
18223 (if (org-at-table-p)
18224 (org-table-paste-rectangle)
18225 (org-paste-subtree arg)))
18227 (defun org-edit-special (&optional arg)
18228 "Call a special editor for the stuff at point.
18229 When at a table, call the formula editor with `org-table-edit-formulas'.
18230 When at the first line of an src example, call `org-edit-src-code'.
18231 When in an #+include line, visit the include file. Otherwise call
18232 `ffap' to visit the file at point."
18233 (interactive)
18234 ;; possibly prep session before editing source
18235 (when arg
18236 (let* ((info (org-babel-get-src-block-info))
18237 (lang (nth 0 info))
18238 (params (nth 2 info))
18239 (session (cdr (assoc :session params))))
18240 (when (and info session) ;; we are in a source-code block with a session
18241 (funcall
18242 (intern (concat "org-babel-prep-session:" lang)) session params))))
18243 (cond ;; proceed with `org-edit-special'
18244 ((save-excursion
18245 (beginning-of-line 1)
18246 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
18247 (find-file (org-trim (match-string 1))))
18248 ((org-edit-src-code))
18249 ((org-edit-fixed-width-region))
18250 ((org-at-table.el-p)
18251 (org-edit-src-code))
18252 ((or (org-at-table-p)
18253 (save-excursion
18254 (beginning-of-line 1)
18255 (looking-at "[ \t]*#\\+TBLFM:")))
18256 (call-interactively 'org-table-edit-formulas))
18257 (t (call-interactively 'ffap))))
18259 (defvar org-table-coordinate-overlays) ; defined in org-table.el
18260 (defun org-ctrl-c-ctrl-c (&optional arg)
18261 "Set tags in headline, or update according to changed information at point.
18263 This command does many different things, depending on context:
18265 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
18266 this is what we do.
18268 - If the cursor is on a statistics cookie, update it.
18270 - If the cursor is in a headline, prompt for tags and insert them
18271 into the current line, aligned to `org-tags-column'. When called
18272 with prefix arg, realign all tags in the current buffer.
18274 - If the cursor is in one of the special #+KEYWORD lines, this
18275 triggers scanning the buffer for these lines and updating the
18276 information.
18278 - If the cursor is inside a table, realign the table. This command
18279 works even if the automatic table editor has been turned off.
18281 - If the cursor is on a #+TBLFM line, re-apply the formulas to
18282 the entire table.
18284 - If the cursor is at a footnote reference or definition, jump to
18285 the corresponding definition or references, respectively.
18287 - If the cursor is a the beginning of a dynamic block, update it.
18289 - If the current buffer is a capture buffer, close note and file it.
18291 - If the cursor is on a <<<target>>>, update radio targets and
18292 corresponding links in this buffer.
18294 - If the cursor is on a numbered item in a plain list, renumber the
18295 ordered list.
18297 - If the cursor is on a checkbox, toggle it.
18299 - If the cursor is on a code block, evaluate it. The variable
18300 `org-confirm-babel-evaluate' can be used to control prompting
18301 before code block evaluation, by default every code block
18302 evaluation requires confirmation. Code block evaluation can be
18303 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
18304 (interactive "P")
18305 (let ((org-enable-table-editor t))
18306 (cond
18307 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
18308 org-occur-highlights
18309 org-latex-fragment-image-overlays)
18310 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
18311 (org-remove-occur-highlights)
18312 (org-remove-latex-fragment-image-overlays)
18313 (message "Temporary highlights/overlays removed from current buffer"))
18314 ((and (local-variable-p 'org-finish-function (current-buffer))
18315 (fboundp org-finish-function))
18316 (funcall org-finish-function))
18317 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
18318 ((org-in-regexp org-ts-regexp-both)
18319 (org-timestamp-change 0 'day))
18320 ((or (looking-at org-property-start-re)
18321 (org-at-property-p))
18322 (call-interactively 'org-property-action))
18323 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
18324 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
18325 (or (org-on-heading-p) (org-at-item-p)))
18326 (call-interactively 'org-update-statistics-cookies))
18327 ((org-on-heading-p) (call-interactively 'org-set-tags))
18328 ((org-at-table.el-p)
18329 (message "Use C-c ' to edit table.el tables"))
18330 ((org-at-table-p)
18331 (org-table-maybe-eval-formula)
18332 (if arg
18333 (call-interactively 'org-table-recalculate)
18334 (org-table-maybe-recalculate-line))
18335 (call-interactively 'org-table-align)
18336 (orgtbl-send-table 'maybe))
18337 ((or (org-footnote-at-reference-p)
18338 (org-footnote-at-definition-p))
18339 (call-interactively 'org-footnote-action))
18340 ((org-at-item-checkbox-p)
18341 ;; Cursor at a checkbox: repair list and update checkboxes. Send
18342 ;; list only if at top item.
18343 (let* ((cbox (match-string 1))
18344 (struct (org-list-struct))
18345 (old-struct (copy-tree struct))
18346 (parents (org-list-parents-alist struct))
18347 (orderedp (org-entry-get nil "ORDERED"))
18348 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18349 block-item)
18350 ;; Use a light version of `org-toggle-checkbox' to avoid
18351 ;; computing list structure twice.
18352 (org-list-set-checkbox (point-at-bol) struct
18353 (cond
18354 ((equal arg '(16)) "[-]")
18355 ((equal arg '(4)) nil)
18356 ((equal "[X]" cbox) "[ ]")
18357 (t "[X]")))
18358 ;; Replicate `org-list-write-struct', while grabbing a return
18359 ;; value from `org-list-struct-fix-box'.
18360 (org-list-struct-fix-ind struct parents 2)
18361 (org-list-struct-fix-item-end struct)
18362 (let ((prevs (org-list-prevs-alist struct)))
18363 (org-list-struct-fix-bul struct prevs)
18364 (org-list-struct-fix-ind struct parents)
18365 (setq block-item
18366 (org-list-struct-fix-box struct parents prevs orderedp)))
18367 (org-list-struct-apply-struct struct old-struct)
18368 (org-update-checkbox-count-maybe)
18369 (when block-item
18370 (message
18371 "Checkboxes were removed due to unchecked box at line %d"
18372 (org-current-line block-item)))
18373 (when firstp (org-list-send-list 'maybe))))
18374 ((org-at-item-p)
18375 ;; Cursor at an item: repair list. Do checkbox related actions
18376 ;; only if function was called with an argument. Send list only
18377 ;; if at top item.
18378 (let* ((struct (org-list-struct))
18379 (firstp (= (org-list-get-top-point struct) (point-at-bol))))
18380 (when arg (org-list-set-checkbox (point-at-bol) struct "[ ]"))
18381 (org-list-write-struct struct (org-list-parents-alist struct))
18382 (when arg (org-update-checkbox-count-maybe))
18383 (when firstp (org-list-send-list 'maybe))))
18384 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
18385 ;; Dynamic block
18386 (beginning-of-line 1)
18387 (save-excursion (org-update-dblock)))
18388 ((save-excursion
18389 (beginning-of-line 1)
18390 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
18391 (cond
18392 ((equal (match-string 1) "TBLFM")
18393 ;; Recalculate the table before this line
18394 (save-excursion
18395 (beginning-of-line 1)
18396 (skip-chars-backward " \r\n\t")
18397 (if (org-at-table-p)
18398 (org-call-with-arg 'org-table-recalculate (or arg t)))))
18400 (let ((org-inhibit-startup-visibility-stuff t)
18401 (org-startup-align-all-tables nil))
18402 (when (boundp 'org-table-coordinate-overlays)
18403 (mapc 'delete-overlay org-table-coordinate-overlays)
18404 (setq org-table-coordinate-overlays nil))
18405 (org-save-outline-visibility 'use-markers (org-mode-restart)))
18406 (message "Local setup has been refreshed"))))
18407 ((org-clock-update-time-maybe))
18409 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
18410 (error "C-c C-c can do nothing useful at this location"))))))
18412 (defun org-mode-restart ()
18413 "Restart Org-mode, to scan again for special lines.
18414 Also updates the keyword regular expressions."
18415 (interactive)
18416 (org-mode)
18417 (message "Org-mode restarted"))
18419 (defun org-kill-note-or-show-branches ()
18420 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
18421 (interactive)
18422 (if (not org-finish-function)
18423 (progn
18424 (hide-subtree)
18425 (call-interactively 'show-branches))
18426 (let ((org-note-abort t))
18427 (funcall org-finish-function))))
18429 (defun org-return (&optional indent)
18430 "Goto next table row or insert a newline.
18431 Calls `org-table-next-row' or `newline', depending on context.
18432 See the individual commands for more information."
18433 (interactive)
18434 (cond
18435 ((bobp) (if indent (newline-and-indent) (newline)))
18436 ((org-at-table-p)
18437 (org-table-justify-field-maybe)
18438 (call-interactively 'org-table-next-row))
18439 ;; when `newline-and-indent' is called within a list, make sure
18440 ;; text moved stays inside the item.
18441 ((and (org-in-item-p) indent)
18442 (if (and (org-at-item-p) (>= (point) (match-end 0)))
18443 (progn
18444 (save-match-data (newline))
18445 (org-indent-line-to (length (match-string 0))))
18446 (let ((ind (org-get-indentation)))
18447 (newline)
18448 (if (org-looking-back org-list-end-re)
18449 (org-indent-line-function)
18450 (org-indent-line-to ind)))))
18451 ((and org-return-follows-link
18452 (let ((tprop (get-text-property (point) 'face)))
18453 (or (eq tprop 'org-link)
18454 (and (listp tprop) (memq 'org-link tprop)))))
18455 (call-interactively 'org-open-at-point))
18456 ((and (org-at-heading-p)
18457 (looking-at
18458 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
18459 (org-show-entry)
18460 (end-of-line 1)
18461 (newline))
18462 (t (if indent (newline-and-indent) (newline)))))
18464 (defun org-return-indent ()
18465 "Goto next table row or insert a newline and indent.
18466 Calls `org-table-next-row' or `newline-and-indent', depending on
18467 context. See the individual commands for more information."
18468 (interactive)
18469 (org-return t))
18471 (defun org-ctrl-c-star ()
18472 "Compute table, or change heading status of lines.
18473 Calls `org-table-recalculate' or `org-toggle-heading',
18474 depending on context."
18475 (interactive)
18476 (cond
18477 ((org-at-table-p)
18478 (call-interactively 'org-table-recalculate))
18480 ;; Convert all lines in region to list items
18481 (call-interactively 'org-toggle-heading))))
18483 (defun org-ctrl-c-minus ()
18484 "Insert separator line in table or modify bullet status of line.
18485 Also turns a plain line or a region of lines into list items.
18486 Calls `org-table-insert-hline', `org-toggle-item', or
18487 `org-cycle-list-bullet', depending on context."
18488 (interactive)
18489 (cond
18490 ((org-at-table-p)
18491 (call-interactively 'org-table-insert-hline))
18492 ((org-region-active-p)
18493 (call-interactively 'org-toggle-item))
18494 ((org-in-item-p)
18495 (call-interactively 'org-cycle-list-bullet))
18497 (call-interactively 'org-toggle-item))))
18499 (defun org-toggle-item (arg)
18500 "Convert headings or normal lines to items, items to normal lines.
18501 If there is no active region, only the current line is considered.
18503 If the first non blank line in the region is an headline, convert
18504 all headlines to items, shifting text accordingly.
18506 If it is an item, convert all items to normal lines.
18508 If it is normal text, change region into an item. With a prefix
18509 argument ARG, change each line in region into an item."
18510 (interactive "P")
18511 (let ((shift-text
18512 (function
18513 ;; Shift text in current section to IND, from point to END.
18514 ;; The function leaves point to END line.
18515 (lambda (ind end)
18516 (let ((min-i 1000) (end (copy-marker end)))
18517 ;; First determine the minimum indentation (MIN-I) of
18518 ;; the text.
18519 (save-excursion
18520 (catch 'exit
18521 (while (< (point) end)
18522 (let ((i (org-get-indentation)))
18523 (cond
18524 ;; Skip blank lines and inline tasks.
18525 ((looking-at "^[ \t]*$"))
18526 ((looking-at org-outline-regexp-bol))
18527 ;; We can't find less than 0 indentation.
18528 ((zerop i) (throw 'exit (setq min-i 0)))
18529 ((< i min-i) (setq min-i i))))
18530 (forward-line))))
18531 ;; Then indent each line so that a line indented to
18532 ;; MIN-I becomes indented to IND. Ignore blank lines
18533 ;; and inline tasks in the process.
18534 (let ((delta (- ind min-i)))
18535 (while (< (point) end)
18536 (unless (or (looking-at "^[ \t]*$")
18537 (looking-at org-outline-regexp-bol))
18538 (org-indent-line-to (+ (org-get-indentation) delta)))
18539 (forward-line)))))))
18540 (skip-blanks
18541 (function
18542 ;; Return beginning of first non-blank line, starting from
18543 ;; line at POS.
18544 (lambda (pos)
18545 (save-excursion
18546 (goto-char pos)
18547 (skip-chars-forward " \r\t\n")
18548 (point-at-bol)))))
18549 beg end)
18550 ;; Determine boundaries of changes.
18551 (if (org-region-active-p)
18552 (setq beg (funcall skip-blanks (region-beginning))
18553 end (copy-marker (region-end)))
18554 (setq beg (funcall skip-blanks (point-at-bol))
18555 end (copy-marker (point-at-eol))))
18556 ;; Depending on the starting line, choose an action on the text
18557 ;; between BEG and END.
18558 (org-with-limited-levels
18559 (save-excursion
18560 (goto-char beg)
18561 (cond
18562 ;; Case 1. Start at an item: de-itemize. Note that it only
18563 ;; happens when a region is active: `org-ctrl-c-minus'
18564 ;; would call `org-cycle-list-bullet' otherwise.
18565 ((org-at-item-p)
18566 (while (< (point) end)
18567 (when (org-at-item-p)
18568 (skip-chars-forward " \t")
18569 (delete-region (point) (match-end 0)))
18570 (forward-line)))
18571 ;; Case 2. Start at an heading: convert to items.
18572 ((org-on-heading-p)
18573 (let* ((bul (org-list-bullet-string "-"))
18574 (bul-len (length bul))
18575 ;; Indentation of the first heading. It should be
18576 ;; relative to the indentation of its parent, if any.
18577 (start-ind (save-excursion
18578 (cond
18579 ((not org-adapt-indentation) 0)
18580 ((not (outline-previous-heading)) 0)
18581 (t (length (match-string 0))))))
18582 ;; Level of first heading. Further headings will be
18583 ;; compared to it to determine hierarchy in the list.
18584 (ref-level (org-reduced-level (org-outline-level))))
18585 (while (< (point) end)
18586 (let* ((level (org-reduced-level (org-outline-level)))
18587 (delta (max 0 (- level ref-level))))
18588 ;; If current headline is less indented than the first
18589 ;; one, set it as reference, in order to preserve
18590 ;; subtrees.
18591 (when (< level ref-level) (setq ref-level level))
18592 (replace-match bul t t)
18593 (org-indent-line-to (+ start-ind (* delta bul-len)))
18594 ;; Ensure all text down to END (or SECTION-END) belongs
18595 ;; to the newly created item.
18596 (let ((section-end (save-excursion
18597 (or (outline-next-heading) (point)))))
18598 (forward-line)
18599 (funcall shift-text
18600 (+ start-ind (* (1+ delta) bul-len))
18601 (min end section-end)))))))
18602 ;; Case 3. Normal line with ARG: turn each non-item line into
18603 ;; an item.
18604 (arg
18605 (while (< (point) end)
18606 (unless (or (org-on-heading-p) (org-at-item-p))
18607 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
18608 (replace-match
18609 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
18610 (forward-line)))
18611 ;; Case 4. Normal line without ARG: make the first line of
18612 ;; region an item, and shift indentation of others
18613 ;; lines to set them as item's body.
18614 (t (let* ((bul (org-list-bullet-string "-"))
18615 (bul-len (length bul))
18616 (ref-ind (org-get-indentation)))
18617 (skip-chars-forward " \t")
18618 (insert bul)
18619 (forward-line)
18620 (while (< (point) end)
18621 ;; Ensure that lines less indented than first one
18622 ;; still get included in item body.
18623 (funcall shift-text
18624 (+ ref-ind bul-len)
18625 (min end (save-excursion (or (outline-next-heading)
18626 (point)))))
18627 (forward-line)))))))))
18629 (defun org-toggle-heading (&optional nstars)
18630 "Convert headings to normal text, or items or text to headings.
18631 If there is no active region, only the current line is considered.
18633 If the first non blank line is an headline, remove the stars from
18634 all headlines in the region.
18636 If it is a plain list item, turn all plain list items into headings.
18638 If it is a normal line, turn each and every normal line (i.e. not
18639 an heading or an item) in the region into a heading.
18641 When converting a line into a heading, the number of stars is chosen
18642 such that the lines become children of the current entry. However,
18643 when a prefix argument is given, its value determines the number of
18644 stars to add."
18645 (interactive "P")
18646 (let ((skip-blanks
18647 (function
18648 ;; Return beginning of first non-blank line, starting from
18649 ;; line at POS.
18650 (lambda (pos)
18651 (save-excursion
18652 (goto-char pos)
18653 (skip-chars-forward " \r\t\n")
18654 (point-at-bol)))))
18655 beg end)
18656 ;; Determine boundaries of changes. If region ends at a bol, do
18657 ;; not consider the last line to be in the region.
18658 (if (org-region-active-p)
18659 (setq beg (funcall skip-blanks (region-beginning))
18660 end (copy-marker (save-excursion
18661 (goto-char (region-end))
18662 (if (bolp) (point) (point-at-eol)))))
18663 (setq beg (funcall skip-blanks (point-at-bol))
18664 end (copy-marker (point-at-eol))))
18665 ;; Ensure inline tasks don't count as headings.
18666 (org-with-limited-levels
18667 (save-excursion
18668 (goto-char beg)
18669 (cond
18670 ;; Case 1. Started at an heading: de-star headings.
18671 ((org-on-heading-p)
18672 (while (< (point) end)
18673 (when (org-on-heading-p t)
18674 (looking-at org-outline-regexp) (replace-match ""))
18675 (forward-line)))
18676 ;; Case 2. Started at an item: change items into headlines.
18677 ;; One star will be added by `org-list-to-subtree'.
18678 ((org-at-item-p)
18679 (let* ((stars (make-string
18680 (if nstars
18681 ;; subtract the star that will be added again by
18682 ;; `org-list-to-subtree'
18683 (1- (prefix-numeric-value current-prefix-arg))
18684 (or (org-current-level) 0))
18685 ?*))
18686 (add-stars
18687 (cond (nstars "") ; stars from prefix only
18688 ((equal stars "") "") ; before first heading
18689 (org-odd-levels-only "*") ; inside heading, odd
18690 (t "")))) ; inside heading, oddeven
18691 (while (< (point) end)
18692 (when (org-at-item-p)
18693 ;; Pay attention to cases when region ends before list.
18694 (let* ((struct (org-list-struct))
18695 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
18696 (save-restriction
18697 (narrow-to-region (point) list-end)
18698 (insert
18699 (org-list-to-subtree
18700 (org-list-parse-list t)
18701 '(:istart (concat stars add-stars (funcall get-stars depth))
18702 :icount (concat stars add-stars (funcall get-stars depth))))))))
18703 (forward-line))))
18704 ;; Case 3. Started at normal text: make every line an heading,
18705 ;; skipping headlines and items.
18706 (t (let* ((stars (make-string
18707 (if nstars
18708 (prefix-numeric-value current-prefix-arg)
18709 (or (org-current-level) 0))
18710 ?*))
18711 (add-stars
18712 (cond (nstars "") ; stars from prefix only
18713 ((equal stars "") "*") ; before first heading
18714 (org-odd-levels-only "**") ; inside heading, odd
18715 (t "*"))) ; inside heading, oddeven
18716 (rpl (concat stars add-stars " ")))
18717 (while (< (point) end)
18718 (when (and (not (org-on-heading-p)) (not (org-at-item-p))
18719 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
18720 (replace-match (concat rpl (match-string 2))))
18721 (forward-line)))))))))
18723 (defun org-meta-return (&optional arg)
18724 "Insert a new heading or wrap a region in a table.
18725 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
18726 See the individual commands for more information."
18727 (interactive "P")
18728 (cond
18729 ((run-hook-with-args-until-success 'org-metareturn-hook))
18730 ((org-at-table-p)
18731 (call-interactively 'org-table-wrap-region))
18732 (t (call-interactively 'org-insert-heading))))
18734 ;;; Menu entries
18736 ;; Define the Org-mode menus
18737 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
18738 '("Tbl"
18739 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
18740 ["Next Field" org-cycle (org-at-table-p)]
18741 ["Previous Field" org-shifttab (org-at-table-p)]
18742 ["Next Row" org-return (org-at-table-p)]
18743 "--"
18744 ["Blank Field" org-table-blank-field (org-at-table-p)]
18745 ["Edit Field" org-table-edit-field (org-at-table-p)]
18746 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
18747 "--"
18748 ("Column"
18749 ["Move Column Left" org-metaleft (org-at-table-p)]
18750 ["Move Column Right" org-metaright (org-at-table-p)]
18751 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
18752 ["Insert Column" org-shiftmetaright (org-at-table-p)])
18753 ("Row"
18754 ["Move Row Up" org-metaup (org-at-table-p)]
18755 ["Move Row Down" org-metadown (org-at-table-p)]
18756 ["Delete Row" org-shiftmetaup (org-at-table-p)]
18757 ["Insert Row" org-shiftmetadown (org-at-table-p)]
18758 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
18759 "--"
18760 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
18761 ("Rectangle"
18762 ["Copy Rectangle" org-copy-special (org-at-table-p)]
18763 ["Cut Rectangle" org-cut-special (org-at-table-p)]
18764 ["Paste Rectangle" org-paste-special (org-at-table-p)]
18765 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
18766 "--"
18767 ("Calculate"
18768 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
18769 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
18770 ["Edit Formulas" org-edit-special (org-at-table-p)]
18771 "--"
18772 ["Recalculate line" org-table-recalculate (org-at-table-p)]
18773 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
18774 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
18775 "--"
18776 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
18777 "--"
18778 ["Sum Column/Rectangle" org-table-sum
18779 (or (org-at-table-p) (org-region-active-p))]
18780 ["Which Column?" org-table-current-column (org-at-table-p)])
18781 ["Debug Formulas"
18782 org-table-toggle-formula-debugger
18783 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
18784 ["Show Col/Row Numbers"
18785 org-table-toggle-coordinate-overlays
18786 :style toggle
18787 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
18788 "--"
18789 ["Create" org-table-create (and (not (org-at-table-p))
18790 org-enable-table-editor)]
18791 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
18792 ["Import from File" org-table-import (not (org-at-table-p))]
18793 ["Export to File" org-table-export (org-at-table-p)]
18794 "--"
18795 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
18797 (easy-menu-define org-org-menu org-mode-map "Org menu"
18798 '("Org"
18799 ("Show/Hide"
18800 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
18801 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
18802 ["Sparse Tree..." org-sparse-tree t]
18803 ["Reveal Context" org-reveal t]
18804 ["Show All" show-all t]
18805 "--"
18806 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
18807 "--"
18808 ["New Heading" org-insert-heading t]
18809 ("Navigate Headings"
18810 ["Up" outline-up-heading t]
18811 ["Next" outline-next-visible-heading t]
18812 ["Previous" outline-previous-visible-heading t]
18813 ["Next Same Level" outline-forward-same-level t]
18814 ["Previous Same Level" outline-backward-same-level t]
18815 "--"
18816 ["Jump" org-goto t])
18817 ("Edit Structure"
18818 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
18819 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
18820 "--"
18821 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
18822 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
18823 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
18824 "--"
18825 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
18826 "--"
18827 ["Copy visible text" org-copy-visible t]
18828 "--"
18829 ["Promote Heading" org-metaleft (not (org-at-table-p))]
18830 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
18831 ["Demote Heading" org-metaright (not (org-at-table-p))]
18832 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
18833 "--"
18834 ["Sort Region/Children" org-sort (not (org-at-table-p))]
18835 "--"
18836 ["Convert to odd levels" org-convert-to-odd-levels t]
18837 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
18838 ("Editing"
18839 ["Emphasis..." org-emphasize t]
18840 ["Edit Source Example" org-edit-special t]
18841 "--"
18842 ["Footnote new/jump" org-footnote-action t]
18843 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
18844 ("Archive"
18845 ["Archive (default method)" org-archive-subtree-default t]
18846 "--"
18847 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
18848 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
18849 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
18851 "--"
18852 ("Hyperlinks"
18853 ["Store Link (Global)" org-store-link t]
18854 ["Find existing link to here" org-occur-link-in-agenda-files t]
18855 ["Insert Link" org-insert-link t]
18856 ["Follow Link" org-open-at-point t]
18857 "--"
18858 ["Next link" org-next-link t]
18859 ["Previous link" org-previous-link t]
18860 "--"
18861 ["Descriptive Links"
18862 org-toggle-link-display
18863 :style radio
18864 :selected org-descriptive-links
18866 ["Literal Links"
18867 org-toggle-link-display
18868 :style radio
18869 :selected (not org-descriptive-links)])
18870 "--"
18871 ("TODO Lists"
18872 ["TODO/DONE/-" org-todo t]
18873 ("Select keyword"
18874 ["Next keyword" org-shiftright (org-on-heading-p)]
18875 ["Previous keyword" org-shiftleft (org-on-heading-p)]
18876 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
18877 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
18878 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
18879 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
18880 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
18881 "--"
18882 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
18883 :selected org-enforce-todo-dependencies :style toggle :active t]
18884 "Settings for tree at point"
18885 ["Do Children sequentially" org-toggle-ordered-property :style radio
18886 :selected (org-entry-get nil "ORDERED")
18887 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
18888 ["Do Children parallel" org-toggle-ordered-property :style radio
18889 :selected (not (org-entry-get nil "ORDERED"))
18890 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
18891 "--"
18892 ["Set Priority" org-priority t]
18893 ["Priority Up" org-shiftup t]
18894 ["Priority Down" org-shiftdown t]
18895 "--"
18896 ["Get news from all feeds" org-feed-update-all t]
18897 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
18898 ["Customize feeds" (customize-variable 'org-feed-alist) t])
18899 ("TAGS and Properties"
18900 ["Set Tags" org-set-tags-command t]
18901 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
18902 "--"
18903 ["Set property" org-set-property t]
18904 ["Column view of properties" org-columns t]
18905 ["Insert Column View DBlock" org-insert-columns-dblock t])
18906 ("Dates and Scheduling"
18907 ["Timestamp" org-time-stamp t]
18908 ["Timestamp (inactive)" org-time-stamp-inactive t]
18909 ("Change Date"
18910 ["1 Day Later" org-shiftright t]
18911 ["1 Day Earlier" org-shiftleft t]
18912 ["1 ... Later" org-shiftup t]
18913 ["1 ... Earlier" org-shiftdown t])
18914 ["Compute Time Range" org-evaluate-time-range t]
18915 ["Schedule Item" org-schedule t]
18916 ["Deadline" org-deadline t]
18917 "--"
18918 ["Custom time format" org-toggle-time-stamp-overlays
18919 :style radio :selected org-display-custom-times]
18920 "--"
18921 ["Goto Calendar" org-goto-calendar t]
18922 ["Date from Calendar" org-date-from-calendar t]
18923 "--"
18924 ["Start/Restart Timer" org-timer-start t]
18925 ["Pause/Continue Timer" org-timer-pause-or-continue t]
18926 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
18927 ["Insert Timer String" org-timer t]
18928 ["Insert Timer Item" org-timer-item t])
18929 ("Logging work"
18930 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
18931 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
18932 ["Clock out" org-clock-out t]
18933 ["Clock cancel" org-clock-cancel t]
18934 "--"
18935 ["Mark as default task" org-clock-mark-default-task t]
18936 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
18937 ["Goto running clock" org-clock-goto t]
18938 "--"
18939 ["Display times" org-clock-display t]
18940 ["Create clock table" org-clock-report t]
18941 "--"
18942 ["Record DONE time"
18943 (progn (setq org-log-done (not org-log-done))
18944 (message "Switching to %s will %s record a timestamp"
18945 (car org-done-keywords)
18946 (if org-log-done "automatically" "not")))
18947 :style toggle :selected org-log-done])
18948 "--"
18949 ["Agenda Command..." org-agenda t]
18950 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
18951 ("File List for Agenda")
18952 ("Special views current file"
18953 ["TODO Tree" org-show-todo-tree t]
18954 ["Check Deadlines" org-check-deadlines t]
18955 ["Timeline" org-timeline t]
18956 ["Tags/Property tree" org-match-sparse-tree t])
18957 "--"
18958 ["Export/Publish..." org-export t]
18959 ("LaTeX"
18960 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
18961 :selected org-cdlatex-mode]
18962 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
18963 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
18964 ["Modify math symbol" org-cdlatex-math-modify
18965 (org-inside-LaTeX-fragment-p)]
18966 ["Insert citation" org-reftex-citation t]
18967 "--"
18968 ["Template for BEAMER" org-insert-beamer-options-template t])
18969 "--"
18970 ("MobileOrg"
18971 ["Push Files and Views" org-mobile-push t]
18972 ["Get Captured and Flagged" org-mobile-pull t]
18973 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
18974 "--"
18975 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
18976 "--"
18977 ("Documentation"
18978 ["Show Version" org-version t]
18979 ["Info Documentation" org-info t])
18980 ("Customize"
18981 ["Browse Org Group" org-customize t]
18982 "--"
18983 ["Expand This Menu" org-create-customize-menu
18984 (fboundp 'customize-menu-create)])
18985 ["Send bug report" org-submit-bug-report t]
18986 "--"
18987 ("Refresh/Reload"
18988 ["Refresh setup current buffer" org-mode-restart t]
18989 ["Reload Org (after update)" org-reload t]
18990 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
18993 (defun org-info (&optional node)
18994 "Read documentation for Org-mode in the info system.
18995 With optional NODE, go directly to that node."
18996 (interactive)
18997 (info (format "(org)%s" (or node ""))))
18999 ;;;###autoload
19000 (defun org-submit-bug-report ()
19001 "Submit a bug report on Org-mode via mail.
19003 Don't hesitate to report any problems or inaccurate documentation.
19005 If you don't have setup sending mail from (X)Emacs, please copy the
19006 output buffer into your mail program, as it gives us important
19007 information about your Org-mode version and configuration."
19008 (interactive)
19009 (require 'reporter)
19010 (org-load-modules-maybe)
19011 (org-require-autoloaded-modules)
19012 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19013 (reporter-submit-bug-report
19014 "emacs-orgmode@gnu.org"
19015 (org-version)
19016 (let (list)
19017 (save-window-excursion
19018 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19019 (delete-other-windows)
19020 (erase-buffer)
19021 (insert "You are about to submit a bug report to the Org-mode mailing list.
19023 We would like to add your full Org-mode and Outline configuration to the
19024 bug report. This greatly simplifies the work of the maintainer and
19025 other experts on the mailing list.
19027 HOWEVER, some variables you have customized may contain private
19028 information. The names of customers, colleagues, or friends, might
19029 appear in the form of file names, tags, todo states, or search strings.
19030 If you answer yes to the prompt, you might want to check and remove
19031 such private information before sending the email.")
19032 (add-text-properties (point-min) (point-max) '(face org-warning))
19033 (when (yes-or-no-p "Include your Org-mode configuration ")
19034 (mapatoms
19035 (lambda (v)
19036 (and (boundp v)
19037 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19038 (or (and (symbol-value v)
19039 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19040 (and
19041 (get v 'custom-type) (get v 'standard-value)
19042 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19043 (push v list)))))
19044 (kill-buffer (get-buffer "*Warn about privacy*"))
19045 list))
19046 nil nil
19047 "Remember to cover the basics, that is, what you expected to happen and
19048 what in fact did happen. You don't know how to make a good report? See
19050 http://orgmode.org/manual/Feedback.html#Feedback
19052 Your bug report will be posted to the Org-mode mailing list.
19053 ------------------------------------------------------------------------")
19054 (save-excursion
19055 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19056 (replace-match "\\1Bug: \\3 [\\2]")))))
19059 (defun org-install-agenda-files-menu ()
19060 (let ((bl (buffer-list)))
19061 (save-excursion
19062 (while bl
19063 (set-buffer (pop bl))
19064 (if (eq major-mode 'org-mode) (setq bl nil)))
19065 (when (eq major-mode 'org-mode)
19066 (easy-menu-change
19067 '("Org") "File List for Agenda"
19068 (append
19069 (list
19070 ["Edit File List" (org-edit-agenda-file-list) t]
19071 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19072 ["Remove Current File from List" org-remove-file t]
19073 ["Cycle through agenda files" org-cycle-agenda-files t]
19074 ["Occur in all agenda files" org-occur-in-agenda-files t]
19075 "--")
19076 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19078 ;;;; Documentation
19080 ;;;###autoload
19081 (defun org-require-autoloaded-modules ()
19082 (interactive)
19083 (mapc 'require
19084 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19085 org-docbook org-exp org-html org-icalendar
19086 org-id org-latex
19087 org-publish org-remember org-table
19088 org-timer org-xoxo)))
19090 ;;;###autoload
19091 (defun org-reload (&optional uncompiled)
19092 "Reload all org lisp files.
19093 With prefix arg UNCOMPILED, load the uncompiled versions."
19094 (interactive "P")
19095 (require 'find-func)
19096 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
19097 (dir-org (file-name-directory (org-find-library-name "org")))
19098 (dir-org-contrib (ignore-errors
19099 (file-name-directory
19100 (org-find-library-name "org-contribdir"))))
19101 (babel-files
19102 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19103 (append (list nil "comint" "eval" "exp" "keys"
19104 "lob" "ref" "table" "tangle")
19105 (delq nil
19106 (mapcar
19107 (lambda (lang)
19108 (when (cdr lang) (symbol-name (car lang))))
19109 org-babel-load-languages)))))
19110 (files
19111 (append (directory-files dir-org t file-re)
19112 babel-files
19113 (and dir-org-contrib
19114 (directory-files dir-org-contrib t file-re))))
19115 (remove-re (concat (if (featurep 'xemacs)
19116 "org-colview" "org-colview-xemacs")
19117 "\\'")))
19118 (setq files (mapcar 'file-name-sans-extension files))
19119 (setq files (mapcar
19120 (lambda (x) (if (string-match remove-re x) nil x))
19121 files))
19122 (setq files (delq nil files))
19123 (mapc
19124 (lambda (f)
19125 (when (featurep (intern (file-name-nondirectory f)))
19126 (if (and (not uncompiled)
19127 (file-exists-p (concat f ".elc")))
19128 (load (concat f ".elc") nil nil t)
19129 (load (concat f ".el") nil nil t))))
19130 files))
19131 (org-version))
19133 ;;;###autoload
19134 (defun org-customize ()
19135 "Call the customize function with org as argument."
19136 (interactive)
19137 (org-load-modules-maybe)
19138 (org-require-autoloaded-modules)
19139 (customize-browse 'org))
19141 (defun org-create-customize-menu ()
19142 "Create a full customization menu for Org-mode, insert it into the menu."
19143 (interactive)
19144 (org-load-modules-maybe)
19145 (org-require-autoloaded-modules)
19146 (if (fboundp 'customize-menu-create)
19147 (progn
19148 (easy-menu-change
19149 '("Org") "Customize"
19150 `(["Browse Org group" org-customize t]
19151 "--"
19152 ,(customize-menu-create 'org)
19153 ["Set" Custom-set t]
19154 ["Save" Custom-save t]
19155 ["Reset to Current" Custom-reset-current t]
19156 ["Reset to Saved" Custom-reset-saved t]
19157 ["Reset to Standard Settings" Custom-reset-standard t]))
19158 (message "\"Org\"-menu now contains full customization menu"))
19159 (error "Cannot expand menu (outdated version of cus-edit.el)")))
19161 ;;;; Miscellaneous stuff
19163 ;;; Generally useful functions
19165 (defun org-get-at-bol (property)
19166 "Get text property PROPERTY at beginning of line."
19167 (get-text-property (point-at-bol) property))
19169 (defun org-find-text-property-in-string (prop s)
19170 "Return the first non-nil value of property PROP in string S."
19171 (or (get-text-property 0 prop s)
19172 (get-text-property (or (next-single-property-change 0 prop s) 0)
19173 prop s)))
19175 (defun org-display-warning (message) ;; Copied from Emacs-Muse
19176 "Display the given MESSAGE as a warning."
19177 (if (fboundp 'display-warning)
19178 (display-warning 'org message
19179 (if (featurep 'xemacs) 'warning :warning))
19180 (let ((buf (get-buffer-create "*Org warnings*")))
19181 (with-current-buffer buf
19182 (goto-char (point-max))
19183 (insert "Warning (Org): " message)
19184 (unless (bolp)
19185 (newline)))
19186 (display-buffer buf)
19187 (sit-for 0))))
19189 (defun org-eval (form)
19190 "Eval FORM and return result."
19191 (condition-case error
19192 (eval form)
19193 (error (format "%%![Error: %s]" error))))
19195 (defun org-in-commented-line ()
19196 "Is point in a line starting with `#'?"
19197 (equal (char-after (point-at-bol)) ?#))
19199 (defun org-in-indented-comment-line ()
19200 "Is point in a line starting with `#' after some white space?"
19201 (save-excursion
19202 (save-match-data
19203 (goto-char (point-at-bol))
19204 (looking-at "[ \t]*#"))))
19206 (defun org-in-verbatim-emphasis ()
19207 (save-match-data
19208 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
19210 (defun org-goto-marker-or-bmk (marker &optional bookmark)
19211 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
19212 (if (and marker (marker-buffer marker)
19213 (buffer-live-p (marker-buffer marker)))
19214 (progn
19215 (org-pop-to-buffer-same-window (marker-buffer marker))
19216 (if (or (> marker (point-max)) (< marker (point-min)))
19217 (widen))
19218 (goto-char marker)
19219 (org-show-context 'org-goto))
19220 (if bookmark
19221 (bookmark-jump bookmark)
19222 (error "Cannot find location"))))
19224 (defun org-quote-csv-field (s)
19225 "Quote field for inclusion in CSV material."
19226 (if (string-match "[\",]" s)
19227 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
19230 (defun org-force-self-insert (N)
19231 "Needed to enforce self-insert under remapping."
19232 (interactive "p")
19233 (self-insert-command N))
19235 (defun org-string-width (s)
19236 "Compute width of string, ignoring invisible characters.
19237 This ignores character with invisibility property `org-link', and also
19238 characters with property `org-cwidth', because these will become invisible
19239 upon the next fontification round."
19240 (let (b l)
19241 (when (or (eq t buffer-invisibility-spec)
19242 (assq 'org-link buffer-invisibility-spec))
19243 (while (setq b (text-property-any 0 (length s)
19244 'invisible 'org-link s))
19245 (setq s (concat (substring s 0 b)
19246 (substring s (or (next-single-property-change
19247 b 'invisible s) (length s)))))))
19248 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
19249 (setq s (concat (substring s 0 b)
19250 (substring s (or (next-single-property-change
19251 b 'org-cwidth s) (length s))))))
19252 (setq l (string-width s) b -1)
19253 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
19254 (setq l (- l (get-text-property b 'org-dwidth-n s))))
19257 (defun org-shorten-string (s maxlength)
19258 "Shorten string S so tht it is no longer than MAXLENGTH characters.
19259 If the string is shorter or has length MAXLENGTH, just return the
19260 original string. If it is longer, the functions finds a space in the
19261 string, breaks this string off at that locations and adds three dots
19262 as ellipsis. Including the ellipsis, the string will not be longer
19263 than MAXLENGTH. If finding a good breaking point in the string does
19264 not work, the string is just chopped off in the middle of a word
19265 if necessary."
19266 (if (<= (length s) maxlength)
19268 (let* ((n (max (- maxlength 4) 1))
19269 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
19270 (if (string-match re s)
19271 (concat (match-string 1 s) "...")
19272 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
19274 (defun org-get-indentation (&optional line)
19275 "Get the indentation of the current line, interpreting tabs.
19276 When LINE is given, assume it represents a line and compute its indentation."
19277 (if line
19278 (if (string-match "^ *" (org-remove-tabs line))
19279 (match-end 0))
19280 (save-excursion
19281 (beginning-of-line 1)
19282 (skip-chars-forward " \t")
19283 (current-column))))
19285 (defun org-get-string-indentation (s)
19286 "What indentation has S due to SPACE and TAB at the beginning of the string?"
19287 (let ((n -1) (i 0) (w tab-width) c)
19288 (catch 'exit
19289 (while (< (setq n (1+ n)) (length s))
19290 (setq c (aref s n))
19291 (cond ((= c ?\ ) (setq i (1+ i)))
19292 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
19293 (t (throw 'exit t)))))
19296 (defun org-remove-tabs (s &optional width)
19297 "Replace tabulators in S with spaces.
19298 Assumes that s is a single line, starting in column 0."
19299 (setq width (or width tab-width))
19300 (while (string-match "\t" s)
19301 (setq s (replace-match
19302 (make-string
19303 (- (* width (/ (+ (match-beginning 0) width) width))
19304 (match-beginning 0)) ?\ )
19305 t t s)))
19308 (defun org-fix-indentation (line ind)
19309 "Fix indentation in LINE.
19310 IND is a cons cell with target and minimum indentation.
19311 If the current indentation in LINE is smaller than the minimum,
19312 leave it alone. If it is larger than ind, set it to the target."
19313 (let* ((l (org-remove-tabs line))
19314 (i (org-get-indentation l))
19315 (i1 (car ind)) (i2 (cdr ind)))
19316 (if (>= i i2) (setq l (substring line i2)))
19317 (if (> i1 0)
19318 (concat (make-string i1 ?\ ) l)
19319 l)))
19321 (defun org-remove-indentation (code &optional n)
19322 "Remove the maximum common indentation from the lines in CODE.
19323 N may optionally be the number of spaces to remove."
19324 (with-temp-buffer
19325 (insert code)
19326 (org-do-remove-indentation n)
19327 (buffer-string)))
19329 (defun org-do-remove-indentation (&optional n)
19330 "Remove the maximum common indentation from the buffer."
19331 (untabify (point-min) (point-max))
19332 (let ((min 10000) re)
19333 (if n
19334 (setq min n)
19335 (goto-char (point-min))
19336 (while (re-search-forward "^ *[^ \n]" nil t)
19337 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
19338 (unless (or (= min 0) (= min 10000))
19339 (setq re (format "^ \\{%d\\}" min))
19340 (goto-char (point-min))
19341 (while (re-search-forward re nil t)
19342 (replace-match "")
19343 (end-of-line 1))
19344 min)))
19346 (defun org-fill-template (template alist)
19347 "Find each %key of ALIST in TEMPLATE and replace it."
19348 (let ((case-fold-search nil)
19349 entry key value)
19350 (setq alist (sort (copy-sequence alist)
19351 (lambda (a b) (< (length (car a)) (length (car b))))))
19352 (while (setq entry (pop alist))
19353 (setq template
19354 (replace-regexp-in-string
19355 (concat "%" (regexp-quote (car entry)))
19356 (cdr entry) template t t)))
19357 template))
19359 (defun org-base-buffer (buffer)
19360 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
19361 (if (not buffer)
19362 buffer
19363 (or (buffer-base-buffer buffer)
19364 buffer)))
19366 (defun org-trim (s)
19367 "Remove whitespace at beginning and end of string."
19368 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
19369 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
19372 (defun org-wrap (string &optional width lines)
19373 "Wrap string to either a number of lines, or a width in characters.
19374 If WIDTH is non-nil, the string is wrapped to that width, however many lines
19375 that costs. If there is a word longer than WIDTH, the text is actually
19376 wrapped to the length of that word.
19377 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
19378 many lines, whatever width that takes.
19379 The return value is a list of lines, without newlines at the end."
19380 (let* ((words (org-split-string string "[ \t\n]+"))
19381 (maxword (apply 'max (mapcar 'org-string-width words)))
19382 w ll)
19383 (cond (width
19384 (org-do-wrap words (max maxword width)))
19385 (lines
19386 (setq w maxword)
19387 (setq ll (org-do-wrap words maxword))
19388 (if (<= (length ll) lines)
19390 (setq ll words)
19391 (while (> (length ll) lines)
19392 (setq w (1+ w))
19393 (setq ll (org-do-wrap words w)))
19394 ll))
19395 (t (error "Cannot wrap this")))))
19397 (defun org-do-wrap (words width)
19398 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
19399 (let (lines line)
19400 (while words
19401 (setq line (pop words))
19402 (while (and words (< (+ (length line) (length (car words))) width))
19403 (setq line (concat line " " (pop words))))
19404 (setq lines (push line lines)))
19405 (nreverse lines)))
19407 (defun org-split-string (string &optional separators)
19408 "Splits STRING into substrings at SEPARATORS.
19409 No empty strings are returned if there are matches at the beginning
19410 and end of string."
19411 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
19412 (start 0)
19413 notfirst
19414 (list nil))
19415 (while (and (string-match rexp string
19416 (if (and notfirst
19417 (= start (match-beginning 0))
19418 (< start (length string)))
19419 (1+ start) start))
19420 (< (match-beginning 0) (length string)))
19421 (setq notfirst t)
19422 (or (eq (match-beginning 0) 0)
19423 (and (eq (match-beginning 0) (match-end 0))
19424 (eq (match-beginning 0) start))
19425 (setq list
19426 (cons (substring string start (match-beginning 0))
19427 list)))
19428 (setq start (match-end 0)))
19429 (or (eq start (length string))
19430 (setq list
19431 (cons (substring string start)
19432 list)))
19433 (nreverse list)))
19435 (defun org-quote-vert (s)
19436 "Replace \"|\" with \"\\vert\"."
19437 (while (string-match "|" s)
19438 (setq s (replace-match "\\vert" t t s)))
19441 (defun org-uuidgen-p (s)
19442 "Is S an ID created by UUIDGEN?"
19443 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
19445 (defun org-context ()
19446 "Return a list of contexts of the current cursor position.
19447 If several contexts apply, all are returned.
19448 Each context entry is a list with a symbol naming the context, and
19449 two positions indicating start and end of the context. Possible
19450 contexts are:
19452 :headline anywhere in a headline
19453 :headline-stars on the leading stars in a headline
19454 :todo-keyword on a TODO keyword (including DONE) in a headline
19455 :tags on the TAGS in a headline
19456 :priority on the priority cookie in a headline
19457 :item on the first line of a plain list item
19458 :item-bullet on the bullet/number of a plain list item
19459 :checkbox on the checkbox in a plain list item
19460 :table in an org-mode table
19461 :table-special on a special filed in a table
19462 :table-table in a table.el table
19463 :link on a hyperlink
19464 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
19465 :target on a <<target>>
19466 :radio-target on a <<<radio-target>>>
19467 :latex-fragment on a LaTeX fragment
19468 :latex-preview on a LaTeX fragment with overlaid preview image
19470 This function expects the position to be visible because it uses font-lock
19471 faces as a help to recognize the following contexts: :table-special, :link,
19472 and :keyword."
19473 (let* ((f (get-text-property (point) 'face))
19474 (faces (if (listp f) f (list f)))
19475 (p (point)) clist o)
19476 ;; First the large context
19477 (cond
19478 ((org-on-heading-p t)
19479 (push (list :headline (point-at-bol) (point-at-eol)) clist)
19480 (when (progn
19481 (beginning-of-line 1)
19482 (looking-at org-todo-line-tags-regexp))
19483 (push (org-point-in-group p 1 :headline-stars) clist)
19484 (push (org-point-in-group p 2 :todo-keyword) clist)
19485 (push (org-point-in-group p 4 :tags) clist))
19486 (goto-char p)
19487 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
19488 (if (looking-at "\\[#[A-Z0-9]\\]")
19489 (push (org-point-in-group p 0 :priority) clist)))
19491 ((org-at-item-p)
19492 (push (org-point-in-group p 2 :item-bullet) clist)
19493 (push (list :item (point-at-bol)
19494 (save-excursion (org-end-of-item) (point)))
19495 clist)
19496 (and (org-at-item-checkbox-p)
19497 (push (org-point-in-group p 0 :checkbox) clist)))
19499 ((org-at-table-p)
19500 (push (list :table (org-table-begin) (org-table-end)) clist)
19501 (if (memq 'org-formula faces)
19502 (push (list :table-special
19503 (previous-single-property-change p 'face)
19504 (next-single-property-change p 'face)) clist)))
19505 ((org-at-table-p 'any)
19506 (push (list :table-table) clist)))
19507 (goto-char p)
19509 ;; Now the small context
19510 (cond
19511 ((org-at-timestamp-p)
19512 (push (org-point-in-group p 0 :timestamp) clist))
19513 ((memq 'org-link faces)
19514 (push (list :link
19515 (previous-single-property-change p 'face)
19516 (next-single-property-change p 'face)) clist))
19517 ((memq 'org-special-keyword faces)
19518 (push (list :keyword
19519 (previous-single-property-change p 'face)
19520 (next-single-property-change p 'face)) clist))
19521 ((org-on-target-p)
19522 (push (org-point-in-group p 0 :target) clist)
19523 (goto-char (1- (match-beginning 0)))
19524 (if (looking-at org-radio-target-regexp)
19525 (push (org-point-in-group p 0 :radio-target) clist))
19526 (goto-char p))
19527 ((setq o (car (delq nil
19528 (mapcar
19529 (lambda (x)
19530 (if (memq x org-latex-fragment-image-overlays) x))
19531 (overlays-at (point))))))
19532 (push (list :latex-fragment
19533 (overlay-start o) (overlay-end o)) clist)
19534 (push (list :latex-preview
19535 (overlay-start o) (overlay-end o)) clist))
19536 ((org-inside-LaTeX-fragment-p)
19537 ;; FIXME: positions wrong.
19538 (push (list :latex-fragment (point) (point)) clist)))
19540 (setq clist (nreverse (delq nil clist)))
19541 clist))
19543 ;; FIXME: Compare with at-regexp-p Do we need both?
19544 (defun org-in-regexp (re &optional nlines visually)
19545 "Check if point is inside a match of regexp.
19546 Normally only the current line is checked, but you can include NLINES extra
19547 lines both before and after point into the search.
19548 If VISUALLY is set, require that the cursor is not after the match but
19549 really on, so that the block visually is on the match."
19550 (catch 'exit
19551 (let ((pos (point))
19552 (eol (point-at-eol (+ 1 (or nlines 0))))
19553 (inc (if visually 1 0)))
19554 (save-excursion
19555 (beginning-of-line (- 1 (or nlines 0)))
19556 (while (re-search-forward re eol t)
19557 (if (and (<= (match-beginning 0) pos)
19558 (>= (+ inc (match-end 0)) pos))
19559 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
19561 (defun org-at-regexp-p (regexp)
19562 "Is point inside a match of REGEXP in the current line?"
19563 (catch 'exit
19564 (save-excursion
19565 (let ((pos (point)) (end (point-at-eol)))
19566 (beginning-of-line 1)
19567 (while (re-search-forward regexp end t)
19568 (if (and (<= (match-beginning 0) pos)
19569 (>= (match-end 0) pos))
19570 (throw 'exit t)))
19571 nil))))
19573 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
19574 "Non-nil when point is between matches of START-RE and END-RE.
19576 Also return a non-nil value when point is on one of the matches.
19578 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
19579 buffer positions. Default values are the positions of headlines
19580 surrounding the point.
19582 The functions returns a cons cell whose car (resp. cdr) is the
19583 position before START-RE (resp. after END-RE)."
19584 (save-match-data
19585 (let ((pos (point))
19586 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
19587 (limit-down (or lim-down (save-excursion (outline-next-heading))))
19588 beg end)
19589 (save-excursion
19590 ;; Point is on a block when on START-RE or if START-RE can be
19591 ;; found before it...
19592 (and (or (org-at-regexp-p start-re)
19593 (re-search-backward start-re limit-up t))
19594 (setq beg (match-beginning 0))
19595 ;; ... and END-RE after it...
19596 (goto-char (match-end 0))
19597 (re-search-forward end-re limit-down t)
19598 (> (setq end (match-end 0)) pos)
19599 ;; ... without another START-RE in-between.
19600 (goto-char (match-beginning 0))
19601 (not (re-search-backward start-re (1+ beg) t))
19602 ;; Return value.
19603 (cons beg end))))))
19605 (defun org-in-block-p (names)
19606 "Non-nil when point belongs to a block whose name belongs to NAMES.
19608 NAMES is a list of strings containing names of blocks.
19610 Return first block name matched, or nil. Beware that in case of
19611 nested blocks, the returned name may not belong to the closest
19612 block from point."
19613 (save-match-data
19614 (catch 'exit
19615 (let ((case-fold-search t)
19616 (lim-up (save-excursion (outline-previous-heading)))
19617 (lim-down (save-excursion (outline-next-heading))))
19618 (mapc (lambda (name)
19619 (let ((n (regexp-quote name)))
19620 (when (org-between-regexps-p
19621 (concat "^[ \t]*#\\+begin_" n)
19622 (concat "^[ \t]*#\\+end_" n)
19623 lim-up lim-down)
19624 (throw 'exit n))))
19625 names))
19626 nil)))
19628 (defun org-occur-in-agenda-files (regexp &optional nlines)
19629 "Call `multi-occur' with buffers for all agenda files."
19630 (interactive "sOrg-files matching: \np")
19631 (let* ((files (org-agenda-files))
19632 (tnames (mapcar 'file-truename files))
19633 (extra org-agenda-text-search-extra-files)
19635 (when (eq (car extra) 'agenda-archives)
19636 (setq extra (cdr extra))
19637 (setq files (org-add-archive-files files)))
19638 (while (setq f (pop extra))
19639 (unless (member (file-truename f) tnames)
19640 (add-to-list 'files f 'append)
19641 (add-to-list 'tnames (file-truename f) 'append)))
19642 (multi-occur
19643 (mapcar (lambda (x)
19644 (with-current-buffer
19645 (or (get-file-buffer x) (find-file-noselect x))
19646 (widen)
19647 (current-buffer)))
19648 files)
19649 regexp)))
19651 (if (boundp 'occur-mode-find-occurrence-hook)
19652 ;; Emacs 23
19653 (add-hook 'occur-mode-find-occurrence-hook
19654 (lambda ()
19655 (when (eq major-mode 'org-mode)
19656 (org-reveal))))
19657 ;; Emacs 22
19658 (defadvice occur-mode-goto-occurrence
19659 (after org-occur-reveal activate)
19660 (and (eq major-mode 'org-mode) (org-reveal)))
19661 (defadvice occur-mode-goto-occurrence-other-window
19662 (after org-occur-reveal activate)
19663 (and (eq major-mode 'org-mode) (org-reveal)))
19664 (defadvice occur-mode-display-occurrence
19665 (after org-occur-reveal activate)
19666 (when (eq major-mode 'org-mode)
19667 (let ((pos (occur-mode-find-occurrence)))
19668 (with-current-buffer (marker-buffer pos)
19669 (save-excursion
19670 (goto-char pos)
19671 (org-reveal)))))))
19673 (defun org-occur-link-in-agenda-files ()
19674 "Create a link and search for it in the agendas.
19675 The link is not stored in `org-stored-links', it is just created
19676 for the search purpose."
19677 (interactive)
19678 (let ((link (condition-case nil
19679 (org-store-link nil)
19680 (error "Unable to create a link to here"))))
19681 (org-occur-in-agenda-files (regexp-quote link))))
19683 (defun org-uniquify (list)
19684 "Remove duplicate elements from LIST."
19685 (let (res)
19686 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
19687 res))
19689 (defun org-delete-all (elts list)
19690 "Remove all elements in ELTS from LIST."
19691 (while elts
19692 (setq list (delete (pop elts) list)))
19693 list)
19695 (defun org-count (cl-item cl-seq)
19696 "Count the number of occurrences of ITEM in SEQ.
19697 Taken from `count' in cl-seq.el with all keyword arguments removed."
19698 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
19699 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
19700 (while (< cl-start cl-end)
19701 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
19702 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
19703 (setq cl-start (1+ cl-start)))
19704 cl-count))
19706 (defun org-remove-if (predicate seq)
19707 "Remove everything from SEQ that fulfills PREDICATE."
19708 (let (res e)
19709 (while seq
19710 (setq e (pop seq))
19711 (if (not (funcall predicate e)) (push e res)))
19712 (nreverse res)))
19714 (defun org-remove-if-not (predicate seq)
19715 "Remove everything from SEQ that does not fulfill PREDICATE."
19716 (let (res e)
19717 (while seq
19718 (setq e (pop seq))
19719 (if (funcall predicate e) (push e res)))
19720 (nreverse res)))
19722 (defun org-reduce (cl-func cl-seq &rest cl-keys)
19723 "Reduce two-argument FUNCTION across SEQ.
19724 Taken from `reduce' in cl-seq.el with all keyword arguments but
19725 \":initial-value\" removed."
19726 (let ((cl-accum (cond ((memq :initial-value cl-keys)
19727 (cadr (memq :initial-value cl-keys)))
19728 (cl-seq (pop cl-seq))
19729 (t (funcall cl-func)))))
19730 (while cl-seq
19731 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
19732 cl-accum))
19734 (defun org-back-over-empty-lines ()
19735 "Move backwards over whitespace, to the beginning of the first empty line.
19736 Returns the number of empty lines passed."
19737 (let ((pos (point)))
19738 (if (cdr (assoc 'heading org-blank-before-new-entry))
19739 (skip-chars-backward " \t\n\r")
19740 (unless (eobp)
19741 (forward-line -1)))
19742 (beginning-of-line 2)
19743 (goto-char (min (point) pos))
19744 (count-lines (point) pos)))
19746 (defun org-skip-whitespace ()
19747 (skip-chars-forward " \t\n\r"))
19749 (defun org-point-in-group (point group &optional context)
19750 "Check if POINT is in match-group GROUP.
19751 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
19752 match. If the match group does not exist or point is not inside it,
19753 return nil."
19754 (and (match-beginning group)
19755 (>= point (match-beginning group))
19756 (<= point (match-end group))
19757 (if context
19758 (list context (match-beginning group) (match-end group))
19759 t)))
19761 (defun org-switch-to-buffer-other-window (&rest args)
19762 "Switch to buffer in a second window on the current frame.
19763 In particular, do not allow pop-up frames.
19764 Returns the newly created buffer."
19765 (let (pop-up-frames special-display-buffer-names special-display-regexps
19766 special-display-function)
19767 (apply 'switch-to-buffer-other-window args)))
19769 (defun org-combine-plists (&rest plists)
19770 "Create a single property list from all plists in PLISTS.
19771 The process starts by copying the first list, and then setting properties
19772 from the other lists. Settings in the last list are the most significant
19773 ones and overrule settings in the other lists."
19774 (let ((rtn (copy-sequence (pop plists)))
19775 p v ls)
19776 (while plists
19777 (setq ls (pop plists))
19778 (while ls
19779 (setq p (pop ls) v (pop ls))
19780 (setq rtn (plist-put rtn p v))))
19781 rtn))
19783 (defun org-move-line-down (arg)
19784 "Move the current line down. With prefix argument, move it past ARG lines."
19785 (interactive "p")
19786 (let ((col (current-column))
19787 beg end pos)
19788 (beginning-of-line 1) (setq beg (point))
19789 (beginning-of-line 2) (setq end (point))
19790 (beginning-of-line (+ 1 arg))
19791 (setq pos (move-marker (make-marker) (point)))
19792 (insert (delete-and-extract-region beg end))
19793 (goto-char pos)
19794 (org-move-to-column col)))
19796 (defun org-move-line-up (arg)
19797 "Move the current line up. With prefix argument, move it past ARG lines."
19798 (interactive "p")
19799 (let ((col (current-column))
19800 beg end pos)
19801 (beginning-of-line 1) (setq beg (point))
19802 (beginning-of-line 2) (setq end (point))
19803 (beginning-of-line (- arg))
19804 (setq pos (move-marker (make-marker) (point)))
19805 (insert (delete-and-extract-region beg end))
19806 (goto-char pos)
19807 (org-move-to-column col)))
19809 (defun org-replace-escapes (string table)
19810 "Replace %-escapes in STRING with values in TABLE.
19811 TABLE is an association list with keys like \"%a\" and string values.
19812 The sequences in STRING may contain normal field width and padding information,
19813 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
19814 so values can contain further %-escapes if they are define later in TABLE."
19815 (let ((tbl (copy-alist table))
19816 (case-fold-search nil)
19817 (pchg 0)
19818 e re rpl)
19819 (while (setq e (pop tbl))
19820 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
19821 (when (and (cdr e) (string-match re (cdr e)))
19822 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
19823 (safe "SREF"))
19824 (add-text-properties 0 3 (list 'sref sref) safe)
19825 (setcdr e (replace-match safe t t (cdr e)))))
19826 (while (string-match re string)
19827 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
19828 (cdr e)))
19829 (setq string (replace-match rpl t t string))))
19830 (while (setq pchg (next-property-change pchg string))
19831 (let ((sref (get-text-property pchg 'sref string)))
19832 (when (and sref (string-match "SREF" string pchg))
19833 (setq string (replace-match sref t t string)))))
19834 string))
19836 (defun org-sublist (list start end)
19837 "Return a section of LIST, from START to END.
19838 Counting starts at 1."
19839 (let (rtn (c start))
19840 (setq list (nthcdr (1- start) list))
19841 (while (and list (<= c end))
19842 (push (pop list) rtn)
19843 (setq c (1+ c)))
19844 (nreverse rtn)))
19846 (defun org-find-base-buffer-visiting (file)
19847 "Like `find-buffer-visiting' but always return the base buffer and
19848 not an indirect buffer."
19849 (let ((buf (or (get-file-buffer file)
19850 (find-buffer-visiting file))))
19851 (if buf
19852 (or (buffer-base-buffer buf) buf)
19853 nil)))
19855 (defun org-image-file-name-regexp (&optional extensions)
19856 "Return regexp matching the file names of images.
19857 If EXTENSIONS is given, only match these."
19858 (if (and (not extensions) (fboundp 'image-file-name-regexp))
19859 (image-file-name-regexp)
19860 (let ((image-file-name-extensions
19861 (or extensions
19862 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
19863 "xbm" "xpm" "pbm" "pgm" "ppm"))))
19864 (concat "\\."
19865 (regexp-opt (nconc (mapcar 'upcase
19866 image-file-name-extensions)
19867 image-file-name-extensions)
19869 "\\'"))))
19871 (defun org-file-image-p (file &optional extensions)
19872 "Return non-nil if FILE is an image."
19873 (save-match-data
19874 (string-match (org-image-file-name-regexp extensions) file)))
19876 (defun org-get-cursor-date ()
19877 "Return the date at cursor in as a time.
19878 This works in the calendar and in the agenda, anywhere else it just
19879 returns the current time."
19880 (let (date day defd)
19881 (cond
19882 ((eq major-mode 'calendar-mode)
19883 (setq date (calendar-cursor-to-date)
19884 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
19885 ((eq major-mode 'org-agenda-mode)
19886 (setq day (get-text-property (point) 'day))
19887 (if day
19888 (setq date (calendar-gregorian-from-absolute day)
19889 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
19890 (nth 2 date))))))
19891 (or defd (current-time))))
19893 (defvar org-agenda-action-marker (make-marker)
19894 "Marker pointing to the entry for the next agenda action.")
19896 (defun org-mark-entry-for-agenda-action ()
19897 "Mark the current entry as target of an agenda action.
19898 Agenda actions are actions executed from the agenda with the key `k',
19899 which make use of the date at the cursor."
19900 (interactive)
19901 (move-marker org-agenda-action-marker
19902 (save-excursion (org-back-to-heading t) (point))
19903 (current-buffer))
19904 (message
19905 "Entry marked for action; press `k' at desired date in agenda or calendar"))
19907 (defun org-mark-subtree ()
19908 "Mark the current subtree.
19909 This puts point at the start of the current subtree, and mark at the end.
19911 If point is in an inline task, mark that task instead."
19912 (interactive)
19913 (let ((inline-task-p
19914 (and (featurep 'org-inlinetask)
19915 (org-inlinetask-in-task-p)))
19916 (beg))
19917 ;; Get beginning of subtree
19918 (cond
19919 (inline-task-p (org-inlinetask-goto-beginning))
19920 ((org-at-heading-p) (beginning-of-line))
19921 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
19922 (setq beg (point))
19923 ;; Get end of it
19924 (if inline-task-p
19925 (org-inlinetask-goto-end)
19926 (org-end-of-subtree))
19927 ;; Mark zone
19928 (push-mark (point) nil t)
19929 (goto-char beg)))
19931 ;;; Paragraph filling stuff.
19932 ;; We want this to be just right, so use the full arsenal.
19934 (defun org-indent-line-function ()
19935 "Indent line depending on context."
19936 (interactive)
19937 (let* ((pos (point))
19938 (itemp (org-at-item-p))
19939 (case-fold-search t)
19940 (org-drawer-regexp (or org-drawer-regexp "\000"))
19941 (inline-task-p (and (featurep 'org-inlinetask)
19942 (org-inlinetask-in-task-p)))
19943 (inline-re (and inline-task-p
19944 (org-inlinetask-outline-regexp)))
19945 column)
19946 (beginning-of-line 1)
19947 (cond
19948 ;; Comments
19949 ((looking-at "# ") (setq column 0))
19950 ;; Headings
19951 ((looking-at org-outline-regexp) (setq column 0))
19952 ;; Included files
19953 ((looking-at "#\\+include:") (setq column 0))
19954 ;; Footnote definition
19955 ((looking-at org-footnote-definition-re) (setq column 0))
19956 ;; Literal examples
19957 ((looking-at "[ \t]*:\\( \\|$\\)")
19958 (setq column (org-get-indentation))) ; do nothing
19959 ;; Lists
19960 ((ignore-errors (goto-char (org-in-item-p)))
19961 (setq column (if itemp
19962 (org-get-indentation)
19963 (org-list-item-body-column (point))))
19964 (goto-char pos))
19965 ;; Drawers
19966 ((and (looking-at "[ \t]*:END:")
19967 (save-excursion (re-search-backward org-drawer-regexp nil t)))
19968 (save-excursion
19969 (goto-char (1- (match-beginning 1)))
19970 (setq column (current-column))))
19971 ;; Special blocks
19972 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
19973 (save-excursion
19974 (re-search-backward
19975 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
19976 (setq column (org-get-indentation (match-string 0))))
19977 ((and (not (looking-at "[ \t]*#\\+begin_"))
19978 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
19979 (save-excursion
19980 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
19981 (setq column
19982 (cond ((equal (downcase (match-string 1)) "src")
19983 ;; src blocks: let `org-edit-src-exit' handle them
19984 (org-get-indentation))
19985 ((equal (downcase (match-string 1)) "example")
19986 (max (org-get-indentation)
19987 (org-get-indentation (match-string 0))))
19989 (org-get-indentation (match-string 0))))))
19990 ;; This line has nothing special, look at the previous relevant
19991 ;; line to compute indentation
19993 (beginning-of-line 0)
19994 (while (and (not (bobp))
19995 (not (looking-at org-drawer-regexp))
19996 ;; When point started in an inline task, do not move
19997 ;; above task starting line.
19998 (not (and inline-task-p (looking-at inline-re)))
19999 ;; Skip drawers, blocks, empty lines, verbatim,
20000 ;; comments, tables, footnotes definitions, lists,
20001 ;; inline tasks.
20002 (or (and (looking-at "[ \t]*:END:")
20003 (re-search-backward org-drawer-regexp nil t))
20004 (and (looking-at "[ \t]*#\\+end_")
20005 (re-search-backward "[ \t]*#\\+begin_"nil t))
20006 (looking-at "[ \t]*[\n:#|]")
20007 (looking-at org-footnote-definition-re)
20008 (and (ignore-errors (goto-char (org-in-item-p)))
20009 (goto-char
20010 (org-list-get-top-point (org-list-struct))))
20011 (and (not inline-task-p)
20012 (featurep 'org-inlinetask)
20013 (org-inlinetask-in-task-p)
20014 (or (org-inlinetask-goto-beginning) t))))
20015 (beginning-of-line 0))
20016 (cond
20017 ;; There was an heading above.
20018 ((looking-at "\\*+[ \t]+")
20019 (if (not org-adapt-indentation)
20020 (setq column 0)
20021 (goto-char (match-end 0))
20022 (setq column (current-column))))
20023 ;; A drawer had started and is unfinished
20024 ((looking-at org-drawer-regexp)
20025 (goto-char (1- (match-beginning 1)))
20026 (setq column (current-column)))
20027 ;; Else, nothing noticeable found: get indentation and go on.
20028 (t (setq column (org-get-indentation))))))
20029 ;; Now apply indentation and move cursor accordingly
20030 (goto-char pos)
20031 (if (<= (current-column) (current-indentation))
20032 (org-indent-line-to column)
20033 (save-excursion (org-indent-line-to column)))
20034 ;; Special polishing for properties, see `org-property-format'
20035 (setq column (current-column))
20036 (beginning-of-line 1)
20037 (if (looking-at
20038 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20039 (replace-match (concat (match-string 1)
20040 (format org-property-format
20041 (match-string 2) (match-string 3)))
20042 t t))
20043 (org-move-to-column column)))
20045 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
20046 "Variable to store copy of `adaptive-fill-regexp'.
20047 Since `adaptive-fill-regexp' is set to never match, we need to
20048 store a backup of its value before entering `org-mode' so that
20049 the functionality can be provided as a fall-back.")
20051 (defun org-set-autofill-regexps ()
20052 (interactive)
20053 ;; In the paragraph separator we include headlines, because filling
20054 ;; text in a line directly attached to a headline would otherwise
20055 ;; fill the headline as well.
20056 (org-set-local 'comment-start-skip "^#+[ \t]*")
20057 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
20058 ;; The paragraph starter includes hand-formatted lists.
20059 (org-set-local
20060 'paragraph-start
20061 (concat
20062 "\f" "\\|"
20063 "[ ]*$" "\\|"
20064 org-outline-regexp "\\|"
20065 "[ \t]*#" "\\|"
20066 (org-item-re) "\\|"
20067 "[ \t]*[:|]" "\\|"
20068 "\\$\\$" "\\|"
20069 "\\\\\\(begin\\|end\\|[][]\\)"))
20070 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
20071 ;; But only if the user has not turned off tables or fixed-width regions
20072 (org-set-local
20073 'auto-fill-inhibit-regexp
20074 (concat org-outline-regexp
20075 "\\|#\\+"
20076 "\\|[ \t]*" org-keyword-time-regexp
20077 (if (or org-enable-table-editor org-enable-fixed-width-editor)
20078 (concat
20079 "\\|[ \t]*["
20080 (if org-enable-table-editor "|" "")
20081 (if org-enable-fixed-width-editor ":" "")
20082 "]"))))
20083 ;; We use our own fill-paragraph function, to make sure that tables
20084 ;; and fixed-width regions are not wrapped. That function will pass
20085 ;; through to `fill-paragraph' when appropriate.
20086 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20087 ;; Prevent auto-fill from inserting unwanted new items.
20088 (if (boundp 'fill-nobreak-predicate)
20089 (org-set-local 'fill-nobreak-predicate
20090 (if (memq 'org-fill-item-nobreak-p fill-nobreak-predicate)
20091 fill-nobreak-predicate
20092 (cons 'org-fill-item-nobreak-p fill-nobreak-predicate))))
20093 ;; Adaptive filling: To get full control, first make sure that
20094 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
20095 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
20096 (org-set-local 'org-adaptive-fill-regexp-backup
20097 adaptive-fill-regexp))
20098 (org-set-local 'adaptive-fill-regexp "\000")
20099 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20100 (org-set-local 'adaptive-fill-function
20101 'org-adaptive-fill-function)
20102 (org-set-local
20103 'align-mode-rules-list
20104 '((org-in-buffer-settings
20105 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
20106 (modes . '(org-mode))))))
20108 (defun org-fill-item-nobreak-p ()
20109 "Non-nil when a line break at point would insert a new item."
20110 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
20112 (defun org-fill-paragraph (&optional justify)
20113 "Re-align a table, pass through to fill-paragraph if no table."
20114 (let ((table-p (org-at-table-p))
20115 (table.el-p (org-at-table.el-p))
20116 (itemp (org-in-item-p)))
20117 (cond ((and (equal (char-after (point-at-bol)) ?*)
20118 (save-excursion (goto-char (point-at-bol))
20119 (looking-at org-outline-regexp)))
20120 t) ; skip headlines
20121 (table.el-p t) ; skip table.el tables
20122 (table-p (org-table-align) t) ; align Org tables
20123 (itemp ; align text in items
20124 (let* ((struct (save-excursion (goto-char itemp)
20125 (org-list-struct)))
20126 (parents (org-list-parents-alist struct))
20127 (children (org-list-get-children itemp struct parents))
20128 beg end prev next prefix)
20129 ;; Determine in which part of item point is: before
20130 ;; first child, after last child, between two
20131 ;; sub-lists, or simply in item if there's no child.
20132 (cond
20133 ((not children)
20134 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20135 beg itemp
20136 end (org-list-get-item-end itemp struct)))
20137 ((< (point) (setq next (car children)))
20138 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20139 beg itemp
20140 end next))
20141 ((> (point) (setq prev (car (last children))))
20142 (setq beg (org-list-get-item-end prev struct)
20143 end (org-list-get-item-end itemp struct)
20144 prefix (save-excursion
20145 (goto-char beg)
20146 (skip-chars-forward " \t")
20147 (make-string (current-column) ?\ ))))
20148 (t (catch 'exit
20149 (while (setq next (pop children))
20150 (if (> (point) next)
20151 (setq prev next)
20152 (setq beg (org-list-get-item-end prev struct)
20153 end next
20154 prefix (save-excursion
20155 (goto-char beg)
20156 (skip-chars-forward " \t")
20157 (make-string (current-column) ?\ )))
20158 (throw 'exit nil))))))
20159 ;; Use `fill-paragraph' with buffer narrowed to item
20160 ;; without any child, and with our computed PREFIX.
20161 (flet ((fill-context-prefix (from to &optional flr) prefix))
20162 (save-restriction
20163 (narrow-to-region beg end)
20164 (save-excursion (fill-paragraph justify)))) t))
20165 ;; Special case where point is not in a list but is on
20166 ;; a paragraph adjacent to a list: make sure this paragraph
20167 ;; doesn't get merged with the end of the list by narrowing
20168 ;; buffer first.
20169 ((save-excursion (forward-paragraph -1)
20170 (setq itemp (org-in-item-p)))
20171 (let ((struct (save-excursion (goto-char itemp)
20172 (org-list-struct))))
20173 (save-restriction
20174 (narrow-to-region (org-list-get-bottom-point struct)
20175 (save-excursion (forward-paragraph 1)
20176 (point)))
20177 (fill-paragraph justify) t)))
20178 ;; Else simply call `fill-paragraph'.
20179 (t nil))))
20181 ;; For reference, this is the default value of adaptive-fill-regexp
20182 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
20184 (defun org-adaptive-fill-function ()
20185 "Return a fill prefix for org-mode files."
20186 (let (itemp)
20187 (save-excursion
20188 (cond
20189 ;; Comment line
20190 ((looking-at "#[ \t]+")
20191 (match-string-no-properties 0))
20192 ;; Plain list item
20193 ((org-at-item-p)
20194 (make-string (org-list-item-body-column (point-at-bol)) ?\ ))
20195 ;; Point is in a list after `backward-paragraph': original
20196 ;; point wasn't in the list, or filling would have been taken
20197 ;; care of by `org-auto-fill-function', but the list and the
20198 ;; real paragraph are not separated by a blank line. Thus, move
20199 ;; point after the list to go back to real paragraph and
20200 ;; determine fill-prefix.
20201 ((setq itemp (org-in-item-p))
20202 (goto-char itemp)
20203 (let* ((struct (org-list-struct))
20204 (bottom (org-list-get-bottom-point struct)))
20205 (goto-char bottom)
20206 (make-string (org-get-indentation) ?\ )))
20207 ;; Other text
20208 ((looking-at org-adaptive-fill-regexp-backup)
20209 (match-string-no-properties 0))))))
20211 (defun org-auto-fill-function ()
20212 "Auto-fill function."
20213 (let (itemp prefix)
20214 ;; When in a list, compute an appropriate fill-prefix and make
20215 ;; sure it will be used by `do-auto-fill'.
20216 (if (setq itemp (org-in-item-p))
20217 (progn
20218 (setq prefix (make-string (org-list-item-body-column itemp) ?\ ))
20219 (flet ((fill-context-prefix (from to &optional flr) prefix))
20220 (do-auto-fill)))
20221 ;; Else just use `do-auto-fill'.
20222 (do-auto-fill))))
20224 ;;; Other stuff.
20226 (defun org-toggle-fixed-width-section (arg)
20227 "Toggle the fixed-width export.
20228 If there is no active region, the QUOTE keyword at the current headline is
20229 inserted or removed. When present, it causes the text between this headline
20230 and the next to be exported as fixed-width text, and unmodified.
20231 If there is an active region, this command adds or removes a colon as the
20232 first character of this line. If the first character of a line is a colon,
20233 this line is also exported in fixed-width font."
20234 (interactive "P")
20235 (let* ((cc 0)
20236 (regionp (org-region-active-p))
20237 (beg (if regionp (region-beginning) (point)))
20238 (end (if regionp (region-end)))
20239 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
20240 (case-fold-search nil)
20241 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
20242 off)
20243 (if regionp
20244 (save-excursion
20245 (goto-char beg)
20246 (setq cc (current-column))
20247 (beginning-of-line 1)
20248 (setq off (looking-at re))
20249 (while (> nlines 0)
20250 (setq nlines (1- nlines))
20251 (beginning-of-line 1)
20252 (cond
20253 (arg
20254 (org-move-to-column cc t)
20255 (insert ": \n")
20256 (forward-line -1))
20257 ((and off (looking-at re))
20258 (replace-match "" t t nil 1))
20259 ((not off) (org-move-to-column cc t) (insert ": ")))
20260 (forward-line 1)))
20261 (save-excursion
20262 (org-back-to-heading)
20263 (cond
20264 ((looking-at (format org-heading-keyword-regexp-format
20265 org-quote-string))
20266 (goto-char (match-end 1))
20267 (looking-at (concat " +" org-quote-string))
20268 (replace-match "" t t)
20269 (when (eolp) (insert " ")))
20270 ((looking-at org-outline-regexp)
20271 (goto-char (match-end 0))
20272 (insert org-quote-string " ")))))))
20274 (defun org-reftex-citation ()
20275 "Use reftex-citation to insert a citation into the buffer.
20276 This looks for a line like
20278 #+BIBLIOGRAPHY: foo plain option:-d
20280 and derives from it that foo.bib is the bibliography file relevant
20281 for this document. It then installs the necessary environment for RefTeX
20282 to work in this buffer and calls `reftex-citation' to insert a citation
20283 into the buffer.
20285 Export of such citations to both LaTeX and HTML is handled by the contributed
20286 package org-exp-bibtex by Taru Karttunen."
20287 (interactive)
20288 (let ((reftex-docstruct-symbol 'rds)
20289 (reftex-cite-format "\\cite{%l}")
20290 rds bib)
20291 (save-excursion
20292 (save-restriction
20293 (widen)
20294 (let ((case-fold-search t)
20295 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
20296 (if (not (save-excursion
20297 (or (re-search-forward re nil t)
20298 (re-search-backward re nil t))))
20299 (error "No bibliography defined in file")
20300 (setq bib (concat (match-string 1) ".bib")
20301 rds (list (list 'bib bib)))))))
20302 (call-interactively 'reftex-citation)))
20304 ;;;; Functions extending outline functionality
20306 (defun org-beginning-of-line (&optional arg)
20307 "Go to the beginning of the current line. If that is invisible, continue
20308 to a visible line beginning. This makes the function of C-a more intuitive.
20309 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20310 first attempt, and only move to after the tags when the cursor is already
20311 beyond the end of the headline."
20312 (interactive "P")
20313 (let ((pos (point))
20314 (special (if (consp org-special-ctrl-a/e)
20315 (car org-special-ctrl-a/e)
20316 org-special-ctrl-a/e))
20317 refpos)
20318 (if (org-bound-and-true-p line-move-visual)
20319 (beginning-of-visual-line 1)
20320 (beginning-of-line 1))
20321 (if (and arg (fboundp 'move-beginning-of-line))
20322 (call-interactively 'move-beginning-of-line)
20323 (if (bobp)
20325 (backward-char 1)
20326 (if (org-truely-invisible-p)
20327 (while (and (not (bobp)) (org-truely-invisible-p))
20328 (backward-char 1)
20329 (beginning-of-line 1))
20330 (forward-char 1))))
20331 (when special
20332 (cond
20333 ((and (looking-at org-complex-heading-regexp)
20334 (= (char-after (match-end 1)) ?\ ))
20335 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
20336 (point-at-eol)))
20337 (goto-char
20338 (if (eq special t)
20339 (cond ((> pos refpos) refpos)
20340 ((= pos (point)) refpos)
20341 (t (point)))
20342 (cond ((> pos (point)) (point))
20343 ((not (eq last-command this-command)) (point))
20344 (t refpos)))))
20345 ((org-at-item-p)
20346 (goto-char
20347 (if (eq special t)
20348 (cond ((> pos (match-end 0)) (match-end 0))
20349 ((= pos (point)) (match-end 0))
20350 (t (point)))
20351 (cond ((> pos (point)) (point))
20352 ((not (eq last-command this-command)) (point))
20353 (t (match-end 0))))))))
20354 (org-no-warnings
20355 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20357 (defun org-end-of-line (&optional arg)
20358 "Go to the end of the line.
20359 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20360 first attempt, and only move to after the tags when the cursor is already
20361 beyond the end of the headline."
20362 (interactive "P")
20363 (let ((special (if (consp org-special-ctrl-a/e)
20364 (cdr org-special-ctrl-a/e)
20365 org-special-ctrl-a/e)))
20366 (cond
20367 ((or (not special) arg
20368 (not (or (org-on-heading-p) (org-at-item-p))))
20369 (call-interactively
20370 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
20371 ((fboundp 'move-end-of-line) 'move-end-of-line)
20372 (t 'end-of-line))))
20373 ((org-on-heading-p)
20374 (let ((pos (point)))
20375 (beginning-of-line 1)
20376 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
20377 (if (eq special t)
20378 (if (or (< pos (match-beginning 1))
20379 (= pos (match-end 0)))
20380 (goto-char (match-beginning 1))
20381 (goto-char (match-end 0)))
20382 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
20383 (goto-char (match-end 0))
20384 (goto-char (match-beginning 1))))
20385 (call-interactively (if (fboundp 'move-end-of-line)
20386 'move-end-of-line
20387 'end-of-line)))))
20388 ;; At an item: Move before any hidden text.
20389 (t (call-interactively 'end-of-line)))
20390 (org-no-warnings
20391 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20393 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
20394 (define-key org-mode-map "\C-e" 'org-end-of-line)
20396 (defun org-backward-sentence (&optional arg)
20397 "Go to beginning of sentence, or beginning of table field.
20398 This will call `backward-sentence' or `org-table-beginning-of-field',
20399 depending on context."
20400 (interactive "P")
20401 (cond
20402 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
20403 (t (call-interactively 'backward-sentence))))
20405 (defun org-forward-sentence (&optional arg)
20406 "Go to end of sentence, or end of table field.
20407 This will call `forward-sentence' or `org-table-end-of-field',
20408 depending on context."
20409 (interactive "P")
20410 (cond
20411 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
20412 (t (call-interactively 'forward-sentence))))
20414 (define-key org-mode-map "\M-a" 'org-backward-sentence)
20415 (define-key org-mode-map "\M-e" 'org-forward-sentence)
20417 (defun org-kill-line (&optional arg)
20418 "Kill line, to tags or end of line."
20419 (interactive "P")
20420 (cond
20421 ((or (not org-special-ctrl-k)
20422 (bolp)
20423 (not (org-on-heading-p)))
20424 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
20425 org-ctrl-k-protect-subtree)
20426 (if (or (eq org-ctrl-k-protect-subtree 'error)
20427 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
20428 (error "C-k aborted - would kill hidden subtree")))
20429 (call-interactively 'kill-line))
20430 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
20431 (kill-region (point) (match-beginning 1))
20432 (org-set-tags nil t))
20433 (t (kill-region (point) (point-at-eol)))))
20435 (define-key org-mode-map "\C-k" 'org-kill-line)
20437 (defun org-yank (&optional arg)
20438 "Yank. If the kill is a subtree, treat it specially.
20439 This command will look at the current kill and check if is a single
20440 subtree, or a series of subtrees[1]. If it passes the test, and if the
20441 cursor is at the beginning of a line or after the stars of a currently
20442 empty headline, then the yank is handled specially. How exactly depends
20443 on the value of the following variables, both set by default.
20445 org-yank-folded-subtrees
20446 When set, the subtree(s) will be folded after insertion, but only
20447 if doing so would now swallow text after the yanked text.
20449 org-yank-adjusted-subtrees
20450 When set, the subtree will be promoted or demoted in order to
20451 fit into the local outline tree structure, which means that the level
20452 will be adjusted so that it becomes the smaller one of the two
20453 *visible* surrounding headings.
20455 Any prefix to this command will cause `yank' to be called directly with
20456 no special treatment. In particular, a simple \\[universal-argument] prefix \
20457 will just
20458 plainly yank the text as it is.
20460 \[1] The test checks if the first non-white line is a heading
20461 and if there are no other headings with fewer stars."
20462 (interactive "P")
20463 (org-yank-generic 'yank arg))
20465 (defun org-yank-generic (command arg)
20466 "Perform some yank-like command.
20468 This function implements the behavior described in the `org-yank'
20469 documentation. However, it has been generalized to work for any
20470 interactive command with similar behavior."
20472 ;; pretend to be command COMMAND
20473 (setq this-command command)
20475 (if arg
20476 (call-interactively command)
20478 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
20479 (and (org-kill-is-subtree-p)
20480 (or (bolp)
20481 (and (looking-at "[ \t]*$")
20482 (string-match
20483 "\\`\\*+\\'"
20484 (buffer-substring (point-at-bol) (point)))))))
20485 swallowp)
20486 (cond
20487 ((and subtreep org-yank-folded-subtrees)
20488 (let ((beg (point))
20489 end)
20490 (if (and subtreep org-yank-adjusted-subtrees)
20491 (org-paste-subtree nil nil 'for-yank)
20492 (call-interactively command))
20494 (setq end (point))
20495 (goto-char beg)
20496 (when (and (bolp) subtreep
20497 (not (setq swallowp
20498 (org-yank-folding-would-swallow-text beg end))))
20499 (org-with-limited-levels
20500 (or (looking-at org-outline-regexp)
20501 (re-search-forward org-outline-regexp-bol end t))
20502 (while (and (< (point) end) (looking-at org-outline-regexp))
20503 (hide-subtree)
20504 (org-cycle-show-empty-lines 'folded)
20505 (condition-case nil
20506 (outline-forward-same-level 1)
20507 (error (goto-char end))))))
20508 (when swallowp
20509 (message
20510 "Inserted text not folded because that would swallow text"))
20512 (goto-char end)
20513 (skip-chars-forward " \t\n\r")
20514 (beginning-of-line 1)
20515 (push-mark beg 'nomsg)))
20516 ((and subtreep org-yank-adjusted-subtrees)
20517 (let ((beg (point-at-bol)))
20518 (org-paste-subtree nil nil 'for-yank)
20519 (push-mark beg 'nomsg)))
20521 (call-interactively command))))))
20523 (defun org-yank-folding-would-swallow-text (beg end)
20524 "Would hide-subtree at BEG swallow any text after END?"
20525 (let (level)
20526 (org-with-limited-levels
20527 (save-excursion
20528 (goto-char beg)
20529 (when (or (looking-at org-outline-regexp)
20530 (re-search-forward org-outline-regexp-bol end t))
20531 (setq level (org-outline-level)))
20532 (goto-char end)
20533 (skip-chars-forward " \t\r\n\v\f")
20534 (if (or (eobp)
20535 (and (bolp) (looking-at org-outline-regexp)
20536 (<= (org-outline-level) level)))
20537 nil ; Nothing would be swallowed
20538 t))))) ; something would swallow
20540 (define-key org-mode-map "\C-y" 'org-yank)
20542 (defun org-truely-invisible-p ()
20543 "Check if point is at a character currently not visible.
20544 This version does not only check the character property, but also
20545 `visible-mode'."
20546 ;; Early versions of noutline don't have `outline-invisible-p'.
20547 (if (org-bound-and-true-p visible-mode)
20549 (outline-invisible-p)))
20551 (defun org-invisible-p2 ()
20552 "Check if point is at a character currently not visible."
20553 (save-excursion
20554 (if (and (eolp) (not (bobp))) (backward-char 1))
20555 ;; Early versions of noutline don't have `outline-invisible-p'.
20556 (outline-invisible-p)))
20558 (defun org-back-to-heading (&optional invisible-ok)
20559 "Call `outline-back-to-heading', but provide a better error message."
20560 (condition-case nil
20561 (outline-back-to-heading invisible-ok)
20562 (error (error "Before first headline at position %d in buffer %s"
20563 (point) (current-buffer)))))
20565 (defun org-beginning-of-defun ()
20566 "Go to the beginning of the subtree, i.e. back to the heading."
20567 (org-back-to-heading))
20568 (defun org-end-of-defun ()
20569 "Go to the end of the subtree."
20570 (org-end-of-subtree nil t))
20572 (defun org-before-first-heading-p ()
20573 "Before first heading?"
20574 (save-excursion
20575 (end-of-line)
20576 (null (re-search-backward org-outline-regexp-bol nil t))))
20578 (defun org-on-heading-p (&optional ignored)
20579 (outline-on-heading-p t))
20580 (defun org-at-heading-p (&optional ignored)
20581 (outline-on-heading-p t))
20583 (defun org-point-at-end-of-empty-headline ()
20584 "If point is at the end of an empty headline, return t, else nil.
20585 If the heading only contains a TODO keyword, it is still still considered
20586 empty."
20587 (and (looking-at "[ \t]*$")
20588 (save-excursion
20589 (beginning-of-line 1)
20590 (let ((case-fold-search nil))
20591 (looking-at org-todo-line-regexp)))
20592 (string= (match-string 3) "")))
20594 (defun org-at-heading-or-item-p ()
20595 (or (org-on-heading-p) (org-at-item-p)))
20597 (defun org-on-target-p ()
20598 (or (org-in-regexp org-radio-target-regexp)
20599 (org-in-regexp org-target-regexp)))
20601 (defun org-up-heading-all (arg)
20602 "Move to the heading line of which the present line is a subheading.
20603 This function considers both visible and invisible heading lines.
20604 With argument, move up ARG levels."
20605 (if (fboundp 'outline-up-heading-all)
20606 (outline-up-heading-all arg) ; emacs 21 version of outline.el
20607 (outline-up-heading arg t))) ; emacs 22 version of outline.el
20609 (defun org-up-heading-safe ()
20610 "Move to the heading line of which the present line is a subheading.
20611 This version will not throw an error. It will return the level of the
20612 headline found, or nil if no higher level is found.
20614 Also, this function will be a lot faster than `outline-up-heading',
20615 because it relies on stars being the outline starters. This can really
20616 make a significant difference in outlines with very many siblings."
20617 (let (start-level re)
20618 (org-back-to-heading t)
20619 (setq start-level (funcall outline-level))
20620 (if (equal start-level 1)
20622 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
20623 (if (re-search-backward re nil t)
20624 (funcall outline-level)))))
20626 (defun org-first-sibling-p ()
20627 "Is this heading the first child of its parents?"
20628 (interactive)
20629 (let ((re org-outline-regexp-bol)
20630 level l)
20631 (unless (org-at-heading-p t)
20632 (error "Not at a heading"))
20633 (setq level (funcall outline-level))
20634 (save-excursion
20635 (if (not (re-search-backward re nil t))
20637 (setq l (funcall outline-level))
20638 (< l level)))))
20640 (defun org-goto-sibling (&optional previous)
20641 "Goto the next sibling, even if it is invisible.
20642 When PREVIOUS is set, go to the previous sibling instead. Returns t
20643 when a sibling was found. When none is found, return nil and don't
20644 move point."
20645 (let ((fun (if previous 're-search-backward 're-search-forward))
20646 (pos (point))
20647 (re org-outline-regexp-bol)
20648 level l)
20649 (when (condition-case nil (org-back-to-heading t) (error nil))
20650 (setq level (funcall outline-level))
20651 (catch 'exit
20652 (or previous (forward-char 1))
20653 (while (funcall fun re nil t)
20654 (setq l (funcall outline-level))
20655 (when (< l level) (goto-char pos) (throw 'exit nil))
20656 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
20657 (goto-char pos)
20658 nil))))
20660 (defun org-show-siblings ()
20661 "Show all siblings of the current headline."
20662 (save-excursion
20663 (while (org-goto-sibling) (org-flag-heading nil)))
20664 (save-excursion
20665 (while (org-goto-sibling 'previous)
20666 (org-flag-heading nil))))
20668 (defun org-goto-first-child ()
20669 "Goto the first child, even if it is invisible.
20670 Return t when a child was found. Otherwise don't move point and
20671 return nil."
20672 (let (level (pos (point)) (re org-outline-regexp-bol))
20673 (when (condition-case nil (org-back-to-heading t) (error nil))
20674 (setq level (outline-level))
20675 (forward-char 1)
20676 (if (and (re-search-forward re nil t) (> (outline-level) level))
20677 (progn (goto-char (match-beginning 0)) t)
20678 (goto-char pos) nil))))
20680 (defun org-show-hidden-entry ()
20681 "Show an entry where even the heading is hidden."
20682 (save-excursion
20683 (org-show-entry)))
20685 (defun org-flag-heading (flag &optional entry)
20686 "Flag the current heading. FLAG non-nil means make invisible.
20687 When ENTRY is non-nil, show the entire entry."
20688 (save-excursion
20689 (org-back-to-heading t)
20690 ;; Check if we should show the entire entry
20691 (if entry
20692 (progn
20693 (org-show-entry)
20694 (save-excursion
20695 (and (outline-next-heading)
20696 (org-flag-heading nil))))
20697 (outline-flag-region (max (point-min) (1- (point)))
20698 (save-excursion (outline-end-of-heading) (point))
20699 flag))))
20701 (defun org-get-next-sibling ()
20702 "Move to next heading of the same level, and return point.
20703 If there is no such heading, return nil.
20704 This is like outline-next-sibling, but invisible headings are ok."
20705 (let ((level (funcall outline-level)))
20706 (outline-next-heading)
20707 (while (and (not (eobp)) (> (funcall outline-level) level))
20708 (outline-next-heading))
20709 (if (or (eobp) (< (funcall outline-level) level))
20711 (point))))
20713 (defun org-get-last-sibling ()
20714 "Move to previous heading of the same level, and return point.
20715 If there is no such heading, return nil."
20716 (let ((opoint (point))
20717 (level (funcall outline-level)))
20718 (outline-previous-heading)
20719 (when (and (/= (point) opoint) (outline-on-heading-p t))
20720 (while (and (> (funcall outline-level) level)
20721 (not (bobp)))
20722 (outline-previous-heading))
20723 (if (< (funcall outline-level) level)
20725 (point)))))
20727 (defun org-end-of-subtree (&optional invisible-OK to-heading)
20728 ;; This contains an exact copy of the original function, but it uses
20729 ;; `org-back-to-heading', to make it work also in invisible
20730 ;; trees. And is uses an invisible-OK argument.
20731 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
20732 ;; Furthermore, when used inside Org, finding the end of a large subtree
20733 ;; with many children and grandchildren etc, this can be much faster
20734 ;; than the outline version.
20735 (org-back-to-heading invisible-OK)
20736 (let ((first t)
20737 (level (funcall outline-level)))
20738 (if (and (eq major-mode 'org-mode) (< level 1000))
20739 ;; A true heading (not a plain list item), in Org-mode
20740 ;; This means we can easily find the end by looking
20741 ;; only for the right number of stars. Using a regexp to do
20742 ;; this is so much faster than using a Lisp loop.
20743 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
20744 (forward-char 1)
20745 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
20746 ;; something else, do it the slow way
20747 (while (and (not (eobp))
20748 (or first (> (funcall outline-level) level)))
20749 (setq first nil)
20750 (outline-next-heading)))
20751 (unless to-heading
20752 (if (memq (preceding-char) '(?\n ?\^M))
20753 (progn
20754 ;; Go to end of line before heading
20755 (forward-char -1)
20756 (if (memq (preceding-char) '(?\n ?\^M))
20757 ;; leave blank line before heading
20758 (forward-char -1))))))
20759 (point))
20761 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
20762 "Use Org version in org-mode, for dramatic speed-up."
20763 (if (eq major-mode 'org-mode)
20764 (progn
20765 (org-end-of-subtree nil t)
20766 (unless (eobp) (backward-char 1)))
20767 ad-do-it))
20769 (defun org-end-of-meta-data-and-drawers ()
20770 "Jump to the first text after meta data and drawers in the current entry.
20771 This will move over empty lines, lines with planning time stamps,
20772 clocking lines, and drawers."
20773 (org-back-to-heading t)
20774 (let ((end (save-excursion (outline-next-heading) (point)))
20775 (re (concat "\\(" org-drawer-regexp "\\)"
20776 "\\|" "[ \t]*" org-keyword-time-regexp)))
20777 (forward-line 1)
20778 (while (re-search-forward re end t)
20779 (if (not (match-end 1))
20780 ;; empty or planning line
20781 (forward-line 1)
20782 ;; a drawer, find the end
20783 (re-search-forward "^[ \t]*:END:" end 'move)
20784 (forward-line 1)))
20785 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
20786 (point)))
20788 (defun org-forward-same-level (arg &optional invisible-ok)
20789 "Move forward to the arg'th subheading at same level as this one.
20790 Stop at the first and last subheadings of a superior heading.
20791 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
20792 it wil also look at invisible ones."
20793 (interactive "p")
20794 (org-back-to-heading invisible-ok)
20795 (org-on-heading-p)
20796 (let* ((level (- (match-end 0) (match-beginning 0) 1))
20797 (re (format "^\\*\\{1,%d\\} " level))
20799 (forward-char 1)
20800 (while (> arg 0)
20801 (while (and (re-search-forward re nil 'move)
20802 (setq l (- (match-end 0) (match-beginning 0) 1))
20803 (= l level)
20804 (not invisible-ok)
20805 (progn (backward-char 1) (outline-invisible-p)))
20806 (if (< l level) (setq arg 1)))
20807 (setq arg (1- arg)))
20808 (beginning-of-line 1)))
20810 (defun org-backward-same-level (arg &optional invisible-ok)
20811 "Move backward to the arg'th subheading at same level as this one.
20812 Stop at the first and last subheadings of a superior heading."
20813 (interactive "p")
20814 (org-back-to-heading)
20815 (org-on-heading-p)
20816 (let* ((level (- (match-end 0) (match-beginning 0) 1))
20817 (re (format "^\\*\\{1,%d\\} " level))
20819 (while (> arg 0)
20820 (while (and (re-search-backward re nil 'move)
20821 (setq l (- (match-end 0) (match-beginning 0) 1))
20822 (= l level)
20823 (not invisible-ok)
20824 (outline-invisible-p))
20825 (if (< l level) (setq arg 1)))
20826 (setq arg (1- arg)))))
20828 (defun org-show-subtree ()
20829 "Show everything after this heading at deeper levels."
20830 (outline-flag-region
20831 (point)
20832 (save-excursion
20833 (org-end-of-subtree t t))
20834 nil))
20836 (defun org-show-entry ()
20837 "Show the body directly following this heading.
20838 Show the heading too, if it is currently invisible."
20839 (interactive)
20840 (save-excursion
20841 (condition-case nil
20842 (progn
20843 (org-back-to-heading t)
20844 (outline-flag-region
20845 (max (point-min) (1- (point)))
20846 (save-excursion
20847 (if (re-search-forward
20848 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
20849 (match-beginning 1)
20850 (point-max)))
20851 nil)
20852 (org-cycle-hide-drawers 'children))
20853 (error nil))))
20855 (defun org-make-options-regexp (kwds &optional extra)
20856 "Make a regular expression for keyword lines."
20857 (concat
20859 "#?[ \t]*\\+\\("
20860 (mapconcat 'regexp-quote kwds "\\|")
20861 (if extra (concat "\\|" extra))
20862 "\\):[ \t]*"
20863 "\\(.*\\)"))
20865 ;; Make isearch reveal the necessary context
20866 (defun org-isearch-end ()
20867 "Reveal context after isearch exits."
20868 (when isearch-success ; only if search was successful
20869 (if (featurep 'xemacs)
20870 ;; Under XEmacs, the hook is run in the correct place,
20871 ;; we directly show the context.
20872 (org-show-context 'isearch)
20873 ;; In Emacs the hook runs *before* restoring the overlays.
20874 ;; So we have to use a one-time post-command-hook to do this.
20875 ;; (Emacs 22 has a special variable, see function `org-mode')
20876 (unless (and (boundp 'isearch-mode-end-hook-quit)
20877 isearch-mode-end-hook-quit)
20878 ;; Only when the isearch was not quitted.
20879 (org-add-hook 'post-command-hook 'org-isearch-post-command
20880 'append 'local)))))
20882 (defun org-isearch-post-command ()
20883 "Remove self from hook, and show context."
20884 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
20885 (org-show-context 'isearch))
20888 ;;;; Integration with and fixes for other packages
20890 ;;; Imenu support
20892 (defvar org-imenu-markers nil
20893 "All markers currently used by Imenu.")
20894 (make-variable-buffer-local 'org-imenu-markers)
20896 (defun org-imenu-new-marker (&optional pos)
20897 "Return a new marker for use by Imenu, and remember the marker."
20898 (let ((m (make-marker)))
20899 (move-marker m (or pos (point)))
20900 (push m org-imenu-markers)
20903 (defun org-imenu-get-tree ()
20904 "Produce the index for Imenu."
20905 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
20906 (setq org-imenu-markers nil)
20907 (let* ((n org-imenu-depth)
20908 (re (concat "^" (org-get-limited-outline-regexp)))
20909 (subs (make-vector (1+ n) nil))
20910 (last-level 0)
20911 m level head)
20912 (save-excursion
20913 (save-restriction
20914 (widen)
20915 (goto-char (point-max))
20916 (while (re-search-backward re nil t)
20917 (setq level (org-reduced-level (funcall outline-level)))
20918 (when (<= level n)
20919 (looking-at org-complex-heading-regexp)
20920 (setq head (org-link-display-format
20921 (org-match-string-no-properties 4))
20922 m (org-imenu-new-marker))
20923 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
20924 (if (>= level last-level)
20925 (push (cons head m) (aref subs level))
20926 (push (cons head (aref subs (1+ level))) (aref subs level))
20927 (loop for i from (1+ level) to n do (aset subs i nil)))
20928 (setq last-level level)))))
20929 (aref subs 1)))
20931 (eval-after-load "imenu"
20932 '(progn
20933 (add-hook 'imenu-after-jump-hook
20934 (lambda ()
20935 (if (eq major-mode 'org-mode)
20936 (org-show-context 'org-goto))))))
20938 (defun org-link-display-format (link)
20939 "Replace a link with either the description, or the link target
20940 if no description is present"
20941 (save-match-data
20942 (if (string-match org-bracket-link-analytic-regexp link)
20943 (replace-match (if (match-end 5)
20944 (match-string 5 link)
20945 (concat (match-string 1 link)
20946 (match-string 3 link)))
20947 nil t link)
20948 link)))
20950 (defun org-toggle-link-display ()
20951 "Toggle the literal or descriptive display of links."
20952 (interactive)
20953 (if org-descriptive-links
20954 (progn (org-remove-from-invisibility-spec '(org-link))
20955 (org-restart-font-lock)
20956 (setq org-descriptive-links nil))
20957 (progn (add-to-invisibility-spec '(org-link))
20958 (org-restart-font-lock)
20959 (setq org-descriptive-links t))))
20961 ;; Speedbar support
20963 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
20964 "Overlay marking the agenda restriction line in speedbar.")
20965 (overlay-put org-speedbar-restriction-lock-overlay
20966 'face 'org-agenda-restriction-lock)
20967 (overlay-put org-speedbar-restriction-lock-overlay
20968 'help-echo "Agendas are currently limited to this item.")
20969 (org-detach-overlay org-speedbar-restriction-lock-overlay)
20971 (defun org-speedbar-set-agenda-restriction ()
20972 "Restrict future agenda commands to the location at point in speedbar.
20973 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
20974 (interactive)
20975 (require 'org-agenda)
20976 (let (p m tp np dir txt)
20977 (cond
20978 ((setq p (text-property-any (point-at-bol) (point-at-eol)
20979 'org-imenu t))
20980 (setq m (get-text-property p 'org-imenu-marker))
20981 (with-current-buffer (marker-buffer m)
20982 (goto-char m)
20983 (org-agenda-set-restriction-lock 'subtree)))
20984 ((setq p (text-property-any (point-at-bol) (point-at-eol)
20985 'speedbar-function 'speedbar-find-file))
20986 (setq tp (previous-single-property-change
20987 (1+ p) 'speedbar-function)
20988 np (next-single-property-change
20989 tp 'speedbar-function)
20990 dir (speedbar-line-directory)
20991 txt (buffer-substring-no-properties (or tp (point-min))
20992 (or np (point-max))))
20993 (with-current-buffer (find-file-noselect
20994 (let ((default-directory dir))
20995 (expand-file-name txt)))
20996 (unless (eq major-mode 'org-mode)
20997 (error "Cannot restrict to non-Org-mode file"))
20998 (org-agenda-set-restriction-lock 'file)))
20999 (t (error "Don't know how to restrict Org-mode's agenda")))
21000 (move-overlay org-speedbar-restriction-lock-overlay
21001 (point-at-bol) (point-at-eol))
21002 (setq current-prefix-arg nil)
21003 (org-agenda-maybe-redo)))
21005 (eval-after-load "speedbar"
21006 '(progn
21007 (speedbar-add-supported-extension ".org")
21008 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
21009 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
21010 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
21011 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
21012 (add-hook 'speedbar-visiting-tag-hook
21013 (lambda () (and (eq major-mode 'org-mode) (org-show-context 'org-goto))))))
21015 ;;; Fixes and Hacks for problems with other packages
21017 ;; Make flyspell not check words in links, to not mess up our keymap
21018 (defun org-mode-flyspell-verify ()
21019 "Don't let flyspell put overlays at active buttons, or on
21020 {todo,all-time,additional-option-like}-keywords."
21021 (let ((pos (max (1- (point)) (point-min)))
21022 (word (thing-at-point 'word)))
21023 (and (not (get-text-property pos 'keymap))
21024 (not (get-text-property pos 'org-no-flyspell))
21025 (not (member word org-todo-keywords-1))
21026 (not (member word org-all-time-keywords))
21027 (not (member word org-additional-option-like-keywords)))))
21029 (defun org-remove-flyspell-overlays-in (beg end)
21030 "Remove flyspell overlays in region."
21031 (and (org-bound-and-true-p flyspell-mode)
21032 (fboundp 'flyspell-delete-region-overlays)
21033 (flyspell-delete-region-overlays beg end))
21034 (add-text-properties beg end '(org-no-flyspell t)))
21036 ;; Make `bookmark-jump' shows the jump location if it was hidden.
21037 (eval-after-load "bookmark"
21038 '(if (boundp 'bookmark-after-jump-hook)
21039 ;; We can use the hook
21040 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
21041 ;; Hook not available, use advice
21042 (defadvice bookmark-jump (after org-make-visible activate)
21043 "Make the position visible."
21044 (org-bookmark-jump-unhide))))
21046 ;; Make sure saveplace shows the location if it was hidden
21047 (eval-after-load "saveplace"
21048 '(defadvice save-place-find-file-hook (after org-make-visible activate)
21049 "Make the position visible."
21050 (org-bookmark-jump-unhide)))
21052 ;; Make sure ecb shows the location if it was hidden
21053 (eval-after-load "ecb"
21054 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
21055 "Make hierarchy visible when jumping into location from ECB tree buffer."
21056 (if (eq major-mode 'org-mode)
21057 (org-show-context))))
21059 (defun org-bookmark-jump-unhide ()
21060 "Unhide the current position, to show the bookmark location."
21061 (and (eq major-mode 'org-mode)
21062 (or (outline-invisible-p)
21063 (save-excursion (goto-char (max (point-min) (1- (point))))
21064 (outline-invisible-p)))
21065 (org-show-context 'bookmark-jump)))
21067 ;; Make session.el ignore our circular variable
21068 (eval-after-load "session"
21069 '(add-to-list 'session-globals-exclude 'org-mark-ring))
21071 ;;;; Experimental code
21073 (defun org-closed-in-range ()
21074 "Sparse tree of items closed in a certain time range.
21075 Still experimental, may disappear in the future."
21076 (interactive)
21077 ;; Get the time interval from the user.
21078 (let* ((time1 (org-float-time
21079 (org-read-date nil 'to-time nil "Starting date: ")))
21080 (time2 (org-float-time
21081 (org-read-date nil 'to-time nil "End date:")))
21082 ;; callback function
21083 (callback (lambda ()
21084 (let ((time
21085 (org-float-time
21086 (apply 'encode-time
21087 (org-parse-time-string
21088 (match-string 1))))))
21089 ;; check if time in interval
21090 (and (>= time time1) (<= time time2))))))
21091 ;; make tree, check each match with the callback
21092 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
21094 ;;;; Finish up
21096 (provide 'org)
21098 (run-hooks 'org-load-hook)
21100 ;;; org.el ends here