org.el (org-show-context): Complete docstring.
[org-mode.git] / lisp / org.el
blob2528fa82f35503dffae49d0057303cd4e74bf421
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 (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11195 (let (org-loop-over-headlines-in-active-region)
11196 (org-map-entries
11197 `(org-todo ,arg)
11198 org-loop-over-headlines-in-active-region
11199 'region
11200 (if (outline-invisible-p) (org-end-of-subtree nil t))))
11201 (if (equal arg '(16)) (setq arg 'nextset))
11202 (let ((org-blocker-hook org-blocker-hook)
11203 (case-fold-search nil))
11204 (when (equal arg '(64))
11205 (setq arg nil org-blocker-hook nil))
11206 (when (and org-blocker-hook
11207 (or org-inhibit-blocking
11208 (org-entry-get nil "NOBLOCKING")))
11209 (setq org-blocker-hook nil))
11210 (save-excursion
11211 (catch 'exit
11212 (org-back-to-heading t)
11213 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11214 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11215 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11216 (let* ((match-data (match-data))
11217 (startpos (point-at-bol))
11218 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11219 (org-log-done org-log-done)
11220 (org-log-repeat org-log-repeat)
11221 (org-todo-log-states org-todo-log-states)
11222 (org-inhibit-logging
11223 (if (equal arg 0)
11224 (progn (setq arg nil) 'note) org-inhibit-logging))
11225 (this (match-string 1))
11226 (hl-pos (match-beginning 0))
11227 (head (org-get-todo-sequence-head this))
11228 (ass (assoc head org-todo-kwd-alist))
11229 (interpret (nth 1 ass))
11230 (done-word (nth 3 ass))
11231 (final-done-word (nth 4 ass))
11232 (last-state (or this ""))
11233 (completion-ignore-case t)
11234 (member (member this org-todo-keywords-1))
11235 (tail (cdr member))
11236 (state (cond
11237 ((and org-todo-key-trigger
11238 (or (and (equal arg '(4))
11239 (eq org-use-fast-todo-selection 'prefix))
11240 (and (not arg) org-use-fast-todo-selection
11241 (not (eq org-use-fast-todo-selection
11242 'prefix)))))
11243 ;; Use fast selection
11244 (org-fast-todo-selection))
11245 ((and (equal arg '(4))
11246 (or (not org-use-fast-todo-selection)
11247 (not org-todo-key-trigger)))
11248 ;; Read a state with completion
11249 (org-icompleting-read
11250 "State: " (mapcar (lambda(x) (list x))
11251 org-todo-keywords-1)
11252 nil t))
11253 ((eq arg 'right)
11254 (if this
11255 (if tail (car tail) nil)
11256 (car org-todo-keywords-1)))
11257 ((eq arg 'left)
11258 (if (equal member org-todo-keywords-1)
11260 (if this
11261 (nth (- (length org-todo-keywords-1)
11262 (length tail) 2)
11263 org-todo-keywords-1)
11264 (org-last org-todo-keywords-1))))
11265 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11266 (setq arg nil))) ; hack to fall back to cycling
11267 (arg
11268 ;; user or caller requests a specific state
11269 (cond
11270 ((equal arg "") nil)
11271 ((eq arg 'none) nil)
11272 ((eq arg 'done) (or done-word (car org-done-keywords)))
11273 ((eq arg 'nextset)
11274 (or (car (cdr (member head org-todo-heads)))
11275 (car org-todo-heads)))
11276 ((eq arg 'previousset)
11277 (let ((org-todo-heads (reverse org-todo-heads)))
11278 (or (car (cdr (member head org-todo-heads)))
11279 (car org-todo-heads))))
11280 ((car (member arg org-todo-keywords-1)))
11281 ((stringp arg)
11282 (error "State `%s' not valid in this file" arg))
11283 ((nth (1- (prefix-numeric-value arg))
11284 org-todo-keywords-1))))
11285 ((null member) (or head (car org-todo-keywords-1)))
11286 ((equal this final-done-word) nil) ;; -> make empty
11287 ((null tail) nil) ;; -> first entry
11288 ((memq interpret '(type priority))
11289 (if (eq this-command last-command)
11290 (car tail)
11291 (if (> (length tail) 0)
11292 (or done-word (car org-done-keywords))
11293 nil)))
11295 (car tail))))
11296 (state (or
11297 (run-hook-with-args-until-success
11298 'org-todo-get-default-hook state last-state)
11299 state))
11300 (next (if state (concat " " state " ") " "))
11301 (change-plist (list :type 'todo-state-change :from this :to state
11302 :position startpos))
11303 dolog now-done-p)
11304 (when org-blocker-hook
11305 (setq org-last-todo-state-is-todo
11306 (not (member this org-done-keywords)))
11307 (unless (save-excursion
11308 (save-match-data
11309 (org-with-wide-buffer
11310 (run-hook-with-args-until-failure
11311 'org-blocker-hook change-plist))))
11312 (if (org-called-interactively-p 'interactive)
11313 (error "TODO state change from %s to %s blocked" this state)
11314 ;; fail silently
11315 (message "TODO state change from %s to %s blocked" this state)
11316 (throw 'exit nil))))
11317 (store-match-data match-data)
11318 (replace-match next t t)
11319 (unless (pos-visible-in-window-p hl-pos)
11320 (message "TODO state changed to %s" (org-trim next)))
11321 (unless head
11322 (setq head (org-get-todo-sequence-head state)
11323 ass (assoc head org-todo-kwd-alist)
11324 interpret (nth 1 ass)
11325 done-word (nth 3 ass)
11326 final-done-word (nth 4 ass)))
11327 (when (memq arg '(nextset previousset))
11328 (message "Keyword-Set %d/%d: %s"
11329 (- (length org-todo-sets) -1
11330 (length (memq (assoc state org-todo-sets) org-todo-sets)))
11331 (length org-todo-sets)
11332 (mapconcat 'identity (assoc state org-todo-sets) " ")))
11333 (setq org-last-todo-state-is-todo
11334 (not (member state org-done-keywords)))
11335 (setq now-done-p (and (member state org-done-keywords)
11336 (not (member this org-done-keywords))))
11337 (and logging (org-local-logging logging))
11338 (when (and (or org-todo-log-states org-log-done)
11339 (not (eq org-inhibit-logging t))
11340 (not (memq arg '(nextset previousset))))
11341 ;; we need to look at recording a time and note
11342 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
11343 (nth 2 (assoc this org-todo-log-states))))
11344 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11345 (setq dolog 'time))
11346 (when (and state
11347 (member state org-not-done-keywords)
11348 (not (member this org-not-done-keywords)))
11349 ;; This is now a todo state and was not one before
11350 ;; If there was a CLOSED time stamp, get rid of it.
11351 (org-add-planning-info nil nil 'closed))
11352 (when (and now-done-p org-log-done)
11353 ;; It is now done, and it was not done before
11354 (org-add-planning-info 'closed (org-current-effective-time))
11355 (if (and (not dolog) (eq 'note org-log-done))
11356 (org-add-log-setup 'done state this 'findpos 'note)))
11357 (when (and state dolog)
11358 ;; This is a non-nil state, and we need to log it
11359 (org-add-log-setup 'state state this 'findpos dolog)))
11360 ;; Fixup tag positioning
11361 (org-todo-trigger-tag-changes state)
11362 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11363 (when org-provide-todo-statistics
11364 (org-update-parent-todo-statistics))
11365 (run-hooks 'org-after-todo-state-change-hook)
11366 (if (and arg (not (member state org-done-keywords)))
11367 (setq head (org-get-todo-sequence-head state)))
11368 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11369 ;; Do we need to trigger a repeat?
11370 (when now-done-p
11371 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11372 ;; This is for the agenda, take a snapshot of the headline.
11373 (save-match-data
11374 (setq org-agenda-headline-snapshot-before-repeat
11375 (org-get-heading))))
11376 (org-auto-repeat-maybe state))
11377 ;; Fixup cursor location if close to the keyword
11378 (if (and (outline-on-heading-p)
11379 (not (bolp))
11380 (save-excursion (beginning-of-line 1)
11381 (looking-at org-todo-line-regexp))
11382 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11383 (progn
11384 (goto-char (or (match-end 2) (match-end 1)))
11385 (and (looking-at " ") (just-one-space))))
11386 (when org-trigger-hook
11387 (save-excursion
11388 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11390 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11391 "Block turning an entry into a TODO, using the hierarchy.
11392 This checks whether the current task should be blocked from state
11393 changes. Such blocking occurs when:
11395 1. The task has children which are not all in a completed state.
11397 2. A task has a parent with the property :ORDERED:, and there
11398 are siblings prior to the current task with incomplete
11399 status.
11401 3. The parent of the task is blocked because it has siblings that should
11402 be done first, or is child of a block grandparent TODO entry."
11404 (if (not org-enforce-todo-dependencies)
11405 t ; if locally turned off don't block
11406 (catch 'dont-block
11407 ;; If this is not a todo state change, or if this entry is already DONE,
11408 ;; do not block
11409 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11410 (member (plist-get change-plist :from)
11411 (cons 'done org-done-keywords))
11412 (member (plist-get change-plist :to)
11413 (cons 'todo org-not-done-keywords))
11414 (not (plist-get change-plist :to)))
11415 (throw 'dont-block t))
11416 ;; If this task has children, and any are undone, it's blocked
11417 (save-excursion
11418 (org-back-to-heading t)
11419 (let ((this-level (funcall outline-level)))
11420 (outline-next-heading)
11421 (let ((child-level (funcall outline-level)))
11422 (while (and (not (eobp))
11423 (> child-level this-level))
11424 ;; this todo has children, check whether they are all
11425 ;; completed
11426 (if (and (not (org-entry-is-done-p))
11427 (org-entry-is-todo-p))
11428 (throw 'dont-block nil))
11429 (outline-next-heading)
11430 (setq child-level (funcall outline-level))))))
11431 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11432 ;; any previous siblings are undone, it's blocked
11433 (save-excursion
11434 (org-back-to-heading t)
11435 (let* ((pos (point))
11436 (parent-pos (and (org-up-heading-safe) (point))))
11437 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11438 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11439 (forward-line 1)
11440 (re-search-forward org-not-done-heading-regexp pos t))
11441 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11442 ;; Search further up the hierarchy, to see if an anchestor is blocked
11443 (while t
11444 (goto-char parent-pos)
11445 (if (not (looking-at org-not-done-heading-regexp))
11446 (throw 'dont-block t)) ; do not block, parent is not a TODO
11447 (setq pos (point))
11448 (setq parent-pos (and (org-up-heading-safe) (point)))
11449 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11450 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11451 (forward-line 1)
11452 (re-search-forward org-not-done-heading-regexp pos t))
11453 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11455 (defcustom org-track-ordered-property-with-tag nil
11456 "Should the ORDERED property also be shown as a tag?
11457 The ORDERED property decides if an entry should require subtasks to be
11458 completed in sequence. Since a property is not very visible, setting
11459 this option means that toggling the ORDERED property with the command
11460 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11461 not relevant for the behavior, but it makes things more visible.
11463 Note that toggling the tag with tags commands will not change the property
11464 and therefore not influence behavior!
11466 This can be t, meaning the tag ORDERED should be used, It can also be a
11467 string to select a different tag for this task."
11468 :group 'org-todo
11469 :type '(choice
11470 (const :tag "No tracking" nil)
11471 (const :tag "Track with ORDERED tag" t)
11472 (string :tag "Use other tag")))
11474 (defun org-toggle-ordered-property ()
11475 "Toggle the ORDERED property of the current entry.
11476 For better visibility, you can track the value of this property with a tag.
11477 See variable `org-track-ordered-property-with-tag'."
11478 (interactive)
11479 (let* ((t1 org-track-ordered-property-with-tag)
11480 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11481 (save-excursion
11482 (org-back-to-heading)
11483 (if (org-entry-get nil "ORDERED")
11484 (progn
11485 (org-delete-property "ORDERED")
11486 (and tag (org-toggle-tag tag 'off))
11487 (message "Subtasks can be completed in arbitrary order"))
11488 (org-entry-put nil "ORDERED" "t")
11489 (and tag (org-toggle-tag tag 'on))
11490 (message "Subtasks must be completed in sequence")))))
11492 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11493 (defun org-block-todo-from-checkboxes (change-plist)
11494 "Block turning an entry into a TODO, using checkboxes.
11495 This checks whether the current task should be blocked from state
11496 changes because there are unchecked boxes in this entry."
11497 (if (not org-enforce-todo-checkbox-dependencies)
11498 t ; if locally turned off don't block
11499 (catch 'dont-block
11500 ;; If this is not a todo state change, or if this entry is already DONE,
11501 ;; do not block
11502 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11503 (member (plist-get change-plist :from)
11504 (cons 'done org-done-keywords))
11505 (member (plist-get change-plist :to)
11506 (cons 'todo org-not-done-keywords))
11507 (not (plist-get change-plist :to)))
11508 (throw 'dont-block t))
11509 ;; If this task has checkboxes that are not checked, it's blocked
11510 (save-excursion
11511 (org-back-to-heading t)
11512 (let ((beg (point)) end)
11513 (outline-next-heading)
11514 (setq end (point))
11515 (goto-char beg)
11516 (if (org-list-search-forward
11517 (concat (org-item-beginning-re)
11518 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11519 "\\[[- ]\\]")
11520 end t)
11521 (progn
11522 (if (boundp 'org-blocked-by-checkboxes)
11523 (setq org-blocked-by-checkboxes t))
11524 (throw 'dont-block nil)))))
11525 t))) ; do not block
11527 (defun org-entry-blocked-p ()
11528 "Is the current entry blocked?"
11529 (if (org-entry-get nil "NOBLOCKING")
11530 nil ;; Never block this entry
11531 (not
11532 (run-hook-with-args-until-failure
11533 'org-blocker-hook
11534 (list :type 'todo-state-change
11535 :position (point)
11536 :from 'todo
11537 :to 'done)))))
11539 (defun org-update-statistics-cookies (all)
11540 "Update the statistics cookie, either from TODO or from checkboxes.
11541 This should be called with the cursor in a line with a statistics cookie."
11542 (interactive "P")
11543 (if all
11544 (progn
11545 (org-update-checkbox-count 'all)
11546 (org-map-entries 'org-update-parent-todo-statistics))
11547 (if (not (org-on-heading-p))
11548 (org-update-checkbox-count)
11549 (let ((pos (move-marker (make-marker) (point)))
11550 end l1 l2)
11551 (ignore-errors (org-back-to-heading t))
11552 (if (not (org-on-heading-p))
11553 (org-update-checkbox-count)
11554 (setq l1 (org-outline-level))
11555 (setq end (save-excursion
11556 (outline-next-heading)
11557 (if (org-on-heading-p) (setq l2 (org-outline-level)))
11558 (point)))
11559 (if (and (save-excursion
11560 (re-search-forward
11561 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11562 (not (save-excursion (re-search-forward
11563 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11564 (org-update-checkbox-count)
11565 (if (and l2 (> l2 l1))
11566 (progn
11567 (goto-char end)
11568 (org-update-parent-todo-statistics))
11569 (goto-char pos)
11570 (beginning-of-line 1)
11571 (while (re-search-forward
11572 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11573 (point-at-eol) t)
11574 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11575 (goto-char pos)
11576 (move-marker pos nil)))))
11578 (defvar org-entry-property-inherited-from) ;; defined below
11579 (defun org-update-parent-todo-statistics ()
11580 "Update any statistics cookie in the parent of the current headline.
11581 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11582 the entire subtree and this will travel up the hierarchy and update
11583 statistics everywhere."
11584 (let* ((prop (save-excursion (org-up-heading-safe)
11585 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11586 (recursive (or (not org-hierarchical-todo-statistics)
11587 (and prop (string-match "\\<recursive\\>" prop))))
11588 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11590 (first t)
11591 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11592 level ltoggle l1 new ndel
11593 (cnt-all 0) (cnt-done 0) is-percent kwd
11594 checkbox-beg ov ovs ove cookie-present)
11595 (catch 'exit
11596 (save-excursion
11597 (beginning-of-line 1)
11598 (setq ltoggle (funcall outline-level))
11599 ;; Three situations are to consider:
11601 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11602 ;; to the top-level ancestor on the headline;
11604 ;; 2. If parent has "recursive" property, repeat up to the
11605 ;; headline setting that property, taking inheritance into
11606 ;; account;
11608 ;; 3. Else, move up to direct parent and proceed only once.
11609 (while (and (setq level (org-up-heading-safe))
11610 (or recursive first)
11611 (>= (point) lim))
11612 (setq first nil cookie-present nil)
11613 (unless (and level
11614 (not (string-match
11615 "\\<checkbox\\>"
11616 (downcase (or (org-entry-get nil "COOKIE_DATA")
11617 "")))))
11618 (throw 'exit nil))
11619 (while (re-search-forward box-re (point-at-eol) t)
11620 (setq cnt-all 0 cnt-done 0 cookie-present t)
11621 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11622 (save-match-data
11623 (unless (outline-next-heading) (throw 'exit nil))
11624 (while (and (looking-at org-complex-heading-regexp)
11625 (> (setq l1 (length (match-string 1))) level))
11626 (setq kwd (and (or recursive (= l1 ltoggle))
11627 (match-string 2)))
11628 (if (or (eq org-provide-todo-statistics 'all-headlines)
11629 (and (listp org-provide-todo-statistics)
11630 (or (member kwd org-provide-todo-statistics)
11631 (member kwd org-done-keywords))))
11632 (setq cnt-all (1+ cnt-all))
11633 (if (eq org-provide-todo-statistics t)
11634 (and kwd (setq cnt-all (1+ cnt-all)))))
11635 (and (member kwd org-done-keywords)
11636 (setq cnt-done (1+ cnt-done)))
11637 (outline-next-heading)))
11638 (setq new
11639 (if is-percent
11640 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11641 (format "[%d/%d]" cnt-done cnt-all))
11642 ndel (- (match-end 0) checkbox-beg))
11643 ;; handle overlays when updating cookie from column view
11644 (when (setq ov (car (overlays-at checkbox-beg)))
11645 (setq ovs (overlay-start ov) ove (overlay-end ov))
11646 (delete-overlay ov))
11647 (goto-char checkbox-beg)
11648 (insert new)
11649 (delete-region (point) (+ (point) ndel))
11650 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11651 (when ov (move-overlay ov ovs ove)))
11652 (when cookie-present
11653 (run-hook-with-args 'org-after-todo-statistics-hook
11654 cnt-done (- cnt-all cnt-done))))))
11655 (run-hooks 'org-todo-statistics-hook)))
11657 (defvar org-after-todo-statistics-hook nil
11658 "Hook that is called after a TODO statistics cookie has been updated.
11659 Each function is called with two arguments: the number of not-done entries
11660 and the number of done entries.
11662 For example, the following function, when added to this hook, will switch
11663 an entry to DONE when all children are done, and back to TODO when new
11664 entries are set to a TODO status. Note that this hook is only called
11665 when there is a statistics cookie in the headline!
11667 (defun org-summary-todo (n-done n-not-done)
11668 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11669 (let (org-log-done org-log-states) ; turn off logging
11670 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11673 (defvar org-todo-statistics-hook nil
11674 "Hook that is run whenever Org thinks TODO statistics should be updated.
11675 This hook runs even if there is no statistics cookie present, in which case
11676 `org-after-todo-statistics-hook' would not run.")
11678 (defun org-todo-trigger-tag-changes (state)
11679 "Apply the changes defined in `org-todo-state-tags-triggers'."
11680 (let ((l org-todo-state-tags-triggers)
11681 changes)
11682 (when (or (not state) (equal state ""))
11683 (setq changes (append changes (cdr (assoc "" l)))))
11684 (when (and (stringp state) (> (length state) 0))
11685 (setq changes (append changes (cdr (assoc state l)))))
11686 (when (member state org-not-done-keywords)
11687 (setq changes (append changes (cdr (assoc 'todo l)))))
11688 (when (member state org-done-keywords)
11689 (setq changes (append changes (cdr (assoc 'done l)))))
11690 (dolist (c changes)
11691 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11693 (defun org-local-logging (value)
11694 "Get logging settings from a property VALUE."
11695 (let* (words w a)
11696 ;; directly set the variables, they are already local.
11697 (setq org-log-done nil
11698 org-log-repeat nil
11699 org-todo-log-states nil)
11700 (setq words (org-split-string value))
11701 (while (setq w (pop words))
11702 (cond
11703 ((setq a (assoc w org-startup-options))
11704 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11705 (set (nth 1 a) (nth 2 a))))
11706 ((setq a (org-extract-log-state-settings w))
11707 (and (member (car a) org-todo-keywords-1)
11708 (push a org-todo-log-states)))))))
11710 (defun org-get-todo-sequence-head (kwd)
11711 "Return the head of the TODO sequence to which KWD belongs.
11712 If KWD is not set, check if there is a text property remembering the
11713 right sequence."
11714 (let (p)
11715 (cond
11716 ((not kwd)
11717 (or (get-text-property (point-at-bol) 'org-todo-head)
11718 (progn
11719 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11720 nil (point-at-eol)))
11721 (get-text-property p 'org-todo-head))))
11722 ((not (member kwd org-todo-keywords-1))
11723 (car org-todo-keywords-1))
11724 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11726 (defun org-fast-todo-selection ()
11727 "Fast TODO keyword selection with single keys.
11728 Returns the new TODO keyword, or nil if no state change should occur."
11729 (let* ((fulltable org-todo-key-alist)
11730 (done-keywords org-done-keywords) ;; needed for the faces.
11731 (maxlen (apply 'max (mapcar
11732 (lambda (x)
11733 (if (stringp (car x)) (string-width (car x)) 0))
11734 fulltable)))
11735 (expert nil)
11736 (fwidth (+ maxlen 3 1 3))
11737 (ncol (/ (- (window-width) 4) fwidth))
11738 tg cnt e c tbl
11739 groups ingroup)
11740 (save-excursion
11741 (save-window-excursion
11742 (if expert
11743 (set-buffer (get-buffer-create " *Org todo*"))
11744 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11745 (erase-buffer)
11746 (org-set-local 'org-done-keywords done-keywords)
11747 (setq tbl fulltable cnt 0)
11748 (while (setq e (pop tbl))
11749 (cond
11750 ((equal e '(:startgroup))
11751 (push '() groups) (setq ingroup t)
11752 (when (not (= cnt 0))
11753 (setq cnt 0)
11754 (insert "\n"))
11755 (insert "{ "))
11756 ((equal e '(:endgroup))
11757 (setq ingroup nil cnt 0)
11758 (insert "}\n"))
11759 ((equal e '(:newline))
11760 (when (not (= cnt 0))
11761 (setq cnt 0)
11762 (insert "\n")
11763 (setq e (car tbl))
11764 (while (equal (car tbl) '(:newline))
11765 (insert "\n")
11766 (setq tbl (cdr tbl)))))
11768 (setq tg (car e) c (cdr e))
11769 (if ingroup (push tg (car groups)))
11770 (setq tg (org-add-props tg nil 'face
11771 (org-get-todo-face tg)))
11772 (if (and (= cnt 0) (not ingroup)) (insert " "))
11773 (insert "[" c "] " tg (make-string
11774 (- fwidth 4 (length tg)) ?\ ))
11775 (when (= (setq cnt (1+ cnt)) ncol)
11776 (insert "\n")
11777 (if ingroup (insert " "))
11778 (setq cnt 0)))))
11779 (insert "\n")
11780 (goto-char (point-min))
11781 (if (not expert) (org-fit-window-to-buffer))
11782 (message "[a-z..]:Set [SPC]:clear")
11783 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11784 (cond
11785 ((or (= c ?\C-g)
11786 (and (= c ?q) (not (rassoc c fulltable))))
11787 (setq quit-flag t))
11788 ((= c ?\ ) nil)
11789 ((setq e (rassoc c fulltable) tg (car e))
11791 (t (setq quit-flag t)))))))
11793 (defun org-entry-is-todo-p ()
11794 (member (org-get-todo-state) org-not-done-keywords))
11796 (defun org-entry-is-done-p ()
11797 (member (org-get-todo-state) org-done-keywords))
11799 (defun org-get-todo-state ()
11800 (save-excursion
11801 (org-back-to-heading t)
11802 (and (looking-at org-todo-line-regexp)
11803 (match-end 2)
11804 (match-string 2))))
11806 (defun org-at-date-range-p (&optional inactive-ok)
11807 "Is the cursor inside a date range?"
11808 (interactive)
11809 (save-excursion
11810 (catch 'exit
11811 (let ((pos (point)))
11812 (skip-chars-backward "^[<\r\n")
11813 (skip-chars-backward "<[")
11814 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11815 (>= (match-end 0) pos)
11816 (throw 'exit t))
11817 (skip-chars-backward "^<[\r\n")
11818 (skip-chars-backward "<[")
11819 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11820 (>= (match-end 0) pos)
11821 (throw 'exit t)))
11822 nil)))
11824 (defun org-get-repeat (&optional tagline)
11825 "Check if there is a deadline/schedule with repeater in this entry."
11826 (save-match-data
11827 (save-excursion
11828 (org-back-to-heading t)
11829 (and (re-search-forward (if tagline
11830 (concat tagline "\\s-*" org-repeat-re)
11831 org-repeat-re)
11832 (org-entry-end-position) t)
11833 (match-string-no-properties 1)))))
11835 (defvar org-last-changed-timestamp)
11836 (defvar org-last-inserted-timestamp)
11837 (defvar org-log-post-message)
11838 (defvar org-log-note-purpose)
11839 (defvar org-log-note-how)
11840 (defvar org-log-note-extra)
11841 (defun org-auto-repeat-maybe (done-word)
11842 "Check if the current headline contains a repeated deadline/schedule.
11843 If yes, set TODO state back to what it was and change the base date
11844 of repeating deadline/scheduled time stamps to new date.
11845 This function is run automatically after each state change to a DONE state."
11846 ;; last-state is dynamically scoped into this function
11847 (let* ((repeat (org-get-repeat))
11848 (aa (assoc last-state org-todo-kwd-alist))
11849 (interpret (nth 1 aa))
11850 (head (nth 2 aa))
11851 (whata '(("d" . day) ("m" . month) ("y" . year)))
11852 (msg "Entry repeats: ")
11853 (org-log-done nil)
11854 (org-todo-log-states nil)
11855 re type n what ts time to-state)
11856 (when repeat
11857 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11858 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11859 org-todo-repeat-to-state))
11860 (unless (and to-state (member to-state org-todo-keywords-1))
11861 (setq to-state (if (eq interpret 'type) last-state head)))
11862 (org-todo to-state)
11863 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11864 (org-entry-put nil "LAST_REPEAT" (format-time-string
11865 (org-time-stamp-format t t))))
11866 (when org-log-repeat
11867 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11868 (memq 'org-add-log-note post-command-hook))
11869 ;; OK, we are already setup for some record
11870 (if (eq org-log-repeat 'note)
11871 ;; make sure we take a note, not only a time stamp
11872 (setq org-log-note-how 'note))
11873 ;; Set up for taking a record
11874 (org-add-log-setup 'state (or done-word (car org-done-keywords))
11875 last-state
11876 'findpos org-log-repeat)))
11877 (org-back-to-heading t)
11878 (org-add-planning-info nil nil 'closed)
11879 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11880 org-deadline-time-regexp "\\)\\|\\("
11881 org-ts-regexp "\\)"))
11882 (while (re-search-forward
11883 re (save-excursion (outline-next-heading) (point)) t)
11884 (setq type (if (match-end 1) org-scheduled-string
11885 (if (match-end 3) org-deadline-string "Plain:"))
11886 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
11887 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
11888 (setq n (string-to-number (match-string 2 ts))
11889 what (match-string 3 ts))
11890 (if (equal what "w") (setq n (* n 7) what "d"))
11891 ;; Preparation, see if we need to modify the start date for the change
11892 (when (match-end 1)
11893 (setq time (save-match-data (org-time-string-to-time ts)))
11894 (cond
11895 ((equal (match-string 1 ts) ".")
11896 ;; Shift starting date to today
11897 (org-timestamp-change
11898 (- (org-today) (time-to-days time))
11899 'day))
11900 ((equal (match-string 1 ts) "+")
11901 (let ((nshiftmax 10) (nshift 0))
11902 (while (or (= nshift 0)
11903 (<= (time-to-days time)
11904 (time-to-days (current-time))))
11905 (when (= (incf nshift) nshiftmax)
11906 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
11907 (error "Abort")))
11908 (org-timestamp-change n (cdr (assoc what whata)))
11909 (org-at-timestamp-p t)
11910 (setq ts (match-string 1))
11911 (setq time (save-match-data (org-time-string-to-time ts)))))
11912 (org-timestamp-change (- n) (cdr (assoc what whata)))
11913 ;; rematch, so that we have everything in place for the real shift
11914 (org-at-timestamp-p t)
11915 (setq ts (match-string 1))
11916 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
11917 (org-timestamp-change n (cdr (assoc what whata)))
11918 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
11919 (setq org-log-post-message msg)
11920 (message "%s" msg))))
11922 (defun org-show-todo-tree (arg)
11923 "Make a compact tree which shows all headlines marked with TODO.
11924 The tree will show the lines where the regexp matches, and all higher
11925 headlines above the match.
11926 With a \\[universal-argument] prefix, prompt for a regexp to match.
11927 With a numeric prefix N, construct a sparse tree for the Nth element
11928 of `org-todo-keywords-1'."
11929 (interactive "P")
11930 (let ((case-fold-search nil)
11931 (kwd-re
11932 (cond ((null arg) org-not-done-regexp)
11933 ((equal arg '(4))
11934 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
11935 (mapcar 'list org-todo-keywords-1))))
11936 (concat "\\("
11937 (mapconcat 'identity (org-split-string kwd "|") "\\|")
11938 "\\)\\>")))
11939 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
11940 (regexp-quote (nth (1- (prefix-numeric-value arg))
11941 org-todo-keywords-1)))
11942 (t (error "Invalid prefix argument: %s" arg)))))
11943 (message "%d TODO entries found"
11944 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
11946 (defun org-deadline (&optional remove time)
11947 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
11948 With argument REMOVE, remove any deadline from the item.
11949 With argument TIME, set the deadline at the corresponding date. TIME
11950 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
11951 (interactive "P")
11952 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11953 (let (org-loop-over-headlines-in-active-region)
11954 (org-map-entries
11955 `(org-deadline ',remove ,time) org-loop-over-headlines-in-active-region 'region (if (outline-invisible-p) (org-end-of-subtree nil t))))
11956 (let* ((old-date (org-entry-get nil "DEADLINE"))
11957 (repeater (and old-date
11958 (string-match
11959 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
11960 old-date)
11961 (match-string 1 old-date))))
11962 (if remove
11963 (progn
11964 (when (and old-date org-log-redeadline)
11965 (org-add-log-setup 'deldeadline nil old-date 'findpos
11966 org-log-redeadline))
11967 (org-remove-timestamp-with-keyword org-deadline-string)
11968 (message "Item no longer has a deadline."))
11969 (org-add-planning-info 'deadline time 'closed)
11970 (when (and old-date org-log-redeadline
11971 (not (equal old-date
11972 (substring org-last-inserted-timestamp 1 -1))))
11973 (org-add-log-setup 'redeadline nil old-date 'findpos
11974 org-log-redeadline))
11975 (when repeater
11976 (save-excursion
11977 (org-back-to-heading t)
11978 (when (re-search-forward (concat org-deadline-string " "
11979 org-last-inserted-timestamp)
11980 (save-excursion
11981 (outline-next-heading) (point)) t)
11982 (goto-char (1- (match-end 0)))
11983 (insert " " repeater)
11984 (setq org-last-inserted-timestamp
11985 (concat (substring org-last-inserted-timestamp 0 -1)
11986 " " repeater
11987 (substring org-last-inserted-timestamp -1))))))
11988 (message "Deadline on %s" org-last-inserted-timestamp)))))
11990 (defun org-schedule (&optional remove time)
11991 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
11992 With argument REMOVE, remove any scheduling date from the item.
11993 With argument TIME, scheduled at the corresponding date. TIME can
11994 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
11995 (interactive "P")
11996 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11997 (let (org-loop-over-headlines-in-active-region)
11998 (org-map-entries
11999 `(org-schedule ',remove ,time) org-loop-over-headlines-in-active-region 'region (if (outline-invisible-p) (org-end-of-subtree nil t))))
12000 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12001 (repeater (and old-date
12002 (string-match
12003 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
12004 old-date)
12005 (match-string 1 old-date))))
12006 (if remove
12007 (progn
12008 (when (and old-date org-log-reschedule)
12009 (org-add-log-setup 'delschedule nil old-date 'findpos
12010 org-log-reschedule))
12011 (org-remove-timestamp-with-keyword org-scheduled-string)
12012 (message "Item is no longer scheduled."))
12013 (org-add-planning-info 'scheduled time 'closed)
12014 (when (and old-date org-log-reschedule
12015 (not (equal old-date
12016 (substring org-last-inserted-timestamp 1 -1))))
12017 (org-add-log-setup 'reschedule nil old-date 'findpos
12018 org-log-reschedule))
12019 (when repeater
12020 (save-excursion
12021 (org-back-to-heading t)
12022 (when (re-search-forward (concat org-scheduled-string " "
12023 org-last-inserted-timestamp)
12024 (save-excursion
12025 (outline-next-heading) (point)) t)
12026 (goto-char (1- (match-end 0)))
12027 (insert " " repeater)
12028 (setq org-last-inserted-timestamp
12029 (concat (substring org-last-inserted-timestamp 0 -1)
12030 " " repeater
12031 (substring org-last-inserted-timestamp -1))))))
12032 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12034 (defun org-get-scheduled-time (pom &optional inherit)
12035 "Get the scheduled time as a time tuple, of a format suitable
12036 for calling org-schedule with, or if there is no scheduling,
12037 returns nil."
12038 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12039 (when time
12040 (apply 'encode-time (org-parse-time-string time)))))
12042 (defun org-get-deadline-time (pom &optional inherit)
12043 "Get the deadline as a time tuple, of a format suitable for
12044 calling org-deadline with, or if there is no scheduling, returns
12045 nil."
12046 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12047 (when time
12048 (apply 'encode-time (org-parse-time-string time)))))
12050 (defun org-remove-timestamp-with-keyword (keyword)
12051 "Remove all time stamps with KEYWORD in the current entry."
12052 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12053 beg)
12054 (save-excursion
12055 (org-back-to-heading t)
12056 (setq beg (point))
12057 (outline-next-heading)
12058 (while (re-search-backward re beg t)
12059 (replace-match "")
12060 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12061 (equal (char-before) ?\ ))
12062 (backward-delete-char 1)
12063 (if (string-match "^[ \t]*$" (buffer-substring
12064 (point-at-bol) (point-at-eol)))
12065 (delete-region (point-at-bol)
12066 (min (point-max) (1+ (point-at-eol))))))))))
12068 (defun org-add-planning-info (what &optional time &rest remove)
12069 "Insert new timestamp with keyword in the line directly after the headline.
12070 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12071 If non is given, the user is prompted for a date.
12072 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12073 be removed."
12074 (interactive)
12075 (let (org-time-was-given org-end-time-was-given ts
12076 end default-time default-input)
12078 (catch 'exit
12079 (when (and (memq what '(scheduled deadline))
12080 (or (not time)
12081 (and (stringp time)
12082 (string-match "^[-+]+[0-9]" time))))
12083 ;; Try to get a default date/time from existing timestamp
12084 (save-excursion
12085 (org-back-to-heading t)
12086 (setq end (save-excursion (outline-next-heading) (point)))
12087 (when (re-search-forward (if (eq what 'scheduled)
12088 org-scheduled-time-regexp
12089 org-deadline-time-regexp)
12090 end t)
12091 (setq ts (match-string 1)
12092 default-time
12093 (apply 'encode-time (org-parse-time-string ts))
12094 default-input (and ts (org-get-compact-tod ts))))))
12095 (when what
12096 (setq time
12097 (if (stringp time)
12098 ;; This is a string (relative or absolute), set proper date
12099 (apply 'encode-time
12100 (org-read-date-analyze
12101 time default-time (decode-time default-time)))
12102 ;; If necessary, get the time from the user
12103 (or time (org-read-date nil 'to-time nil nil
12104 default-time default-input)))))
12106 (when (and org-insert-labeled-timestamps-at-point
12107 (member what '(scheduled deadline)))
12108 (insert
12109 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12110 (org-insert-time-stamp time org-time-was-given
12111 nil nil nil (list org-end-time-was-given))
12112 (setq what nil))
12113 (save-excursion
12114 (save-restriction
12115 (let (col list elt ts buffer-invisibility-spec)
12116 (org-back-to-heading t)
12117 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12118 (goto-char (match-end 1))
12119 (setq col (current-column))
12120 (goto-char (match-end 0))
12121 (if (eobp) (insert "\n") (forward-char 1))
12122 (when (and (not what)
12123 (not (looking-at
12124 (concat "[ \t]*"
12125 org-keyword-time-not-clock-regexp))))
12126 ;; Nothing to add, nothing to remove...... :-)
12127 (throw 'exit nil))
12128 (if (and (not (looking-at org-outline-regexp))
12129 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12130 "[^\r\n]*"))
12131 (not (equal (match-string 1) org-clock-string)))
12132 (narrow-to-region (match-beginning 0) (match-end 0))
12133 (insert-before-markers "\n")
12134 (backward-char 1)
12135 (narrow-to-region (point) (point))
12136 (and org-adapt-indentation (org-indent-to-column col)))
12137 ;; Check if we have to remove something.
12138 (setq list (cons what remove))
12139 (while list
12140 (setq elt (pop list))
12141 (when (or (and (eq elt 'scheduled)
12142 (re-search-forward org-scheduled-time-regexp nil t))
12143 (and (eq elt 'deadline)
12144 (re-search-forward org-deadline-time-regexp nil t))
12145 (and (eq elt 'closed)
12146 (re-search-forward org-closed-time-regexp nil t)))
12147 (replace-match "")
12148 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12149 (and (looking-at "[ \t]+") (replace-match ""))
12150 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12151 (when what
12152 (insert
12153 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12154 (cond ((eq what 'scheduled) org-scheduled-string)
12155 ((eq what 'deadline) org-deadline-string)
12156 ((eq what 'closed) org-closed-string))
12157 " ")
12158 (setq ts (org-insert-time-stamp
12159 time
12160 (or org-time-was-given
12161 (and (eq what 'closed) org-log-done-with-time))
12162 (eq what 'closed)
12163 nil nil (list org-end-time-was-given)))
12164 (insert
12165 (if (not (or (bolp) (eq (char-before) ?\ )
12166 (memq (char-after) '(32 10))
12167 (eobp))) " " ""))
12168 (end-of-line 1))
12169 (goto-char (point-min))
12170 (widen)
12171 (if (and (looking-at "[ \t]*\n")
12172 (equal (char-before) ?\n))
12173 (delete-region (1- (point)) (point-at-eol)))
12174 ts))))))
12176 (defvar org-log-note-marker (make-marker))
12177 (defvar org-log-note-purpose nil)
12178 (defvar org-log-note-state nil)
12179 (defvar org-log-note-previous-state nil)
12180 (defvar org-log-note-how nil)
12181 (defvar org-log-note-extra nil)
12182 (defvar org-log-note-window-configuration nil)
12183 (defvar org-log-note-return-to (make-marker))
12184 (defvar org-log-note-effective-time nil
12185 "Remembered current time so that dynamically scoped
12186 `org-extend-today-until' affects tha timestamps in state change
12187 log")
12189 (defvar org-log-post-message nil
12190 "Message to be displayed after a log note has been stored.
12191 The auto-repeater uses this.")
12193 (defun org-add-note ()
12194 "Add a note to the current entry.
12195 This is done in the same way as adding a state change note."
12196 (interactive)
12197 (org-add-log-setup 'note nil nil 'findpos nil))
12199 (defvar org-property-end-re)
12200 (defun org-add-log-setup (&optional purpose state prev-state
12201 findpos how extra)
12202 "Set up the post command hook to take a note.
12203 If this is about to TODO state change, the new state is expected in STATE.
12204 When FINDPOS is non-nil, find the correct position for the note in
12205 the current entry. If not, assume that it can be inserted at point.
12206 HOW is an indicator what kind of note should be created.
12207 EXTRA is additional text that will be inserted into the notes buffer."
12208 (let* ((org-log-into-drawer (org-log-into-drawer))
12209 (drawer (cond ((stringp org-log-into-drawer)
12210 org-log-into-drawer)
12211 (org-log-into-drawer "LOGBOOK")
12212 (t nil))))
12213 (save-restriction
12214 (save-excursion
12215 (when findpos
12216 (org-back-to-heading t)
12217 (narrow-to-region (point) (save-excursion
12218 (outline-next-heading) (point)))
12219 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12220 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12221 "[^\r\n]*\\)?"))
12222 (goto-char (match-end 0))
12223 (cond
12224 (drawer
12225 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12226 nil t)
12227 (progn
12228 (goto-char (match-end 0))
12229 (or org-log-states-order-reversed
12230 (and (re-search-forward org-property-end-re nil t)
12231 (goto-char (1- (match-beginning 0))))))
12232 (insert "\n:" drawer ":\n:END:")
12233 (beginning-of-line 0)
12234 (org-indent-line-function)
12235 (beginning-of-line 2)
12236 (org-indent-line-function)
12237 (end-of-line 0)))
12238 ((and org-log-state-notes-insert-after-drawers
12239 (save-excursion
12240 (forward-line) (looking-at org-drawer-regexp)))
12241 (forward-line)
12242 (while (looking-at org-drawer-regexp)
12243 (goto-char (match-end 0))
12244 (re-search-forward org-property-end-re (point-max) t)
12245 (forward-line))
12246 (forward-line -1)))
12247 (unless org-log-states-order-reversed
12248 (and (= (char-after) ?\n) (forward-char 1))
12249 (org-skip-over-state-notes)
12250 (skip-chars-backward " \t\n\r")))
12251 (move-marker org-log-note-marker (point))
12252 (setq org-log-note-purpose purpose
12253 org-log-note-state state
12254 org-log-note-previous-state prev-state
12255 org-log-note-how how
12256 org-log-note-extra extra
12257 org-log-note-effective-time (org-current-effective-time))
12258 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12260 (defun org-skip-over-state-notes ()
12261 "Skip past the list of State notes in an entry."
12262 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12263 (when (ignore-errors (goto-char (org-in-item-p)))
12264 (let* ((struct (org-list-struct))
12265 (prevs (org-list-prevs-alist struct)))
12266 (while (looking-at "[ \t]*- State")
12267 (goto-char (or (org-list-get-next-item (point) struct prevs)
12268 (org-list-get-item-end (point) struct)))))))
12270 (defun org-add-log-note (&optional purpose)
12271 "Pop up a window for taking a note, and add this note later at point."
12272 (remove-hook 'post-command-hook 'org-add-log-note)
12273 (setq org-log-note-window-configuration (current-window-configuration))
12274 (delete-other-windows)
12275 (move-marker org-log-note-return-to (point))
12276 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12277 (goto-char org-log-note-marker)
12278 (org-switch-to-buffer-other-window "*Org Note*")
12279 (erase-buffer)
12280 (if (memq org-log-note-how '(time state))
12281 (let (current-prefix-arg) (org-store-log-note))
12282 (let ((org-inhibit-startup t)) (org-mode))
12283 (insert (format "# Insert note for %s.
12284 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12285 (cond
12286 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12287 ((eq org-log-note-purpose 'done) "closed todo item")
12288 ((eq org-log-note-purpose 'state)
12289 (format "state change from \"%s\" to \"%s\""
12290 (or org-log-note-previous-state "")
12291 (or org-log-note-state "")))
12292 ((eq org-log-note-purpose 'reschedule)
12293 "rescheduling")
12294 ((eq org-log-note-purpose 'delschedule)
12295 "no longer scheduled")
12296 ((eq org-log-note-purpose 'redeadline)
12297 "changing deadline")
12298 ((eq org-log-note-purpose 'deldeadline)
12299 "removing deadline")
12300 ((eq org-log-note-purpose 'refile)
12301 "refiling")
12302 ((eq org-log-note-purpose 'note)
12303 "this entry")
12304 (t (error "This should not happen")))))
12305 (if org-log-note-extra (insert org-log-note-extra))
12306 (org-set-local 'org-finish-function 'org-store-log-note)
12307 (run-hooks 'org-log-buffer-setup-hook)))
12309 (defvar org-note-abort nil) ; dynamically scoped
12310 (defun org-store-log-note ()
12311 "Finish taking a log note, and insert it to where it belongs."
12312 (let ((txt (buffer-string))
12313 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12314 lines ind bul)
12315 (kill-buffer (current-buffer))
12316 (while (string-match "\\`#.*\n[ \t\n]*" txt)
12317 (setq txt (replace-match "" t t txt)))
12318 (if (string-match "\\s-+\\'" txt)
12319 (setq txt (replace-match "" t t txt)))
12320 (setq lines (org-split-string txt "\n"))
12321 (when (and note (string-match "\\S-" note))
12322 (setq note
12323 (org-replace-escapes
12324 note
12325 (list (cons "%u" (user-login-name))
12326 (cons "%U" user-full-name)
12327 (cons "%t" (format-time-string
12328 (org-time-stamp-format 'long 'inactive)
12329 org-log-note-effective-time))
12330 (cons "%T" (format-time-string
12331 (org-time-stamp-format 'long nil)
12332 org-log-note-effective-time))
12333 (cons "%d" (format-time-string
12334 (org-time-stamp-format nil 'inactive)
12335 org-log-note-effective-time))
12336 (cons "%D" (format-time-string
12337 (org-time-stamp-format nil nil)
12338 org-log-note-effective-time))
12339 (cons "%s" (if org-log-note-state
12340 (concat "\"" org-log-note-state "\"")
12341 ""))
12342 (cons "%S" (if org-log-note-previous-state
12343 (concat "\"" org-log-note-previous-state "\"")
12344 "\"\"")))))
12345 (if lines (setq note (concat note " \\\\")))
12346 (push note lines))
12347 (when (or current-prefix-arg org-note-abort)
12348 (when org-log-into-drawer
12349 (org-remove-empty-drawer-at
12350 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12351 org-log-note-marker))
12352 (setq lines nil))
12353 (when lines
12354 (with-current-buffer (marker-buffer org-log-note-marker)
12355 (save-excursion
12356 (goto-char org-log-note-marker)
12357 (move-marker org-log-note-marker nil)
12358 (end-of-line 1)
12359 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12360 (setq ind (save-excursion
12361 (if (ignore-errors (goto-char (org-in-item-p)))
12362 (let ((struct (org-list-struct)))
12363 (org-list-get-ind
12364 (org-list-get-top-point struct) struct))
12365 (skip-chars-backward " \r\t\n")
12366 (cond
12367 ((and (org-at-heading-p)
12368 org-adapt-indentation)
12369 (1+ (org-current-level)))
12370 ((org-at-heading-p) 0)
12371 (t (org-get-indentation))))))
12372 (setq bul (org-list-bullet-string "-"))
12373 (org-indent-line-to ind)
12374 (insert bul (pop lines))
12375 (let ((ind-body (+ (length bul) ind)))
12376 (while lines
12377 (insert "\n")
12378 (org-indent-line-to ind-body)
12379 (insert (pop lines))))
12380 (message "Note stored")
12381 (org-back-to-heading t)
12382 (org-cycle-hide-drawers 'children)))))
12383 (set-window-configuration org-log-note-window-configuration)
12384 (with-current-buffer (marker-buffer org-log-note-return-to)
12385 (goto-char org-log-note-return-to))
12386 (move-marker org-log-note-return-to nil)
12387 (and org-log-post-message (message "%s" org-log-post-message)))
12389 (defun org-remove-empty-drawer-at (drawer pos)
12390 "Remove an empty drawer DRAWER at position POS.
12391 POS may also be a marker."
12392 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12393 (save-excursion
12394 (save-restriction
12395 (widen)
12396 (goto-char pos)
12397 (if (org-in-regexp
12398 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12399 (replace-match ""))))))
12401 (defun org-sparse-tree (&optional arg)
12402 "Create a sparse tree, prompt for the details.
12403 This command can create sparse trees. You first need to select the type
12404 of match used to create the tree:
12406 t Show all TODO entries.
12407 T Show entries with a specific TODO keyword.
12408 m Show entries selected by a tags/property match.
12409 p Enter a property name and its value (both with completion on existing
12410 names/values) and show entries with that property.
12411 r Show entries matching a regular expression (`/' can be used as well)
12412 d Show deadlines due within `org-deadline-warning-days'.
12413 b Show deadlines and scheduled items before a date.
12414 a Show deadlines and scheduled items after a date."
12415 (interactive "P")
12416 (let (ans kwd value)
12417 (message "Sparse tree: [r]egexp [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty\n [d]eadlines [b]efore-date [a]fter-date")
12418 (setq ans (read-char-exclusive))
12419 (cond
12420 ((equal ans ?d)
12421 (call-interactively 'org-check-deadlines))
12422 ((equal ans ?b)
12423 (call-interactively 'org-check-before-date))
12424 ((equal ans ?a)
12425 (call-interactively 'org-check-after-date))
12426 ((equal ans ?t)
12427 (org-show-todo-tree nil))
12428 ((equal ans ?T)
12429 (org-show-todo-tree '(4)))
12430 ((member ans '(?T ?m))
12431 (call-interactively 'org-match-sparse-tree))
12432 ((member ans '(?p ?P))
12433 (setq kwd (org-icompleting-read "Property: "
12434 (mapcar 'list (org-buffer-property-keys))))
12435 (setq value (org-icompleting-read "Value: "
12436 (mapcar 'list (org-property-values kwd))))
12437 (unless (string-match "\\`{.*}\\'" value)
12438 (setq value (concat "\"" value "\"")))
12439 (org-match-sparse-tree arg (concat kwd "=" value)))
12440 ((member ans '(?r ?R ?/))
12441 (call-interactively 'org-occur))
12442 (t (error "No such sparse tree command \"%c\"" ans)))))
12444 (defvar org-occur-highlights nil
12445 "List of overlays used for occur matches.")
12446 (make-variable-buffer-local 'org-occur-highlights)
12447 (defvar org-occur-parameters nil
12448 "Parameters of the active org-occur calls.
12449 This is a list, each call to org-occur pushes as cons cell,
12450 containing the regular expression and the callback, onto the list.
12451 The list can contain several entries if `org-occur' has been called
12452 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12453 will only contain one set of parameters. When the highlights are
12454 removed (for example with `C-c C-c', or with the next edit (depending
12455 on `org-remove-highlights-with-change'), this variable is emptied
12456 as well.")
12457 (make-variable-buffer-local 'org-occur-parameters)
12459 (defun org-occur (regexp &optional keep-previous callback)
12460 "Make a compact tree which shows all matches of REGEXP.
12461 The tree will show the lines where the regexp matches, and all higher
12462 headlines above the match. It will also show the heading after the match,
12463 to make sure editing the matching entry is easy.
12464 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12465 call to `org-occur' will be kept, to allow stacking of calls to this
12466 command.
12467 If CALLBACK is non-nil, it is a function which is called to confirm
12468 that the match should indeed be shown."
12469 (interactive "sRegexp: \nP")
12470 (when (equal regexp "")
12471 (error "Regexp cannot be empty"))
12472 (unless keep-previous
12473 (org-remove-occur-highlights nil nil t))
12474 (push (cons regexp callback) org-occur-parameters)
12475 (let ((cnt 0))
12476 (save-excursion
12477 (goto-char (point-min))
12478 (if (or (not keep-previous) ; do not want to keep
12479 (not org-occur-highlights)) ; no previous matches
12480 ;; hide everything
12481 (org-overview))
12482 (while (re-search-forward regexp nil t)
12483 (when (or (not callback)
12484 (save-match-data (funcall callback)))
12485 (setq cnt (1+ cnt))
12486 (when org-highlight-sparse-tree-matches
12487 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12488 (org-show-context 'occur-tree))))
12489 (when org-remove-highlights-with-change
12490 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12491 nil 'local))
12492 (unless org-sparse-tree-open-archived-trees
12493 (org-hide-archived-subtrees (point-min) (point-max)))
12494 (run-hooks 'org-occur-hook)
12495 (if (org-called-interactively-p 'interactive)
12496 (message "%d match(es) for regexp %s" cnt regexp))
12497 cnt))
12499 (defun org-occur-next-match (&optional n reset)
12500 "Function for `next-error-function' to find sparse tree matches.
12501 N is the number of matches to move, when negative move backwards.
12502 RESET is entirely ignored - this function always goes back to the
12503 starting point when no match is found."
12504 (let* ((limit (if (< n 0) (point-min) (point-max)))
12505 (search-func (if (< n 0)
12506 'previous-single-char-property-change
12507 'next-single-char-property-change))
12508 (n (abs n))
12509 (pos (point))
12511 (catch 'exit
12512 (while (setq p1 (funcall search-func (point) 'org-type))
12513 (when (equal p1 limit)
12514 (goto-char pos)
12515 (error "No more matches"))
12516 (when (equal (get-char-property p1 'org-type) 'org-occur)
12517 (setq n (1- n))
12518 (when (= n 0)
12519 (goto-char p1)
12520 (throw 'exit (point))))
12521 (goto-char p1))
12522 (goto-char p1)
12523 (error "No more matches"))))
12525 (defun org-show-context (&optional key)
12526 "Make sure point and context are visible.
12527 How much context is shown depends upon the variables
12528 `org-show-hierarchy-above', `org-show-following-heading',
12529 `org-show-entry-below' and `org-show-siblings'."
12530 (let ((heading-p (org-on-heading-p t))
12531 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12532 (following-p (org-get-alist-option org-show-following-heading key))
12533 (entry-p (org-get-alist-option org-show-entry-below key))
12534 (siblings-p (org-get-alist-option org-show-siblings key)))
12535 (catch 'exit
12536 ;; Show heading or entry text
12537 (if (and heading-p (not entry-p))
12538 (org-flag-heading nil) ; only show the heading
12539 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12540 (org-show-hidden-entry))) ; show entire entry
12541 (when following-p
12542 ;; Show next sibling, or heading below text
12543 (save-excursion
12544 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12545 (org-flag-heading nil))))
12546 (when siblings-p (org-show-siblings))
12547 (when hierarchy-p
12548 ;; show all higher headings, possibly with siblings
12549 (save-excursion
12550 (while (and (condition-case nil
12551 (progn (org-up-heading-all 1) t)
12552 (error nil))
12553 (not (bobp)))
12554 (org-flag-heading nil)
12555 (when siblings-p (org-show-siblings))))))))
12557 (defvar org-reveal-start-hook nil
12558 "Hook run before revealing a location.")
12560 (defun org-reveal (&optional siblings)
12561 "Show current entry, hierarchy above it, and the following headline.
12562 This can be used to show a consistent set of context around locations
12563 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12564 not t for the search context.
12566 With optional argument SIBLINGS, on each level of the hierarchy all
12567 siblings are shown. This repairs the tree structure to what it would
12568 look like when opened with hierarchical calls to `org-cycle'.
12569 With double optional argument \\[universal-argument] \\[universal-argument], \
12570 go to the parent and show the
12571 entire tree."
12572 (interactive "P")
12573 (run-hooks 'org-reveal-start-hook)
12574 (let ((org-show-hierarchy-above t)
12575 (org-show-following-heading t)
12576 (org-show-siblings (if siblings t org-show-siblings)))
12577 (org-show-context nil))
12578 (when (equal siblings '(16))
12579 (save-excursion
12580 (when (org-up-heading-safe)
12581 (org-show-subtree)
12582 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12584 (defun org-highlight-new-match (beg end)
12585 "Highlight from BEG to END and mark the highlight is an occur headline."
12586 (let ((ov (make-overlay beg end)))
12587 (overlay-put ov 'face 'secondary-selection)
12588 (overlay-put ov 'org-type 'org-occur)
12589 (push ov org-occur-highlights)))
12591 (defun org-remove-occur-highlights (&optional beg end noremove)
12592 "Remove the occur highlights from the buffer.
12593 BEG and END are ignored. If NOREMOVE is nil, remove this function
12594 from the `before-change-functions' in the current buffer."
12595 (interactive)
12596 (unless org-inhibit-highlight-removal
12597 (mapc 'delete-overlay org-occur-highlights)
12598 (setq org-occur-highlights nil)
12599 (setq org-occur-parameters nil)
12600 (unless noremove
12601 (remove-hook 'before-change-functions
12602 'org-remove-occur-highlights 'local))))
12604 ;;;; Priorities
12606 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12607 "Regular expression matching the priority indicator.")
12609 (defvar org-remove-priority-next-time nil)
12611 (defun org-priority-up ()
12612 "Increase the priority of the current item."
12613 (interactive)
12614 (org-priority 'up))
12616 (defun org-priority-down ()
12617 "Decrease the priority of the current item."
12618 (interactive)
12619 (org-priority 'down))
12621 (defun org-priority (&optional action)
12622 "Change the priority of an item by ARG.
12623 ACTION can be `set', `up', `down', or a character."
12624 (interactive)
12625 (unless org-enable-priority-commands
12626 (error "Priority commands are disabled"))
12627 (setq action (or action 'set))
12628 (let (current new news have remove)
12629 (save-excursion
12630 (org-back-to-heading t)
12631 (if (looking-at org-priority-regexp)
12632 (setq current (string-to-char (match-string 2))
12633 have t))
12634 (cond
12635 ((eq action 'remove)
12636 (setq remove t new ?\ ))
12637 ((or (eq action 'set)
12638 (if (featurep 'xemacs) (characterp action) (integerp action)))
12639 (if (not (eq action 'set))
12640 (setq new action)
12641 (message "Priority %c-%c, SPC to remove: "
12642 org-highest-priority org-lowest-priority)
12643 (save-match-data
12644 (setq new (read-char-exclusive))))
12645 (if (and (= (upcase org-highest-priority) org-highest-priority)
12646 (= (upcase org-lowest-priority) org-lowest-priority))
12647 (setq new (upcase new)))
12648 (cond ((equal new ?\ ) (setq remove t))
12649 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12650 (error "Priority must be between `%c' and `%c'"
12651 org-highest-priority org-lowest-priority))))
12652 ((eq action 'up)
12653 (setq new (if have
12654 (1- current) ; normal cycling
12655 ;; last priority was empty
12656 (if (eq last-command this-command)
12657 org-lowest-priority ; wrap around empty to lowest
12658 ;; default
12659 (if org-priority-start-cycle-with-default
12660 org-default-priority
12661 (1- org-default-priority))))))
12662 ((eq action 'down)
12663 (setq new (if have
12664 (1+ current) ; normal cycling
12665 ;; last priority was empty
12666 (if (eq last-command this-command)
12667 org-highest-priority ; wrap around empty to highest
12668 ;; default
12669 (if org-priority-start-cycle-with-default
12670 org-default-priority
12671 (1+ org-default-priority))))))
12672 (t (error "Invalid action")))
12673 (if (or (< (upcase new) org-highest-priority)
12674 (> (upcase new) org-lowest-priority))
12675 (if (and (memq action '(up down))
12676 (not have) (not (eq last-command this-command)))
12677 ;; `new' is from default priority
12678 (error
12679 "The default can not be set, see `org-default-priority' why")
12680 ;; normal cycling: `new' is beyond highest/lowest priority
12681 ;; and is wrapped around to the empty priority
12682 (setq remove t)))
12683 (setq news (format "%c" new))
12684 (if have
12685 (if remove
12686 (replace-match "" t t nil 1)
12687 (replace-match news t t nil 2))
12688 (if remove
12689 (error "No priority cookie found in line")
12690 (let ((case-fold-search nil))
12691 (looking-at org-todo-line-regexp))
12692 (if (match-end 2)
12693 (progn
12694 (goto-char (match-end 2))
12695 (insert " [#" news "]"))
12696 (goto-char (match-beginning 3))
12697 (insert "[#" news "] "))))
12698 (org-preserve-lc (org-set-tags nil 'align)))
12699 (if remove
12700 (message "Priority removed")
12701 (message "Priority of current item set to %s" news))))
12703 (defun org-get-priority (s)
12704 "Find priority cookie and return priority."
12705 (if (functionp org-get-priority-function)
12706 (funcall org-get-priority-function)
12707 (save-match-data
12708 (if (not (string-match org-priority-regexp s))
12709 (* 1000 (- org-lowest-priority org-default-priority))
12710 (* 1000 (- org-lowest-priority
12711 (string-to-char (match-string 2 s))))))))
12713 ;;;; Tags
12715 (defvar org-agenda-archives-mode)
12716 (defvar org-map-continue-from nil
12717 "Position from where mapping should continue.
12718 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
12720 (defvar org-scanner-tags nil
12721 "The current tag list while the tags scanner is running.")
12722 (defvar org-trust-scanner-tags nil
12723 "Should `org-get-tags-at' use the tags for the scanner.
12724 This is for internal dynamical scoping only.
12725 When this is non-nil, the function `org-get-tags-at' will return the value
12726 of `org-scanner-tags' instead of building the list by itself. This
12727 can lead to large speed-ups when the tags scanner is used in a file with
12728 many entries, and when the list of tags is retrieved, for example to
12729 obtain a list of properties. Building the tags list for each entry in such
12730 a file becomes an N^2 operation - but with this variable set, it scales
12731 as N.")
12733 (defun org-scan-tags (action matcher &optional todo-only start-level)
12734 "Scan headline tags with inheritance and produce output ACTION.
12736 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12737 or `agenda' to produce an entry list for an agenda view. It can also be
12738 a Lisp form or a function that should be called at each matched headline, in
12739 this case the return value is a list of all return values from these calls.
12741 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12742 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12743 only lines with a TODO keyword are included in the output.
12745 START-LEVEL can be a string with asterisks, reducing the scope to
12746 headlines matching this string."
12747 (require 'org-agenda)
12748 (let* ((re (concat "^"
12749 (if start-level
12750 ;; Get the correct level to match
12751 (concat "\\*\\{" (number-to-string start-level) "\\} ")
12752 org-outline-regexp)
12753 " *\\(\\<\\("
12754 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12755 (org-re
12756 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
12757 (props (list 'face 'default
12758 'done-face 'org-agenda-done
12759 'undone-face 'default
12760 'mouse-face 'highlight
12761 'org-not-done-regexp org-not-done-regexp
12762 'org-todo-regexp org-todo-regexp
12763 'org-complex-heading-regexp org-complex-heading-regexp
12764 'help-echo
12765 (format "mouse-2 or RET jump to org file %s"
12766 (abbreviate-file-name
12767 (or (buffer-file-name (buffer-base-buffer))
12768 (buffer-name (buffer-base-buffer)))))))
12769 (case-fold-search nil)
12770 (org-map-continue-from nil)
12771 lspos tags tags-list
12772 (tags-alist (list (cons 0 org-file-tags)))
12773 (llast 0) rtn rtn1 level category i txt
12774 todo marker entry priority)
12775 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12776 (setq action (list 'lambda nil action)))
12777 (save-excursion
12778 (goto-char (point-min))
12779 (when (eq action 'sparse-tree)
12780 (org-overview)
12781 (org-remove-occur-highlights))
12782 (while (re-search-forward re nil t)
12783 (setq org-map-continue-from nil)
12784 (catch :skip
12785 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12786 tags (if (match-end 4) (org-match-string-no-properties 4)))
12787 (goto-char (setq lspos (match-beginning 0)))
12788 (setq level (org-reduced-level (funcall outline-level))
12789 category (org-get-category))
12790 (setq i llast llast level)
12791 ;; remove tag lists from same and sublevels
12792 (while (>= i level)
12793 (when (setq entry (assoc i tags-alist))
12794 (setq tags-alist (delete entry tags-alist)))
12795 (setq i (1- i)))
12796 ;; add the next tags
12797 (when tags
12798 (setq tags (org-split-string tags ":")
12799 tags-alist
12800 (cons (cons level tags) tags-alist)))
12801 ;; compile tags for current headline
12802 (setq tags-list
12803 (if org-use-tag-inheritance
12804 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12805 tags)
12806 org-scanner-tags tags-list)
12807 (when org-use-tag-inheritance
12808 (setcdr (car tags-alist)
12809 (mapcar (lambda (x)
12810 (setq x (copy-sequence x))
12811 (org-add-prop-inherited x))
12812 (cdar tags-alist))))
12813 (when (and tags org-use-tag-inheritance
12814 (or (not (eq t org-use-tag-inheritance))
12815 org-tags-exclude-from-inheritance))
12816 ;; selective inheritance, remove uninherited ones
12817 (setcdr (car tags-alist)
12818 (org-remove-uninherited-tags (cdar tags-alist))))
12819 (when (and
12821 ;; eval matcher only when the todo condition is OK
12822 (and (or (not todo-only) (member todo org-not-done-keywords))
12823 (let ((case-fold-search t)) (eval matcher)))
12825 ;; Call the skipper, but return t if it does not skip,
12826 ;; so that the `and' form continues evaluating
12827 (progn
12828 (unless (eq action 'sparse-tree) (org-agenda-skip))
12831 ;; Check if timestamps are deselecting this entry
12832 (or (not todo-only)
12833 (and (member todo org-not-done-keywords)
12834 (or (not org-agenda-tags-todo-honor-ignore-options)
12835 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
12837 ;; Extra check for the archive tag
12838 ;; FIXME: Does the skipper already do this????
12840 (not (member org-archive-tag tags-list))
12841 ;; we have an archive tag, should we use this anyway?
12842 (or (not org-agenda-skip-archived-trees)
12843 (and (eq action 'agenda) org-agenda-archives-mode))))
12845 ;; select this headline
12847 (cond
12848 ((eq action 'sparse-tree)
12849 (and org-highlight-sparse-tree-matches
12850 (org-get-heading) (match-end 0)
12851 (org-highlight-new-match
12852 (match-beginning 0) (match-beginning 1)))
12853 (org-show-context 'tags-tree))
12854 ((eq action 'agenda)
12855 (setq txt (org-agenda-format-item
12857 (concat
12858 (if (eq org-tags-match-list-sublevels 'indented)
12859 (make-string (1- level) ?.) "")
12860 (org-get-heading))
12861 category
12862 tags-list
12864 priority (org-get-priority txt))
12865 (goto-char lspos)
12866 (setq marker (org-agenda-new-marker))
12867 (org-add-props txt props
12868 'org-marker marker 'org-hd-marker marker 'org-category category
12869 'todo-state todo
12870 'priority priority 'type "tagsmatch")
12871 (push txt rtn))
12872 ((functionp action)
12873 (setq org-map-continue-from nil)
12874 (save-excursion
12875 (setq rtn1 (funcall action))
12876 (push rtn1 rtn)))
12877 (t (error "Invalid action")))
12879 ;; if we are to skip sublevels, jump to end of subtree
12880 (unless org-tags-match-list-sublevels
12881 (org-end-of-subtree t)
12882 (backward-char 1))))
12883 ;; Get the correct position from where to continue
12884 (if org-map-continue-from
12885 (goto-char org-map-continue-from)
12886 (and (= (point) lspos) (end-of-line 1)))))
12887 (when (and (eq action 'sparse-tree)
12888 (not org-sparse-tree-open-archived-trees))
12889 (org-hide-archived-subtrees (point-min) (point-max)))
12890 (nreverse rtn)))
12892 (defun org-remove-uninherited-tags (tags)
12893 "Remove all tags that are not inherited from the list TAGS."
12894 (cond
12895 ((eq org-use-tag-inheritance t)
12896 (if org-tags-exclude-from-inheritance
12897 (org-delete-all org-tags-exclude-from-inheritance tags)
12898 tags))
12899 ((not org-use-tag-inheritance) nil)
12900 ((stringp org-use-tag-inheritance)
12901 (delq nil (mapcar
12902 (lambda (x)
12903 (if (and (string-match org-use-tag-inheritance x)
12904 (not (member x org-tags-exclude-from-inheritance)))
12905 x nil))
12906 tags)))
12907 ((listp org-use-tag-inheritance)
12908 (delq nil (mapcar
12909 (lambda (x)
12910 (if (member x org-use-tag-inheritance) x nil))
12911 tags)))))
12913 (defvar todo-only) ;; dynamically scoped
12915 (defun org-match-sparse-tree (&optional todo-only match)
12916 "Create a sparse tree according to tags string MATCH.
12917 MATCH can contain positive and negative selection of tags, like
12918 \"+WORK+URGENT-WITHBOSS\".
12919 If optional argument TODO-ONLY is non-nil, only select lines that are
12920 also TODO lines."
12921 (interactive "P")
12922 (org-prepare-agenda-buffers (list (current-buffer)))
12923 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
12925 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
12927 (defvar org-cached-props nil)
12928 (defun org-cached-entry-get (pom property)
12929 (if (or (eq t org-use-property-inheritance)
12930 (and (stringp org-use-property-inheritance)
12931 (string-match org-use-property-inheritance property))
12932 (and (listp org-use-property-inheritance)
12933 (member property org-use-property-inheritance)))
12934 ;; Caching is not possible, check it directly
12935 (org-entry-get pom property 'inherit)
12936 ;; Get all properties, so that we can do complicated checks easily
12937 (cdr (assoc property (or org-cached-props
12938 (setq org-cached-props
12939 (org-entry-properties pom)))))))
12941 (defun org-global-tags-completion-table (&optional files)
12942 "Return the list of all tags in all agenda buffer/files.
12943 Optional FILES argument is a list of files to which can be used
12944 instead of the agenda files."
12945 (save-excursion
12946 (org-uniquify
12947 (delq nil
12948 (apply 'append
12949 (mapcar
12950 (lambda (file)
12951 (set-buffer (find-file-noselect file))
12952 (append (org-get-buffer-tags)
12953 (mapcar (lambda (x) (if (stringp (car-safe x))
12954 (list (car-safe x)) nil))
12955 org-tag-alist)))
12956 (if (and files (car files))
12957 files
12958 (org-agenda-files))))))))
12960 (defun org-make-tags-matcher (match)
12961 "Create the TAGS/TODO matcher form for the selection string MATCH."
12962 ;; todo-only is scoped dynamically into this function, and the function
12963 ;; may change it if the matcher asks for it.
12964 (unless match
12965 ;; Get a new match request, with completion
12966 (let ((org-last-tags-completion-table
12967 (org-global-tags-completion-table)))
12968 (setq match (org-completing-read-no-i
12969 "Match: " 'org-tags-completion-function nil nil nil
12970 'org-tags-history))))
12972 ;; Parse the string and create a lisp form
12973 (let ((match0 match)
12974 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
12975 minus tag mm
12976 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
12977 orterms term orlist re-p str-p level-p level-op time-p
12978 prop-p pn pv po gv rest)
12979 (if (string-match "/+" match)
12980 ;; match contains also a todo-matching request
12981 (progn
12982 (setq tagsmatch (substring match 0 (match-beginning 0))
12983 todomatch (substring match (match-end 0)))
12984 (if (string-match "^!" todomatch)
12985 (setq todo-only t todomatch (substring todomatch 1)))
12986 (if (string-match "^\\s-*$" todomatch)
12987 (setq todomatch nil)))
12988 ;; only matching tags
12989 (setq tagsmatch match todomatch nil))
12991 ;; Make the tags matcher
12992 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
12993 (setq tagsmatcher t)
12994 (setq orterms (org-split-string tagsmatch "|") orlist nil)
12995 (while (setq term (pop orterms))
12996 (while (and (equal (substring term -1) "\\") orterms)
12997 (setq term (concat term "|" (pop orterms)))) ; repair bad split
12998 (while (string-match re term)
12999 (setq rest (substring term (match-end 0))
13000 minus (and (match-end 1)
13001 (equal (match-string 1 term) "-"))
13002 tag (save-match-data (replace-regexp-in-string
13003 "\\\\-" "-"
13004 (match-string 2 term)))
13005 re-p (equal (string-to-char tag) ?{)
13006 level-p (match-end 4)
13007 prop-p (match-end 5)
13008 mm (cond
13009 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13010 (level-p
13011 (setq level-op (org-op-to-function (match-string 3 term)))
13012 `(,level-op level ,(string-to-number
13013 (match-string 4 term))))
13014 (prop-p
13015 (setq pn (match-string 5 term)
13016 po (match-string 6 term)
13017 pv (match-string 7 term)
13018 re-p (equal (string-to-char pv) ?{)
13019 str-p (equal (string-to-char pv) ?\")
13020 time-p (save-match-data
13021 (string-match "^\"[[<].*[]>]\"$" pv))
13022 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13023 (if time-p (setq pv (org-matcher-time pv)))
13024 (setq po (org-op-to-function po (if time-p 'time str-p)))
13025 (cond
13026 ((equal pn "CATEGORY")
13027 (setq gv '(get-text-property (point) 'org-category)))
13028 ((equal pn "TODO")
13029 (setq gv 'todo))
13031 (setq gv `(org-cached-entry-get nil ,pn))))
13032 (if re-p
13033 (if (eq po 'org<>)
13034 `(not (string-match ,pv (or ,gv "")))
13035 `(string-match ,pv (or ,gv "")))
13036 (if str-p
13037 `(,po (or ,gv "") ,pv)
13038 `(,po (string-to-number (or ,gv ""))
13039 ,(string-to-number pv) ))))
13040 (t `(member ,tag tags-list)))
13041 mm (if minus (list 'not mm) mm)
13042 term rest)
13043 (push mm tagsmatcher))
13044 (push (if (> (length tagsmatcher) 1)
13045 (cons 'and tagsmatcher)
13046 (car tagsmatcher))
13047 orlist)
13048 (setq tagsmatcher nil))
13049 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13050 (setq tagsmatcher
13051 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13052 ;; Make the todo matcher
13053 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13054 (setq todomatcher t)
13055 (setq orterms (org-split-string todomatch "|") orlist nil)
13056 (while (setq term (pop orterms))
13057 (while (string-match re term)
13058 (setq minus (and (match-end 1)
13059 (equal (match-string 1 term) "-"))
13060 kwd (match-string 2 term)
13061 re-p (equal (string-to-char kwd) ?{)
13062 term (substring term (match-end 0))
13063 mm (if re-p
13064 `(string-match ,(substring kwd 1 -1) todo)
13065 (list 'equal 'todo kwd))
13066 mm (if minus (list 'not mm) mm))
13067 (push mm todomatcher))
13068 (push (if (> (length todomatcher) 1)
13069 (cons 'and todomatcher)
13070 (car todomatcher))
13071 orlist)
13072 (setq todomatcher nil))
13073 (setq todomatcher (if (> (length orlist) 1)
13074 (cons 'or orlist) (car orlist))))
13076 ;; Return the string and lisp forms of the matcher
13077 (setq matcher (if todomatcher
13078 (list 'and tagsmatcher todomatcher)
13079 tagsmatcher))
13080 (cons match0 matcher)))
13082 (defun org-op-to-function (op &optional stringp)
13083 "Turn an operator into the appropriate function."
13084 (setq op
13085 (cond
13086 ((equal op "<" ) '(< string< org-time<))
13087 ((equal op ">" ) '(> org-string> org-time>))
13088 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13089 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13090 ((member op '("=" "==")) '(= string= org-time=))
13091 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13092 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13094 (defun org<> (a b) (not (= a b)))
13095 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13096 (defun org-string>= (a b) (not (string< a b)))
13097 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13098 (defun org-string<> (a b) (not (string= a b)))
13099 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13100 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13101 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13102 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13103 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13104 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13105 (defun org-2ft (s)
13106 "Convert S to a floating point time.
13107 If S is already a number, just return it. If it is a string, parse
13108 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13109 (cond
13110 ((numberp s) s)
13111 ((stringp s)
13112 (condition-case nil
13113 (float-time (apply 'encode-time (org-parse-time-string s)))
13114 (error 0.)))
13115 (t 0.)))
13117 (defun org-time-today ()
13118 "Time in seconds today at 0:00.
13119 Returns the float number of seconds since the beginning of the
13120 epoch to the beginning of today (00:00)."
13121 (float-time (apply 'encode-time
13122 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13124 (defun org-matcher-time (s)
13125 "Interpret a time comparison value."
13126 (save-match-data
13127 (cond
13128 ((string= s "<now>") (float-time))
13129 ((string= s "<today>") (org-time-today))
13130 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13131 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13132 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
13133 (+ (org-time-today)
13134 (* (string-to-number (match-string 1 s))
13135 (cdr (assoc (match-string 2 s)
13136 '(("d" . 86400.0) ("w" . 604800.0)
13137 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13138 (t (org-2ft s)))))
13140 (defun org-match-any-p (re list)
13141 "Does re match any element of list?"
13142 (setq list (mapcar (lambda (x) (string-match re x)) list))
13143 (delq nil list))
13145 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13146 (defvar org-tags-overlay (make-overlay 1 1))
13147 (org-detach-overlay org-tags-overlay)
13149 (defun org-get-local-tags-at (&optional pos)
13150 "Get a list of tags defined in the current headline."
13151 (org-get-tags-at pos 'local))
13153 (defun org-get-local-tags ()
13154 "Get a list of tags defined in the current headline."
13155 (org-get-tags-at nil 'local))
13157 (defun org-get-tags-at (&optional pos local)
13158 "Get a list of all headline tags applicable at POS.
13159 POS defaults to point. If tags are inherited, the list contains
13160 the targets in the same sequence as the headlines appear, i.e.
13161 the tags of the current headline come last.
13162 When LOCAL is non-nil, only return tags from the current headline,
13163 ignore inherited ones."
13164 (interactive)
13165 (if (and org-trust-scanner-tags
13166 (or (not pos) (equal pos (point)))
13167 (not local))
13168 org-scanner-tags
13169 (let (tags ltags lastpos parent)
13170 (save-excursion
13171 (save-restriction
13172 (widen)
13173 (goto-char (or pos (point)))
13174 (save-match-data
13175 (catch 'done
13176 (condition-case nil
13177 (progn
13178 (org-back-to-heading t)
13179 (while (not (equal lastpos (point)))
13180 (setq lastpos (point))
13181 (when (looking-at
13182 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13183 (setq ltags (org-split-string
13184 (org-match-string-no-properties 1) ":"))
13185 (when parent
13186 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13187 (setq tags (append
13188 (if parent
13189 (org-remove-uninherited-tags ltags)
13190 ltags)
13191 tags)))
13192 (or org-use-tag-inheritance (throw 'done t))
13193 (if local (throw 'done t))
13194 (or (org-up-heading-safe) (error nil))
13195 (setq parent t)))
13196 (error nil)))))
13197 (if local
13198 tags
13199 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13201 (defun org-add-prop-inherited (s)
13202 (add-text-properties 0 (length s) '(inherited t) s)
13205 (defun org-toggle-tag (tag &optional onoff)
13206 "Toggle the tag TAG for the current line.
13207 If ONOFF is `on' or `off', don't toggle but set to this state."
13208 (let (res current)
13209 (save-excursion
13210 (org-back-to-heading t)
13211 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13212 (point-at-eol) t)
13213 (progn
13214 (setq current (match-string 1))
13215 (replace-match ""))
13216 (setq current ""))
13217 (setq current (nreverse (org-split-string current ":")))
13218 (cond
13219 ((eq onoff 'on)
13220 (setq res t)
13221 (or (member tag current) (push tag current)))
13222 ((eq onoff 'off)
13223 (or (not (member tag current)) (setq current (delete tag current))))
13224 (t (if (member tag current)
13225 (setq current (delete tag current))
13226 (setq res t)
13227 (push tag current))))
13228 (end-of-line 1)
13229 (if current
13230 (progn
13231 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13232 (org-set-tags nil t))
13233 (delete-horizontal-space))
13234 (run-hooks 'org-after-tags-change-hook))
13235 res))
13237 (defun org-align-tags-here (to-col)
13238 ;; Assumes that this is a headline
13239 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13240 (beginning-of-line 1)
13241 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13242 (< pos (match-beginning 2)))
13243 (progn
13244 (setq tags-l (- (match-end 2) (match-beginning 2)))
13245 (goto-char (match-beginning 1))
13246 (insert " ")
13247 (delete-region (point) (1+ (match-beginning 2)))
13248 (setq ncol (max (current-column)
13249 (1+ col)
13250 (if (> to-col 0)
13251 to-col
13252 (- (abs to-col) tags-l))))
13253 (setq p (point))
13254 (insert (make-string (- ncol (current-column)) ?\ ))
13255 (setq ncol (current-column))
13256 (when indent-tabs-mode (tabify p (point-at-eol)))
13257 (org-move-to-column (min ncol col) t))
13258 (goto-char pos))))
13260 (defun org-set-tags-command (&optional arg just-align)
13261 "Call the set-tags command for the current entry."
13262 (interactive "P")
13263 (if (org-on-heading-p)
13264 (org-set-tags arg just-align)
13265 (save-excursion
13266 (org-back-to-heading t)
13267 (org-set-tags arg just-align))))
13269 (defun org-set-tags-to (data)
13270 "Set the tags of the current entry to DATA, replacing the current tags.
13271 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13272 If DATA is nil or the empty string, any tags will be removed."
13273 (interactive "sTags: ")
13274 (setq data
13275 (cond
13276 ((eq data nil) "")
13277 ((equal data "") "")
13278 ((stringp data)
13279 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13280 ":"))
13281 ((listp data)
13282 (concat ":" (mapconcat 'identity data ":") ":"))
13283 (t nil)))
13284 (when data
13285 (save-excursion
13286 (org-back-to-heading t)
13287 (when (looking-at org-complex-heading-regexp)
13288 (if (match-end 5)
13289 (progn
13290 (goto-char (match-beginning 5))
13291 (insert data)
13292 (delete-region (point) (point-at-eol))
13293 (org-set-tags nil 'align))
13294 (goto-char (point-at-eol))
13295 (insert " " data)
13296 (org-set-tags nil 'align)))
13297 (beginning-of-line 1)
13298 (if (looking-at ".*?\\([ \t]+\\)$")
13299 (delete-region (match-beginning 1) (match-end 1))))))
13301 (defun org-align-all-tags ()
13302 "Align the tags i all headings."
13303 (interactive)
13304 (save-excursion
13305 (or (ignore-errors (org-back-to-heading t))
13306 (outline-next-heading))
13307 (if (org-on-heading-p)
13308 (org-set-tags t)
13309 (message "No headings"))))
13311 (defvar org-indent-indentation-per-level)
13312 (defun org-set-tags (&optional arg just-align)
13313 "Set the tags for the current headline.
13314 With prefix ARG, realign all tags in headings in the current buffer."
13315 (interactive "P")
13316 (let* ((re org-outline-regexp-bol)
13317 (current (org-get-tags-string))
13318 (col (current-column))
13319 (org-setting-tags t)
13320 table current-tags inherited-tags ; computed below when needed
13321 tags p0 c0 c1 rpl di tc level)
13322 (if arg
13323 (save-excursion
13324 (goto-char (point-min))
13325 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13326 (while (re-search-forward re nil t)
13327 (org-set-tags nil t)
13328 (end-of-line 1)))
13329 (message "All tags realigned to column %d" org-tags-column))
13330 (if just-align
13331 (setq tags current)
13332 ;; Get a new set of tags from the user
13333 (save-excursion
13334 (setq table (append org-tag-persistent-alist
13335 (or org-tag-alist (org-get-buffer-tags))
13336 (and
13337 org-complete-tags-always-offer-all-agenda-tags
13338 (org-global-tags-completion-table
13339 (org-agenda-files))))
13340 org-last-tags-completion-table table
13341 current-tags (org-split-string current ":")
13342 inherited-tags (nreverse
13343 (nthcdr (length current-tags)
13344 (nreverse (org-get-tags-at))))
13345 tags
13346 (if (or (eq t org-use-fast-tag-selection)
13347 (and org-use-fast-tag-selection
13348 (delq nil (mapcar 'cdr table))))
13349 (org-fast-tag-selection
13350 current-tags inherited-tags table
13351 (if org-fast-tag-selection-include-todo
13352 org-todo-key-alist))
13353 (let ((org-add-colon-after-tag-completion t))
13354 (org-trim
13355 (org-icompleting-read "Tags: "
13356 'org-tags-completion-function
13357 nil nil current 'org-tags-history))))))
13358 (while (string-match "[-+&]+" tags)
13359 ;; No boolean logic, just a list
13360 (setq tags (replace-match ":" t t tags))))
13362 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13364 (if org-tags-sort-function
13365 (setq tags (mapconcat 'identity
13366 (sort (org-split-string
13367 tags (org-re "[^[:alnum:]_@#%]+"))
13368 org-tags-sort-function) ":")))
13370 (if (string-match "\\`[\t ]*\\'" tags)
13371 (setq tags "")
13372 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13373 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13375 ;; Insert new tags at the correct column
13376 (beginning-of-line 1)
13377 (setq level (or (and (looking-at org-outline-regexp)
13378 (- (match-end 0) (point) 1))
13380 (cond
13381 ((and (equal current "") (equal tags "")))
13382 ((re-search-forward
13383 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13384 (point-at-eol) t)
13385 (if (equal tags "")
13386 (setq rpl "")
13387 (goto-char (match-beginning 0))
13388 (setq c0 (current-column)
13389 ;; compute offset for the case of org-indent-mode active
13390 di (if org-indent-mode
13391 (* (1- org-indent-indentation-per-level) (1- level))
13393 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13394 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13395 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13396 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13397 (replace-match rpl t t)
13398 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13399 tags)
13400 (t (error "Tags alignment failed")))
13401 (org-move-to-column col)
13402 (unless just-align
13403 (run-hooks 'org-after-tags-change-hook)))))
13405 (defun org-change-tag-in-region (beg end tag off)
13406 "Add or remove TAG for each entry in the region.
13407 This works in the agenda, and also in an org-mode buffer."
13408 (interactive
13409 (list (region-beginning) (region-end)
13410 (let ((org-last-tags-completion-table
13411 (if (eq major-mode 'org-mode)
13412 (org-get-buffer-tags)
13413 (org-global-tags-completion-table))))
13414 (org-icompleting-read
13415 "Tag: " 'org-tags-completion-function nil nil nil
13416 'org-tags-history))
13417 (progn
13418 (message "[s]et or [r]emove? ")
13419 (equal (read-char-exclusive) ?r))))
13420 (if (fboundp 'deactivate-mark) (deactivate-mark))
13421 (let ((agendap (equal major-mode 'org-agenda-mode))
13422 l1 l2 m buf pos newhead (cnt 0))
13423 (goto-char end)
13424 (setq l2 (1- (org-current-line)))
13425 (goto-char beg)
13426 (setq l1 (org-current-line))
13427 (loop for l from l1 to l2 do
13428 (org-goto-line l)
13429 (setq m (get-text-property (point) 'org-hd-marker))
13430 (when (or (and (eq major-mode 'org-mode) (org-on-heading-p))
13431 (and agendap m))
13432 (setq buf (if agendap (marker-buffer m) (current-buffer))
13433 pos (if agendap m (point)))
13434 (with-current-buffer buf
13435 (save-excursion
13436 (save-restriction
13437 (goto-char pos)
13438 (setq cnt (1+ cnt))
13439 (org-toggle-tag tag (if off 'off 'on))
13440 (setq newhead (org-get-heading)))))
13441 (and agendap (org-agenda-change-all-lines newhead m))))
13442 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13444 (defun org-tags-completion-function (string predicate &optional flag)
13445 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13446 (confirm (lambda (x) (stringp (car x)))))
13447 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13448 (setq s1 (match-string 1 string)
13449 s2 (match-string 2 string))
13450 (setq s1 "" s2 string))
13451 (cond
13452 ((eq flag nil)
13453 ;; try completion
13454 (setq rtn (try-completion s2 ctable confirm))
13455 (if (stringp rtn)
13456 (setq rtn
13457 (concat s1 s2 (substring rtn (length s2))
13458 (if (and org-add-colon-after-tag-completion
13459 (assoc rtn ctable))
13460 ":" ""))))
13461 rtn)
13462 ((eq flag t)
13463 ;; all-completions
13464 (all-completions s2 ctable confirm)
13466 ((eq flag 'lambda)
13467 ;; exact match?
13468 (assoc s2 ctable)))
13471 (defun org-fast-tag-insert (kwd tags face &optional end)
13472 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13473 (insert (format "%-12s" (concat kwd ":"))
13474 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13475 (or end "")))
13477 (defun org-fast-tag-show-exit (flag)
13478 (save-excursion
13479 (org-goto-line 3)
13480 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13481 (replace-match ""))
13482 (when flag
13483 (end-of-line 1)
13484 (org-move-to-column (- (window-width) 19) t)
13485 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13487 (defun org-set-current-tags-overlay (current prefix)
13488 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13489 (if (featurep 'xemacs)
13490 (org-overlay-display org-tags-overlay (concat prefix s)
13491 'secondary-selection)
13492 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13493 (org-overlay-display org-tags-overlay (concat prefix s)))))
13495 (defvar org-last-tag-selection-key nil)
13496 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13497 "Fast tag selection with single keys.
13498 CURRENT is the current list of tags in the headline, INHERITED is the
13499 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13500 possibly with grouping information. TODO-TABLE is a similar table with
13501 TODO keywords, should these have keys assigned to them.
13502 If the keys are nil, a-z are automatically assigned.
13503 Returns the new tags string, or nil to not change the current settings."
13504 (let* ((fulltable (append table todo-table))
13505 (maxlen (apply 'max (mapcar
13506 (lambda (x)
13507 (if (stringp (car x)) (string-width (car x)) 0))
13508 fulltable)))
13509 (buf (current-buffer))
13510 (expert (eq org-fast-tag-selection-single-key 'expert))
13511 (buffer-tags nil)
13512 (fwidth (+ maxlen 3 1 3))
13513 (ncol (/ (- (window-width) 4) fwidth))
13514 (i-face 'org-done)
13515 (c-face 'org-todo)
13516 tg cnt e c char c1 c2 ntable tbl rtn
13517 ov-start ov-end ov-prefix
13518 (exit-after-next org-fast-tag-selection-single-key)
13519 (done-keywords org-done-keywords)
13520 groups ingroup)
13521 (save-excursion
13522 (beginning-of-line 1)
13523 (if (looking-at
13524 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13525 (setq ov-start (match-beginning 1)
13526 ov-end (match-end 1)
13527 ov-prefix "")
13528 (setq ov-start (1- (point-at-eol))
13529 ov-end (1+ ov-start))
13530 (skip-chars-forward "^\n\r")
13531 (setq ov-prefix
13532 (concat
13533 (buffer-substring (1- (point)) (point))
13534 (if (> (current-column) org-tags-column)
13536 (make-string (- org-tags-column (current-column)) ?\ ))))))
13537 (move-overlay org-tags-overlay ov-start ov-end)
13538 (save-window-excursion
13539 (if expert
13540 (set-buffer (get-buffer-create " *Org tags*"))
13541 (delete-other-windows)
13542 (split-window-vertically)
13543 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13544 (erase-buffer)
13545 (org-set-local 'org-done-keywords done-keywords)
13546 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13547 (org-fast-tag-insert "Current" current c-face "\n\n")
13548 (org-fast-tag-show-exit exit-after-next)
13549 (org-set-current-tags-overlay current ov-prefix)
13550 (setq tbl fulltable char ?a cnt 0)
13551 (while (setq e (pop tbl))
13552 (cond
13553 ((equal (car e) :startgroup)
13554 (push '() groups) (setq ingroup t)
13555 (when (not (= cnt 0))
13556 (setq cnt 0)
13557 (insert "\n"))
13558 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13559 ((equal (car e) :endgroup)
13560 (setq ingroup nil cnt 0)
13561 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13562 ((equal e '(:newline))
13563 (when (not (= cnt 0))
13564 (setq cnt 0)
13565 (insert "\n")
13566 (setq e (car tbl))
13567 (while (equal (car tbl) '(:newline))
13568 (insert "\n")
13569 (setq tbl (cdr tbl)))))
13571 (setq tg (copy-sequence (car e)) c2 nil)
13572 (if (cdr e)
13573 (setq c (cdr e))
13574 ;; automatically assign a character.
13575 (setq c1 (string-to-char
13576 (downcase (substring
13577 tg (if (= (string-to-char tg) ?@) 1 0)))))
13578 (if (or (rassoc c1 ntable) (rassoc c1 table))
13579 (while (or (rassoc char ntable) (rassoc char table))
13580 (setq char (1+ char)))
13581 (setq c2 c1))
13582 (setq c (or c2 char)))
13583 (if ingroup (push tg (car groups)))
13584 (setq tg (org-add-props tg nil 'face
13585 (cond
13586 ((not (assoc tg table))
13587 (org-get-todo-face tg))
13588 ((member tg current) c-face)
13589 ((member tg inherited) i-face)
13590 (t nil))))
13591 (if (and (= cnt 0) (not ingroup)) (insert " "))
13592 (insert "[" c "] " tg (make-string
13593 (- fwidth 4 (length tg)) ?\ ))
13594 (push (cons tg c) ntable)
13595 (when (= (setq cnt (1+ cnt)) ncol)
13596 (insert "\n")
13597 (if ingroup (insert " "))
13598 (setq cnt 0)))))
13599 (setq ntable (nreverse ntable))
13600 (insert "\n")
13601 (goto-char (point-min))
13602 (if (not expert) (org-fit-window-to-buffer))
13603 (setq rtn
13604 (catch 'exit
13605 (while t
13606 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13607 (if (not groups) "no " "")
13608 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13609 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13610 (setq org-last-tag-selection-key c)
13611 (cond
13612 ((= c ?\r) (throw 'exit t))
13613 ((= c ?!)
13614 (setq groups (not groups))
13615 (goto-char (point-min))
13616 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13617 ((= c ?\C-c)
13618 (if (not expert)
13619 (org-fast-tag-show-exit
13620 (setq exit-after-next (not exit-after-next)))
13621 (setq expert nil)
13622 (delete-other-windows)
13623 (set-window-buffer (split-window-vertically) " *Org tags*")
13624 (org-switch-to-buffer-other-window " *Org tags*")
13625 (org-fit-window-to-buffer)))
13626 ((or (= c ?\C-g)
13627 (and (= c ?q) (not (rassoc c ntable))))
13628 (org-detach-overlay org-tags-overlay)
13629 (setq quit-flag t))
13630 ((= c ?\ )
13631 (setq current nil)
13632 (if exit-after-next (setq exit-after-next 'now)))
13633 ((= c ?\t)
13634 (condition-case nil
13635 (setq tg (org-icompleting-read
13636 "Tag: "
13637 (or buffer-tags
13638 (with-current-buffer buf
13639 (org-get-buffer-tags)))))
13640 (quit (setq tg "")))
13641 (when (string-match "\\S-" tg)
13642 (add-to-list 'buffer-tags (list tg))
13643 (if (member tg current)
13644 (setq current (delete tg current))
13645 (push tg current)))
13646 (if exit-after-next (setq exit-after-next 'now)))
13647 ((setq e (rassoc c todo-table) tg (car e))
13648 (with-current-buffer buf
13649 (save-excursion (org-todo tg)))
13650 (if exit-after-next (setq exit-after-next 'now)))
13651 ((setq e (rassoc c ntable) tg (car e))
13652 (if (member tg current)
13653 (setq current (delete tg current))
13654 (loop for g in groups do
13655 (if (member tg g)
13656 (mapc (lambda (x)
13657 (setq current (delete x current)))
13658 g)))
13659 (push tg current))
13660 (if exit-after-next (setq exit-after-next 'now))))
13662 ;; Create a sorted list
13663 (setq current
13664 (sort current
13665 (lambda (a b)
13666 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13667 (if (eq exit-after-next 'now) (throw 'exit t))
13668 (goto-char (point-min))
13669 (beginning-of-line 2)
13670 (delete-region (point) (point-at-eol))
13671 (org-fast-tag-insert "Current" current c-face)
13672 (org-set-current-tags-overlay current ov-prefix)
13673 (while (re-search-forward
13674 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13675 (setq tg (match-string 1))
13676 (add-text-properties
13677 (match-beginning 1) (match-end 1)
13678 (list 'face
13679 (cond
13680 ((member tg current) c-face)
13681 ((member tg inherited) i-face)
13682 (t (get-text-property (match-beginning 1) 'face))))))
13683 (goto-char (point-min)))))
13684 (org-detach-overlay org-tags-overlay)
13685 (if rtn
13686 (mapconcat 'identity current ":")
13687 nil))))
13689 (defun org-get-tags-string ()
13690 "Get the TAGS string in the current headline."
13691 (unless (org-on-heading-p t)
13692 (error "Not on a heading"))
13693 (save-excursion
13694 (beginning-of-line 1)
13695 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13696 (org-match-string-no-properties 1)
13697 "")))
13699 (defun org-get-tags ()
13700 "Get the list of tags specified in the current headline."
13701 (org-split-string (org-get-tags-string) ":"))
13703 (defun org-get-buffer-tags ()
13704 "Get a table of all tags used in the buffer, for completion."
13705 (let (tags)
13706 (save-excursion
13707 (goto-char (point-min))
13708 (while (re-search-forward
13709 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13710 (when (equal (char-after (point-at-bol 0)) ?*)
13711 (mapc (lambda (x) (add-to-list 'tags x))
13712 (org-split-string (org-match-string-no-properties 1) ":")))))
13713 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13714 (mapcar 'list tags)))
13716 ;;;; The mapping API
13718 ;;;###autoload
13719 (defun org-map-entries (func &optional match scope &rest skip)
13720 "Call FUNC at each headline selected by MATCH in SCOPE.
13722 FUNC is a function or a lisp form. The function will be called without
13723 arguments, with the cursor positioned at the beginning of the headline.
13724 The return values of all calls to the function will be collected and
13725 returned as a list.
13727 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13728 does not need to preserve point. After evaluation, the cursor will be
13729 moved to the end of the line (presumably of the headline of the
13730 processed entry) and search continues from there. Under some
13731 circumstances, this may not produce the wanted results. For example,
13732 if you have removed (e.g. archived) the current (sub)tree it could
13733 mean that the next entry will be skipped entirely. In such cases, you
13734 can specify the position from where search should continue by making
13735 FUNC set the variable `org-map-continue-from' to the desired buffer
13736 position.
13738 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13739 Only headlines that are matched by this query will be considered during
13740 the iteration. When MATCH is nil or t, all headlines will be
13741 visited by the iteration.
13743 SCOPE determines the scope of this command. It can be any of:
13745 nil The current buffer, respecting the restriction if any
13746 tree The subtree started with the entry at point
13747 region The entries within the active region, if any
13748 region-start-level
13749 The entries within the active region, but only those at
13750 the same level than the first one.
13751 file The current buffer, without restriction
13752 file-with-archives
13753 The current buffer, and any archives associated with it
13754 agenda All agenda files
13755 agenda-with-archives
13756 All agenda files with any archive files associated with them
13757 \(file1 file2 ...)
13758 If this is a list, all files in the list will be scanned
13760 The remaining args are treated as settings for the skipping facilities of
13761 the scanner. The following items can be given here:
13763 archive skip trees with the archive tag.
13764 comment skip trees with the COMMENT keyword
13765 function or Emacs Lisp form:
13766 will be used as value for `org-agenda-skip-function', so whenever
13767 the function returns t, FUNC will not be called for that
13768 entry and search will continue from the point where the
13769 function leaves it.
13771 If your function needs to retrieve the tags including inherited tags
13772 at the *current* entry, you can use the value of the variable
13773 `org-scanner-tags' which will be much faster than getting the value
13774 with `org-get-tags-at'. If your function gets properties with
13775 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13776 to t around the call to `org-entry-properties' to get the same speedup.
13777 Note that if your function moves around to retrieve tags and properties at
13778 a *different* entry, you cannot use these techniques."
13779 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
13780 (not (org-region-active-p)))
13781 (let* ((org-agenda-archives-mode nil) ; just to make sure
13782 (org-agenda-skip-archived-trees (memq 'archive skip))
13783 (org-agenda-skip-comment-trees (memq 'comment skip))
13784 (org-agenda-skip-function
13785 (car (org-delete-all '(comment archive) skip)))
13786 (org-tags-match-list-sublevels t)
13787 (start-level (eq scope 'region-start-level))
13788 matcher file res
13789 org-todo-keywords-for-agenda
13790 org-done-keywords-for-agenda
13791 org-todo-keyword-alist-for-agenda
13792 org-drawers-for-agenda
13793 org-tag-alist-for-agenda)
13795 (cond
13796 ((eq match t) (setq matcher t))
13797 ((eq match nil) (setq matcher t))
13798 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13800 (save-excursion
13801 (save-restriction
13802 (cond ((eq scope 'tree)
13803 (org-back-to-heading t)
13804 (org-narrow-to-subtree)
13805 (setq scope nil))
13806 ((and (or (eq scope 'region) (eq scope 'region-start-level))
13807 (org-region-active-p))
13808 ;; If needed, set start-level to a string like "2"
13809 (when start-level
13810 (save-excursion
13811 (goto-char (region-beginning))
13812 (unless (org-at-heading-p) (outline-next-heading))
13813 (setq start-level (org-current-level))))
13814 (narrow-to-region (region-beginning)
13815 (save-excursion
13816 (goto-char (region-end))
13817 (unless (and (bolp) (org-at-heading-p))
13818 (outline-next-heading))
13819 (point)))
13820 (setq scope nil)))
13822 (if (not scope)
13823 (progn
13824 (org-prepare-agenda-buffers
13825 (list (buffer-file-name (current-buffer))))
13826 (setq res (org-scan-tags func matcher nil start-level)))
13827 ;; Get the right scope
13828 (cond
13829 ((and scope (listp scope) (symbolp (car scope)))
13830 (setq scope (eval scope)))
13831 ((eq scope 'agenda)
13832 (setq scope (org-agenda-files t)))
13833 ((eq scope 'agenda-with-archives)
13834 (setq scope (org-agenda-files t))
13835 (setq scope (org-add-archive-files scope)))
13836 ((eq scope 'file)
13837 (setq scope (list (buffer-file-name))))
13838 ((eq scope 'file-with-archives)
13839 (setq scope (org-add-archive-files (list (buffer-file-name))))))
13840 (org-prepare-agenda-buffers scope)
13841 (while (setq file (pop scope))
13842 (with-current-buffer (org-find-base-buffer-visiting file)
13843 (save-excursion
13844 (save-restriction
13845 (widen)
13846 (goto-char (point-min))
13847 (setq res (append res (org-scan-tags func matcher))))))))))
13848 res)))
13850 ;;;; Properties
13852 ;;; Setting and retrieving properties
13854 (defconst org-special-properties
13855 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
13856 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM")
13857 "The special properties valid in Org-mode.
13859 These are properties that are not defined in the property drawer,
13860 but in some other way.")
13862 (defconst org-default-properties
13863 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
13864 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
13865 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
13866 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
13867 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
13868 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
13869 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
13870 "Some properties that are used by Org-mode for various purposes.
13871 Being in this list makes sure that they are offered for completion.")
13873 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
13874 "Regular expression matching the first line of a property drawer.")
13876 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
13877 "Regular expression matching the last line of a property drawer.")
13879 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
13880 "Regular expression matching the first line of a property drawer.")
13882 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
13883 "Regular expression matching the first line of a property drawer.")
13885 (defconst org-property-drawer-re
13886 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
13887 org-property-end-re "\\)\n?")
13888 "Matches an entire property drawer.")
13890 (defconst org-clock-drawer-re
13891 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
13892 org-property-end-re "\\)\n?")
13893 "Matches an entire clock drawer.")
13895 (defsubst org-re-property (property)
13896 "Return a regexp matching PROPERTY.
13897 Match group 1 will be set to the value "
13898 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
13900 (defun org-property-action ()
13901 "Do an action on properties."
13902 (interactive)
13903 (let (c)
13904 (org-at-property-p)
13905 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
13906 (setq c (read-char-exclusive))
13907 (cond
13908 ((equal c ?s)
13909 (call-interactively 'org-set-property))
13910 ((equal c ?d)
13911 (call-interactively 'org-delete-property))
13912 ((equal c ?D)
13913 (call-interactively 'org-delete-property-globally))
13914 ((equal c ?c)
13915 (call-interactively 'org-compute-property-at-point))
13916 (t (error "No such property action %c" c)))))
13918 (defun org-set-effort (&optional value)
13919 "Set the effort property of the current entry.
13920 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
13921 allowed value."
13922 (interactive "P")
13923 (if (equal value 0) (setq value 10))
13924 (let* ((completion-ignore-case t)
13925 (prop org-effort-property)
13926 (cur (org-entry-get nil prop))
13927 (allowed (org-property-get-allowed-values nil prop 'table))
13928 (existing (mapcar 'list (org-property-values prop)))
13930 (val (cond
13931 ((stringp value) value)
13932 ((and allowed (integerp value))
13933 (or (car (nth (1- value) allowed))
13934 (car (org-last allowed))))
13935 (allowed
13936 (message "Select 1-9,0, [RET%s]: %s"
13937 (if cur (concat "=" cur) "")
13938 (mapconcat 'car allowed " "))
13939 (setq rpl (read-char-exclusive))
13940 (if (equal rpl ?\r)
13942 (setq rpl (- rpl ?0))
13943 (if (equal rpl 0) (setq rpl 10))
13944 (if (and (> rpl 0) (<= rpl (length allowed)))
13945 (car (nth (1- rpl) allowed))
13946 (org-completing-read "Effort: " allowed nil))))
13948 (let (org-completion-use-ido org-completion-use-iswitchb)
13949 (org-completing-read
13950 (concat "Effort " (if (and cur (string-match "\\S-" cur))
13951 (concat "[" cur "]") "")
13952 ": ")
13953 existing nil nil "" nil cur))))))
13954 (unless (equal (org-entry-get nil prop) val)
13955 (org-entry-put nil prop val))
13956 (message "%s is now %s" prop val)))
13958 (defun org-at-property-p ()
13959 "Is cursor inside a property drawer?"
13960 (save-excursion
13961 (beginning-of-line 1)
13962 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
13963 (save-match-data ;; Used by calling procedures
13964 (let ((p (point))
13965 (range (unless (org-before-first-heading-p)
13966 (org-get-property-block))))
13967 (and range (<= (car range) p) (< p (cdr range))))))))
13969 (defun org-get-property-block (&optional beg end force)
13970 "Return the (beg . end) range of the body of the property drawer.
13971 BEG and END can be beginning and end of subtree, if not given
13972 they will be found.
13973 If the drawer does not exist and FORCE is non-nil, create the drawer."
13974 (catch 'exit
13975 (save-excursion
13976 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
13977 (end (or end (progn (outline-next-heading) (point)))))
13978 (goto-char beg)
13979 (if (re-search-forward org-property-start-re end t)
13980 (setq beg (1+ (match-end 0)))
13981 (if force
13982 (save-excursion
13983 (org-insert-property-drawer)
13984 (setq end (progn (outline-next-heading) (point))))
13985 (throw 'exit nil))
13986 (goto-char beg)
13987 (if (re-search-forward org-property-start-re end t)
13988 (setq beg (1+ (match-end 0)))))
13989 (if (re-search-forward org-property-end-re end t)
13990 (setq end (match-beginning 0))
13991 (or force (throw 'exit nil))
13992 (goto-char beg)
13993 (setq end beg)
13994 (org-indent-line-function)
13995 (insert ":END:\n"))
13996 (cons beg end)))))
13998 (defun org-entry-properties (&optional pom which specific)
13999 "Get all properties of the entry at point-or-marker POM.
14000 This includes the TODO keyword, the tags, time strings for deadline,
14001 scheduled, and clocking, and any additional properties defined in the
14002 entry. The return value is an alist, keys may occur multiple times
14003 if the property key was used several times.
14004 POM may also be nil, in which case the current entry is used.
14005 If WHICH is nil or `all', get all properties. If WHICH is
14006 `special' or `standard', only get that subclass. If WHICH
14007 is a string only get exactly this property. SPECIFIC can be a string, the
14008 specific property we are interested in. Specifying it can speed
14009 things up because then unnecessary parsing is avoided."
14010 (setq which (or which 'all))
14011 (org-with-point-at pom
14012 (let ((clockstr (substring org-clock-string 0 -1))
14013 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14014 (case-fold-search nil)
14015 beg end range props sum-props key key1 value string clocksum)
14016 (save-excursion
14017 (when (condition-case nil
14018 (and (eq major-mode 'org-mode) (org-back-to-heading t))
14019 (error nil))
14020 (setq beg (point))
14021 (setq sum-props (get-text-property (point) 'org-summaries))
14022 (setq clocksum (get-text-property (point) :org-clock-minutes))
14023 (outline-next-heading)
14024 (setq end (point))
14025 (when (memq which '(all special))
14026 ;; Get the special properties, like TODO and tags
14027 (goto-char beg)
14028 (when (and (or (not specific) (string= specific "TODO"))
14029 (looking-at org-todo-line-regexp) (match-end 2))
14030 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14031 (when (and (or (not specific) (string= specific "PRIORITY"))
14032 (looking-at org-priority-regexp))
14033 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14034 (when (or (not specific) (string= specific "FILE"))
14035 (push (cons "FILE" buffer-file-name) props))
14036 (when (and (or (not specific) (string= specific "TAGS"))
14037 (setq value (org-get-tags-string))
14038 (string-match "\\S-" value))
14039 (push (cons "TAGS" value) props))
14040 (when (and (or (not specific) (string= specific "ALLTAGS"))
14041 (setq value (org-get-tags-at)))
14042 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14043 ":"))
14044 props))
14045 (when (or (not specific) (string= specific "BLOCKED"))
14046 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14047 (when (or (not specific)
14048 (member specific
14049 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14050 "TIMESTAMP" "TIMESTAMP_IA")))
14051 (catch 'match
14052 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14053 (setq key (if (match-end 1)
14054 (substring (org-match-string-no-properties 1)
14055 0 -1))
14056 string (if (equal key clockstr)
14057 (org-no-properties
14058 (org-trim
14059 (buffer-substring
14060 (match-beginning 3) (goto-char
14061 (point-at-eol)))))
14062 (substring (org-match-string-no-properties 3)
14063 1 -1)))
14064 ;; Get the correct property name from the key. This is
14065 ;; necessary if the user has configured time keywords.
14066 (setq key1 (concat key ":"))
14067 (cond
14068 ((not key)
14069 (setq key
14070 (if (= (char-after (match-beginning 3)) ?\[)
14071 "TIMESTAMP_IA" "TIMESTAMP")))
14072 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14073 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14074 ((equal key1 org-closed-string) (setq key "CLOSED"))
14075 ((equal key1 org-clock-string) (setq key "CLOCK")))
14076 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14077 (progn
14078 (push (cons key string) props)
14079 ;; no need to search further if match is found
14080 (throw 'match t))
14081 (when (or (equal key "CLOCK") (not (assoc key props)))
14082 (push (cons key string) props))))))
14085 (when (memq which '(all standard))
14086 ;; Get the standard properties, like :PROP: ...
14087 (setq range (org-get-property-block beg end))
14088 (when range
14089 (goto-char (car range))
14090 (while (re-search-forward
14091 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14092 (cdr range) t)
14093 (setq key (org-match-string-no-properties 1)
14094 value (org-trim (or (org-match-string-no-properties 2) "")))
14095 (unless (member key excluded)
14096 (push (cons key (or value "")) props)))))
14097 (if clocksum
14098 (push (cons "CLOCKSUM"
14099 (org-columns-number-to-string (/ (float clocksum) 60.)
14100 'add_times))
14101 props))
14102 (unless (assoc "CATEGORY" props)
14103 (push (cons "CATEGORY" (org-get-category)) props))
14104 (append sum-props (nreverse props)))))))
14106 (defun org-entry-get (pom property &optional inherit literal-nil)
14107 "Get value of PROPERTY for entry at point-or-marker POM.
14108 If INHERIT is non-nil and the entry does not have the property,
14109 then also check higher levels of the hierarchy.
14110 If INHERIT is the symbol `selective', use inheritance only if the setting
14111 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14112 If the property is present but empty, the return value is the empty string.
14113 If the property is not present at all, nil is returned.
14115 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14116 do not interpret it as the list atom nil. This is used for inheritance
14117 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14118 (org-with-point-at pom
14119 (if (and inherit (if (eq inherit 'selective)
14120 (org-property-inherit-p property)
14122 (org-entry-get-with-inheritance property literal-nil)
14123 (if (member property org-special-properties)
14124 ;; We need a special property. Use `org-entry-properties' to
14125 ;; retrieve it, but specify the wanted property
14126 (cdr (assoc property (org-entry-properties nil 'special property)))
14127 (let ((range (unless (org-before-first-heading-p)
14128 (org-get-property-block))))
14129 (when (and range (goto-char (car range)))
14130 ((lambda (val) (when val (if literal-nil val (org-not-nil val))))
14131 (cond
14132 ((re-search-forward
14133 (org-re-property property) (cdr range) t)
14134 (if (match-end 1) (org-match-string-no-properties 1) ""))
14135 ((re-search-forward
14136 (org-re-property (concat property "+")) (cdr range) t)
14137 (cdr (assoc
14138 property
14139 (org-update-property-plist
14140 (concat property "+")
14141 (if (match-end 1) (org-match-string-no-properties 1) "")
14142 (list (or (assoc property org-file-properties)
14143 (assoc property org-global-properties)
14144 (assoc property org-global-properties-fixed)
14145 ))))))))))))))
14147 (defun org-property-or-variable-value (var &optional inherit)
14148 "Check if there is a property fixing the value of VAR.
14149 If yes, return this value. If not, return the current value of the variable."
14150 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14151 (if (and prop (stringp prop) (string-match "\\S-" prop))
14152 (read prop)
14153 (symbol-value var))))
14155 (defun org-entry-delete (pom property)
14156 "Delete the property PROPERTY from entry at point-or-marker POM."
14157 (org-with-point-at pom
14158 (if (member property org-special-properties)
14159 nil ; cannot delete these properties.
14160 (let ((range (org-get-property-block)))
14161 (if (and range
14162 (goto-char (car range))
14163 (re-search-forward
14164 (org-re-property property)
14165 (cdr range) t))
14166 (progn
14167 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14169 nil)))))
14171 ;; Multi-values properties are properties that contain multiple values
14172 ;; These values are assumed to be single words, separated by whitespace.
14173 (defun org-entry-add-to-multivalued-property (pom property value)
14174 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14175 (let* ((old (org-entry-get pom property))
14176 (values (and old (org-split-string old "[ \t]"))))
14177 (setq value (org-entry-protect-space value))
14178 (unless (member value values)
14179 (setq values (cons value values))
14180 (org-entry-put pom property
14181 (mapconcat 'identity values " ")))))
14183 (defun org-entry-remove-from-multivalued-property (pom property value)
14184 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14185 (let* ((old (org-entry-get pom property))
14186 (values (and old (org-split-string old "[ \t]"))))
14187 (setq value (org-entry-protect-space value))
14188 (when (member value values)
14189 (setq values (delete value values))
14190 (org-entry-put pom property
14191 (mapconcat 'identity values " ")))))
14193 (defun org-entry-member-in-multivalued-property (pom property value)
14194 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14195 (let* ((old (org-entry-get pom property))
14196 (values (and old (org-split-string old "[ \t]"))))
14197 (setq value (org-entry-protect-space value))
14198 (member value values)))
14200 (defun org-entry-get-multivalued-property (pom property)
14201 "Return a list of values in a multivalued property."
14202 (let* ((value (org-entry-get pom property))
14203 (values (and value (org-split-string value "[ \t]"))))
14204 (mapcar 'org-entry-restore-space values)))
14206 (defun org-entry-put-multivalued-property (pom property &rest values)
14207 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14208 VALUES should be a list of strings. Spaces will be protected."
14209 (org-entry-put pom property
14210 (mapconcat 'org-entry-protect-space values " "))
14211 (let* ((value (org-entry-get pom property))
14212 (values (and value (org-split-string value "[ \t]"))))
14213 (mapcar 'org-entry-restore-space values)))
14215 (defun org-entry-protect-space (s)
14216 "Protect spaces and newline in string S."
14217 (while (string-match " " s)
14218 (setq s (replace-match "%20" t t s)))
14219 (while (string-match "\n" s)
14220 (setq s (replace-match "%0A" t t s)))
14223 (defun org-entry-restore-space (s)
14224 "Restore spaces and newline in string S."
14225 (while (string-match "%20" s)
14226 (setq s (replace-match " " t t s)))
14227 (while (string-match "%0A" s)
14228 (setq s (replace-match "\n" t t s)))
14231 (defvar org-entry-property-inherited-from (make-marker)
14232 "Marker pointing to the entry from where a property was inherited.
14233 Each call to `org-entry-get-with-inheritance' will set this marker to the
14234 location of the entry where the inheritance search matched. If there was
14235 no match, the marker will point nowhere.
14236 Note that also `org-entry-get' calls this function, if the INHERIT flag
14237 is set.")
14239 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14240 "Get entry property, and search higher levels if not present.
14241 The search will stop at the first ancestor which has the property defined.
14242 If the value found is \"nil\", return nil to show that the property
14243 should be considered as undefined (this is the meaning of nil here).
14244 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14245 (move-marker org-entry-property-inherited-from nil)
14246 (let (tmp)
14247 (unless (org-before-first-heading-p)
14248 (save-excursion
14249 (save-restriction
14250 (widen)
14251 (catch 'ex
14252 (while t
14253 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14254 (org-back-to-heading t)
14255 (move-marker org-entry-property-inherited-from (point))
14256 (throw 'ex tmp))
14257 (or (org-up-heading-safe) (throw 'ex nil)))))))
14258 (setq tmp (or tmp
14259 (cdr (assoc property org-file-properties))
14260 (cdr (assoc property org-global-properties))
14261 (cdr (assoc property org-global-properties-fixed))))
14262 (if literal-nil tmp (org-not-nil tmp))))
14264 (defvar org-property-changed-functions nil
14265 "Hook called when the value of a property has changed.
14266 Each hook function should accept two arguments, the name of the property
14267 and the new value.")
14269 (defun org-entry-put (pom property value)
14270 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14271 (org-with-point-at pom
14272 (org-back-to-heading t)
14273 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14274 range)
14275 (cond
14276 ((equal property "TODO")
14277 (when (and (stringp value) (string-match "\\S-" value)
14278 (not (member value org-todo-keywords-1)))
14279 (error "\"%s\" is not a valid TODO state" value))
14280 (if (or (not value)
14281 (not (string-match "\\S-" value)))
14282 (setq value 'none))
14283 (org-todo value)
14284 (org-set-tags nil 'align))
14285 ((equal property "PRIORITY")
14286 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14287 (string-to-char value) ?\ ))
14288 (org-set-tags nil 'align))
14289 ((equal property "SCHEDULED")
14290 (if (re-search-forward org-scheduled-time-regexp end t)
14291 (cond
14292 ((eq value 'earlier) (org-timestamp-change -1 'day))
14293 ((eq value 'later) (org-timestamp-change 1 'day))
14294 (t (call-interactively 'org-schedule)))
14295 (call-interactively 'org-schedule)))
14296 ((equal property "DEADLINE")
14297 (if (re-search-forward org-deadline-time-regexp end t)
14298 (cond
14299 ((eq value 'earlier) (org-timestamp-change -1 'day))
14300 ((eq value 'later) (org-timestamp-change 1 'day))
14301 (t (call-interactively 'org-deadline)))
14302 (call-interactively 'org-deadline)))
14303 ((member property org-special-properties)
14304 (error "The %s property can not yet be set with `org-entry-put'"
14305 property))
14306 (t ; a non-special property
14307 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14308 (setq range (org-get-property-block beg end 'force))
14309 (goto-char (car range))
14310 (if (re-search-forward
14311 (org-re-property property) (cdr range) t)
14312 (progn
14313 (delete-region (match-beginning 0) (match-end 0))
14314 (goto-char (match-beginning 0)))
14315 (goto-char (cdr range))
14316 (insert "\n")
14317 (backward-char 1)
14318 (org-indent-line-function))
14319 (insert ":" property ":")
14320 (and value (insert " " value))
14321 (org-indent-line-function)))))
14322 (run-hook-with-args 'org-property-changed-functions property value)))
14324 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14325 "Get all property keys in the current buffer.
14326 With INCLUDE-SPECIALS, also list the special properties that reflect things
14327 like tags and TODO state.
14328 With INCLUDE-DEFAULTS, also include properties that has special meaning
14329 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14330 and others.
14331 With INCLUDE-COLUMNS, also include property names given in COLUMN
14332 formats in the current buffer."
14333 (let (rtn range cfmt s p)
14334 (save-excursion
14335 (save-restriction
14336 (widen)
14337 (goto-char (point-min))
14338 (while (re-search-forward org-property-start-re nil t)
14339 (setq range (org-get-property-block))
14340 (goto-char (car range))
14341 (while (re-search-forward
14342 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14343 (cdr range) t)
14344 (add-to-list 'rtn (org-match-string-no-properties 1)))
14345 (outline-next-heading))))
14347 (when include-specials
14348 (setq rtn (append org-special-properties rtn)))
14350 (when include-defaults
14351 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14352 (add-to-list 'rtn org-effort-property))
14354 (when include-columns
14355 (save-excursion
14356 (save-restriction
14357 (widen)
14358 (goto-char (point-min))
14359 (while (re-search-forward
14360 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14361 nil t)
14362 (setq cfmt (match-string 2) s 0)
14363 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14364 cfmt s)
14365 (setq s (match-end 0)
14366 p (match-string 1 cfmt))
14367 (unless (or (equal p "ITEM")
14368 (member p org-special-properties))
14369 (add-to-list 'rtn (match-string 1 cfmt))))))))
14371 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14373 (defun org-property-values (key)
14374 "Return a list of all values of property KEY in the current buffer."
14375 (save-excursion
14376 (save-restriction
14377 (widen)
14378 (goto-char (point-min))
14379 (let ((re (org-re-property key))
14380 values)
14381 (while (re-search-forward re nil t)
14382 (add-to-list 'values (org-trim (match-string 1))))
14383 (delete "" values)))))
14385 (defun org-insert-property-drawer ()
14386 "Insert a property drawer into the current entry."
14387 (interactive)
14388 (org-back-to-heading t)
14389 (looking-at org-outline-regexp)
14390 (let ((indent (if org-adapt-indentation
14391 (- (match-end 0)(match-beginning 0))
14393 (beg (point))
14394 (re (concat "^[ \t]*" org-keyword-time-regexp))
14395 end hiddenp)
14396 (outline-next-heading)
14397 (setq end (point))
14398 (goto-char beg)
14399 (while (re-search-forward re end t))
14400 (setq hiddenp (outline-invisible-p))
14401 (end-of-line 1)
14402 (and (equal (char-after) ?\n) (forward-char 1))
14403 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14404 (if (member (match-string 1) '("CLOCK:" ":END:"))
14405 ;; just skip this line
14406 (beginning-of-line 2)
14407 ;; Drawer start, find the end
14408 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14409 (beginning-of-line 1)))
14410 (org-skip-over-state-notes)
14411 (skip-chars-backward " \t\n\r")
14412 (if (eq (char-before) ?*) (forward-char 1))
14413 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14414 (beginning-of-line 0)
14415 (org-indent-to-column indent)
14416 (beginning-of-line 2)
14417 (org-indent-to-column indent)
14418 (beginning-of-line 0)
14419 (if hiddenp
14420 (save-excursion
14421 (org-back-to-heading t)
14422 (hide-entry))
14423 (org-flag-drawer t))))
14425 (defvar org-property-set-functions-alist nil
14426 "Property set function alist.
14427 Each entry should have the following format:
14429 (PROPERTY . READ-FUNCTION)
14431 The read function will be called with the same argument as
14432 `org-completing-read'.")
14434 (defun org-set-property-function (property)
14435 "Get the function that should be used to set PROPERTY.
14436 This is computed according to `org-property-set-functions-alist'."
14437 (or (cdr (assoc property org-property-set-functions-alist))
14438 'org-completing-read))
14440 (defun org-read-property-value (property)
14441 "Read PROPERTY value from user."
14442 (let* ((completion-ignore-case t)
14443 (allowed (org-property-get-allowed-values nil property 'table))
14444 (cur (org-entry-get nil property))
14445 (prompt (concat property " value"
14446 (if (and cur (string-match "\\S-" cur))
14447 (concat " [" cur "]") "") ": "))
14448 (set-function (org-set-property-function property))
14449 (val (if allowed
14450 (funcall set-function prompt allowed nil
14451 (not (get-text-property 0 'org-unrestricted
14452 (caar allowed))))
14453 (let (org-completion-use-ido org-completion-use-iswitchb)
14454 (funcall set-function prompt
14455 (mapcar 'list (org-property-values property))
14456 nil nil "" nil cur)))))
14457 (if (equal val "")
14459 val)))
14461 (defvar org-last-set-property nil)
14462 (defun org-read-property-name ()
14463 "Read a property name."
14464 (let* ((completion-ignore-case t)
14465 (keys (org-buffer-property-keys nil t t))
14466 (default-prop (or (save-excursion
14467 (save-match-data
14468 (beginning-of-line)
14469 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14470 (null (string= (match-string 1) "END"))
14471 (match-string 1))))
14472 org-last-set-property))
14473 (property (org-icompleting-read
14474 (concat "Property"
14475 (if default-prop (concat " [" default-prop "]") "")
14476 ": ")
14477 (mapcar 'list keys)
14478 nil nil nil nil
14479 default-prop
14481 (if (member property keys)
14482 property
14483 (or (cdr (assoc (downcase property)
14484 (mapcar (lambda (x) (cons (downcase x) x))
14485 keys)))
14486 property))))
14488 (defun org-set-property (property value)
14489 "In the current entry, set PROPERTY to VALUE.
14490 When called interactively, this will prompt for a property name, offering
14491 completion on existing and default properties. And then it will prompt
14492 for a value, offering completion either on allowed values (via an inherited
14493 xxx_ALL property) or on existing values in other instances of this property
14494 in the current file."
14495 (interactive (list nil nil))
14496 (let* ((property (or property (org-read-property-name)))
14497 (value (or value (org-read-property-value property)))
14498 (fn (assoc property org-properties-postprocess-alist)))
14499 (setq org-last-set-property property)
14500 ;; Possibly postprocess the inserted value:
14501 (when fn (setq value (funcall (cadr fn) value)))
14502 (unless (equal (org-entry-get nil property) value)
14503 (org-entry-put nil property value))))
14505 (defun org-delete-property (property)
14506 "In the current entry, delete PROPERTY."
14507 (interactive
14508 (let* ((completion-ignore-case t)
14509 (prop (org-icompleting-read "Property: "
14510 (org-entry-properties nil 'standard))))
14511 (list prop)))
14512 (message "Property %s %s" property
14513 (if (org-entry-delete nil property)
14514 "deleted"
14515 "was not present in the entry")))
14517 (defun org-delete-property-globally (property)
14518 "Remove PROPERTY globally, from all entries."
14519 (interactive
14520 (let* ((completion-ignore-case t)
14521 (prop (org-icompleting-read
14522 "Globally remove property: "
14523 (mapcar 'list (org-buffer-property-keys)))))
14524 (list prop)))
14525 (save-excursion
14526 (save-restriction
14527 (widen)
14528 (goto-char (point-min))
14529 (let ((cnt 0))
14530 (while (re-search-forward
14531 (org-re-property property)
14532 nil t)
14533 (setq cnt (1+ cnt))
14534 (replace-match ""))
14535 (message "Property \"%s\" removed from %d entries" property cnt)))))
14537 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14539 (defun org-compute-property-at-point ()
14540 "Compute the property at point.
14541 This looks for an enclosing column format, extracts the operator and
14542 then applies it to the property in the column format's scope."
14543 (interactive)
14544 (unless (org-at-property-p)
14545 (error "Not at a property"))
14546 (let ((prop (org-match-string-no-properties 2)))
14547 (org-columns-get-format-and-top-level)
14548 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14549 (error "No operator defined for property %s" prop))
14550 (org-columns-compute prop)))
14552 (defvar org-property-allowed-value-functions nil
14553 "Hook for functions supplying allowed values for a specific property.
14554 The functions must take a single argument, the name of the property, and
14555 return a flat list of allowed values. If \":ETC\" is one of
14556 the values, this means that these values are intended as defaults for
14557 completion, but that other values should be allowed too.
14558 The functions must return nil if they are not responsible for this
14559 property.")
14561 (defun org-property-get-allowed-values (pom property &optional table)
14562 "Get allowed values for the property PROPERTY.
14563 When TABLE is non-nil, return an alist that can directly be used for
14564 completion."
14565 (let (vals)
14566 (cond
14567 ((equal property "TODO")
14568 (setq vals (org-with-point-at pom
14569 (append org-todo-keywords-1 '("")))))
14570 ((equal property "PRIORITY")
14571 (let ((n org-lowest-priority))
14572 (while (>= n org-highest-priority)
14573 (push (char-to-string n) vals)
14574 (setq n (1- n)))))
14575 ((member property org-special-properties))
14576 ((setq vals (run-hook-with-args-until-success
14577 'org-property-allowed-value-functions property)))
14579 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14580 (when (and vals (string-match "\\S-" vals))
14581 (setq vals (car (read-from-string (concat "(" vals ")"))))
14582 (setq vals (mapcar (lambda (x)
14583 (cond ((stringp x) x)
14584 ((numberp x) (number-to-string x))
14585 ((symbolp x) (symbol-name x))
14586 (t "???")))
14587 vals)))))
14588 (when (member ":ETC" vals)
14589 (setq vals (remove ":ETC" vals))
14590 (org-add-props (car vals) '(org-unrestricted t)))
14591 (if table (mapcar 'list vals) vals)))
14593 (defun org-property-previous-allowed-value (&optional previous)
14594 "Switch to the next allowed value for this property."
14595 (interactive)
14596 (org-property-next-allowed-value t))
14598 (defun org-property-next-allowed-value (&optional previous)
14599 "Switch to the next allowed value for this property."
14600 (interactive)
14601 (unless (org-at-property-p)
14602 (error "Not at a property"))
14603 (let* ((key (match-string 2))
14604 (value (match-string 3))
14605 (allowed (or (org-property-get-allowed-values (point) key)
14606 (and (member value '("[ ]" "[-]" "[X]"))
14607 '("[ ]" "[X]"))))
14608 nval)
14609 (unless allowed
14610 (error "Allowed values for this property have not been defined"))
14611 (if previous (setq allowed (reverse allowed)))
14612 (if (member value allowed)
14613 (setq nval (car (cdr (member value allowed)))))
14614 (setq nval (or nval (car allowed)))
14615 (if (equal nval value)
14616 (error "Only one allowed value for this property"))
14617 (org-at-property-p)
14618 (replace-match (concat " :" key ": " nval) t t)
14619 (org-indent-line-function)
14620 (beginning-of-line 1)
14621 (skip-chars-forward " \t")
14622 (run-hook-with-args 'org-property-changed-functions key nval)))
14624 (defun org-find-olp (path &optional this-buffer)
14625 "Return a marker pointing to the entry at outline path OLP.
14626 If anything goes wrong, throw an error.
14627 You can wrap this call to catch the error like this:
14629 (condition-case msg
14630 (org-mobile-locate-entry (match-string 4))
14631 (error (nth 1 msg)))
14633 The return value will then be either a string with the error message,
14634 or a marker if everything is OK.
14636 If THIS-BUFFER is set, the outline path does not contain a file,
14637 only headings."
14638 (let* ((file (if this-buffer buffer-file-name (pop path)))
14639 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14640 (level 1)
14641 (lmin 1)
14642 (lmax 1)
14643 limit re end found pos heading cnt flevel)
14644 (unless buffer (error "File not found :%s" file))
14645 (with-current-buffer buffer
14646 (save-excursion
14647 (save-restriction
14648 (widen)
14649 (setq limit (point-max))
14650 (goto-char (point-min))
14651 (while (setq heading (pop path))
14652 (setq re (format org-complex-heading-regexp-format
14653 (regexp-quote heading)))
14654 (setq cnt 0 pos (point))
14655 (while (re-search-forward re end t)
14656 (setq level (- (match-end 1) (match-beginning 1)))
14657 (if (and (>= level lmin) (<= level lmax))
14658 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
14659 (when (= cnt 0) (error "Heading not found on level %d: %s"
14660 lmax heading))
14661 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14662 lmax heading))
14663 (goto-char found)
14664 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
14665 (setq end (save-excursion (org-end-of-subtree t t))))
14666 (when (org-on-heading-p)
14667 (move-marker (make-marker) (point))))))))
14669 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14670 "Find node HEADING in BUFFER.
14671 Return a marker to the heading if it was found, or nil if not.
14672 If POS-ONLY is set, return just the position instead of a marker.
14674 The heading text must match exact, but it may have a TODO keyword,
14675 a priority cookie and tags in the standard locations."
14676 (with-current-buffer (or buffer (current-buffer))
14677 (save-excursion
14678 (save-restriction
14679 (widen)
14680 (goto-char (point-min))
14681 (let (case-fold-search)
14682 (if (re-search-forward
14683 (format org-complex-heading-regexp-format
14684 (regexp-quote heading)) nil t)
14685 (if pos-only
14686 (match-beginning 0)
14687 (move-marker (make-marker) (match-beginning 0)))))))))
14689 (defun org-find-exact-heading-in-directory (heading &optional dir)
14690 "Find Org node headline HEADING in all .org files in directory DIR.
14691 When the target headline is found, return a marker to this location."
14692 (let ((files (directory-files (or dir default-directory)
14693 nil "\\`[^.#].*\\.org\\'"))
14694 file visiting m buffer)
14695 (catch 'found
14696 (while (setq file (pop files))
14697 (message "trying %s" file)
14698 (setq visiting (org-find-base-buffer-visiting file))
14699 (setq buffer (or visiting (find-file-noselect file)))
14700 (setq m (org-find-exact-headline-in-buffer
14701 heading buffer))
14702 (when (and (not m) (not visiting)) (kill-buffer buffer))
14703 (and m (throw 'found m))))))
14705 (defun org-find-entry-with-id (ident)
14706 "Locate the entry that contains the ID property with exact value IDENT.
14707 IDENT can be a string, a symbol or a number, this function will search for
14708 the string representation of it.
14709 Return the position where this entry starts, or nil if there is no such entry."
14710 (interactive "sID: ")
14711 (let ((id (cond
14712 ((stringp ident) ident)
14713 ((symbol-name ident) (symbol-name ident))
14714 ((numberp ident) (number-to-string ident))
14715 (t (error "IDENT %s must be a string, symbol or number" ident))))
14716 (case-fold-search nil))
14717 (save-excursion
14718 (save-restriction
14719 (widen)
14720 (goto-char (point-min))
14721 (when (re-search-forward
14722 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
14723 nil t)
14724 (org-back-to-heading t)
14725 (point))))))
14727 ;;;; Timestamps
14729 (defvar org-last-changed-timestamp nil)
14730 (defvar org-last-inserted-timestamp nil
14731 "The last time stamp inserted with `org-insert-time-stamp'.")
14732 (defvar org-time-was-given) ; dynamically scoped parameter
14733 (defvar org-end-time-was-given) ; dynamically scoped parameter
14734 (defvar org-ts-what) ; dynamically scoped parameter
14736 (defun org-time-stamp (arg &optional inactive)
14737 "Prompt for a date/time and insert a time stamp.
14738 If the user specifies a time like HH:MM, or if this command is called
14739 with a prefix argument, the time stamp will contain date and time.
14740 Otherwise, only the date will be included. All parts of a date not
14741 specified by the user will be filled in from the current date/time.
14742 So if you press just return without typing anything, the time stamp
14743 will represent the current date/time. If there is already a timestamp
14744 at the cursor, it will be modified."
14745 (interactive "P")
14746 (let* ((ts nil)
14747 (default-time
14748 ;; Default time is either today, or, when entering a range,
14749 ;; the range start.
14750 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
14751 (save-excursion
14752 (re-search-backward
14753 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
14754 (- (point) 20) t)))
14755 (apply 'encode-time (org-parse-time-string (match-string 1)))
14756 (current-time)))
14757 (default-input (and ts (org-get-compact-tod ts)))
14758 (repeater (save-excursion
14759 (save-match-data
14760 (beginning-of-line)
14761 (when (re-search-forward
14762 "\\([.+-]+[0-9]+[dwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
14763 (save-excursion (progn (end-of-line) (point))) t)
14764 (match-string 0)))))
14765 org-time-was-given org-end-time-was-given time)
14766 (cond
14767 ((and (org-at-timestamp-p t)
14768 (memq last-command '(org-time-stamp org-time-stamp-inactive))
14769 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
14770 (insert "--")
14771 (setq time (let ((this-command this-command))
14772 (org-read-date arg 'totime nil nil
14773 default-time default-input)))
14774 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
14775 ((org-at-timestamp-p t)
14776 (setq time (let ((this-command this-command))
14777 (org-read-date arg 'totime nil nil default-time default-input)))
14778 (when (org-at-timestamp-p t) ; just to get the match data
14779 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
14780 (replace-match "")
14781 (setq org-last-changed-timestamp
14782 (org-insert-time-stamp
14783 time (or org-time-was-given arg)
14784 inactive nil nil (list org-end-time-was-given)))
14785 (when repeater (goto-char (1- (point))) (insert " " repeater)
14786 (setq org-last-changed-timestamp
14787 (concat (substring org-last-inserted-timestamp 0 -1)
14788 " " repeater ">"))))
14789 (message "Timestamp updated"))
14791 (setq time (let ((this-command this-command))
14792 (org-read-date arg 'totime nil nil default-time default-input)))
14793 (org-insert-time-stamp time (or org-time-was-given arg) inactive
14794 nil nil (list org-end-time-was-given))))))
14796 ;; FIXME: can we use this for something else, like computing time differences?
14797 (defun org-get-compact-tod (s)
14798 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
14799 (let* ((t1 (match-string 1 s))
14800 (h1 (string-to-number (match-string 2 s)))
14801 (m1 (string-to-number (match-string 3 s)))
14802 (t2 (and (match-end 4) (match-string 5 s)))
14803 (h2 (and t2 (string-to-number (match-string 6 s))))
14804 (m2 (and t2 (string-to-number (match-string 7 s))))
14805 dh dm)
14806 (if (not t2)
14808 (setq dh (- h2 h1) dm (- m2 m1))
14809 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
14810 (concat t1 "+" (number-to-string dh)
14811 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
14813 (defun org-time-stamp-inactive (&optional arg)
14814 "Insert an inactive time stamp.
14815 An inactive time stamp is enclosed in square brackets instead of angle
14816 brackets. It is inactive in the sense that it does not trigger agenda entries,
14817 does not link to the calendar and cannot be changed with the S-cursor keys.
14818 So these are more for recording a certain time/date."
14819 (interactive "P")
14820 (org-time-stamp arg 'inactive))
14822 (defvar org-date-ovl (make-overlay 1 1))
14823 (overlay-put org-date-ovl 'face 'org-warning)
14824 (org-detach-overlay org-date-ovl)
14826 (defvar org-ans1) ; dynamically scoped parameter
14827 (defvar org-ans2) ; dynamically scoped parameter
14829 (defvar org-plain-time-of-day-regexp) ; defined below
14831 (defvar org-overriding-default-time nil) ; dynamically scoped
14832 (defvar org-read-date-overlay nil)
14833 (defvar org-dcst nil) ; dynamically scoped
14834 (defvar org-read-date-history nil)
14835 (defvar org-read-date-final-answer nil)
14836 (defvar org-read-date-analyze-futurep nil)
14837 (defvar org-read-date-analyze-forced-year nil)
14839 (defun org-read-date (&optional with-time to-time from-string prompt
14840 default-time default-input)
14841 "Read a date, possibly a time, and make things smooth for the user.
14842 The prompt will suggest to enter an ISO date, but you can also enter anything
14843 which will at least partially be understood by `parse-time-string'.
14844 Unrecognized parts of the date will default to the current day, month, year,
14845 hour and minute. If this command is called to replace a timestamp at point,
14846 or to enter the second timestamp of a range, the default time is taken
14847 from the existing stamp. Furthermore, the command prefers the future,
14848 so if you are giving a date where the year is not given, and the day-month
14849 combination is already past in the current year, it will assume you
14850 mean next year. For details, see the manual. A few examples:
14852 3-2-5 --> 2003-02-05
14853 feb 15 --> currentyear-02-15
14854 2/15 --> currentyear-02-15
14855 sep 12 9 --> 2009-09-12
14856 12:45 --> today 12:45
14857 22 sept 0:34 --> currentyear-09-22 0:34
14858 12 --> currentyear-currentmonth-12
14859 Fri --> nearest Friday (today or later)
14860 etc.
14862 Furthermore you can specify a relative date by giving, as the *first* thing
14863 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
14864 change in days weeks, months, years.
14865 With a single plus or minus, the date is relative to today. With a double
14866 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
14867 +4d --> four days from today
14868 +4 --> same as above
14869 +2w --> two weeks from today
14870 ++5 --> five days from default date
14872 The function understands only English month and weekday abbreviations,
14873 but this can be configured with the variables `parse-time-months' and
14874 `parse-time-weekdays'.
14876 While prompting, a calendar is popped up - you can also select the
14877 date with the mouse (button 1). The calendar shows a period of three
14878 months. To scroll it to other months, use the keys `>' and `<'.
14879 If you don't like the calendar, turn it off with
14880 \(setq org-read-date-popup-calendar nil)
14882 With optional argument TO-TIME, the date will immediately be converted
14883 to an internal time.
14884 With an optional argument WITH-TIME, the prompt will suggest to also
14885 insert a time. Note that when WITH-TIME is not set, you can still
14886 enter a time, and this function will inform the calling routine about
14887 this change. The calling routine may then choose to change the format
14888 used to insert the time stamp into the buffer to include the time.
14889 With optional argument FROM-STRING, read from this string instead from
14890 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
14891 the time/date that is used for everything that is not specified by the
14892 user."
14893 (require 'parse-time)
14894 (let* ((org-time-stamp-rounding-minutes
14895 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
14896 (org-dcst org-display-custom-times)
14897 (ct (org-current-time))
14898 (def (or org-overriding-default-time default-time ct))
14899 (defdecode (decode-time def))
14900 (dummy (progn
14901 (when (< (nth 2 defdecode) org-extend-today-until)
14902 (setcar (nthcdr 2 defdecode) -1)
14903 (setcar (nthcdr 1 defdecode) 59)
14904 (setq def (apply 'encode-time defdecode)
14905 defdecode (decode-time def)))))
14906 (calendar-frame-setup nil)
14907 (calendar-setup nil)
14908 (calendar-move-hook nil)
14909 (calendar-view-diary-initially-flag nil)
14910 (calendar-view-holidays-initially-flag nil)
14911 (timestr (format-time-string
14912 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
14913 (prompt (concat (if prompt (concat prompt " ") "")
14914 (format "Date+time [%s]: " timestr)))
14915 ans (org-ans0 "") org-ans1 org-ans2 final)
14917 (cond
14918 (from-string (setq ans from-string))
14919 (org-read-date-popup-calendar
14920 (save-excursion
14921 (save-window-excursion
14922 (calendar)
14923 (unwind-protect
14924 (progn
14925 (calendar-forward-day (- (time-to-days def)
14926 (calendar-absolute-from-gregorian
14927 (calendar-current-date))))
14928 (org-eval-in-calendar nil t)
14929 (let* ((old-map (current-local-map))
14930 (map (copy-keymap calendar-mode-map))
14931 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
14932 (org-defkey map (kbd "RET") 'org-calendar-select)
14933 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
14934 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
14935 (org-defkey minibuffer-local-map [(meta shift left)]
14936 (lambda () (interactive)
14937 (org-eval-in-calendar '(calendar-backward-month 1))))
14938 (org-defkey minibuffer-local-map [(meta shift right)]
14939 (lambda () (interactive)
14940 (org-eval-in-calendar '(calendar-forward-month 1))))
14941 (org-defkey minibuffer-local-map [(meta shift up)]
14942 (lambda () (interactive)
14943 (org-eval-in-calendar '(calendar-backward-year 1))))
14944 (org-defkey minibuffer-local-map [(meta shift down)]
14945 (lambda () (interactive)
14946 (org-eval-in-calendar '(calendar-forward-year 1))))
14947 (org-defkey minibuffer-local-map [?\e (shift left)]
14948 (lambda () (interactive)
14949 (org-eval-in-calendar '(calendar-backward-month 1))))
14950 (org-defkey minibuffer-local-map [?\e (shift right)]
14951 (lambda () (interactive)
14952 (org-eval-in-calendar '(calendar-forward-month 1))))
14953 (org-defkey minibuffer-local-map [?\e (shift up)]
14954 (lambda () (interactive)
14955 (org-eval-in-calendar '(calendar-backward-year 1))))
14956 (org-defkey minibuffer-local-map [?\e (shift down)]
14957 (lambda () (interactive)
14958 (org-eval-in-calendar '(calendar-forward-year 1))))
14959 (org-defkey minibuffer-local-map [(shift up)]
14960 (lambda () (interactive)
14961 (org-eval-in-calendar '(calendar-backward-week 1))))
14962 (org-defkey minibuffer-local-map [(shift down)]
14963 (lambda () (interactive)
14964 (org-eval-in-calendar '(calendar-forward-week 1))))
14965 (org-defkey minibuffer-local-map [(shift left)]
14966 (lambda () (interactive)
14967 (org-eval-in-calendar '(calendar-backward-day 1))))
14968 (org-defkey minibuffer-local-map [(shift right)]
14969 (lambda () (interactive)
14970 (org-eval-in-calendar '(calendar-forward-day 1))))
14971 (org-defkey minibuffer-local-map ">"
14972 (lambda () (interactive)
14973 (org-eval-in-calendar '(scroll-calendar-left 1))))
14974 (org-defkey minibuffer-local-map "<"
14975 (lambda () (interactive)
14976 (org-eval-in-calendar '(scroll-calendar-right 1))))
14977 (org-defkey minibuffer-local-map "\C-v"
14978 (lambda () (interactive)
14979 (org-eval-in-calendar
14980 '(calendar-scroll-left-three-months 1))))
14981 (org-defkey minibuffer-local-map "\M-v"
14982 (lambda () (interactive)
14983 (org-eval-in-calendar
14984 '(calendar-scroll-right-three-months 1))))
14985 (run-hooks 'org-read-date-minibuffer-setup-hook)
14986 (unwind-protect
14987 (progn
14988 (use-local-map map)
14989 (add-hook 'post-command-hook 'org-read-date-display)
14990 (setq org-ans0 (read-string prompt default-input
14991 'org-read-date-history nil))
14992 ;; org-ans0: from prompt
14993 ;; org-ans1: from mouse click
14994 ;; org-ans2: from calendar motion
14995 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
14996 (remove-hook 'post-command-hook 'org-read-date-display)
14997 (use-local-map old-map)
14998 (when org-read-date-overlay
14999 (delete-overlay org-read-date-overlay)
15000 (setq org-read-date-overlay nil)))))
15001 (bury-buffer "*Calendar*")))))
15003 (t ; Naked prompt only
15004 (unwind-protect
15005 (setq ans (read-string prompt default-input
15006 'org-read-date-history timestr))
15007 (when org-read-date-overlay
15008 (delete-overlay org-read-date-overlay)
15009 (setq org-read-date-overlay nil)))))
15011 (setq final (org-read-date-analyze ans def defdecode))
15013 (when org-read-date-analyze-forced-year
15014 (message "Year was forced into %s"
15015 (if org-read-date-force-compatible-dates
15016 "compatible range (1970-2037)"
15017 "range representable on this machine"))
15018 (ding))
15020 ;; One round trip to get rid of 34th of August and stuff like that....
15021 (setq final (decode-time (apply 'encode-time final)))
15023 (setq org-read-date-final-answer ans)
15025 (if to-time
15026 (apply 'encode-time final)
15027 (if (and (boundp 'org-time-was-given) org-time-was-given)
15028 (format "%04d-%02d-%02d %02d:%02d"
15029 (nth 5 final) (nth 4 final) (nth 3 final)
15030 (nth 2 final) (nth 1 final))
15031 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15033 (defvar def)
15034 (defvar defdecode)
15035 (defvar with-time)
15036 (defun org-read-date-display ()
15037 "Display the current date prompt interpretation in the minibuffer."
15038 (when org-read-date-display-live
15039 (when org-read-date-overlay
15040 (delete-overlay org-read-date-overlay))
15041 (let ((p (point)))
15042 (end-of-line 1)
15043 (while (not (equal (buffer-substring
15044 (max (point-min) (- (point) 4)) (point))
15045 " "))
15046 (insert " "))
15047 (goto-char p))
15048 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15049 " " (or org-ans1 org-ans2)))
15050 (org-end-time-was-given nil)
15051 (f (org-read-date-analyze ans def defdecode))
15052 (fmts (if org-dcst
15053 org-time-stamp-custom-formats
15054 org-time-stamp-formats))
15055 (fmt (if (or with-time
15056 (and (boundp 'org-time-was-given) org-time-was-given))
15057 (cdr fmts)
15058 (car fmts)))
15059 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
15060 (when (and org-end-time-was-given
15061 (string-match org-plain-time-of-day-regexp txt))
15062 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15063 org-end-time-was-given
15064 (substring txt (match-end 0)))))
15065 (when org-read-date-analyze-futurep
15066 (setq txt (concat txt " (=>F)")))
15067 (setq org-read-date-overlay
15068 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15069 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
15071 (defun org-read-date-analyze (ans def defdecode)
15072 "Analyze the combined answer of the date prompt."
15073 ;; FIXME: cleanup and comment
15074 (let ((nowdecode (decode-time (current-time)))
15075 delta deltan deltaw deltadef year month day
15076 hour minute second wday pm h2 m2 tl wday1
15077 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15078 (setq org-read-date-analyze-futurep nil
15079 org-read-date-analyze-forced-year nil)
15080 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15081 (setq ans "+0"))
15083 (when (setq delta (org-read-date-get-relative ans (current-time) def))
15084 (setq ans (replace-match "" t t ans)
15085 deltan (car delta)
15086 deltaw (nth 1 delta)
15087 deltadef (nth 2 delta)))
15089 ;; Check if there is an iso week date in there
15090 ;; If yes, store the info and postpone interpreting it until the rest
15091 ;; of the parsing is done
15092 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15093 (setq iso-year (if (match-end 1)
15094 (org-small-year-to-year
15095 (string-to-number (match-string 1 ans))))
15096 iso-weekday (if (match-end 3)
15097 (string-to-number (match-string 3 ans)))
15098 iso-week (string-to-number (match-string 2 ans)))
15099 (setq ans (replace-match "" t t ans)))
15101 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15102 (when (string-match
15103 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15104 (setq year (if (match-end 2)
15105 (string-to-number (match-string 2 ans))
15106 (progn (setq kill-year t)
15107 (string-to-number (format-time-string "%Y"))))
15108 month (string-to-number (match-string 3 ans))
15109 day (string-to-number (match-string 4 ans)))
15110 (if (< year 100) (setq year (+ 2000 year)))
15111 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15112 t nil ans)))
15114 ;; Help matching dottet european dates
15115 (when (string-match
15116 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15117 (setq year (if (match-end 3)
15118 (string-to-number (match-string 3 ans))
15119 (progn (setq kill-year t)
15120 (string-to-number (format-time-string "%Y"))))
15121 day (string-to-number (match-string 1 ans))
15122 month (string-to-number (match-string 2 ans))
15123 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15124 t nil ans)))
15126 ;; Help matching american dates, like 5/30 or 5/30/7
15127 (when (string-match
15128 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15129 (setq year (if (match-end 4)
15130 (string-to-number (match-string 4 ans))
15131 (progn (setq kill-year t)
15132 (string-to-number (format-time-string "%Y"))))
15133 month (string-to-number (match-string 1 ans))
15134 day (string-to-number (match-string 2 ans)))
15135 (if (< year 100) (setq year (+ 2000 year)))
15136 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15137 t nil ans)))
15138 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15139 ;; If there is a time with am/pm, and *no* time without it, we convert
15140 ;; so that matching will be successful.
15141 (loop for i from 1 to 2 do ; twice, for end time as well
15142 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15143 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15144 (setq hour (string-to-number (match-string 1 ans))
15145 minute (if (match-end 3)
15146 (string-to-number (match-string 3 ans))
15148 pm (equal ?p
15149 (string-to-char (downcase (match-string 4 ans)))))
15150 (if (and (= hour 12) (not pm))
15151 (setq hour 0)
15152 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15153 (setq ans (replace-match (format "%02d:%02d" hour minute)
15154 t t ans))))
15156 ;; Check if a time range is given as a duration
15157 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15158 (setq hour (string-to-number (match-string 1 ans))
15159 h2 (+ hour (string-to-number (match-string 3 ans)))
15160 minute (string-to-number (match-string 2 ans))
15161 m2 (+ minute (if (match-end 5) (string-to-number
15162 (match-string 5 ans))0)))
15163 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15164 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15165 t t ans)))
15167 ;; Check if there is a time range
15168 (when (boundp 'org-end-time-was-given)
15169 (setq org-time-was-given nil)
15170 (when (and (string-match org-plain-time-of-day-regexp ans)
15171 (match-end 8))
15172 (setq org-end-time-was-given (match-string 8 ans))
15173 (setq ans (concat (substring ans 0 (match-beginning 7))
15174 (substring ans (match-end 7))))))
15176 (setq tl (parse-time-string ans)
15177 day (or (nth 3 tl) (nth 3 defdecode))
15178 month (or (nth 4 tl)
15179 (if (and org-read-date-prefer-future
15180 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15181 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15182 (nth 4 defdecode)))
15183 year (or (and (not kill-year) (nth 5 tl))
15184 (if (and org-read-date-prefer-future
15185 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15186 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15187 (nth 5 defdecode)))
15188 hour (or (nth 2 tl) (nth 2 defdecode))
15189 minute (or (nth 1 tl) (nth 1 defdecode))
15190 second (or (nth 0 tl) 0)
15191 wday (nth 6 tl))
15193 (when (and (eq org-read-date-prefer-future 'time)
15194 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15195 (equal day (nth 3 nowdecode))
15196 (equal month (nth 4 nowdecode))
15197 (equal year (nth 5 nowdecode))
15198 (nth 2 tl)
15199 (or (< (nth 2 tl) (nth 2 nowdecode))
15200 (and (= (nth 2 tl) (nth 2 nowdecode))
15201 (nth 1 tl)
15202 (< (nth 1 tl) (nth 1 nowdecode)))))
15203 (setq day (1+ day)
15204 futurep t))
15206 ;; Special date definitions below
15207 (cond
15208 (iso-week
15209 ;; There was an iso week
15210 (require 'cal-iso)
15211 (setq futurep nil)
15212 (setq year (or iso-year year)
15213 day (or iso-weekday wday 1)
15214 wday nil ; to make sure that the trigger below does not match
15215 iso-date (calendar-gregorian-from-absolute
15216 (calendar-absolute-from-iso
15217 (list iso-week day year))))
15218 ; FIXME: Should we also push ISO weeks into the future?
15219 ; (when (and org-read-date-prefer-future
15220 ; (not iso-year)
15221 ; (< (calendar-absolute-from-gregorian iso-date)
15222 ; (time-to-days (current-time))))
15223 ; (setq year (1+ year)
15224 ; iso-date (calendar-gregorian-from-absolute
15225 ; (calendar-absolute-from-iso
15226 ; (list iso-week day year)))))
15227 (setq month (car iso-date)
15228 year (nth 2 iso-date)
15229 day (nth 1 iso-date)))
15230 (deltan
15231 (setq futurep nil)
15232 (unless deltadef
15233 (let ((now (decode-time (current-time))))
15234 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15235 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15236 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15237 ((equal deltaw "m") (setq month (+ month deltan)))
15238 ((equal deltaw "y") (setq year (+ year deltan)))))
15239 ((and wday (not (nth 3 tl)))
15240 (setq futurep nil)
15241 ;; Weekday was given, but no day, so pick that day in the week
15242 ;; on or after the derived date.
15243 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15244 (unless (equal wday wday1)
15245 (setq day (+ day (% (- wday wday1 -7) 7))))))
15246 (if (and (boundp 'org-time-was-given)
15247 (nth 2 tl))
15248 (setq org-time-was-given t))
15249 (if (< year 100) (setq year (+ 2000 year)))
15250 ;; Check of the date is representable
15251 (if org-read-date-force-compatible-dates
15252 (progn
15253 (if (< year 1970)
15254 (setq year 1970 org-read-date-analyze-forced-year t))
15255 (if (> year 2037)
15256 (setq year 2037 org-read-date-analyze-forced-year t)))
15257 (condition-case nil
15258 (ignore (encode-time second minute hour day month year))
15259 (error
15260 (setq year (nth 5 defdecode))
15261 (setq org-read-date-analyze-forced-year t))))
15262 (setq org-read-date-analyze-futurep futurep)
15263 (list second minute hour day month year)))
15265 (defvar parse-time-weekdays)
15267 (defun org-read-date-get-relative (s today default)
15268 "Check string S for special relative date string.
15269 TODAY and DEFAULT are internal times, for today and for a default.
15270 Return shift list (N what def-flag)
15271 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15272 N is the number of WHATs to shift.
15273 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15274 the DEFAULT date rather than TODAY."
15275 (require 'parse-time)
15276 (when (and
15277 (string-match
15278 (concat
15279 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15280 "\\([0-9]+\\)?"
15281 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15282 "\\([ \t]\\|$\\)") s)
15283 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15284 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15285 (string-to-char (substring (match-string 1 s) -1))
15286 ?+))
15287 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15288 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15289 (what (if (match-end 3) (match-string 3 s) "d"))
15290 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15291 (date (if rel default today))
15292 (wday (nth 6 (decode-time date)))
15293 delta)
15294 (if wday1
15295 (progn
15296 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15297 (if (= dir ?-) (setq delta (- delta 7)))
15298 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15299 (list delta "d" rel))
15300 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15302 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15303 "Turn a user-specified date into the internal representation.
15304 The internal representation needed by the calendar is (month day year).
15305 This is a wrapper to handle the brain-dead convention in calendar that
15306 user function argument order change dependent on argument order."
15307 (if (boundp 'calendar-date-style)
15308 (cond
15309 ((eq calendar-date-style 'american)
15310 (list arg1 arg2 arg3))
15311 ((eq calendar-date-style 'european)
15312 (list arg2 arg1 arg3))
15313 ((eq calendar-date-style 'iso)
15314 (list arg2 arg3 arg1)))
15315 (with-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15316 (if (org-bound-and-true-p european-calendar-style)
15317 (list arg2 arg1 arg3)
15318 (list arg1 arg2 arg3)))))
15320 (defun org-eval-in-calendar (form &optional keepdate)
15321 "Eval FORM in the calendar window and return to current window.
15322 Also, store the cursor date in variable org-ans2."
15323 (let ((sf (selected-frame))
15324 (sw (selected-window)))
15325 (select-window (get-buffer-window "*Calendar*" t))
15326 (eval form)
15327 (when (and (not keepdate) (calendar-cursor-to-date))
15328 (let* ((date (calendar-cursor-to-date))
15329 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15330 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15331 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15332 (select-window sw)
15333 (org-select-frame-set-input-focus sf)))
15335 (defun org-calendar-select ()
15336 "Return to `org-read-date' with the date currently selected.
15337 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15338 (interactive)
15339 (when (calendar-cursor-to-date)
15340 (let* ((date (calendar-cursor-to-date))
15341 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15342 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15343 (if (active-minibuffer-window) (exit-minibuffer))))
15345 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15346 "Insert a date stamp for the date given by the internal TIME.
15347 WITH-HM means use the stamp format that includes the time of the day.
15348 INACTIVE means use square brackets instead of angular ones, so that the
15349 stamp will not contribute to the agenda.
15350 PRE and POST are optional strings to be inserted before and after the
15351 stamp.
15352 The command returns the inserted time stamp."
15353 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15354 stamp)
15355 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15356 (insert-before-markers (or pre ""))
15357 (when (listp extra)
15358 (setq extra (car extra))
15359 (if (and (stringp extra)
15360 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15361 (setq extra (format "-%02d:%02d"
15362 (string-to-number (match-string 1 extra))
15363 (string-to-number (match-string 2 extra))))
15364 (setq extra nil)))
15365 (when extra
15366 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15367 (insert-before-markers (setq stamp (format-time-string fmt time)))
15368 (insert-before-markers (or post ""))
15369 (setq org-last-inserted-timestamp stamp)))
15371 (defun org-toggle-time-stamp-overlays ()
15372 "Toggle the use of custom time stamp formats."
15373 (interactive)
15374 (setq org-display-custom-times (not org-display-custom-times))
15375 (unless org-display-custom-times
15376 (let ((p (point-min)) (bmp (buffer-modified-p)))
15377 (while (setq p (next-single-property-change p 'display))
15378 (if (and (get-text-property p 'display)
15379 (eq (get-text-property p 'face) 'org-date))
15380 (remove-text-properties
15381 p (setq p (next-single-property-change p 'display))
15382 '(display t))))
15383 (set-buffer-modified-p bmp)))
15384 (if (featurep 'xemacs)
15385 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15386 (org-restart-font-lock)
15387 (setq org-table-may-need-update t)
15388 (if org-display-custom-times
15389 (message "Time stamps are overlaid with custom format")
15390 (message "Time stamp overlays removed")))
15392 (defun org-display-custom-time (beg end)
15393 "Overlay modified time stamp format over timestamp between BEG and END."
15394 (let* ((ts (buffer-substring beg end))
15395 t1 w1 with-hm tf time str w2 (off 0))
15396 (save-match-data
15397 (setq t1 (org-parse-time-string ts t))
15398 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
15399 (setq off (- (match-end 0) (match-beginning 0)))))
15400 (setq end (- end off))
15401 (setq w1 (- end beg)
15402 with-hm (and (nth 1 t1) (nth 2 t1))
15403 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15404 time (org-fix-decoded-time t1)
15405 str (org-add-props
15406 (format-time-string
15407 (substring tf 1 -1) (apply 'encode-time time))
15408 nil 'mouse-face 'highlight)
15409 w2 (length str))
15410 (if (not (= w2 w1))
15411 (add-text-properties (1+ beg) (+ 2 beg)
15412 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15413 (if (featurep 'xemacs)
15414 (progn
15415 (put-text-property beg end 'invisible t)
15416 (put-text-property beg end 'end-glyph (make-glyph str)))
15417 (put-text-property beg end 'display str))))
15419 (defun org-translate-time (string)
15420 "Translate all timestamps in STRING to custom format.
15421 But do this only if the variable `org-display-custom-times' is set."
15422 (when org-display-custom-times
15423 (save-match-data
15424 (let* ((start 0)
15425 (re org-ts-regexp-both)
15426 t1 with-hm inactive tf time str beg end)
15427 (while (setq start (string-match re string start))
15428 (setq beg (match-beginning 0)
15429 end (match-end 0)
15430 t1 (save-match-data
15431 (org-parse-time-string (substring string beg end) t))
15432 with-hm (and (nth 1 t1) (nth 2 t1))
15433 inactive (equal (substring string beg (1+ beg)) "[")
15434 tf (funcall (if with-hm 'cdr 'car)
15435 org-time-stamp-custom-formats)
15436 time (org-fix-decoded-time t1)
15437 str (format-time-string
15438 (concat
15439 (if inactive "[" "<") (substring tf 1 -1)
15440 (if inactive "]" ">"))
15441 (apply 'encode-time time))
15442 string (replace-match str t t string)
15443 start (+ start (length str)))))))
15444 string)
15446 (defun org-fix-decoded-time (time)
15447 "Set 0 instead of nil for the first 6 elements of time.
15448 Don't touch the rest."
15449 (let ((n 0))
15450 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15452 (defun org-days-to-time (timestamp-string)
15453 "Difference between TIMESTAMP-STRING and now in days."
15454 (- (time-to-days (org-time-string-to-time timestamp-string))
15455 (time-to-days (current-time))))
15457 (defun org-deadline-close (timestamp-string &optional ndays)
15458 "Is the time in TIMESTAMP-STRING close to the current date?"
15459 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15460 (and (< (org-days-to-time timestamp-string) ndays)
15461 (not (org-entry-is-done-p))))
15463 (defun org-get-wdays (ts)
15464 "Get the deadline lead time appropriate for timestring TS."
15465 (cond
15466 ((<= org-deadline-warning-days 0)
15467 ;; 0 or negative, enforce this value no matter what
15468 (- org-deadline-warning-days))
15469 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
15470 ;; lead time is specified.
15471 (floor (* (string-to-number (match-string 1 ts))
15472 (cdr (assoc (match-string 2 ts)
15473 '(("d" . 1) ("w" . 7)
15474 ("m" . 30.4) ("y" . 365.25)))))))
15475 ;; go for the default.
15476 (t org-deadline-warning-days)))
15478 (defun org-calendar-select-mouse (ev)
15479 "Return to `org-read-date' with the date currently selected.
15480 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15481 (interactive "e")
15482 (mouse-set-point ev)
15483 (when (calendar-cursor-to-date)
15484 (let* ((date (calendar-cursor-to-date))
15485 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15486 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15487 (if (active-minibuffer-window) (exit-minibuffer))))
15489 (defun org-check-deadlines (ndays)
15490 "Check if there are any deadlines due or past due.
15491 A deadline is considered due if it happens within `org-deadline-warning-days'
15492 days from today's date. If the deadline appears in an entry marked DONE,
15493 it is not shown. The prefix arg NDAYS can be used to test that many
15494 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15495 (interactive "P")
15496 (let* ((org-warn-days
15497 (cond
15498 ((equal ndays '(4)) 100000)
15499 (ndays (prefix-numeric-value ndays))
15500 (t (abs org-deadline-warning-days))))
15501 (case-fold-search nil)
15502 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15503 (callback
15504 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15506 (message "%d deadlines past-due or due within %d days"
15507 (org-occur regexp nil callback)
15508 org-warn-days)))
15510 (defun org-check-before-date (date)
15511 "Check if there are deadlines or scheduled entries before DATE."
15512 (interactive (list (org-read-date)))
15513 (let ((case-fold-search nil)
15514 (regexp (concat "\\<\\(" org-deadline-string
15515 "\\|" org-scheduled-string
15516 "\\) *<\\([^>]+\\)>"))
15517 (callback
15518 (lambda () (time-less-p
15519 (org-time-string-to-time (match-string 2))
15520 (org-time-string-to-time date)))))
15521 (message "%d entries before %s"
15522 (org-occur regexp nil callback) date)))
15524 (defun org-check-after-date (date)
15525 "Check if there are deadlines or scheduled entries after DATE."
15526 (interactive (list (org-read-date)))
15527 (let ((case-fold-search nil)
15528 (regexp (concat "\\<\\(" org-deadline-string
15529 "\\|" org-scheduled-string
15530 "\\) *<\\([^>]+\\)>"))
15531 (callback
15532 (lambda () (not
15533 (time-less-p
15534 (org-time-string-to-time (match-string 2))
15535 (org-time-string-to-time date))))))
15536 (message "%d entries after %s"
15537 (org-occur regexp nil callback) date)))
15539 (defun org-evaluate-time-range (&optional to-buffer)
15540 "Evaluate a time range by computing the difference between start and end.
15541 Normally the result is just printed in the echo area, but with prefix arg
15542 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15543 If the time range is actually in a table, the result is inserted into the
15544 next column.
15545 For time difference computation, a year is assumed to be exactly 365
15546 days in order to avoid rounding problems."
15547 (interactive "P")
15549 (org-clock-update-time-maybe)
15550 (save-excursion
15551 (unless (org-at-date-range-p t)
15552 (goto-char (point-at-bol))
15553 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15554 (if (not (org-at-date-range-p t))
15555 (error "Not at a time-stamp range, and none found in current line")))
15556 (let* ((ts1 (match-string 1))
15557 (ts2 (match-string 2))
15558 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15559 (match-end (match-end 0))
15560 (time1 (org-time-string-to-time ts1))
15561 (time2 (org-time-string-to-time ts2))
15562 (t1 (org-float-time time1))
15563 (t2 (org-float-time time2))
15564 (diff (abs (- t2 t1)))
15565 (negative (< (- t2 t1) 0))
15566 ;; (ys (floor (* 365 24 60 60)))
15567 (ds (* 24 60 60))
15568 (hs (* 60 60))
15569 (fy "%dy %dd %02d:%02d")
15570 (fy1 "%dy %dd")
15571 (fd "%dd %02d:%02d")
15572 (fd1 "%dd")
15573 (fh "%02d:%02d")
15574 y d h m align)
15575 (if havetime
15576 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15578 d (floor (/ diff ds)) diff (mod diff ds)
15579 h (floor (/ diff hs)) diff (mod diff hs)
15580 m (floor (/ diff 60)))
15581 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15583 d (floor (+ (/ diff ds) 0.5))
15584 h 0 m 0))
15585 (if (not to-buffer)
15586 (message "%s" (org-make-tdiff-string y d h m))
15587 (if (org-at-table-p)
15588 (progn
15589 (goto-char match-end)
15590 (setq align t)
15591 (and (looking-at " *|") (goto-char (match-end 0))))
15592 (goto-char match-end))
15593 (if (looking-at
15594 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15595 (replace-match ""))
15596 (if negative (insert " -"))
15597 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15598 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15599 (insert " " (format fh h m))))
15600 (if align (org-table-align))
15601 (message "Time difference inserted")))))
15603 (defun org-make-tdiff-string (y d h m)
15604 (let ((fmt "")
15605 (l nil))
15606 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15607 l (push y l)))
15608 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15609 l (push d l)))
15610 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15611 l (push h l)))
15612 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15613 l (push m l)))
15614 (apply 'format fmt (nreverse l))))
15616 (defun org-time-string-to-time (s &optional buffer pos)
15617 (condition-case errdata
15618 (apply 'encode-time (org-parse-time-string s))
15619 (error (error "Bad timestamp `%s'%s\nError was: %s"
15620 s (if (not (and buffer pos))
15622 (format " at %d in buffer `%s'" pos buffer))
15623 (cdr errdata)))))
15625 (defun org-time-string-to-seconds (s)
15626 (org-float-time (org-time-string-to-time s)))
15628 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
15629 "Convert a time stamp to an absolute day number.
15630 If there is a specifier for a cyclic time stamp, get the closest date to
15631 DAYNR.
15632 PREFER and SHOW-ALL are passed through to `org-closest-date'.
15633 The variable date is bound by the calendar when this is called."
15634 (cond
15635 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15636 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15637 daynr
15638 (+ daynr 1000)))
15639 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
15640 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15641 (time-to-days (current-time))) (match-string 0 s)
15642 prefer show-all))
15643 (t (time-to-days
15644 (condition-case errdata
15645 (apply 'encode-time (org-parse-time-string s))
15646 (error (error "Bad timestamp `%s'%s\nError was: %s"
15647 s (if (not (and buffer pos))
15649 (format " at %d in buffer `%s'" pos buffer))
15650 (cdr errdata))))))))
15652 (defun org-days-to-iso-week (days)
15653 "Return the iso week number."
15654 (require 'cal-iso)
15655 (car (calendar-iso-from-absolute days)))
15657 (defun org-small-year-to-year (year)
15658 "Convert 2-digit years into 4-digit years.
15659 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15660 The year 2000 cannot be abbreviated. Any year larger than 99
15661 is returned unchanged."
15662 (if (< year 38)
15663 (setq year (+ 2000 year))
15664 (if (< year 100)
15665 (setq year (+ 1900 year))))
15666 year)
15668 (defun org-time-from-absolute (d)
15669 "Return the time corresponding to date D.
15670 D may be an absolute day number, or a calendar-type list (month day year)."
15671 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15672 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15674 (defun org-calendar-holiday ()
15675 "List of holidays, for Diary display in Org-mode."
15676 (require 'holidays)
15677 (let ((hl (funcall
15678 (if (fboundp 'calendar-check-holidays)
15679 'calendar-check-holidays 'check-calendar-holidays) date)))
15680 (if hl (mapconcat 'identity hl "; "))))
15682 (defun org-diary-sexp-entry (sexp entry date)
15683 "Process a SEXP diary ENTRY for DATE."
15684 (require 'diary-lib)
15685 (let ((result (if calendar-debug-sexp
15686 (let ((stack-trace-on-error t))
15687 (eval (car (read-from-string sexp))))
15688 (condition-case nil
15689 (eval (car (read-from-string sexp)))
15690 (error
15691 (beep)
15692 (message "Bad sexp at line %d in %s: %s"
15693 (org-current-line)
15694 (buffer-file-name) sexp)
15695 (sleep-for 2))))))
15696 (cond ((stringp result) (split-string result "; "))
15697 ((and (consp result)
15698 (not (consp (cdr result)))
15699 (stringp (cdr result))) (cdr result))
15700 ((and (consp result)
15701 (stringp (car result))) result)
15702 (result entry)
15703 (t nil))))
15705 (defun org-diary-to-ical-string (frombuf)
15706 "Get iCalendar entries from diary entries in buffer FROMBUF.
15707 This uses the icalendar.el library."
15708 (let* ((tmpdir (if (featurep 'xemacs)
15709 (temp-directory)
15710 temporary-file-directory))
15711 (tmpfile (make-temp-name
15712 (expand-file-name "orgics" tmpdir)))
15713 buf rtn b e)
15714 (with-current-buffer frombuf
15715 (icalendar-export-region (point-min) (point-max) tmpfile)
15716 (setq buf (find-buffer-visiting tmpfile))
15717 (set-buffer buf)
15718 (goto-char (point-min))
15719 (if (re-search-forward "^BEGIN:VEVENT" nil t)
15720 (setq b (match-beginning 0)))
15721 (goto-char (point-max))
15722 (if (re-search-backward "^END:VEVENT" nil t)
15723 (setq e (match-end 0)))
15724 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
15725 (kill-buffer buf)
15726 (delete-file tmpfile)
15727 rtn))
15729 (defun org-closest-date (start current change prefer show-all)
15730 "Find the date closest to CURRENT that is consistent with START and CHANGE.
15731 When PREFER is `past', return a date that is either CURRENT or past.
15732 When PREFER is `future', return a date that is either CURRENT or future.
15733 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
15734 ;; Make the proper lists from the dates
15735 (catch 'exit
15736 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
15737 dn dw sday cday n1 n2 n0
15738 d m y y1 y2 date1 date2 nmonths nm ny m2)
15740 (setq start (org-date-to-gregorian start)
15741 current (org-date-to-gregorian
15742 (if show-all
15743 current
15744 (time-to-days (current-time))))
15745 sday (calendar-absolute-from-gregorian start)
15746 cday (calendar-absolute-from-gregorian current))
15748 (if (<= cday sday) (throw 'exit sday))
15750 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
15751 (setq dn (string-to-number (match-string 1 change))
15752 dw (cdr (assoc (match-string 2 change) a1)))
15753 (error "Invalid change specifier: %s" change))
15754 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
15755 (cond
15756 ((eq dw 'day)
15757 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
15758 n2 (+ n1 dn)))
15759 ((eq dw 'year)
15760 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
15761 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
15762 (setq date1 (list m d y1)
15763 n1 (calendar-absolute-from-gregorian date1)
15764 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
15765 n2 (calendar-absolute-from-gregorian date2)))
15766 ((eq dw 'month)
15767 ;; approx number of month between the two dates
15768 (setq nmonths (floor (/ (- cday sday) 30.436875)))
15769 ;; How often does dn fit in there?
15770 (setq d (nth 1 start) m (car start) y (nth 2 start)
15771 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
15772 m (+ m nm)
15773 ny (floor (/ m 12))
15774 y (+ y ny)
15775 m (- m (* ny 12)))
15776 (while (> m 12) (setq m (- m 12) y (1+ y)))
15777 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
15778 (setq m2 (+ m dn) y2 y)
15779 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15780 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
15781 (while (<= n2 cday)
15782 (setq n1 n2 m m2 y y2)
15783 (setq m2 (+ m dn) y2 y)
15784 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15785 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
15786 ;; Make sure n1 is the earlier date
15787 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
15788 (if show-all
15789 (cond
15790 ((eq prefer 'past) (if (= cday n2) n2 n1))
15791 ((eq prefer 'future) (if (= cday n1) n1 n2))
15792 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
15793 (cond
15794 ((eq prefer 'past) (if (= cday n2) n2 n1))
15795 ((eq prefer 'future) (if (= cday n1) n1 n2))
15796 (t (if (= cday n1) n1 n2)))))))
15798 (defun org-date-to-gregorian (date)
15799 "Turn any specification of DATE into a Gregorian date for the calendar."
15800 (cond ((integerp date) (calendar-gregorian-from-absolute date))
15801 ((and (listp date) (= (length date) 3)) date)
15802 ((stringp date)
15803 (setq date (org-parse-time-string date))
15804 (list (nth 4 date) (nth 3 date) (nth 5 date)))
15805 ((listp date)
15806 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
15808 (defun org-parse-time-string (s &optional nodefault)
15809 "Parse the standard Org-mode time string.
15810 This should be a lot faster than the normal `parse-time-string'.
15811 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
15812 hour and minute fields will be nil if not given."
15813 (if (string-match org-ts-regexp0 s)
15814 (list 0
15815 (if (or (match-beginning 8) (not nodefault))
15816 (string-to-number (or (match-string 8 s) "0")))
15817 (if (or (match-beginning 7) (not nodefault))
15818 (string-to-number (or (match-string 7 s) "0")))
15819 (string-to-number (match-string 4 s))
15820 (string-to-number (match-string 3 s))
15821 (string-to-number (match-string 2 s))
15822 nil nil nil)
15823 (error "Not a standard Org-mode time string: %s" s)))
15825 (defun org-timestamp-up (&optional arg)
15826 "Increase 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-down (&optional arg)
15834 "Decrease the date item at the cursor by one.
15835 If the cursor is on the year, change the year. If it is on the month,
15836 the day or the time, change that.
15837 With prefix ARG, change by that many units."
15838 (interactive "p")
15839 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
15841 (defun org-timestamp-up-day (&optional arg)
15842 "Increase the date in the time stamp by one day.
15843 With prefix ARG, change that many days."
15844 (interactive "p")
15845 (if (and (not (org-at-timestamp-p t))
15846 (org-on-heading-p))
15847 (org-todo 'up)
15848 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
15850 (defun org-timestamp-down-day (&optional arg)
15851 "Decrease the date in the time stamp by one day.
15852 With prefix ARG, change that many days."
15853 (interactive "p")
15854 (if (and (not (org-at-timestamp-p t))
15855 (org-on-heading-p))
15856 (org-todo 'down)
15857 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
15859 (defun org-at-timestamp-p (&optional inactive-ok)
15860 "Determine if the cursor is in or at a timestamp."
15861 (interactive)
15862 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
15863 (pos (point))
15864 (ans (or (looking-at tsr)
15865 (save-excursion
15866 (skip-chars-backward "^[<\n\r\t")
15867 (if (> (point) (point-min)) (backward-char 1))
15868 (and (looking-at tsr)
15869 (> (- (match-end 0) pos) -1))))))
15870 (and ans
15871 (boundp 'org-ts-what)
15872 (setq org-ts-what
15873 (cond
15874 ((= pos (match-beginning 0)) 'bracket)
15875 ;; Point is considered to be "on the bracket" whether
15876 ;; it's really on it or right after it.
15877 ((or (= pos (1- (match-end 0)))
15878 (= pos (match-end 0))) 'bracket)
15879 ((org-pos-in-match-range pos 2) 'year)
15880 ((org-pos-in-match-range pos 3) 'month)
15881 ((org-pos-in-match-range pos 7) 'hour)
15882 ((org-pos-in-match-range pos 8) 'minute)
15883 ((or (org-pos-in-match-range pos 4)
15884 (org-pos-in-match-range pos 5)) 'day)
15885 ((and (> pos (or (match-end 8) (match-end 5)))
15886 (< pos (match-end 0)))
15887 (- pos (or (match-end 8) (match-end 5))))
15888 (t 'day))))
15889 ans))
15891 (defun org-toggle-timestamp-type ()
15892 "Toggle the type (<active> or [inactive]) of a time stamp."
15893 (interactive)
15894 (when (org-at-timestamp-p t)
15895 (let ((beg (match-beginning 0)) (end (match-end 0))
15896 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
15897 (save-excursion
15898 (goto-char beg)
15899 (while (re-search-forward "[][<>]" end t)
15900 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
15901 t t)))
15902 (message "Timestamp is now %sactive"
15903 (if (equal (char-after beg) ?<) "" "in")))))
15905 (defun org-timestamp-change (n &optional what updown)
15906 "Change the date in the time stamp at point.
15907 The date will be changed by N times WHAT. WHAT can be `day', `month',
15908 `year', `minute', `second'. If WHAT is not given, the cursor position
15909 in the timestamp determines what will be changed."
15910 (let ((origin (point)) origin-cat
15911 with-hm inactive
15912 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
15913 org-ts-what
15914 extra rem
15915 ts time time0)
15916 (if (not (org-at-timestamp-p t))
15917 (error "Not at a timestamp"))
15918 (if (and (not what) (eq org-ts-what 'bracket))
15919 (org-toggle-timestamp-type)
15920 ;; Point isn't on brackets. Remember the part of the time-stamp
15921 ;; the point was in. Indeed, size of time-stamps may change,
15922 ;; but point must be kept in the same category nonetheless.
15923 (setq origin-cat org-ts-what)
15924 (if (and (not what) (not (eq org-ts-what 'day))
15925 org-display-custom-times
15926 (get-text-property (point) 'display)
15927 (not (get-text-property (1- (point)) 'display)))
15928 (setq org-ts-what 'day))
15929 (setq org-ts-what (or what org-ts-what)
15930 inactive (= (char-after (match-beginning 0)) ?\[)
15931 ts (match-string 0))
15932 (replace-match "")
15933 (if (string-match
15934 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
15936 (setq extra (match-string 1 ts)))
15937 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
15938 (setq with-hm t))
15939 (setq time0 (org-parse-time-string ts))
15940 (when (and updown
15941 (eq org-ts-what 'minute)
15942 (not current-prefix-arg))
15943 ;; This looks like s-up and s-down. Change by one rounding step.
15944 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
15945 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
15946 (setcar (cdr time0) (+ (nth 1 time0)
15947 (if (> n 0) (- rem) (- dm rem))))))
15948 (setq time
15949 (encode-time (or (car time0) 0)
15950 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
15951 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
15952 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
15953 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
15954 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
15955 (nthcdr 6 time0)))
15956 (when (and (member org-ts-what '(hour minute))
15957 extra
15958 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
15959 (setq extra (org-modify-ts-extra
15960 extra
15961 (if (eq org-ts-what 'hour) 2 5)
15962 n dm)))
15963 (when (integerp org-ts-what)
15964 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
15965 (if (eq what 'calendar)
15966 (let ((cal-date (org-get-date-from-calendar)))
15967 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
15968 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
15969 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
15970 (setcar time0 (or (car time0) 0))
15971 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
15972 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
15973 (setq time (apply 'encode-time time0))))
15974 ;; Insert the new time-stamp, and ensure point stays in the same
15975 ;; category as before (i.e. not after the last position in that
15976 ;; category).
15977 (let ((pos (point)))
15978 ;; Stay before inserted string. `save-excursion' is of no use.
15979 (setq org-last-changed-timestamp
15980 (org-insert-time-stamp time with-hm inactive nil nil extra))
15981 (goto-char pos))
15982 (save-match-data
15983 (looking-at org-ts-regexp3)
15984 (goto-char (cond
15985 ;; `day' category ends before `hour' if any, or at
15986 ;; the end of the day name.
15987 ((eq origin-cat 'day)
15988 (min (or (match-beginning 7) (1- (match-end 5))) origin))
15989 ((eq origin-cat 'hour) (min (match-end 7) origin))
15990 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
15991 ((integerp origin-cat) (min (1- (match-end 0)) origin))
15992 ;; `year' and `month' have both fixed size: point
15993 ;; couldn't have moved into another part.
15994 (t origin))))
15995 ;; Update clock if on a CLOCK line.
15996 (org-clock-update-time-maybe)
15997 ;; Try to recenter the calendar window, if any.
15998 (if (and org-calendar-follow-timestamp-change
15999 (get-buffer-window "*Calendar*" t)
16000 (memq org-ts-what '(day month year)))
16001 (org-recenter-calendar (time-to-days time))))))
16003 (defun org-modify-ts-extra (s pos n dm)
16004 "Change the different parts of the lead-time and repeat fields in timestamp."
16005 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16006 ng h m new rem)
16007 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16008 (cond
16009 ((or (org-pos-in-match-range pos 2)
16010 (org-pos-in-match-range pos 3))
16011 (setq m (string-to-number (match-string 3 s))
16012 h (string-to-number (match-string 2 s)))
16013 (if (org-pos-in-match-range pos 2)
16014 (setq h (+ h n))
16015 (setq n (* dm (org-no-warnings (signum n))))
16016 (when (not (= 0 (setq rem (% m dm))))
16017 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16018 (setq m (+ m n)))
16019 (if (< m 0) (setq m (+ m 60) h (1- h)))
16020 (if (> m 59) (setq m (- m 60) h (1+ h)))
16021 (setq h (min 24 (max 0 h)))
16022 (setq ng 1 new (format "-%02d:%02d" h m)))
16023 ((org-pos-in-match-range pos 6)
16024 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16025 ((org-pos-in-match-range pos 5)
16026 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16028 ((org-pos-in-match-range pos 9)
16029 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16030 ((org-pos-in-match-range pos 8)
16031 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16033 (when ng
16034 (setq s (concat
16035 (substring s 0 (match-beginning ng))
16037 (substring s (match-end ng))))))
16040 (defun org-recenter-calendar (date)
16041 "If the calendar is visible, recenter it to DATE."
16042 (let* ((win (selected-window))
16043 (cwin (get-buffer-window "*Calendar*" t))
16044 (calendar-move-hook nil))
16045 (when cwin
16046 (select-window cwin)
16047 (calendar-goto-date (if (listp date) date
16048 (calendar-gregorian-from-absolute date)))
16049 (select-window win))))
16051 (defun org-goto-calendar (&optional arg)
16052 "Go to the Emacs calendar at the current date.
16053 If there is a time stamp in the current line, go to that date.
16054 A prefix ARG can be used to force the current date."
16055 (interactive "P")
16056 (let ((tsr org-ts-regexp) diff
16057 (calendar-move-hook nil)
16058 (calendar-view-holidays-initially-flag nil)
16059 (calendar-view-diary-initially-flag nil))
16060 (if (or (org-at-timestamp-p)
16061 (save-excursion
16062 (beginning-of-line 1)
16063 (looking-at (concat ".*" tsr))))
16064 (let ((d1 (time-to-days (current-time)))
16065 (d2 (time-to-days
16066 (org-time-string-to-time (match-string 1)))))
16067 (setq diff (- d2 d1))))
16068 (calendar)
16069 (calendar-goto-today)
16070 (if (and diff (not arg)) (calendar-forward-day diff))))
16072 (defun org-get-date-from-calendar ()
16073 "Return a list (month day year) of date at point in calendar."
16074 (with-current-buffer "*Calendar*"
16075 (save-match-data
16076 (calendar-cursor-to-date))))
16078 (defun org-date-from-calendar ()
16079 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16080 If there is already a time stamp at the cursor position, update it."
16081 (interactive)
16082 (if (org-at-timestamp-p t)
16083 (org-timestamp-change 0 'calendar)
16084 (let ((cal-date (org-get-date-from-calendar)))
16085 (org-insert-time-stamp
16086 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16088 (defun org-minutes-to-hh:mm-string (m)
16089 "Compute H:MM from a number of minutes."
16090 (let ((h (/ m 60)))
16091 (setq m (- m (* 60 h)))
16092 (format org-time-clocksum-format h m)))
16094 (defun org-hh:mm-string-to-minutes (s)
16095 "Convert a string H:MM to a number of minutes.
16096 If the string is just a number, interpret it as minutes.
16097 In fact, the first hh:mm or number in the string will be taken,
16098 there can be extra stuff in the string.
16099 If no number is found, the return value is 0."
16100 (cond
16101 ((integerp s) s)
16102 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16103 (+ (* (string-to-number (match-string 1 s)) 60)
16104 (string-to-number (match-string 2 s))))
16105 ((string-match "\\([0-9]+\\)" s)
16106 (string-to-number (match-string 1 s)))
16107 (t 0)))
16109 (defcustom org-effort-durations
16110 `(("h" . 60)
16111 ("d" . ,(* 60 8))
16112 ("w" . ,(* 60 8 5))
16113 ("m" . ,(* 60 8 5 4))
16114 ("y" . ,(* 60 8 5 40)))
16115 "Conversion factor to minutes for an effort modifier.
16117 Each entry has the form (MODIFIER . MINUTES).
16119 In an effort string, a number followed by MODIFIER is multiplied
16120 by the specified number of MINUTES to obtain an effort in
16121 minutes.
16123 For example, if the value of this variable is ((\"hours\" . 60)), then an
16124 effort string \"2hours\" is equivalent to 120 minutes."
16125 :group 'org-agenda
16126 :type '(alist :key-type (string :tag "Modifier")
16127 :value-type (number :tag "Minutes")))
16129 (defun org-duration-string-to-minutes (s)
16130 "Convert a duration string S to minutes.
16132 A bare number is interpreted as minutes, modifiers can be set by
16133 customizing `org-effort-durations' (which see).
16135 Entries containing a colon are interpreted as H:MM by
16136 `org-hh:mm-string-to-minutes'."
16137 (let ((result 0)
16138 (re (concat "\\([0-9]+\\) *\\("
16139 (regexp-opt (mapcar 'car org-effort-durations))
16140 "\\)")))
16141 (while (string-match re s)
16142 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16143 (string-to-number (match-string 1 s))))
16144 (setq s (replace-match "" nil t s)))
16145 (incf result (org-hh:mm-string-to-minutes s))
16146 result))
16148 ;;;; Files
16150 (defun org-save-all-org-buffers ()
16151 "Save all Org-mode buffers without user confirmation."
16152 (interactive)
16153 (message "Saving all Org-mode buffers...")
16154 (save-some-buffers t (lambda () (eq major-mode 'org-mode)))
16155 (when (featurep 'org-id) (org-id-locations-save))
16156 (message "Saving all Org-mode buffers... done"))
16158 (defun org-revert-all-org-buffers ()
16159 "Revert all Org-mode buffers.
16160 Prompt for confirmation when there are unsaved changes.
16161 Be sure you know what you are doing before letting this function
16162 overwrite your changes.
16164 This function is useful in a setup where one tracks org files
16165 with a version control system, to revert on one machine after pulling
16166 changes from another. I believe the procedure must be like this:
16168 1. M-x org-save-all-org-buffers
16169 2. Pull changes from the other machine, resolve conflicts
16170 3. M-x org-revert-all-org-buffers"
16171 (interactive)
16172 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16173 (error "Abort"))
16174 (save-excursion
16175 (save-window-excursion
16176 (mapc
16177 (lambda (b)
16178 (when (and (with-current-buffer b (eq major-mode 'org-mode))
16179 (with-current-buffer b buffer-file-name))
16180 (org-pop-to-buffer-same-window b)
16181 (revert-buffer t 'no-confirm)))
16182 (buffer-list))
16183 (when (and (featurep 'org-id) org-id-track-globally)
16184 (org-id-locations-load)))))
16186 ;;;; Agenda files
16188 ;;;###autoload
16189 (defun org-switchb (&optional arg)
16190 "Switch between Org buffers.
16191 With one prefix argument, restrict available buffers to files.
16192 With two prefix arguments, restrict available buffers to agenda files.
16194 Defaults to `iswitchb' for buffer name completion.
16195 Set `org-completion-use-ido' to make it use ido instead."
16196 (interactive "P")
16197 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16198 ((equal arg '(16)) (org-buffer-list 'agenda))
16199 (t (org-buffer-list))))
16200 (org-completion-use-iswitchb org-completion-use-iswitchb)
16201 (org-completion-use-ido org-completion-use-ido))
16202 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16203 (setq org-completion-use-iswitchb t))
16204 (org-pop-to-buffer-same-window
16205 (org-icompleting-read "Org buffer: "
16206 (mapcar 'list (mapcar 'buffer-name blist))
16207 nil t))))
16209 ;;; Define some older names previously used for this functionality
16210 ;;;###autoload
16211 (defalias 'org-ido-switchb 'org-switchb)
16212 ;;;###autoload
16213 (defalias 'org-iswitchb 'org-switchb)
16215 (defun org-buffer-list (&optional predicate exclude-tmp)
16216 "Return a list of Org buffers.
16217 PREDICATE can be `export', `files' or `agenda'.
16219 export restrict the list to Export buffers.
16220 files restrict the list to buffers visiting Org files.
16221 agenda restrict the list to buffers visiting agenda files.
16223 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16224 (let* ((bfn nil)
16225 (agenda-files (and (eq predicate 'agenda)
16226 (mapcar 'file-truename (org-agenda-files t))))
16227 (filter
16228 (cond
16229 ((eq predicate 'files)
16230 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
16231 ((eq predicate 'export)
16232 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16233 ((eq predicate 'agenda)
16234 (lambda (b)
16235 (with-current-buffer b
16236 (and (eq major-mode 'org-mode)
16237 (setq bfn (buffer-file-name b))
16238 (member (file-truename bfn) agenda-files)))))
16239 (t (lambda (b) (with-current-buffer b
16240 (or (eq major-mode 'org-mode)
16241 (string-match "\*Org .*Export"
16242 (buffer-name b)))))))))
16243 (delq nil
16244 (mapcar
16245 (lambda(b)
16246 (if (and (funcall filter b)
16247 (or (not exclude-tmp)
16248 (not (string-match "tmp" (buffer-name b)))))
16250 nil))
16251 (buffer-list)))))
16253 (defun org-agenda-files (&optional unrestricted archives)
16254 "Get the list of agenda files.
16255 Optional UNRESTRICTED means return the full list even if a restriction
16256 is currently in place.
16257 When ARCHIVES is t, include all archive files that are really being
16258 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16259 `org-agenda-archives-mode' is t."
16260 (let ((files
16261 (cond
16262 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16263 ((stringp org-agenda-files) (org-read-agenda-file-list))
16264 ((listp org-agenda-files) org-agenda-files)
16265 (t (error "Invalid value of `org-agenda-files'")))))
16266 (setq files (apply 'append
16267 (mapcar (lambda (f)
16268 (if (file-directory-p f)
16269 (directory-files
16270 f t org-agenda-file-regexp)
16271 (list f)))
16272 files)))
16273 (when org-agenda-skip-unavailable-files
16274 (setq files (delq nil
16275 (mapcar (function
16276 (lambda (file)
16277 (and (file-readable-p file) file)))
16278 files))))
16279 (when (or (eq archives t)
16280 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16281 (setq files (org-add-archive-files files)))
16282 files))
16284 (defun org-agenda-file-p (&optional file)
16285 "Return non-nil, if FILE is an agenda file.
16286 If FILE is omitted, use the file associated with the current
16287 buffer."
16288 (member (or file (buffer-file-name))
16289 (org-agenda-files t)))
16291 (defun org-edit-agenda-file-list ()
16292 "Edit the list of agenda files.
16293 Depending on setup, this either uses customize to edit the variable
16294 `org-agenda-files', or it visits the file that is holding the list. In the
16295 latter case, the buffer is set up in a way that saving it automatically kills
16296 the buffer and restores the previous window configuration."
16297 (interactive)
16298 (if (stringp org-agenda-files)
16299 (let ((cw (current-window-configuration)))
16300 (find-file org-agenda-files)
16301 (org-set-local 'org-window-configuration cw)
16302 (org-add-hook 'after-save-hook
16303 (lambda ()
16304 (set-window-configuration
16305 (prog1 org-window-configuration
16306 (kill-buffer (current-buffer))))
16307 (org-install-agenda-files-menu)
16308 (message "New agenda file list installed"))
16309 nil 'local)
16310 (message "%s" (substitute-command-keys
16311 "Edit list and finish with \\[save-buffer]")))
16312 (customize-variable 'org-agenda-files)))
16314 (defun org-store-new-agenda-file-list (list)
16315 "Set new value for the agenda file list and save it correctly."
16316 (if (stringp org-agenda-files)
16317 (let ((fe (org-read-agenda-file-list t)) b u)
16318 (while (setq b (find-buffer-visiting org-agenda-files))
16319 (kill-buffer b))
16320 (with-temp-file org-agenda-files
16321 (insert
16322 (mapconcat
16323 (lambda (f) ;; Keep un-expanded entries.
16324 (if (setq u (assoc f fe))
16325 (cdr u)
16327 list "\n")
16328 "\n")))
16329 (let ((org-mode-hook nil) (org-inhibit-startup t)
16330 (org-insert-mode-line-in-empty-file nil))
16331 (setq org-agenda-files list)
16332 (customize-save-variable 'org-agenda-files org-agenda-files))))
16334 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16335 "Read the list of agenda files from a file.
16336 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16337 filenames, used by `org-store-new-agenda-file-list' to write back
16338 un-expanded file names."
16339 (when (file-directory-p org-agenda-files)
16340 (error "`org-agenda-files' cannot be a single directory"))
16341 (when (stringp org-agenda-files)
16342 (with-temp-buffer
16343 (insert-file-contents org-agenda-files)
16344 (mapcar
16345 (lambda (f)
16346 (let ((e (expand-file-name (substitute-in-file-name f)
16347 org-directory)))
16348 (if pair-with-expansion
16349 (cons e f)
16350 e)))
16351 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16353 ;;;###autoload
16354 (defun org-cycle-agenda-files ()
16355 "Cycle through the files in `org-agenda-files'.
16356 If the current buffer visits an agenda file, find the next one in the list.
16357 If the current buffer does not, find the first agenda file."
16358 (interactive)
16359 (let* ((fs (org-agenda-files t))
16360 (files (append fs (list (car fs))))
16361 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16362 file)
16363 (unless files (error "No agenda files"))
16364 (catch 'exit
16365 (while (setq file (pop files))
16366 (if (equal (file-truename file) tcf)
16367 (when (car files)
16368 (find-file (car files))
16369 (throw 'exit t))))
16370 (find-file (car fs)))
16371 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16373 (defun org-agenda-file-to-front (&optional to-end)
16374 "Move/add the current file to the top of the agenda file list.
16375 If the file is not present in the list, it is added to the front. If it is
16376 present, it is moved there. With optional argument TO-END, add/move to the
16377 end of the list."
16378 (interactive "P")
16379 (let ((org-agenda-skip-unavailable-files nil)
16380 (file-alist (mapcar (lambda (x)
16381 (cons (file-truename x) x))
16382 (org-agenda-files t)))
16383 (ctf (file-truename buffer-file-name))
16384 x had)
16385 (setq x (assoc ctf file-alist) had x)
16387 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16388 (if to-end
16389 (setq file-alist (append (delq x file-alist) (list x)))
16390 (setq file-alist (cons x (delq x file-alist))))
16391 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16392 (org-install-agenda-files-menu)
16393 (message "File %s to %s of agenda file list"
16394 (if had "moved" "added") (if to-end "end" "front"))))
16396 (defun org-remove-file (&optional file)
16397 "Remove current file from the list of files in variable `org-agenda-files'.
16398 These are the files which are being checked for agenda entries.
16399 Optional argument FILE means use this file instead of the current."
16400 (interactive)
16401 (let* ((org-agenda-skip-unavailable-files nil)
16402 (file (or file buffer-file-name))
16403 (true-file (file-truename file))
16404 (afile (abbreviate-file-name file))
16405 (files (delq nil (mapcar
16406 (lambda (x)
16407 (if (equal true-file
16408 (file-truename x))
16409 nil x))
16410 (org-agenda-files t)))))
16411 (if (not (= (length files) (length (org-agenda-files t))))
16412 (progn
16413 (org-store-new-agenda-file-list files)
16414 (org-install-agenda-files-menu)
16415 (message "Removed file: %s" afile))
16416 (message "File was not in list: %s (not removed)" afile))))
16418 (defun org-file-menu-entry (file)
16419 (vector file (list 'find-file file) t))
16421 (defun org-check-agenda-file (file)
16422 "Make sure FILE exists. If not, ask user what to do."
16423 (when (not (file-exists-p file))
16424 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16425 (abbreviate-file-name file))
16426 (let ((r (downcase (read-char-exclusive))))
16427 (cond
16428 ((equal r ?r)
16429 (org-remove-file file)
16430 (throw 'nextfile t))
16431 (t (error "Abort"))))))
16433 (defun org-get-agenda-file-buffer (file)
16434 "Get a buffer visiting FILE. If the buffer needs to be created, add
16435 it to the list of buffers which might be released later."
16436 (let ((buf (org-find-base-buffer-visiting file)))
16437 (if buf
16438 buf ; just return it
16439 ;; Make a new buffer and remember it
16440 (setq buf (find-file-noselect file))
16441 (if buf (push buf org-agenda-new-buffers))
16442 buf)))
16444 (defun org-release-buffers (blist)
16445 "Release all buffers in list, asking the user for confirmation when needed.
16446 When a buffer is unmodified, it is just killed. When modified, it is saved
16447 \(if the user agrees) and then killed."
16448 (let (buf file)
16449 (while (setq buf (pop blist))
16450 (setq file (buffer-file-name buf))
16451 (when (and (buffer-modified-p buf)
16452 file
16453 (y-or-n-p (format "Save file %s? " file)))
16454 (with-current-buffer buf (save-buffer)))
16455 (kill-buffer buf))))
16457 (defun org-prepare-agenda-buffers (files)
16458 "Create buffers for all agenda files, protect archived trees and comments."
16459 (interactive)
16460 (let ((pa '(:org-archived t))
16461 (pc '(:org-comment t))
16462 (pall '(:org-archived t :org-comment t))
16463 (inhibit-read-only t)
16464 (rea (concat ":" org-archive-tag ":"))
16465 bmp file re)
16466 (save-excursion
16467 (while (setq file (pop files))
16468 (catch 'nextfile
16469 (if (bufferp file)
16470 (set-buffer file)
16471 (org-check-agenda-file file)
16472 (set-buffer (org-get-agenda-file-buffer file)))
16473 (save-restriction
16474 (widen)
16475 (setq bmp (buffer-modified-p))
16476 (org-refresh-category-properties)
16477 (setq org-todo-keywords-for-agenda
16478 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16479 (setq org-done-keywords-for-agenda
16480 (append org-done-keywords-for-agenda org-done-keywords))
16481 (setq org-todo-keyword-alist-for-agenda
16482 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16483 (setq org-drawers-for-agenda
16484 (append org-drawers-for-agenda org-drawers))
16485 (setq org-tag-alist-for-agenda
16486 (append org-tag-alist-for-agenda org-tag-alist))
16488 (save-excursion
16489 (remove-text-properties (point-min) (point-max) pall)
16490 (when org-agenda-skip-archived-trees
16491 (goto-char (point-min))
16492 (while (re-search-forward rea nil t)
16493 (if (org-on-heading-p t)
16494 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16495 (goto-char (point-min))
16496 (setq re (format org-heading-keyword-regexp-format
16497 org-comment-string))
16498 (while (re-search-forward re nil t)
16499 (add-text-properties
16500 (match-beginning 0) (org-end-of-subtree t) pc)))
16501 (set-buffer-modified-p bmp)))))
16502 (setq org-todo-keywords-for-agenda
16503 (org-uniquify org-todo-keywords-for-agenda))
16504 (setq org-todo-keyword-alist-for-agenda
16505 (org-uniquify org-todo-keyword-alist-for-agenda)
16506 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16508 ;;;; Embedded LaTeX
16510 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16511 "Keymap for the minor `org-cdlatex-mode'.")
16513 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16514 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16515 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16516 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16517 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16519 (defvar org-cdlatex-texmathp-advice-is-done nil
16520 "Flag remembering if we have applied the advice to texmathp already.")
16522 (define-minor-mode org-cdlatex-mode
16523 "Toggle the minor `org-cdlatex-mode'.
16524 This mode supports entering LaTeX environment and math in LaTeX fragments
16525 in Org-mode.
16526 \\{org-cdlatex-mode-map}"
16527 nil " OCDL" nil
16528 (when org-cdlatex-mode
16529 (require 'cdlatex)
16530 (run-hooks 'cdlatex-mode-hook)
16531 (cdlatex-compute-tables))
16532 (unless org-cdlatex-texmathp-advice-is-done
16533 (setq org-cdlatex-texmathp-advice-is-done t)
16534 (defadvice texmathp (around org-math-always-on activate)
16535 "Always return t in org-mode buffers.
16536 This is because we want to insert math symbols without dollars even outside
16537 the LaTeX math segments. If Orgmode thinks that point is actually inside
16538 an embedded LaTeX fragment, let texmathp do its job.
16539 \\[org-cdlatex-mode-map]"
16540 (interactive)
16541 (let (p)
16542 (cond
16543 ((not (eq major-mode 'org-mode)) ad-do-it)
16544 ((eq this-command 'cdlatex-math-symbol)
16545 (setq ad-return-value t
16546 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16548 (let ((p (org-inside-LaTeX-fragment-p)))
16549 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16550 (setq ad-return-value t
16551 texmathp-why '("Org-mode embedded math" . 0))
16552 (if p ad-do-it)))))))))
16554 (defun turn-on-org-cdlatex ()
16555 "Unconditionally turn on `org-cdlatex-mode'."
16556 (org-cdlatex-mode 1))
16558 (defun org-inside-LaTeX-fragment-p ()
16559 "Test if point is inside a LaTeX fragment.
16560 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16561 sequence appearing also before point.
16562 Even though the matchers for math are configurable, this function assumes
16563 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16564 delimiters are skipped when they have been removed by customization.
16565 The return value is nil, or a cons cell with the delimiter and the
16566 position of this delimiter.
16568 This function does a reasonably good job, but can locally be fooled by
16569 for example currency specifications. For example it will assume being in
16570 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16571 fragments that are properly closed, but during editing, we have to live
16572 with the uncertainty caused by missing closing delimiters. This function
16573 looks only before point, not after."
16574 (catch 'exit
16575 (let ((pos (point))
16576 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16577 (lim (progn
16578 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16579 (point)))
16580 dd-on str (start 0) m re)
16581 (goto-char pos)
16582 (when dodollar
16583 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16584 re (nth 1 (assoc "$" org-latex-regexps)))
16585 (while (string-match re str start)
16586 (cond
16587 ((= (match-end 0) (length str))
16588 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16589 ((= (match-end 0) (- (length str) 5))
16590 (throw 'exit nil))
16591 (t (setq start (match-end 0))))))
16592 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16593 (goto-char pos)
16594 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16595 (and (match-beginning 2) (throw 'exit nil))
16596 ;; count $$
16597 (while (re-search-backward "\\$\\$" lim t)
16598 (setq dd-on (not dd-on)))
16599 (goto-char pos)
16600 (if dd-on (cons "$$" m))))))
16602 (defun org-inside-latex-macro-p ()
16603 "Is point inside a LaTeX macro or its arguments?"
16604 (save-match-data
16605 (org-in-regexp
16606 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16608 (defun org-try-cdlatex-tab ()
16609 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16610 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16611 - inside a LaTeX fragment, or
16612 - after the first word in a line, where an abbreviation expansion could
16613 insert a LaTeX environment."
16614 (when org-cdlatex-mode
16615 (cond
16616 ;; Before any word on the line: No expansion possible.
16617 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
16618 ;; Just after first word on the line: Expand it. Make sure it
16619 ;; cannot happen on headlines, though.
16620 ((save-excursion
16621 (skip-chars-backward "a-zA-Z0-9*")
16622 (skip-chars-backward " \t")
16623 (and (bolp) (not (org-at-heading-p))))
16624 (cdlatex-tab) t)
16625 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
16627 (defun org-cdlatex-underscore-caret (&optional arg)
16628 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16629 Revert to the normal definition outside of these fragments."
16630 (interactive "P")
16631 (if (org-inside-LaTeX-fragment-p)
16632 (call-interactively 'cdlatex-sub-superscript)
16633 (let (org-cdlatex-mode)
16634 (call-interactively (key-binding (vector last-input-event))))))
16636 (defun org-cdlatex-math-modify (&optional arg)
16637 "Execute `cdlatex-math-modify' in LaTeX fragments.
16638 Revert to the normal definition outside of these fragments."
16639 (interactive "P")
16640 (if (org-inside-LaTeX-fragment-p)
16641 (call-interactively 'cdlatex-math-modify)
16642 (let (org-cdlatex-mode)
16643 (call-interactively (key-binding (vector last-input-event))))))
16645 (defvar org-latex-fragment-image-overlays nil
16646 "List of overlays carrying the images of latex fragments.")
16647 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16649 (defun org-remove-latex-fragment-image-overlays ()
16650 "Remove all overlays with LaTeX fragment images in current buffer."
16651 (mapc 'delete-overlay org-latex-fragment-image-overlays)
16652 (setq org-latex-fragment-image-overlays nil))
16654 (defun org-preview-latex-fragment (&optional subtree)
16655 "Preview the LaTeX fragment at point, or all locally or globally.
16656 If the cursor is in a LaTeX fragment, create the image and overlay
16657 it over the source code. If there is no fragment at point, display
16658 all fragments in the current text, from one headline to the next. With
16659 prefix SUBTREE, display all fragments in the current subtree. With a
16660 double prefix arg \\[universal-argument] \\[universal-argument], or when \
16661 the cursor is before the first headline,
16662 display all fragments in the buffer.
16663 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16664 (interactive "P")
16665 (org-remove-latex-fragment-image-overlays)
16666 (save-excursion
16667 (save-restriction
16668 (let (beg end at msg)
16669 (cond
16670 ((or (equal subtree '(16))
16671 (not (save-excursion
16672 (re-search-backward org-outline-regexp-bol nil t))))
16673 (setq beg (point-min) end (point-max)
16674 msg "Creating images for buffer...%s"))
16675 ((equal subtree '(4))
16676 (org-back-to-heading)
16677 (setq beg (point) end (org-end-of-subtree t)
16678 msg "Creating images for subtree...%s"))
16680 (if (setq at (org-inside-LaTeX-fragment-p))
16681 (goto-char (max (point-min) (- (cdr at) 2)))
16682 (org-back-to-heading))
16683 (setq beg (point) end (progn (outline-next-heading) (point))
16684 msg (if at "Creating image...%s"
16685 "Creating images for entry...%s"))))
16686 (message msg "")
16687 (narrow-to-region beg end)
16688 (goto-char beg)
16689 (org-format-latex
16690 (concat "ltxpng/" (file-name-sans-extension
16691 (file-name-nondirectory
16692 buffer-file-name)))
16693 default-directory 'overlays msg at 'forbuffer 'dvipng)
16694 (message msg "done. Use `C-c C-c' to remove images.")))))
16696 (defvar org-latex-regexps
16697 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16698 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16699 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16700 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16701 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16702 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16703 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
16704 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
16705 "Regular expressions for matching embedded LaTeX.")
16707 (defvar org-export-have-math nil) ;; dynamic scoping
16708 (defun org-format-latex (prefix &optional dir overlays msg at
16709 forbuffer processing-type)
16710 "Replace LaTeX fragments with links to an image, and produce images.
16711 Some of the options can be changed using the variable
16712 `org-format-latex-options'."
16713 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16714 (let* ((prefixnodir (file-name-nondirectory prefix))
16715 (absprefix (expand-file-name prefix dir))
16716 (todir (file-name-directory absprefix))
16717 (opt org-format-latex-options)
16718 (matchers (plist-get opt :matchers))
16719 (re-list org-latex-regexps)
16720 (org-format-latex-header-extra
16721 (plist-get (org-infile-export-plist) :latex-header-extra))
16722 (cnt 0) txt hash link beg end re e checkdir
16723 executables-checked string
16724 m n block-type block linkfile movefile ov)
16725 ;; Check the different regular expressions
16726 (while (setq e (pop re-list))
16727 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
16728 block (if block-type "\n\n" ""))
16729 (when (member m matchers)
16730 (goto-char (point-min))
16731 (while (re-search-forward re nil t)
16732 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
16733 (not (get-text-property (match-beginning n)
16734 'org-protected))
16735 (or (not overlays)
16736 (not (eq (get-char-property (match-beginning n)
16737 'org-overlay-type)
16738 'org-latex-overlay))))
16739 (setq org-export-have-math t)
16740 (cond
16741 ((eq processing-type 'verbatim)
16742 ;; Leave the text verbatim, just protect it
16743 (add-text-properties (match-beginning n) (match-end n)
16744 '(org-protected t)))
16745 ((eq processing-type 'mathjax)
16746 ;; Prepare for MathJax processing
16747 (setq string (match-string n))
16748 (if (member m '("$" "$1"))
16749 (save-excursion
16750 (delete-region (match-beginning n) (match-end n))
16751 (goto-char (match-beginning n))
16752 (insert (org-add-props (concat "\\(" (substring string 1 -1)
16753 "\\)")
16754 '(org-protected t))))
16755 (add-text-properties (match-beginning n) (match-end n)
16756 '(org-protected t))))
16757 ((eq processing-type 'dvipng)
16758 ;; Process to an image
16759 (setq txt (match-string n)
16760 beg (match-beginning n) end (match-end n)
16761 cnt (1+ cnt))
16762 (let (print-length print-level) ; make sure full list is printed
16763 (setq hash (sha1 (prin1-to-string
16764 (list org-format-latex-header
16765 org-format-latex-header-extra
16766 org-export-latex-default-packages-alist
16767 org-export-latex-packages-alist
16768 org-format-latex-options
16769 forbuffer txt)))
16770 linkfile (format "%s_%s.png" prefix hash)
16771 movefile (format "%s_%s.png" absprefix hash)))
16772 (setq link (concat block "[[file:" linkfile "]]" block))
16773 (if msg (message msg cnt))
16774 (goto-char beg)
16775 (unless checkdir ; make sure the directory exists
16776 (setq checkdir t)
16777 (or (file-directory-p todir) (make-directory todir t)))
16779 (unless executables-checked
16780 (org-check-external-command
16781 "latex" "needed to convert LaTeX fragments to images")
16782 (org-check-external-command
16783 "dvipng" "needed to convert LaTeX fragments to images")
16784 (setq executables-checked t))
16786 (unless (file-exists-p movefile)
16787 (org-create-formula-image
16788 txt movefile opt forbuffer))
16789 (if overlays
16790 (progn
16791 (mapc (lambda (o)
16792 (if (eq (overlay-get o 'org-overlay-type)
16793 'org-latex-overlay)
16794 (delete-overlay o)))
16795 (overlays-in beg end))
16796 (setq ov (make-overlay beg end))
16797 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
16798 (if (featurep 'xemacs)
16799 (progn
16800 (overlay-put ov 'invisible t)
16801 (overlay-put
16802 ov 'end-glyph
16803 (make-glyph (vector 'png :file movefile))))
16804 (overlay-put
16805 ov 'display
16806 (list 'image :type 'png :file movefile :ascent 'center)))
16807 (push ov org-latex-fragment-image-overlays)
16808 (goto-char end))
16809 (delete-region beg end)
16810 (insert (org-add-props link
16811 (list 'org-latex-src
16812 (replace-regexp-in-string
16813 "\"" "" txt)
16814 'org-latex-src-embed-type
16815 (if block-type 'paragraph 'character))))))
16816 ((eq processing-type 'mathml)
16817 ;; Process to MathML
16818 (unless executables-checked
16819 (unless (save-match-data (org-format-latex-mathml-available-p))
16820 (error "LaTeX to MathML converter not configured"))
16821 (setq executables-checked t))
16822 (setq txt (match-string n)
16823 beg (match-beginning n) end (match-end n)
16824 cnt (1+ cnt))
16825 (if msg (message msg cnt))
16826 (goto-char beg)
16827 (delete-region beg end)
16828 (insert (org-format-latex-as-mathml
16829 txt block-type prefix dir)))
16831 (error "Unknown conversion type %s for latex fragments"
16832 processing-type)))))))))
16834 (defun org-create-math-formula (latex-frag &optional mathml-file)
16835 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
16836 Use `org-latex-to-mathml-convert-command'. If the conversion is
16837 sucessful, return the portion between \"<math...> </math>\"
16838 elements otherwise return nil. When MATHML-FILE is specified,
16839 write the results in to that file. When invoked as an
16840 interactive command, prompt for LATEX-FRAG, with initial value
16841 set to the current active region and echo the results for user
16842 inspection."
16843 (interactive (list (let ((frag (when (region-active-p)
16844 (buffer-substring-no-properties
16845 (region-beginning) (region-end)))))
16846 (read-string "LaTeX Fragment: " frag nil frag))))
16847 (unless latex-frag (error "Invalid latex-frag"))
16848 (let* ((tmp-in-file (file-relative-name
16849 (make-temp-name (expand-file-name "ltxmathml-in"))))
16850 (ignore (write-region latex-frag nil tmp-in-file))
16851 (tmp-out-file (file-relative-name
16852 (make-temp-name (expand-file-name "ltxmathml-out"))))
16853 (cmd (format-spec
16854 org-latex-to-mathml-convert-command
16855 `((?j . ,(shell-quote-argument
16856 (expand-file-name org-latex-to-mathml-jar-file)))
16857 (?I . ,(shell-quote-argument tmp-in-file))
16858 (?o . ,(shell-quote-argument tmp-out-file)))))
16859 mathml shell-command-output)
16860 (when (org-called-interactively-p 'any)
16861 (unless (org-format-latex-mathml-available-p)
16862 (error "LaTeX to MathML converter not configured")))
16863 (message "Running %s" cmd)
16864 (setq shell-command-output (shell-command-to-string cmd))
16865 (setq mathml
16866 (when (file-readable-p tmp-out-file)
16867 (with-current-buffer (find-file-noselect tmp-out-file t)
16868 (goto-char (point-min))
16869 (when (re-search-forward
16870 (concat
16871 (regexp-quote
16872 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
16873 "\\(.\\|\n\\)*"
16874 (regexp-quote "</math>")) nil t)
16875 (prog1 (match-string 0) (kill-buffer))))))
16876 (cond
16877 (mathml
16878 (setq mathml
16879 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
16880 (when mathml-file
16881 (write-region mathml nil mathml-file))
16882 (when (org-called-interactively-p 'any)
16883 (message mathml)))
16884 ((message "LaTeX to MathML conversion failed")
16885 (message shell-command-output)))
16886 (delete-file tmp-in-file)
16887 (when (file-exists-p tmp-out-file)
16888 (delete-file tmp-out-file))
16889 mathml))
16891 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
16892 prefix &optional dir)
16893 "Use `org-create-math-formula' but check local cache first."
16894 (let* ((absprefix (expand-file-name prefix dir))
16895 (print-length nil) (print-level nil)
16896 (formula-id (concat
16897 "formula-"
16898 (sha1
16899 (prin1-to-string
16900 (list latex-frag
16901 org-latex-to-mathml-convert-command)))))
16902 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
16903 (formula-cache-dir (file-name-directory formula-cache)))
16905 (unless (file-directory-p formula-cache-dir)
16906 (make-directory formula-cache-dir t))
16908 (unless (file-exists-p formula-cache)
16909 (org-create-math-formula latex-frag formula-cache))
16911 (if (file-exists-p formula-cache)
16912 ;; Successful conversion. Return the link to MathML file.
16913 (org-add-props
16914 (format "[[file:%s]]" (file-relative-name formula-cache dir))
16915 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
16916 'org-latex-src-embed-type (if latex-frag-type
16917 'paragraph 'character)))
16918 ;; Failed conversion. Return the LaTeX fragment verbatim
16919 (add-text-properties
16920 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
16921 latex-frag)))
16923 ;; This function borrows from Ganesh Swami's latex2png.el
16924 (defun org-create-formula-image (string tofile options buffer)
16925 "This calls dvipng."
16926 (require 'org-latex)
16927 (let* ((tmpdir (if (featurep 'xemacs)
16928 (temp-directory)
16929 temporary-file-directory))
16930 (texfilebase (make-temp-name
16931 (expand-file-name "orgtex" tmpdir)))
16932 (texfile (concat texfilebase ".tex"))
16933 (dvifile (concat texfilebase ".dvi"))
16934 (pngfile (concat texfilebase ".png"))
16935 (fnh (if (featurep 'xemacs)
16936 (font-height (get-face-font 'default))
16937 (face-attribute 'default :height nil)))
16938 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
16939 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
16940 (fg (or (plist-get options (if buffer :foreground :html-foreground))
16941 "Black"))
16942 (bg (or (plist-get options (if buffer :background :html-background))
16943 "Transparent")))
16944 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
16945 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
16946 (with-temp-file texfile
16947 (insert (org-splice-latex-header
16948 org-format-latex-header
16949 org-export-latex-default-packages-alist
16950 org-export-latex-packages-alist t
16951 org-format-latex-header-extra))
16952 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
16953 (require 'org-latex)
16954 (org-export-latex-fix-inputenc))
16955 (let ((dir default-directory))
16956 (condition-case nil
16957 (progn
16958 (cd tmpdir)
16959 (call-process "latex" nil nil nil texfile))
16960 (error nil))
16961 (cd dir))
16962 (if (not (file-exists-p dvifile))
16963 (progn (message "Failed to create dvi file from %s" texfile) nil)
16964 (condition-case nil
16965 (call-process "dvipng" nil nil nil
16966 "-fg" fg "-bg" bg
16967 "-D" dpi
16968 ;;"-x" scale "-y" scale
16969 "-T" "tight"
16970 "-o" pngfile
16971 dvifile)
16972 (error nil))
16973 (if (not (file-exists-p pngfile))
16974 (if org-format-latex-signal-error
16975 (error "Failed to create png file from %s" texfile)
16976 (message "Failed to create png file from %s" texfile)
16977 nil)
16978 ;; Use the requested file name and clean up
16979 (copy-file pngfile tofile 'replace)
16980 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
16981 (delete-file (concat texfilebase e)))
16982 pngfile))))
16984 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
16985 "Fill a LaTeX header template TPL.
16986 In the template, the following place holders will be recognized:
16988 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
16989 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
16990 [PACKAGES] \\usepackage statements for PKG
16991 [NO-PACKAGES] do not include PKG
16992 [EXTRA] the string EXTRA
16993 [NO-EXTRA] do not include EXTRA
16995 For backward compatibility, if both the positive and the negative place
16996 holder is missing, the positive one (without the \"NO-\") will be
16997 assumed to be present at the end of the template.
16998 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
16999 EXTRA is a string.
17000 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17001 (let (rpl (end ""))
17002 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17003 (setq rpl (if (or (match-end 1) (not def-pkg))
17004 "" (org-latex-packages-to-string def-pkg snippets-p t))
17005 tpl (replace-match rpl t t tpl))
17006 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17008 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17009 (setq rpl (if (or (match-end 1) (not pkg))
17010 "" (org-latex-packages-to-string pkg snippets-p t))
17011 tpl (replace-match rpl t t tpl))
17012 (if pkg (setq end
17013 (concat end "\n"
17014 (org-latex-packages-to-string pkg snippets-p)))))
17016 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17017 (setq rpl (if (or (match-end 1) (not extra))
17018 "" (concat extra "\n"))
17019 tpl (replace-match rpl t t tpl))
17020 (if (and extra (string-match "\\S-" extra))
17021 (setq end (concat end "\n" extra))))
17023 (if (string-match "\\S-" end)
17024 (concat tpl "\n" end)
17025 tpl)))
17027 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17028 "Turn an alist of packages into a string with the \\usepackage macros."
17029 (setq pkg (mapconcat (lambda(p)
17030 (cond
17031 ((stringp p) p)
17032 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17033 (format "%% Package %s omitted" (cadr p)))
17034 ((equal "" (car p))
17035 (format "\\usepackage{%s}" (cadr p)))
17037 (format "\\usepackage[%s]{%s}"
17038 (car p) (cadr p)))))
17040 "\n"))
17041 (if newline (concat pkg "\n") pkg))
17043 (defun org-dvipng-color (attr)
17044 "Return an rgb color specification for dvipng."
17045 (apply 'format "rgb %s %s %s"
17046 (mapcar 'org-normalize-color
17047 (color-values (face-attribute 'default attr nil)))))
17049 (defun org-normalize-color (value)
17050 "Return string to be used as color value for an RGB component."
17051 (format "%g" (/ value 65535.0)))
17053 ;; Image display
17056 (defvar org-inline-image-overlays nil)
17057 (make-variable-buffer-local 'org-inline-image-overlays)
17059 (defun org-toggle-inline-images (&optional include-linked)
17060 "Toggle the display of inline images.
17061 INCLUDE-LINKED is passed to `org-display-inline-images'."
17062 (interactive "P")
17063 (if org-inline-image-overlays
17064 (progn
17065 (org-remove-inline-images)
17066 (message "Inline image display turned off"))
17067 (org-display-inline-images include-linked)
17068 (if org-inline-image-overlays
17069 (message "%d images displayed inline"
17070 (length org-inline-image-overlays))
17071 (message "No images to display inline"))))
17073 (defun org-display-inline-images (&optional include-linked refresh beg end)
17074 "Display inline images.
17075 Normally only links without a description part are inlined, because this
17076 is how it will work for export. When INCLUDE-LINKED is set, also links
17077 with a description part will be inlined. This can be nice for a quick
17078 look at those images, but it does not reflect what exported files will look
17079 like.
17080 When REFRESH is set, refresh existing images between BEG and END.
17081 This will create new image displays only if necessary.
17082 BEG and END default to the buffer boundaries."
17083 (interactive "P")
17084 (unless refresh
17085 (org-remove-inline-images)
17086 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17087 (save-excursion
17088 (save-restriction
17089 (widen)
17090 (setq beg (or beg (point-min)) end (or end (point-max)))
17091 (goto-char (point-min))
17092 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17093 (substring (org-image-file-name-regexp) 0 -2)
17094 "\\)\\]" (if include-linked "" "\\]")))
17095 old file ov img)
17096 (while (re-search-forward re end t)
17097 (setq old (get-char-property-and-overlay (match-beginning 1)
17098 'org-image-overlay))
17099 (setq file (expand-file-name
17100 (concat (or (match-string 3) "") (match-string 4))))
17101 (when (file-exists-p file)
17102 (if (and (car-safe old) refresh)
17103 (image-refresh (overlay-get (cdr old) 'display))
17104 (setq img (save-match-data (create-image file)))
17105 (when img
17106 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17107 (overlay-put ov 'display img)
17108 (overlay-put ov 'face 'default)
17109 (overlay-put ov 'org-image-overlay t)
17110 (overlay-put ov 'modification-hooks
17111 (list 'org-display-inline-modification-hook))
17112 (push ov org-inline-image-overlays)))))))))
17114 (defun org-display-inline-modification-hook (ov after beg end &optional len)
17115 "Remove inline-display overlay if a corresponding region is modified."
17116 (let ((inhibit-modification-hooks t))
17117 (when (and ov after)
17118 (delete ov org-inline-image-overlays)
17119 (delete-overlay ov))))
17121 (defun org-remove-inline-images ()
17122 "Remove inline display of images."
17123 (interactive)
17124 (mapc 'delete-overlay org-inline-image-overlays)
17125 (setq org-inline-image-overlays nil))
17127 ;;;; Key bindings
17129 ;; Outline functions from `outline-mode-prefix-map'
17130 ;; that can be remapped in Org:
17131 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17132 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17133 (define-key org-mode-map [remap outline-forward-same-level]
17134 'org-forward-same-level)
17135 (define-key org-mode-map [remap outline-backward-same-level]
17136 'org-backward-same-level)
17137 (define-key org-mode-map [remap show-branches]
17138 'org-kill-note-or-show-branches)
17139 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17140 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17141 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17143 ;; Outline functions from `outline-mode-prefix-map'
17144 ;; that can not be remapped in Org:
17145 ;; - the column "key binding" shows whether the Outline function is still
17146 ;; available in Org mode on the same key that it has been bound to in
17147 ;; Outline mode:
17148 ;; - "overridden": key used for a different functionality in Org mode
17149 ;; - else: key still bound to the same Outline function in Org mode
17150 ;; | Outline function | key binding | Org replacement |
17151 ;; |------------------------------------+-------------+-----------------------|
17152 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17153 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17154 ;; | `show-children' | `C-c C-i' | visibility cycling |
17155 ;; | `hide-subtree' | overridden | visibility cycling |
17156 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17157 ;; | `hide-body' | overridden | no replacement |
17158 ;; | `show-all' | overridden | no replacement |
17159 ;; | `hide-entry' | overridden | visibility cycling |
17160 ;; | `show-entry' | overridden | no replacement |
17161 ;; | `hide-leaves' | overridden | no replacement |
17162 ;; | `hide-sublevels' | overridden | no replacement |
17163 ;; | `hide-other' | overridden | no replacement |
17164 ;; | `outline-move-subtree-up' | `C-c C-^' | better: org-shiftup |
17165 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17167 ;; Make `C-c C-x' a prefix key
17168 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17170 ;; TAB key with modifiers
17171 (org-defkey org-mode-map "\C-i" 'org-cycle)
17172 (org-defkey org-mode-map [(tab)] 'org-cycle)
17173 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17174 (org-defkey org-mode-map [(meta tab)] 'pcomplete)
17175 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17176 (org-defkey org-mode-map "\M-\C-i" 'pcomplete)
17177 ;; The following line is necessary under Suse GNU/Linux
17178 (unless (featurep 'xemacs)
17179 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17180 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17181 (define-key org-mode-map [backtab] 'org-shifttab)
17183 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17184 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17185 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17187 ;; Cursor keys with modifiers
17188 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17189 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17190 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17191 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17193 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17194 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17195 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17196 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17198 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17199 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17200 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17201 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17203 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17204 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17205 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17206 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17208 ;; Babel keys
17209 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17210 (mapc (lambda (pair)
17211 (define-key org-babel-map (car pair) (cdr pair)))
17212 org-babel-key-bindings)
17214 ;;; Extra keys for tty access.
17215 ;; We only set them when really needed because otherwise the
17216 ;; menus don't show the simple keys
17218 (when (or org-use-extra-keys
17219 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17220 (not window-system))
17221 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17222 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17223 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17224 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17225 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17226 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17227 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17228 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17229 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17230 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17231 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17232 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17233 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17234 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17235 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17236 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17237 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17238 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17239 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17240 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17241 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17242 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17243 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17244 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17245 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17246 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17247 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17248 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17250 ;; All the other keys
17252 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17253 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17254 (if (boundp 'narrow-map)
17255 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17256 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17257 (if (boundp 'narrow-map)
17258 (org-defkey narrow-map "b" 'org-narrow-to-block)
17259 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17260 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
17261 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
17262 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17263 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17264 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17265 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17266 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17267 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17268 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17269 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17270 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17271 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17272 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17273 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17274 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17275 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17276 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17277 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17278 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17279 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17280 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17281 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17282 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
17283 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
17284 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
17285 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
17286 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
17287 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
17288 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
17289 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
17290 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17291 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17292 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17293 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17294 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
17295 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
17296 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17297 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
17298 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
17299 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
17300 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
17301 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17302 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
17303 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
17304 (org-defkey org-mode-map "\C-c^" 'org-sort)
17305 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
17306 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
17307 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
17308 (org-defkey org-mode-map "\C-m" 'org-return)
17309 (org-defkey org-mode-map "\C-j" 'org-return-indent)
17310 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
17311 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
17312 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
17313 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
17314 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
17315 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
17316 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
17317 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
17318 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
17319 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
17320 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
17321 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
17322 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
17323 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
17324 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
17325 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
17326 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
17327 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
17328 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
17329 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
17330 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
17332 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
17333 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
17334 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
17335 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
17337 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
17338 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
17339 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
17340 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
17341 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
17342 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
17343 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
17344 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
17345 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
17346 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
17347 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
17348 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
17349 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
17350 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
17351 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
17352 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
17353 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
17354 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
17356 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
17357 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
17358 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
17359 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
17360 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
17362 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
17364 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
17366 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
17367 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
17369 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
17372 (when (featurep 'xemacs)
17373 (org-defkey org-mode-map 'button3 'popup-mode-menu))
17376 (defconst org-speed-commands-default
17378 ("Outline Navigation")
17379 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
17380 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
17381 ("f" . (org-speed-move-safe 'org-forward-same-level))
17382 ("b" . (org-speed-move-safe 'org-backward-same-level))
17383 ("u" . (org-speed-move-safe 'outline-up-heading))
17384 ("j" . org-goto)
17385 ("g" . (org-refile t))
17386 ("Outline Visibility")
17387 ("c" . org-cycle)
17388 ("C" . org-shifttab)
17389 (" " . org-display-outline-path)
17390 ("Outline Structure Editing")
17391 ("U" . org-shiftmetaup)
17392 ("D" . org-shiftmetadown)
17393 ("r" . org-metaright)
17394 ("l" . org-metaleft)
17395 ("R" . org-shiftmetaright)
17396 ("L" . org-shiftmetaleft)
17397 ("i" . (progn (forward-char 1) (call-interactively
17398 'org-insert-heading-respect-content)))
17399 ("^" . org-sort)
17400 ("w" . org-refile)
17401 ("a" . org-archive-subtree-default-with-confirmation)
17402 ("." . org-mark-subtree)
17403 ("Clock Commands")
17404 ("I" . org-clock-in)
17405 ("O" . org-clock-out)
17406 ("Meta Data Editing")
17407 ("t" . org-todo)
17408 ("0" . (org-priority ?\ ))
17409 ("1" . (org-priority ?A))
17410 ("2" . (org-priority ?B))
17411 ("3" . (org-priority ?C))
17412 (";" . org-set-tags-command)
17413 ("e" . org-set-effort)
17414 ("Agenda Views etc")
17415 ("v" . org-agenda)
17416 ("/" . org-sparse-tree)
17417 ("Misc")
17418 ("o" . org-open-at-point)
17419 ("?" . org-speed-command-help)
17420 ("<" . (org-agenda-set-restriction-lock 'subtree))
17421 (">" . (org-agenda-remove-restriction-lock))
17423 "The default speed commands.")
17425 (defun org-print-speed-command (e)
17426 (if (> (length (car e)) 1)
17427 (progn
17428 (princ "\n")
17429 (princ (car e))
17430 (princ "\n")
17431 (princ (make-string (length (car e)) ?-))
17432 (princ "\n"))
17433 (princ (car e))
17434 (princ " ")
17435 (if (symbolp (cdr e))
17436 (princ (symbol-name (cdr e)))
17437 (prin1 (cdr e)))
17438 (princ "\n")))
17440 (defun org-speed-command-help ()
17441 "Show the available speed commands."
17442 (interactive)
17443 (if (not org-use-speed-commands)
17444 (error "Speed commands are not activated, customize `org-use-speed-commands'")
17445 (with-output-to-temp-buffer "*Help*"
17446 (princ "User-defined Speed commands\n===========================\n")
17447 (mapc 'org-print-speed-command org-speed-commands-user)
17448 (princ "\n")
17449 (princ "Built-in Speed commands\n=======================\n")
17450 (mapc 'org-print-speed-command org-speed-commands-default))
17451 (with-current-buffer "*Help*"
17452 (setq truncate-lines t))))
17454 (defun org-speed-move-safe (cmd)
17455 "Execute CMD, but make sure that the cursor always ends up in a headline.
17456 If not, return to the original position and throw an error."
17457 (interactive)
17458 (let ((pos (point)))
17459 (call-interactively cmd)
17460 (unless (and (bolp) (org-on-heading-p))
17461 (goto-char pos)
17462 (error "Boundary reached while executing %s" cmd))))
17464 (defvar org-self-insert-command-undo-counter 0)
17466 (defvar org-table-auto-blank-field) ; defined in org-table.el
17467 (defvar org-speed-command nil)
17469 (defun org-speed-command-default-hook (keys)
17470 "Hook for activating single-letter speed commands.
17471 `org-speed-commands-default' specifies a minimal command set.
17472 Use `org-speed-commands-user' for further customization."
17473 (when (or (and (bolp) (looking-at org-outline-regexp))
17474 (and (functionp org-use-speed-commands)
17475 (funcall org-use-speed-commands)))
17476 (cdr (assoc keys (append org-speed-commands-user
17477 org-speed-commands-default)))))
17479 (defun org-babel-speed-command-hook (keys)
17480 "Hook for activating single-letter code block commands."
17481 (when (and (bolp) (looking-at org-babel-src-block-regexp))
17482 (cdr (assoc keys org-babel-key-bindings))))
17484 (defcustom org-speed-command-hook
17485 '(org-speed-command-default-hook org-babel-speed-command-hook)
17486 "Hook for activating speed commands at strategic locations.
17487 Hook functions are called in sequence until a valid handler is
17488 found.
17490 Each hook takes a single argument, a user-pressed command key
17491 which is also a `self-insert-command' from the global map.
17493 Within the hook, examine the cursor position and the command key
17494 and return nil or a valid handler as appropriate. Handler could
17495 be one of an interactive command, a function, or a form.
17497 Set `org-use-speed-commands' to non-nil value to enable this
17498 hook. The default setting is `org-speed-command-default-hook'."
17499 :group 'org-structure
17500 :type 'hook)
17502 (defun org-self-insert-command (N)
17503 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
17504 If the cursor is in a table looking at whitespace, the whitespace is
17505 overwritten, and the table is not marked as requiring realignment."
17506 (interactive "p")
17507 (org-check-before-invisible-edit 'insert)
17508 (cond
17509 ((and org-use-speed-commands
17510 (setq org-speed-command
17511 (run-hook-with-args-until-success
17512 'org-speed-command-hook (this-command-keys))))
17513 (cond
17514 ((commandp org-speed-command)
17515 (setq this-command org-speed-command)
17516 (call-interactively org-speed-command))
17517 ((functionp org-speed-command)
17518 (funcall org-speed-command))
17519 ((and org-speed-command (listp org-speed-command))
17520 (eval org-speed-command))
17521 (t (let (org-use-speed-commands)
17522 (call-interactively 'org-self-insert-command)))))
17523 ((and
17524 (org-table-p)
17525 (progn
17526 ;; check if we blank the field, and if that triggers align
17527 (and (featurep 'org-table) org-table-auto-blank-field
17528 (member last-command
17529 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
17530 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
17531 ;; got extra space, this field does not determine column width
17532 (let (org-table-may-need-update) (org-table-blank-field))
17533 ;; no extra space, this field may determine column width
17534 (org-table-blank-field)))
17536 (eq N 1)
17537 (looking-at "[^|\n]* |"))
17538 (let (org-table-may-need-update)
17539 (goto-char (1- (match-end 0)))
17540 (delete-char -1)
17541 (goto-char (match-beginning 0))
17542 (self-insert-command N)))
17544 (setq org-table-may-need-update t)
17545 (self-insert-command N)
17546 (org-fix-tags-on-the-fly)
17547 (if org-self-insert-cluster-for-undo
17548 (if (not (eq last-command 'org-self-insert-command))
17549 (setq org-self-insert-command-undo-counter 1)
17550 (if (>= org-self-insert-command-undo-counter 20)
17551 (setq org-self-insert-command-undo-counter 1)
17552 (and (> org-self-insert-command-undo-counter 0)
17553 buffer-undo-list (listp buffer-undo-list)
17554 (not (cadr buffer-undo-list)) ; remove nil entry
17555 (setcdr buffer-undo-list (cddr buffer-undo-list)))
17556 (setq org-self-insert-command-undo-counter
17557 (1+ org-self-insert-command-undo-counter))))))))
17559 (defun org-check-before-invisible-edit (kind)
17560 "Check is editing if kind KIND would be dangerous with invisible text around.
17561 The detailed reaction depends on the user option `org-catch-invisible-edits'."
17562 ;; First, try to get out of here as quickly as possible, to reduce overhead
17563 (if (and org-catch-invisible-edits
17564 (or (not (boundp 'visible-mode)) (not visible-mode))
17565 (or (get-char-property (point) 'invisible)
17566 (get-char-property (max (point-min) (1- (point))) 'invisible)))
17567 ;; OK, we need to take a closer look
17568 (let* ((invisible-at-point (get-char-property (point) 'invisible))
17569 (invisible-before-point (if (bobp) nil (get-char-property
17570 (1- (point)) 'invisible)))
17571 (border-and-ok-direction
17573 ;; Check if we are acting predictably before invisible text
17574 (and invisible-at-point (not invisible-before-point)
17575 (memq kind '(insert delete-backward)))
17576 ;; Check if we are acting predictably after invisible text
17577 ;; This works not well, and I have turned it off. It seems
17578 ;; better to always show and stop after invisible text.
17579 ;; (and (not invisible-at-point) invisible-before-point
17580 ;; (memq kind '(insert delete)))
17583 (when (or (memq invisible-at-point '(outline org-hide-block))
17584 (memq invisible-before-point '(outline org-hide-block)))
17585 (if (eq org-catch-invisible-edits 'error)
17586 (error "Editing in invisible areas is prohibited - make visible first"))
17587 ;; Make the area visible
17588 (save-excursion
17589 (if invisible-before-point
17590 (goto-char (previous-single-char-property-change
17591 (point) 'invisible)))
17592 (org-cycle))
17593 (cond
17594 ((eq org-catch-invisible-edits 'show)
17595 ;; That's it, we do the edit after showing
17596 (message
17597 "Unfolding invisible region around point before editing")
17598 (sit-for 1))
17599 ((and (eq org-catch-invisible-edits 'smart)
17600 border-and-ok-direction)
17601 (message "Unfolding invisible region around point before editing"))
17603 ;; Don't do the edit, make the user repeat it in full visibility
17604 (error "Edit in invisible region aborted, repeat to confirm with text visible")))))))
17606 (defun org-fix-tags-on-the-fly ()
17607 (when (and (equal (char-after (point-at-bol)) ?*)
17608 (org-on-heading-p))
17609 (org-align-tags-here org-tags-column)))
17611 (defun org-delete-backward-char (N)
17612 "Like `delete-backward-char', insert whitespace at field end in tables.
17613 When deleting backwards, in tables this function will insert whitespace in
17614 front of the next \"|\" separator, to keep the table aligned. The table will
17615 still be marked for re-alignment if the field did fill the entire column,
17616 because, in this case the deletion might narrow the column."
17617 (interactive "p")
17618 (org-check-before-invisible-edit 'delete-backward)
17619 (if (and (org-table-p)
17620 (eq N 1)
17621 (string-match "|" (buffer-substring (point-at-bol) (point)))
17622 (looking-at ".*?|"))
17623 (let ((pos (point))
17624 (noalign (looking-at "[^|\n\r]* |"))
17625 (c org-table-may-need-update))
17626 (backward-delete-char N)
17627 (if (not overwrite-mode)
17628 (progn
17629 (skip-chars-forward "^|")
17630 (insert " ")
17631 (goto-char (1- pos))))
17632 ;; noalign: if there were two spaces at the end, this field
17633 ;; does not determine the width of the column.
17634 (if noalign (setq org-table-may-need-update c)))
17635 (backward-delete-char N)
17636 (org-fix-tags-on-the-fly)))
17638 (defun org-delete-char (N)
17639 "Like `delete-char', but insert whitespace at field end in tables.
17640 When deleting characters, in tables this function will insert whitespace in
17641 front of the next \"|\" separator, to keep the table aligned. The table will
17642 still be marked for re-alignment if the field did fill the entire column,
17643 because, in this case the deletion might narrow the column."
17644 (interactive "p")
17645 (org-check-before-invisible-edit 'delete)
17646 (if (and (org-table-p)
17647 (not (bolp))
17648 (not (= (char-after) ?|))
17649 (eq N 1))
17650 (if (looking-at ".*?|")
17651 (let ((pos (point))
17652 (noalign (looking-at "[^|\n\r]* |"))
17653 (c org-table-may-need-update))
17654 (replace-match (concat
17655 (substring (match-string 0) 1 -1)
17656 " |"))
17657 (goto-char pos)
17658 ;; noalign: if there were two spaces at the end, this field
17659 ;; does not determine the width of the column.
17660 (if noalign (setq org-table-may-need-update c)))
17661 (delete-char N))
17662 (delete-char N)
17663 (org-fix-tags-on-the-fly)))
17665 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
17666 (put 'org-self-insert-command 'delete-selection t)
17667 (put 'orgtbl-self-insert-command 'delete-selection t)
17668 (put 'org-delete-char 'delete-selection 'supersede)
17669 (put 'org-delete-backward-char 'delete-selection 'supersede)
17670 (put 'org-yank 'delete-selection 'yank)
17672 ;; Make `flyspell-mode' delay after some commands
17673 (put 'org-self-insert-command 'flyspell-delayed t)
17674 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
17675 (put 'org-delete-char 'flyspell-delayed t)
17676 (put 'org-delete-backward-char 'flyspell-delayed t)
17678 ;; Make pabbrev-mode expand after org-mode commands
17679 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
17680 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
17682 ;; How to do this: Measure non-white length of current string
17683 ;; If equal to column width, we should realign.
17685 (defun org-remap (map &rest commands)
17686 "In MAP, remap the functions given in COMMANDS.
17687 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
17688 (let (new old)
17689 (while commands
17690 (setq old (pop commands) new (pop commands))
17691 (if (fboundp 'command-remapping)
17692 (org-defkey map (vector 'remap old) new)
17693 (substitute-key-definition old new map global-map)))))
17695 (when (eq org-enable-table-editor 'optimized)
17696 ;; If the user wants maximum table support, we need to hijack
17697 ;; some standard editing functions
17698 (org-remap org-mode-map
17699 'self-insert-command 'org-self-insert-command
17700 'delete-char 'org-delete-char
17701 'delete-backward-char 'org-delete-backward-char)
17702 (org-defkey org-mode-map "|" 'org-force-self-insert))
17704 (defvar org-ctrl-c-ctrl-c-hook nil
17705 "Hook for functions attaching themselves to `C-c C-c'.
17707 This can be used to add additional functionality to the C-c C-c
17708 key which executes context-dependent commands. This hook is run
17709 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
17710 run after the last test.
17712 Each function will be called with no arguments. The function
17713 must check if the context is appropriate for it to act. If yes,
17714 it should do its thing and then return a non-nil value. If the
17715 context is wrong, just do nothing and return nil.")
17717 (defvar org-ctrl-c-ctrl-c-final-hook nil
17718 "Hook for functions attaching themselves to `C-c C-c'.
17720 This can be used to add additional functionality to the C-c C-c
17721 key which executes context-dependent commands. This hook is run
17722 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
17723 before the first test.
17725 Each function will be called with no arguments. The function
17726 must check if the context is appropriate for it to act. If yes,
17727 it should do its thing and then return a non-nil value. If the
17728 context is wrong, just do nothing and return nil.")
17730 (defvar org-tab-first-hook nil
17731 "Hook for functions to attach themselves to TAB.
17732 See `org-ctrl-c-ctrl-c-hook' for more information.
17733 This hook runs as the first action when TAB is pressed, even before
17734 `org-cycle' messes around with the `outline-regexp' to cater for
17735 inline tasks and plain list item folding.
17736 If any function in this hook returns t, any other actions that
17737 would have been caused by TAB (such as table field motion or visibility
17738 cycling) will not occur.")
17740 (defvar org-tab-after-check-for-table-hook nil
17741 "Hook for functions to attach themselves to TAB.
17742 See `org-ctrl-c-ctrl-c-hook' for more information.
17743 This hook runs after it has been established that the cursor is not in a
17744 table, but before checking if the cursor is in a headline or if global cycling
17745 should be done.
17746 If any function in this hook returns t, not other actions like visibility
17747 cycling will be done.")
17749 (defvar org-tab-after-check-for-cycling-hook nil
17750 "Hook for functions to attach themselves to TAB.
17751 See `org-ctrl-c-ctrl-c-hook' for more information.
17752 This hook runs after it has been established that not table field motion and
17753 not visibility should be done because of current context. This is probably
17754 the place where a package like yasnippets can hook in.")
17756 (defvar org-tab-before-tab-emulation-hook nil
17757 "Hook for functions to attach themselves to TAB.
17758 See `org-ctrl-c-ctrl-c-hook' for more information.
17759 This hook runs after every other options for TAB have been exhausted, but
17760 before indentation and \t insertion takes place.")
17762 (defvar org-metaleft-hook nil
17763 "Hook for functions attaching themselves to `M-left'.
17764 See `org-ctrl-c-ctrl-c-hook' for more information.")
17765 (defvar org-metaright-hook nil
17766 "Hook for functions attaching themselves to `M-right'.
17767 See `org-ctrl-c-ctrl-c-hook' for more information.")
17768 (defvar org-metaup-hook nil
17769 "Hook for functions attaching themselves to `M-up'.
17770 See `org-ctrl-c-ctrl-c-hook' for more information.")
17771 (defvar org-metadown-hook nil
17772 "Hook for functions attaching themselves to `M-down'.
17773 See `org-ctrl-c-ctrl-c-hook' for more information.")
17774 (defvar org-shiftmetaleft-hook nil
17775 "Hook for functions attaching themselves to `M-S-left'.
17776 See `org-ctrl-c-ctrl-c-hook' for more information.")
17777 (defvar org-shiftmetaright-hook nil
17778 "Hook for functions attaching themselves to `M-S-right'.
17779 See `org-ctrl-c-ctrl-c-hook' for more information.")
17780 (defvar org-shiftmetaup-hook nil
17781 "Hook for functions attaching themselves to `M-S-up'.
17782 See `org-ctrl-c-ctrl-c-hook' for more information.")
17783 (defvar org-shiftmetadown-hook nil
17784 "Hook for functions attaching themselves to `M-S-down'.
17785 See `org-ctrl-c-ctrl-c-hook' for more information.")
17786 (defvar org-metareturn-hook nil
17787 "Hook for functions attaching themselves to `M-RET'.
17788 See `org-ctrl-c-ctrl-c-hook' for more information.")
17789 (defvar org-shiftup-hook nil
17790 "Hook for functions attaching themselves to `S-up'.
17791 See `org-ctrl-c-ctrl-c-hook' for more information.")
17792 (defvar org-shiftup-final-hook nil
17793 "Hook for functions attaching themselves to `S-up'.
17794 This one runs after all other options except shift-select have been excluded.
17795 See `org-ctrl-c-ctrl-c-hook' for more information.")
17796 (defvar org-shiftdown-hook nil
17797 "Hook for functions attaching themselves to `S-down'.
17798 See `org-ctrl-c-ctrl-c-hook' for more information.")
17799 (defvar org-shiftdown-final-hook nil
17800 "Hook for functions attaching themselves to `S-down'.
17801 This one runs after all other options except shift-select have been excluded.
17802 See `org-ctrl-c-ctrl-c-hook' for more information.")
17803 (defvar org-shiftleft-hook nil
17804 "Hook for functions attaching themselves to `S-left'.
17805 See `org-ctrl-c-ctrl-c-hook' for more information.")
17806 (defvar org-shiftleft-final-hook nil
17807 "Hook for functions attaching themselves to `S-left'.
17808 This one runs after all other options except shift-select have been excluded.
17809 See `org-ctrl-c-ctrl-c-hook' for more information.")
17810 (defvar org-shiftright-hook nil
17811 "Hook for functions attaching themselves to `S-right'.
17812 See `org-ctrl-c-ctrl-c-hook' for more information.")
17813 (defvar org-shiftright-final-hook nil
17814 "Hook for functions attaching themselves to `S-right'.
17815 This one runs after all other options except shift-select have been excluded.
17816 See `org-ctrl-c-ctrl-c-hook' for more information.")
17818 (defun org-modifier-cursor-error ()
17819 "Throw an error, a modified cursor command was applied in wrong context."
17820 (error "This command is active in special context like tables, headlines or items"))
17822 (defun org-shiftselect-error ()
17823 "Throw an error because Shift-Cursor command was applied in wrong context."
17824 (if (and (boundp 'shift-select-mode) shift-select-mode)
17825 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
17826 (error "This command works only in special context like headlines or timestamps")))
17828 (defun org-call-for-shift-select (cmd)
17829 (let ((this-command-keys-shift-translated t))
17830 (call-interactively cmd)))
17832 (defun org-shifttab (&optional arg)
17833 "Global visibility cycling or move to previous table field.
17834 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
17835 on context.
17836 See the individual commands for more information."
17837 (interactive "P")
17838 (cond
17839 ((org-at-table-p) (call-interactively 'org-table-previous-field))
17840 ((integerp arg)
17841 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
17842 (message "Content view to level: %d" arg)
17843 (org-content (prefix-numeric-value arg2))
17844 (setq org-cycle-global-status 'overview)))
17845 (t (call-interactively 'org-global-cycle))))
17847 (defun org-shiftmetaleft ()
17848 "Promote subtree or delete table column.
17849 Calls `org-promote-subtree', `org-outdent-item',
17850 or `org-table-delete-column', depending on context.
17851 See the individual commands for more information."
17852 (interactive)
17853 (cond
17854 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
17855 ((org-at-table-p) (call-interactively 'org-table-delete-column))
17856 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
17857 ((org-at-item-p) (call-interactively 'org-outdent-item-tree))
17858 (t (org-modifier-cursor-error))))
17860 (defun org-shiftmetaright ()
17861 "Demote subtree or insert table column.
17862 Calls `org-demote-subtree', `org-indent-item',
17863 or `org-table-insert-column', depending on context.
17864 See the individual commands for more information."
17865 (interactive)
17866 (cond
17867 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
17868 ((org-at-table-p) (call-interactively 'org-table-insert-column))
17869 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
17870 ((org-at-item-p) (call-interactively 'org-indent-item-tree))
17871 (t (org-modifier-cursor-error))))
17873 (defun org-shiftmetaup (&optional arg)
17874 "Move subtree up or kill table row.
17875 Calls `org-move-subtree-up' or `org-table-kill-row' or
17876 `org-move-item-up' depending on context. See the individual commands
17877 for more information."
17878 (interactive "P")
17879 (cond
17880 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
17881 ((org-at-table-p) (call-interactively 'org-table-kill-row))
17882 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17883 ((org-at-item-p) (call-interactively 'org-move-item-up))
17884 (t (org-modifier-cursor-error))))
17886 (defun org-shiftmetadown (&optional arg)
17887 "Move subtree down or insert table row.
17888 Calls `org-move-subtree-down' or `org-table-insert-row' or
17889 `org-move-item-down', depending on context. See the individual
17890 commands for more information."
17891 (interactive "P")
17892 (cond
17893 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
17894 ((org-at-table-p) (call-interactively 'org-table-insert-row))
17895 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17896 ((org-at-item-p) (call-interactively 'org-move-item-down))
17897 (t (org-modifier-cursor-error))))
17899 (defsubst org-hidden-tree-error ()
17900 (error
17901 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
17903 (defun org-metaleft (&optional arg)
17904 "Promote heading or move table column to left.
17905 Calls `org-do-promote' or `org-table-move-column', depending on context.
17906 With no specific context, calls the Emacs default `backward-word'.
17907 See the individual commands for more information."
17908 (interactive "P")
17909 (cond
17910 ((run-hook-with-args-until-success 'org-metaleft-hook))
17911 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
17912 ((org-with-limited-levels
17913 (or (org-on-heading-p)
17914 (and (org-region-active-p)
17915 (save-excursion
17916 (goto-char (region-beginning))
17917 (org-on-heading-p)))))
17918 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17919 (call-interactively 'org-do-promote))
17920 ;; At an inline task.
17921 ((org-on-heading-p)
17922 (call-interactively 'org-inlinetask-promote))
17923 ((or (org-at-item-p)
17924 (and (org-region-active-p)
17925 (save-excursion
17926 (goto-char (region-beginning))
17927 (org-at-item-p))))
17928 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17929 (call-interactively 'org-outdent-item))
17930 (t (call-interactively 'backward-word))))
17932 (defun org-metaright (&optional arg)
17933 "Demote subtree or move table column to right.
17934 Calls `org-do-demote' or `org-table-move-column', depending on context.
17935 With no specific context, calls the Emacs default `forward-word'.
17936 See the individual commands for more information."
17937 (interactive "P")
17938 (cond
17939 ((run-hook-with-args-until-success 'org-metaright-hook))
17940 ((org-at-table-p) (call-interactively 'org-table-move-column))
17941 ((org-with-limited-levels
17942 (or (org-on-heading-p)
17943 (and (org-region-active-p)
17944 (save-excursion
17945 (goto-char (region-beginning))
17946 (org-on-heading-p)))))
17947 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17948 (call-interactively 'org-do-demote))
17949 ;; At an inline task.
17950 ((org-on-heading-p)
17951 (call-interactively 'org-inlinetask-demote))
17952 ((or (org-at-item-p)
17953 (and (org-region-active-p)
17954 (save-excursion
17955 (goto-char (region-beginning))
17956 (org-at-item-p))))
17957 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17958 (call-interactively 'org-indent-item))
17959 (t (call-interactively 'forward-word))))
17961 (defun org-check-for-hidden (what)
17962 "Check if there are hidden headlines/items in the current visual line.
17963 WHAT can be either `headlines' or `items'. If the current line is
17964 an outline or item heading and it has a folded subtree below it,
17965 this function returns t, nil otherwise."
17966 (let ((re (cond
17967 ((eq what 'headlines) org-outline-regexp-bol)
17968 ((eq what 'items) (org-item-beginning-re))
17969 (t (error "This should not happen"))))
17970 beg end)
17971 (save-excursion
17972 (catch 'exit
17973 (unless (org-region-active-p)
17974 (setq beg (point-at-bol))
17975 (beginning-of-line 2)
17976 (while (and (not (eobp)) ;; this is like `next-line'
17977 (get-char-property (1- (point)) 'invisible))
17978 (beginning-of-line 2))
17979 (setq end (point))
17980 (goto-char beg)
17981 (goto-char (point-at-eol))
17982 (setq end (max end (point)))
17983 (while (re-search-forward re end t)
17984 (if (get-char-property (match-beginning 0) 'invisible)
17985 (throw 'exit t))))
17986 nil))))
17988 (defun org-metaup (&optional arg)
17989 "Move subtree up or move table row up.
17990 Calls `org-move-subtree-up' or `org-table-move-row' or
17991 `org-move-item-up', depending on context. See the individual commands
17992 for more information."
17993 (interactive "P")
17994 (cond
17995 ((run-hook-with-args-until-success 'org-metaup-hook))
17996 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
17997 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17998 ((org-at-item-p) (call-interactively 'org-move-item-up))
17999 (t (transpose-lines 1) (beginning-of-line -1))))
18001 (defun org-metadown (&optional arg)
18002 "Move subtree down or move table row down.
18003 Calls `org-move-subtree-down' or `org-table-move-row' or
18004 `org-move-item-down', depending on context. See the individual
18005 commands for more information."
18006 (interactive "P")
18007 (cond
18008 ((run-hook-with-args-until-success 'org-metadown-hook))
18009 ((org-at-table-p) (call-interactively 'org-table-move-row))
18010 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
18011 ((org-at-item-p) (call-interactively 'org-move-item-down))
18012 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
18014 (defun org-shiftup (&optional arg)
18015 "Increase item in timestamp or increase priority of current headline.
18016 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18017 depending on context. See the individual commands for more information."
18018 (interactive "P")
18019 (cond
18020 ((run-hook-with-args-until-success 'org-shiftup-hook))
18021 ((and org-support-shift-select (org-region-active-p))
18022 (org-call-for-shift-select 'previous-line))
18023 ((org-at-timestamp-p t)
18024 (call-interactively (if org-edit-timestamp-down-means-later
18025 'org-timestamp-down 'org-timestamp-up)))
18026 ((and (not (eq org-support-shift-select 'always))
18027 org-enable-priority-commands
18028 (org-on-heading-p))
18029 (call-interactively 'org-priority-up))
18030 ((and (not org-support-shift-select) (org-at-item-p))
18031 (call-interactively 'org-previous-item))
18032 ((org-clocktable-try-shift 'up arg))
18033 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18034 (org-support-shift-select
18035 (org-call-for-shift-select 'previous-line))
18036 (t (org-shiftselect-error))))
18038 (defun org-shiftdown (&optional arg)
18039 "Decrease item in timestamp or decrease priority of current headline.
18040 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18041 depending on context. See the individual commands for more information."
18042 (interactive "P")
18043 (cond
18044 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18045 ((and org-support-shift-select (org-region-active-p))
18046 (org-call-for-shift-select 'next-line))
18047 ((org-at-timestamp-p t)
18048 (call-interactively (if org-edit-timestamp-down-means-later
18049 'org-timestamp-up 'org-timestamp-down)))
18050 ((and (not (eq org-support-shift-select 'always))
18051 org-enable-priority-commands
18052 (org-on-heading-p))
18053 (call-interactively 'org-priority-down))
18054 ((and (not org-support-shift-select) (org-at-item-p))
18055 (call-interactively 'org-next-item))
18056 ((org-clocktable-try-shift 'down arg))
18057 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18058 (org-support-shift-select
18059 (org-call-for-shift-select 'next-line))
18060 (t (org-shiftselect-error))))
18062 (defun org-shiftright (&optional arg)
18063 "Cycle the thing at point or in the current line, depending on context.
18064 Depending on context, this does one of the following:
18066 - switch a timestamp at point one day into the future
18067 - on a headline, switch to the next TODO keyword.
18068 - on an item, switch entire list to the next bullet type
18069 - on a property line, switch to the next allowed value
18070 - on a clocktable definition line, move time block into the future"
18071 (interactive "P")
18072 (cond
18073 ((run-hook-with-args-until-success 'org-shiftright-hook))
18074 ((and org-support-shift-select (org-region-active-p))
18075 (org-call-for-shift-select 'forward-char))
18076 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18077 ((and (not (eq org-support-shift-select 'always))
18078 (org-on-heading-p))
18079 (let ((org-inhibit-logging
18080 (not org-treat-S-cursor-todo-selection-as-state-change))
18081 (org-inhibit-blocking
18082 (not org-treat-S-cursor-todo-selection-as-state-change)))
18083 (org-call-with-arg 'org-todo 'right)))
18084 ((or (and org-support-shift-select
18085 (not (eq org-support-shift-select 'always))
18086 (org-at-item-bullet-p))
18087 (and (not org-support-shift-select) (org-at-item-p)))
18088 (org-call-with-arg 'org-cycle-list-bullet nil))
18089 ((and (not (eq org-support-shift-select 'always))
18090 (org-at-property-p))
18091 (call-interactively 'org-property-next-allowed-value))
18092 ((org-clocktable-try-shift 'right arg))
18093 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18094 (org-support-shift-select
18095 (org-call-for-shift-select 'forward-char))
18096 (t (org-shiftselect-error))))
18098 (defun org-shiftleft (&optional arg)
18099 "Cycle the thing at point or in the current line, depending on context.
18100 Depending on context, this does one of the following:
18102 - switch a timestamp at point one day into the past
18103 - on a headline, switch to the previous TODO keyword.
18104 - on an item, switch entire list to the previous bullet type
18105 - on a property line, switch to the previous allowed value
18106 - on a clocktable definition line, move time block into the past"
18107 (interactive "P")
18108 (cond
18109 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18110 ((and org-support-shift-select (org-region-active-p))
18111 (org-call-for-shift-select 'backward-char))
18112 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18113 ((and (not (eq org-support-shift-select 'always))
18114 (org-on-heading-p))
18115 (let ((org-inhibit-logging
18116 (not org-treat-S-cursor-todo-selection-as-state-change))
18117 (org-inhibit-blocking
18118 (not org-treat-S-cursor-todo-selection-as-state-change)))
18119 (org-call-with-arg 'org-todo 'left)))
18120 ((or (and org-support-shift-select
18121 (not (eq org-support-shift-select 'always))
18122 (org-at-item-bullet-p))
18123 (and (not org-support-shift-select) (org-at-item-p)))
18124 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18125 ((and (not (eq org-support-shift-select 'always))
18126 (org-at-property-p))
18127 (call-interactively 'org-property-previous-allowed-value))
18128 ((org-clocktable-try-shift 'left arg))
18129 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18130 (org-support-shift-select
18131 (org-call-for-shift-select 'backward-char))
18132 (t (org-shiftselect-error))))
18134 (defun org-shiftcontrolright ()
18135 "Switch to next TODO set."
18136 (interactive)
18137 (cond
18138 ((and org-support-shift-select (org-region-active-p))
18139 (org-call-for-shift-select 'forward-word))
18140 ((and (not (eq org-support-shift-select 'always))
18141 (org-on-heading-p))
18142 (org-call-with-arg 'org-todo 'nextset))
18143 (org-support-shift-select
18144 (org-call-for-shift-select 'forward-word))
18145 (t (org-shiftselect-error))))
18147 (defun org-shiftcontrolleft ()
18148 "Switch to previous TODO set."
18149 (interactive)
18150 (cond
18151 ((and org-support-shift-select (org-region-active-p))
18152 (org-call-for-shift-select 'backward-word))
18153 ((and (not (eq org-support-shift-select 'always))
18154 (org-on-heading-p))
18155 (org-call-with-arg 'org-todo 'previousset))
18156 (org-support-shift-select
18157 (org-call-for-shift-select 'backward-word))
18158 (t (org-shiftselect-error))))
18160 (defun org-shiftcontrolup ()
18161 "Change timestamps synchronously up in CLOCK log lines."
18162 (interactive)
18163 (cond ((and (not org-support-shift-select)
18164 (org-at-clock-log-p)
18165 (org-at-timestamp-p t))
18166 (org-clock-timestamps-up))
18167 (t (org-shiftselect-error))))
18169 (defun org-shiftcontroldown ()
18170 "Change timestamps synchronously down in CLOCK log lines."
18171 (interactive)
18172 (cond ((and (not org-support-shift-select)
18173 (org-at-clock-log-p)
18174 (org-at-timestamp-p t))
18175 (org-clock-timestamps-down))
18176 (t (org-shiftselect-error))))
18178 (defun org-ctrl-c-ret ()
18179 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18180 (interactive)
18181 (cond
18182 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18183 (t (call-interactively 'org-insert-heading))))
18185 (defun org-find-visible ()
18186 (let ((s (point)))
18187 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18188 (get-char-property s 'invisible)))
18190 (defun org-find-invisible ()
18191 (let ((s (point)))
18192 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18193 (not (get-char-property s 'invisible))))
18196 (defun org-copy-visible (beg end)
18197 "Copy the visible parts of the region."
18198 (interactive "r")
18199 (let (snippets s)
18200 (save-excursion
18201 (save-restriction
18202 (narrow-to-region beg end)
18203 (setq s (goto-char (point-min)))
18204 (while (not (= (point) (point-max)))
18205 (goto-char (org-find-invisible))
18206 (push (buffer-substring s (point)) snippets)
18207 (setq s (goto-char (org-find-visible))))))
18208 (kill-new (apply 'concat (nreverse snippets)))))
18210 (defun org-copy-special ()
18211 "Copy region in table or copy current subtree.
18212 Calls `org-table-copy' or `org-copy-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-copy-region 'org-copy-subtree)))
18218 (defun org-cut-special ()
18219 "Cut region in table or cut current subtree.
18220 Calls `org-table-copy' or `org-cut-subtree', depending on context.
18221 See the individual commands for more information."
18222 (interactive)
18223 (call-interactively
18224 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
18226 (defun org-paste-special (arg)
18227 "Paste rectangular region into table, or past subtree relative to level.
18228 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
18229 See the individual commands for more information."
18230 (interactive "P")
18231 (if (org-at-table-p)
18232 (org-table-paste-rectangle)
18233 (org-paste-subtree arg)))
18235 (defun org-edit-special (&optional arg)
18236 "Call a special editor for the stuff at point.
18237 When at a table, call the formula editor with `org-table-edit-formulas'.
18238 When at the first line of an src example, call `org-edit-src-code'.
18239 When in an #+include line, visit the include file. Otherwise call
18240 `ffap' to visit the file at point."
18241 (interactive)
18242 ;; possibly prep session before editing source
18243 (when arg
18244 (let* ((info (org-babel-get-src-block-info))
18245 (lang (nth 0 info))
18246 (params (nth 2 info))
18247 (session (cdr (assoc :session params))))
18248 (when (and info session) ;; we are in a source-code block with a session
18249 (funcall
18250 (intern (concat "org-babel-prep-session:" lang)) session params))))
18251 (cond ;; proceed with `org-edit-special'
18252 ((save-excursion
18253 (beginning-of-line 1)
18254 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
18255 (find-file (org-trim (match-string 1))))
18256 ((org-edit-src-code))
18257 ((org-edit-fixed-width-region))
18258 ((org-at-table.el-p)
18259 (org-edit-src-code))
18260 ((or (org-at-table-p)
18261 (save-excursion
18262 (beginning-of-line 1)
18263 (looking-at "[ \t]*#\\+TBLFM:")))
18264 (call-interactively 'org-table-edit-formulas))
18265 (t (call-interactively 'ffap))))
18267 (defvar org-table-coordinate-overlays) ; defined in org-table.el
18268 (defun org-ctrl-c-ctrl-c (&optional arg)
18269 "Set tags in headline, or update according to changed information at point.
18271 This command does many different things, depending on context:
18273 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
18274 this is what we do.
18276 - If the cursor is on a statistics cookie, update it.
18278 - If the cursor is in a headline, prompt for tags and insert them
18279 into the current line, aligned to `org-tags-column'. When called
18280 with prefix arg, realign all tags in the current buffer.
18282 - If the cursor is in one of the special #+KEYWORD lines, this
18283 triggers scanning the buffer for these lines and updating the
18284 information.
18286 - If the cursor is inside a table, realign the table. This command
18287 works even if the automatic table editor has been turned off.
18289 - If the cursor is on a #+TBLFM line, re-apply the formulas to
18290 the entire table.
18292 - If the cursor is at a footnote reference or definition, jump to
18293 the corresponding definition or references, respectively.
18295 - If the cursor is a the beginning of a dynamic block, update it.
18297 - If the current buffer is a capture buffer, close note and file it.
18299 - If the cursor is on a <<<target>>>, update radio targets and
18300 corresponding links in this buffer.
18302 - If the cursor is on a numbered item in a plain list, renumber the
18303 ordered list.
18305 - If the cursor is on a checkbox, toggle it.
18307 - If the cursor is on a code block, evaluate it. The variable
18308 `org-confirm-babel-evaluate' can be used to control prompting
18309 before code block evaluation, by default every code block
18310 evaluation requires confirmation. Code block evaluation can be
18311 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
18312 (interactive "P")
18313 (let ((org-enable-table-editor t))
18314 (cond
18315 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
18316 org-occur-highlights
18317 org-latex-fragment-image-overlays)
18318 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
18319 (org-remove-occur-highlights)
18320 (org-remove-latex-fragment-image-overlays)
18321 (message "Temporary highlights/overlays removed from current buffer"))
18322 ((and (local-variable-p 'org-finish-function (current-buffer))
18323 (fboundp org-finish-function))
18324 (funcall org-finish-function))
18325 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
18326 ((org-in-regexp org-ts-regexp-both)
18327 (org-timestamp-change 0 'day))
18328 ((or (looking-at org-property-start-re)
18329 (org-at-property-p))
18330 (call-interactively 'org-property-action))
18331 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
18332 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
18333 (or (org-on-heading-p) (org-at-item-p)))
18334 (call-interactively 'org-update-statistics-cookies))
18335 ((org-on-heading-p) (call-interactively 'org-set-tags))
18336 ((org-at-table.el-p)
18337 (message "Use C-c ' to edit table.el tables"))
18338 ((org-at-table-p)
18339 (org-table-maybe-eval-formula)
18340 (if arg
18341 (call-interactively 'org-table-recalculate)
18342 (org-table-maybe-recalculate-line))
18343 (call-interactively 'org-table-align)
18344 (orgtbl-send-table 'maybe))
18345 ((or (org-footnote-at-reference-p)
18346 (org-footnote-at-definition-p))
18347 (call-interactively 'org-footnote-action))
18348 ((org-at-item-checkbox-p)
18349 ;; Cursor at a checkbox: repair list and update checkboxes. Send
18350 ;; list only if at top item.
18351 (let* ((cbox (match-string 1))
18352 (struct (org-list-struct))
18353 (old-struct (copy-tree struct))
18354 (parents (org-list-parents-alist struct))
18355 (orderedp (org-entry-get nil "ORDERED"))
18356 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18357 block-item)
18358 ;; Use a light version of `org-toggle-checkbox' to avoid
18359 ;; computing list structure twice.
18360 (org-list-set-checkbox (point-at-bol) struct
18361 (cond
18362 ((equal arg '(16)) "[-]")
18363 ((equal arg '(4)) nil)
18364 ((equal "[X]" cbox) "[ ]")
18365 (t "[X]")))
18366 ;; Replicate `org-list-write-struct', while grabbing a return
18367 ;; value from `org-list-struct-fix-box'.
18368 (org-list-struct-fix-ind struct parents 2)
18369 (org-list-struct-fix-item-end struct)
18370 (let ((prevs (org-list-prevs-alist struct)))
18371 (org-list-struct-fix-bul struct prevs)
18372 (org-list-struct-fix-ind struct parents)
18373 (setq block-item
18374 (org-list-struct-fix-box struct parents prevs orderedp)))
18375 (org-list-struct-apply-struct struct old-struct)
18376 (org-update-checkbox-count-maybe)
18377 (when block-item
18378 (message
18379 "Checkboxes were removed due to unchecked box at line %d"
18380 (org-current-line block-item)))
18381 (when firstp (org-list-send-list 'maybe))))
18382 ((org-at-item-p)
18383 ;; Cursor at an item: repair list. Do checkbox related actions
18384 ;; only if function was called with an argument. Send list only
18385 ;; if at top item.
18386 (let* ((struct (org-list-struct))
18387 (firstp (= (org-list-get-top-point struct) (point-at-bol))))
18388 (when arg (org-list-set-checkbox (point-at-bol) struct "[ ]"))
18389 (org-list-write-struct struct (org-list-parents-alist struct))
18390 (when arg (org-update-checkbox-count-maybe))
18391 (when firstp (org-list-send-list 'maybe))))
18392 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
18393 ;; Dynamic block
18394 (beginning-of-line 1)
18395 (save-excursion (org-update-dblock)))
18396 ((save-excursion
18397 (beginning-of-line 1)
18398 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
18399 (cond
18400 ((equal (match-string 1) "TBLFM")
18401 ;; Recalculate the table before this line
18402 (save-excursion
18403 (beginning-of-line 1)
18404 (skip-chars-backward " \r\n\t")
18405 (if (org-at-table-p)
18406 (org-call-with-arg 'org-table-recalculate (or arg t)))))
18408 (let ((org-inhibit-startup-visibility-stuff t)
18409 (org-startup-align-all-tables nil))
18410 (when (boundp 'org-table-coordinate-overlays)
18411 (mapc 'delete-overlay org-table-coordinate-overlays)
18412 (setq org-table-coordinate-overlays nil))
18413 (org-save-outline-visibility 'use-markers (org-mode-restart)))
18414 (message "Local setup has been refreshed"))))
18415 ((org-clock-update-time-maybe))
18417 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
18418 (error "C-c C-c can do nothing useful at this location"))))))
18420 (defun org-mode-restart ()
18421 "Restart Org-mode, to scan again for special lines.
18422 Also updates the keyword regular expressions."
18423 (interactive)
18424 (org-mode)
18425 (message "Org-mode restarted"))
18427 (defun org-kill-note-or-show-branches ()
18428 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
18429 (interactive)
18430 (if (not org-finish-function)
18431 (progn
18432 (hide-subtree)
18433 (call-interactively 'show-branches))
18434 (let ((org-note-abort t))
18435 (funcall org-finish-function))))
18437 (defun org-return (&optional indent)
18438 "Goto next table row or insert a newline.
18439 Calls `org-table-next-row' or `newline', depending on context.
18440 See the individual commands for more information."
18441 (interactive)
18442 (cond
18443 ((bobp) (if indent (newline-and-indent) (newline)))
18444 ((org-at-table-p)
18445 (org-table-justify-field-maybe)
18446 (call-interactively 'org-table-next-row))
18447 ;; when `newline-and-indent' is called within a list, make sure
18448 ;; text moved stays inside the item.
18449 ((and (org-in-item-p) indent)
18450 (if (and (org-at-item-p) (>= (point) (match-end 0)))
18451 (progn
18452 (save-match-data (newline))
18453 (org-indent-line-to (length (match-string 0))))
18454 (let ((ind (org-get-indentation)))
18455 (newline)
18456 (if (org-looking-back org-list-end-re)
18457 (org-indent-line-function)
18458 (org-indent-line-to ind)))))
18459 ((and org-return-follows-link
18460 (let ((tprop (get-text-property (point) 'face)))
18461 (or (eq tprop 'org-link)
18462 (and (listp tprop) (memq 'org-link tprop)))))
18463 (call-interactively 'org-open-at-point))
18464 ((and (org-at-heading-p)
18465 (looking-at
18466 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
18467 (org-show-entry)
18468 (end-of-line 1)
18469 (newline))
18470 (t (if indent (newline-and-indent) (newline)))))
18472 (defun org-return-indent ()
18473 "Goto next table row or insert a newline and indent.
18474 Calls `org-table-next-row' or `newline-and-indent', depending on
18475 context. See the individual commands for more information."
18476 (interactive)
18477 (org-return t))
18479 (defun org-ctrl-c-star ()
18480 "Compute table, or change heading status of lines.
18481 Calls `org-table-recalculate' or `org-toggle-heading',
18482 depending on context."
18483 (interactive)
18484 (cond
18485 ((org-at-table-p)
18486 (call-interactively 'org-table-recalculate))
18488 ;; Convert all lines in region to list items
18489 (call-interactively 'org-toggle-heading))))
18491 (defun org-ctrl-c-minus ()
18492 "Insert separator line in table or modify bullet status of line.
18493 Also turns a plain line or a region of lines into list items.
18494 Calls `org-table-insert-hline', `org-toggle-item', or
18495 `org-cycle-list-bullet', depending on context."
18496 (interactive)
18497 (cond
18498 ((org-at-table-p)
18499 (call-interactively 'org-table-insert-hline))
18500 ((org-region-active-p)
18501 (call-interactively 'org-toggle-item))
18502 ((org-in-item-p)
18503 (call-interactively 'org-cycle-list-bullet))
18505 (call-interactively 'org-toggle-item))))
18507 (defun org-toggle-item (arg)
18508 "Convert headings or normal lines to items, items to normal lines.
18509 If there is no active region, only the current line is considered.
18511 If the first non blank line in the region is an headline, convert
18512 all headlines to items, shifting text accordingly.
18514 If it is an item, convert all items to normal lines.
18516 If it is normal text, change region into an item. With a prefix
18517 argument ARG, change each line in region into an item."
18518 (interactive "P")
18519 (let ((shift-text
18520 (function
18521 ;; Shift text in current section to IND, from point to END.
18522 ;; The function leaves point to END line.
18523 (lambda (ind end)
18524 (let ((min-i 1000) (end (copy-marker end)))
18525 ;; First determine the minimum indentation (MIN-I) of
18526 ;; the text.
18527 (save-excursion
18528 (catch 'exit
18529 (while (< (point) end)
18530 (let ((i (org-get-indentation)))
18531 (cond
18532 ;; Skip blank lines and inline tasks.
18533 ((looking-at "^[ \t]*$"))
18534 ((looking-at org-outline-regexp-bol))
18535 ;; We can't find less than 0 indentation.
18536 ((zerop i) (throw 'exit (setq min-i 0)))
18537 ((< i min-i) (setq min-i i))))
18538 (forward-line))))
18539 ;; Then indent each line so that a line indented to
18540 ;; MIN-I becomes indented to IND. Ignore blank lines
18541 ;; and inline tasks in the process.
18542 (let ((delta (- ind min-i)))
18543 (while (< (point) end)
18544 (unless (or (looking-at "^[ \t]*$")
18545 (looking-at org-outline-regexp-bol))
18546 (org-indent-line-to (+ (org-get-indentation) delta)))
18547 (forward-line)))))))
18548 (skip-blanks
18549 (function
18550 ;; Return beginning of first non-blank line, starting from
18551 ;; line at POS.
18552 (lambda (pos)
18553 (save-excursion
18554 (goto-char pos)
18555 (skip-chars-forward " \r\t\n")
18556 (point-at-bol)))))
18557 beg end)
18558 ;; Determine boundaries of changes.
18559 (if (org-region-active-p)
18560 (setq beg (funcall skip-blanks (region-beginning))
18561 end (copy-marker (region-end)))
18562 (setq beg (funcall skip-blanks (point-at-bol))
18563 end (copy-marker (point-at-eol))))
18564 ;; Depending on the starting line, choose an action on the text
18565 ;; between BEG and END.
18566 (org-with-limited-levels
18567 (save-excursion
18568 (goto-char beg)
18569 (cond
18570 ;; Case 1. Start at an item: de-itemize. Note that it only
18571 ;; happens when a region is active: `org-ctrl-c-minus'
18572 ;; would call `org-cycle-list-bullet' otherwise.
18573 ((org-at-item-p)
18574 (while (< (point) end)
18575 (when (org-at-item-p)
18576 (skip-chars-forward " \t")
18577 (delete-region (point) (match-end 0)))
18578 (forward-line)))
18579 ;; Case 2. Start at an heading: convert to items.
18580 ((org-on-heading-p)
18581 (let* ((bul (org-list-bullet-string "-"))
18582 (bul-len (length bul))
18583 ;; Indentation of the first heading. It should be
18584 ;; relative to the indentation of its parent, if any.
18585 (start-ind (save-excursion
18586 (cond
18587 ((not org-adapt-indentation) 0)
18588 ((not (outline-previous-heading)) 0)
18589 (t (length (match-string 0))))))
18590 ;; Level of first heading. Further headings will be
18591 ;; compared to it to determine hierarchy in the list.
18592 (ref-level (org-reduced-level (org-outline-level))))
18593 (while (< (point) end)
18594 (let* ((level (org-reduced-level (org-outline-level)))
18595 (delta (max 0 (- level ref-level))))
18596 ;; If current headline is less indented than the first
18597 ;; one, set it as reference, in order to preserve
18598 ;; subtrees.
18599 (when (< level ref-level) (setq ref-level level))
18600 (replace-match bul t t)
18601 (org-indent-line-to (+ start-ind (* delta bul-len)))
18602 ;; Ensure all text down to END (or SECTION-END) belongs
18603 ;; to the newly created item.
18604 (let ((section-end (save-excursion
18605 (or (outline-next-heading) (point)))))
18606 (forward-line)
18607 (funcall shift-text
18608 (+ start-ind (* (1+ delta) bul-len))
18609 (min end section-end)))))))
18610 ;; Case 3. Normal line with ARG: turn each non-item line into
18611 ;; an item.
18612 (arg
18613 (while (< (point) end)
18614 (unless (or (org-on-heading-p) (org-at-item-p))
18615 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
18616 (replace-match
18617 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
18618 (forward-line)))
18619 ;; Case 4. Normal line without ARG: make the first line of
18620 ;; region an item, and shift indentation of others
18621 ;; lines to set them as item's body.
18622 (t (let* ((bul (org-list-bullet-string "-"))
18623 (bul-len (length bul))
18624 (ref-ind (org-get-indentation)))
18625 (skip-chars-forward " \t")
18626 (insert bul)
18627 (forward-line)
18628 (while (< (point) end)
18629 ;; Ensure that lines less indented than first one
18630 ;; still get included in item body.
18631 (funcall shift-text
18632 (+ ref-ind bul-len)
18633 (min end (save-excursion (or (outline-next-heading)
18634 (point)))))
18635 (forward-line)))))))))
18637 (defun org-toggle-heading (&optional nstars)
18638 "Convert headings to normal text, or items or text to headings.
18639 If there is no active region, only the current line is considered.
18641 If the first non blank line is an headline, remove the stars from
18642 all headlines in the region.
18644 If it is a plain list item, turn all plain list items into headings.
18646 If it is a normal line, turn each and every normal line (i.e. not
18647 an heading or an item) in the region into a heading.
18649 When converting a line into a heading, the number of stars is chosen
18650 such that the lines become children of the current entry. However,
18651 when a prefix argument is given, its value determines the number of
18652 stars to add."
18653 (interactive "P")
18654 (let ((skip-blanks
18655 (function
18656 ;; Return beginning of first non-blank line, starting from
18657 ;; line at POS.
18658 (lambda (pos)
18659 (save-excursion
18660 (goto-char pos)
18661 (skip-chars-forward " \r\t\n")
18662 (point-at-bol)))))
18663 beg end)
18664 ;; Determine boundaries of changes. If region ends at a bol, do
18665 ;; not consider the last line to be in the region.
18666 (if (org-region-active-p)
18667 (setq beg (funcall skip-blanks (region-beginning))
18668 end (copy-marker (save-excursion
18669 (goto-char (region-end))
18670 (if (bolp) (point) (point-at-eol)))))
18671 (setq beg (funcall skip-blanks (point-at-bol))
18672 end (copy-marker (point-at-eol))))
18673 ;; Ensure inline tasks don't count as headings.
18674 (org-with-limited-levels
18675 (save-excursion
18676 (goto-char beg)
18677 (cond
18678 ;; Case 1. Started at an heading: de-star headings.
18679 ((org-on-heading-p)
18680 (while (< (point) end)
18681 (when (org-on-heading-p t)
18682 (looking-at org-outline-regexp) (replace-match ""))
18683 (forward-line)))
18684 ;; Case 2. Started at an item: change items into headlines.
18685 ;; One star will be added by `org-list-to-subtree'.
18686 ((org-at-item-p)
18687 (let* ((stars (make-string
18688 (if nstars
18689 ;; subtract the star that will be added again by
18690 ;; `org-list-to-subtree'
18691 (1- (prefix-numeric-value current-prefix-arg))
18692 (or (org-current-level) 0))
18693 ?*))
18694 (add-stars
18695 (cond (nstars "") ; stars from prefix only
18696 ((equal stars "") "") ; before first heading
18697 (org-odd-levels-only "*") ; inside heading, odd
18698 (t "")))) ; inside heading, oddeven
18699 (while (< (point) end)
18700 (when (org-at-item-p)
18701 ;; Pay attention to cases when region ends before list.
18702 (let* ((struct (org-list-struct))
18703 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
18704 (save-restriction
18705 (narrow-to-region (point) list-end)
18706 (insert
18707 (org-list-to-subtree
18708 (org-list-parse-list t)
18709 '(:istart (concat stars add-stars (funcall get-stars depth))
18710 :icount (concat stars add-stars (funcall get-stars depth))))))))
18711 (forward-line))))
18712 ;; Case 3. Started at normal text: make every line an heading,
18713 ;; skipping headlines and items.
18714 (t (let* ((stars (make-string
18715 (if nstars
18716 (prefix-numeric-value current-prefix-arg)
18717 (or (org-current-level) 0))
18718 ?*))
18719 (add-stars
18720 (cond (nstars "") ; stars from prefix only
18721 ((equal stars "") "*") ; before first heading
18722 (org-odd-levels-only "**") ; inside heading, odd
18723 (t "*"))) ; inside heading, oddeven
18724 (rpl (concat stars add-stars " ")))
18725 (while (< (point) end)
18726 (when (and (not (org-on-heading-p)) (not (org-at-item-p))
18727 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
18728 (replace-match (concat rpl (match-string 2))))
18729 (forward-line)))))))))
18731 (defun org-meta-return (&optional arg)
18732 "Insert a new heading or wrap a region in a table.
18733 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
18734 See the individual commands for more information."
18735 (interactive "P")
18736 (cond
18737 ((run-hook-with-args-until-success 'org-metareturn-hook))
18738 ((org-at-table-p)
18739 (call-interactively 'org-table-wrap-region))
18740 (t (call-interactively 'org-insert-heading))))
18742 ;;; Menu entries
18744 ;; Define the Org-mode menus
18745 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
18746 '("Tbl"
18747 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
18748 ["Next Field" org-cycle (org-at-table-p)]
18749 ["Previous Field" org-shifttab (org-at-table-p)]
18750 ["Next Row" org-return (org-at-table-p)]
18751 "--"
18752 ["Blank Field" org-table-blank-field (org-at-table-p)]
18753 ["Edit Field" org-table-edit-field (org-at-table-p)]
18754 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
18755 "--"
18756 ("Column"
18757 ["Move Column Left" org-metaleft (org-at-table-p)]
18758 ["Move Column Right" org-metaright (org-at-table-p)]
18759 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
18760 ["Insert Column" org-shiftmetaright (org-at-table-p)])
18761 ("Row"
18762 ["Move Row Up" org-metaup (org-at-table-p)]
18763 ["Move Row Down" org-metadown (org-at-table-p)]
18764 ["Delete Row" org-shiftmetaup (org-at-table-p)]
18765 ["Insert Row" org-shiftmetadown (org-at-table-p)]
18766 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
18767 "--"
18768 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
18769 ("Rectangle"
18770 ["Copy Rectangle" org-copy-special (org-at-table-p)]
18771 ["Cut Rectangle" org-cut-special (org-at-table-p)]
18772 ["Paste Rectangle" org-paste-special (org-at-table-p)]
18773 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
18774 "--"
18775 ("Calculate"
18776 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
18777 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
18778 ["Edit Formulas" org-edit-special (org-at-table-p)]
18779 "--"
18780 ["Recalculate line" org-table-recalculate (org-at-table-p)]
18781 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
18782 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
18783 "--"
18784 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
18785 "--"
18786 ["Sum Column/Rectangle" org-table-sum
18787 (or (org-at-table-p) (org-region-active-p))]
18788 ["Which Column?" org-table-current-column (org-at-table-p)])
18789 ["Debug Formulas"
18790 org-table-toggle-formula-debugger
18791 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
18792 ["Show Col/Row Numbers"
18793 org-table-toggle-coordinate-overlays
18794 :style toggle
18795 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
18796 "--"
18797 ["Create" org-table-create (and (not (org-at-table-p))
18798 org-enable-table-editor)]
18799 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
18800 ["Import from File" org-table-import (not (org-at-table-p))]
18801 ["Export to File" org-table-export (org-at-table-p)]
18802 "--"
18803 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
18805 (easy-menu-define org-org-menu org-mode-map "Org menu"
18806 '("Org"
18807 ("Show/Hide"
18808 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
18809 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
18810 ["Sparse Tree..." org-sparse-tree t]
18811 ["Reveal Context" org-reveal t]
18812 ["Show All" show-all t]
18813 "--"
18814 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
18815 "--"
18816 ["New Heading" org-insert-heading t]
18817 ("Navigate Headings"
18818 ["Up" outline-up-heading t]
18819 ["Next" outline-next-visible-heading t]
18820 ["Previous" outline-previous-visible-heading t]
18821 ["Next Same Level" outline-forward-same-level t]
18822 ["Previous Same Level" outline-backward-same-level t]
18823 "--"
18824 ["Jump" org-goto t])
18825 ("Edit Structure"
18826 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
18827 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
18828 "--"
18829 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
18830 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
18831 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
18832 "--"
18833 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
18834 "--"
18835 ["Copy visible text" org-copy-visible t]
18836 "--"
18837 ["Promote Heading" org-metaleft (not (org-at-table-p))]
18838 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
18839 ["Demote Heading" org-metaright (not (org-at-table-p))]
18840 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
18841 "--"
18842 ["Sort Region/Children" org-sort (not (org-at-table-p))]
18843 "--"
18844 ["Convert to odd levels" org-convert-to-odd-levels t]
18845 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
18846 ("Editing"
18847 ["Emphasis..." org-emphasize t]
18848 ["Edit Source Example" org-edit-special t]
18849 "--"
18850 ["Footnote new/jump" org-footnote-action t]
18851 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
18852 ("Archive"
18853 ["Archive (default method)" org-archive-subtree-default t]
18854 "--"
18855 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
18856 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
18857 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
18859 "--"
18860 ("Hyperlinks"
18861 ["Store Link (Global)" org-store-link t]
18862 ["Find existing link to here" org-occur-link-in-agenda-files t]
18863 ["Insert Link" org-insert-link t]
18864 ["Follow Link" org-open-at-point t]
18865 "--"
18866 ["Next link" org-next-link t]
18867 ["Previous link" org-previous-link t]
18868 "--"
18869 ["Descriptive Links"
18870 org-toggle-link-display
18871 :style radio
18872 :selected org-descriptive-links
18874 ["Literal Links"
18875 org-toggle-link-display
18876 :style radio
18877 :selected (not org-descriptive-links)])
18878 "--"
18879 ("TODO Lists"
18880 ["TODO/DONE/-" org-todo t]
18881 ("Select keyword"
18882 ["Next keyword" org-shiftright (org-on-heading-p)]
18883 ["Previous keyword" org-shiftleft (org-on-heading-p)]
18884 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
18885 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
18886 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
18887 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
18888 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
18889 "--"
18890 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
18891 :selected org-enforce-todo-dependencies :style toggle :active t]
18892 "Settings for tree at point"
18893 ["Do Children sequentially" org-toggle-ordered-property :style radio
18894 :selected (org-entry-get nil "ORDERED")
18895 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
18896 ["Do Children parallel" org-toggle-ordered-property :style radio
18897 :selected (not (org-entry-get nil "ORDERED"))
18898 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
18899 "--"
18900 ["Set Priority" org-priority t]
18901 ["Priority Up" org-shiftup t]
18902 ["Priority Down" org-shiftdown t]
18903 "--"
18904 ["Get news from all feeds" org-feed-update-all t]
18905 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
18906 ["Customize feeds" (customize-variable 'org-feed-alist) t])
18907 ("TAGS and Properties"
18908 ["Set Tags" org-set-tags-command t]
18909 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
18910 "--"
18911 ["Set property" org-set-property t]
18912 ["Column view of properties" org-columns t]
18913 ["Insert Column View DBlock" org-insert-columns-dblock t])
18914 ("Dates and Scheduling"
18915 ["Timestamp" org-time-stamp t]
18916 ["Timestamp (inactive)" org-time-stamp-inactive t]
18917 ("Change Date"
18918 ["1 Day Later" org-shiftright t]
18919 ["1 Day Earlier" org-shiftleft t]
18920 ["1 ... Later" org-shiftup t]
18921 ["1 ... Earlier" org-shiftdown t])
18922 ["Compute Time Range" org-evaluate-time-range t]
18923 ["Schedule Item" org-schedule t]
18924 ["Deadline" org-deadline t]
18925 "--"
18926 ["Custom time format" org-toggle-time-stamp-overlays
18927 :style radio :selected org-display-custom-times]
18928 "--"
18929 ["Goto Calendar" org-goto-calendar t]
18930 ["Date from Calendar" org-date-from-calendar t]
18931 "--"
18932 ["Start/Restart Timer" org-timer-start t]
18933 ["Pause/Continue Timer" org-timer-pause-or-continue t]
18934 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
18935 ["Insert Timer String" org-timer t]
18936 ["Insert Timer Item" org-timer-item t])
18937 ("Logging work"
18938 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
18939 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
18940 ["Clock out" org-clock-out t]
18941 ["Clock cancel" org-clock-cancel t]
18942 "--"
18943 ["Mark as default task" org-clock-mark-default-task t]
18944 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
18945 ["Goto running clock" org-clock-goto t]
18946 "--"
18947 ["Display times" org-clock-display t]
18948 ["Create clock table" org-clock-report t]
18949 "--"
18950 ["Record DONE time"
18951 (progn (setq org-log-done (not org-log-done))
18952 (message "Switching to %s will %s record a timestamp"
18953 (car org-done-keywords)
18954 (if org-log-done "automatically" "not")))
18955 :style toggle :selected org-log-done])
18956 "--"
18957 ["Agenda Command..." org-agenda t]
18958 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
18959 ("File List for Agenda")
18960 ("Special views current file"
18961 ["TODO Tree" org-show-todo-tree t]
18962 ["Check Deadlines" org-check-deadlines t]
18963 ["Timeline" org-timeline t]
18964 ["Tags/Property tree" org-match-sparse-tree t])
18965 "--"
18966 ["Export/Publish..." org-export t]
18967 ("LaTeX"
18968 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
18969 :selected org-cdlatex-mode]
18970 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
18971 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
18972 ["Modify math symbol" org-cdlatex-math-modify
18973 (org-inside-LaTeX-fragment-p)]
18974 ["Insert citation" org-reftex-citation t]
18975 "--"
18976 ["Template for BEAMER" org-insert-beamer-options-template t])
18977 "--"
18978 ("MobileOrg"
18979 ["Push Files and Views" org-mobile-push t]
18980 ["Get Captured and Flagged" org-mobile-pull t]
18981 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
18982 "--"
18983 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
18984 "--"
18985 ("Documentation"
18986 ["Show Version" org-version t]
18987 ["Info Documentation" org-info t])
18988 ("Customize"
18989 ["Browse Org Group" org-customize t]
18990 "--"
18991 ["Expand This Menu" org-create-customize-menu
18992 (fboundp 'customize-menu-create)])
18993 ["Send bug report" org-submit-bug-report t]
18994 "--"
18995 ("Refresh/Reload"
18996 ["Refresh setup current buffer" org-mode-restart t]
18997 ["Reload Org (after update)" org-reload t]
18998 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19001 (defun org-info (&optional node)
19002 "Read documentation for Org-mode in the info system.
19003 With optional NODE, go directly to that node."
19004 (interactive)
19005 (info (format "(org)%s" (or node ""))))
19007 ;;;###autoload
19008 (defun org-submit-bug-report ()
19009 "Submit a bug report on Org-mode via mail.
19011 Don't hesitate to report any problems or inaccurate documentation.
19013 If you don't have setup sending mail from (X)Emacs, please copy the
19014 output buffer into your mail program, as it gives us important
19015 information about your Org-mode version and configuration."
19016 (interactive)
19017 (require 'reporter)
19018 (org-load-modules-maybe)
19019 (org-require-autoloaded-modules)
19020 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19021 (reporter-submit-bug-report
19022 "emacs-orgmode@gnu.org"
19023 (org-version)
19024 (let (list)
19025 (save-window-excursion
19026 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19027 (delete-other-windows)
19028 (erase-buffer)
19029 (insert "You are about to submit a bug report to the Org-mode mailing list.
19031 We would like to add your full Org-mode and Outline configuration to the
19032 bug report. This greatly simplifies the work of the maintainer and
19033 other experts on the mailing list.
19035 HOWEVER, some variables you have customized may contain private
19036 information. The names of customers, colleagues, or friends, might
19037 appear in the form of file names, tags, todo states, or search strings.
19038 If you answer yes to the prompt, you might want to check and remove
19039 such private information before sending the email.")
19040 (add-text-properties (point-min) (point-max) '(face org-warning))
19041 (when (yes-or-no-p "Include your Org-mode configuration ")
19042 (mapatoms
19043 (lambda (v)
19044 (and (boundp v)
19045 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19046 (or (and (symbol-value v)
19047 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19048 (and
19049 (get v 'custom-type) (get v 'standard-value)
19050 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19051 (push v list)))))
19052 (kill-buffer (get-buffer "*Warn about privacy*"))
19053 list))
19054 nil nil
19055 "Remember to cover the basics, that is, what you expected to happen and
19056 what in fact did happen. You don't know how to make a good report? See
19058 http://orgmode.org/manual/Feedback.html#Feedback
19060 Your bug report will be posted to the Org-mode mailing list.
19061 ------------------------------------------------------------------------")
19062 (save-excursion
19063 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19064 (replace-match "\\1Bug: \\3 [\\2]")))))
19067 (defun org-install-agenda-files-menu ()
19068 (let ((bl (buffer-list)))
19069 (save-excursion
19070 (while bl
19071 (set-buffer (pop bl))
19072 (if (eq major-mode 'org-mode) (setq bl nil)))
19073 (when (eq major-mode 'org-mode)
19074 (easy-menu-change
19075 '("Org") "File List for Agenda"
19076 (append
19077 (list
19078 ["Edit File List" (org-edit-agenda-file-list) t]
19079 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19080 ["Remove Current File from List" org-remove-file t]
19081 ["Cycle through agenda files" org-cycle-agenda-files t]
19082 ["Occur in all agenda files" org-occur-in-agenda-files t]
19083 "--")
19084 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19086 ;;;; Documentation
19088 ;;;###autoload
19089 (defun org-require-autoloaded-modules ()
19090 (interactive)
19091 (mapc 'require
19092 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19093 org-docbook org-exp org-html org-icalendar
19094 org-id org-latex
19095 org-publish org-remember org-table
19096 org-timer org-xoxo)))
19098 ;;;###autoload
19099 (defun org-reload (&optional uncompiled)
19100 "Reload all org lisp files.
19101 With prefix arg UNCOMPILED, load the uncompiled versions."
19102 (interactive "P")
19103 (require 'find-func)
19104 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
19105 (dir-org (file-name-directory (org-find-library-name "org")))
19106 (dir-org-contrib (ignore-errors
19107 (file-name-directory
19108 (org-find-library-name "org-contribdir"))))
19109 (babel-files
19110 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19111 (append (list nil "comint" "eval" "exp" "keys"
19112 "lob" "ref" "table" "tangle")
19113 (delq nil
19114 (mapcar
19115 (lambda (lang)
19116 (when (cdr lang) (symbol-name (car lang))))
19117 org-babel-load-languages)))))
19118 (files
19119 (append (directory-files dir-org t file-re)
19120 babel-files
19121 (and dir-org-contrib
19122 (directory-files dir-org-contrib t file-re))))
19123 (remove-re (concat (if (featurep 'xemacs)
19124 "org-colview" "org-colview-xemacs")
19125 "\\'")))
19126 (setq files (mapcar 'file-name-sans-extension files))
19127 (setq files (mapcar
19128 (lambda (x) (if (string-match remove-re x) nil x))
19129 files))
19130 (setq files (delq nil files))
19131 (mapc
19132 (lambda (f)
19133 (when (featurep (intern (file-name-nondirectory f)))
19134 (if (and (not uncompiled)
19135 (file-exists-p (concat f ".elc")))
19136 (load (concat f ".elc") nil nil t)
19137 (load (concat f ".el") nil nil t))))
19138 files))
19139 (org-version))
19141 ;;;###autoload
19142 (defun org-customize ()
19143 "Call the customize function with org as argument."
19144 (interactive)
19145 (org-load-modules-maybe)
19146 (org-require-autoloaded-modules)
19147 (customize-browse 'org))
19149 (defun org-create-customize-menu ()
19150 "Create a full customization menu for Org-mode, insert it into the menu."
19151 (interactive)
19152 (org-load-modules-maybe)
19153 (org-require-autoloaded-modules)
19154 (if (fboundp 'customize-menu-create)
19155 (progn
19156 (easy-menu-change
19157 '("Org") "Customize"
19158 `(["Browse Org group" org-customize t]
19159 "--"
19160 ,(customize-menu-create 'org)
19161 ["Set" Custom-set t]
19162 ["Save" Custom-save t]
19163 ["Reset to Current" Custom-reset-current t]
19164 ["Reset to Saved" Custom-reset-saved t]
19165 ["Reset to Standard Settings" Custom-reset-standard t]))
19166 (message "\"Org\"-menu now contains full customization menu"))
19167 (error "Cannot expand menu (outdated version of cus-edit.el)")))
19169 ;;;; Miscellaneous stuff
19171 ;;; Generally useful functions
19173 (defun org-get-at-bol (property)
19174 "Get text property PROPERTY at beginning of line."
19175 (get-text-property (point-at-bol) property))
19177 (defun org-find-text-property-in-string (prop s)
19178 "Return the first non-nil value of property PROP in string S."
19179 (or (get-text-property 0 prop s)
19180 (get-text-property (or (next-single-property-change 0 prop s) 0)
19181 prop s)))
19183 (defun org-display-warning (message) ;; Copied from Emacs-Muse
19184 "Display the given MESSAGE as a warning."
19185 (if (fboundp 'display-warning)
19186 (display-warning 'org message
19187 (if (featurep 'xemacs) 'warning :warning))
19188 (let ((buf (get-buffer-create "*Org warnings*")))
19189 (with-current-buffer buf
19190 (goto-char (point-max))
19191 (insert "Warning (Org): " message)
19192 (unless (bolp)
19193 (newline)))
19194 (display-buffer buf)
19195 (sit-for 0))))
19197 (defun org-eval (form)
19198 "Eval FORM and return result."
19199 (condition-case error
19200 (eval form)
19201 (error (format "%%![Error: %s]" error))))
19203 (defun org-in-commented-line ()
19204 "Is point in a line starting with `#'?"
19205 (equal (char-after (point-at-bol)) ?#))
19207 (defun org-in-indented-comment-line ()
19208 "Is point in a line starting with `#' after some white space?"
19209 (save-excursion
19210 (save-match-data
19211 (goto-char (point-at-bol))
19212 (looking-at "[ \t]*#"))))
19214 (defun org-in-verbatim-emphasis ()
19215 (save-match-data
19216 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
19218 (defun org-goto-marker-or-bmk (marker &optional bookmark)
19219 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
19220 (if (and marker (marker-buffer marker)
19221 (buffer-live-p (marker-buffer marker)))
19222 (progn
19223 (org-pop-to-buffer-same-window (marker-buffer marker))
19224 (if (or (> marker (point-max)) (< marker (point-min)))
19225 (widen))
19226 (goto-char marker)
19227 (org-show-context 'org-goto))
19228 (if bookmark
19229 (bookmark-jump bookmark)
19230 (error "Cannot find location"))))
19232 (defun org-quote-csv-field (s)
19233 "Quote field for inclusion in CSV material."
19234 (if (string-match "[\",]" s)
19235 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
19238 (defun org-force-self-insert (N)
19239 "Needed to enforce self-insert under remapping."
19240 (interactive "p")
19241 (self-insert-command N))
19243 (defun org-string-width (s)
19244 "Compute width of string, ignoring invisible characters.
19245 This ignores character with invisibility property `org-link', and also
19246 characters with property `org-cwidth', because these will become invisible
19247 upon the next fontification round."
19248 (let (b l)
19249 (when (or (eq t buffer-invisibility-spec)
19250 (assq 'org-link buffer-invisibility-spec))
19251 (while (setq b (text-property-any 0 (length s)
19252 'invisible 'org-link s))
19253 (setq s (concat (substring s 0 b)
19254 (substring s (or (next-single-property-change
19255 b 'invisible s) (length s)))))))
19256 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
19257 (setq s (concat (substring s 0 b)
19258 (substring s (or (next-single-property-change
19259 b 'org-cwidth s) (length s))))))
19260 (setq l (string-width s) b -1)
19261 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
19262 (setq l (- l (get-text-property b 'org-dwidth-n s))))
19265 (defun org-shorten-string (s maxlength)
19266 "Shorten string S so tht it is no longer than MAXLENGTH characters.
19267 If the string is shorter or has length MAXLENGTH, just return the
19268 original string. If it is longer, the functions finds a space in the
19269 string, breaks this string off at that locations and adds three dots
19270 as ellipsis. Including the ellipsis, the string will not be longer
19271 than MAXLENGTH. If finding a good breaking point in the string does
19272 not work, the string is just chopped off in the middle of a word
19273 if necessary."
19274 (if (<= (length s) maxlength)
19276 (let* ((n (max (- maxlength 4) 1))
19277 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
19278 (if (string-match re s)
19279 (concat (match-string 1 s) "...")
19280 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
19282 (defun org-get-indentation (&optional line)
19283 "Get the indentation of the current line, interpreting tabs.
19284 When LINE is given, assume it represents a line and compute its indentation."
19285 (if line
19286 (if (string-match "^ *" (org-remove-tabs line))
19287 (match-end 0))
19288 (save-excursion
19289 (beginning-of-line 1)
19290 (skip-chars-forward " \t")
19291 (current-column))))
19293 (defun org-get-string-indentation (s)
19294 "What indentation has S due to SPACE and TAB at the beginning of the string?"
19295 (let ((n -1) (i 0) (w tab-width) c)
19296 (catch 'exit
19297 (while (< (setq n (1+ n)) (length s))
19298 (setq c (aref s n))
19299 (cond ((= c ?\ ) (setq i (1+ i)))
19300 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
19301 (t (throw 'exit t)))))
19304 (defun org-remove-tabs (s &optional width)
19305 "Replace tabulators in S with spaces.
19306 Assumes that s is a single line, starting in column 0."
19307 (setq width (or width tab-width))
19308 (while (string-match "\t" s)
19309 (setq s (replace-match
19310 (make-string
19311 (- (* width (/ (+ (match-beginning 0) width) width))
19312 (match-beginning 0)) ?\ )
19313 t t s)))
19316 (defun org-fix-indentation (line ind)
19317 "Fix indentation in LINE.
19318 IND is a cons cell with target and minimum indentation.
19319 If the current indentation in LINE is smaller than the minimum,
19320 leave it alone. If it is larger than ind, set it to the target."
19321 (let* ((l (org-remove-tabs line))
19322 (i (org-get-indentation l))
19323 (i1 (car ind)) (i2 (cdr ind)))
19324 (if (>= i i2) (setq l (substring line i2)))
19325 (if (> i1 0)
19326 (concat (make-string i1 ?\ ) l)
19327 l)))
19329 (defun org-remove-indentation (code &optional n)
19330 "Remove the maximum common indentation from the lines in CODE.
19331 N may optionally be the number of spaces to remove."
19332 (with-temp-buffer
19333 (insert code)
19334 (org-do-remove-indentation n)
19335 (buffer-string)))
19337 (defun org-do-remove-indentation (&optional n)
19338 "Remove the maximum common indentation from the buffer."
19339 (untabify (point-min) (point-max))
19340 (let ((min 10000) re)
19341 (if n
19342 (setq min n)
19343 (goto-char (point-min))
19344 (while (re-search-forward "^ *[^ \n]" nil t)
19345 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
19346 (unless (or (= min 0) (= min 10000))
19347 (setq re (format "^ \\{%d\\}" min))
19348 (goto-char (point-min))
19349 (while (re-search-forward re nil t)
19350 (replace-match "")
19351 (end-of-line 1))
19352 min)))
19354 (defun org-fill-template (template alist)
19355 "Find each %key of ALIST in TEMPLATE and replace it."
19356 (let ((case-fold-search nil)
19357 entry key value)
19358 (setq alist (sort (copy-sequence alist)
19359 (lambda (a b) (< (length (car a)) (length (car b))))))
19360 (while (setq entry (pop alist))
19361 (setq template
19362 (replace-regexp-in-string
19363 (concat "%" (regexp-quote (car entry)))
19364 (cdr entry) template t t)))
19365 template))
19367 (defun org-base-buffer (buffer)
19368 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
19369 (if (not buffer)
19370 buffer
19371 (or (buffer-base-buffer buffer)
19372 buffer)))
19374 (defun org-trim (s)
19375 "Remove whitespace at beginning and end of string."
19376 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
19377 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
19380 (defun org-wrap (string &optional width lines)
19381 "Wrap string to either a number of lines, or a width in characters.
19382 If WIDTH is non-nil, the string is wrapped to that width, however many lines
19383 that costs. If there is a word longer than WIDTH, the text is actually
19384 wrapped to the length of that word.
19385 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
19386 many lines, whatever width that takes.
19387 The return value is a list of lines, without newlines at the end."
19388 (let* ((words (org-split-string string "[ \t\n]+"))
19389 (maxword (apply 'max (mapcar 'org-string-width words)))
19390 w ll)
19391 (cond (width
19392 (org-do-wrap words (max maxword width)))
19393 (lines
19394 (setq w maxword)
19395 (setq ll (org-do-wrap words maxword))
19396 (if (<= (length ll) lines)
19398 (setq ll words)
19399 (while (> (length ll) lines)
19400 (setq w (1+ w))
19401 (setq ll (org-do-wrap words w)))
19402 ll))
19403 (t (error "Cannot wrap this")))))
19405 (defun org-do-wrap (words width)
19406 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
19407 (let (lines line)
19408 (while words
19409 (setq line (pop words))
19410 (while (and words (< (+ (length line) (length (car words))) width))
19411 (setq line (concat line " " (pop words))))
19412 (setq lines (push line lines)))
19413 (nreverse lines)))
19415 (defun org-split-string (string &optional separators)
19416 "Splits STRING into substrings at SEPARATORS.
19417 No empty strings are returned if there are matches at the beginning
19418 and end of string."
19419 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
19420 (start 0)
19421 notfirst
19422 (list nil))
19423 (while (and (string-match rexp string
19424 (if (and notfirst
19425 (= start (match-beginning 0))
19426 (< start (length string)))
19427 (1+ start) start))
19428 (< (match-beginning 0) (length string)))
19429 (setq notfirst t)
19430 (or (eq (match-beginning 0) 0)
19431 (and (eq (match-beginning 0) (match-end 0))
19432 (eq (match-beginning 0) start))
19433 (setq list
19434 (cons (substring string start (match-beginning 0))
19435 list)))
19436 (setq start (match-end 0)))
19437 (or (eq start (length string))
19438 (setq list
19439 (cons (substring string start)
19440 list)))
19441 (nreverse list)))
19443 (defun org-quote-vert (s)
19444 "Replace \"|\" with \"\\vert\"."
19445 (while (string-match "|" s)
19446 (setq s (replace-match "\\vert" t t s)))
19449 (defun org-uuidgen-p (s)
19450 "Is S an ID created by UUIDGEN?"
19451 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
19453 (defun org-context ()
19454 "Return a list of contexts of the current cursor position.
19455 If several contexts apply, all are returned.
19456 Each context entry is a list with a symbol naming the context, and
19457 two positions indicating start and end of the context. Possible
19458 contexts are:
19460 :headline anywhere in a headline
19461 :headline-stars on the leading stars in a headline
19462 :todo-keyword on a TODO keyword (including DONE) in a headline
19463 :tags on the TAGS in a headline
19464 :priority on the priority cookie in a headline
19465 :item on the first line of a plain list item
19466 :item-bullet on the bullet/number of a plain list item
19467 :checkbox on the checkbox in a plain list item
19468 :table in an org-mode table
19469 :table-special on a special filed in a table
19470 :table-table in a table.el table
19471 :link on a hyperlink
19472 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
19473 :target on a <<target>>
19474 :radio-target on a <<<radio-target>>>
19475 :latex-fragment on a LaTeX fragment
19476 :latex-preview on a LaTeX fragment with overlaid preview image
19478 This function expects the position to be visible because it uses font-lock
19479 faces as a help to recognize the following contexts: :table-special, :link,
19480 and :keyword."
19481 (let* ((f (get-text-property (point) 'face))
19482 (faces (if (listp f) f (list f)))
19483 (p (point)) clist o)
19484 ;; First the large context
19485 (cond
19486 ((org-on-heading-p t)
19487 (push (list :headline (point-at-bol) (point-at-eol)) clist)
19488 (when (progn
19489 (beginning-of-line 1)
19490 (looking-at org-todo-line-tags-regexp))
19491 (push (org-point-in-group p 1 :headline-stars) clist)
19492 (push (org-point-in-group p 2 :todo-keyword) clist)
19493 (push (org-point-in-group p 4 :tags) clist))
19494 (goto-char p)
19495 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
19496 (if (looking-at "\\[#[A-Z0-9]\\]")
19497 (push (org-point-in-group p 0 :priority) clist)))
19499 ((org-at-item-p)
19500 (push (org-point-in-group p 2 :item-bullet) clist)
19501 (push (list :item (point-at-bol)
19502 (save-excursion (org-end-of-item) (point)))
19503 clist)
19504 (and (org-at-item-checkbox-p)
19505 (push (org-point-in-group p 0 :checkbox) clist)))
19507 ((org-at-table-p)
19508 (push (list :table (org-table-begin) (org-table-end)) clist)
19509 (if (memq 'org-formula faces)
19510 (push (list :table-special
19511 (previous-single-property-change p 'face)
19512 (next-single-property-change p 'face)) clist)))
19513 ((org-at-table-p 'any)
19514 (push (list :table-table) clist)))
19515 (goto-char p)
19517 ;; Now the small context
19518 (cond
19519 ((org-at-timestamp-p)
19520 (push (org-point-in-group p 0 :timestamp) clist))
19521 ((memq 'org-link faces)
19522 (push (list :link
19523 (previous-single-property-change p 'face)
19524 (next-single-property-change p 'face)) clist))
19525 ((memq 'org-special-keyword faces)
19526 (push (list :keyword
19527 (previous-single-property-change p 'face)
19528 (next-single-property-change p 'face)) clist))
19529 ((org-on-target-p)
19530 (push (org-point-in-group p 0 :target) clist)
19531 (goto-char (1- (match-beginning 0)))
19532 (if (looking-at org-radio-target-regexp)
19533 (push (org-point-in-group p 0 :radio-target) clist))
19534 (goto-char p))
19535 ((setq o (car (delq nil
19536 (mapcar
19537 (lambda (x)
19538 (if (memq x org-latex-fragment-image-overlays) x))
19539 (overlays-at (point))))))
19540 (push (list :latex-fragment
19541 (overlay-start o) (overlay-end o)) clist)
19542 (push (list :latex-preview
19543 (overlay-start o) (overlay-end o)) clist))
19544 ((org-inside-LaTeX-fragment-p)
19545 ;; FIXME: positions wrong.
19546 (push (list :latex-fragment (point) (point)) clist)))
19548 (setq clist (nreverse (delq nil clist)))
19549 clist))
19551 ;; FIXME: Compare with at-regexp-p Do we need both?
19552 (defun org-in-regexp (re &optional nlines visually)
19553 "Check if point is inside a match of regexp.
19554 Normally only the current line is checked, but you can include NLINES extra
19555 lines both before and after point into the search.
19556 If VISUALLY is set, require that the cursor is not after the match but
19557 really on, so that the block visually is on the match."
19558 (catch 'exit
19559 (let ((pos (point))
19560 (eol (point-at-eol (+ 1 (or nlines 0))))
19561 (inc (if visually 1 0)))
19562 (save-excursion
19563 (beginning-of-line (- 1 (or nlines 0)))
19564 (while (re-search-forward re eol t)
19565 (if (and (<= (match-beginning 0) pos)
19566 (>= (+ inc (match-end 0)) pos))
19567 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
19569 (defun org-at-regexp-p (regexp)
19570 "Is point inside a match of REGEXP in the current line?"
19571 (catch 'exit
19572 (save-excursion
19573 (let ((pos (point)) (end (point-at-eol)))
19574 (beginning-of-line 1)
19575 (while (re-search-forward regexp end t)
19576 (if (and (<= (match-beginning 0) pos)
19577 (>= (match-end 0) pos))
19578 (throw 'exit t)))
19579 nil))))
19581 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
19582 "Non-nil when point is between matches of START-RE and END-RE.
19584 Also return a non-nil value when point is on one of the matches.
19586 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
19587 buffer positions. Default values are the positions of headlines
19588 surrounding the point.
19590 The functions returns a cons cell whose car (resp. cdr) is the
19591 position before START-RE (resp. after END-RE)."
19592 (save-match-data
19593 (let ((pos (point))
19594 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
19595 (limit-down (or lim-down (save-excursion (outline-next-heading))))
19596 beg end)
19597 (save-excursion
19598 ;; Point is on a block when on START-RE or if START-RE can be
19599 ;; found before it...
19600 (and (or (org-at-regexp-p start-re)
19601 (re-search-backward start-re limit-up t))
19602 (setq beg (match-beginning 0))
19603 ;; ... and END-RE after it...
19604 (goto-char (match-end 0))
19605 (re-search-forward end-re limit-down t)
19606 (> (setq end (match-end 0)) pos)
19607 ;; ... without another START-RE in-between.
19608 (goto-char (match-beginning 0))
19609 (not (re-search-backward start-re (1+ beg) t))
19610 ;; Return value.
19611 (cons beg end))))))
19613 (defun org-in-block-p (names)
19614 "Non-nil when point belongs to a block whose name belongs to NAMES.
19616 NAMES is a list of strings containing names of blocks.
19618 Return first block name matched, or nil. Beware that in case of
19619 nested blocks, the returned name may not belong to the closest
19620 block from point."
19621 (save-match-data
19622 (catch 'exit
19623 (let ((case-fold-search t)
19624 (lim-up (save-excursion (outline-previous-heading)))
19625 (lim-down (save-excursion (outline-next-heading))))
19626 (mapc (lambda (name)
19627 (let ((n (regexp-quote name)))
19628 (when (org-between-regexps-p
19629 (concat "^[ \t]*#\\+begin_" n)
19630 (concat "^[ \t]*#\\+end_" n)
19631 lim-up lim-down)
19632 (throw 'exit n))))
19633 names))
19634 nil)))
19636 (defun org-occur-in-agenda-files (regexp &optional nlines)
19637 "Call `multi-occur' with buffers for all agenda files."
19638 (interactive "sOrg-files matching: \np")
19639 (let* ((files (org-agenda-files))
19640 (tnames (mapcar 'file-truename files))
19641 (extra org-agenda-text-search-extra-files)
19643 (when (eq (car extra) 'agenda-archives)
19644 (setq extra (cdr extra))
19645 (setq files (org-add-archive-files files)))
19646 (while (setq f (pop extra))
19647 (unless (member (file-truename f) tnames)
19648 (add-to-list 'files f 'append)
19649 (add-to-list 'tnames (file-truename f) 'append)))
19650 (multi-occur
19651 (mapcar (lambda (x)
19652 (with-current-buffer
19653 (or (get-file-buffer x) (find-file-noselect x))
19654 (widen)
19655 (current-buffer)))
19656 files)
19657 regexp)))
19659 (if (boundp 'occur-mode-find-occurrence-hook)
19660 ;; Emacs 23
19661 (add-hook 'occur-mode-find-occurrence-hook
19662 (lambda ()
19663 (when (eq major-mode 'org-mode)
19664 (org-reveal))))
19665 ;; Emacs 22
19666 (defadvice occur-mode-goto-occurrence
19667 (after org-occur-reveal activate)
19668 (and (eq major-mode 'org-mode) (org-reveal)))
19669 (defadvice occur-mode-goto-occurrence-other-window
19670 (after org-occur-reveal activate)
19671 (and (eq major-mode 'org-mode) (org-reveal)))
19672 (defadvice occur-mode-display-occurrence
19673 (after org-occur-reveal activate)
19674 (when (eq major-mode 'org-mode)
19675 (let ((pos (occur-mode-find-occurrence)))
19676 (with-current-buffer (marker-buffer pos)
19677 (save-excursion
19678 (goto-char pos)
19679 (org-reveal)))))))
19681 (defun org-occur-link-in-agenda-files ()
19682 "Create a link and search for it in the agendas.
19683 The link is not stored in `org-stored-links', it is just created
19684 for the search purpose."
19685 (interactive)
19686 (let ((link (condition-case nil
19687 (org-store-link nil)
19688 (error "Unable to create a link to here"))))
19689 (org-occur-in-agenda-files (regexp-quote link))))
19691 (defun org-uniquify (list)
19692 "Remove duplicate elements from LIST."
19693 (let (res)
19694 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
19695 res))
19697 (defun org-delete-all (elts list)
19698 "Remove all elements in ELTS from LIST."
19699 (while elts
19700 (setq list (delete (pop elts) list)))
19701 list)
19703 (defun org-count (cl-item cl-seq)
19704 "Count the number of occurrences of ITEM in SEQ.
19705 Taken from `count' in cl-seq.el with all keyword arguments removed."
19706 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
19707 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
19708 (while (< cl-start cl-end)
19709 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
19710 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
19711 (setq cl-start (1+ cl-start)))
19712 cl-count))
19714 (defun org-remove-if (predicate seq)
19715 "Remove everything from SEQ that fulfills PREDICATE."
19716 (let (res e)
19717 (while seq
19718 (setq e (pop seq))
19719 (if (not (funcall predicate e)) (push e res)))
19720 (nreverse res)))
19722 (defun org-remove-if-not (predicate seq)
19723 "Remove everything from SEQ that does not fulfill PREDICATE."
19724 (let (res e)
19725 (while seq
19726 (setq e (pop seq))
19727 (if (funcall predicate e) (push e res)))
19728 (nreverse res)))
19730 (defun org-reduce (cl-func cl-seq &rest cl-keys)
19731 "Reduce two-argument FUNCTION across SEQ.
19732 Taken from `reduce' in cl-seq.el with all keyword arguments but
19733 \":initial-value\" removed."
19734 (let ((cl-accum (cond ((memq :initial-value cl-keys)
19735 (cadr (memq :initial-value cl-keys)))
19736 (cl-seq (pop cl-seq))
19737 (t (funcall cl-func)))))
19738 (while cl-seq
19739 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
19740 cl-accum))
19742 (defun org-back-over-empty-lines ()
19743 "Move backwards over whitespace, to the beginning of the first empty line.
19744 Returns the number of empty lines passed."
19745 (let ((pos (point)))
19746 (if (cdr (assoc 'heading org-blank-before-new-entry))
19747 (skip-chars-backward " \t\n\r")
19748 (unless (eobp)
19749 (forward-line -1)))
19750 (beginning-of-line 2)
19751 (goto-char (min (point) pos))
19752 (count-lines (point) pos)))
19754 (defun org-skip-whitespace ()
19755 (skip-chars-forward " \t\n\r"))
19757 (defun org-point-in-group (point group &optional context)
19758 "Check if POINT is in match-group GROUP.
19759 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
19760 match. If the match group does not exist or point is not inside it,
19761 return nil."
19762 (and (match-beginning group)
19763 (>= point (match-beginning group))
19764 (<= point (match-end group))
19765 (if context
19766 (list context (match-beginning group) (match-end group))
19767 t)))
19769 (defun org-switch-to-buffer-other-window (&rest args)
19770 "Switch to buffer in a second window on the current frame.
19771 In particular, do not allow pop-up frames.
19772 Returns the newly created buffer."
19773 (let (pop-up-frames special-display-buffer-names special-display-regexps
19774 special-display-function)
19775 (apply 'switch-to-buffer-other-window args)))
19777 (defun org-combine-plists (&rest plists)
19778 "Create a single property list from all plists in PLISTS.
19779 The process starts by copying the first list, and then setting properties
19780 from the other lists. Settings in the last list are the most significant
19781 ones and overrule settings in the other lists."
19782 (let ((rtn (copy-sequence (pop plists)))
19783 p v ls)
19784 (while plists
19785 (setq ls (pop plists))
19786 (while ls
19787 (setq p (pop ls) v (pop ls))
19788 (setq rtn (plist-put rtn p v))))
19789 rtn))
19791 (defun org-move-line-down (arg)
19792 "Move the current line down. With prefix argument, move it past ARG lines."
19793 (interactive "p")
19794 (let ((col (current-column))
19795 beg end pos)
19796 (beginning-of-line 1) (setq beg (point))
19797 (beginning-of-line 2) (setq end (point))
19798 (beginning-of-line (+ 1 arg))
19799 (setq pos (move-marker (make-marker) (point)))
19800 (insert (delete-and-extract-region beg end))
19801 (goto-char pos)
19802 (org-move-to-column col)))
19804 (defun org-move-line-up (arg)
19805 "Move the current line up. With prefix argument, move it past ARG lines."
19806 (interactive "p")
19807 (let ((col (current-column))
19808 beg end pos)
19809 (beginning-of-line 1) (setq beg (point))
19810 (beginning-of-line 2) (setq end (point))
19811 (beginning-of-line (- arg))
19812 (setq pos (move-marker (make-marker) (point)))
19813 (insert (delete-and-extract-region beg end))
19814 (goto-char pos)
19815 (org-move-to-column col)))
19817 (defun org-replace-escapes (string table)
19818 "Replace %-escapes in STRING with values in TABLE.
19819 TABLE is an association list with keys like \"%a\" and string values.
19820 The sequences in STRING may contain normal field width and padding information,
19821 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
19822 so values can contain further %-escapes if they are define later in TABLE."
19823 (let ((tbl (copy-alist table))
19824 (case-fold-search nil)
19825 (pchg 0)
19826 e re rpl)
19827 (while (setq e (pop tbl))
19828 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
19829 (when (and (cdr e) (string-match re (cdr e)))
19830 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
19831 (safe "SREF"))
19832 (add-text-properties 0 3 (list 'sref sref) safe)
19833 (setcdr e (replace-match safe t t (cdr e)))))
19834 (while (string-match re string)
19835 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
19836 (cdr e)))
19837 (setq string (replace-match rpl t t string))))
19838 (while (setq pchg (next-property-change pchg string))
19839 (let ((sref (get-text-property pchg 'sref string)))
19840 (when (and sref (string-match "SREF" string pchg))
19841 (setq string (replace-match sref t t string)))))
19842 string))
19844 (defun org-sublist (list start end)
19845 "Return a section of LIST, from START to END.
19846 Counting starts at 1."
19847 (let (rtn (c start))
19848 (setq list (nthcdr (1- start) list))
19849 (while (and list (<= c end))
19850 (push (pop list) rtn)
19851 (setq c (1+ c)))
19852 (nreverse rtn)))
19854 (defun org-find-base-buffer-visiting (file)
19855 "Like `find-buffer-visiting' but always return the base buffer and
19856 not an indirect buffer."
19857 (let ((buf (or (get-file-buffer file)
19858 (find-buffer-visiting file))))
19859 (if buf
19860 (or (buffer-base-buffer buf) buf)
19861 nil)))
19863 (defun org-image-file-name-regexp (&optional extensions)
19864 "Return regexp matching the file names of images.
19865 If EXTENSIONS is given, only match these."
19866 (if (and (not extensions) (fboundp 'image-file-name-regexp))
19867 (image-file-name-regexp)
19868 (let ((image-file-name-extensions
19869 (or extensions
19870 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
19871 "xbm" "xpm" "pbm" "pgm" "ppm"))))
19872 (concat "\\."
19873 (regexp-opt (nconc (mapcar 'upcase
19874 image-file-name-extensions)
19875 image-file-name-extensions)
19877 "\\'"))))
19879 (defun org-file-image-p (file &optional extensions)
19880 "Return non-nil if FILE is an image."
19881 (save-match-data
19882 (string-match (org-image-file-name-regexp extensions) file)))
19884 (defun org-get-cursor-date ()
19885 "Return the date at cursor in as a time.
19886 This works in the calendar and in the agenda, anywhere else it just
19887 returns the current time."
19888 (let (date day defd)
19889 (cond
19890 ((eq major-mode 'calendar-mode)
19891 (setq date (calendar-cursor-to-date)
19892 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
19893 ((eq major-mode 'org-agenda-mode)
19894 (setq day (get-text-property (point) 'day))
19895 (if day
19896 (setq date (calendar-gregorian-from-absolute day)
19897 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
19898 (nth 2 date))))))
19899 (or defd (current-time))))
19901 (defvar org-agenda-action-marker (make-marker)
19902 "Marker pointing to the entry for the next agenda action.")
19904 (defun org-mark-entry-for-agenda-action ()
19905 "Mark the current entry as target of an agenda action.
19906 Agenda actions are actions executed from the agenda with the key `k',
19907 which make use of the date at the cursor."
19908 (interactive)
19909 (move-marker org-agenda-action-marker
19910 (save-excursion (org-back-to-heading t) (point))
19911 (current-buffer))
19912 (message
19913 "Entry marked for action; press `k' at desired date in agenda or calendar"))
19915 (defun org-mark-subtree ()
19916 "Mark the current subtree.
19917 This puts point at the start of the current subtree, and mark at the end.
19919 If point is in an inline task, mark that task instead."
19920 (interactive)
19921 (let ((inline-task-p
19922 (and (featurep 'org-inlinetask)
19923 (org-inlinetask-in-task-p)))
19924 (beg))
19925 ;; Get beginning of subtree
19926 (cond
19927 (inline-task-p (org-inlinetask-goto-beginning))
19928 ((org-at-heading-p) (beginning-of-line))
19929 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
19930 (setq beg (point))
19931 ;; Get end of it
19932 (if inline-task-p
19933 (org-inlinetask-goto-end)
19934 (org-end-of-subtree))
19935 ;; Mark zone
19936 (push-mark (point) nil t)
19937 (goto-char beg)))
19939 ;;; Paragraph filling stuff.
19940 ;; We want this to be just right, so use the full arsenal.
19942 (defun org-indent-line-function ()
19943 "Indent line depending on context."
19944 (interactive)
19945 (let* ((pos (point))
19946 (itemp (org-at-item-p))
19947 (case-fold-search t)
19948 (org-drawer-regexp (or org-drawer-regexp "\000"))
19949 (inline-task-p (and (featurep 'org-inlinetask)
19950 (org-inlinetask-in-task-p)))
19951 (inline-re (and inline-task-p
19952 (org-inlinetask-outline-regexp)))
19953 column)
19954 (beginning-of-line 1)
19955 (cond
19956 ;; Comments
19957 ((looking-at "# ") (setq column 0))
19958 ;; Headings
19959 ((looking-at org-outline-regexp) (setq column 0))
19960 ;; Included files
19961 ((looking-at "#\\+include:") (setq column 0))
19962 ;; Footnote definition
19963 ((looking-at org-footnote-definition-re) (setq column 0))
19964 ;; Literal examples
19965 ((looking-at "[ \t]*:\\( \\|$\\)")
19966 (setq column (org-get-indentation))) ; do nothing
19967 ;; Lists
19968 ((ignore-errors (goto-char (org-in-item-p)))
19969 (setq column (if itemp
19970 (org-get-indentation)
19971 (org-list-item-body-column (point))))
19972 (goto-char pos))
19973 ;; Drawers
19974 ((and (looking-at "[ \t]*:END:")
19975 (save-excursion (re-search-backward org-drawer-regexp nil t)))
19976 (save-excursion
19977 (goto-char (1- (match-beginning 1)))
19978 (setq column (current-column))))
19979 ;; Special blocks
19980 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
19981 (save-excursion
19982 (re-search-backward
19983 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
19984 (setq column (org-get-indentation (match-string 0))))
19985 ((and (not (looking-at "[ \t]*#\\+begin_"))
19986 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
19987 (save-excursion
19988 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
19989 (setq column
19990 (cond ((equal (downcase (match-string 1)) "src")
19991 ;; src blocks: let `org-edit-src-exit' handle them
19992 (org-get-indentation))
19993 ((equal (downcase (match-string 1)) "example")
19994 (max (org-get-indentation)
19995 (org-get-indentation (match-string 0))))
19997 (org-get-indentation (match-string 0))))))
19998 ;; This line has nothing special, look at the previous relevant
19999 ;; line to compute indentation
20001 (beginning-of-line 0)
20002 (while (and (not (bobp))
20003 (not (looking-at org-drawer-regexp))
20004 ;; When point started in an inline task, do not move
20005 ;; above task starting line.
20006 (not (and inline-task-p (looking-at inline-re)))
20007 ;; Skip drawers, blocks, empty lines, verbatim,
20008 ;; comments, tables, footnotes definitions, lists,
20009 ;; inline tasks.
20010 (or (and (looking-at "[ \t]*:END:")
20011 (re-search-backward org-drawer-regexp nil t))
20012 (and (looking-at "[ \t]*#\\+end_")
20013 (re-search-backward "[ \t]*#\\+begin_"nil t))
20014 (looking-at "[ \t]*[\n:#|]")
20015 (looking-at org-footnote-definition-re)
20016 (and (ignore-errors (goto-char (org-in-item-p)))
20017 (goto-char
20018 (org-list-get-top-point (org-list-struct))))
20019 (and (not inline-task-p)
20020 (featurep 'org-inlinetask)
20021 (org-inlinetask-in-task-p)
20022 (or (org-inlinetask-goto-beginning) t))))
20023 (beginning-of-line 0))
20024 (cond
20025 ;; There was an heading above.
20026 ((looking-at "\\*+[ \t]+")
20027 (if (not org-adapt-indentation)
20028 (setq column 0)
20029 (goto-char (match-end 0))
20030 (setq column (current-column))))
20031 ;; A drawer had started and is unfinished
20032 ((looking-at org-drawer-regexp)
20033 (goto-char (1- (match-beginning 1)))
20034 (setq column (current-column)))
20035 ;; Else, nothing noticeable found: get indentation and go on.
20036 (t (setq column (org-get-indentation))))))
20037 ;; Now apply indentation and move cursor accordingly
20038 (goto-char pos)
20039 (if (<= (current-column) (current-indentation))
20040 (org-indent-line-to column)
20041 (save-excursion (org-indent-line-to column)))
20042 ;; Special polishing for properties, see `org-property-format'
20043 (setq column (current-column))
20044 (beginning-of-line 1)
20045 (if (looking-at
20046 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20047 (replace-match (concat (match-string 1)
20048 (format org-property-format
20049 (match-string 2) (match-string 3)))
20050 t t))
20051 (org-move-to-column column)))
20053 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
20054 "Variable to store copy of `adaptive-fill-regexp'.
20055 Since `adaptive-fill-regexp' is set to never match, we need to
20056 store a backup of its value before entering `org-mode' so that
20057 the functionality can be provided as a fall-back.")
20059 (defun org-set-autofill-regexps ()
20060 (interactive)
20061 ;; In the paragraph separator we include headlines, because filling
20062 ;; text in a line directly attached to a headline would otherwise
20063 ;; fill the headline as well.
20064 (org-set-local 'comment-start-skip "^#+[ \t]*")
20065 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
20066 ;; The paragraph starter includes hand-formatted lists.
20067 (org-set-local
20068 'paragraph-start
20069 (concat
20070 "\f" "\\|"
20071 "[ ]*$" "\\|"
20072 org-outline-regexp "\\|"
20073 "[ \t]*#" "\\|"
20074 (org-item-re) "\\|"
20075 "[ \t]*[:|]" "\\|"
20076 "\\$\\$" "\\|"
20077 "\\\\\\(begin\\|end\\|[][]\\)"))
20078 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
20079 ;; But only if the user has not turned off tables or fixed-width regions
20080 (org-set-local
20081 'auto-fill-inhibit-regexp
20082 (concat org-outline-regexp
20083 "\\|#\\+"
20084 "\\|[ \t]*" org-keyword-time-regexp
20085 (if (or org-enable-table-editor org-enable-fixed-width-editor)
20086 (concat
20087 "\\|[ \t]*["
20088 (if org-enable-table-editor "|" "")
20089 (if org-enable-fixed-width-editor ":" "")
20090 "]"))))
20091 ;; We use our own fill-paragraph function, to make sure that tables
20092 ;; and fixed-width regions are not wrapped. That function will pass
20093 ;; through to `fill-paragraph' when appropriate.
20094 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20095 ;; Prevent auto-fill from inserting unwanted new items.
20096 (if (boundp 'fill-nobreak-predicate)
20097 (org-set-local 'fill-nobreak-predicate
20098 (if (memq 'org-fill-item-nobreak-p fill-nobreak-predicate)
20099 fill-nobreak-predicate
20100 (cons 'org-fill-item-nobreak-p fill-nobreak-predicate))))
20101 ;; Adaptive filling: To get full control, first make sure that
20102 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
20103 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
20104 (org-set-local 'org-adaptive-fill-regexp-backup
20105 adaptive-fill-regexp))
20106 (org-set-local 'adaptive-fill-regexp "\000")
20107 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20108 (org-set-local 'adaptive-fill-function
20109 'org-adaptive-fill-function)
20110 (org-set-local
20111 'align-mode-rules-list
20112 '((org-in-buffer-settings
20113 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
20114 (modes . '(org-mode))))))
20116 (defun org-fill-item-nobreak-p ()
20117 "Non-nil when a line break at point would insert a new item."
20118 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
20120 (defun org-fill-paragraph (&optional justify)
20121 "Re-align a table, pass through to fill-paragraph if no table."
20122 (let ((table-p (org-at-table-p))
20123 (table.el-p (org-at-table.el-p))
20124 (itemp (org-in-item-p)))
20125 (cond ((and (equal (char-after (point-at-bol)) ?*)
20126 (save-excursion (goto-char (point-at-bol))
20127 (looking-at org-outline-regexp)))
20128 t) ; skip headlines
20129 (table.el-p t) ; skip table.el tables
20130 (table-p (org-table-align) t) ; align Org tables
20131 (itemp ; align text in items
20132 (let* ((struct (save-excursion (goto-char itemp)
20133 (org-list-struct)))
20134 (parents (org-list-parents-alist struct))
20135 (children (org-list-get-children itemp struct parents))
20136 beg end prev next prefix)
20137 ;; Determine in which part of item point is: before
20138 ;; first child, after last child, between two
20139 ;; sub-lists, or simply in item if there's no child.
20140 (cond
20141 ((not children)
20142 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20143 beg itemp
20144 end (org-list-get-item-end itemp struct)))
20145 ((< (point) (setq next (car children)))
20146 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20147 beg itemp
20148 end next))
20149 ((> (point) (setq prev (car (last children))))
20150 (setq beg (org-list-get-item-end prev struct)
20151 end (org-list-get-item-end itemp struct)
20152 prefix (save-excursion
20153 (goto-char beg)
20154 (skip-chars-forward " \t")
20155 (make-string (current-column) ?\ ))))
20156 (t (catch 'exit
20157 (while (setq next (pop children))
20158 (if (> (point) next)
20159 (setq prev next)
20160 (setq beg (org-list-get-item-end prev struct)
20161 end next
20162 prefix (save-excursion
20163 (goto-char beg)
20164 (skip-chars-forward " \t")
20165 (make-string (current-column) ?\ )))
20166 (throw 'exit nil))))))
20167 ;; Use `fill-paragraph' with buffer narrowed to item
20168 ;; without any child, and with our computed PREFIX.
20169 (flet ((fill-context-prefix (from to &optional flr) prefix))
20170 (save-restriction
20171 (narrow-to-region beg end)
20172 (save-excursion (fill-paragraph justify)))) t))
20173 ;; Special case where point is not in a list but is on
20174 ;; a paragraph adjacent to a list: make sure this paragraph
20175 ;; doesn't get merged with the end of the list by narrowing
20176 ;; buffer first.
20177 ((save-excursion (forward-paragraph -1)
20178 (setq itemp (org-in-item-p)))
20179 (let ((struct (save-excursion (goto-char itemp)
20180 (org-list-struct))))
20181 (save-restriction
20182 (narrow-to-region (org-list-get-bottom-point struct)
20183 (save-excursion (forward-paragraph 1)
20184 (point)))
20185 (fill-paragraph justify) t)))
20186 ;; Else simply call `fill-paragraph'.
20187 (t nil))))
20189 ;; For reference, this is the default value of adaptive-fill-regexp
20190 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
20192 (defun org-adaptive-fill-function ()
20193 "Return a fill prefix for org-mode files."
20194 (let (itemp)
20195 (save-excursion
20196 (cond
20197 ;; Comment line
20198 ((looking-at "#[ \t]+")
20199 (match-string-no-properties 0))
20200 ;; Plain list item
20201 ((org-at-item-p)
20202 (make-string (org-list-item-body-column (point-at-bol)) ?\ ))
20203 ;; Point is in a list after `backward-paragraph': original
20204 ;; point wasn't in the list, or filling would have been taken
20205 ;; care of by `org-auto-fill-function', but the list and the
20206 ;; real paragraph are not separated by a blank line. Thus, move
20207 ;; point after the list to go back to real paragraph and
20208 ;; determine fill-prefix.
20209 ((setq itemp (org-in-item-p))
20210 (goto-char itemp)
20211 (let* ((struct (org-list-struct))
20212 (bottom (org-list-get-bottom-point struct)))
20213 (goto-char bottom)
20214 (make-string (org-get-indentation) ?\ )))
20215 ;; Other text
20216 ((looking-at org-adaptive-fill-regexp-backup)
20217 (match-string-no-properties 0))))))
20219 (defun org-auto-fill-function ()
20220 "Auto-fill function."
20221 (let (itemp prefix)
20222 ;; When in a list, compute an appropriate fill-prefix and make
20223 ;; sure it will be used by `do-auto-fill'.
20224 (if (setq itemp (org-in-item-p))
20225 (progn
20226 (setq prefix (make-string (org-list-item-body-column itemp) ?\ ))
20227 (flet ((fill-context-prefix (from to &optional flr) prefix))
20228 (do-auto-fill)))
20229 ;; Else just use `do-auto-fill'.
20230 (do-auto-fill))))
20232 ;;; Other stuff.
20234 (defun org-toggle-fixed-width-section (arg)
20235 "Toggle the fixed-width export.
20236 If there is no active region, the QUOTE keyword at the current headline is
20237 inserted or removed. When present, it causes the text between this headline
20238 and the next to be exported as fixed-width text, and unmodified.
20239 If there is an active region, this command adds or removes a colon as the
20240 first character of this line. If the first character of a line is a colon,
20241 this line is also exported in fixed-width font."
20242 (interactive "P")
20243 (let* ((cc 0)
20244 (regionp (org-region-active-p))
20245 (beg (if regionp (region-beginning) (point)))
20246 (end (if regionp (region-end)))
20247 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
20248 (case-fold-search nil)
20249 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
20250 off)
20251 (if regionp
20252 (save-excursion
20253 (goto-char beg)
20254 (setq cc (current-column))
20255 (beginning-of-line 1)
20256 (setq off (looking-at re))
20257 (while (> nlines 0)
20258 (setq nlines (1- nlines))
20259 (beginning-of-line 1)
20260 (cond
20261 (arg
20262 (org-move-to-column cc t)
20263 (insert ": \n")
20264 (forward-line -1))
20265 ((and off (looking-at re))
20266 (replace-match "" t t nil 1))
20267 ((not off) (org-move-to-column cc t) (insert ": ")))
20268 (forward-line 1)))
20269 (save-excursion
20270 (org-back-to-heading)
20271 (cond
20272 ((looking-at (format org-heading-keyword-regexp-format
20273 org-quote-string))
20274 (goto-char (match-end 1))
20275 (looking-at (concat " +" org-quote-string))
20276 (replace-match "" t t)
20277 (when (eolp) (insert " ")))
20278 ((looking-at org-outline-regexp)
20279 (goto-char (match-end 0))
20280 (insert org-quote-string " ")))))))
20282 (defun org-reftex-citation ()
20283 "Use reftex-citation to insert a citation into the buffer.
20284 This looks for a line like
20286 #+BIBLIOGRAPHY: foo plain option:-d
20288 and derives from it that foo.bib is the bibliography file relevant
20289 for this document. It then installs the necessary environment for RefTeX
20290 to work in this buffer and calls `reftex-citation' to insert a citation
20291 into the buffer.
20293 Export of such citations to both LaTeX and HTML is handled by the contributed
20294 package org-exp-bibtex by Taru Karttunen."
20295 (interactive)
20296 (let ((reftex-docstruct-symbol 'rds)
20297 (reftex-cite-format "\\cite{%l}")
20298 rds bib)
20299 (save-excursion
20300 (save-restriction
20301 (widen)
20302 (let ((case-fold-search t)
20303 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
20304 (if (not (save-excursion
20305 (or (re-search-forward re nil t)
20306 (re-search-backward re nil t))))
20307 (error "No bibliography defined in file")
20308 (setq bib (concat (match-string 1) ".bib")
20309 rds (list (list 'bib bib)))))))
20310 (call-interactively 'reftex-citation)))
20312 ;;;; Functions extending outline functionality
20314 (defun org-beginning-of-line (&optional arg)
20315 "Go to the beginning of the current line. If that is invisible, continue
20316 to a visible line beginning. This makes the function of C-a more intuitive.
20317 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20318 first attempt, and only move to after the tags when the cursor is already
20319 beyond the end of the headline."
20320 (interactive "P")
20321 (let ((pos (point))
20322 (special (if (consp org-special-ctrl-a/e)
20323 (car org-special-ctrl-a/e)
20324 org-special-ctrl-a/e))
20325 refpos)
20326 (if (org-bound-and-true-p line-move-visual)
20327 (beginning-of-visual-line 1)
20328 (beginning-of-line 1))
20329 (if (and arg (fboundp 'move-beginning-of-line))
20330 (call-interactively 'move-beginning-of-line)
20331 (if (bobp)
20333 (backward-char 1)
20334 (if (org-truely-invisible-p)
20335 (while (and (not (bobp)) (org-truely-invisible-p))
20336 (backward-char 1)
20337 (beginning-of-line 1))
20338 (forward-char 1))))
20339 (when special
20340 (cond
20341 ((and (looking-at org-complex-heading-regexp)
20342 (= (char-after (match-end 1)) ?\ ))
20343 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
20344 (point-at-eol)))
20345 (goto-char
20346 (if (eq special t)
20347 (cond ((> pos refpos) refpos)
20348 ((= pos (point)) refpos)
20349 (t (point)))
20350 (cond ((> pos (point)) (point))
20351 ((not (eq last-command this-command)) (point))
20352 (t refpos)))))
20353 ((org-at-item-p)
20354 (goto-char
20355 (if (eq special t)
20356 (cond ((> pos (match-end 0)) (match-end 0))
20357 ((= pos (point)) (match-end 0))
20358 (t (point)))
20359 (cond ((> pos (point)) (point))
20360 ((not (eq last-command this-command)) (point))
20361 (t (match-end 0))))))))
20362 (org-no-warnings
20363 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20365 (defun org-end-of-line (&optional arg)
20366 "Go to the end of the line.
20367 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20368 first attempt, and only move to after the tags when the cursor is already
20369 beyond the end of the headline."
20370 (interactive "P")
20371 (let ((special (if (consp org-special-ctrl-a/e)
20372 (cdr org-special-ctrl-a/e)
20373 org-special-ctrl-a/e)))
20374 (cond
20375 ((or (not special) arg
20376 (not (or (org-on-heading-p) (org-at-item-p))))
20377 (call-interactively
20378 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
20379 ((fboundp 'move-end-of-line) 'move-end-of-line)
20380 (t 'end-of-line))))
20381 ((org-on-heading-p)
20382 (let ((pos (point)))
20383 (beginning-of-line 1)
20384 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
20385 (if (eq special t)
20386 (if (or (< pos (match-beginning 1))
20387 (= pos (match-end 0)))
20388 (goto-char (match-beginning 1))
20389 (goto-char (match-end 0)))
20390 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
20391 (goto-char (match-end 0))
20392 (goto-char (match-beginning 1))))
20393 (call-interactively (if (fboundp 'move-end-of-line)
20394 'move-end-of-line
20395 'end-of-line)))))
20396 ;; At an item: Move before any hidden text.
20397 (t (call-interactively 'end-of-line)))
20398 (org-no-warnings
20399 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20401 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
20402 (define-key org-mode-map "\C-e" 'org-end-of-line)
20404 (defun org-backward-sentence (&optional arg)
20405 "Go to beginning of sentence, or beginning of table field.
20406 This will call `backward-sentence' or `org-table-beginning-of-field',
20407 depending on context."
20408 (interactive "P")
20409 (cond
20410 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
20411 (t (call-interactively 'backward-sentence))))
20413 (defun org-forward-sentence (&optional arg)
20414 "Go to end of sentence, or end of table field.
20415 This will call `forward-sentence' or `org-table-end-of-field',
20416 depending on context."
20417 (interactive "P")
20418 (cond
20419 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
20420 (t (call-interactively 'forward-sentence))))
20422 (define-key org-mode-map "\M-a" 'org-backward-sentence)
20423 (define-key org-mode-map "\M-e" 'org-forward-sentence)
20425 (defun org-kill-line (&optional arg)
20426 "Kill line, to tags or end of line."
20427 (interactive "P")
20428 (cond
20429 ((or (not org-special-ctrl-k)
20430 (bolp)
20431 (not (org-on-heading-p)))
20432 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
20433 org-ctrl-k-protect-subtree)
20434 (if (or (eq org-ctrl-k-protect-subtree 'error)
20435 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
20436 (error "C-k aborted - would kill hidden subtree")))
20437 (call-interactively 'kill-line))
20438 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
20439 (kill-region (point) (match-beginning 1))
20440 (org-set-tags nil t))
20441 (t (kill-region (point) (point-at-eol)))))
20443 (define-key org-mode-map "\C-k" 'org-kill-line)
20445 (defun org-yank (&optional arg)
20446 "Yank. If the kill is a subtree, treat it specially.
20447 This command will look at the current kill and check if is a single
20448 subtree, or a series of subtrees[1]. If it passes the test, and if the
20449 cursor is at the beginning of a line or after the stars of a currently
20450 empty headline, then the yank is handled specially. How exactly depends
20451 on the value of the following variables, both set by default.
20453 org-yank-folded-subtrees
20454 When set, the subtree(s) will be folded after insertion, but only
20455 if doing so would now swallow text after the yanked text.
20457 org-yank-adjusted-subtrees
20458 When set, the subtree will be promoted or demoted in order to
20459 fit into the local outline tree structure, which means that the level
20460 will be adjusted so that it becomes the smaller one of the two
20461 *visible* surrounding headings.
20463 Any prefix to this command will cause `yank' to be called directly with
20464 no special treatment. In particular, a simple \\[universal-argument] prefix \
20465 will just
20466 plainly yank the text as it is.
20468 \[1] The test checks if the first non-white line is a heading
20469 and if there are no other headings with fewer stars."
20470 (interactive "P")
20471 (org-yank-generic 'yank arg))
20473 (defun org-yank-generic (command arg)
20474 "Perform some yank-like command.
20476 This function implements the behavior described in the `org-yank'
20477 documentation. However, it has been generalized to work for any
20478 interactive command with similar behavior."
20480 ;; pretend to be command COMMAND
20481 (setq this-command command)
20483 (if arg
20484 (call-interactively command)
20486 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
20487 (and (org-kill-is-subtree-p)
20488 (or (bolp)
20489 (and (looking-at "[ \t]*$")
20490 (string-match
20491 "\\`\\*+\\'"
20492 (buffer-substring (point-at-bol) (point)))))))
20493 swallowp)
20494 (cond
20495 ((and subtreep org-yank-folded-subtrees)
20496 (let ((beg (point))
20497 end)
20498 (if (and subtreep org-yank-adjusted-subtrees)
20499 (org-paste-subtree nil nil 'for-yank)
20500 (call-interactively command))
20502 (setq end (point))
20503 (goto-char beg)
20504 (when (and (bolp) subtreep
20505 (not (setq swallowp
20506 (org-yank-folding-would-swallow-text beg end))))
20507 (org-with-limited-levels
20508 (or (looking-at org-outline-regexp)
20509 (re-search-forward org-outline-regexp-bol end t))
20510 (while (and (< (point) end) (looking-at org-outline-regexp))
20511 (hide-subtree)
20512 (org-cycle-show-empty-lines 'folded)
20513 (condition-case nil
20514 (outline-forward-same-level 1)
20515 (error (goto-char end))))))
20516 (when swallowp
20517 (message
20518 "Inserted text not folded because that would swallow text"))
20520 (goto-char end)
20521 (skip-chars-forward " \t\n\r")
20522 (beginning-of-line 1)
20523 (push-mark beg 'nomsg)))
20524 ((and subtreep org-yank-adjusted-subtrees)
20525 (let ((beg (point-at-bol)))
20526 (org-paste-subtree nil nil 'for-yank)
20527 (push-mark beg 'nomsg)))
20529 (call-interactively command))))))
20531 (defun org-yank-folding-would-swallow-text (beg end)
20532 "Would hide-subtree at BEG swallow any text after END?"
20533 (let (level)
20534 (org-with-limited-levels
20535 (save-excursion
20536 (goto-char beg)
20537 (when (or (looking-at org-outline-regexp)
20538 (re-search-forward org-outline-regexp-bol end t))
20539 (setq level (org-outline-level)))
20540 (goto-char end)
20541 (skip-chars-forward " \t\r\n\v\f")
20542 (if (or (eobp)
20543 (and (bolp) (looking-at org-outline-regexp)
20544 (<= (org-outline-level) level)))
20545 nil ; Nothing would be swallowed
20546 t))))) ; something would swallow
20548 (define-key org-mode-map "\C-y" 'org-yank)
20550 (defun org-truely-invisible-p ()
20551 "Check if point is at a character currently not visible.
20552 This version does not only check the character property, but also
20553 `visible-mode'."
20554 ;; Early versions of noutline don't have `outline-invisible-p'.
20555 (if (org-bound-and-true-p visible-mode)
20557 (outline-invisible-p)))
20559 (defun org-invisible-p2 ()
20560 "Check if point is at a character currently not visible."
20561 (save-excursion
20562 (if (and (eolp) (not (bobp))) (backward-char 1))
20563 ;; Early versions of noutline don't have `outline-invisible-p'.
20564 (outline-invisible-p)))
20566 (defun org-back-to-heading (&optional invisible-ok)
20567 "Call `outline-back-to-heading', but provide a better error message."
20568 (condition-case nil
20569 (outline-back-to-heading invisible-ok)
20570 (error (error "Before first headline at position %d in buffer %s"
20571 (point) (current-buffer)))))
20573 (defun org-beginning-of-defun ()
20574 "Go to the beginning of the subtree, i.e. back to the heading."
20575 (org-back-to-heading))
20576 (defun org-end-of-defun ()
20577 "Go to the end of the subtree."
20578 (org-end-of-subtree nil t))
20580 (defun org-before-first-heading-p ()
20581 "Before first heading?"
20582 (save-excursion
20583 (end-of-line)
20584 (null (re-search-backward org-outline-regexp-bol nil t))))
20586 (defun org-on-heading-p (&optional ignored)
20587 (outline-on-heading-p t))
20588 (defun org-at-heading-p (&optional ignored)
20589 (outline-on-heading-p t))
20591 (defun org-point-at-end-of-empty-headline ()
20592 "If point is at the end of an empty headline, return t, else nil.
20593 If the heading only contains a TODO keyword, it is still still considered
20594 empty."
20595 (and (looking-at "[ \t]*$")
20596 (save-excursion
20597 (beginning-of-line 1)
20598 (let ((case-fold-search nil))
20599 (looking-at org-todo-line-regexp)))
20600 (string= (match-string 3) "")))
20602 (defun org-at-heading-or-item-p ()
20603 (or (org-on-heading-p) (org-at-item-p)))
20605 (defun org-on-target-p ()
20606 (or (org-in-regexp org-radio-target-regexp)
20607 (org-in-regexp org-target-regexp)))
20609 (defun org-up-heading-all (arg)
20610 "Move to the heading line of which the present line is a subheading.
20611 This function considers both visible and invisible heading lines.
20612 With argument, move up ARG levels."
20613 (if (fboundp 'outline-up-heading-all)
20614 (outline-up-heading-all arg) ; emacs 21 version of outline.el
20615 (outline-up-heading arg t))) ; emacs 22 version of outline.el
20617 (defun org-up-heading-safe ()
20618 "Move to the heading line of which the present line is a subheading.
20619 This version will not throw an error. It will return the level of the
20620 headline found, or nil if no higher level is found.
20622 Also, this function will be a lot faster than `outline-up-heading',
20623 because it relies on stars being the outline starters. This can really
20624 make a significant difference in outlines with very many siblings."
20625 (let (start-level re)
20626 (org-back-to-heading t)
20627 (setq start-level (funcall outline-level))
20628 (if (equal start-level 1)
20630 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
20631 (if (re-search-backward re nil t)
20632 (funcall outline-level)))))
20634 (defun org-first-sibling-p ()
20635 "Is this heading the first child of its parents?"
20636 (interactive)
20637 (let ((re org-outline-regexp-bol)
20638 level l)
20639 (unless (org-at-heading-p t)
20640 (error "Not at a heading"))
20641 (setq level (funcall outline-level))
20642 (save-excursion
20643 (if (not (re-search-backward re nil t))
20645 (setq l (funcall outline-level))
20646 (< l level)))))
20648 (defun org-goto-sibling (&optional previous)
20649 "Goto the next sibling, even if it is invisible.
20650 When PREVIOUS is set, go to the previous sibling instead. Returns t
20651 when a sibling was found. When none is found, return nil and don't
20652 move point."
20653 (let ((fun (if previous 're-search-backward 're-search-forward))
20654 (pos (point))
20655 (re org-outline-regexp-bol)
20656 level l)
20657 (when (condition-case nil (org-back-to-heading t) (error nil))
20658 (setq level (funcall outline-level))
20659 (catch 'exit
20660 (or previous (forward-char 1))
20661 (while (funcall fun re nil t)
20662 (setq l (funcall outline-level))
20663 (when (< l level) (goto-char pos) (throw 'exit nil))
20664 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
20665 (goto-char pos)
20666 nil))))
20668 (defun org-show-siblings ()
20669 "Show all siblings of the current headline."
20670 (save-excursion
20671 (while (org-goto-sibling) (org-flag-heading nil)))
20672 (save-excursion
20673 (while (org-goto-sibling 'previous)
20674 (org-flag-heading nil))))
20676 (defun org-goto-first-child ()
20677 "Goto the first child, even if it is invisible.
20678 Return t when a child was found. Otherwise don't move point and
20679 return nil."
20680 (let (level (pos (point)) (re org-outline-regexp-bol))
20681 (when (condition-case nil (org-back-to-heading t) (error nil))
20682 (setq level (outline-level))
20683 (forward-char 1)
20684 (if (and (re-search-forward re nil t) (> (outline-level) level))
20685 (progn (goto-char (match-beginning 0)) t)
20686 (goto-char pos) nil))))
20688 (defun org-show-hidden-entry ()
20689 "Show an entry where even the heading is hidden."
20690 (save-excursion
20691 (org-show-entry)))
20693 (defun org-flag-heading (flag &optional entry)
20694 "Flag the current heading. FLAG non-nil means make invisible.
20695 When ENTRY is non-nil, show the entire entry."
20696 (save-excursion
20697 (org-back-to-heading t)
20698 ;; Check if we should show the entire entry
20699 (if entry
20700 (progn
20701 (org-show-entry)
20702 (save-excursion
20703 (and (outline-next-heading)
20704 (org-flag-heading nil))))
20705 (outline-flag-region (max (point-min) (1- (point)))
20706 (save-excursion (outline-end-of-heading) (point))
20707 flag))))
20709 (defun org-get-next-sibling ()
20710 "Move to next heading of the same level, and return point.
20711 If there is no such heading, return nil.
20712 This is like outline-next-sibling, but invisible headings are ok."
20713 (let ((level (funcall outline-level)))
20714 (outline-next-heading)
20715 (while (and (not (eobp)) (> (funcall outline-level) level))
20716 (outline-next-heading))
20717 (if (or (eobp) (< (funcall outline-level) level))
20719 (point))))
20721 (defun org-get-last-sibling ()
20722 "Move to previous heading of the same level, and return point.
20723 If there is no such heading, return nil."
20724 (let ((opoint (point))
20725 (level (funcall outline-level)))
20726 (outline-previous-heading)
20727 (when (and (/= (point) opoint) (outline-on-heading-p t))
20728 (while (and (> (funcall outline-level) level)
20729 (not (bobp)))
20730 (outline-previous-heading))
20731 (if (< (funcall outline-level) level)
20733 (point)))))
20735 (defun org-end-of-subtree (&optional invisible-OK to-heading)
20736 ;; This contains an exact copy of the original function, but it uses
20737 ;; `org-back-to-heading', to make it work also in invisible
20738 ;; trees. And is uses an invisible-OK argument.
20739 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
20740 ;; Furthermore, when used inside Org, finding the end of a large subtree
20741 ;; with many children and grandchildren etc, this can be much faster
20742 ;; than the outline version.
20743 (org-back-to-heading invisible-OK)
20744 (let ((first t)
20745 (level (funcall outline-level)))
20746 (if (and (eq major-mode 'org-mode) (< level 1000))
20747 ;; A true heading (not a plain list item), in Org-mode
20748 ;; This means we can easily find the end by looking
20749 ;; only for the right number of stars. Using a regexp to do
20750 ;; this is so much faster than using a Lisp loop.
20751 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
20752 (forward-char 1)
20753 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
20754 ;; something else, do it the slow way
20755 (while (and (not (eobp))
20756 (or first (> (funcall outline-level) level)))
20757 (setq first nil)
20758 (outline-next-heading)))
20759 (unless to-heading
20760 (if (memq (preceding-char) '(?\n ?\^M))
20761 (progn
20762 ;; Go to end of line before heading
20763 (forward-char -1)
20764 (if (memq (preceding-char) '(?\n ?\^M))
20765 ;; leave blank line before heading
20766 (forward-char -1))))))
20767 (point))
20769 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
20770 "Use Org version in org-mode, for dramatic speed-up."
20771 (if (eq major-mode 'org-mode)
20772 (progn
20773 (org-end-of-subtree nil t)
20774 (unless (eobp) (backward-char 1)))
20775 ad-do-it))
20777 (defun org-end-of-meta-data-and-drawers ()
20778 "Jump to the first text after meta data and drawers in the current entry.
20779 This will move over empty lines, lines with planning time stamps,
20780 clocking lines, and drawers."
20781 (org-back-to-heading t)
20782 (let ((end (save-excursion (outline-next-heading) (point)))
20783 (re (concat "\\(" org-drawer-regexp "\\)"
20784 "\\|" "[ \t]*" org-keyword-time-regexp)))
20785 (forward-line 1)
20786 (while (re-search-forward re end t)
20787 (if (not (match-end 1))
20788 ;; empty or planning line
20789 (forward-line 1)
20790 ;; a drawer, find the end
20791 (re-search-forward "^[ \t]*:END:" end 'move)
20792 (forward-line 1)))
20793 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
20794 (point)))
20796 (defun org-forward-same-level (arg &optional invisible-ok)
20797 "Move forward to the arg'th subheading at same level as this one.
20798 Stop at the first and last subheadings of a superior heading.
20799 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
20800 it wil also look at invisible ones."
20801 (interactive "p")
20802 (org-back-to-heading invisible-ok)
20803 (org-on-heading-p)
20804 (let* ((level (- (match-end 0) (match-beginning 0) 1))
20805 (re (format "^\\*\\{1,%d\\} " level))
20807 (forward-char 1)
20808 (while (> arg 0)
20809 (while (and (re-search-forward re nil 'move)
20810 (setq l (- (match-end 0) (match-beginning 0) 1))
20811 (= l level)
20812 (not invisible-ok)
20813 (progn (backward-char 1) (outline-invisible-p)))
20814 (if (< l level) (setq arg 1)))
20815 (setq arg (1- arg)))
20816 (beginning-of-line 1)))
20818 (defun org-backward-same-level (arg &optional invisible-ok)
20819 "Move backward to the arg'th subheading at same level as this one.
20820 Stop at the first and last subheadings of a superior heading."
20821 (interactive "p")
20822 (org-back-to-heading)
20823 (org-on-heading-p)
20824 (let* ((level (- (match-end 0) (match-beginning 0) 1))
20825 (re (format "^\\*\\{1,%d\\} " level))
20827 (while (> arg 0)
20828 (while (and (re-search-backward re nil 'move)
20829 (setq l (- (match-end 0) (match-beginning 0) 1))
20830 (= l level)
20831 (not invisible-ok)
20832 (outline-invisible-p))
20833 (if (< l level) (setq arg 1)))
20834 (setq arg (1- arg)))))
20836 (defun org-show-subtree ()
20837 "Show everything after this heading at deeper levels."
20838 (outline-flag-region
20839 (point)
20840 (save-excursion
20841 (org-end-of-subtree t t))
20842 nil))
20844 (defun org-show-entry ()
20845 "Show the body directly following this heading.
20846 Show the heading too, if it is currently invisible."
20847 (interactive)
20848 (save-excursion
20849 (condition-case nil
20850 (progn
20851 (org-back-to-heading t)
20852 (outline-flag-region
20853 (max (point-min) (1- (point)))
20854 (save-excursion
20855 (if (re-search-forward
20856 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
20857 (match-beginning 1)
20858 (point-max)))
20859 nil)
20860 (org-cycle-hide-drawers 'children))
20861 (error nil))))
20863 (defun org-make-options-regexp (kwds &optional extra)
20864 "Make a regular expression for keyword lines."
20865 (concat
20867 "#?[ \t]*\\+\\("
20868 (mapconcat 'regexp-quote kwds "\\|")
20869 (if extra (concat "\\|" extra))
20870 "\\):[ \t]*"
20871 "\\(.*\\)"))
20873 ;; Make isearch reveal the necessary context
20874 (defun org-isearch-end ()
20875 "Reveal context after isearch exits."
20876 (when isearch-success ; only if search was successful
20877 (if (featurep 'xemacs)
20878 ;; Under XEmacs, the hook is run in the correct place,
20879 ;; we directly show the context.
20880 (org-show-context 'isearch)
20881 ;; In Emacs the hook runs *before* restoring the overlays.
20882 ;; So we have to use a one-time post-command-hook to do this.
20883 ;; (Emacs 22 has a special variable, see function `org-mode')
20884 (unless (and (boundp 'isearch-mode-end-hook-quit)
20885 isearch-mode-end-hook-quit)
20886 ;; Only when the isearch was not quitted.
20887 (org-add-hook 'post-command-hook 'org-isearch-post-command
20888 'append 'local)))))
20890 (defun org-isearch-post-command ()
20891 "Remove self from hook, and show context."
20892 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
20893 (org-show-context 'isearch))
20896 ;;;; Integration with and fixes for other packages
20898 ;;; Imenu support
20900 (defvar org-imenu-markers nil
20901 "All markers currently used by Imenu.")
20902 (make-variable-buffer-local 'org-imenu-markers)
20904 (defun org-imenu-new-marker (&optional pos)
20905 "Return a new marker for use by Imenu, and remember the marker."
20906 (let ((m (make-marker)))
20907 (move-marker m (or pos (point)))
20908 (push m org-imenu-markers)
20911 (defun org-imenu-get-tree ()
20912 "Produce the index for Imenu."
20913 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
20914 (setq org-imenu-markers nil)
20915 (let* ((n org-imenu-depth)
20916 (re (concat "^" (org-get-limited-outline-regexp)))
20917 (subs (make-vector (1+ n) nil))
20918 (last-level 0)
20919 m level head)
20920 (save-excursion
20921 (save-restriction
20922 (widen)
20923 (goto-char (point-max))
20924 (while (re-search-backward re nil t)
20925 (setq level (org-reduced-level (funcall outline-level)))
20926 (when (<= level n)
20927 (looking-at org-complex-heading-regexp)
20928 (setq head (org-link-display-format
20929 (org-match-string-no-properties 4))
20930 m (org-imenu-new-marker))
20931 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
20932 (if (>= level last-level)
20933 (push (cons head m) (aref subs level))
20934 (push (cons head (aref subs (1+ level))) (aref subs level))
20935 (loop for i from (1+ level) to n do (aset subs i nil)))
20936 (setq last-level level)))))
20937 (aref subs 1)))
20939 (eval-after-load "imenu"
20940 '(progn
20941 (add-hook 'imenu-after-jump-hook
20942 (lambda ()
20943 (if (eq major-mode 'org-mode)
20944 (org-show-context 'org-goto))))))
20946 (defun org-link-display-format (link)
20947 "Replace a link with either the description, or the link target
20948 if no description is present"
20949 (save-match-data
20950 (if (string-match org-bracket-link-analytic-regexp link)
20951 (replace-match (if (match-end 5)
20952 (match-string 5 link)
20953 (concat (match-string 1 link)
20954 (match-string 3 link)))
20955 nil t link)
20956 link)))
20958 (defun org-toggle-link-display ()
20959 "Toggle the literal or descriptive display of links."
20960 (interactive)
20961 (if org-descriptive-links
20962 (progn (org-remove-from-invisibility-spec '(org-link))
20963 (org-restart-font-lock)
20964 (setq org-descriptive-links nil))
20965 (progn (add-to-invisibility-spec '(org-link))
20966 (org-restart-font-lock)
20967 (setq org-descriptive-links t))))
20969 ;; Speedbar support
20971 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
20972 "Overlay marking the agenda restriction line in speedbar.")
20973 (overlay-put org-speedbar-restriction-lock-overlay
20974 'face 'org-agenda-restriction-lock)
20975 (overlay-put org-speedbar-restriction-lock-overlay
20976 'help-echo "Agendas are currently limited to this item.")
20977 (org-detach-overlay org-speedbar-restriction-lock-overlay)
20979 (defun org-speedbar-set-agenda-restriction ()
20980 "Restrict future agenda commands to the location at point in speedbar.
20981 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
20982 (interactive)
20983 (require 'org-agenda)
20984 (let (p m tp np dir txt)
20985 (cond
20986 ((setq p (text-property-any (point-at-bol) (point-at-eol)
20987 'org-imenu t))
20988 (setq m (get-text-property p 'org-imenu-marker))
20989 (with-current-buffer (marker-buffer m)
20990 (goto-char m)
20991 (org-agenda-set-restriction-lock 'subtree)))
20992 ((setq p (text-property-any (point-at-bol) (point-at-eol)
20993 'speedbar-function 'speedbar-find-file))
20994 (setq tp (previous-single-property-change
20995 (1+ p) 'speedbar-function)
20996 np (next-single-property-change
20997 tp 'speedbar-function)
20998 dir (speedbar-line-directory)
20999 txt (buffer-substring-no-properties (or tp (point-min))
21000 (or np (point-max))))
21001 (with-current-buffer (find-file-noselect
21002 (let ((default-directory dir))
21003 (expand-file-name txt)))
21004 (unless (eq major-mode 'org-mode)
21005 (error "Cannot restrict to non-Org-mode file"))
21006 (org-agenda-set-restriction-lock 'file)))
21007 (t (error "Don't know how to restrict Org-mode's agenda")))
21008 (move-overlay org-speedbar-restriction-lock-overlay
21009 (point-at-bol) (point-at-eol))
21010 (setq current-prefix-arg nil)
21011 (org-agenda-maybe-redo)))
21013 (eval-after-load "speedbar"
21014 '(progn
21015 (speedbar-add-supported-extension ".org")
21016 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
21017 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
21018 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
21019 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
21020 (add-hook 'speedbar-visiting-tag-hook
21021 (lambda () (and (eq major-mode 'org-mode) (org-show-context 'org-goto))))))
21023 ;;; Fixes and Hacks for problems with other packages
21025 ;; Make flyspell not check words in links, to not mess up our keymap
21026 (defun org-mode-flyspell-verify ()
21027 "Don't let flyspell put overlays at active buttons, or on
21028 {todo,all-time,additional-option-like}-keywords."
21029 (let ((pos (max (1- (point)) (point-min)))
21030 (word (thing-at-point 'word)))
21031 (and (not (get-text-property pos 'keymap))
21032 (not (get-text-property pos 'org-no-flyspell))
21033 (not (member word org-todo-keywords-1))
21034 (not (member word org-all-time-keywords))
21035 (not (member word org-additional-option-like-keywords)))))
21037 (defun org-remove-flyspell-overlays-in (beg end)
21038 "Remove flyspell overlays in region."
21039 (and (org-bound-and-true-p flyspell-mode)
21040 (fboundp 'flyspell-delete-region-overlays)
21041 (flyspell-delete-region-overlays beg end))
21042 (add-text-properties beg end '(org-no-flyspell t)))
21044 ;; Make `bookmark-jump' shows the jump location if it was hidden.
21045 (eval-after-load "bookmark"
21046 '(if (boundp 'bookmark-after-jump-hook)
21047 ;; We can use the hook
21048 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
21049 ;; Hook not available, use advice
21050 (defadvice bookmark-jump (after org-make-visible activate)
21051 "Make the position visible."
21052 (org-bookmark-jump-unhide))))
21054 ;; Make sure saveplace shows the location if it was hidden
21055 (eval-after-load "saveplace"
21056 '(defadvice save-place-find-file-hook (after org-make-visible activate)
21057 "Make the position visible."
21058 (org-bookmark-jump-unhide)))
21060 ;; Make sure ecb shows the location if it was hidden
21061 (eval-after-load "ecb"
21062 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
21063 "Make hierarchy visible when jumping into location from ECB tree buffer."
21064 (if (eq major-mode 'org-mode)
21065 (org-show-context))))
21067 (defun org-bookmark-jump-unhide ()
21068 "Unhide the current position, to show the bookmark location."
21069 (and (eq major-mode 'org-mode)
21070 (or (outline-invisible-p)
21071 (save-excursion (goto-char (max (point-min) (1- (point))))
21072 (outline-invisible-p)))
21073 (org-show-context 'bookmark-jump)))
21075 ;; Make session.el ignore our circular variable
21076 (eval-after-load "session"
21077 '(add-to-list 'session-globals-exclude 'org-mark-ring))
21079 ;;;; Experimental code
21081 (defun org-closed-in-range ()
21082 "Sparse tree of items closed in a certain time range.
21083 Still experimental, may disappear in the future."
21084 (interactive)
21085 ;; Get the time interval from the user.
21086 (let* ((time1 (org-float-time
21087 (org-read-date nil 'to-time nil "Starting date: ")))
21088 (time2 (org-float-time
21089 (org-read-date nil 'to-time nil "End date:")))
21090 ;; callback function
21091 (callback (lambda ()
21092 (let ((time
21093 (org-float-time
21094 (apply 'encode-time
21095 (org-parse-time-string
21096 (match-string 1))))))
21097 ;; check if time in interval
21098 (and (>= time time1) (<= time time2))))))
21099 ;; make tree, check each match with the callback
21100 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
21102 ;;;; Finish up
21104 (provide 'org)
21106 (run-hooks 'org-load-hook)
21108 ;;; org.el ends here