org.el (org-show-context): Complete docstring.
[org-mode.git] / lisp / org.el
blob1003164a398a5636e6e2112736163fdfb5802021
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 a string, those commands will be performed on the
414 matching headlines within the active region. Such string must be
415 a tags/property/todo match as it is used in the agenda tags view.
417 The list of commands is:
418 - `org-schedule'
419 - `org-deadline'"
420 :type '(choice (const :tag "Don't loop" nil)
421 (const :tag "All headlines in active region" t)
422 (string :tag "Tags/Property/Todo matcher"))
423 :group 'org-todo
424 :group 'org-archive)
426 (defgroup org-startup nil
427 "Options concerning startup of Org-mode."
428 :tag "Org Startup"
429 :group 'org)
431 (defcustom org-startup-folded t
432 "Non-nil means entering Org-mode will switch to OVERVIEW.
433 This can also be configured on a per-file basis by adding one of
434 the following lines anywhere in the buffer:
436 #+STARTUP: fold (or `overview', this is equivalent)
437 #+STARTUP: nofold (or `showall', this is equivalent)
438 #+STARTUP: content
439 #+STARTUP: showeverything"
440 :group 'org-startup
441 :type '(choice
442 (const :tag "nofold: show all" nil)
443 (const :tag "fold: overview" t)
444 (const :tag "content: all headlines" content)
445 (const :tag "show everything, even drawers" showeverything)))
447 (defcustom org-startup-truncated t
448 "Non-nil means entering Org-mode will set `truncate-lines'.
449 This is useful since some lines containing links can be very long and
450 uninteresting. Also tables look terrible when wrapped."
451 :group 'org-startup
452 :type 'boolean)
454 (defcustom org-startup-indented nil
455 "Non-nil means turn on `org-indent-mode' on startup.
456 This can also be configured on a per-file basis by adding one of
457 the following lines anywhere in the buffer:
459 #+STARTUP: indent
460 #+STARTUP: noindent"
461 :group 'org-structure
462 :type '(choice
463 (const :tag "Not" nil)
464 (const :tag "Globally (slow on startup in large files)" t)))
466 (defcustom org-use-sub-superscripts t
467 "Non-nil means interpret \"_\" and \"^\" for export.
468 When this option is turned on, you can use TeX-like syntax for sub- and
469 superscripts. Several characters after \"_\" or \"^\" will be
470 considered as a single item - so grouping with {} is normally not
471 needed. For example, the following things will be parsed as single
472 sub- or superscripts.
474 10^24 or 10^tau several digits will be considered 1 item.
475 10^-12 or 10^-tau a leading sign with digits or a word
476 x^2-y^3 will be read as x^2 - y^3, because items are
477 terminated by almost any nonword/nondigit char.
478 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
480 Still, ambiguity is possible - so when in doubt use {} to enclose the
481 sub/superscript. If you set this variable to the symbol `{}',
482 the braces are *required* in order to trigger interpretations as
483 sub/superscript. This can be helpful in documents that need \"_\"
484 frequently in plain text.
486 Not all export backends support this, but HTML does.
488 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
489 :group 'org-startup
490 :group 'org-export-translation
491 :type '(choice
492 (const :tag "Always interpret" t)
493 (const :tag "Only with braces" {})
494 (const :tag "Never interpret" nil)))
496 (if (fboundp 'defvaralias)
497 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
500 (defcustom org-startup-with-beamer-mode nil
501 "Non-nil means turn on `org-beamer-mode' on startup.
502 This can also be configured on a per-file basis by adding one of
503 the following lines anywhere in the buffer:
505 #+STARTUP: beamer"
506 :group 'org-startup
507 :type 'boolean)
509 (defcustom org-startup-align-all-tables nil
510 "Non-nil means align all tables when visiting a file.
511 This is useful when the column width in tables is forced with <N> cookies
512 in table fields. Such tables will look correct only after the first re-align.
513 This can also be configured on a per-file basis by adding one of
514 the following lines anywhere in the buffer:
515 #+STARTUP: align
516 #+STARTUP: noalign"
517 :group 'org-startup
518 :type 'boolean)
520 (defcustom org-startup-with-inline-images nil
521 "Non-nil means show inline images when loading a new Org file.
522 This can also be configured on a per-file basis by adding one of
523 the following lines anywhere in the buffer:
524 #+STARTUP: inlineimages
525 #+STARTUP: noinlineimages"
526 :group 'org-startup
527 :type 'boolean)
529 (defcustom org-insert-mode-line-in-empty-file nil
530 "Non-nil means insert the first line setting Org-mode in empty files.
531 When the function `org-mode' is called interactively in an empty file, this
532 normally means that the file name does not automatically trigger Org-mode.
533 To ensure that the file will always be in Org-mode in the future, a
534 line enforcing Org-mode will be inserted into the buffer, if this option
535 has been set."
536 :group 'org-startup
537 :type 'boolean)
539 (defcustom org-replace-disputed-keys nil
540 "Non-nil means use alternative key bindings for some keys.
541 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
542 These keys are also used by other packages like shift-selection-mode'
543 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
544 If you want to use Org-mode together with one of these other modes,
545 or more generally if you would like to move some Org-mode commands to
546 other keys, set this variable and configure the keys with the variable
547 `org-disputed-keys'.
549 This option is only relevant at load-time of Org-mode, and must be set
550 *before* org.el is loaded. Changing it requires a restart of Emacs to
551 become effective."
552 :group 'org-startup
553 :type 'boolean)
555 (defcustom org-use-extra-keys nil
556 "Non-nil means use extra key sequence definitions for certain commands.
557 This happens automatically if you run XEmacs or if `window-system'
558 is nil. This variable lets you do the same manually. You must
559 set it before loading org.
561 Example: on Carbon Emacs 22 running graphically, with an external
562 keyboard on a Powerbook, the default way of setting M-left might
563 not work for either Alt or ESC. Setting this variable will make
564 it work for ESC."
565 :group 'org-startup
566 :type 'boolean)
568 (if (fboundp 'defvaralias)
569 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
571 (defcustom org-disputed-keys
572 '(([(shift up)] . [(meta p)])
573 ([(shift down)] . [(meta n)])
574 ([(shift left)] . [(meta -)])
575 ([(shift right)] . [(meta +)])
576 ([(control shift right)] . [(meta shift +)])
577 ([(control shift left)] . [(meta shift -)]))
578 "Keys for which Org-mode and other modes compete.
579 This is an alist, cars are the default keys, second element specifies
580 the alternative to use when `org-replace-disputed-keys' is t.
582 Keys can be specified in any syntax supported by `define-key'.
583 The value of this option takes effect only at Org-mode's startup,
584 therefore you'll have to restart Emacs to apply it after changing."
585 :group 'org-startup
586 :type 'alist)
588 (defun org-key (key)
589 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
590 Or return the original if not disputed.
591 Also apply the translations defined in `org-xemacs-key-equivalents'."
592 (when org-replace-disputed-keys
593 (let* ((nkey (key-description key))
594 (x (org-find-if (lambda (x)
595 (equal (key-description (car x)) nkey))
596 org-disputed-keys)))
597 (setq key (if x (cdr x) key))))
598 (when (featurep 'xemacs)
599 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
600 key)
602 (defun org-find-if (predicate seq)
603 (catch 'exit
604 (while seq
605 (if (funcall predicate (car seq))
606 (throw 'exit (car seq))
607 (pop seq)))))
609 (defun org-defkey (keymap key def)
610 "Define a key, possibly translated, as returned by `org-key'."
611 (define-key keymap (org-key key) def))
613 (defcustom org-ellipsis nil
614 "The ellipsis to use in the Org-mode outline.
615 When nil, just use the standard three dots. When a string, use that instead,
616 When a face, use the standard 3 dots, but with the specified face.
617 The change affects only Org-mode (which will then use its own display table).
618 Changing this requires executing `M-x org-mode' in a buffer to become
619 effective."
620 :group 'org-startup
621 :type '(choice (const :tag "Default" nil)
622 (face :tag "Face" :value org-warning)
623 (string :tag "String" :value "...#")))
625 (defvar org-display-table nil
626 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
628 (defgroup org-keywords nil
629 "Keywords in Org-mode."
630 :tag "Org Keywords"
631 :group 'org)
633 (defcustom org-deadline-string "DEADLINE:"
634 "String to mark deadline entries.
635 A deadline is this string, followed by a time stamp. Should be a word,
636 terminated by a colon. You can insert a schedule keyword and
637 a timestamp with \\[org-deadline].
638 Changes become only effective after restarting Emacs."
639 :group 'org-keywords
640 :type 'string)
642 (defcustom org-scheduled-string "SCHEDULED:"
643 "String to mark scheduled TODO entries.
644 A schedule is this string, followed by a time stamp. Should be a word,
645 terminated by a colon. You can insert a schedule keyword and
646 a timestamp with \\[org-schedule].
647 Changes become only effective after restarting Emacs."
648 :group 'org-keywords
649 :type 'string)
651 (defcustom org-closed-string "CLOSED:"
652 "String used as the prefix for timestamps logging closing a TODO entry."
653 :group 'org-keywords
654 :type 'string)
656 (defcustom org-clock-string "CLOCK:"
657 "String used as prefix for timestamps clocking work hours on an item."
658 :group 'org-keywords
659 :type 'string)
661 (defcustom org-comment-string "COMMENT"
662 "Entries starting with this keyword will never be exported.
663 An entry can be toggled between COMMENT and normal with
664 \\[org-toggle-comment].
665 Changes become only effective after restarting Emacs."
666 :group 'org-keywords
667 :type 'string)
669 (defcustom org-quote-string "QUOTE"
670 "Entries starting with this keyword will be exported in fixed-width font.
671 Quoting applies only to the text in the entry following the headline, and does
672 not extend beyond the next headline, even if that is lower level.
673 An entry can be toggled between QUOTE and normal with
674 \\[org-toggle-fixed-width-section]."
675 :group 'org-keywords
676 :type 'string)
678 (defconst org-repeat-re
679 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
680 "Regular expression for specifying repeated events.
681 After a match, group 1 contains the repeat expression.")
683 (defgroup org-structure nil
684 "Options concerning the general structure of Org-mode files."
685 :tag "Org Structure"
686 :group 'org)
688 (defgroup org-reveal-location nil
689 "Options about how to make context of a location visible."
690 :tag "Org Reveal Location"
691 :group 'org-structure)
693 (defconst org-context-choice
694 '(choice
695 (const :tag "Always" t)
696 (const :tag "Never" nil)
697 (repeat :greedy t :tag "Individual contexts"
698 (cons
699 (choice :tag "Context"
700 (const agenda)
701 (const org-goto)
702 (const occur-tree)
703 (const tags-tree)
704 (const link-search)
705 (const mark-goto)
706 (const bookmark-jump)
707 (const isearch)
708 (const default))
709 (boolean))))
710 "Contexts for the reveal options.")
712 (defcustom org-show-hierarchy-above '((default . t))
713 "Non-nil means show full hierarchy when revealing a location.
714 Org-mode often shows locations in an org-mode file which might have
715 been invisible before. When this is set, the hierarchy of headings
716 above the exposed location is shown.
717 Turning this off for example for sparse trees makes them very compact.
718 Instead of t, this can also be an alist specifying this option for different
719 contexts. Valid contexts are
720 agenda when exposing an entry from the agenda
721 org-goto when using the command `org-goto' on key C-c C-j
722 occur-tree when using the command `org-occur' on key C-c /
723 tags-tree when constructing a sparse tree based on tags matches
724 link-search when exposing search matches associated with a link
725 mark-goto when exposing the jump goal of a mark
726 bookmark-jump when exposing a bookmark location
727 isearch when exiting from an incremental search
728 default default for all contexts not set explicitly"
729 :group 'org-reveal-location
730 :type org-context-choice)
732 (defcustom org-show-following-heading '((default . nil))
733 "Non-nil means show following heading when revealing a location.
734 Org-mode often shows locations in an org-mode file which might have
735 been invisible before. When this is set, the heading following the
736 match is shown.
737 Turning this off for example for sparse trees makes them very compact,
738 but makes it harder to edit the location of the match. In such a case,
739 use the command \\[org-reveal] to show more context.
740 Instead of t, this can also be an alist specifying this option for different
741 contexts. See `org-show-hierarchy-above' for valid contexts."
742 :group 'org-reveal-location
743 :type org-context-choice)
745 (defcustom org-show-siblings '((default . nil) (isearch t))
746 "Non-nil means show all sibling heading when revealing a location.
747 Org-mode often shows locations in an org-mode file which might have
748 been invisible before. When this is set, the sibling of the current entry
749 heading are all made visible. If `org-show-hierarchy-above' is t,
750 the same happens on each level of the hierarchy above the current entry.
752 By default this is on for the isearch context, off for all other contexts.
753 Turning this off for example for sparse trees makes them very compact,
754 but makes it harder to edit the location of the match. In such a case,
755 use the command \\[org-reveal] to show more context.
756 Instead of t, this can also be an alist specifying this option for different
757 contexts. See `org-show-hierarchy-above' for valid contexts."
758 :group 'org-reveal-location
759 :type org-context-choice)
761 (defcustom org-show-entry-below '((default . nil))
762 "Non-nil means show the entry below a headline when revealing a location.
763 Org-mode often shows locations in an org-mode file which might have
764 been invisible before. When this is set, the text below the headline that is
765 exposed is also shown.
767 By default this is off for all contexts.
768 Instead of t, this can also be an alist specifying this option for different
769 contexts. See `org-show-hierarchy-above' for valid contexts."
770 :group 'org-reveal-location
771 :type org-context-choice)
773 (defcustom org-indirect-buffer-display 'other-window
774 "How should indirect tree buffers be displayed?
775 This applies to indirect buffers created with the commands
776 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
777 Valid values are:
778 current-window Display in the current window
779 other-window Just display in another window.
780 dedicated-frame Create one new frame, and re-use it each time.
781 new-frame Make a new frame each time. Note that in this case
782 previously-made indirect buffers are kept, and you need to
783 kill these buffers yourself."
784 :group 'org-structure
785 :group 'org-agenda-windows
786 :type '(choice
787 (const :tag "In current window" current-window)
788 (const :tag "In current frame, other window" other-window)
789 (const :tag "Each time a new frame" new-frame)
790 (const :tag "One dedicated frame" dedicated-frame)))
792 (defcustom org-use-speed-commands nil
793 "Non-nil means activate single letter commands at beginning of a headline.
794 This may also be a function to test for appropriate locations where speed
795 commands should be active."
796 :group 'org-structure
797 :type '(choice
798 (const :tag "Never" nil)
799 (const :tag "At beginning of headline stars" t)
800 (function)))
802 (defcustom org-speed-commands-user nil
803 "Alist of additional speed commands.
804 This list will be checked before `org-speed-commands-default'
805 when the variable `org-use-speed-commands' is non-nil
806 and when the cursor is at the beginning of a headline.
807 The car if each entry is a string with a single letter, which must
808 be assigned to `self-insert-command' in the global map.
809 The cdr is either a command to be called interactively, a function
810 to be called, or a form to be evaluated.
811 An entry that is just a list with a single string will be interpreted
812 as a descriptive headline that will be added when listing the speed
813 commands in the Help buffer using the `?' speed command."
814 :group 'org-structure
815 :type '(repeat :value ("k" . ignore)
816 (choice :value ("k" . ignore)
817 (list :tag "Descriptive Headline" (string :tag "Headline"))
818 (cons :tag "Letter and Command"
819 (string :tag "Command letter")
820 (choice
821 (function)
822 (sexp))))))
824 (defgroup org-cycle nil
825 "Options concerning visibility cycling in Org-mode."
826 :tag "Org Cycle"
827 :group 'org-structure)
829 (defcustom org-cycle-skip-children-state-if-no-children t
830 "Non-nil means skip CHILDREN state in entries that don't have any."
831 :group 'org-cycle
832 :type 'boolean)
834 (defcustom org-cycle-max-level nil
835 "Maximum level which should still be subject to visibility cycling.
836 Levels higher than this will, for cycling, be treated as text, not a headline.
837 When `org-odd-levels-only' is set, a value of N in this variable actually
838 means 2N-1 stars as the limiting headline.
839 When nil, cycle all levels.
840 Note that the limiting level of cycling is also influenced by
841 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
842 `org-inlinetask-min-level' is, cycling will be limited to levels one less
843 than its value."
844 :group 'org-cycle
845 :type '(choice
846 (const :tag "No limit" nil)
847 (integer :tag "Maximum level")))
849 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
850 "Names of drawers. Drawers are not opened by cycling on the headline above.
851 Drawers only open with a TAB on the drawer line itself. A drawer looks like
852 this:
853 :DRAWERNAME:
854 .....
855 :END:
856 The drawer \"PROPERTIES\" is special for capturing properties through
857 the property API.
859 Drawers can be defined on the per-file basis with a line like:
861 #+DRAWERS: HIDDEN STATE PROPERTIES"
862 :group 'org-structure
863 :group 'org-cycle
864 :type '(repeat (string :tag "Drawer Name")))
866 (defcustom org-hide-block-startup nil
867 "Non-nil means entering Org-mode will fold all blocks.
868 This can also be set in on a per-file basis with
870 #+STARTUP: hideblocks
871 #+STARTUP: showblocks"
872 :group 'org-startup
873 :group 'org-cycle
874 :type 'boolean)
876 (defcustom org-cycle-global-at-bob nil
877 "Cycle globally if cursor is at beginning of buffer and not at a headline.
878 This makes it possible to do global cycling without having to use S-TAB or
879 \\[universal-argument] TAB. For this special case to work, the first line \
880 of the buffer
881 must not be a headline - it may be empty or some other text. When used in
882 this way, `org-cycle-hook' is disables temporarily, to make sure the
883 cursor stays at the beginning of the buffer.
884 When this option is nil, don't do anything special at the beginning
885 of the buffer."
886 :group 'org-cycle
887 :type 'boolean)
889 (defcustom org-cycle-level-after-item/entry-creation t
890 "Non-nil means cycle entry level or item indentation in new empty entries.
892 When the cursor is at the end of an empty headline, i.e with only stars
893 and maybe a TODO keyword, TAB will then switch the entry to become a child,
894 and then all possible ancestor states, before returning to the original state.
895 This makes data entry extremely fast: M-RET to create a new headline,
896 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
898 When the cursor is at the end of an empty plain list item, one TAB will
899 make it a subitem, two or more tabs will back up to make this an item
900 higher up in the item hierarchy."
901 :group 'org-cycle
902 :type 'boolean)
904 (defcustom org-cycle-emulate-tab t
905 "Where should `org-cycle' emulate TAB.
906 nil Never
907 white Only in completely white lines
908 whitestart Only at the beginning of lines, before the first non-white char
909 t Everywhere except in headlines
910 exc-hl-bol Everywhere except at the start of a headline
911 If TAB is used in a place where it does not emulate TAB, the current subtree
912 visibility is cycled."
913 :group 'org-cycle
914 :type '(choice (const :tag "Never" nil)
915 (const :tag "Only in completely white lines" white)
916 (const :tag "Before first char in a line" whitestart)
917 (const :tag "Everywhere except in headlines" t)
918 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
921 (defcustom org-cycle-separator-lines 2
922 "Number of empty lines needed to keep an empty line between collapsed trees.
923 If you leave an empty line between the end of a subtree and the following
924 headline, this empty line is hidden when the subtree is folded.
925 Org-mode will leave (exactly) one empty line visible if the number of
926 empty lines is equal or larger to the number given in this variable.
927 So the default 2 means at least 2 empty lines after the end of a subtree
928 are needed to produce free space between a collapsed subtree and the
929 following headline.
931 If the number is negative, and the number of empty lines is at least -N,
932 all empty lines are shown.
934 Special case: when 0, never leave empty lines in collapsed view."
935 :group 'org-cycle
936 :type 'integer)
937 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
939 (defcustom org-pre-cycle-hook nil
940 "Hook that is run before visibility cycling is happening.
941 The function(s) in this hook must accept a single argument which indicates
942 the new state that will be set right after running this hook. The
943 argument is a symbol. Before a global state change, it can have the values
944 `overview', `content', or `all'. Before a local state change, it can have
945 the values `folded', `children', or `subtree'."
946 :group 'org-cycle
947 :type 'hook)
949 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
950 org-cycle-hide-drawers
951 org-cycle-show-empty-lines
952 org-optimize-window-after-visibility-change)
953 "Hook that is run after `org-cycle' has changed the buffer visibility.
954 The function(s) in this hook must accept a single argument which indicates
955 the new state that was set by the most recent `org-cycle' command. The
956 argument is a symbol. After a global state change, it can have the values
957 `overview', `content', or `all'. After a local state change, it can have
958 the values `folded', `children', or `subtree'."
959 :group 'org-cycle
960 :type 'hook)
962 (defgroup org-edit-structure nil
963 "Options concerning structure editing in Org-mode."
964 :tag "Org Edit Structure"
965 :group 'org-structure)
967 (defcustom org-odd-levels-only nil
968 "Non-nil means skip even levels and only use odd levels for the outline.
969 This has the effect that two stars are being added/taken away in
970 promotion/demotion commands. It also influences how levels are
971 handled by the exporters.
972 Changing it requires restart of `font-lock-mode' to become effective
973 for fontification also in regions already fontified.
974 You may also set this on a per-file basis by adding one of the following
975 lines to the buffer:
977 #+STARTUP: odd
978 #+STARTUP: oddeven"
979 :group 'org-edit-structure
980 :group 'org-appearance
981 :type 'boolean)
983 (defcustom org-adapt-indentation t
984 "Non-nil means adapt indentation to outline node level.
986 When this variable is set, Org assumes that you write outlines by
987 indenting text in each node to align with the headline (after the stars).
988 The following issues are influenced by this variable:
990 - When this is set and the *entire* text in an entry is indented, the
991 indentation is increased by one space in a demotion command, and
992 decreased by one in a promotion command. If any line in the entry
993 body starts with text at column 0, indentation is not changed at all.
995 - Property drawers and planning information is inserted indented when
996 this variable s set. When nil, they will not be indented.
998 - TAB indents a line relative to context. The lines below a headline
999 will be indented when this variable is set.
1001 Note that this is all about true indentation, by adding and removing
1002 space characters. See also `org-indent.el' which does level-dependent
1003 indentation in a virtual way, i.e. at display time in Emacs."
1004 :group 'org-edit-structure
1005 :type 'boolean)
1007 (defcustom org-special-ctrl-a/e nil
1008 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1010 When t, `C-a' will bring back the cursor to the beginning of the
1011 headline text, i.e. after the stars and after a possible TODO keyword.
1012 In an item, this will be the position after the bullet.
1013 When the cursor is already at that position, another `C-a' will bring
1014 it to the beginning of the line.
1016 `C-e' will jump to the end of the headline, ignoring the presence of tags
1017 in the headline. A second `C-e' will then jump to the true end of the
1018 line, after any tags. This also means that, when this variable is
1019 non-nil, `C-e' also will never jump beyond the end of the heading of a
1020 folded section, i.e. not after the ellipses.
1022 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
1023 going to the true line boundary first. Only a directly following, identical
1024 keypress will bring the cursor to the special positions.
1026 This may also be a cons cell where the behavior for `C-a' and `C-e' is
1027 set separately."
1028 :group 'org-edit-structure
1029 :type '(choice
1030 (const :tag "off" nil)
1031 (const :tag "on: after stars/bullet and before tags first" t)
1032 (const :tag "reversed: true line boundary first" reversed)
1033 (cons :tag "Set C-a and C-e separately"
1034 (choice :tag "Special C-a"
1035 (const :tag "off" nil)
1036 (const :tag "on: after stars/bullet first" t)
1037 (const :tag "reversed: before stars/bullet first" reversed))
1038 (choice :tag "Special C-e"
1039 (const :tag "off" nil)
1040 (const :tag "on: before tags first" t)
1041 (const :tag "reversed: after tags first" reversed)))))
1042 (if (fboundp 'defvaralias)
1043 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1045 (defcustom org-special-ctrl-k nil
1046 "Non-nil means `C-k' will behave specially in headlines.
1047 When nil, `C-k' will call the default `kill-line' command.
1048 When t, the following will happen while the cursor is in the headline:
1050 - When the cursor is at the beginning of a headline, kill the entire
1051 line and possible the folded subtree below the line.
1052 - When in the middle of the headline text, kill the headline up to the tags.
1053 - When after the headline text, kill the tags."
1054 :group 'org-edit-structure
1055 :type 'boolean)
1057 (defcustom org-ctrl-k-protect-subtree nil
1058 "Non-nil means, do not delete a hidden subtree with C-k.
1059 When set to the symbol `error', simply throw an error when C-k is
1060 used to kill (part-of) a headline that has hidden text behind it.
1061 Any other non-nil value will result in a query to the user, if it is
1062 OK to kill that hidden subtree. When nil, kill without remorse."
1063 :group 'org-edit-structure
1064 :type '(choice
1065 (const :tag "Do not protect hidden subtrees" nil)
1066 (const :tag "Protect hidden subtrees with a security query" t)
1067 (const :tag "Never kill a hidden subtree with C-k" error)))
1069 (defcustom org-catch-invisible-edits nil
1070 "Check if in invisible region before inserting or deleting a character.
1071 Valid values are:
1073 nil Do not check, so just do invisible edits.
1074 error Throw an error and do nothing.
1075 show Make point visible, and do the requested edit.
1076 show-and-error Make point visible, then throw an error and abort the edit.
1077 smart Make point visible, and do insertion/deletion if it is
1078 adjacent to visible text and the change feels predictable.
1079 Never delete a previously invisible character or add in the
1080 middle or right after an invisible region. Basically, this
1081 allows insertion and backward-delete right before ellipses.
1082 FIXME: maybe in this case we should not even show?"
1083 :group 'org-edit-structure
1084 :type '(choice
1085 (const :tag "Do not check" nil)
1086 (const :tag "Throw error when trying to edit" error)
1087 (const :tag "Unhide, but do not do the edit" show-and-error)
1088 (const :tag "Show invisible part and do the edit" show)
1089 (const :tag "Be smart and do the right thing" smart)))
1091 (defcustom org-yank-folded-subtrees t
1092 "Non-nil means when yanking subtrees, fold them.
1093 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1094 it starts with a heading and all other headings in it are either children
1095 or siblings, then fold all the subtrees. However, do this only if no
1096 text after the yank would be swallowed into a folded tree by this action."
1097 :group 'org-edit-structure
1098 :type 'boolean)
1100 (defcustom org-yank-adjusted-subtrees nil
1101 "Non-nil means when yanking subtrees, adjust the level.
1102 With this setting, `org-paste-subtree' is used to insert the subtree, see
1103 this function for details."
1104 :group 'org-edit-structure
1105 :type 'boolean)
1107 (defcustom org-M-RET-may-split-line '((default . t))
1108 "Non-nil means M-RET will split the line at the cursor position.
1109 When nil, it will go to the end of the line before making a
1110 new line.
1111 You may also set this option in a different way for different
1112 contexts. Valid contexts are:
1114 headline when creating a new headline
1115 item when creating a new item
1116 table in a table field
1117 default the value to be used for all contexts not explicitly
1118 customized"
1119 :group 'org-structure
1120 :group 'org-table
1121 :type '(choice
1122 (const :tag "Always" t)
1123 (const :tag "Never" nil)
1124 (repeat :greedy t :tag "Individual contexts"
1125 (cons
1126 (choice :tag "Context"
1127 (const headline)
1128 (const item)
1129 (const table)
1130 (const default))
1131 (boolean)))))
1134 (defcustom org-insert-heading-respect-content nil
1135 "Non-nil means insert new headings after the current subtree.
1136 When nil, the new heading is created directly after the current line.
1137 The commands \\[org-insert-heading-respect-content] and
1138 \\[org-insert-todo-heading-respect-content] turn this variable on
1139 for the duration of the command."
1140 :group 'org-structure
1141 :type 'boolean)
1143 (defcustom org-blank-before-new-entry '((heading . auto)
1144 (plain-list-item . auto))
1145 "Should `org-insert-heading' leave a blank line before new heading/item?
1146 The value is an alist, with `heading' and `plain-list-item' as CAR,
1147 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1148 which case Org will look at the surrounding headings/items and try to
1149 make an intelligent decision whether to insert a blank line or not.
1151 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1152 set, the setting here is ignored and no empty line is inserted, to avoid
1153 breaking the list structure."
1154 :group 'org-edit-structure
1155 :type '(list
1156 (cons (const heading)
1157 (choice (const :tag "Never" nil)
1158 (const :tag "Always" t)
1159 (const :tag "Auto" auto)))
1160 (cons (const plain-list-item)
1161 (choice (const :tag "Never" nil)
1162 (const :tag "Always" t)
1163 (const :tag "Auto" auto)))))
1165 (defcustom org-insert-heading-hook nil
1166 "Hook being run after inserting a new heading."
1167 :group 'org-edit-structure
1168 :type 'hook)
1170 (defcustom org-enable-fixed-width-editor t
1171 "Non-nil means lines starting with \":\" are treated as fixed-width.
1172 This currently only means they are never auto-wrapped.
1173 When nil, such lines will be treated like ordinary lines.
1174 See also the QUOTE keyword."
1175 :group 'org-edit-structure
1176 :type 'boolean)
1178 (defcustom org-goto-auto-isearch t
1179 "Non-nil means typing characters in `org-goto' starts incremental search."
1180 :group 'org-edit-structure
1181 :type 'boolean)
1183 (defgroup org-sparse-trees nil
1184 "Options concerning sparse trees in Org-mode."
1185 :tag "Org Sparse Trees"
1186 :group 'org-structure)
1188 (defcustom org-highlight-sparse-tree-matches t
1189 "Non-nil means highlight all matches that define a sparse tree.
1190 The highlights will automatically disappear the next time the buffer is
1191 changed by an edit command."
1192 :group 'org-sparse-trees
1193 :type 'boolean)
1195 (defcustom org-remove-highlights-with-change t
1196 "Non-nil means any change to the buffer will remove temporary highlights.
1197 Such highlights are created by `org-occur' and `org-clock-display'.
1198 When nil, `C-c C-c needs to be used to get rid of the highlights.
1199 The highlights created by `org-preview-latex-fragment' always need
1200 `C-c C-c' to be removed."
1201 :group 'org-sparse-trees
1202 :group 'org-time
1203 :type 'boolean)
1206 (defcustom org-occur-hook '(org-first-headline-recenter)
1207 "Hook that is run after `org-occur' has constructed a sparse tree.
1208 This can be used to recenter the window to show as much of the structure
1209 as possible."
1210 :group 'org-sparse-trees
1211 :type 'hook)
1213 (defgroup org-imenu-and-speedbar nil
1214 "Options concerning imenu and speedbar in Org-mode."
1215 :tag "Org Imenu and Speedbar"
1216 :group 'org-structure)
1218 (defcustom org-imenu-depth 2
1219 "The maximum level for Imenu access to Org-mode headlines.
1220 This also applied for speedbar access."
1221 :group 'org-imenu-and-speedbar
1222 :type 'integer)
1224 (defgroup org-table nil
1225 "Options concerning tables in Org-mode."
1226 :tag "Org Table"
1227 :group 'org)
1229 (defcustom org-enable-table-editor 'optimized
1230 "Non-nil means lines starting with \"|\" are handled by the table editor.
1231 When nil, such lines will be treated like ordinary lines.
1233 When equal to the symbol `optimized', the table editor will be optimized to
1234 do the following:
1235 - Automatic overwrite mode in front of whitespace in table fields.
1236 This makes the structure of the table stay in tact as long as the edited
1237 field does not exceed the column width.
1238 - Minimize the number of realigns. Normally, the table is aligned each time
1239 TAB or RET are pressed to move to another field. With optimization this
1240 happens only if changes to a field might have changed the column width.
1241 Optimization requires replacing the functions `self-insert-command',
1242 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1243 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1244 very good at guessing when a re-align will be necessary, but you can always
1245 force one with \\[org-ctrl-c-ctrl-c].
1247 If you would like to use the optimized version in Org-mode, but the
1248 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1250 This variable can be used to turn on and off the table editor during a session,
1251 but in order to toggle optimization, a restart is required.
1253 See also the variable `org-table-auto-blank-field'."
1254 :group 'org-table
1255 :type '(choice
1256 (const :tag "off" nil)
1257 (const :tag "on" t)
1258 (const :tag "on, optimized" optimized)))
1260 (defcustom org-self-insert-cluster-for-undo t
1261 "Non-nil means cluster self-insert commands for undo when possible.
1262 If this is set, then, like in the Emacs command loop, 20 consecutive
1263 characters will be undone together.
1264 This is configurable, because there is some impact on typing performance."
1265 :group 'org-table
1266 :type 'boolean)
1268 (defcustom org-table-tab-recognizes-table.el t
1269 "Non-nil means TAB will automatically notice a table.el table.
1270 When it sees such a table, it moves point into it and - if necessary -
1271 calls `table-recognize-table'."
1272 :group 'org-table-editing
1273 :type 'boolean)
1275 (defgroup org-link nil
1276 "Options concerning links in Org-mode."
1277 :tag "Org Link"
1278 :group 'org)
1280 (defvar org-link-abbrev-alist-local nil
1281 "Buffer-local version of `org-link-abbrev-alist', which see.
1282 The value of this is taken from the #+LINK lines.")
1283 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1285 (defcustom org-link-abbrev-alist nil
1286 "Alist of link abbreviations.
1287 The car of each element is a string, to be replaced at the start of a link.
1288 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1289 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1291 [[linkkey:tag][description]]
1293 The 'linkkey' must be a word word, starting with a letter, followed
1294 by letters, numbers, '-' or '_'.
1296 If REPLACE is a string, the tag will simply be appended to create the link.
1297 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1298 the placeholder \"%h\" will cause a url-encoded version of the tag to
1299 be inserted at that point (see the function `url-hexify-string').
1301 REPLACE may also be a function that will be called with the tag as the
1302 only argument to create the link, which should be returned as a string.
1304 See the manual for examples."
1305 :group 'org-link
1306 :type '(repeat
1307 (cons
1308 (string :tag "Protocol")
1309 (choice
1310 (string :tag "Format")
1311 (function)))))
1313 (defcustom org-descriptive-links t
1314 "Non-nil means Org will display descriptive links.
1315 E.g. [[http://orgmode.org][Org website]] will be displayed as
1316 \"Org Website\", hiding the link itself and just displaying its
1317 description. When set to `nil', Org will display the full links
1318 literally.
1320 You can interactively set the value of this variable by calling
1321 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1322 :group 'org-link
1323 :type 'boolean)
1325 (defcustom org-link-file-path-type 'adaptive
1326 "How the path name in file links should be stored.
1327 Valid values are:
1329 relative Relative to the current directory, i.e. the directory of the file
1330 into which the link is being inserted.
1331 absolute Absolute path, if possible with ~ for home directory.
1332 noabbrev Absolute path, no abbreviation of home directory.
1333 adaptive Use relative path for files in the current directory and sub-
1334 directories of it. For other files, use an absolute path."
1335 :group 'org-link
1336 :type '(choice
1337 (const relative)
1338 (const absolute)
1339 (const noabbrev)
1340 (const adaptive)))
1342 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1343 "Types of links that should be activated in Org-mode files.
1344 This is a list of symbols, each leading to the activation of a certain link
1345 type. In principle, it does not hurt to turn on most link types - there may
1346 be a small gain when turning off unused link types. The types are:
1348 bracket The recommended [[link][description]] or [[link]] links with hiding.
1349 angle Links in angular brackets that may contain whitespace like
1350 <bbdb:Carsten Dominik>.
1351 plain Plain links in normal text, no whitespace, like http://google.com.
1352 radio Text that is matched by a radio target, see manual for details.
1353 tag Tag settings in a headline (link to tag search).
1354 date Time stamps (link to calendar).
1355 footnote Footnote labels.
1357 Changing this variable requires a restart of Emacs to become effective."
1358 :group 'org-link
1359 :type '(set :greedy t
1360 (const :tag "Double bracket links" bracket)
1361 (const :tag "Angular bracket links" angle)
1362 (const :tag "Plain text links" plain)
1363 (const :tag "Radio target matches" radio)
1364 (const :tag "Tags" tag)
1365 (const :tag "Timestamps" date)
1366 (const :tag "Footnotes" footnote)))
1368 (defcustom org-make-link-description-function nil
1369 "Function to use to generate link descriptions from links.
1370 If nil the link location will be used. This function must take
1371 two parameters; the first is the link and the second the
1372 description `org-insert-link' has generated, and should return the
1373 description to use."
1374 :group 'org-link
1375 :type 'function)
1377 (defgroup org-link-store nil
1378 "Options concerning storing links in Org-mode."
1379 :tag "Org Store Link"
1380 :group 'org-link)
1382 (defcustom org-email-link-description-format "Email %c: %.30s"
1383 "Format of the description part of a link to an email or usenet message.
1384 The following %-escapes will be replaced by corresponding information:
1386 %F full \"From\" field
1387 %f name, taken from \"From\" field, address if no name
1388 %T full \"To\" field
1389 %t first name in \"To\" field, address if no name
1390 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1391 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1392 %s subject
1393 %d date
1394 %m message-id.
1396 You may use normal field width specification between the % and the letter.
1397 This is for example useful to limit the length of the subject.
1399 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1400 :group 'org-link-store
1401 :type 'string)
1403 (defcustom org-from-is-user-regexp
1404 (let (r1 r2)
1405 (when (and user-mail-address (not (string= user-mail-address "")))
1406 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1407 (when (and user-full-name (not (string= user-full-name "")))
1408 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1409 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1410 "Regexp matched against the \"From:\" header of an email or usenet message.
1411 It should match if the message is from the user him/herself."
1412 :group 'org-link-store
1413 :type 'regexp)
1415 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1416 "Non-nil means storing a link to an Org file will use entry IDs.
1418 Note that before this variable is even considered, org-id must be loaded,
1419 so please customize `org-modules' and turn it on.
1421 The variable can have the following values:
1423 t Create an ID if needed to make a link to the current entry.
1425 create-if-interactive
1426 If `org-store-link' is called directly (interactively, as a user
1427 command), do create an ID to support the link. But when doing the
1428 job for remember, only use the ID if it already exists. The
1429 purpose of this setting is to avoid proliferation of unwanted
1430 IDs, just because you happen to be in an Org file when you
1431 call `org-remember' that automatically and preemptively
1432 creates a link. If you do want to get an ID link in a remember
1433 template to an entry not having an ID, create it first by
1434 explicitly creating a link to it, using `C-c C-l' first.
1436 create-if-interactive-and-no-custom-id
1437 Like create-if-interactive, but do not create an ID if there is
1438 a CUSTOM_ID property defined in the entry. This is the default.
1440 use-existing
1441 Use existing ID, do not create one.
1443 nil Never use an ID to make a link, instead link using a text search for
1444 the headline text."
1445 :group 'org-link-store
1446 :type '(choice
1447 (const :tag "Create ID to make link" t)
1448 (const :tag "Create if storing link interactively"
1449 create-if-interactive)
1450 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1451 create-if-interactive-and-no-custom-id)
1452 (const :tag "Only use existing" use-existing)
1453 (const :tag "Do not use ID to create link" nil)))
1455 (defcustom org-context-in-file-links t
1456 "Non-nil means file links from `org-store-link' contain context.
1457 A search string will be added to the file name with :: as separator and
1458 used to find the context when the link is activated by the command
1459 `org-open-at-point'. When this option is t, the entire active region
1460 will be placed in the search string of the file link. If set to a
1461 positive integer, only the first n lines of context will be stored.
1463 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1464 negates this setting for the duration of the command."
1465 :group 'org-link-store
1466 :type '(choice boolean integer))
1468 (defcustom org-keep-stored-link-after-insertion nil
1469 "Non-nil means keep link in list for entire session.
1471 The command `org-store-link' adds a link pointing to the current
1472 location to an internal list. These links accumulate during a session.
1473 The command `org-insert-link' can be used to insert links into any
1474 Org-mode file (offering completion for all stored links). When this
1475 option is nil, every link which has been inserted once using \\[org-insert-link]
1476 will be removed from the list, to make completing the unused links
1477 more efficient."
1478 :group 'org-link-store
1479 :type 'boolean)
1481 (defgroup org-link-follow nil
1482 "Options concerning following links in Org-mode."
1483 :tag "Org Follow Link"
1484 :group 'org-link)
1486 (defcustom org-link-translation-function nil
1487 "Function to translate links with different syntax to Org syntax.
1488 This can be used to translate links created for example by the Planner
1489 or emacs-wiki packages to Org syntax.
1490 The function must accept two parameters, a TYPE containing the link
1491 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1492 which is everything after the link protocol. It should return a cons
1493 with possibly modified values of type and path.
1494 Org contains a function for this, so if you set this variable to
1495 `org-translate-link-from-planner', you should be able follow many
1496 links created by planner."
1497 :group 'org-link-follow
1498 :type 'function)
1500 (defcustom org-follow-link-hook nil
1501 "Hook that is run after a link has been followed."
1502 :group 'org-link-follow
1503 :type 'hook)
1505 (defcustom org-tab-follows-link nil
1506 "Non-nil means on links TAB will follow the link.
1507 Needs to be set before org.el is loaded.
1508 This really should not be used, it does not make sense, and the
1509 implementation is bad."
1510 :group 'org-link-follow
1511 :type 'boolean)
1513 (defcustom org-return-follows-link nil
1514 "Non-nil means on links RET will follow the link."
1515 :group 'org-link-follow
1516 :type 'boolean)
1518 (defcustom org-mouse-1-follows-link
1519 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1520 "Non-nil means mouse-1 on a link will follow the link.
1521 A longer mouse click will still set point. Does not work on XEmacs.
1522 Needs to be set before org.el is loaded."
1523 :group 'org-link-follow
1524 :type 'boolean)
1526 (defcustom org-mark-ring-length 4
1527 "Number of different positions to be recorded in the ring.
1528 Changing this requires a restart of Emacs to work correctly."
1529 :group 'org-link-follow
1530 :type 'integer)
1532 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1533 "Non-nil means internal links in Org files must exactly match a headline.
1534 When nil, the link search tries to match a phrase with all words
1535 in the search text."
1536 :group 'org-link-follow
1537 :type '(choice
1538 (const :tag "Use fuzzy text search" nil)
1539 (const :tag "Match only exact headline" t)
1540 (const :tag "Match exact headline or query to create it"
1541 query-to-create)))
1543 (defcustom org-link-frame-setup
1544 '((vm . vm-visit-folder-other-frame)
1545 (gnus . org-gnus-no-new-news)
1546 (file . find-file-other-window)
1547 (wl . wl-other-frame))
1548 "Setup the frame configuration for following links.
1549 When following a link with Emacs, it may often be useful to display
1550 this link in another window or frame. This variable can be used to
1551 set this up for the different types of links.
1552 For VM, use any of
1553 `vm-visit-folder'
1554 `vm-visit-folder-other-window'
1555 `vm-visit-folder-other-frame'
1556 For Gnus, use any of
1557 `gnus'
1558 `gnus-other-frame'
1559 `org-gnus-no-new-news'
1560 For FILE, use any of
1561 `find-file'
1562 `find-file-other-window'
1563 `find-file-other-frame'
1564 For Wanderlust use any of
1565 `wl'
1566 `wl-other-frame'
1567 For the calendar, use the variable `calendar-setup'.
1568 For BBDB, it is currently only possible to display the matches in
1569 another window."
1570 :group 'org-link-follow
1571 :type '(list
1572 (cons (const vm)
1573 (choice
1574 (const vm-visit-folder)
1575 (const vm-visit-folder-other-window)
1576 (const vm-visit-folder-other-frame)))
1577 (cons (const gnus)
1578 (choice
1579 (const gnus)
1580 (const gnus-other-frame)
1581 (const org-gnus-no-new-news)))
1582 (cons (const file)
1583 (choice
1584 (const find-file)
1585 (const find-file-other-window)
1586 (const find-file-other-frame)))
1587 (cons (const wl)
1588 (choice
1589 (const wl)
1590 (const wl-other-frame)))))
1592 (defcustom org-display-internal-link-with-indirect-buffer nil
1593 "Non-nil means use indirect buffer to display infile links.
1594 Activating internal links (from one location in a file to another location
1595 in the same file) normally just jumps to the location. When the link is
1596 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1597 is displayed in
1598 another window. When this option is set, the other window actually displays
1599 an indirect buffer clone of the current buffer, to avoid any visibility
1600 changes to the current buffer."
1601 :group 'org-link-follow
1602 :type 'boolean)
1604 (defcustom org-open-non-existing-files nil
1605 "Non-nil means `org-open-file' will open non-existing files.
1606 When nil, an error will be generated.
1607 This variable applies only to external applications because they
1608 might choke on non-existing files. If the link is to a file that
1609 will be opened in Emacs, the variable is ignored."
1610 :group 'org-link-follow
1611 :type 'boolean)
1613 (defcustom org-open-directory-means-index-dot-org nil
1614 "Non-nil means a link to a directory really means to index.org.
1615 When nil, following a directory link will run dired or open a finder/explorer
1616 window on that directory."
1617 :group 'org-link-follow
1618 :type 'boolean)
1620 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1621 "Function and arguments to call for following mailto links.
1622 This is a list with the first element being a Lisp function, and the
1623 remaining elements being arguments to the function. In string arguments,
1624 %a will be replaced by the address, and %s will be replaced by the subject
1625 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1626 :group 'org-link-follow
1627 :type '(choice
1628 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1629 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1630 (const :tag "message-mail" (message-mail "%a" "%s"))
1631 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1633 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1634 "Non-nil means ask for confirmation before executing shell links.
1635 Shell links can be dangerous: just think about a link
1637 [[shell:rm -rf ~/*][Google Search]]
1639 This link would show up in your Org-mode document as \"Google Search\",
1640 but really it would remove your entire home directory.
1641 Therefore we advise against setting this variable to nil.
1642 Just change it to `y-or-n-p' if you want to confirm with a
1643 single keystroke rather than having to type \"yes\"."
1644 :group 'org-link-follow
1645 :type '(choice
1646 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1647 (const :tag "with y-or-n (faster)" y-or-n-p)
1648 (const :tag "no confirmation (dangerous)" nil)))
1649 (put 'org-confirm-shell-link-function
1650 'safe-local-variable
1651 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1653 (defcustom org-confirm-shell-link-not-regexp ""
1654 "A regexp to skip confirmation for shell links."
1655 :group 'org-link-follow
1656 :type 'regexp)
1658 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1659 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1660 Elisp links can be dangerous: just think about a link
1662 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1664 This link would show up in your Org-mode document as \"Google Search\",
1665 but really it would remove your entire home directory.
1666 Therefore we advise against setting this variable to nil.
1667 Just change it to `y-or-n-p' if you want to confirm with a
1668 single keystroke rather than having to type \"yes\"."
1669 :group 'org-link-follow
1670 :type '(choice
1671 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1672 (const :tag "with y-or-n (faster)" y-or-n-p)
1673 (const :tag "no confirmation (dangerous)" nil)))
1674 (put 'org-confirm-shell-link-function
1675 'safe-local-variable
1676 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1678 (defcustom org-confirm-elisp-link-not-regexp ""
1679 "A regexp to skip confirmation for Elisp links."
1680 :group 'org-link-follow
1681 :type 'regexp)
1683 (defconst org-file-apps-defaults-gnu
1684 '((remote . emacs)
1685 (system . mailcap)
1686 (t . mailcap))
1687 "Default file applications on a UNIX or GNU/Linux system.
1688 See `org-file-apps'.")
1690 (defconst org-file-apps-defaults-macosx
1691 '((remote . emacs)
1692 (t . "open %s")
1693 (system . "open %s")
1694 ("ps.gz" . "gv %s")
1695 ("eps.gz" . "gv %s")
1696 ("dvi" . "xdvi %s")
1697 ("fig" . "xfig %s"))
1698 "Default file applications on a MacOS X system.
1699 The system \"open\" is known as a default, but we use X11 applications
1700 for some files for which the OS does not have a good default.
1701 See `org-file-apps'.")
1703 (defconst org-file-apps-defaults-windowsnt
1704 (list
1705 '(remote . emacs)
1706 (cons t
1707 (list (if (featurep 'xemacs)
1708 'mswindows-shell-execute
1709 'w32-shell-execute)
1710 "open" 'file))
1711 (cons 'system
1712 (list (if (featurep 'xemacs)
1713 'mswindows-shell-execute
1714 'w32-shell-execute)
1715 "open" 'file)))
1716 "Default file applications on a Windows NT system.
1717 The system \"open\" is used for most files.
1718 See `org-file-apps'.")
1720 (defcustom org-file-apps
1722 (auto-mode . emacs)
1723 ("\\.mm\\'" . default)
1724 ("\\.x?html?\\'" . default)
1725 ("\\.pdf\\'" . default)
1727 "External applications for opening `file:path' items in a document.
1728 Org-mode uses system defaults for different file types, but
1729 you can use this variable to set the application for a given file
1730 extension. The entries in this list are cons cells where the car identifies
1731 files and the cdr the corresponding command. Possible values for the
1732 file identifier are
1733 \"string\" A string as a file identifier can be interpreted in different
1734 ways, depending on its contents:
1736 - Alphanumeric characters only:
1737 Match links with this file extension.
1738 Example: (\"pdf\" . \"evince %s\")
1739 to open PDFs with evince.
1741 - Regular expression: Match links where the
1742 filename matches the regexp. If you want to
1743 use groups here, use shy groups.
1745 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1746 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1747 to open *.html and *.xhtml with firefox.
1749 - Regular expression which contains (non-shy) groups:
1750 Match links where the whole link, including \"::\", and
1751 anything after that, matches the regexp.
1752 In a custom command string, %1, %2, etc. are replaced with
1753 the parts of the link that were matched by the groups.
1754 For backwards compatibility, if a command string is given
1755 that does not use any of the group matches, this case is
1756 handled identically to the second one (i.e. match against
1757 file name only).
1758 In a custom lisp form, you can access the group matches with
1759 (match-string n link).
1761 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1762 to open [[file:document.pdf::5]] with evince at page 5.
1764 `directory' Matches a directory
1765 `remote' Matches a remote file, accessible through tramp or efs.
1766 Remote files most likely should be visited through Emacs
1767 because external applications cannot handle such paths.
1768 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1769 so all files Emacs knows how to handle. Using this with
1770 command `emacs' will open most files in Emacs. Beware that this
1771 will also open html files inside Emacs, unless you add
1772 (\"html\" . default) to the list as well.
1773 t Default for files not matched by any of the other options.
1774 `system' The system command to open files, like `open' on Windows
1775 and Mac OS X, and mailcap under GNU/Linux. This is the command
1776 that will be selected if you call `C-c C-o' with a double
1777 \\[universal-argument] \\[universal-argument] prefix.
1779 Possible values for the command are:
1780 `emacs' The file will be visited by the current Emacs process.
1781 `default' Use the default application for this file type, which is the
1782 association for t in the list, most likely in the system-specific
1783 part.
1784 This can be used to overrule an unwanted setting in the
1785 system-specific variable.
1786 `system' Use the system command for opening files, like \"open\".
1787 This command is specified by the entry whose car is `system'.
1788 Most likely, the system-specific version of this variable
1789 does define this command, but you can overrule/replace it
1790 here.
1791 string A command to be executed by a shell; %s will be replaced
1792 by the path to the file.
1793 sexp A Lisp form which will be evaluated. The file path will
1794 be available in the Lisp variable `file'.
1795 For more examples, see the system specific constants
1796 `org-file-apps-defaults-macosx'
1797 `org-file-apps-defaults-windowsnt'
1798 `org-file-apps-defaults-gnu'."
1799 :group 'org-link-follow
1800 :type '(repeat
1801 (cons (choice :value ""
1802 (string :tag "Extension")
1803 (const :tag "System command to open files" system)
1804 (const :tag "Default for unrecognized files" t)
1805 (const :tag "Remote file" remote)
1806 (const :tag "Links to a directory" directory)
1807 (const :tag "Any files that have Emacs modes"
1808 auto-mode))
1809 (choice :value ""
1810 (const :tag "Visit with Emacs" emacs)
1811 (const :tag "Use default" default)
1812 (const :tag "Use the system command" system)
1813 (string :tag "Command")
1814 (sexp :tag "Lisp form")))))
1818 (defgroup org-refile nil
1819 "Options concerning refiling entries in Org-mode."
1820 :tag "Org Refile"
1821 :group 'org)
1823 (defcustom org-directory "~/org"
1824 "Directory with org files.
1825 This is just a default location to look for Org files. There is no need
1826 at all to put your files into this directory. It is only used in the
1827 following situations:
1829 1. When a remember template specifies a target file that is not an
1830 absolute path. The path will then be interpreted relative to
1831 `org-directory'
1832 2. When a remember note is filed away in an interactive way (when exiting the
1833 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1834 with `org-directory' as the default path."
1835 :group 'org-refile
1836 :group 'org-remember
1837 :type 'directory)
1839 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1840 "Default target for storing notes.
1841 Used as a fall back file for org-remember.el and org-capture.el, for
1842 templates that do not specify a target file."
1843 :group 'org-refile
1844 :group 'org-remember
1845 :type '(choice
1846 (const :tag "Default from remember-data-file" nil)
1847 file))
1849 (defcustom org-goto-interface 'outline
1850 "The default interface to be used for `org-goto'.
1851 Allowed values are:
1852 outline The interface shows an outline of the relevant file
1853 and the correct heading is found by moving through
1854 the outline or by searching with incremental search.
1855 outline-path-completion Headlines in the current buffer are offered via
1856 completion. This is the interface also used by
1857 the refile command."
1858 :group 'org-refile
1859 :type '(choice
1860 (const :tag "Outline" outline)
1861 (const :tag "Outline-path-completion" outline-path-completion)))
1863 (defcustom org-goto-max-level 5
1864 "Maximum target level when running `org-goto' with refile interface."
1865 :group 'org-refile
1866 :type 'integer)
1868 (defcustom org-reverse-note-order nil
1869 "Non-nil means store new notes at the beginning of a file or entry.
1870 When nil, new notes will be filed to the end of a file or entry.
1871 This can also be a list with cons cells of regular expressions that
1872 are matched against file names, and values."
1873 :group 'org-remember
1874 :group 'org-refile
1875 :type '(choice
1876 (const :tag "Reverse always" t)
1877 (const :tag "Reverse never" nil)
1878 (repeat :tag "By file name regexp"
1879 (cons regexp boolean))))
1881 (defcustom org-log-refile nil
1882 "Information to record when a task is refiled.
1884 Possible values are:
1886 nil Don't add anything
1887 time Add a time stamp to the task
1888 note Prompt for a note and add it with template `org-log-note-headings'
1890 This option can also be set with on a per-file-basis with
1892 #+STARTUP: nologrefile
1893 #+STARTUP: logrefile
1894 #+STARTUP: lognoterefile
1896 You can have local logging settings for a subtree by setting the LOGGING
1897 property to one or more of these keywords.
1899 When bulk-refiling from the agenda, the value `note' is forbidden and
1900 will temporarily be changed to `time'."
1901 :group 'org-refile
1902 :group 'org-progress
1903 :type '(choice
1904 (const :tag "No logging" nil)
1905 (const :tag "Record timestamp" time)
1906 (const :tag "Record timestamp with note." note)))
1908 (defcustom org-refile-targets nil
1909 "Targets for refiling entries with \\[org-refile].
1910 This is a list of cons cells. Each cell contains:
1911 - a specification of the files to be considered, either a list of files,
1912 or a symbol whose function or variable value will be used to retrieve
1913 a file name or a list of file names. If you use `org-agenda-files' for
1914 that, all agenda files will be scanned for targets. Nil means consider
1915 headings in the current buffer.
1916 - A specification of how to find candidate refile targets. This may be
1917 any of:
1918 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1919 This tag has to be present in all target headlines, inheritance will
1920 not be considered.
1921 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1922 todo keyword.
1923 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1924 headlines that are refiling targets.
1925 - a cons cell (:level . N). Any headline of level N is considered a target.
1926 Note that, when `org-odd-levels-only' is set, level corresponds to
1927 order in hierarchy, not to the number of stars.
1928 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1929 Note that, when `org-odd-levels-only' is set, level corresponds to
1930 order in hierarchy, not to the number of stars.
1932 Each element of this list generates a set of possible targets.
1933 The union of these sets is presented (with completion) to
1934 the user by `org-refile'.
1936 You can set the variable `org-refile-target-verify-function' to a function
1937 to verify each headline found by the simple criteria above.
1939 When this variable is nil, all top-level headlines in the current buffer
1940 are used, equivalent to the value `((nil . (:level . 1))'."
1941 :group 'org-refile
1942 :type '(repeat
1943 (cons
1944 (choice :value org-agenda-files
1945 (const :tag "All agenda files" org-agenda-files)
1946 (const :tag "Current buffer" nil)
1947 (function) (variable) (file))
1948 (choice :tag "Identify target headline by"
1949 (cons :tag "Specific tag" (const :value :tag) (string))
1950 (cons :tag "TODO keyword" (const :value :todo) (string))
1951 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1952 (cons :tag "Level number" (const :value :level) (integer))
1953 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1955 (defcustom org-refile-target-verify-function nil
1956 "Function to verify if the headline at point should be a refile target.
1957 The function will be called without arguments, with point at the
1958 beginning of the headline. It should return t and leave point
1959 where it is if the headline is a valid target for refiling.
1961 If the target should not be selected, the function must return nil.
1962 In addition to this, it may move point to a place from where the search
1963 should be continued. For example, the function may decide that the entire
1964 subtree of the current entry should be excluded and move point to the end
1965 of the subtree."
1966 :group 'org-refile
1967 :type 'function)
1969 (defcustom org-refile-use-cache nil
1970 "Non-nil means cache refile targets to speed up the process.
1971 The cache for a particular file will be updated automatically when
1972 the buffer has been killed, or when any of the marker used for flagging
1973 refile targets no longer points at a live buffer.
1974 If you have added new entries to a buffer that might themselves be targets,
1975 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
1976 find that easier, `C-u C-u C-u C-c C-w'."
1977 :group 'org-refile
1978 :type 'boolean)
1980 (defcustom org-refile-use-outline-path nil
1981 "Non-nil means provide refile targets as paths.
1982 So a level 3 headline will be available as level1/level2/level3.
1984 When the value is `file', also include the file name (without directory)
1985 into the path. In this case, you can also stop the completion after
1986 the file name, to get entries inserted as top level in the file.
1988 When `full-file-path', include the full file path."
1989 :group 'org-refile
1990 :type '(choice
1991 (const :tag "Not" nil)
1992 (const :tag "Yes" t)
1993 (const :tag "Start with file name" file)
1994 (const :tag "Start with full file path" full-file-path)))
1996 (defcustom org-outline-path-complete-in-steps t
1997 "Non-nil means complete the outline path in hierarchical steps.
1998 When Org-mode uses the refile interface to select an outline path
1999 \(see variable `org-refile-use-outline-path'), the completion of
2000 the path can be done is a single go, or if can be done in steps down
2001 the headline hierarchy. Going in steps is probably the best if you
2002 do not use a special completion package like `ido' or `icicles'.
2003 However, when using these packages, going in one step can be very
2004 fast, while still showing the whole path to the entry."
2005 :group 'org-refile
2006 :type 'boolean)
2008 (defcustom org-refile-allow-creating-parent-nodes nil
2009 "Non-nil means allow to create new nodes as refile targets.
2010 New nodes are then created by adding \"/new node name\" to the completion
2011 of an existing node. When the value of this variable is `confirm',
2012 new node creation must be confirmed by the user (recommended)
2013 When nil, the completion must match an existing entry.
2015 Note that, if the new heading is not seen by the criteria
2016 listed in `org-refile-targets', multiple instances of the same
2017 heading would be created by trying again to file under the new
2018 heading."
2019 :group 'org-refile
2020 :type '(choice
2021 (const :tag "Never" nil)
2022 (const :tag "Always" t)
2023 (const :tag "Prompt for confirmation" confirm)))
2025 (defcustom org-refile-active-region-within-subtree nil
2026 "Non-nil means also refile active region within a subtree.
2028 By default `org-refile' doesn't allow refiling regions if they
2029 don't contain a set of subtrees, but it might be convenient to
2030 do so sometimes: in that case, the first line of the region is
2031 converted to a headline before refiling."
2032 :group 'org-refile
2033 :type 'boolean)
2035 (defgroup org-todo nil
2036 "Options concerning TODO items in Org-mode."
2037 :tag "Org TODO"
2038 :group 'org)
2040 (defgroup org-progress nil
2041 "Options concerning Progress logging in Org-mode."
2042 :tag "Org Progress"
2043 :group 'org-time)
2045 (defvar org-todo-interpretation-widgets
2046 '((:tag "Sequence (cycling hits every state)" sequence)
2047 (:tag "Type (cycling directly to DONE)" type))
2048 "The available interpretation symbols for customizing `org-todo-keywords'.
2049 Interested libraries should add to this list.")
2051 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2052 "List of TODO entry keyword sequences and their interpretation.
2053 \\<org-mode-map>This is a list of sequences.
2055 Each sequence starts with a symbol, either `sequence' or `type',
2056 indicating if the keywords should be interpreted as a sequence of
2057 action steps, or as different types of TODO items. The first
2058 keywords are states requiring action - these states will select a headline
2059 for inclusion into the global TODO list Org-mode produces. If one of
2060 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2061 signify that no further action is necessary. If \"|\" is not found,
2062 the last keyword is treated as the only DONE state of the sequence.
2064 The command \\[org-todo] cycles an entry through these states, and one
2065 additional state where no keyword is present. For details about this
2066 cycling, see the manual.
2068 TODO keywords and interpretation can also be set on a per-file basis with
2069 the special #+SEQ_TODO and #+TYP_TODO lines.
2071 Each keyword can optionally specify a character for fast state selection
2072 \(in combination with the variable `org-use-fast-todo-selection')
2073 and specifiers for state change logging, using the same syntax
2074 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
2075 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2076 indicates to record a time stamp each time this state is selected.
2078 Each keyword may also specify if a timestamp or a note should be
2079 recorded when entering or leaving the state, by adding additional
2080 characters in the parenthesis after the keyword. This looks like this:
2081 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2082 record only the time of the state change. With X and Y being either
2083 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2084 Y when leaving the state if and only if the *target* state does not
2085 define X. You may omit any of the fast-selection key or X or /Y,
2086 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2088 For backward compatibility, this variable may also be just a list
2089 of keywords - in this case the interpretation (sequence or type) will be
2090 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2091 :group 'org-todo
2092 :group 'org-keywords
2093 :type '(choice
2094 (repeat :tag "Old syntax, just keywords"
2095 (string :tag "Keyword"))
2096 (repeat :tag "New syntax"
2097 (cons
2098 (choice
2099 :tag "Interpretation"
2100 ;;Quick and dirty way to see
2101 ;;`org-todo-interpretations'. This takes the
2102 ;;place of item arguments
2103 :convert-widget
2104 (lambda (widget)
2105 (widget-put widget
2106 :args (mapcar
2107 #'(lambda (x)
2108 (widget-convert
2109 (cons 'const x)))
2110 org-todo-interpretation-widgets))
2111 widget))
2112 (repeat
2113 (string :tag "Keyword"))))))
2115 (defvar org-todo-keywords-1 nil
2116 "All TODO and DONE keywords active in a buffer.")
2117 (make-variable-buffer-local 'org-todo-keywords-1)
2118 (defvar org-todo-keywords-for-agenda nil)
2119 (defvar org-done-keywords-for-agenda nil)
2120 (defvar org-drawers-for-agenda nil)
2121 (defvar org-todo-keyword-alist-for-agenda nil)
2122 (defvar org-tag-alist-for-agenda nil)
2123 (defvar org-agenda-contributing-files nil)
2124 (defvar org-not-done-keywords nil)
2125 (make-variable-buffer-local 'org-not-done-keywords)
2126 (defvar org-done-keywords nil)
2127 (make-variable-buffer-local 'org-done-keywords)
2128 (defvar org-todo-heads nil)
2129 (make-variable-buffer-local 'org-todo-heads)
2130 (defvar org-todo-sets nil)
2131 (make-variable-buffer-local 'org-todo-sets)
2132 (defvar org-todo-log-states nil)
2133 (make-variable-buffer-local 'org-todo-log-states)
2134 (defvar org-todo-kwd-alist nil)
2135 (make-variable-buffer-local 'org-todo-kwd-alist)
2136 (defvar org-todo-key-alist nil)
2137 (make-variable-buffer-local 'org-todo-key-alist)
2138 (defvar org-todo-key-trigger nil)
2139 (make-variable-buffer-local 'org-todo-key-trigger)
2141 (defcustom org-todo-interpretation 'sequence
2142 "Controls how TODO keywords are interpreted.
2143 This variable is in principle obsolete and is only used for
2144 backward compatibility, if the interpretation of todo keywords is
2145 not given already in `org-todo-keywords'. See that variable for
2146 more information."
2147 :group 'org-todo
2148 :group 'org-keywords
2149 :type '(choice (const sequence)
2150 (const type)))
2152 (defcustom org-use-fast-todo-selection t
2153 "Non-nil means use the fast todo selection scheme with C-c C-t.
2154 This variable describes if and under what circumstances the cycling
2155 mechanism for TODO keywords will be replaced by a single-key, direct
2156 selection scheme.
2158 When nil, fast selection is never used.
2160 When the symbol `prefix', it will be used when `org-todo' is called with
2161 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
2162 in an agenda buffer.
2164 When t, fast selection is used by default. In this case, the prefix
2165 argument forces cycling instead.
2167 In all cases, the special interface is only used if access keys have actually
2168 been assigned by the user, i.e. if keywords in the configuration are followed
2169 by a letter in parenthesis, like TODO(t)."
2170 :group 'org-todo
2171 :type '(choice
2172 (const :tag "Never" nil)
2173 (const :tag "By default" t)
2174 (const :tag "Only with C-u C-c C-t" prefix)))
2176 (defcustom org-provide-todo-statistics t
2177 "Non-nil means update todo statistics after insert and toggle.
2178 ALL-HEADLINES means update todo statistics by including headlines
2179 with no TODO keyword as well, counting them as not done.
2180 A list of TODO keywords means the same, but skip keywords that are
2181 not in this list.
2183 When this is set, todo statistics is updated in the parent of the
2184 current entry each time a todo state is changed."
2185 :group 'org-todo
2186 :type '(choice
2187 (const :tag "Yes, only for TODO entries" t)
2188 (const :tag "Yes, including all entries" 'all-headlines)
2189 (repeat :tag "Yes, for TODOs in this list"
2190 (string :tag "TODO keyword"))
2191 (other :tag "No TODO statistics" nil)))
2193 (defcustom org-hierarchical-todo-statistics t
2194 "Non-nil means TODO statistics covers just direct children.
2195 When nil, all entries in the subtree are considered.
2196 This has only an effect if `org-provide-todo-statistics' is set.
2197 To set this to nil for only a single subtree, use a COOKIE_DATA
2198 property and include the word \"recursive\" into the value."
2199 :group 'org-todo
2200 :type 'boolean)
2202 (defcustom org-after-todo-state-change-hook nil
2203 "Hook which is run after the state of a TODO item was changed.
2204 The new state (a string with a TODO keyword, or nil) is available in the
2205 Lisp variable `state'."
2206 :group 'org-todo
2207 :type 'hook)
2209 (defvar org-blocker-hook nil
2210 "Hook for functions that are allowed to block a state change.
2212 Each function gets as its single argument a property list, see
2213 `org-trigger-hook' for more information about this list.
2215 If any of the functions in this hook returns nil, the state change
2216 is blocked.")
2218 (defvar org-trigger-hook nil
2219 "Hook for functions that are triggered by a state change.
2221 Each function gets as its single argument a property list with at least
2222 the following elements:
2224 (:type type-of-change :position pos-at-entry-start
2225 :from old-state :to new-state)
2227 Depending on the type, more properties may be present.
2229 This mechanism is currently implemented for:
2231 TODO state changes
2232 ------------------
2233 :type todo-state-change
2234 :from previous state (keyword as a string), or nil, or a symbol
2235 'todo' or 'done', to indicate the general type of state.
2236 :to new state, like in :from")
2238 (defcustom org-enforce-todo-dependencies nil
2239 "Non-nil means undone TODO entries will block switching the parent to DONE.
2240 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2241 be blocked if any prior sibling is not yet done.
2242 Finally, if the parent is blocked because of ordered siblings of its own,
2243 the child will also be blocked.
2244 This variable needs to be set before org.el is loaded, and you need to
2245 restart Emacs after a change to make the change effective. The only way
2246 to change is while Emacs is running is through the customize interface."
2247 :set (lambda (var val)
2248 (set var val)
2249 (if val
2250 (add-hook 'org-blocker-hook
2251 'org-block-todo-from-children-or-siblings-or-parent)
2252 (remove-hook 'org-blocker-hook
2253 'org-block-todo-from-children-or-siblings-or-parent)))
2254 :group 'org-todo
2255 :type 'boolean)
2257 (defcustom org-enforce-todo-checkbox-dependencies nil
2258 "Non-nil means unchecked boxes will block switching the parent to DONE.
2259 When this is nil, checkboxes have no influence on switching TODO states.
2260 When non-nil, you first need to check off all check boxes before the TODO
2261 entry can be switched to DONE.
2262 This variable needs to be set before org.el is loaded, and you need to
2263 restart Emacs after a change to make the change effective. The only way
2264 to change is while Emacs is running is through the customize interface."
2265 :set (lambda (var val)
2266 (set var val)
2267 (if val
2268 (add-hook 'org-blocker-hook
2269 'org-block-todo-from-checkboxes)
2270 (remove-hook 'org-blocker-hook
2271 'org-block-todo-from-checkboxes)))
2272 :group 'org-todo
2273 :type 'boolean)
2275 (defcustom org-treat-insert-todo-heading-as-state-change nil
2276 "Non-nil means inserting a TODO heading is treated as state change.
2277 So when the command \\[org-insert-todo-heading] is used, state change
2278 logging will apply if appropriate. When nil, the new TODO item will
2279 be inserted directly, and no logging will take place."
2280 :group 'org-todo
2281 :type 'boolean)
2283 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2284 "Non-nil means switching TODO states with S-cursor counts as state change.
2285 This is the default behavior. However, setting this to nil allows a
2286 convenient way to select a TODO state and bypass any logging associated
2287 with that."
2288 :group 'org-todo
2289 :type 'boolean)
2291 (defcustom org-todo-state-tags-triggers nil
2292 "Tag changes that should be triggered by TODO state changes.
2293 This is a list. Each entry is
2295 (state-change (tag . flag) .......)
2297 State-change can be a string with a state, and empty string to indicate the
2298 state that has no TODO keyword, or it can be one of the symbols `todo'
2299 or `done', meaning any not-done or done state, respectively."
2300 :group 'org-todo
2301 :group 'org-tags
2302 :type '(repeat
2303 (cons (choice :tag "When changing to"
2304 (const :tag "Not-done state" todo)
2305 (const :tag "Done state" done)
2306 (string :tag "State"))
2307 (repeat
2308 (cons :tag "Tag action"
2309 (string :tag "Tag")
2310 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2312 (defcustom org-log-done nil
2313 "Information to record when a task moves to the DONE state.
2315 Possible values are:
2317 nil Don't add anything, just change the keyword
2318 time Add a time stamp to the task
2319 note Prompt for a note and add it with template `org-log-note-headings'
2321 This option can also be set with on a per-file-basis with
2323 #+STARTUP: nologdone
2324 #+STARTUP: logdone
2325 #+STARTUP: lognotedone
2327 You can have local logging settings for a subtree by setting the LOGGING
2328 property to one or more of these keywords."
2329 :group 'org-todo
2330 :group 'org-progress
2331 :type '(choice
2332 (const :tag "No logging" nil)
2333 (const :tag "Record CLOSED timestamp" time)
2334 (const :tag "Record CLOSED timestamp with note." note)))
2336 ;; Normalize old uses of org-log-done.
2337 (cond
2338 ((eq org-log-done t) (setq org-log-done 'time))
2339 ((and (listp org-log-done) (memq 'done org-log-done))
2340 (setq org-log-done 'note)))
2342 (defcustom org-log-reschedule nil
2343 "Information to record when the scheduling date of a tasks is modified.
2345 Possible values are:
2347 nil Don't add anything, just change the date
2348 time Add a time stamp to the task
2349 note Prompt for a note and add it with template `org-log-note-headings'
2351 This option can also be set with on a per-file-basis with
2353 #+STARTUP: nologreschedule
2354 #+STARTUP: logreschedule
2355 #+STARTUP: lognotereschedule"
2356 :group 'org-todo
2357 :group 'org-progress
2358 :type '(choice
2359 (const :tag "No logging" nil)
2360 (const :tag "Record timestamp" time)
2361 (const :tag "Record timestamp with note." note)))
2363 (defcustom org-log-redeadline nil
2364 "Information to record when the deadline date of a tasks is modified.
2366 Possible values are:
2368 nil Don't add anything, just change the date
2369 time Add a time stamp to the task
2370 note Prompt for a note and add it with template `org-log-note-headings'
2372 This option can also be set with on a per-file-basis with
2374 #+STARTUP: nologredeadline
2375 #+STARTUP: logredeadline
2376 #+STARTUP: lognoteredeadline
2378 You can have local logging settings for a subtree by setting the LOGGING
2379 property to one or more of these keywords."
2380 :group 'org-todo
2381 :group 'org-progress
2382 :type '(choice
2383 (const :tag "No logging" nil)
2384 (const :tag "Record timestamp" time)
2385 (const :tag "Record timestamp with note." note)))
2387 (defcustom org-log-note-clock-out nil
2388 "Non-nil means record a note when clocking out of an item.
2389 This can also be configured on a per-file basis by adding one of
2390 the following lines anywhere in the buffer:
2392 #+STARTUP: lognoteclock-out
2393 #+STARTUP: nolognoteclock-out"
2394 :group 'org-todo
2395 :group 'org-progress
2396 :type 'boolean)
2398 (defcustom org-log-done-with-time t
2399 "Non-nil means the CLOSED time stamp will contain date and time.
2400 When nil, only the date will be recorded."
2401 :group 'org-progress
2402 :type 'boolean)
2404 (defcustom org-log-note-headings
2405 '((done . "CLOSING NOTE %t")
2406 (state . "State %-12s from %-12S %t")
2407 (note . "Note taken on %t")
2408 (reschedule . "Rescheduled from %S on %t")
2409 (delschedule . "Not scheduled, was %S on %t")
2410 (redeadline . "New deadline from %S on %t")
2411 (deldeadline . "Removed deadline, was %S on %t")
2412 (refile . "Refiled on %t")
2413 (clock-out . ""))
2414 "Headings for notes added to entries.
2415 The value is an alist, with the car being a symbol indicating the note
2416 context, and the cdr is the heading to be used. The heading may also be the
2417 empty string.
2418 %t in the heading will be replaced by a time stamp.
2419 %T will be an active time stamp instead the default inactive one
2420 %d will be replaced by a short-format time stamp.
2421 %D will be replaced by an active short-format time stamp.
2422 %s will be replaced by the new TODO state, in double quotes.
2423 %S will be replaced by the old TODO state, in double quotes.
2424 %u will be replaced by the user name.
2425 %U will be replaced by the full user name.
2427 In fact, it is not a good idea to change the `state' entry, because
2428 agenda log mode depends on the format of these entries."
2429 :group 'org-todo
2430 :group 'org-progress
2431 :type '(list :greedy t
2432 (cons (const :tag "Heading when closing an item" done) string)
2433 (cons (const :tag
2434 "Heading when changing todo state (todo sequence only)"
2435 state) string)
2436 (cons (const :tag "Heading when just taking a note" note) string)
2437 (cons (const :tag "Heading when clocking out" clock-out) string)
2438 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2439 (cons (const :tag "Heading when rescheduling" reschedule) string)
2440 (cons (const :tag "Heading when changing deadline" redeadline) string)
2441 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2442 (cons (const :tag "Heading when refiling" refile) string)))
2444 (unless (assq 'note org-log-note-headings)
2445 (push '(note . "%t") org-log-note-headings))
2447 (defcustom org-log-into-drawer nil
2448 "Non-nil means insert state change notes and time stamps into a drawer.
2449 When nil, state changes notes will be inserted after the headline and
2450 any scheduling and clock lines, but not inside a drawer.
2452 The value of this variable should be the name of the drawer to use.
2453 LOGBOOK is proposed as the default drawer for this purpose, you can
2454 also set this to a string to define the drawer of your choice.
2456 A value of t is also allowed, representing \"LOGBOOK\".
2458 If this variable is set, `org-log-state-notes-insert-after-drawers'
2459 will be ignored.
2461 You can set the property LOG_INTO_DRAWER to overrule this setting for
2462 a subtree."
2463 :group 'org-todo
2464 :group 'org-progress
2465 :type '(choice
2466 (const :tag "Not into a drawer" nil)
2467 (const :tag "LOGBOOK" t)
2468 (string :tag "Other")))
2470 (if (fboundp 'defvaralias)
2471 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2473 (defun org-log-into-drawer ()
2474 "Return the value of `org-log-into-drawer', but let properties overrule.
2475 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2476 used instead of the default value."
2477 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2478 (cond
2479 ((or (not p) (equal p "nil")) org-log-into-drawer)
2480 ((equal p "t") "LOGBOOK")
2481 (t p))))
2483 (defcustom org-log-state-notes-insert-after-drawers nil
2484 "Non-nil means insert state change notes after any drawers in entry.
2485 Only the drawers that *immediately* follow the headline and the
2486 deadline/scheduled line are skipped.
2487 When nil, insert notes right after the heading and perhaps the line
2488 with deadline/scheduling if present.
2490 This variable will have no effect if `org-log-into-drawer' is
2491 set."
2492 :group 'org-todo
2493 :group 'org-progress
2494 :type 'boolean)
2496 (defcustom org-log-states-order-reversed t
2497 "Non-nil means the latest state note will be directly after heading.
2498 When nil, the state change notes will be ordered according to time."
2499 :group 'org-todo
2500 :group 'org-progress
2501 :type 'boolean)
2503 (defcustom org-todo-repeat-to-state nil
2504 "The TODO state to which a repeater should return the repeating task.
2505 By default this is the first task in a TODO sequence, or the previous state
2506 in a TODO_TYP set. But you can specify another task here.
2507 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2508 :group 'org-todo
2509 :type '(choice (const :tag "Head of sequence" nil)
2510 (string :tag "Specific state")))
2512 (defcustom org-log-repeat 'time
2513 "Non-nil means record moving through the DONE state when triggering repeat.
2514 An auto-repeating task is immediately switched back to TODO when
2515 marked DONE. If you are not logging state changes (by adding \"@\"
2516 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2517 record a closing note, there will be no record of the task moving
2518 through DONE. This variable forces taking a note anyway.
2520 nil Don't force a record
2521 time Record a time stamp
2522 note Record a note
2524 This option can also be set with on a per-file-basis with
2526 #+STARTUP: logrepeat
2527 #+STARTUP: lognoterepeat
2528 #+STARTUP: nologrepeat
2530 You can have local logging settings for a subtree by setting the LOGGING
2531 property to one or more of these keywords."
2532 :group 'org-todo
2533 :group 'org-progress
2534 :type '(choice
2535 (const :tag "Don't force a record" nil)
2536 (const :tag "Force recording the DONE state" time)
2537 (const :tag "Force recording a note with the DONE state" note)))
2540 (defgroup org-priorities nil
2541 "Priorities in Org-mode."
2542 :tag "Org Priorities"
2543 :group 'org-todo)
2545 (defcustom org-enable-priority-commands t
2546 "Non-nil means priority commands are active.
2547 When nil, these commands will be disabled, so that you never accidentally
2548 set a priority."
2549 :group 'org-priorities
2550 :type 'boolean)
2552 (defcustom org-highest-priority ?A
2553 "The highest priority of TODO items. A character like ?A, ?B etc.
2554 Must have a smaller ASCII number than `org-lowest-priority'."
2555 :group 'org-priorities
2556 :type 'character)
2558 (defcustom org-lowest-priority ?C
2559 "The lowest priority of TODO items. A character like ?A, ?B etc.
2560 Must have a larger ASCII number than `org-highest-priority'."
2561 :group 'org-priorities
2562 :type 'character)
2564 (defcustom org-default-priority ?B
2565 "The default priority of TODO items.
2566 This is the priority an item gets if no explicit priority is given.
2567 When starting to cycle on an empty priority the first step in the cycle
2568 depends on `org-priority-start-cycle-with-default'. The resulting first
2569 step priority must not exceed the range from `org-highest-priority' to
2570 `org-lowest-priority' which means that `org-default-priority' has to be
2571 in this range exclusive or inclusive the range boundaries. Else the
2572 first step refuses to set the default and the second will fall back
2573 to (depending on the command used) the highest or lowest priority."
2574 :group 'org-priorities
2575 :type 'character)
2577 (defcustom org-priority-start-cycle-with-default t
2578 "Non-nil means start with default priority when starting to cycle.
2579 When this is nil, the first step in the cycle will be (depending on the
2580 command used) one higher or lower than the default priority.
2581 See also `org-default-priority'."
2582 :group 'org-priorities
2583 :type 'boolean)
2585 (defcustom org-get-priority-function nil
2586 "Function to extract the priority from a string.
2587 The string is normally the headline. If this is nil Org computes the
2588 priority from the priority cookie like [#A] in the headline. It returns
2589 an integer, increasing by 1000 for each priority level.
2590 The user can set a different function here, which should take a string
2591 as an argument and return the numeric priority."
2592 :group 'org-priorities
2593 :type 'function)
2595 (defgroup org-time nil
2596 "Options concerning time stamps and deadlines in Org-mode."
2597 :tag "Org Time"
2598 :group 'org)
2600 (defcustom org-insert-labeled-timestamps-at-point nil
2601 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2602 When nil, these labeled time stamps are forces into the second line of an
2603 entry, just after the headline. When scheduling from the global TODO list,
2604 the time stamp will always be forced into the second line."
2605 :group 'org-time
2606 :type 'boolean)
2608 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2609 "Formats for `format-time-string' which are used for time stamps.
2610 It is not recommended to change this constant.")
2612 (defcustom org-time-stamp-rounding-minutes '(0 5)
2613 "Number of minutes to round time stamps to.
2614 These are two values, the first applies when first creating a time stamp.
2615 The second applies when changing it with the commands `S-up' and `S-down'.
2616 When changing the time stamp, this means that it will change in steps
2617 of N minutes, as given by the second value.
2619 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2620 numbers should be factors of 60, so for example 5, 10, 15.
2622 When this is larger than 1, you can still force an exact time stamp by using
2623 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2624 and by using a prefix arg to `S-up/down' to specify the exact number
2625 of minutes to shift."
2626 :group 'org-time
2627 :get #'(lambda (var) ; Make sure both elements are there
2628 (if (integerp (default-value var))
2629 (list (default-value var) 5)
2630 (default-value var)))
2631 :type '(list
2632 (integer :tag "when inserting times")
2633 (integer :tag "when modifying times")))
2635 ;; Normalize old customizations of this variable.
2636 (when (integerp org-time-stamp-rounding-minutes)
2637 (setq org-time-stamp-rounding-minutes
2638 (list org-time-stamp-rounding-minutes
2639 org-time-stamp-rounding-minutes)))
2641 (defcustom org-display-custom-times nil
2642 "Non-nil means overlay custom formats over all time stamps.
2643 The formats are defined through the variable `org-time-stamp-custom-formats'.
2644 To turn this on on a per-file basis, insert anywhere in the file:
2645 #+STARTUP: customtime"
2646 :group 'org-time
2647 :set 'set-default
2648 :type 'sexp)
2649 (make-variable-buffer-local 'org-display-custom-times)
2651 (defcustom org-time-stamp-custom-formats
2652 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2653 "Custom formats for time stamps. See `format-time-string' for the syntax.
2654 These are overlaid over the default ISO format if the variable
2655 `org-display-custom-times' is set. Time like %H:%M should be at the
2656 end of the second format. The custom formats are also honored by export
2657 commands, if custom time display is turned on at the time of export."
2658 :group 'org-time
2659 :type 'sexp)
2661 (defun org-time-stamp-format (&optional long inactive)
2662 "Get the right format for a time string."
2663 (let ((f (if long (cdr org-time-stamp-formats)
2664 (car org-time-stamp-formats))))
2665 (if inactive
2666 (concat "[" (substring f 1 -1) "]")
2667 f)))
2669 (defcustom org-time-clocksum-format "%d:%02d"
2670 "The format string used when creating CLOCKSUM lines.
2671 This is also used when org-mode generates a time duration."
2672 :group 'org-time
2673 :type 'string)
2675 (defcustom org-time-clocksum-use-fractional nil
2676 "If non-nil, \\[org-clock-display] uses fractional times.
2677 org-mode generates a time duration."
2678 :group 'org-time
2679 :type 'boolean)
2681 (defcustom org-time-clocksum-fractional-format "%.2f"
2682 "The format string used when creating CLOCKSUM lines, or when
2683 org-mode generates a time duration."
2684 :group 'org-time
2685 :type 'string)
2687 (defcustom org-deadline-warning-days 14
2688 "No. of days before expiration during which a deadline becomes active.
2689 This variable governs the display in sparse trees and in the agenda.
2690 When 0 or negative, it means use this number (the absolute value of it)
2691 even if a deadline has a different individual lead time specified.
2693 Custom commands can set this variable in the options section."
2694 :group 'org-time
2695 :group 'org-agenda-daily/weekly
2696 :type 'integer)
2698 (defcustom org-read-date-prefer-future t
2699 "Non-nil means assume future for incomplete date input from user.
2700 This affects the following situations:
2701 1. The user gives a month but not a year.
2702 For example, if it is April and you enter \"feb 2\", this will be read
2703 as Feb 2, *next* year. \"May 5\", however, will be this year.
2704 2. The user gives a day, but no month.
2705 For example, if today is the 15th, and you enter \"3\", Org-mode will
2706 read this as the third of *next* month. However, if you enter \"17\",
2707 it will be considered as *this* month.
2709 If you set this variable to the symbol `time', then also the following
2710 will work:
2712 3. If the user gives a time, but no day. If the time is before now,
2713 to will be interpreted as tomorrow.
2715 Currently none of this works for ISO week specifications.
2717 When this option is nil, the current day, month and year will always be
2718 used as defaults.
2720 See also `org-agenda-jump-prefer-future'."
2721 :group 'org-time
2722 :type '(choice
2723 (const :tag "Never" nil)
2724 (const :tag "Check month and day" t)
2725 (const :tag "Check month, day, and time" time)))
2727 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2728 "Should the agenda jump command prefer the future for incomplete dates?
2729 The default is to do the same as configured in `org-read-date-prefer-future'.
2730 But you can also set a deviating value here.
2731 This may t or nil, or the symbol `org-read-date-prefer-future'."
2732 :group 'org-agenda
2733 :group 'org-time
2734 :type '(choice
2735 (const :tag "Use org-read-date-prefer-future"
2736 org-read-date-prefer-future)
2737 (const :tag "Never" nil)
2738 (const :tag "Always" t)))
2740 (defcustom org-read-date-force-compatible-dates t
2741 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2743 Depending on the system Emacs is running on, certain dates cannot
2744 be represented with the type used internally to represent time.
2745 Dates between 1970-1-1 and 2038-1-1 can always be represented
2746 correctly. Some systems allow for earlier dates, some for later,
2747 some for both. One way to find out it to insert any date into an
2748 Org buffer, putting the cursor on the year and hitting S-up and
2749 S-down to test the range.
2751 When this variable is set to t, the date/time prompt will not let
2752 you specify dates outside the 1970-2037 range, so it is certain that
2753 these dates will work in whatever version of Emacs you are
2754 running, and also that you can move a file from one Emacs implementation
2755 to another. WHenever Org is forcing the year for you, it will display
2756 a message and beep.
2758 When this variable is nil, Org will check if the date is
2759 representable in the specific Emacs implementation you are using.
2760 If not, it will force a year, usually the current year, and beep
2761 to remind you. Currently this setting is not recommended because
2762 the likelihood that you will open your Org files in an Emacs that
2763 has limited date range is not negligible.
2765 A workaround for this problem is to use diary sexp dates for time
2766 stamps outside of this range."
2767 :group 'org-time
2768 :type 'boolean)
2770 (defcustom org-read-date-display-live t
2771 "Non-nil means display current interpretation of date prompt live.
2772 This display will be in an overlay, in the minibuffer."
2773 :group 'org-time
2774 :type 'boolean)
2776 (defcustom org-read-date-popup-calendar t
2777 "Non-nil means pop up a calendar when prompting for a date.
2778 In the calendar, the date can be selected with mouse-1. However, the
2779 minibuffer will also be active, and you can simply enter the date as well.
2780 When nil, only the minibuffer will be available."
2781 :group 'org-time
2782 :type 'boolean)
2783 (if (fboundp 'defvaralias)
2784 (defvaralias 'org-popup-calendar-for-date-prompt
2785 'org-read-date-popup-calendar))
2787 (defcustom org-read-date-minibuffer-setup-hook nil
2788 "Hook to be used to set up keys for the date/time interface.
2789 Add key definitions to `minibuffer-local-map', which will be a temporary
2790 copy."
2791 :group 'org-time
2792 :type 'hook)
2794 (defcustom org-extend-today-until 0
2795 "The hour when your day really ends. Must be an integer.
2796 This has influence for the following applications:
2797 - When switching the agenda to \"today\". It it is still earlier than
2798 the time given here, the day recognized as TODAY is actually yesterday.
2799 - When a date is read from the user and it is still before the time given
2800 here, the current date and time will be assumed to be yesterday, 23:59.
2801 Also, timestamps inserted in remember templates follow this rule.
2803 IMPORTANT: This is a feature whose implementation is and likely will
2804 remain incomplete. Really, it is only here because past midnight seems to
2805 be the favorite working time of John Wiegley :-)"
2806 :group 'org-time
2807 :type 'integer)
2809 (defcustom org-use-effective-time nil
2810 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2811 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2812 \"effective time\" of any timestamps between midnight and 8am will be
2813 23:59 of the previous day."
2814 :group 'boolean
2815 :type 'integer)
2817 (defcustom org-edit-timestamp-down-means-later nil
2818 "Non-nil means S-down will increase the time in a time stamp.
2819 When nil, S-up will increase."
2820 :group 'org-time
2821 :type 'boolean)
2823 (defcustom org-calendar-follow-timestamp-change t
2824 "Non-nil means make the calendar window follow timestamp changes.
2825 When a timestamp is modified and the calendar window is visible, it will be
2826 moved to the new date."
2827 :group 'org-time
2828 :type 'boolean)
2830 (defgroup org-tags nil
2831 "Options concerning tags in Org-mode."
2832 :tag "Org Tags"
2833 :group 'org)
2835 (defcustom org-tag-alist nil
2836 "List of tags allowed in Org-mode files.
2837 When this list is nil, Org-mode will base TAG input on what is already in the
2838 buffer.
2839 The value of this variable is an alist, the car of each entry must be a
2840 keyword as a string, the cdr may be a character that is used to select
2841 that tag through the fast-tag-selection interface.
2842 See the manual for details."
2843 :group 'org-tags
2844 :type '(repeat
2845 (choice
2846 (cons (string :tag "Tag name")
2847 (character :tag "Access char"))
2848 (list :tag "Start radio group"
2849 (const :startgroup)
2850 (option (string :tag "Group description")))
2851 (list :tag "End radio group"
2852 (const :endgroup)
2853 (option (string :tag "Group description")))
2854 (const :tag "New line" (:newline)))))
2856 (defcustom org-tag-persistent-alist nil
2857 "List of tags that will always appear in all Org-mode files.
2858 This is in addition to any in buffer settings or customizations
2859 of `org-tag-alist'.
2860 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2861 The value of this variable is an alist, the car of each entry must be a
2862 keyword as a string, the cdr may be a character that is used to select
2863 that tag through the fast-tag-selection interface.
2864 See the manual for details.
2865 To disable these tags on a per-file basis, insert anywhere in the file:
2866 #+STARTUP: noptag"
2867 :group 'org-tags
2868 :type '(repeat
2869 (choice
2870 (cons (string :tag "Tag name")
2871 (character :tag "Access char"))
2872 (const :tag "Start radio group" (:startgroup))
2873 (const :tag "End radio group" (:endgroup))
2874 (const :tag "New line" (:newline)))))
2876 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2877 "If non-nil, always offer completion for all tags of all agenda files.
2878 Instead of customizing this variable directly, you might want to
2879 set it locally for capture buffers, because there no list of
2880 tags in that file can be created dynamically (there are none).
2882 (add-hook 'org-capture-mode-hook
2883 (lambda ()
2884 (set (make-local-variable
2885 'org-complete-tags-always-offer-all-agenda-tags)
2886 t)))"
2887 :group 'org-tags
2888 :type 'boolean)
2890 (defvar org-file-tags nil
2891 "List of tags that can be inherited by all entries in the file.
2892 The tags will be inherited if the variable `org-use-tag-inheritance'
2893 says they should be.
2894 This variable is populated from #+FILETAGS lines.")
2896 (defcustom org-use-fast-tag-selection 'auto
2897 "Non-nil means use fast tag selection scheme.
2898 This is a special interface to select and deselect tags with single keys.
2899 When nil, fast selection is never used.
2900 When the symbol `auto', fast selection is used if and only if selection
2901 characters for tags have been configured, either through the variable
2902 `org-tag-alist' or through a #+TAGS line in the buffer.
2903 When t, fast selection is always used and selection keys are assigned
2904 automatically if necessary."
2905 :group 'org-tags
2906 :type '(choice
2907 (const :tag "Always" t)
2908 (const :tag "Never" nil)
2909 (const :tag "When selection characters are configured" 'auto)))
2911 (defcustom org-fast-tag-selection-single-key nil
2912 "Non-nil means fast tag selection exits after first change.
2913 When nil, you have to press RET to exit it.
2914 During fast tag selection, you can toggle this flag with `C-c'.
2915 This variable can also have the value `expert'. In this case, the window
2916 displaying the tags menu is not even shown, until you press C-c again."
2917 :group 'org-tags
2918 :type '(choice
2919 (const :tag "No" nil)
2920 (const :tag "Yes" t)
2921 (const :tag "Expert" expert)))
2923 (defvar org-fast-tag-selection-include-todo nil
2924 "Non-nil means fast tags selection interface will also offer TODO states.
2925 This is an undocumented feature, you should not rely on it.")
2927 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2928 "The column to which tags should be indented in a headline.
2929 If this number is positive, it specifies the column. If it is negative,
2930 it means that the tags should be flushright to that column. For example,
2931 -80 works well for a normal 80 character screen.
2932 When 0, place tags directly after headline text, with only one space in
2933 between."
2934 :group 'org-tags
2935 :type 'integer)
2937 (defcustom org-auto-align-tags t
2938 "Non-nil keeps tags aligned when modifying headlines.
2939 Some operations (i.e. demoting) change the length of a headline and
2940 therefore shift the tags around. With this option turned on, after
2941 each such operation the tags are again aligned to `org-tags-column'."
2942 :group 'org-tags
2943 :type 'boolean)
2945 (defcustom org-use-tag-inheritance t
2946 "Non-nil means tags in levels apply also for sublevels.
2947 When nil, only the tags directly given in a specific line apply there.
2948 This may also be a list of tags that should be inherited, or a regexp that
2949 matches tags that should be inherited. Additional control is possible
2950 with the variable `org-tags-exclude-from-inheritance' which gives an
2951 explicit list of tags to be excluded from inheritance., even if the value of
2952 `org-use-tag-inheritance' would select it for inheritance.
2954 If this option is t, a match early-on in a tree can lead to a large
2955 number of matches in the subtree when constructing the agenda or creating
2956 a sparse tree. If you only want to see the first match in a tree during
2957 a search, check out the variable `org-tags-match-list-sublevels'."
2958 :group 'org-tags
2959 :type '(choice
2960 (const :tag "Not" nil)
2961 (const :tag "Always" t)
2962 (repeat :tag "Specific tags" (string :tag "Tag"))
2963 (regexp :tag "Tags matched by regexp")))
2965 (defcustom org-tags-exclude-from-inheritance nil
2966 "List of tags that should never be inherited.
2967 This is a way to exclude a few tags from inheritance. For way to do
2968 the opposite, to actively allow inheritance for selected tags,
2969 see the variable `org-use-tag-inheritance'."
2970 :group 'org-tags
2971 :type '(repeat (string :tag "Tag")))
2973 (defun org-tag-inherit-p (tag)
2974 "Check if TAG is one that should be inherited."
2975 (cond
2976 ((member tag org-tags-exclude-from-inheritance) nil)
2977 ((eq org-use-tag-inheritance t) t)
2978 ((not org-use-tag-inheritance) nil)
2979 ((stringp org-use-tag-inheritance)
2980 (string-match org-use-tag-inheritance tag))
2981 ((listp org-use-tag-inheritance)
2982 (member tag org-use-tag-inheritance))
2983 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2985 (defcustom org-tags-match-list-sublevels t
2986 "Non-nil means list also sublevels of headlines matching a search.
2987 This variable applies to tags/property searches, and also to stuck
2988 projects because this search is based on a tags match as well.
2990 When set to the symbol `indented', sublevels are indented with
2991 leading dots.
2993 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2994 the sublevels of a headline matching a tag search often also match
2995 the same search. Listing all of them can create very long lists.
2996 Setting this variable to nil causes subtrees of a match to be skipped.
2998 This variable is semi-obsolete and probably should always be true. It
2999 is better to limit inheritance to certain tags using the variables
3000 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3001 :group 'org-tags
3002 :type '(choice
3003 (const :tag "No, don't list them" nil)
3004 (const :tag "Yes, do list them" t)
3005 (const :tag "List them, indented with leading dots" indented)))
3007 (defcustom org-tags-sort-function nil
3008 "When set, tags are sorted using this function as a comparator."
3009 :group 'org-tags
3010 :type '(choice
3011 (const :tag "No sorting" nil)
3012 (const :tag "Alphabetical" string<)
3013 (const :tag "Reverse alphabetical" string>)
3014 (function :tag "Custom function" nil)))
3016 (defvar org-tags-history nil
3017 "History of minibuffer reads for tags.")
3018 (defvar org-last-tags-completion-table nil
3019 "The last used completion table for tags.")
3020 (defvar org-after-tags-change-hook nil
3021 "Hook that is run after the tags in a line have changed.")
3023 (defgroup org-properties nil
3024 "Options concerning properties in Org-mode."
3025 :tag "Org Properties"
3026 :group 'org)
3028 (defcustom org-property-format "%-10s %s"
3029 "How property key/value pairs should be formatted by `indent-line'.
3030 When `indent-line' hits a property definition, it will format the line
3031 according to this format, mainly to make sure that the values are
3032 lined-up with respect to each other."
3033 :group 'org-properties
3034 :type 'string)
3036 (defcustom org-properties-postprocess-alist nil
3037 "Alist of properties and functions to adjust inserted values.
3038 Elements of this alist must be of the form
3040 ([string] [function])
3042 where [string] must be a property name and [function] must be a
3043 lambda expression: this lambda expression must take one argument,
3044 the value to adjust, and return the new value as a string.
3046 For example, this element will allow the property \"Remaining\"
3047 to be updated wrt the relation between the \"Effort\" property
3048 and the clock summary:
3050 ((\"Remaining\" (lambda(value)
3051 (let ((clocksum (org-clock-sum-current-item))
3052 (effort (org-duration-string-to-minutes
3053 (org-entry-get (point) \"Effort\"))))
3054 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3055 :group 'org-properties
3056 :type 'alist)
3058 (defcustom org-use-property-inheritance nil
3059 "Non-nil means properties apply also for sublevels.
3061 This setting is chiefly used during property searches. Turning it on can
3062 cause significant overhead when doing a search, which is why it is not
3063 on by default.
3065 When nil, only the properties directly given in the current entry count.
3066 When t, every property is inherited. The value may also be a list of
3067 properties that should have inheritance, or a regular expression matching
3068 properties that should be inherited.
3070 However, note that some special properties use inheritance under special
3071 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3072 and the properties ending in \"_ALL\" when they are used as descriptor
3073 for valid values of a property.
3075 Note for programmers:
3076 When querying an entry with `org-entry-get', you can control if inheritance
3077 should be used. By default, `org-entry-get' looks only at the local
3078 properties. You can request inheritance by setting the inherit argument
3079 to t (to force inheritance) or to `selective' (to respect the setting
3080 in this variable)."
3081 :group 'org-properties
3082 :type '(choice
3083 (const :tag "Not" nil)
3084 (const :tag "Always" t)
3085 (repeat :tag "Specific properties" (string :tag "Property"))
3086 (regexp :tag "Properties matched by regexp")))
3088 (defun org-property-inherit-p (property)
3089 "Check if PROPERTY is one that should be inherited."
3090 (cond
3091 ((eq org-use-property-inheritance t) t)
3092 ((not org-use-property-inheritance) nil)
3093 ((stringp org-use-property-inheritance)
3094 (string-match org-use-property-inheritance property))
3095 ((listp org-use-property-inheritance)
3096 (member property org-use-property-inheritance))
3097 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3099 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3100 "The default column format, if no other format has been defined.
3101 This variable can be set on the per-file basis by inserting a line
3103 #+COLUMNS: %25ITEM ....."
3104 :group 'org-properties
3105 :type 'string)
3107 (defcustom org-columns-ellipses ".."
3108 "The ellipses to be used when a field in column view is truncated.
3109 When this is the empty string, as many characters as possible are shown,
3110 but then there will be no visual indication that the field has been truncated.
3111 When this is a string of length N, the last N characters of a truncated
3112 field are replaced by this string. If the column is narrower than the
3113 ellipses string, only part of the ellipses string will be shown."
3114 :group 'org-properties
3115 :type 'string)
3117 (defcustom org-columns-modify-value-for-display-function nil
3118 "Function that modifies values for display in column view.
3119 For example, it can be used to cut out a certain part from a time stamp.
3120 The function must take 2 arguments:
3122 column-title The title of the column (*not* the property name)
3123 value The value that should be modified.
3125 The function should return the value that should be displayed,
3126 or nil if the normal value should be used."
3127 :group 'org-properties
3128 :type 'function)
3130 (defcustom org-effort-property "Effort"
3131 "The property that is being used to keep track of effort estimates.
3132 Effort estimates given in this property need to have the format H:MM."
3133 :group 'org-properties
3134 :group 'org-progress
3135 :type '(string :tag "Property"))
3137 (defconst org-global-properties-fixed
3138 '(("VISIBILITY_ALL" . "folded children content all")
3139 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3140 "List of property/value pairs that can be inherited by any entry.
3142 These are fixed values, for the preset properties. The user variable
3143 that can be used to add to this list is `org-global-properties'.
3145 The entries in this list are cons cells where the car is a property
3146 name and cdr is a string with the value. If the value represents
3147 multiple items like an \"_ALL\" property, separate the items by
3148 spaces.")
3150 (defcustom org-global-properties nil
3151 "List of property/value pairs that can be inherited by any entry.
3153 This list will be combined with the constant `org-global-properties-fixed'.
3155 The entries in this list are cons cells where the car is a property
3156 name and cdr is a string with the value.
3158 You can set buffer-local values for the same purpose in the variable
3159 `org-file-properties' this by adding lines like
3161 #+PROPERTY: NAME VALUE"
3162 :group 'org-properties
3163 :type '(repeat
3164 (cons (string :tag "Property")
3165 (string :tag "Value"))))
3167 (defvar org-file-properties nil
3168 "List of property/value pairs that can be inherited by any entry.
3169 Valid for the current buffer.
3170 This variable is populated from #+PROPERTY lines.")
3171 (make-variable-buffer-local 'org-file-properties)
3173 (defgroup org-agenda nil
3174 "Options concerning agenda views in Org-mode."
3175 :tag "Org Agenda"
3176 :group 'org)
3178 (defvar org-category nil
3179 "Variable used by org files to set a category for agenda display.
3180 Such files should use a file variable to set it, for example
3182 # -*- mode: org; org-category: \"ELisp\"
3184 or contain a special line
3186 #+CATEGORY: ELisp
3188 If the file does not specify a category, then file's base name
3189 is used instead.")
3190 (make-variable-buffer-local 'org-category)
3191 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3193 (defcustom org-agenda-files nil
3194 "The files to be used for agenda display.
3195 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3196 \\[org-remove-file]. You can also use customize to edit the list.
3198 If an entry is a directory, all files in that directory that are matched by
3199 `org-agenda-file-regexp' will be part of the file list.
3201 If the value of the variable is not a list but a single file name, then
3202 the list of agenda files is actually stored and maintained in that file, one
3203 agenda file per line. In this file paths can be given relative to
3204 `org-directory'. Tilde expansion and environment variable substitution
3205 are also made."
3206 :group 'org-agenda
3207 :type '(choice
3208 (repeat :tag "List of files and directories" file)
3209 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3211 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3212 "Regular expression to match files for `org-agenda-files'.
3213 If any element in the list in that variable contains a directory instead
3214 of a normal file, all files in that directory that are matched by this
3215 regular expression will be included."
3216 :group 'org-agenda
3217 :type 'regexp)
3219 (defcustom org-agenda-text-search-extra-files nil
3220 "List of extra files to be searched by text search commands.
3221 These files will be search in addition to the agenda files by the
3222 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3223 Note that these files will only be searched for text search commands,
3224 not for the other agenda views like todo lists, tag searches or the weekly
3225 agenda. This variable is intended to list notes and possibly archive files
3226 that should also be searched by these two commands.
3227 In fact, if the first element in the list is the symbol `agenda-archives',
3228 than all archive files of all agenda files will be added to the search
3229 scope."
3230 :group 'org-agenda
3231 :type '(set :greedy t
3232 (const :tag "Agenda Archives" agenda-archives)
3233 (repeat :inline t (file))))
3235 (if (fboundp 'defvaralias)
3236 (defvaralias 'org-agenda-multi-occur-extra-files
3237 'org-agenda-text-search-extra-files))
3239 (defcustom org-agenda-skip-unavailable-files nil
3240 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3241 A nil value means to remove them, after a query, from the list."
3242 :group 'org-agenda
3243 :type 'boolean)
3245 (defcustom org-calendar-to-agenda-key [?c]
3246 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3247 The command `org-calendar-goto-agenda' will be bound to this key. The
3248 default is the character `c' because then `c' can be used to switch back and
3249 forth between agenda and calendar."
3250 :group 'org-agenda
3251 :type 'sexp)
3253 (defcustom org-calendar-agenda-action-key [?k]
3254 "The key to be installed in `calendar-mode-map' for agenda-action.
3255 The command `org-agenda-action' will be bound to this key. The
3256 default is the character `k' because we use the same key in the agenda."
3257 :group 'org-agenda
3258 :type 'sexp)
3260 (defcustom org-calendar-insert-diary-entry-key [?i]
3261 "The key to be installed in `calendar-mode-map' for adding diary entries.
3262 This option is irrelevant until `org-agenda-diary-file' has been configured
3263 to point to an Org-mode file. When that is the case, the command
3264 `org-agenda-diary-entry' will be bound to the key given here, by default
3265 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3266 if you want to continue doing this, you need to change this to a different
3267 key."
3268 :group 'org-agenda
3269 :type 'sexp)
3271 (defcustom org-agenda-diary-file 'diary-file
3272 "File to which to add new entries with the `i' key in agenda and calendar.
3273 When this is the symbol `diary-file', the functionality in the Emacs
3274 calendar will be used to add entries to the `diary-file'. But when this
3275 points to a file, `org-agenda-diary-entry' will be used instead."
3276 :group 'org-agenda
3277 :type '(choice
3278 (const :tag "The standard Emacs diary file" diary-file)
3279 (file :tag "Special Org file diary entries")))
3281 (eval-after-load "calendar"
3282 '(progn
3283 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3284 'org-calendar-goto-agenda)
3285 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3286 'org-agenda-action)
3287 (add-hook 'calendar-mode-hook
3288 (lambda ()
3289 (unless (eq org-agenda-diary-file 'diary-file)
3290 (define-key calendar-mode-map
3291 org-calendar-insert-diary-entry-key
3292 'org-agenda-diary-entry))))))
3294 (defgroup org-latex nil
3295 "Options for embedding LaTeX code into Org-mode."
3296 :tag "Org LaTeX"
3297 :group 'org)
3299 (defcustom org-format-latex-options
3300 '(:foreground default :background default :scale 1.0
3301 :html-foreground "Black" :html-background "Transparent"
3302 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3303 "Options for creating images from LaTeX fragments.
3304 This is a property list with the following properties:
3305 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3306 `default' means use the foreground of the default face.
3307 :background the background color, or \"Transparent\".
3308 `default' means use the background of the default face.
3309 :scale a scaling factor for the size of the images, to get more pixels
3310 :html-foreground, :html-background, :html-scale
3311 the same numbers for HTML export.
3312 :matchers a list indicating which matchers should be used to
3313 find LaTeX fragments. Valid members of this list are:
3314 \"begin\" find environments
3315 \"$1\" find single characters surrounded by $.$
3316 \"$\" find math expressions surrounded by $...$
3317 \"$$\" find math expressions surrounded by $$....$$
3318 \"\\(\" find math expressions surrounded by \\(...\\)
3319 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3320 :group 'org-latex
3321 :type 'plist)
3323 (defcustom org-format-latex-signal-error t
3324 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3325 When nil, just push out a message."
3326 :group 'org-latex
3327 :type 'boolean)
3328 (defcustom org-latex-to-mathml-jar-file nil
3329 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3330 Use this to specify additional executable file say a jar file.
3332 When using MathToWeb as the converter, specify the full-path to
3333 your mathtoweb.jar file."
3334 :group 'org-latex
3335 :type '(choice
3336 (const :tag "None" nil)
3337 (file :tag "JAR file" :must-match t)))
3339 (defcustom org-latex-to-mathml-convert-command nil
3340 "Command to convert LaTeX fragments to MathML.
3341 Replace format-specifiers in the command as noted below and use
3342 `shell-command' to convert LaTeX to MathML.
3343 %j: Executable file in fully expanded form as specified by
3344 `org-latex-to-mathml-jar-file'.
3345 %I: Input LaTeX file in fully expanded form
3346 %o: Output MathML file
3347 This command is used by `org-create-math-formula'.
3349 When using MathToWeb as the converter, set this to
3350 \"java -jar %j -unicode -force -df %o %I\"."
3351 :group 'org-latex
3352 :type '(choice
3353 (const :tag "None" nil)
3354 (string :tag "\nShell command")))
3356 (defun org-format-latex-mathml-available-p ()
3357 "Return t if `org-latex-to-mathml-convert-command' is usable."
3358 (save-match-data
3359 (when (and (boundp 'org-latex-to-mathml-convert-command)
3360 org-latex-to-mathml-convert-command)
3361 (let ((executable (car (split-string
3362 org-latex-to-mathml-convert-command))))
3363 (when (executable-find executable)
3364 (if (string-match
3365 "%j" org-latex-to-mathml-convert-command)
3366 (file-readable-p org-latex-to-mathml-jar-file)
3367 t))))))
3369 (defcustom org-format-latex-header "\\documentclass{article}
3370 \\usepackage[usenames]{color}
3371 \\usepackage{amsmath}
3372 \\usepackage[mathscr]{eucal}
3373 \\pagestyle{empty} % do not remove
3374 \[PACKAGES]
3375 \[DEFAULT-PACKAGES]
3376 % The settings below are copied from fullpage.sty
3377 \\setlength{\\textwidth}{\\paperwidth}
3378 \\addtolength{\\textwidth}{-3cm}
3379 \\setlength{\\oddsidemargin}{1.5cm}
3380 \\addtolength{\\oddsidemargin}{-2.54cm}
3381 \\setlength{\\evensidemargin}{\\oddsidemargin}
3382 \\setlength{\\textheight}{\\paperheight}
3383 \\addtolength{\\textheight}{-\\headheight}
3384 \\addtolength{\\textheight}{-\\headsep}
3385 \\addtolength{\\textheight}{-\\footskip}
3386 \\addtolength{\\textheight}{-3cm}
3387 \\setlength{\\topmargin}{1.5cm}
3388 \\addtolength{\\topmargin}{-2.54cm}"
3389 "The document header used for processing LaTeX fragments.
3390 It is imperative that this header make sure that no page number
3391 appears on the page. The package defined in the variables
3392 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3393 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3394 will be appended."
3395 :group 'org-latex
3396 :type 'string)
3398 (defvar org-format-latex-header-extra nil)
3400 (defun org-set-packages-alist (var val)
3401 "Set the packages alist and make sure it has 3 elements per entry."
3402 (set var (mapcar (lambda (x)
3403 (if (and (consp x) (= (length x) 2))
3404 (list (car x) (nth 1 x) t)
3406 val)))
3408 (defun org-get-packages-alist (var)
3410 "Get the packages alist and make sure it has 3 elements per entry."
3411 (mapcar (lambda (x)
3412 (if (and (consp x) (= (length x) 2))
3413 (list (car x) (nth 1 x) t)
3415 (default-value var)))
3417 ;; The following variables are defined here because is it also used
3418 ;; when formatting latex fragments. Originally it was part of the
3419 ;; LaTeX exporter, which is why the name includes "export".
3420 (defcustom org-export-latex-default-packages-alist
3421 '(("AUTO" "inputenc" t)
3422 ("T1" "fontenc" t)
3423 ("" "fixltx2e" nil)
3424 ("" "graphicx" t)
3425 ("" "longtable" nil)
3426 ("" "float" nil)
3427 ("" "wrapfig" nil)
3428 ("" "soul" t)
3429 ("" "textcomp" t)
3430 ("" "marvosym" t)
3431 ("" "wasysym" t)
3432 ("" "latexsym" t)
3433 ("" "amssymb" t)
3434 ("" "hyperref" nil)
3435 "\\tolerance=1000"
3437 "Alist of default packages to be inserted in the header.
3438 Change this only if one of the packages here causes an incompatibility
3439 with another package you are using.
3440 The packages in this list are needed by one part or another of Org-mode
3441 to function properly.
3443 - inputenc, fontenc: for basic font and character selection
3444 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3445 for interpreting the entities in `org-entities'. You can skip some of these
3446 packages if you don't use any of the symbols in it.
3447 - graphicx: for including images
3448 - float, wrapfig: for figure placement
3449 - longtable: for long tables
3450 - hyperref: for cross references
3452 Therefore you should not modify this variable unless you know what you
3453 are doing. The one reason to change it anyway is that you might be loading
3454 some other package that conflicts with one of the default packages.
3455 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3456 If SNIPPET-FLAG is t, the package also needs to be included when
3457 compiling LaTeX snippets into images for inclusion into HTML."
3458 :group 'org-export-latex
3459 :set 'org-set-packages-alist
3460 :get 'org-get-packages-alist
3461 :type '(repeat
3462 (choice
3463 (list :tag "options/package pair"
3464 (string :tag "options")
3465 (string :tag "package")
3466 (boolean :tag "Snippet"))
3467 (string :tag "A line of LaTeX"))))
3469 (defcustom org-export-latex-packages-alist nil
3470 "Alist of packages to be inserted in every LaTeX header.
3471 These will be inserted after `org-export-latex-default-packages-alist'.
3472 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3473 SNIPPET-FLAG, when t, indicates that this package is also needed when
3474 turning LaTeX snippets into images for inclusion into HTML.
3475 Make sure that you only list packages here which:
3476 - you want in every file
3477 - do not conflict with the default packages in
3478 `org-export-latex-default-packages-alist'
3479 - do not conflict with the setup in `org-format-latex-header'."
3480 :group 'org-export-latex
3481 :set 'org-set-packages-alist
3482 :get 'org-get-packages-alist
3483 :type '(repeat
3484 (choice
3485 (list :tag "options/package pair"
3486 (string :tag "options")
3487 (string :tag "package")
3488 (boolean :tag "Snippet"))
3489 (string :tag "A line of LaTeX"))))
3492 (defgroup org-appearance nil
3493 "Settings for Org-mode appearance."
3494 :tag "Org Appearance"
3495 :group 'org)
3497 (defcustom org-level-color-stars-only nil
3498 "Non-nil means fontify only the stars in each headline.
3499 When nil, the entire headline is fontified.
3500 Changing it requires restart of `font-lock-mode' to become effective
3501 also in regions already fontified."
3502 :group 'org-appearance
3503 :type 'boolean)
3505 (defcustom org-hide-leading-stars nil
3506 "Non-nil means hide the first N-1 stars in a headline.
3507 This works by using the face `org-hide' for these stars. This
3508 face is white for a light background, and black for a dark
3509 background. You may have to customize the face `org-hide' to
3510 make this work.
3511 Changing it requires restart of `font-lock-mode' to become effective
3512 also in regions already fontified.
3513 You may also set this on a per-file basis by adding one of the following
3514 lines to the buffer:
3516 #+STARTUP: hidestars
3517 #+STARTUP: showstars"
3518 :group 'org-appearance
3519 :type 'boolean)
3521 (defcustom org-hidden-keywords nil
3522 "List of symbols corresponding to keywords to be hidden the org buffer.
3523 For example, a value '(title) for this list will make the document's title
3524 appear in the buffer without the initial #+TITLE: keyword."
3525 :group 'org-appearance
3526 :type '(set (const :tag "#+AUTHOR" author)
3527 (const :tag "#+DATE" date)
3528 (const :tag "#+EMAIL" email)
3529 (const :tag "#+TITLE" title)))
3531 (defcustom org-fontify-done-headline nil
3532 "Non-nil means change the face of a headline if it is marked DONE.
3533 Normally, only the TODO/DONE keyword indicates the state of a headline.
3534 When this is non-nil, the headline after the keyword is set to the
3535 `org-headline-done' as an additional indication."
3536 :group 'org-appearance
3537 :type 'boolean)
3539 (defcustom org-fontify-emphasized-text t
3540 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3541 Changing this variable requires a restart of Emacs to take effect."
3542 :group 'org-appearance
3543 :type 'boolean)
3545 (defcustom org-fontify-whole-heading-line nil
3546 "Non-nil means fontify the whole line for headings.
3547 This is useful when setting a background color for the
3548 org-level-* faces."
3549 :group 'org-appearance
3550 :type 'boolean)
3552 (defcustom org-highlight-latex-fragments-and-specials nil
3553 "Non-nil means fontify what is treated specially by the exporters."
3554 :group 'org-appearance
3555 :type 'boolean)
3557 (defcustom org-hide-emphasis-markers nil
3558 "Non-nil mean font-lock should hide the emphasis marker characters."
3559 :group 'org-appearance
3560 :type 'boolean)
3562 (defcustom org-pretty-entities nil
3563 "Non-nil means show entities as UTF8 characters.
3564 When nil, the \\name form remains in the buffer."
3565 :group 'org-appearance
3566 :type 'boolean)
3568 (defcustom org-pretty-entities-include-sub-superscripts t
3569 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3570 :group 'org-appearance
3571 :type 'boolean)
3573 (defvar org-emph-re nil
3574 "Regular expression for matching emphasis.
3575 After a match, the match groups contain these elements:
3576 0 The match of the full regular expression, including the characters
3577 before and after the proper match
3578 1 The character before the proper match, or empty at beginning of line
3579 2 The proper match, including the leading and trailing markers
3580 3 The leading marker like * or /, indicating the type of highlighting
3581 4 The text between the emphasis markers, not including the markers
3582 5 The character after the match, empty at the end of a line")
3583 (defvar org-verbatim-re nil
3584 "Regular expression for matching verbatim text.")
3585 (defvar org-emphasis-regexp-components) ; defined just below
3586 (defvar org-emphasis-alist) ; defined just below
3587 (defun org-set-emph-re (var val)
3588 "Set variable and compute the emphasis regular expression."
3589 (set var val)
3590 (when (and (boundp 'org-emphasis-alist)
3591 (boundp 'org-emphasis-regexp-components)
3592 org-emphasis-alist org-emphasis-regexp-components)
3593 (let* ((e org-emphasis-regexp-components)
3594 (pre (car e))
3595 (post (nth 1 e))
3596 (border (nth 2 e))
3597 (body (nth 3 e))
3598 (nl (nth 4 e))
3599 (body1 (concat body "*?"))
3600 (markers (mapconcat 'car org-emphasis-alist ""))
3601 (vmarkers (mapconcat
3602 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3603 org-emphasis-alist "")))
3604 ;; make sure special characters appear at the right position in the class
3605 (if (string-match "\\^" markers)
3606 (setq markers (concat (replace-match "" t t markers) "^")))
3607 (if (string-match "-" markers)
3608 (setq markers (concat (replace-match "" t t markers) "-")))
3609 (if (string-match "\\^" vmarkers)
3610 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3611 (if (string-match "-" vmarkers)
3612 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3613 (if (> nl 0)
3614 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3615 (int-to-string nl) "\\}")))
3616 ;; Make the regexp
3617 (setq org-emph-re
3618 (concat "\\([" pre "]\\|^\\)"
3619 "\\("
3620 "\\([" markers "]\\)"
3621 "\\("
3622 "[^" border "]\\|"
3623 "[^" border "]"
3624 body1
3625 "[^" border "]"
3626 "\\)"
3627 "\\3\\)"
3628 "\\([" post "]\\|$\\)"))
3629 (setq org-verbatim-re
3630 (concat "\\([" pre "]\\|^\\)"
3631 "\\("
3632 "\\([" vmarkers "]\\)"
3633 "\\("
3634 "[^" border "]\\|"
3635 "[^" border "]"
3636 body1
3637 "[^" border "]"
3638 "\\)"
3639 "\\3\\)"
3640 "\\([" post "]\\|$\\)")))))
3642 (defcustom org-emphasis-regexp-components
3643 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3644 "Components used to build the regular expression for emphasis.
3645 This is a list with five entries. Terminology: In an emphasis string
3646 like \" *strong word* \", we call the initial space PREMATCH, the final
3647 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3648 and \"trong wor\" is the body. The different components in this variable
3649 specify what is allowed/forbidden in each part:
3651 pre Chars allowed as prematch. Beginning of line will be allowed too.
3652 post Chars allowed as postmatch. End of line will be allowed too.
3653 border The chars *forbidden* as border characters.
3654 body-regexp A regexp like \".\" to match a body character. Don't use
3655 non-shy groups here, and don't allow newline here.
3656 newline The maximum number of newlines allowed in an emphasis exp.
3658 Use customize to modify this, or restart Emacs after changing it."
3659 :group 'org-appearance
3660 :set 'org-set-emph-re
3661 :type '(list
3662 (sexp :tag "Allowed chars in pre ")
3663 (sexp :tag "Allowed chars in post ")
3664 (sexp :tag "Forbidden chars in border ")
3665 (sexp :tag "Regexp for body ")
3666 (integer :tag "number of newlines allowed")
3667 (option (boolean :tag "Please ignore this button"))))
3669 (defcustom org-emphasis-alist
3670 `(("*" bold "<b>" "</b>")
3671 ("/" italic "<i>" "</i>")
3672 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3673 ("=" org-code "<code>" "</code>" verbatim)
3674 ("~" org-verbatim "<code>" "</code>" verbatim)
3675 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3676 "<del>" "</del>")
3678 "Special syntax for emphasized text.
3679 Text starting and ending with a special character will be emphasized, for
3680 example *bold*, _underlined_ and /italic/. This variable sets the marker
3681 characters, the face to be used by font-lock for highlighting in Org-mode
3682 Emacs buffers, and the HTML tags to be used for this.
3683 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3684 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3685 Use customize to modify this, or restart Emacs after changing it."
3686 :group 'org-appearance
3687 :set 'org-set-emph-re
3688 :type '(repeat
3689 (list
3690 (string :tag "Marker character")
3691 (choice
3692 (face :tag "Font-lock-face")
3693 (plist :tag "Face property list"))
3694 (string :tag "HTML start tag")
3695 (string :tag "HTML end tag")
3696 (option (const verbatim)))))
3698 (defvar org-protecting-blocks
3699 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3700 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3701 This is needed for font-lock setup.")
3703 ;;; Miscellaneous options
3705 (defgroup org-completion nil
3706 "Completion in Org-mode."
3707 :tag "Org Completion"
3708 :group 'org)
3710 (defcustom org-completion-use-ido nil
3711 "Non-nil means use ido completion wherever possible.
3712 Note that `ido-mode' must be active for this variable to be relevant.
3713 If you decide to turn this variable on, you might well want to turn off
3714 `org-outline-path-complete-in-steps'.
3715 See also `org-completion-use-iswitchb'."
3716 :group 'org-completion
3717 :type 'boolean)
3719 (defcustom org-completion-use-iswitchb nil
3720 "Non-nil means use iswitchb completion wherever possible.
3721 Note that `iswitchb-mode' must be active for this variable to be relevant.
3722 If you decide to turn this variable on, you might well want to turn off
3723 `org-outline-path-complete-in-steps'.
3724 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3725 :group 'org-completion
3726 :type 'boolean)
3728 (defcustom org-completion-fallback-command 'hippie-expand
3729 "The expansion command called by \\[pcomplete] in normal context.
3730 Normal means, no org-mode-specific context."
3731 :group 'org-completion
3732 :type 'function)
3734 ;;; Functions and variables from their packages
3735 ;; Declared here to avoid compiler warnings
3737 ;; XEmacs only
3738 (defvar outline-mode-menu-heading)
3739 (defvar outline-mode-menu-show)
3740 (defvar outline-mode-menu-hide)
3741 (defvar zmacs-regions) ; XEmacs regions
3743 ;; Emacs only
3744 (defvar mark-active)
3746 ;; Various packages
3747 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3748 (declare-function calendar-forward-day "cal-move" (arg))
3749 (declare-function calendar-goto-date "cal-move" (date))
3750 (declare-function calendar-goto-today "cal-move" ())
3751 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3752 (defvar calc-embedded-close-formula)
3753 (defvar calc-embedded-open-formula)
3754 (declare-function cdlatex-tab "ext:cdlatex" ())
3755 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3756 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3757 (defvar font-lock-unfontify-region-function)
3758 (declare-function iswitchb-read-buffer "iswitchb"
3759 (prompt &optional default require-match start matches-set))
3760 (defvar iswitchb-temp-buflist)
3761 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3762 (defvar org-agenda-tags-todo-honor-ignore-options)
3763 (declare-function org-agenda-skip "org-agenda" ())
3764 (declare-function
3765 org-agenda-format-item "org-agenda"
3766 (extra txt &optional category tags dotime noprefix remove-re habitp))
3767 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3768 (declare-function org-agenda-change-all-lines "org-agenda"
3769 (newhead hdmarker &optional fixface just-this))
3770 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3771 (declare-function org-agenda-maybe-redo "org-agenda" ())
3772 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3773 (beg end))
3774 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3775 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3776 "org-agenda" (&optional end))
3777 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3778 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3779 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3780 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3781 (declare-function org-indent-mode "org-indent" (&optional arg))
3782 (declare-function parse-time-string "parse-time" (string))
3783 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3784 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3785 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3786 (defvar remember-data-file)
3787 (defvar texmathp-why)
3788 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3789 (declare-function table--at-cell-p "table" (position &optional object at-column))
3791 (defvar w3m-current-url)
3792 (defvar w3m-current-title)
3794 (defvar org-latex-regexps)
3796 ;;; Autoload and prepare some org modules
3798 ;; Some table stuff that needs to be defined here, because it is used
3799 ;; by the functions setting up org-mode or checking for table context.
3801 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3802 "Detect an org-type or table-type table.")
3803 (defconst org-table-line-regexp "^[ \t]*|"
3804 "Detect an org-type table line.")
3805 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3806 "Detect an org-type table line.")
3807 (defconst org-table-hline-regexp "^[ \t]*|-"
3808 "Detect an org-type table hline.")
3809 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3810 "Detect a table-type table hline.")
3811 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3812 "Detect the first line outside a table when searching from within it.
3813 This works for both table types.")
3815 ;; Autoload the functions in org-table.el that are needed by functions here.
3817 (eval-and-compile
3818 (org-autoload "org-table"
3819 '(org-table-align org-table-begin org-table-blank-field
3820 org-table-convert org-table-convert-region org-table-copy-down
3821 org-table-copy-region org-table-create
3822 org-table-create-or-convert-from-region
3823 org-table-create-with-table.el org-table-current-dline
3824 org-table-cut-region org-table-delete-column org-table-edit-field
3825 org-table-edit-formulas org-table-end org-table-eval-formula
3826 org-table-export org-table-field-info
3827 org-table-get-stored-formulas org-table-goto-column
3828 org-table-hline-and-move org-table-import org-table-insert-column
3829 org-table-insert-hline org-table-insert-row org-table-iterate
3830 org-table-justify-field-maybe org-table-kill-row
3831 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3832 org-table-move-column org-table-move-column-left
3833 org-table-move-column-right org-table-move-row
3834 org-table-move-row-down org-table-move-row-up
3835 org-table-next-field org-table-next-row org-table-paste-rectangle
3836 org-table-previous-field org-table-recalculate
3837 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3838 org-table-toggle-coordinate-overlays
3839 org-table-toggle-formula-debugger org-table-wrap-region
3840 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3841 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3842 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3844 (defun org-at-table-p (&optional table-type)
3845 "Return t if the cursor is inside an org-type table.
3846 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3847 (if org-enable-table-editor
3848 (save-excursion
3849 (beginning-of-line 1)
3850 (looking-at (if table-type org-table-any-line-regexp
3851 org-table-line-regexp)))
3852 nil))
3853 (defsubst org-table-p () (org-at-table-p))
3855 (defun org-at-table.el-p ()
3856 "Return t if and only if we are at a table.el table."
3857 (and (org-at-table-p 'any)
3858 (save-excursion
3859 (goto-char (org-table-begin 'any))
3860 (looking-at org-table1-hline-regexp))))
3861 (defun org-table-recognize-table.el ()
3862 "If there is a table.el table nearby, recognize it and move into it."
3863 (if org-table-tab-recognizes-table.el
3864 (if (org-at-table.el-p)
3865 (progn
3866 (beginning-of-line 1)
3867 (if (looking-at org-table-dataline-regexp)
3869 (if (looking-at org-table1-hline-regexp)
3870 (progn
3871 (beginning-of-line 2)
3872 (if (looking-at org-table-any-border-regexp)
3873 (beginning-of-line -1)))))
3874 (if (re-search-forward "|" (org-table-end t) t)
3875 (progn
3876 (require 'table)
3877 (if (table--at-cell-p (point))
3879 (message "recognizing table.el table...")
3880 (table-recognize-table)
3881 (message "recognizing table.el table...done")))
3882 (error "This should not happen"))
3884 nil)
3885 nil))
3887 (defun org-at-table-hline-p ()
3888 "Return t if the cursor is inside a hline in a table."
3889 (if org-enable-table-editor
3890 (save-excursion
3891 (beginning-of-line 1)
3892 (looking-at org-table-hline-regexp))
3893 nil))
3895 (defvar org-table-clean-did-remove-column nil)
3897 (defun org-table-map-tables (function &optional quietly)
3898 "Apply FUNCTION to the start of all tables in the buffer."
3899 (save-excursion
3900 (save-restriction
3901 (widen)
3902 (goto-char (point-min))
3903 (while (re-search-forward org-table-any-line-regexp nil t)
3904 (unless quietly
3905 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3906 (beginning-of-line 1)
3907 (when (looking-at org-table-line-regexp)
3908 (save-excursion (funcall function))
3909 (or (looking-at org-table-line-regexp)
3910 (forward-char 1)))
3911 (re-search-forward org-table-any-border-regexp nil 1))))
3912 (unless quietly (message "Mapping tables: done")))
3914 ;; Declare and autoload functions from org-exp.el & Co
3916 (declare-function org-default-export-plist "org-exp")
3917 (declare-function org-infile-export-plist "org-exp")
3918 (declare-function org-get-current-options "org-exp")
3919 (eval-and-compile
3920 (org-autoload "org-exp"
3921 '(org-export org-export-visible
3922 org-insert-export-options-template
3923 org-table-clean-before-export))
3924 (org-autoload "org-ascii"
3925 '(org-export-as-ascii org-export-ascii-preprocess
3926 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3927 org-export-region-as-ascii))
3928 (org-autoload "org-latex"
3929 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3930 org-replace-region-by-latex org-export-region-as-latex
3931 org-export-as-latex org-export-as-pdf
3932 org-export-as-pdf-and-open))
3933 (org-autoload "org-html"
3934 '(org-export-as-html-and-open
3935 org-export-as-html-batch org-export-as-html-to-buffer
3936 org-replace-region-by-html org-export-region-as-html
3937 org-export-as-html))
3938 (org-autoload "org-docbook"
3939 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3940 org-replace-region-by-docbook org-export-region-as-docbook
3941 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3942 org-export-as-docbook))
3943 (org-autoload "org-icalendar"
3944 '(org-export-icalendar-this-file
3945 org-export-icalendar-all-agenda-files
3946 org-export-icalendar-combine-agenda-files))
3947 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3948 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3950 ;; Declare and autoload functions from org-agenda.el
3952 (eval-and-compile
3953 (org-autoload "org-agenda"
3954 '(org-agenda org-agenda-list org-search-view
3955 org-todo-list org-tags-view org-agenda-list-stuck-projects
3956 org-diary org-agenda-to-appt
3957 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3959 ;; Autoload org-remember
3961 (eval-and-compile
3962 (org-autoload "org-remember"
3963 '(org-remember-insinuate org-remember-annotation
3964 org-remember-apply-template org-remember org-remember-handler)))
3966 (eval-and-compile
3967 (org-autoload "org-capture"
3968 '(org-capture org-capture-insert-template-here
3969 org-capture-import-remember-templates)))
3971 ;; Autoload org-clock.el
3973 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3974 (beg end))
3975 (declare-function org-clock-update-mode-line "org-clock" ())
3976 (declare-function org-resolve-clocks "org-clock"
3977 (&optional also-non-dangling-p prompt last-valid))
3978 (defvar org-clock-start-time)
3979 (defvar org-clock-marker (make-marker)
3980 "Marker recording the last clock-in.")
3981 (defvar org-clock-hd-marker (make-marker)
3982 "Marker recording the last clock-in, but the headline position.")
3983 (defvar org-clock-heading ""
3984 "The heading of the current clock entry.")
3985 (defun org-clock-is-active ()
3986 "Return non-nil if clock is currently running.
3987 The return value is actually the clock marker."
3988 (marker-buffer org-clock-marker))
3990 (eval-and-compile
3991 (org-autoload
3992 "org-clock"
3993 '(org-clock-in org-clock-out org-clock-cancel
3994 org-clock-goto org-clock-sum org-clock-display
3995 org-clock-remove-overlays org-clock-report
3996 org-clocktable-shift org-dblock-write:clocktable
3997 org-get-clocktable org-resolve-clocks)))
3999 (defun org-clock-update-time-maybe ()
4000 "If this is a CLOCK line, update it and return t.
4001 Otherwise, return nil."
4002 (interactive)
4003 (save-excursion
4004 (beginning-of-line 1)
4005 (skip-chars-forward " \t")
4006 (when (looking-at org-clock-string)
4007 (let ((re (concat "[ \t]*" org-clock-string
4008 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
4009 "\\([ \t]*=>.*\\)?\\)?"))
4010 ts te h m s neg)
4011 (cond
4012 ((not (looking-at re))
4013 nil)
4014 ((not (match-end 2))
4015 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4016 (> org-clock-marker (point))
4017 (<= org-clock-marker (point-at-eol)))
4018 ;; The clock is running here
4019 (setq org-clock-start-time
4020 (apply 'encode-time
4021 (org-parse-time-string (match-string 1))))
4022 (org-clock-update-mode-line)))
4024 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
4025 (end-of-line 1)
4026 (setq ts (match-string 1)
4027 te (match-string 3))
4028 (setq s (- (org-float-time
4029 (apply 'encode-time (org-parse-time-string te)))
4030 (org-float-time
4031 (apply 'encode-time (org-parse-time-string ts))))
4032 neg (< s 0)
4033 s (abs s)
4034 h (floor (/ s 3600))
4035 s (- s (* 3600 h))
4036 m (floor (/ s 60))
4037 s (- s (* 60 s)))
4038 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
4039 t))))))
4041 (defun org-check-running-clock ()
4042 "Check if the current buffer contains the running clock.
4043 If yes, offer to stop it and to save the buffer with the changes."
4044 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4045 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4046 (buffer-name))))
4047 (org-clock-out)
4048 (when (y-or-n-p "Save changed buffer?")
4049 (save-buffer))))
4051 (defun org-clocktable-try-shift (dir n)
4052 "Check if this line starts a clock table, if yes, shift the time block."
4053 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4054 (org-clocktable-shift dir n)))
4056 ;; Autoload org-timer.el
4058 (eval-and-compile
4059 (org-autoload
4060 "org-timer"
4061 '(org-timer-start org-timer org-timer-item
4062 org-timer-change-times-in-region
4063 org-timer-set-timer
4064 org-timer-reset-timers
4065 org-timer-show-remaining-time)))
4067 ;; Autoload org-feed.el
4069 (eval-and-compile
4070 (org-autoload
4071 "org-feed"
4072 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
4075 ;; Autoload org-indent.el
4077 ;; Define the variable already here, to make sure we have it.
4078 (defvar org-indent-mode nil
4079 "Non-nil if Org-Indent mode is enabled.
4080 Use the command `org-indent-mode' to change this variable.")
4082 (eval-and-compile
4083 (org-autoload
4084 "org-indent"
4085 '(org-indent-mode)))
4087 ;; Autoload org-mobile.el
4089 (eval-and-compile
4090 (org-autoload
4091 "org-mobile"
4092 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
4094 ;; Autoload archiving code
4095 ;; The stuff that is needed for cycling and tags has to be defined here.
4097 (defgroup org-archive nil
4098 "Options concerning archiving in Org-mode."
4099 :tag "Org Archive"
4100 :group 'org-structure)
4102 (defcustom org-archive-location "%s_archive::"
4103 "The location where subtrees should be archived.
4105 The value of this variable is a string, consisting of two parts,
4106 separated by a double-colon. The first part is a filename and
4107 the second part is a headline.
4109 When the filename is omitted, archiving happens in the same file.
4110 %s in the filename will be replaced by the current file
4111 name (without the directory part). Archiving to a different file
4112 is useful to keep archived entries from contributing to the
4113 Org-mode Agenda.
4115 The archived entries will be filed as subtrees of the specified
4116 headline. When the headline is omitted, the subtrees are simply
4117 filed away at the end of the file, as top-level entries. Also in
4118 the heading you can use %s to represent the file name, this can be
4119 useful when using the same archive for a number of different files.
4121 Here are a few examples:
4122 \"%s_archive::\"
4123 If the current file is Projects.org, archive in file
4124 Projects.org_archive, as top-level trees. This is the default.
4126 \"::* Archived Tasks\"
4127 Archive in the current file, under the top-level headline
4128 \"* Archived Tasks\".
4130 \"~/org/archive.org::\"
4131 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4133 \"~/org/archive.org::* From %s\"
4134 Archive in file ~/org/archive.org (absolute path), under headlines
4135 \"From FILENAME\" where file name is the current file name.
4137 \"basement::** Finished Tasks\"
4138 Archive in file ./basement (relative path), as level 3 trees
4139 below the level 2 heading \"** Finished Tasks\".
4141 You may set this option on a per-file basis by adding to the buffer a
4142 line like
4144 #+ARCHIVE: basement::** Finished Tasks
4146 You may also define it locally for a subtree by setting an ARCHIVE property
4147 in the entry. If such a property is found in an entry, or anywhere up
4148 the hierarchy, it will be used."
4149 :group 'org-archive
4150 :type 'string)
4152 (defcustom org-archive-tag "ARCHIVE"
4153 "The tag that marks a subtree as archived.
4154 An archived subtree does not open during visibility cycling, and does
4155 not contribute to the agenda listings.
4156 After changing this, font-lock must be restarted in the relevant buffers to
4157 get the proper fontification."
4158 :group 'org-archive
4159 :group 'org-keywords
4160 :type 'string)
4162 (defcustom org-agenda-skip-archived-trees t
4163 "Non-nil means the agenda will skip any items located in archived trees.
4164 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4165 variable is no longer recommended, you should leave it at the value t.
4166 Instead, use the key `v' to cycle the archives-mode in the agenda."
4167 :group 'org-archive
4168 :group 'org-agenda-skip
4169 :type 'boolean)
4171 (defcustom org-columns-skip-archived-trees t
4172 "Non-nil means ignore archived trees when creating column view."
4173 :group 'org-archive
4174 :group 'org-properties
4175 :type 'boolean)
4177 (defcustom org-cycle-open-archived-trees nil
4178 "Non-nil means `org-cycle' will open archived trees.
4179 An archived tree is a tree marked with the tag ARCHIVE.
4180 When nil, archived trees will stay folded. You can still open them with
4181 normal outline commands like `show-all', but not with the cycling commands."
4182 :group 'org-archive
4183 :group 'org-cycle
4184 :type 'boolean)
4186 (defcustom org-sparse-tree-open-archived-trees nil
4187 "Non-nil means sparse tree construction shows matches in archived trees.
4188 When nil, matches in these trees are highlighted, but the trees are kept in
4189 collapsed state."
4190 :group 'org-archive
4191 :group 'org-sparse-trees
4192 :type 'boolean)
4194 (defun org-cycle-hide-archived-subtrees (state)
4195 "Re-hide all archived subtrees after a visibility state change."
4196 (when (and (not org-cycle-open-archived-trees)
4197 (not (memq state '(overview folded))))
4198 (save-excursion
4199 (let* ((globalp (memq state '(contents all)))
4200 (beg (if globalp (point-min) (point)))
4201 (end (if globalp (point-max) (org-end-of-subtree t))))
4202 (org-hide-archived-subtrees beg end)
4203 (goto-char beg)
4204 (if (looking-at (concat ".*:" org-archive-tag ":"))
4205 (message "%s" (substitute-command-keys
4206 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4208 (defun org-force-cycle-archived ()
4209 "Cycle subtree even if it is archived."
4210 (interactive)
4211 (setq this-command 'org-cycle)
4212 (let ((org-cycle-open-archived-trees t))
4213 (call-interactively 'org-cycle)))
4215 (defun org-hide-archived-subtrees (beg end)
4216 "Re-hide all archived subtrees after a visibility state change."
4217 (save-excursion
4218 (let* ((re (concat ":" org-archive-tag ":")))
4219 (goto-char beg)
4220 (while (re-search-forward re end t)
4221 (when (org-on-heading-p)
4222 (org-flag-subtree t)
4223 (org-end-of-subtree t))))))
4225 (defun org-flag-subtree (flag)
4226 (save-excursion
4227 (org-back-to-heading t)
4228 (outline-end-of-heading)
4229 (outline-flag-region (point)
4230 (progn (org-end-of-subtree t) (point))
4231 flag)))
4233 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4235 (eval-and-compile
4236 (org-autoload "org-archive"
4237 '(org-add-archive-files org-archive-subtree
4238 org-archive-to-archive-sibling org-toggle-archive-tag
4239 org-archive-subtree-default
4240 org-archive-subtree-default-with-confirmation)))
4242 ;; Autoload Column View Code
4244 (declare-function org-columns-number-to-string "org-colview")
4245 (declare-function org-columns-get-format-and-top-level "org-colview")
4246 (declare-function org-columns-compute "org-colview")
4248 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4249 '(org-columns-number-to-string org-columns-get-format-and-top-level
4250 org-columns-compute org-agenda-columns org-columns-remove-overlays
4251 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4253 ;; Autoload ID code
4255 (declare-function org-id-store-link "org-id")
4256 (declare-function org-id-locations-load "org-id")
4257 (declare-function org-id-locations-save "org-id")
4258 (defvar org-id-track-globally)
4259 (org-autoload "org-id"
4260 '(org-id-get-create org-id-new org-id-copy org-id-get
4261 org-id-get-with-outline-path-completion
4262 org-id-get-with-outline-drilling org-id-store-link
4263 org-id-goto org-id-find org-id-store-link))
4265 ;; Autoload Plotting Code
4267 (org-autoload "org-plot"
4268 '(org-plot/gnuplot))
4270 ;;; Variables for pre-computed regular expressions, all buffer local
4272 (defvar org-drawer-regexp nil
4273 "Matches first line of a hidden block.")
4274 (make-variable-buffer-local 'org-drawer-regexp)
4275 (defvar org-todo-regexp nil
4276 "Matches any of the TODO state keywords.")
4277 (make-variable-buffer-local 'org-todo-regexp)
4278 (defvar org-not-done-regexp nil
4279 "Matches any of the TODO state keywords except the last one.")
4280 (make-variable-buffer-local 'org-not-done-regexp)
4281 (defvar org-not-done-heading-regexp nil
4282 "Matches a TODO headline that is not done.")
4283 (make-variable-buffer-local 'org-not-done-regexp)
4284 (defvar org-todo-line-regexp nil
4285 "Matches a headline and puts TODO state into group 2 if present.")
4286 (make-variable-buffer-local 'org-todo-line-regexp)
4287 (defvar org-complex-heading-regexp nil
4288 "Matches a headline and puts everything into groups:
4289 group 1: the stars
4290 group 2: The todo keyword, maybe
4291 group 3: Priority cookie
4292 group 4: True headline
4293 group 5: Tags")
4294 (make-variable-buffer-local 'org-complex-heading-regexp)
4295 (defvar org-complex-heading-regexp-format nil
4296 "Printf format to make regexp to match an exact headline.
4297 This regexp will match the headline of any node which has the
4298 exact headline text that is put into the format, but may have any
4299 TODO state, priority and tags.")
4300 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4301 (defvar org-todo-line-tags-regexp nil
4302 "Matches a headline and puts TODO state into group 2 if present.
4303 Also put tags into group 4 if tags are present.")
4304 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4305 (defvar org-ds-keyword-length 12
4306 "Maximum length of the Deadline and SCHEDULED keywords.")
4307 (make-variable-buffer-local 'org-ds-keyword-length)
4308 (defvar org-deadline-regexp nil
4309 "Matches the DEADLINE keyword.")
4310 (make-variable-buffer-local 'org-deadline-regexp)
4311 (defvar org-deadline-time-regexp nil
4312 "Matches the DEADLINE keyword together with a time stamp.")
4313 (make-variable-buffer-local 'org-deadline-time-regexp)
4314 (defvar org-deadline-line-regexp nil
4315 "Matches the DEADLINE keyword and the rest of the line.")
4316 (make-variable-buffer-local 'org-deadline-line-regexp)
4317 (defvar org-scheduled-regexp nil
4318 "Matches the SCHEDULED keyword.")
4319 (make-variable-buffer-local 'org-scheduled-regexp)
4320 (defvar org-scheduled-time-regexp nil
4321 "Matches the SCHEDULED keyword together with a time stamp.")
4322 (make-variable-buffer-local 'org-scheduled-time-regexp)
4323 (defvar org-closed-time-regexp nil
4324 "Matches the CLOSED keyword together with a time stamp.")
4325 (make-variable-buffer-local 'org-closed-time-regexp)
4327 (defvar org-keyword-time-regexp nil
4328 "Matches any of the 4 keywords, together with the time stamp.")
4329 (make-variable-buffer-local 'org-keyword-time-regexp)
4330 (defvar org-keyword-time-not-clock-regexp nil
4331 "Matches any of the 3 keywords, together with the time stamp.")
4332 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4333 (defvar org-maybe-keyword-time-regexp nil
4334 "Matches a timestamp, possibly preceded by a keyword.")
4335 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4336 (defvar org-planning-or-clock-line-re nil
4337 "Matches a line with planning or clock info.")
4338 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4339 (defvar org-all-time-keywords nil
4340 "List of time keywords.")
4341 (make-variable-buffer-local 'org-all-time-keywords)
4343 (defconst org-plain-time-of-day-regexp
4344 (concat
4345 "\\(\\<[012]?[0-9]"
4346 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4347 "\\(--?"
4348 "\\(\\<[012]?[0-9]"
4349 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4350 "\\)?")
4351 "Regular expression to match a plain time or time range.
4352 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4353 groups carry important information:
4354 0 the full match
4355 1 the first time, range or not
4356 8 the second time, if it is a range.")
4358 (defconst org-plain-time-extension-regexp
4359 (concat
4360 "\\(\\<[012]?[0-9]"
4361 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4362 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4363 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4364 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4365 groups carry important information:
4366 0 the full match
4367 7 hours of duration
4368 9 minutes of duration")
4370 (defconst org-stamp-time-of-day-regexp
4371 (concat
4372 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4373 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4374 "\\(--?"
4375 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4376 "Regular expression to match a timestamp time or time range.
4377 After a match, the following groups carry important information:
4378 0 the full match
4379 1 date plus weekday, for back referencing to make sure both times are on the same day
4380 2 the first time, range or not
4381 4 the second time, if it is a range.")
4383 (defconst org-startup-options
4384 '(("fold" org-startup-folded t)
4385 ("overview" org-startup-folded t)
4386 ("nofold" org-startup-folded nil)
4387 ("showall" org-startup-folded nil)
4388 ("showeverything" org-startup-folded showeverything)
4389 ("content" org-startup-folded content)
4390 ("indent" org-startup-indented t)
4391 ("noindent" org-startup-indented nil)
4392 ("hidestars" org-hide-leading-stars t)
4393 ("showstars" org-hide-leading-stars nil)
4394 ("odd" org-odd-levels-only t)
4395 ("oddeven" org-odd-levels-only nil)
4396 ("align" org-startup-align-all-tables t)
4397 ("noalign" org-startup-align-all-tables nil)
4398 ("inlineimages" org-startup-with-inline-images t)
4399 ("noinlineimages" org-startup-with-inline-images nil)
4400 ("customtime" org-display-custom-times t)
4401 ("logdone" org-log-done time)
4402 ("lognotedone" org-log-done note)
4403 ("nologdone" org-log-done nil)
4404 ("lognoteclock-out" org-log-note-clock-out t)
4405 ("nolognoteclock-out" org-log-note-clock-out nil)
4406 ("logrepeat" org-log-repeat state)
4407 ("lognoterepeat" org-log-repeat note)
4408 ("nologrepeat" org-log-repeat nil)
4409 ("logreschedule" org-log-reschedule time)
4410 ("lognotereschedule" org-log-reschedule note)
4411 ("nologreschedule" org-log-reschedule nil)
4412 ("logredeadline" org-log-redeadline time)
4413 ("lognoteredeadline" org-log-redeadline note)
4414 ("nologredeadline" org-log-redeadline nil)
4415 ("logrefile" org-log-refile time)
4416 ("lognoterefile" org-log-refile note)
4417 ("nologrefile" org-log-refile nil)
4418 ("fninline" org-footnote-define-inline t)
4419 ("nofninline" org-footnote-define-inline nil)
4420 ("fnlocal" org-footnote-section nil)
4421 ("fnauto" org-footnote-auto-label t)
4422 ("fnprompt" org-footnote-auto-label nil)
4423 ("fnconfirm" org-footnote-auto-label confirm)
4424 ("fnplain" org-footnote-auto-label plain)
4425 ("fnadjust" org-footnote-auto-adjust t)
4426 ("nofnadjust" org-footnote-auto-adjust nil)
4427 ("constcgs" constants-unit-system cgs)
4428 ("constSI" constants-unit-system SI)
4429 ("noptag" org-tag-persistent-alist nil)
4430 ("hideblocks" org-hide-block-startup t)
4431 ("nohideblocks" org-hide-block-startup nil)
4432 ("beamer" org-startup-with-beamer-mode t)
4433 ("entitiespretty" org-pretty-entities t)
4434 ("entitiesplain" org-pretty-entities nil))
4435 "Variable associated with STARTUP options for org-mode.
4436 Each element is a list of three items: The startup options as written
4437 in the #+STARTUP line, the corresponding variable, and the value to
4438 set this variable to if the option is found. An optional forth element PUSH
4439 means to push this value onto the list in the variable.")
4441 (defun org-update-property-plist (key val props)
4442 "Update PROPS with KEY and VAL."
4443 (if (string= "+" (substring key (- (length key) 1)))
4444 (let* ((key (substring key 0 (- (length key) 1)))
4445 (previous (cdr (assoc key props))))
4446 (cons (cons key (concat previous " " val))
4447 (org-remove-if (lambda (p) (string= (car p) key)) props)))
4448 (cons (cons key val) props)))
4450 (defconst org-block-regexp
4451 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4452 "Regular expression for hiding blocks.")
4453 (defconst org-heading-keyword-regexp-format
4454 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4455 "Printf format for a regexp matching an headline with some keyword.
4456 This regexp will match the headline of any node which has the
4457 exact keyword that is put into the format. The keyword isn't in
4458 any group by default, but the stars and the body are.")
4459 (defconst org-heading-keyword-maybe-regexp-format
4460 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4461 "Printf format for a regexp matching an headline, possibly with some keyword.
4462 This regexp can match any headline with the specified keyword, or
4463 without a keyword. The keyword isn't in any group by default,
4464 but the stars and the body are.")
4466 (defun org-set-regexps-and-options ()
4467 "Precompute regular expressions for current buffer."
4468 (when (eq major-mode 'org-mode)
4469 (org-set-local 'org-todo-kwd-alist nil)
4470 (org-set-local 'org-todo-key-alist nil)
4471 (org-set-local 'org-todo-key-trigger nil)
4472 (org-set-local 'org-todo-keywords-1 nil)
4473 (org-set-local 'org-done-keywords nil)
4474 (org-set-local 'org-todo-heads nil)
4475 (org-set-local 'org-todo-sets nil)
4476 (org-set-local 'org-todo-log-states nil)
4477 (org-set-local 'org-file-properties nil)
4478 (org-set-local 'org-file-tags nil)
4479 (let ((re (org-make-options-regexp
4480 '("CATEGORY" "TODO" "COLUMNS"
4481 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4482 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4483 "OPTIONS")
4484 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4485 (splitre "[ \t]+")
4486 (scripts org-use-sub-superscripts)
4487 kwds kws0 kwsa key log value cat arch tags const links hw dws
4488 tail sep kws1 prio props ftags drawers beamer-p
4489 ext-setup-or-nil setup-contents (start 0))
4490 (save-excursion
4491 (save-restriction
4492 (widen)
4493 (goto-char (point-min))
4494 (while (or (and ext-setup-or-nil
4495 (string-match re ext-setup-or-nil start)
4496 (setq start (match-end 0)))
4497 (and (setq ext-setup-or-nil nil start 0)
4498 (re-search-forward re nil t)))
4499 (setq key (upcase (match-string 1 ext-setup-or-nil))
4500 value (org-match-string-no-properties 2 ext-setup-or-nil))
4501 (if (stringp value) (setq value (org-trim value)))
4502 (cond
4503 ((equal key "CATEGORY")
4504 (setq cat value))
4505 ((member key '("SEQ_TODO" "TODO"))
4506 (push (cons 'sequence (org-split-string value splitre)) kwds))
4507 ((equal key "TYP_TODO")
4508 (push (cons 'type (org-split-string value splitre)) kwds))
4509 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4510 ;; general TODO-like setup
4511 (push (cons (intern (downcase (match-string 1 key)))
4512 (org-split-string value splitre)) kwds))
4513 ((equal key "TAGS")
4514 (setq tags (append tags (if tags '("\\n") nil)
4515 (org-split-string value splitre))))
4516 ((equal key "COLUMNS")
4517 (org-set-local 'org-columns-default-format value))
4518 ((equal key "LINK")
4519 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4520 (push (cons (match-string 1 value)
4521 (org-trim (match-string 2 value)))
4522 links)))
4523 ((equal key "PRIORITIES")
4524 (setq prio (org-split-string value " +")))
4525 ((equal key "PROPERTY")
4526 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4527 (setq props (org-update-property-plist (match-string 1 value)
4528 (match-string 2 value)
4529 props))))
4530 ((equal key "FILETAGS")
4531 (when (string-match "\\S-" value)
4532 (setq ftags
4533 (append
4534 ftags
4535 (apply 'append
4536 (mapcar (lambda (x) (org-split-string x ":"))
4537 (org-split-string value)))))))
4538 ((equal key "DRAWERS")
4539 (setq drawers (org-split-string value splitre)))
4540 ((equal key "CONSTANTS")
4541 (setq const (append const (org-split-string value splitre))))
4542 ((equal key "STARTUP")
4543 (let ((opts (org-split-string value splitre))
4544 l var val)
4545 (while (setq l (pop opts))
4546 (when (setq l (assoc l org-startup-options))
4547 (setq var (nth 1 l) val (nth 2 l))
4548 (if (not (nth 3 l))
4549 (set (make-local-variable var) val)
4550 (if (not (listp (symbol-value var)))
4551 (set (make-local-variable var) nil))
4552 (set (make-local-variable var) (symbol-value var))
4553 (add-to-list var val))))))
4554 ((equal key "ARCHIVE")
4555 (setq arch value)
4556 (remove-text-properties 0 (length arch)
4557 '(face t fontified t) arch))
4558 ((equal key "LATEX_CLASS")
4559 (setq beamer-p (equal value "beamer")))
4560 ((equal key "OPTIONS")
4561 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4562 (setq scripts (read (match-string 2 value)))))
4563 ((equal key "SETUPFILE")
4564 (setq setup-contents (org-file-contents
4565 (expand-file-name
4566 (org-remove-double-quotes value))
4567 'noerror))
4568 (if (not ext-setup-or-nil)
4569 (setq ext-setup-or-nil setup-contents start 0)
4570 (setq ext-setup-or-nil
4571 (concat (substring ext-setup-or-nil 0 start)
4572 "\n" setup-contents "\n"
4573 (substring ext-setup-or-nil start)))))))
4574 ;; search for property blocks
4575 (goto-char (point-min))
4576 (while (re-search-forward org-block-regexp nil t)
4577 (when (equal "PROPERTY" (upcase (match-string 1)))
4578 (setq value (replace-regexp-in-string
4579 "[\n\r]" " " (match-string 4)))
4580 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4581 (setq props (org-update-property-plist (match-string 1 value)
4582 (match-string 2 value)
4583 props)))))))
4584 (org-set-local 'org-use-sub-superscripts scripts)
4585 (when cat
4586 (org-set-local 'org-category (intern cat))
4587 (push (cons "CATEGORY" cat) props))
4588 (when prio
4589 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4590 (setq prio (mapcar 'string-to-char prio))
4591 (org-set-local 'org-highest-priority (nth 0 prio))
4592 (org-set-local 'org-lowest-priority (nth 1 prio))
4593 (org-set-local 'org-default-priority (nth 2 prio)))
4594 (and props (org-set-local 'org-file-properties (nreverse props)))
4595 (and ftags (org-set-local 'org-file-tags
4596 (mapcar 'org-add-prop-inherited ftags)))
4597 (and drawers (org-set-local 'org-drawers drawers))
4598 (and arch (org-set-local 'org-archive-location arch))
4599 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4600 ;; Process the TODO keywords
4601 (unless kwds
4602 ;; Use the global values as if they had been given locally.
4603 (setq kwds (default-value 'org-todo-keywords))
4604 (if (stringp (car kwds))
4605 (setq kwds (list (cons org-todo-interpretation
4606 (default-value 'org-todo-keywords)))))
4607 (setq kwds (reverse kwds)))
4608 (setq kwds (nreverse kwds))
4609 (let (inter kws kw)
4610 (while (setq kws (pop kwds))
4611 (let ((kws (or
4612 (run-hook-with-args-until-success
4613 'org-todo-setup-filter-hook kws)
4614 kws)))
4615 (setq inter (pop kws) sep (member "|" kws)
4616 kws0 (delete "|" (copy-sequence kws))
4617 kwsa nil
4618 kws1 (mapcar
4619 (lambda (x)
4620 ;; 1 2
4621 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4622 (progn
4623 (setq kw (match-string 1 x)
4624 key (and (match-end 2) (match-string 2 x))
4625 log (org-extract-log-state-settings x))
4626 (push (cons kw (and key (string-to-char key))) kwsa)
4627 (and log (push log org-todo-log-states))
4629 (error "Invalid TODO keyword %s" x)))
4630 kws0)
4631 kwsa (if kwsa (append '((:startgroup))
4632 (nreverse kwsa)
4633 '((:endgroup))))
4634 hw (car kws1)
4635 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4636 tail (list inter hw (car dws) (org-last dws))))
4637 (add-to-list 'org-todo-heads hw 'append)
4638 (push kws1 org-todo-sets)
4639 (setq org-done-keywords (append org-done-keywords dws nil))
4640 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4641 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4642 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4643 (setq org-todo-sets (nreverse org-todo-sets)
4644 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4645 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4646 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4647 ;; Process the constants
4648 (when const
4649 (let (e cst)
4650 (while (setq e (pop const))
4651 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4652 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4653 (setq org-table-formula-constants-local cst)))
4655 ;; Process the tags.
4656 (when tags
4657 (let (e tgs)
4658 (while (setq e (pop tags))
4659 (cond
4660 ((equal e "{") (push '(:startgroup) tgs))
4661 ((equal e "}") (push '(:endgroup) tgs))
4662 ((equal e "\\n") (push '(:newline) tgs))
4663 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4664 (push (cons (match-string 1 e)
4665 (string-to-char (match-string 2 e)))
4666 tgs))
4667 (t (push (list e) tgs))))
4668 (org-set-local 'org-tag-alist nil)
4669 (while (setq e (pop tgs))
4670 (or (and (stringp (car e))
4671 (assoc (car e) org-tag-alist))
4672 (push e org-tag-alist)))))
4674 ;; Compute the regular expressions and other local variables.
4675 ;; Using `org-outline-regexp-bol' would complicate them much,
4676 ;; because of the fixed white space at the end of that string.
4677 (if (not org-done-keywords)
4678 (setq org-done-keywords (and org-todo-keywords-1
4679 (list (org-last org-todo-keywords-1)))))
4680 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4681 (length org-scheduled-string)
4682 (length org-clock-string)
4683 (length org-closed-string)))
4684 org-drawer-regexp
4685 (concat "^[ \t]*:\\("
4686 (mapconcat 'regexp-quote org-drawers "\\|")
4687 "\\):[ \t]*$")
4688 org-not-done-keywords
4689 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4690 org-todo-regexp
4691 (concat "\\("
4692 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4693 "\\)")
4694 org-not-done-regexp
4695 (concat "\\("
4696 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4697 "\\)")
4698 org-not-done-heading-regexp
4699 (format org-heading-keyword-regexp-format org-not-done-regexp)
4700 org-todo-line-regexp
4701 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4702 org-complex-heading-regexp
4703 (concat "^\\(\\*+\\)"
4704 "\\(?: +" org-todo-regexp "\\)?"
4705 "\\(?: +\\(\\[#.\\]\\)\\)?"
4706 "\\(?: +\\(.*?\\)\\)?"
4707 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4708 "[ \t]*$")
4709 org-complex-heading-regexp-format
4710 (concat "^\\(\\*+\\)"
4711 "\\(?: +" org-todo-regexp "\\)?"
4712 "\\(?: +\\(\\[#.\\]\\)\\)?"
4713 "\\(?: +"
4714 ;; Stats cookies can be sticked to body.
4715 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4716 "\\(%s\\)"
4717 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4718 "\\)"
4719 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4720 "[ \t]*$")
4721 org-todo-line-tags-regexp
4722 (concat "^\\(\\*+\\)"
4723 "\\(?: +" org-todo-regexp "\\)?"
4724 "\\(?: +\\(.*?\\)\\)?"
4725 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4726 "[ \t]*$")
4727 org-deadline-regexp (concat "\\<" org-deadline-string)
4728 org-deadline-time-regexp
4729 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4730 org-deadline-line-regexp
4731 (concat "\\<\\(" org-deadline-string "\\).*")
4732 org-scheduled-regexp
4733 (concat "\\<" org-scheduled-string)
4734 org-scheduled-time-regexp
4735 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4736 org-closed-time-regexp
4737 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4738 org-keyword-time-regexp
4739 (concat "\\<\\(" org-scheduled-string
4740 "\\|" org-deadline-string
4741 "\\|" org-closed-string
4742 "\\|" org-clock-string "\\)"
4743 " *[[<]\\([^]>]+\\)[]>]")
4744 org-keyword-time-not-clock-regexp
4745 (concat "\\<\\(" org-scheduled-string
4746 "\\|" org-deadline-string
4747 "\\|" org-closed-string
4748 "\\)"
4749 " *[[<]\\([^]>]+\\)[]>]")
4750 org-maybe-keyword-time-regexp
4751 (concat "\\(\\<\\(" org-scheduled-string
4752 "\\|" org-deadline-string
4753 "\\|" org-closed-string
4754 "\\|" org-clock-string "\\)\\)?"
4755 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4756 org-planning-or-clock-line-re
4757 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4758 "\\|" org-deadline-string
4759 "\\|" org-closed-string "\\|" org-clock-string
4760 "\\)\\>\\)")
4761 org-all-time-keywords
4762 (mapcar (lambda (w) (substring w 0 -1))
4763 (list org-scheduled-string org-deadline-string
4764 org-clock-string org-closed-string))
4766 (org-compute-latex-and-specials-regexp)
4767 (org-set-font-lock-defaults))))
4769 (defun org-file-contents (file &optional noerror)
4770 "Return the contents of FILE, as a string."
4771 (if (or (not file)
4772 (not (file-readable-p file)))
4773 (if noerror
4774 (progn
4775 (message "Cannot read file \"%s\"" file)
4776 (ding) (sit-for 2)
4778 (error "Cannot read file \"%s\"" file))
4779 (with-temp-buffer
4780 (insert-file-contents file)
4781 (buffer-string))))
4783 (defun org-extract-log-state-settings (x)
4784 "Extract the log state setting from a TODO keyword string.
4785 This will extract info from a string like \"WAIT(w@/!)\"."
4786 (let (kw key log1 log2)
4787 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4788 (setq kw (match-string 1 x)
4789 key (and (match-end 2) (match-string 2 x))
4790 log1 (and (match-end 3) (match-string 3 x))
4791 log2 (and (match-end 4) (match-string 4 x)))
4792 (and (or log1 log2)
4793 (list kw
4794 (and log1 (if (equal log1 "!") 'time 'note))
4795 (and log2 (if (equal log2 "!") 'time 'note)))))))
4797 (defun org-remove-keyword-keys (list)
4798 "Remove a pair of parenthesis at the end of each string in LIST."
4799 (mapcar (lambda (x)
4800 (if (string-match "(.*)$" x)
4801 (substring x 0 (match-beginning 0))
4803 list))
4805 (defun org-assign-fast-keys (alist)
4806 "Assign fast keys to a keyword-key alist.
4807 Respect keys that are already there."
4808 (let (new e (alt ?0))
4809 (while (setq e (pop alist))
4810 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4811 (cdr e)) ;; Key already assigned.
4812 (push e new)
4813 (let ((clist (string-to-list (downcase (car e))))
4814 (used (append new alist)))
4815 (when (= (car clist) ?@)
4816 (pop clist))
4817 (while (and clist (rassoc (car clist) used))
4818 (pop clist))
4819 (unless clist
4820 (while (rassoc alt used)
4821 (incf alt)))
4822 (push (cons (car e) (or (car clist) alt)) new))))
4823 (nreverse new)))
4825 ;;; Some variables used in various places
4827 (defvar org-window-configuration nil
4828 "Used in various places to store a window configuration.")
4829 (defvar org-selected-window nil
4830 "Used in various places to store a window configuration.")
4831 (defvar org-finish-function nil
4832 "Function to be called when `C-c C-c' is used.
4833 This is for getting out of special buffers like remember.")
4836 ;; FIXME: Occasionally check by commenting these, to make sure
4837 ;; no other functions uses these, forgetting to let-bind them.
4838 (defvar entry)
4839 (defvar last-state)
4840 (defvar date)
4842 ;; Defined somewhere in this file, but used before definition.
4843 (defvar org-entities) ;; defined in org-entities.el
4844 (defvar org-struct-menu)
4845 (defvar org-org-menu)
4846 (defvar org-tbl-menu)
4848 ;;;; Define the Org-mode
4850 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4851 (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"))
4854 ;; We use a before-change function to check if a table might need
4855 ;; an update.
4856 (defvar org-table-may-need-update t
4857 "Indicates that a table might need an update.
4858 This variable is set by `org-before-change-function'.
4859 `org-table-align' sets it back to nil.")
4860 (defun org-before-change-function (beg end)
4861 "Every change indicates that a table might need an update."
4862 (setq org-table-may-need-update t))
4863 (defvar org-mode-map)
4864 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4865 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4866 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4867 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4868 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4869 (defvar org-table-buffer-is-an nil)
4871 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
4872 ;; some places -- e.g. see the macro org-with-limited-levels.
4874 ;; In Org buffers, the value of `outline-regexp' is that of
4875 ;; `org-outline-regexp'. The only function still directly relying on
4876 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
4877 ;; job when `orgstruct-mode' is active.
4878 (defvar org-outline-regexp "\\*+ "
4879 "Regexp to match Org headlines.")
4880 (defconst org-outline-regexp-bol "^\\*+ "
4881 "Regexp to match Org headlines.
4882 This is similar to `org-outline-regexp' but additionally makes
4883 sure that we are at the beginning of the line.")
4885 (defconst org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4886 "Matches an headline, putting stars and text into groups.
4887 Stars are put in group 1 and the trimmed body in group 2.")
4889 ;;;###autoload
4890 (define-derived-mode org-mode outline-mode "Org"
4891 "Outline-based notes management and organizer, alias
4892 \"Carsten's outline-mode for keeping track of everything.\"
4894 Org-mode develops organizational tasks around a NOTES file which
4895 contains information about projects as plain text. Org-mode is
4896 implemented on top of outline-mode, which is ideal to keep the content
4897 of large files well structured. It supports ToDo items, deadlines and
4898 time stamps, which magically appear in the diary listing of the Emacs
4899 calendar. Tables are easily created with a built-in table editor.
4900 Plain text URL-like links connect to websites, emails (VM), Usenet
4901 messages (Gnus), BBDB entries, and any files related to the project.
4902 For printing and sharing of notes, an Org-mode file (or a part of it)
4903 can be exported as a structured ASCII or HTML file.
4905 The following commands are available:
4907 \\{org-mode-map}"
4909 ;; Get rid of Outline menus, they are not needed
4910 ;; Need to do this here because define-derived-mode sets up
4911 ;; the keymap so late. Still, it is a waste to call this each time
4912 ;; we switch another buffer into org-mode.
4913 (if (featurep 'xemacs)
4914 (when (boundp 'outline-mode-menu-heading)
4915 ;; Assume this is Greg's port, it uses easymenu
4916 (easy-menu-remove outline-mode-menu-heading)
4917 (easy-menu-remove outline-mode-menu-show)
4918 (easy-menu-remove outline-mode-menu-hide))
4919 (define-key org-mode-map [menu-bar headings] 'undefined)
4920 (define-key org-mode-map [menu-bar hide] 'undefined)
4921 (define-key org-mode-map [menu-bar show] 'undefined))
4923 (org-load-modules-maybe)
4924 (easy-menu-add org-org-menu)
4925 (easy-menu-add org-tbl-menu)
4926 (org-install-agenda-files-menu)
4927 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4928 (add-to-invisibility-spec '(org-cwidth))
4929 (add-to-invisibility-spec '(org-hide-block . t))
4930 (when (featurep 'xemacs)
4931 (org-set-local 'line-move-ignore-invisible t))
4932 (org-set-local 'outline-regexp org-outline-regexp)
4933 (org-set-local 'outline-level 'org-outline-level)
4934 (setq bidi-paragraph-direction 'left-to-right)
4935 (when (and org-ellipsis
4936 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4937 (fboundp 'make-glyph-code))
4938 (unless org-display-table
4939 (setq org-display-table (make-display-table)))
4940 (set-display-table-slot
4941 org-display-table 4
4942 (vconcat (mapcar
4943 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4944 org-ellipsis)))
4945 (if (stringp org-ellipsis) org-ellipsis "..."))))
4946 (setq buffer-display-table org-display-table))
4947 (org-set-regexps-and-options)
4948 (when (and org-tag-faces (not org-tags-special-faces-re))
4949 ;; tag faces set outside customize.... force initialization.
4950 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4951 ;; Calc embedded
4952 (org-set-local 'calc-embedded-open-mode "# ")
4953 (modify-syntax-entry ?@ "w")
4954 (if org-startup-truncated (setq truncate-lines t))
4955 (org-set-local 'font-lock-unfontify-region-function
4956 'org-unfontify-region)
4957 ;; Activate before-change-function
4958 (org-set-local 'org-table-may-need-update t)
4959 (org-add-hook 'before-change-functions 'org-before-change-function nil
4960 'local)
4961 ;; Check for running clock before killing a buffer
4962 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4963 ;; Paragraphs and auto-filling
4964 (org-set-autofill-regexps)
4965 (setq indent-line-function 'org-indent-line-function)
4966 (org-update-radio-target-regexp)
4967 ;; Beginning/end of defun
4968 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
4969 (org-set-local 'end-of-defun-function 'org-end-of-defun)
4970 ;; Next error for sparse trees
4971 (org-set-local 'next-error-function 'org-occur-next-match)
4972 ;; Make sure dependence stuff works reliably, even for users who set it
4973 ;; too late :-(
4974 (if org-enforce-todo-dependencies
4975 (add-hook 'org-blocker-hook
4976 'org-block-todo-from-children-or-siblings-or-parent)
4977 (remove-hook 'org-blocker-hook
4978 'org-block-todo-from-children-or-siblings-or-parent))
4979 (if org-enforce-todo-checkbox-dependencies
4980 (add-hook 'org-blocker-hook
4981 'org-block-todo-from-checkboxes)
4982 (remove-hook 'org-blocker-hook
4983 'org-block-todo-from-checkboxes))
4985 ;; Comment characters
4986 (org-set-local 'comment-start "#")
4987 (org-set-local 'comment-padding " ")
4989 ;; Align options lines
4990 (org-set-local
4991 'align-mode-rules-list
4992 '((org-in-buffer-settings
4993 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4994 (modes . '(org-mode)))))
4996 ;; Imenu
4997 (org-set-local 'imenu-create-index-function
4998 'org-imenu-get-tree)
5000 ;; Make isearch reveal context
5001 (if (or (featurep 'xemacs)
5002 (not (boundp 'outline-isearch-open-invisible-function)))
5003 ;; Emacs 21 and XEmacs make use of the hook
5004 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5005 ;; Emacs 22 deals with this through a special variable
5006 (org-set-local 'outline-isearch-open-invisible-function
5007 (lambda (&rest ignore) (org-show-context 'isearch))))
5009 ;; Turn on org-beamer-mode?
5010 (and org-startup-with-beamer-mode (org-beamer-mode 1))
5012 ;; Setup the pcomplete hooks
5013 (set (make-local-variable 'pcomplete-command-completion-function)
5014 'org-pcomplete-initial)
5015 (set (make-local-variable 'pcomplete-command-name-function)
5016 'org-command-at-point)
5017 (set (make-local-variable 'pcomplete-default-completion-function)
5018 'ignore)
5019 (set (make-local-variable 'pcomplete-parse-arguments-function)
5020 'org-parse-arguments)
5021 (set (make-local-variable 'pcomplete-termination-string) "")
5022 (set (make-local-variable 'face-remapping-alist)
5023 '((default org-default)))
5025 ;; If empty file that did not turn on org-mode automatically, make it to.
5026 (if (and org-insert-mode-line-in-empty-file
5027 (org-called-interactively-p 'any)
5028 (= (point-min) (point-max)))
5029 (insert "# -*- mode: org -*-\n\n"))
5030 (unless org-inhibit-startup
5031 (when org-startup-align-all-tables
5032 (let ((bmp (buffer-modified-p)))
5033 (org-table-map-tables 'org-table-align 'quietly)
5034 (set-buffer-modified-p bmp)))
5035 (when org-startup-with-inline-images
5036 (org-display-inline-images))
5037 (when org-startup-indented
5038 (require 'org-indent)
5039 (org-indent-mode 1))
5040 (unless org-inhibit-startup-visibility-stuff
5041 (org-set-startup-visibility))))
5043 (when (fboundp 'abbrev-table-put)
5044 (abbrev-table-put org-mode-abbrev-table
5045 :parents (list text-mode-abbrev-table)))
5047 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5049 (defun org-current-time ()
5050 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5051 (if (> (car org-time-stamp-rounding-minutes) 1)
5052 (let ((r (car org-time-stamp-rounding-minutes))
5053 (time (decode-time)))
5054 (apply 'encode-time
5055 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5056 (nthcdr 2 time))))
5057 (current-time)))
5059 (defun org-today ()
5060 "Return today date, considering `org-extend-today-until'."
5061 (time-to-days
5062 (time-subtract (current-time)
5063 (list 0 (* 3600 org-extend-today-until) 0))))
5065 ;;;; Font-Lock stuff, including the activators
5067 (defvar org-mouse-map (make-sparse-keymap))
5068 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5069 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5070 (when org-mouse-1-follows-link
5071 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5072 (when org-tab-follows-link
5073 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5074 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5076 (require 'font-lock)
5078 (defconst org-non-link-chars "]\t\n\r<>")
5079 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5080 "shell" "elisp" "doi" "message"))
5081 (defvar org-link-types-re nil
5082 "Matches a link that has a url-like prefix like \"http:\"")
5083 (defvar org-link-re-with-space nil
5084 "Matches a link with spaces, optional angular brackets around it.")
5085 (defvar org-link-re-with-space2 nil
5086 "Matches a link with spaces, optional angular brackets around it.")
5087 (defvar org-link-re-with-space3 nil
5088 "Matches a link with spaces, only for internal part in bracket links.")
5089 (defvar org-angle-link-re nil
5090 "Matches link with angular brackets, spaces are allowed.")
5091 (defvar org-plain-link-re nil
5092 "Matches plain link, without spaces.")
5093 (defvar org-bracket-link-regexp nil
5094 "Matches a link in double brackets.")
5095 (defvar org-bracket-link-analytic-regexp nil
5096 "Regular expression used to analyze links.
5097 Here is what the match groups contain after a match:
5098 1: http:
5099 2: http
5100 3: path
5101 4: [desc]
5102 5: desc")
5103 (defvar org-bracket-link-analytic-regexp++ nil
5104 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5105 (defvar org-any-link-re nil
5106 "Regular expression matching any link.")
5108 (defcustom org-match-sexp-depth 3
5109 "Number of stacked braces for sub/superscript matching.
5110 This has to be set before loading org.el to be effective."
5111 :group 'org-export-translation ; ??????????????????????????/
5112 :type 'integer)
5114 (defun org-create-multibrace-regexp (left right n)
5115 "Create a regular expression which will match a balanced sexp.
5116 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5117 as single character strings.
5118 The regexp returned will match the entire expression including the
5119 delimiters. It will also define a single group which contains the
5120 match except for the outermost delimiters. The maximum depth of
5121 stacked delimiters is N. Escaping delimiters is not possible."
5122 (let* ((nothing (concat "[^" left right "]*?"))
5123 (or "\\|")
5124 (re nothing)
5125 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5126 (while (> n 1)
5127 (setq n (1- n)
5128 re (concat re or next)
5129 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5130 (concat left "\\(" re "\\)" right)))
5132 (defvar org-match-substring-regexp
5133 (concat
5134 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5135 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5136 "\\|"
5137 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5138 "\\|"
5139 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5140 "The regular expression matching a sub- or superscript.")
5142 (defvar org-match-substring-with-braces-regexp
5143 (concat
5144 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5145 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5146 "\\)")
5147 "The regular expression matching a sub- or superscript, forcing braces.")
5149 (defun org-make-link-regexps ()
5150 "Update the link regular expressions.
5151 This should be called after the variable `org-link-types' has changed."
5152 (setq org-link-types-re
5153 (concat
5154 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5155 org-link-re-with-space
5156 (concat
5157 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5158 "\\([^" org-non-link-chars " ]"
5159 "[^" org-non-link-chars "]*"
5160 "[^" org-non-link-chars " ]\\)>?")
5161 org-link-re-with-space2
5162 (concat
5163 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5164 "\\([^" org-non-link-chars " ]"
5165 "[^\t\n\r]*"
5166 "[^" org-non-link-chars " ]\\)>?")
5167 org-link-re-with-space3
5168 (concat
5169 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5170 "\\([^" org-non-link-chars " ]"
5171 "[^\t\n\r]*\\)")
5172 org-angle-link-re
5173 (concat
5174 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5175 "\\([^" org-non-link-chars " ]"
5176 "[^" org-non-link-chars "]*"
5177 "\\)>")
5178 org-plain-link-re
5179 (concat
5180 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5181 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5182 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5183 org-bracket-link-regexp
5184 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5185 org-bracket-link-analytic-regexp
5186 (concat
5187 "\\[\\["
5188 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5189 "\\([^]]+\\)"
5190 "\\]"
5191 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5192 "\\]")
5193 org-bracket-link-analytic-regexp++
5194 (concat
5195 "\\[\\["
5196 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5197 "\\([^]]+\\)"
5198 "\\]"
5199 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5200 "\\]")
5201 org-any-link-re
5202 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5203 org-angle-link-re "\\)\\|\\("
5204 org-plain-link-re "\\)")))
5206 (org-make-link-regexps)
5208 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5209 "Regular expression for fast time stamp matching.")
5210 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5211 "Regular expression for fast time stamp matching.")
5212 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5213 "Regular expression matching time strings for analysis.
5214 This one does not require the space after the date, so it can be used
5215 on a string that terminates immediately after the date.")
5216 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5217 "Regular expression matching time strings for analysis.")
5218 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5219 "Regular expression matching time stamps, with groups.")
5220 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5221 "Regular expression matching time stamps (also [..]), with groups.")
5222 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5223 "Regular expression matching a time stamp range.")
5224 (defconst org-tr-regexp-both
5225 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5226 "Regular expression matching a time stamp range.")
5227 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5228 org-ts-regexp "\\)?")
5229 "Regular expression matching a time stamp or time stamp range.")
5230 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5231 org-ts-regexp-both "\\)?")
5232 "Regular expression matching a time stamp or time stamp range.
5233 The time stamps may be either active or inactive.")
5235 (defvar org-emph-face nil)
5237 (defun org-do-emphasis-faces (limit)
5238 "Run through the buffer and add overlays to emphasised strings."
5239 (let (rtn a)
5240 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5241 (if (not (= (char-after (match-beginning 3))
5242 (char-after (match-beginning 4))))
5243 (progn
5244 (setq rtn t)
5245 (setq a (assoc (match-string 3) org-emphasis-alist))
5246 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5247 'face
5248 (nth 1 a))
5249 (and (nth 4 a)
5250 (org-remove-flyspell-overlays-in
5251 (match-beginning 0) (match-end 0)))
5252 (add-text-properties (match-beginning 2) (match-end 2)
5253 '(font-lock-multiline t org-emphasis t))
5254 (when org-hide-emphasis-markers
5255 (add-text-properties (match-end 4) (match-beginning 5)
5256 '(invisible org-link))
5257 (add-text-properties (match-beginning 3) (match-end 3)
5258 '(invisible org-link)))))
5259 (backward-char 1))
5260 rtn))
5262 (defun org-emphasize (&optional char)
5263 "Insert or change an emphasis, i.e. a font like bold or italic.
5264 If there is an active region, change that region to a new emphasis.
5265 If there is no region, just insert the marker characters and position
5266 the cursor between them.
5267 CHAR should be either the marker character, or the first character of the
5268 HTML tag associated with that emphasis. If CHAR is a space, the means
5269 to remove the emphasis of the selected region.
5270 If char is not given (for example in an interactive call) it
5271 will be prompted for."
5272 (interactive)
5273 (let ((eal org-emphasis-alist) e det
5274 (erc org-emphasis-regexp-components)
5275 (prompt "")
5276 (string "") beg end move tag c s)
5277 (if (org-region-active-p)
5278 (setq beg (region-beginning) end (region-end)
5279 string (buffer-substring beg end))
5280 (setq move t))
5282 (while (setq e (pop eal))
5283 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5284 c (aref tag 0))
5285 (push (cons c (string-to-char (car e))) det)
5286 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5287 (substring tag 1)))))
5288 (setq det (nreverse det))
5289 (unless char
5290 (message "%s" (concat "Emphasis marker or tag:" prompt))
5291 (setq char (read-char-exclusive)))
5292 (setq char (or (cdr (assoc char det)) char))
5293 (if (equal char ?\ )
5294 (setq s "" move nil)
5295 (unless (assoc (char-to-string char) org-emphasis-alist)
5296 (error "No such emphasis marker: \"%c\"" char))
5297 (setq s (char-to-string char)))
5298 (while (and (> (length string) 1)
5299 (equal (substring string 0 1) (substring string -1))
5300 (assoc (substring string 0 1) org-emphasis-alist))
5301 (setq string (substring string 1 -1)))
5302 (setq string (concat s string s))
5303 (if beg (delete-region beg end))
5304 (unless (or (bolp)
5305 (string-match (concat "[" (nth 0 erc) "\n]")
5306 (char-to-string (char-before (point)))))
5307 (insert " "))
5308 (unless (or (eobp)
5309 (string-match (concat "[" (nth 1 erc) "\n]")
5310 (char-to-string (char-after (point)))))
5311 (insert " ") (backward-char 1))
5312 (insert string)
5313 (and move (backward-char 1))))
5315 (defconst org-nonsticky-props
5316 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5318 (defsubst org-rear-nonsticky-at (pos)
5319 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5321 (defun org-activate-plain-links (limit)
5322 "Run through the buffer and add overlays to links."
5323 (catch 'exit
5324 (let (f)
5325 (if (re-search-forward org-plain-link-re limit t)
5326 (progn
5327 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5328 (setq f (get-text-property (match-beginning 0) 'face))
5329 (if (or (eq f 'org-tag)
5330 (and (listp f) (memq 'org-tag f)))
5332 (add-text-properties (match-beginning 0) (match-end 0)
5333 (list 'mouse-face 'highlight
5334 'face 'org-link
5335 'keymap org-mouse-map))
5336 (org-rear-nonsticky-at (match-end 0)))
5337 t)))))
5339 (defun org-activate-code (limit)
5340 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5341 (progn
5342 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5343 (remove-text-properties (match-beginning 0) (match-end 0)
5344 '(display t invisible t intangible t))
5345 t)))
5347 (defcustom org-src-fontify-natively nil
5348 "When non-nil, fontify code in code blocks."
5349 :type 'boolean
5350 :group 'org-appearance
5351 :group 'org-babel)
5353 (defun org-fontify-meta-lines-and-blocks (limit)
5354 (condition-case nil
5355 (org-fontify-meta-lines-and-blocks-1 limit)
5356 (error (message "org-mode fontification error"))))
5358 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5359 "Fontify #+ lines and blocks, in the correct ways."
5360 (let ((case-fold-search t))
5361 (if (re-search-forward
5362 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5363 limit t)
5364 (let ((beg (match-beginning 0))
5365 (block-start (match-end 0))
5366 (block-end nil)
5367 (lang (match-string 7))
5368 (beg1 (line-beginning-position 2))
5369 (dc1 (downcase (match-string 2)))
5370 (dc3 (downcase (match-string 3)))
5371 end end1 quoting block-type ovl)
5372 (cond
5373 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
5374 ;; a single line of backend-specific content
5375 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5376 (remove-text-properties (match-beginning 0) (match-end 0)
5377 '(display t invisible t intangible t))
5378 (add-text-properties (match-beginning 1) (match-end 3)
5379 '(font-lock-fontified t face org-meta-line))
5380 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5381 '(font-lock-fontified t face org-block))
5382 ; for backend-specific code
5384 ((and (match-end 4) (equal dc3 "begin"))
5385 ;; Truly a block
5386 (setq block-type (downcase (match-string 5))
5387 quoting (member block-type org-protecting-blocks))
5388 (when (re-search-forward
5389 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5390 nil t) ;; on purpose, we look further than LIMIT
5391 (setq end (match-end 0) end1 (1- (match-beginning 0)))
5392 (setq block-end (match-beginning 0))
5393 (when quoting
5394 (remove-text-properties beg end
5395 '(display t invisible t intangible t)))
5396 (add-text-properties
5397 beg end
5398 '(font-lock-fontified t font-lock-multiline t))
5399 (add-text-properties beg beg1 '(face org-meta-line))
5400 (add-text-properties end1 (min (point-max) (1+ end))
5401 '(face org-meta-line)) ; for end_src
5402 (cond
5403 ((and lang (not (string= lang "")) org-src-fontify-natively)
5404 (org-src-font-lock-fontify-block lang block-start block-end)
5405 ;; remove old background overlays
5406 (mapc (lambda (ov)
5407 (if (eq (overlay-get ov 'face) 'org-block-background)
5408 (delete-overlay ov)))
5409 (overlays-at (/ (+ beg1 block-end) 2)))
5410 ;; add a background overlay
5411 (setq ovl (make-overlay beg1 block-end))
5412 (overlay-put ovl 'face 'org-block-background)
5413 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5414 (quoting
5415 (add-text-properties beg1 (min (point-max) (1+ end1))
5416 '(face org-block))) ; end of source block
5417 ((not org-fontify-quote-and-verse-blocks))
5418 ((string= block-type "quote")
5419 (add-text-properties beg1 (1+ end1) '(face org-quote)))
5420 ((string= block-type "verse")
5421 (add-text-properties beg1 (1+ end1) '(face org-verse))))
5422 (add-text-properties beg beg1 '(face org-block-begin-line))
5423 (add-text-properties (1+ end) (1+ end1) '(face org-block-end-line))
5425 ((member dc1 '("title:" "author:" "email:" "date:"))
5426 (add-text-properties
5427 beg (match-end 3)
5428 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5429 '(font-lock-fontified t invisible t)
5430 '(font-lock-fontified t face org-document-info-keyword)))
5431 (add-text-properties
5432 (match-beginning 6) (match-end 6)
5433 (if (string-equal dc1 "title:")
5434 '(font-lock-fontified t face org-document-title)
5435 '(font-lock-fontified t face org-document-info))))
5436 ((not (member (char-after beg) '(?\ ?\t)))
5437 ;; just any other in-buffer setting, but not indented
5438 (add-text-properties
5439 beg (1+ (match-end 0))
5440 '(font-lock-fontified t face org-meta-line))
5442 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
5443 "orgtbl:" "tblfm:" "tblname:" "results:"
5444 "call:" "header:" "headers:" "name:"))
5445 (and (match-end 4) (equal dc3 "attr")))
5446 (add-text-properties
5447 beg (match-end 0)
5448 '(font-lock-fontified t face org-meta-line))
5450 ((member dc3 '(" " ""))
5451 (add-text-properties
5452 beg (match-end 0)
5453 '(font-lock-fontified t face font-lock-comment-face)))
5454 (t nil))))))
5456 (defun org-activate-angle-links (limit)
5457 "Run through the buffer and add overlays to links."
5458 (if (re-search-forward org-angle-link-re limit t)
5459 (progn
5460 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5461 (add-text-properties (match-beginning 0) (match-end 0)
5462 (list 'mouse-face 'highlight
5463 'keymap org-mouse-map))
5464 (org-rear-nonsticky-at (match-end 0))
5465 t)))
5467 (defun org-activate-footnote-links (limit)
5468 "Run through the buffer and add overlays to footnotes."
5469 (let ((fn (org-footnote-next-reference-or-definition limit)))
5470 (when fn
5471 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5472 (org-remove-flyspell-overlays-in beg end)
5473 (add-text-properties beg end
5474 (list 'mouse-face 'highlight
5475 'keymap org-mouse-map
5476 'help-echo
5477 (if (= (point-at-bol) beg)
5478 "Footnote definition"
5479 "Footnote reference")
5480 'font-lock-fontified t
5481 'font-lock-multiline t
5482 'face 'org-footnote))))))
5484 (defun org-activate-bracket-links (limit)
5485 "Run through the buffer and add overlays to bracketed links."
5486 (if (re-search-forward org-bracket-link-regexp limit t)
5487 (let* ((help (concat "LINK: "
5488 (org-match-string-no-properties 1)))
5489 ;; FIXME: above we should remove the escapes.
5490 ;; but that requires another match, protecting match data,
5491 ;; a lot of overhead for font-lock.
5492 (ip (org-maybe-intangible
5493 (list 'invisible 'org-link
5494 'keymap org-mouse-map 'mouse-face 'highlight
5495 'font-lock-multiline t 'help-echo help)))
5496 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5497 'font-lock-multiline t 'help-echo help)))
5498 ;; We need to remove the invisible property here. Table narrowing
5499 ;; may have made some of this invisible.
5500 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5501 (remove-text-properties (match-beginning 0) (match-end 0)
5502 '(invisible nil))
5503 (if (match-end 3)
5504 (progn
5505 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5506 (org-rear-nonsticky-at (match-beginning 3))
5507 (add-text-properties (match-beginning 3) (match-end 3) vp)
5508 (org-rear-nonsticky-at (match-end 3))
5509 (add-text-properties (match-end 3) (match-end 0) ip)
5510 (org-rear-nonsticky-at (match-end 0)))
5511 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5512 (org-rear-nonsticky-at (match-beginning 1))
5513 (add-text-properties (match-beginning 1) (match-end 1) vp)
5514 (org-rear-nonsticky-at (match-end 1))
5515 (add-text-properties (match-end 1) (match-end 0) ip)
5516 (org-rear-nonsticky-at (match-end 0)))
5517 t)))
5519 (defun org-activate-dates (limit)
5520 "Run through the buffer and add overlays to dates."
5521 (if (re-search-forward org-tsr-regexp-both limit t)
5522 (progn
5523 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5524 (add-text-properties (match-beginning 0) (match-end 0)
5525 (list 'mouse-face 'highlight
5526 'keymap org-mouse-map))
5527 (org-rear-nonsticky-at (match-end 0))
5528 (when org-display-custom-times
5529 (if (match-end 3)
5530 (org-display-custom-time (match-beginning 3) (match-end 3)))
5531 (org-display-custom-time (match-beginning 1) (match-end 1)))
5532 t)))
5534 (defvar org-target-link-regexp nil
5535 "Regular expression matching radio targets in plain text.")
5536 (make-variable-buffer-local 'org-target-link-regexp)
5537 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5538 "Regular expression matching a link target.")
5539 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5540 "Regular expression matching a radio target.")
5541 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5542 "Regular expression matching any target.")
5544 (defun org-activate-target-links (limit)
5545 "Run through the buffer and add overlays to target matches."
5546 (when org-target-link-regexp
5547 (let ((case-fold-search t))
5548 (if (re-search-forward org-target-link-regexp limit t)
5549 (progn
5550 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5551 (add-text-properties (match-beginning 0) (match-end 0)
5552 (list 'mouse-face 'highlight
5553 'keymap org-mouse-map
5554 'help-echo "Radio target link"
5555 'org-linked-text t))
5556 (org-rear-nonsticky-at (match-end 0))
5557 t)))))
5559 (defun org-update-radio-target-regexp ()
5560 "Find all radio targets in this file and update the regular expression."
5561 (interactive)
5562 (when (memq 'radio org-activate-links)
5563 (setq org-target-link-regexp
5564 (org-make-target-link-regexp (org-all-targets 'radio)))
5565 (org-restart-font-lock)))
5567 (defun org-hide-wide-columns (limit)
5568 (let (s e)
5569 (setq s (text-property-any (point) (or limit (point-max))
5570 'org-cwidth t))
5571 (when s
5572 (setq e (next-single-property-change s 'org-cwidth))
5573 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5574 (goto-char e)
5575 t)))
5577 (defvar org-latex-and-specials-regexp nil
5578 "Regular expression for highlighting export special stuff.")
5579 (defvar org-match-substring-regexp)
5580 (defvar org-match-substring-with-braces-regexp)
5582 ;; This should be with the exporter code, but we also use if for font-locking
5583 (defconst org-export-html-special-string-regexps
5584 '(("\\\\-" . "&shy;")
5585 ("---\\([^-]\\)" . "&mdash;\\1")
5586 ("--\\([^-]\\)" . "&ndash;\\1")
5587 ("\\.\\.\\." . "&hellip;"))
5588 "Regular expressions for special string conversion.")
5591 (defun org-compute-latex-and-specials-regexp ()
5592 "Compute regular expression for stuff treated specially by exporters."
5593 (if (not org-highlight-latex-fragments-and-specials)
5594 (org-set-local 'org-latex-and-specials-regexp nil)
5595 (require 'org-exp)
5596 (let*
5597 ((matchers (plist-get org-format-latex-options :matchers))
5598 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5599 org-latex-regexps)))
5600 (org-export-allow-BIND nil)
5601 (options (org-combine-plists (org-default-export-plist)
5602 (org-infile-export-plist)))
5603 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5604 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5605 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5606 (org-export-html-expand (plist-get options :expand-quoted-html))
5607 (org-export-with-special-strings (plist-get options :special-strings))
5608 (re-sub
5609 (cond
5610 ((equal org-export-with-sub-superscripts '{})
5611 (list org-match-substring-with-braces-regexp))
5612 (org-export-with-sub-superscripts
5613 (list org-match-substring-regexp))
5614 (t nil)))
5615 (re-latex
5616 (if org-export-with-LaTeX-fragments
5617 (mapcar (lambda (x) (nth 1 x)) latexs)))
5618 (re-macros
5619 (if org-export-with-TeX-macros
5620 (list (concat "\\\\"
5621 (regexp-opt
5622 (append
5624 (delq nil
5625 (mapcar 'car-safe
5626 (append org-entities-user
5627 org-entities)))
5628 (if (boundp 'org-latex-entities)
5629 (mapcar (lambda (x)
5630 (or (car-safe x) x))
5631 org-latex-entities)
5632 nil))
5633 'words))) ; FIXME
5635 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5636 (re-special (if org-export-with-special-strings
5637 (mapcar (lambda (x) (car x))
5638 org-export-html-special-string-regexps)))
5639 (re-rest
5640 (delq nil
5641 (list
5642 (if org-export-html-expand "@<[^>\n]+>")
5643 ))))
5644 (org-set-local
5645 'org-latex-and-specials-regexp
5646 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5647 re-rest) "\\|")))))
5649 (defun org-do-latex-and-special-faces (limit)
5650 "Run through the buffer and add overlays to links."
5651 (when org-latex-and-specials-regexp
5652 (let (rtn d)
5653 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5654 limit t))
5655 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5656 'face))
5657 '(org-code org-verbatim underline)))
5658 (progn
5659 (setq rtn t
5660 d (cond ((member (char-after (1+ (match-beginning 0)))
5661 '(?_ ?^)) 1)
5662 (t 0)))
5663 (font-lock-prepend-text-property
5664 (+ d (match-beginning 0)) (match-end 0)
5665 'face 'org-latex-and-export-specials)
5666 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5667 '(font-lock-multiline t)))))
5668 rtn)))
5670 (defun org-restart-font-lock ()
5671 "Restart `font-lock-mode', to force refontification."
5672 (when (and (boundp 'font-lock-mode) font-lock-mode)
5673 (font-lock-mode -1)
5674 (font-lock-mode 1)))
5676 (defun org-all-targets (&optional radio)
5677 "Return a list of all targets in this file.
5678 With optional argument RADIO, only find radio targets."
5679 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5680 rtn)
5681 (save-excursion
5682 (goto-char (point-min))
5683 (while (re-search-forward re nil t)
5684 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5685 rtn)))
5687 (defun org-make-target-link-regexp (targets)
5688 "Make regular expression matching all strings in TARGETS.
5689 The regular expression finds the targets also if there is a line break
5690 between words."
5691 (and targets
5692 (concat
5693 "\\<\\("
5694 (mapconcat
5695 (lambda (x)
5696 (setq x (regexp-quote x))
5697 (while (string-match " +" x)
5698 (setq x (replace-match "\\s-+" t t x)))
5700 targets
5701 "\\|")
5702 "\\)\\>")))
5704 (defun org-activate-tags (limit)
5705 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5706 (progn
5707 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5708 (add-text-properties (match-beginning 1) (match-end 1)
5709 (list 'mouse-face 'highlight
5710 'keymap org-mouse-map))
5711 (org-rear-nonsticky-at (match-end 1))
5712 t)))
5714 (defun org-outline-level ()
5715 "Compute the outline level of the heading at point.
5716 This function assumes that the cursor is at the beginning of a line matched
5717 by `outline-regexp'. Otherwise it returns garbage.
5718 If this is called at a normal headline, the level is the number of stars.
5719 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5720 (save-excursion
5721 (looking-at org-outline-regexp)
5722 (1- (- (match-end 0) (match-beginning 0)))))
5724 (defvar org-font-lock-keywords nil)
5726 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5727 "Regular expression matching a property line.")
5729 (defvar org-font-lock-hook nil
5730 "Functions to be called for special font lock stuff.")
5732 (defvar org-font-lock-set-keywords-hook nil
5733 "Functions that can manipulate `org-font-lock-extra-keywords'.
5734 This is calles after `org-font-lock-extra-keywords' is defined, but before
5735 it is installed to be used by font lock. This can be useful if something
5736 needs to be inserted at a specific position in the font-lock sequence.")
5738 (defun org-font-lock-hook (limit)
5739 (run-hook-with-args 'org-font-lock-hook limit))
5741 (defun org-set-font-lock-defaults ()
5742 (let* ((em org-fontify-emphasized-text)
5743 (lk org-activate-links)
5744 (org-font-lock-extra-keywords
5745 (list
5746 ;; Call the hook
5747 '(org-font-lock-hook)
5748 ;; Headlines
5749 `(,(if org-fontify-whole-heading-line
5750 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5751 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5752 (1 (org-get-level-face 1))
5753 (2 (org-get-level-face 2))
5754 (3 (org-get-level-face 3)))
5755 ;; Table lines
5756 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5757 (1 'org-table t))
5758 ;; Table internals
5759 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5760 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5761 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5762 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5763 ;; Drawers
5764 (list org-drawer-regexp '(0 'org-special-keyword t))
5765 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5766 ;; Properties
5767 (list org-property-re
5768 '(1 'org-special-keyword t)
5769 '(3 'org-property-value t))
5770 ;; Links
5771 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5772 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5773 (if (memq 'plain lk) '(org-activate-plain-links))
5774 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5775 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5776 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5777 (if (memq 'footnote lk) '(org-activate-footnote-links))
5778 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5779 '(org-hide-wide-columns (0 nil append))
5780 ;; TODO keyword
5781 (list (format org-heading-keyword-regexp-format
5782 org-todo-regexp)
5783 '(2 (org-get-todo-face 2) t))
5784 ;; DONE
5785 (if org-fontify-done-headline
5786 (list (format org-heading-keyword-regexp-format
5787 (concat
5788 "\\("
5789 (mapconcat 'regexp-quote org-done-keywords "\\|")
5790 "\\)"))
5791 '(2 'org-headline-done t))
5792 nil)
5793 ;; Priorities
5794 '(org-font-lock-add-priority-faces)
5795 ;; Tags
5796 '(org-font-lock-add-tag-faces)
5797 ;; Special keywords
5798 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5799 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5800 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5801 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5802 ;; Emphasis
5803 (if em
5804 (if (featurep 'xemacs)
5805 '(org-do-emphasis-faces (0 nil append))
5806 '(org-do-emphasis-faces)))
5807 ;; Checkboxes
5808 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5809 1 'org-checkbox prepend)
5810 (if (cdr (assq 'checkbox org-list-automatic-rules))
5811 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5812 (0 (org-get-checkbox-statistics-face) t)))
5813 ;; Description list items
5814 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5815 1 'bold prepend)
5816 ;; ARCHIVEd headings
5817 (list (concat
5818 org-outline-regexp-bol
5819 "\\(.*:" org-archive-tag ":.*\\)")
5820 '(1 'org-archived prepend))
5821 ;; Specials
5822 '(org-do-latex-and-special-faces)
5823 '(org-fontify-entities)
5824 '(org-raise-scripts)
5825 ;; Code
5826 '(org-activate-code (1 'org-code t))
5827 ;; COMMENT
5828 (list (format org-heading-keyword-regexp-format
5829 (concat "\\("
5830 org-comment-string "\\|" org-quote-string
5831 "\\)"))
5832 '(2 'org-special-keyword t))
5833 '("^#.*" (0 'font-lock-comment-face t))
5834 ;; Blocks and meta lines
5835 '(org-fontify-meta-lines-and-blocks)
5837 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5838 (run-hooks 'org-font-lock-set-keywords-hook)
5839 ;; Now set the full font-lock-keywords
5840 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5841 (org-set-local 'font-lock-defaults
5842 '(org-font-lock-keywords t nil nil backward-paragraph))
5843 (kill-local-variable 'font-lock-keywords) nil))
5845 (defun org-toggle-pretty-entities ()
5846 "Toggle the composition display of entities as UTF8 characters."
5847 (interactive)
5848 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5849 (org-restart-font-lock)
5850 (if org-pretty-entities
5851 (message "Entities are displayed as UTF8 characers")
5852 (save-restriction
5853 (widen)
5854 (org-decompose-region (point-min) (point-max))
5855 (message "Entities are displayed plain"))))
5857 (defun org-fontify-entities (limit)
5858 "Find an entity to fontify."
5859 (let (ee)
5860 (when org-pretty-entities
5861 (catch 'match
5862 (while (re-search-forward
5863 "\\\\\\(frac[13][24]\\|[a-zA-Z]+\\)\\($\\|[^[:alpha:]\n]\\)"
5864 limit t)
5865 (if (and (not (org-in-indented-comment-line))
5866 (setq ee (org-entity-get (match-string 1)))
5867 (= (length (nth 6 ee)) 1))
5868 (progn
5869 (add-text-properties
5870 (match-beginning 0) (match-end 1)
5871 (list 'font-lock-fontified t))
5872 (compose-region (match-beginning 0) (match-end 1)
5873 (nth 6 ee) nil)
5874 (backward-char 1)
5875 (throw 'match t))))
5876 nil))))
5878 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5879 "Fontify string S like in Org-mode."
5880 (with-temp-buffer
5881 (insert s)
5882 (let ((org-odd-levels-only odd-levels))
5883 (org-mode)
5884 (font-lock-fontify-buffer)
5885 (buffer-string))))
5887 (defvar org-m nil)
5888 (defvar org-l nil)
5889 (defvar org-f nil)
5890 (defun org-get-level-face (n)
5891 "Get the right face for match N in font-lock matching of headlines."
5892 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5893 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5894 (if org-cycle-level-faces
5895 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5896 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5897 (cond
5898 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5899 ((eq n 2) org-f)
5900 (t (if org-level-color-stars-only nil org-f))))
5903 (defun org-get-todo-face (kwd)
5904 "Get the right face for a TODO keyword KWD.
5905 If KWD is a number, get the corresponding match group."
5906 (if (numberp kwd) (setq kwd (match-string kwd)))
5907 (or (org-face-from-face-or-color
5908 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5909 (and (member kwd org-done-keywords) 'org-done)
5910 'org-todo))
5912 (defun org-face-from-face-or-color (context inherit face-or-color)
5913 "Create a face list that inherits INHERIT, but sets the foreground color.
5914 When FACE-OR-COLOR is not a string, just return it."
5915 (if (stringp face-or-color)
5916 (list :inherit inherit
5917 (cdr (assoc context org-faces-easy-properties))
5918 face-or-color)
5919 face-or-color))
5921 (defun org-font-lock-add-tag-faces (limit)
5922 "Add the special tag faces."
5923 (when (and org-tag-faces org-tags-special-faces-re)
5924 (while (re-search-forward org-tags-special-faces-re limit t)
5925 (add-text-properties (match-beginning 1) (match-end 1)
5926 (list 'face (org-get-tag-face 1)
5927 'font-lock-fontified t))
5928 (backward-char 1))))
5930 (defun org-font-lock-add-priority-faces (limit)
5931 "Add the special priority faces."
5932 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5933 (add-text-properties
5934 (match-beginning 0) (match-end 0)
5935 (list 'face (or (org-face-from-face-or-color
5936 'priority 'org-special-keyword
5937 (cdr (assoc (char-after (match-beginning 1))
5938 org-priority-faces)))
5939 'org-special-keyword)
5940 'font-lock-fontified t))))
5942 (defun org-get-tag-face (kwd)
5943 "Get the right face for a TODO keyword KWD.
5944 If KWD is a number, get the corresponding match group."
5945 (if (numberp kwd) (setq kwd (match-string kwd)))
5946 (or (org-face-from-face-or-color
5947 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5948 'org-tag))
5950 (defun org-unfontify-region (beg end &optional maybe_loudly)
5951 "Remove fontification and activation overlays from links."
5952 (font-lock-default-unfontify-region beg end)
5953 (let* ((buffer-undo-list t)
5954 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5955 (inhibit-modification-hooks t)
5956 deactivate-mark buffer-file-name buffer-file-truename)
5957 (org-decompose-region beg end)
5958 (remove-text-properties beg end
5959 '(mouse-face t keymap t org-linked-text t
5960 invisible t intangible t
5961 org-no-flyspell t org-emphasis t))
5962 (org-remove-font-lock-display-properties beg end)))
5964 (defconst org-script-display '(((raise -0.3) (height 0.7))
5965 ((raise 0.3) (height 0.7))
5966 ((raise -0.5))
5967 ((raise 0.5)))
5968 "Display properties for showing superscripts and subscripts.")
5970 (defun org-remove-font-lock-display-properties (beg end)
5971 "Remove specific display properties that have been added by font lock.
5972 The will remove the raise properties that are used to show superscripts
5973 and subscripts."
5974 (let (next prop)
5975 (while (< beg end)
5976 (setq next (next-single-property-change beg 'display nil end)
5977 prop (get-text-property beg 'display))
5978 (if (member prop org-script-display)
5979 (put-text-property beg next 'display nil))
5980 (setq beg next))))
5982 (defun org-raise-scripts (limit)
5983 "Add raise properties to sub/superscripts."
5984 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
5985 (if (re-search-forward
5986 (if (eq org-use-sub-superscripts t)
5987 org-match-substring-regexp
5988 org-match-substring-with-braces-regexp)
5989 limit t)
5990 (let* ((pos (point)) table-p comment-p
5991 (mpos (match-beginning 3))
5992 (emph-p (get-text-property mpos 'org-emphasis))
5993 (link-p (get-text-property mpos 'mouse-face))
5994 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
5995 (goto-char (point-at-bol))
5996 (setq table-p (org-looking-at-p org-table-dataline-regexp)
5997 comment-p (org-looking-at-p "[ \t]*#"))
5998 (goto-char pos)
5999 ;; FIXME: Should we go back one character here, for a_b^c
6000 ;; (goto-char (1- pos)) ;????????????????????
6001 (if (or comment-p emph-p link-p keyw-p)
6003 (put-text-property (match-beginning 3) (match-end 0)
6004 'display
6005 (if (equal (char-after (match-beginning 2)) ?^)
6006 (nth (if table-p 3 1) org-script-display)
6007 (nth (if table-p 2 0) org-script-display)))
6008 (add-text-properties (match-beginning 2) (match-end 2)
6009 (list 'invisible t
6010 'org-dwidth t 'org-dwidth-n 1))
6011 (if (and (eq (char-after (match-beginning 3)) ?{)
6012 (eq (char-before (match-end 3)) ?}))
6013 (progn
6014 (add-text-properties
6015 (match-beginning 3) (1+ (match-beginning 3))
6016 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6017 (add-text-properties
6018 (1- (match-end 3)) (match-end 3)
6019 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6020 t)))))
6022 ;;;; Visibility cycling, including org-goto and indirect buffer
6024 ;;; Cycling
6026 (defvar org-cycle-global-status nil)
6027 (make-variable-buffer-local 'org-cycle-global-status)
6028 (defvar org-cycle-subtree-status nil)
6029 (make-variable-buffer-local 'org-cycle-subtree-status)
6031 ;;;###autoload
6033 (defvar org-inlinetask-min-level)
6035 (defun org-cycle (&optional arg)
6036 "TAB-action and visibility cycling for Org-mode.
6038 This is the command invoked in Org-mode by the TAB key. Its main purpose
6039 is outline visibility cycling, but it also invokes other actions
6040 in special contexts.
6042 - When this function is called with a prefix argument, rotate the entire
6043 buffer through 3 states (global cycling)
6044 1. OVERVIEW: Show only top-level headlines.
6045 2. CONTENTS: Show all headlines of all levels, but no body text.
6046 3. SHOW ALL: Show everything.
6047 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6048 determined by the variable `org-startup-folded', and by any VISIBILITY
6049 properties in the buffer.
6050 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6051 including any drawers.
6053 - When inside a table, re-align the table and move to the next field.
6055 - When point is at the beginning of a headline, rotate the subtree started
6056 by this line through 3 different states (local cycling)
6057 1. FOLDED: Only the main headline is shown.
6058 2. CHILDREN: The main headline and the direct children are shown.
6059 From this state, you can move to one of the children
6060 and zoom in further.
6061 3. SUBTREE: Show the entire subtree, including body text.
6062 If there is no subtree, switch directly from CHILDREN to FOLDED.
6064 - When point is at the beginning of an empty headline and the variable
6065 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6066 of the headline by demoting and promoting it to likely levels. This
6067 speeds up creation document structure by pressing TAB once or several
6068 times right after creating a new headline.
6070 - When there is a numeric prefix, go up to a heading with level ARG, do
6071 a `show-subtree' and return to the previous cursor position. If ARG
6072 is negative, go up that many levels.
6074 - When point is not at the beginning of a headline, execute the global
6075 binding for TAB, which is re-indenting the line. See the option
6076 `org-cycle-emulate-tab' for details.
6078 - Special case: if point is at the beginning of the buffer and there is
6079 no headline in line 1, this function will act as if called with prefix arg
6080 (C-u TAB, same as S-TAB) also when called without prefix arg.
6081 But only if also the variable `org-cycle-global-at-bob' is t."
6082 (interactive "P")
6083 (org-load-modules-maybe)
6084 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6085 (and org-cycle-level-after-item/entry-creation
6086 (or (org-cycle-level)
6087 (org-cycle-item-indentation))))
6088 (let* ((limit-level
6089 (or org-cycle-max-level
6090 (and (boundp 'org-inlinetask-min-level)
6091 org-inlinetask-min-level
6092 (1- org-inlinetask-min-level))))
6093 (nstars (and limit-level
6094 (if org-odd-levels-only
6095 (and limit-level (1- (* limit-level 2)))
6096 limit-level)))
6097 (org-outline-regexp
6098 (if (not (eq major-mode 'org-mode))
6099 outline-regexp
6100 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6101 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6102 (not (looking-at org-outline-regexp))))
6103 (org-cycle-hook
6104 (if bob-special
6105 (delq 'org-optimize-window-after-visibility-change
6106 (copy-sequence org-cycle-hook))
6107 org-cycle-hook))
6108 (pos (point)))
6110 (if (or bob-special (equal arg '(4)))
6111 ;; special case: use global cycling
6112 (setq arg t))
6114 (cond
6116 ((equal arg '(16))
6117 (setq last-command 'dummy)
6118 (org-set-startup-visibility)
6119 (message "Startup visibility, plus VISIBILITY properties"))
6121 ((equal arg '(64))
6122 (show-all)
6123 (message "Entire buffer visible, including drawers"))
6125 ;; Table: enter it or move to the next field.
6126 ((org-at-table-p 'any)
6127 (if (org-at-table.el-p)
6128 (message "Use C-c ' to edit table.el tables")
6129 (if arg (org-table-edit-field t)
6130 (org-table-justify-field-maybe)
6131 (call-interactively 'org-table-next-field))))
6133 ((run-hook-with-args-until-success
6134 'org-tab-after-check-for-table-hook))
6136 ;; Global cycling: delegate to `org-cycle-internal-global'.
6137 ((eq arg t) (org-cycle-internal-global))
6139 ;; Drawers: delegate to `org-flag-drawer'.
6140 ((and org-drawers org-drawer-regexp
6141 (save-excursion
6142 (beginning-of-line 1)
6143 (looking-at org-drawer-regexp)))
6144 (org-flag-drawer ; toggle block visibility
6145 (not (get-char-property (match-end 0) 'invisible))))
6147 ;; Show-subtree, ARG levels up from here.
6148 ((integerp arg)
6149 (save-excursion
6150 (org-back-to-heading)
6151 (outline-up-heading (if (< arg 0) (- arg)
6152 (- (funcall outline-level) arg)))
6153 (org-show-subtree)))
6155 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6156 ((and (featurep 'org-inlinetask)
6157 (org-inlinetask-at-task-p)
6158 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6159 (org-inlinetask-toggle-visibility))
6161 ((org-try-cdlatex-tab))
6163 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6164 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6165 (save-excursion (beginning-of-line 1)
6166 (looking-at org-outline-regexp)))
6167 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6168 (org-cycle-internal-local))
6170 ;; From there: TAB emulation and template completion.
6171 (buffer-read-only (org-back-to-heading))
6173 ((run-hook-with-args-until-success
6174 'org-tab-after-check-for-cycling-hook))
6176 ((org-try-structure-completion))
6178 ((run-hook-with-args-until-success
6179 'org-tab-before-tab-emulation-hook))
6181 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6182 (or (not (bolp))
6183 (not (looking-at org-outline-regexp))))
6184 (call-interactively (global-key-binding "\t")))
6186 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6187 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6188 (or (and (eq org-cycle-emulate-tab 'white)
6189 (= (match-end 0) (point-at-eol)))
6190 (and (eq org-cycle-emulate-tab 'whitestart)
6191 (>= (match-end 0) pos))))
6193 (eq org-cycle-emulate-tab t))
6194 (call-interactively (global-key-binding "\t")))
6196 (t (save-excursion
6197 (org-back-to-heading)
6198 (org-cycle)))))))
6200 (defun org-cycle-internal-global ()
6201 "Do the global cycling action."
6202 (cond
6203 ((and (eq last-command this-command)
6204 (eq org-cycle-global-status 'overview))
6205 ;; We just created the overview - now do table of contents
6206 ;; This can be slow in very large buffers, so indicate action
6207 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6208 (message "CONTENTS...")
6209 (org-content)
6210 (message "CONTENTS...done")
6211 (setq org-cycle-global-status 'contents)
6212 (run-hook-with-args 'org-cycle-hook 'contents))
6214 ((and (eq last-command this-command)
6215 (eq org-cycle-global-status 'contents))
6216 ;; We just showed the table of contents - now show everything
6217 (run-hook-with-args 'org-pre-cycle-hook 'all)
6218 (show-all)
6219 (message "SHOW ALL")
6220 (setq org-cycle-global-status 'all)
6221 (run-hook-with-args 'org-cycle-hook 'all))
6224 ;; Default action: go to overview
6225 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6226 (org-overview)
6227 (message "OVERVIEW")
6228 (setq org-cycle-global-status 'overview)
6229 (run-hook-with-args 'org-cycle-hook 'overview))))
6231 (defun org-cycle-internal-local ()
6232 "Do the local cycling action."
6233 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6234 ;; First, determine end of headline (EOH), end of subtree or item
6235 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6236 (save-excursion
6237 (if (org-at-item-p)
6238 (progn
6239 (beginning-of-line)
6240 (setq struct (org-list-struct))
6241 (setq eoh (point-at-eol))
6242 (setq eos (org-list-get-item-end-before-blank (point) struct))
6243 (setq has-children (org-list-has-child-p (point) struct)))
6244 (org-back-to-heading)
6245 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6246 (setq eos (save-excursion
6247 (org-end-of-subtree t)
6248 (unless (eobp)
6249 (skip-chars-forward " \t\n"))
6250 (if (eobp) (point) (1- (point)))))
6251 (setq has-children
6252 (or (save-excursion
6253 (let ((level (funcall outline-level)))
6254 (outline-next-heading)
6255 (and (org-at-heading-p t)
6256 (> (funcall outline-level) level))))
6257 (save-excursion
6258 (org-list-search-forward (org-item-beginning-re) eos t)))))
6259 ;; Determine end invisible part of buffer (EOL)
6260 (beginning-of-line 2)
6261 ;; XEmacs doesn't have `next-single-char-property-change'
6262 (if (featurep 'xemacs)
6263 (while (and (not (eobp)) ;; this is like `next-line'
6264 (get-char-property (1- (point)) 'invisible))
6265 (beginning-of-line 2))
6266 (while (and (not (eobp)) ;; this is like `next-line'
6267 (get-char-property (1- (point)) 'invisible))
6268 (goto-char (next-single-char-property-change (point) 'invisible))
6269 (and (eolp) (beginning-of-line 2))))
6270 (setq eol (point)))
6271 ;; Find out what to do next and set `this-command'
6272 (cond
6273 ((= eos eoh)
6274 ;; Nothing is hidden behind this heading
6275 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6276 (message "EMPTY ENTRY")
6277 (setq org-cycle-subtree-status nil)
6278 (save-excursion
6279 (goto-char eos)
6280 (outline-next-heading)
6281 (if (outline-invisible-p) (org-flag-heading nil))))
6282 ((and (or (>= eol eos)
6283 (not (string-match "\\S-" (buffer-substring eol eos))))
6284 (or has-children
6285 (not (setq children-skipped
6286 org-cycle-skip-children-state-if-no-children))))
6287 ;; Entire subtree is hidden in one line: children view
6288 (run-hook-with-args 'org-pre-cycle-hook 'children)
6289 (if (org-at-item-p)
6290 (org-list-set-item-visibility (point-at-bol) struct 'children)
6291 (org-show-entry)
6292 (show-children)
6293 ;; Fold every list in subtree to top-level items.
6294 (when (eq org-cycle-include-plain-lists 'integrate)
6295 (save-excursion
6296 (org-back-to-heading)
6297 (while (org-list-search-forward (org-item-beginning-re) eos t)
6298 (beginning-of-line 1)
6299 (let* ((struct (org-list-struct))
6300 (prevs (org-list-prevs-alist struct))
6301 (end (org-list-get-bottom-point struct)))
6302 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6303 (org-list-get-all-items (point) struct prevs))
6304 (goto-char end))))))
6305 (message "CHILDREN")
6306 (save-excursion
6307 (goto-char eos)
6308 (outline-next-heading)
6309 (if (outline-invisible-p) (org-flag-heading nil)))
6310 (setq org-cycle-subtree-status 'children)
6311 (run-hook-with-args 'org-cycle-hook 'children))
6312 ((or children-skipped
6313 (and (eq last-command this-command)
6314 (eq org-cycle-subtree-status 'children)))
6315 ;; We just showed the children, or no children are there,
6316 ;; now show everything.
6317 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6318 (outline-flag-region eoh eos nil)
6319 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6320 (setq org-cycle-subtree-status 'subtree)
6321 (run-hook-with-args 'org-cycle-hook 'subtree))
6323 ;; Default action: hide the subtree.
6324 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6325 (outline-flag-region eoh eos t)
6326 (message "FOLDED")
6327 (setq org-cycle-subtree-status 'folded)
6328 (run-hook-with-args 'org-cycle-hook 'folded)))))
6330 ;;;###autoload
6331 (defun org-global-cycle (&optional arg)
6332 "Cycle the global visibility. For details see `org-cycle'.
6333 With \\[universal-argument] prefix arg, switch to startup visibility.
6334 With a numeric prefix, show all headlines up to that level."
6335 (interactive "P")
6336 (let ((org-cycle-include-plain-lists
6337 (if (eq major-mode 'org-mode) org-cycle-include-plain-lists nil)))
6338 (cond
6339 ((integerp arg)
6340 (show-all)
6341 (hide-sublevels arg)
6342 (setq org-cycle-global-status 'contents))
6343 ((equal arg '(4))
6344 (org-set-startup-visibility)
6345 (message "Startup visibility, plus VISIBILITY properties."))
6347 (org-cycle '(4))))))
6349 (defun org-set-startup-visibility ()
6350 "Set the visibility required by startup options and properties."
6351 (cond
6352 ((eq org-startup-folded t)
6353 (org-cycle '(4)))
6354 ((eq org-startup-folded 'content)
6355 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6356 (org-cycle '(4)) (org-cycle '(4)))))
6357 (unless (eq org-startup-folded 'showeverything)
6358 (if org-hide-block-startup (org-hide-block-all))
6359 (org-set-visibility-according-to-property 'no-cleanup)
6360 (org-cycle-hide-archived-subtrees 'all)
6361 (org-cycle-hide-drawers 'all)
6362 (org-cycle-show-empty-lines t)))
6364 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6365 "Switch subtree visibilities according to :VISIBILITY: property."
6366 (interactive)
6367 (let (org-show-entry-below state)
6368 (save-excursion
6369 (goto-char (point-min))
6370 (while (re-search-forward
6371 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6372 nil t)
6373 (setq state (match-string 1))
6374 (save-excursion
6375 (org-back-to-heading t)
6376 (hide-subtree)
6377 (org-reveal)
6378 (cond
6379 ((equal state '("fold" "folded"))
6380 (hide-subtree))
6381 ((equal state "children")
6382 (org-show-hidden-entry)
6383 (show-children))
6384 ((equal state "content")
6385 (save-excursion
6386 (save-restriction
6387 (org-narrow-to-subtree)
6388 (org-content))))
6389 ((member state '("all" "showall"))
6390 (show-subtree)))))
6391 (unless no-cleanup
6392 (org-cycle-hide-archived-subtrees 'all)
6393 (org-cycle-hide-drawers 'all)
6394 (org-cycle-show-empty-lines 'all)))))
6396 ;; This function uses outline-regexp instead of the more fundamental
6397 ;; org-outline-regexp so that org-cycle-global works outside of Org
6398 ;; buffers, where outline-regexp is needed.
6399 (defun org-overview ()
6400 "Switch to overview mode, showing only top-level headlines.
6401 Really, this shows all headlines with level equal or greater than the level
6402 of the first headline in the buffer. This is important, because if the
6403 first headline is not level one, then (hide-sublevels 1) gives confusing
6404 results."
6405 (interactive)
6406 (let ((level (save-excursion
6407 (goto-char (point-min))
6408 (if (re-search-forward (concat "^" outline-regexp) nil t)
6409 (progn
6410 (goto-char (match-beginning 0))
6411 (funcall outline-level))))))
6412 (and level (hide-sublevels level))))
6414 (defun org-content (&optional arg)
6415 "Show all headlines in the buffer, like a table of contents.
6416 With numerical argument N, show content up to level N."
6417 (interactive "P")
6418 (save-excursion
6419 ;; Visit all headings and show their offspring
6420 (and (integerp arg) (org-overview))
6421 (goto-char (point-max))
6422 (catch 'exit
6423 (while (and (progn (condition-case nil
6424 (outline-previous-visible-heading 1)
6425 (error (goto-char (point-min))))
6427 (looking-at org-outline-regexp))
6428 (if (integerp arg)
6429 (show-children (1- arg))
6430 (show-branches))
6431 (if (bobp) (throw 'exit nil))))))
6434 (defun org-optimize-window-after-visibility-change (state)
6435 "Adjust the window after a change in outline visibility.
6436 This function is the default value of the hook `org-cycle-hook'."
6437 (when (get-buffer-window (current-buffer))
6438 (cond
6439 ((eq state 'content) nil)
6440 ((eq state 'all) nil)
6441 ((eq state 'folded) nil)
6442 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6443 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6445 (defun org-remove-empty-overlays-at (pos)
6446 "Remove outline overlays that do not contain non-white stuff."
6447 (mapc
6448 (lambda (o)
6449 (and (eq 'outline (overlay-get o 'invisible))
6450 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6451 (overlay-end o))))
6452 (delete-overlay o)))
6453 (overlays-at pos)))
6455 (defun org-clean-visibility-after-subtree-move ()
6456 "Fix visibility issues after moving a subtree."
6457 ;; First, find a reasonable region to look at:
6458 ;; Start two siblings above, end three below
6459 (let* ((beg (save-excursion
6460 (and (org-get-last-sibling)
6461 (org-get-last-sibling))
6462 (point)))
6463 (end (save-excursion
6464 (and (org-get-next-sibling)
6465 (org-get-next-sibling)
6466 (org-get-next-sibling))
6467 (if (org-at-heading-p)
6468 (point-at-eol)
6469 (point))))
6470 (level (looking-at "\\*+"))
6471 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6472 (save-excursion
6473 (save-restriction
6474 (narrow-to-region beg end)
6475 (when re
6476 ;; Properly fold already folded siblings
6477 (goto-char (point-min))
6478 (while (re-search-forward re nil t)
6479 (if (and (not (outline-invisible-p))
6480 (save-excursion
6481 (goto-char (point-at-eol)) (outline-invisible-p)))
6482 (hide-entry))))
6483 (org-cycle-show-empty-lines 'overview)
6484 (org-cycle-hide-drawers 'overview)))))
6486 (defun org-cycle-show-empty-lines (state)
6487 "Show empty lines above all visible headlines.
6488 The region to be covered depends on STATE when called through
6489 `org-cycle-hook'. Lisp program can use t for STATE to get the
6490 entire buffer covered. Note that an empty line is only shown if there
6491 are at least `org-cycle-separator-lines' empty lines before the headline."
6492 (when (not (= org-cycle-separator-lines 0))
6493 (save-excursion
6494 (let* ((n (abs org-cycle-separator-lines))
6495 (re (cond
6496 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6497 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6498 (t (let ((ns (number-to-string (- n 2))))
6499 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6500 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6501 beg end b e)
6502 (cond
6503 ((memq state '(overview contents t))
6504 (setq beg (point-min) end (point-max)))
6505 ((memq state '(children folded))
6506 (setq beg (point) end (progn (org-end-of-subtree t t)
6507 (beginning-of-line 2)
6508 (point)))))
6509 (when beg
6510 (goto-char beg)
6511 (while (re-search-forward re end t)
6512 (unless (get-char-property (match-end 1) 'invisible)
6513 (setq e (match-end 1))
6514 (if (< org-cycle-separator-lines 0)
6515 (setq b (save-excursion
6516 (goto-char (match-beginning 0))
6517 (org-back-over-empty-lines)
6518 (if (save-excursion
6519 (goto-char (max (point-min) (1- (point))))
6520 (org-on-heading-p))
6521 (1- (point))
6522 (point))))
6523 (setq b (match-beginning 1)))
6524 (outline-flag-region b e nil)))))))
6525 ;; Never hide empty lines at the end of the file.
6526 (save-excursion
6527 (goto-char (point-max))
6528 (outline-previous-heading)
6529 (outline-end-of-heading)
6530 (if (and (looking-at "[ \t\n]+")
6531 (= (match-end 0) (point-max)))
6532 (outline-flag-region (point) (match-end 0) nil))))
6534 (defun org-show-empty-lines-in-parent ()
6535 "Move to the parent and re-show empty lines before visible headlines."
6536 (save-excursion
6537 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6538 (org-cycle-show-empty-lines context))))
6540 (defun org-files-list ()
6541 "Return `org-agenda-files' list, plus all open org-mode files.
6542 This is useful for operations that need to scan all of a user's
6543 open and agenda-wise Org files."
6544 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6545 (dolist (buf (buffer-list))
6546 (with-current-buffer buf
6547 (if (and (eq major-mode 'org-mode) (buffer-file-name))
6548 (let ((file (expand-file-name (buffer-file-name))))
6549 (unless (member file files)
6550 (push file files))))))
6551 files))
6553 (defsubst org-entry-beginning-position ()
6554 "Return the beginning position of the current entry."
6555 (save-excursion (outline-back-to-heading t) (point)))
6557 (defsubst org-entry-end-position ()
6558 "Return the end position of the current entry."
6559 (save-excursion (outline-next-heading) (point)))
6561 (defun org-cycle-hide-drawers (state)
6562 "Re-hide all drawers after a visibility state change."
6563 (when (and (eq major-mode 'org-mode)
6564 (not (memq state '(overview folded contents))))
6565 (save-excursion
6566 (let* ((globalp (memq state '(contents all)))
6567 (beg (if globalp (point-min) (point)))
6568 (end (if globalp (point-max)
6569 (if (eq state 'children)
6570 (save-excursion (outline-next-heading) (point))
6571 (org-end-of-subtree t)))))
6572 (goto-char beg)
6573 (while (re-search-forward org-drawer-regexp end t)
6574 (org-flag-drawer t))))))
6576 (defun org-flag-drawer (flag)
6577 (save-excursion
6578 (beginning-of-line 1)
6579 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6580 (let ((b (match-end 0)))
6581 (if (re-search-forward
6582 "^[ \t]*:END:"
6583 (save-excursion (outline-next-heading) (point)) t)
6584 (outline-flag-region b (point-at-eol) flag)
6585 (error ":END: line missing at position %s" b))))))
6587 (defun org-subtree-end-visible-p ()
6588 "Is the end of the current subtree visible?"
6589 (pos-visible-in-window-p
6590 (save-excursion (org-end-of-subtree t) (point))))
6592 (defun org-first-headline-recenter (&optional N)
6593 "Move cursor to the first headline and recenter the headline.
6594 Optional argument N means put the headline into the Nth line of the window."
6595 (goto-char (point-min))
6596 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6597 (beginning-of-line)
6598 (recenter (prefix-numeric-value N))))
6600 ;;; Saving and restoring visibility
6602 (defun org-outline-overlay-data (&optional use-markers)
6603 "Return a list of the locations of all outline overlays.
6604 These are overlays with the `invisible' property value `outline'.
6605 The return value is a list of cons cells, with start and stop
6606 positions for each overlay.
6607 If USE-MARKERS is set, return the positions as markers."
6608 (let (beg end)
6609 (save-excursion
6610 (save-restriction
6611 (widen)
6612 (delq nil
6613 (mapcar (lambda (o)
6614 (when (eq (overlay-get o 'invisible) 'outline)
6615 (setq beg (overlay-start o)
6616 end (overlay-end o))
6617 (and beg end (> end beg)
6618 (if use-markers
6619 (cons (move-marker (make-marker) beg)
6620 (move-marker (make-marker) end))
6621 (cons beg end)))))
6622 (overlays-in (point-min) (point-max))))))))
6624 (defun org-set-outline-overlay-data (data)
6625 "Create visibility overlays for all positions in DATA.
6626 DATA should have been made by `org-outline-overlay-data'."
6627 (let (o)
6628 (save-excursion
6629 (save-restriction
6630 (widen)
6631 (show-all)
6632 (mapc (lambda (c)
6633 (outline-flag-region (car c) (cdr c) t))
6634 data)))))
6636 ;;; Folding of blocks
6638 (defvar org-hide-block-overlays nil
6639 "Overlays hiding blocks.")
6640 (make-variable-buffer-local 'org-hide-block-overlays)
6642 (defun org-block-map (function &optional start end)
6643 "Call FUNCTION at the head of all source blocks in the current buffer.
6644 Optional arguments START and END can be used to limit the range."
6645 (let ((start (or start (point-min)))
6646 (end (or end (point-max))))
6647 (save-excursion
6648 (goto-char start)
6649 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6650 (save-excursion
6651 (save-match-data
6652 (goto-char (match-beginning 0))
6653 (funcall function)))))))
6655 (defun org-hide-block-toggle-all ()
6656 "Toggle the visibility of all blocks in the current buffer."
6657 (org-block-map #'org-hide-block-toggle))
6659 (defun org-hide-block-all ()
6660 "Fold all blocks in the current buffer."
6661 (interactive)
6662 (org-show-block-all)
6663 (org-block-map #'org-hide-block-toggle-maybe))
6665 (defun org-show-block-all ()
6666 "Unfold all blocks in the current buffer."
6667 (interactive)
6668 (mapc 'delete-overlay org-hide-block-overlays)
6669 (setq org-hide-block-overlays nil))
6671 (defun org-hide-block-toggle-maybe ()
6672 "Toggle visibility of block at point."
6673 (interactive)
6674 (let ((case-fold-search t))
6675 (if (save-excursion
6676 (beginning-of-line 1)
6677 (looking-at org-block-regexp))
6678 (progn (org-hide-block-toggle)
6679 t) ;; to signal that we took action
6680 nil))) ;; to signal that we did not
6682 (defun org-hide-block-toggle (&optional force)
6683 "Toggle the visibility of the current block."
6684 (interactive)
6685 (save-excursion
6686 (beginning-of-line)
6687 (if (re-search-forward org-block-regexp nil t)
6688 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6689 (end (match-end 0)) ;; end of entire body
6691 (if (memq t (mapcar (lambda (overlay)
6692 (eq (overlay-get overlay 'invisible)
6693 'org-hide-block))
6694 (overlays-at start)))
6695 (if (or (not force) (eq force 'off))
6696 (mapc (lambda (ov)
6697 (when (member ov org-hide-block-overlays)
6698 (setq org-hide-block-overlays
6699 (delq ov org-hide-block-overlays)))
6700 (when (eq (overlay-get ov 'invisible)
6701 'org-hide-block)
6702 (delete-overlay ov)))
6703 (overlays-at start)))
6704 (setq ov (make-overlay start end))
6705 (overlay-put ov 'invisible 'org-hide-block)
6706 ;; make the block accessible to isearch
6707 (overlay-put
6708 ov 'isearch-open-invisible
6709 (lambda (ov)
6710 (when (member ov org-hide-block-overlays)
6711 (setq org-hide-block-overlays
6712 (delq ov org-hide-block-overlays)))
6713 (when (eq (overlay-get ov 'invisible)
6714 'org-hide-block)
6715 (delete-overlay ov))))
6716 (push ov org-hide-block-overlays)))
6717 (error "Not looking at a source block"))))
6719 ;; org-tab-after-check-for-cycling-hook
6720 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6721 ;; Remove overlays when changing major mode
6722 (add-hook 'org-mode-hook
6723 (lambda () (org-add-hook 'change-major-mode-hook
6724 'org-show-block-all 'append 'local)))
6726 ;;; Org-goto
6728 (defvar org-goto-window-configuration nil)
6729 (defvar org-goto-marker nil)
6730 (defvar org-goto-map
6731 (let ((map (make-sparse-keymap)))
6732 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6733 (while (setq cmd (pop cmds))
6734 (substitute-key-definition cmd cmd map global-map)))
6735 (suppress-keymap map)
6736 (org-defkey map "\C-m" 'org-goto-ret)
6737 (org-defkey map [(return)] 'org-goto-ret)
6738 (org-defkey map [(left)] 'org-goto-left)
6739 (org-defkey map [(right)] 'org-goto-right)
6740 (org-defkey map [(control ?g)] 'org-goto-quit)
6741 (org-defkey map "\C-i" 'org-cycle)
6742 (org-defkey map [(tab)] 'org-cycle)
6743 (org-defkey map [(down)] 'outline-next-visible-heading)
6744 (org-defkey map [(up)] 'outline-previous-visible-heading)
6745 (if org-goto-auto-isearch
6746 (if (fboundp 'define-key-after)
6747 (define-key-after map [t] 'org-goto-local-auto-isearch)
6748 nil)
6749 (org-defkey map "q" 'org-goto-quit)
6750 (org-defkey map "n" 'outline-next-visible-heading)
6751 (org-defkey map "p" 'outline-previous-visible-heading)
6752 (org-defkey map "f" 'outline-forward-same-level)
6753 (org-defkey map "b" 'outline-backward-same-level)
6754 (org-defkey map "u" 'outline-up-heading))
6755 (org-defkey map "/" 'org-occur)
6756 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6757 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6758 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6759 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6760 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6761 map))
6763 (defconst org-goto-help
6764 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6765 RET=jump to location [Q]uit and return to previous location
6766 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6768 (defvar org-goto-start-pos) ; dynamically scoped parameter
6770 ;; FIXME: Docstring does not mention both interfaces
6771 (defun org-goto (&optional alternative-interface)
6772 "Look up a different location in the current file, keeping current visibility.
6774 When you want look-up or go to a different location in a document, the
6775 fastest way is often to fold the entire buffer and then dive into the tree.
6776 This method has the disadvantage, that the previous location will be folded,
6777 which may not be what you want.
6779 This command works around this by showing a copy of the current buffer
6780 in an indirect buffer, in overview mode. You can dive into the tree in
6781 that copy, use org-occur and incremental search to find a location.
6782 When pressing RET or `Q', the command returns to the original buffer in
6783 which the visibility is still unchanged. After RET is will also jump to
6784 the location selected in the indirect buffer and expose the headline
6785 hierarchy above."
6786 (interactive "P")
6787 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6788 (org-refile-use-outline-path t)
6789 (org-refile-target-verify-function nil)
6790 (interface
6791 (if (not alternative-interface)
6792 org-goto-interface
6793 (if (eq org-goto-interface 'outline)
6794 'outline-path-completion
6795 'outline)))
6796 (org-goto-start-pos (point))
6797 (selected-point
6798 (if (eq interface 'outline)
6799 (car (org-get-location (current-buffer) org-goto-help))
6800 (let ((pa (org-refile-get-location "Goto")))
6801 (org-refile-check-position pa)
6802 (nth 3 pa)))))
6803 (if selected-point
6804 (progn
6805 (org-mark-ring-push org-goto-start-pos)
6806 (goto-char selected-point)
6807 (if (or (outline-invisible-p) (org-invisible-p2))
6808 (org-show-context 'org-goto)))
6809 (message "Quit"))))
6811 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6812 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6813 (defvar org-goto-local-auto-isearch-map) ; defined below
6815 (defun org-get-location (buf help)
6816 "Let the user select a location in the Org-mode buffer BUF.
6817 This function uses a recursive edit. It returns the selected position
6818 or nil."
6819 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6820 (isearch-hide-immediately nil)
6821 (isearch-search-fun-function
6822 (lambda () 'org-goto-local-search-headings))
6823 (org-goto-selected-point org-goto-exit-command)
6824 (pop-up-frames nil)
6825 (special-display-buffer-names nil)
6826 (special-display-regexps nil)
6827 (special-display-function nil))
6828 (save-excursion
6829 (save-window-excursion
6830 (delete-other-windows)
6831 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6832 (org-pop-to-buffer-same-window
6833 (condition-case nil
6834 (make-indirect-buffer (current-buffer) "*org-goto*")
6835 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6836 (with-output-to-temp-buffer "*Help*"
6837 (princ help))
6838 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6839 (setq buffer-read-only nil)
6840 (let ((org-startup-truncated t)
6841 (org-startup-folded nil)
6842 (org-startup-align-all-tables nil))
6843 (org-mode)
6844 (org-overview))
6845 (setq buffer-read-only t)
6846 (if (and (boundp 'org-goto-start-pos)
6847 (integer-or-marker-p org-goto-start-pos))
6848 (let ((org-show-hierarchy-above t)
6849 (org-show-siblings t)
6850 (org-show-following-heading t))
6851 (goto-char org-goto-start-pos)
6852 (and (outline-invisible-p) (org-show-context)))
6853 (goto-char (point-min)))
6854 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6855 (message "Select location and press RET")
6856 (use-local-map org-goto-map)
6857 (recursive-edit)
6859 (kill-buffer "*org-goto*")
6860 (cons org-goto-selected-point org-goto-exit-command)))
6862 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6863 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6864 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6865 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6867 (defun org-goto-local-search-headings (string bound noerror)
6868 "Search and make sure that any matches are in headlines."
6869 (catch 'return
6870 (while (if isearch-forward
6871 (search-forward string bound noerror)
6872 (search-backward string bound noerror))
6873 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6874 (and (member :headline context)
6875 (not (member :tags context))))
6876 (throw 'return (point))))))
6878 (defun org-goto-local-auto-isearch ()
6879 "Start isearch."
6880 (interactive)
6881 (goto-char (point-min))
6882 (let ((keys (this-command-keys)))
6883 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6884 (isearch-mode t)
6885 (isearch-process-search-char (string-to-char keys)))))
6887 (defun org-goto-ret (&optional arg)
6888 "Finish `org-goto' by going to the new location."
6889 (interactive "P")
6890 (setq org-goto-selected-point (point)
6891 org-goto-exit-command 'return)
6892 (throw 'exit nil))
6894 (defun org-goto-left ()
6895 "Finish `org-goto' by going to the new location."
6896 (interactive)
6897 (if (org-on-heading-p)
6898 (progn
6899 (beginning-of-line 1)
6900 (setq org-goto-selected-point (point)
6901 org-goto-exit-command 'left)
6902 (throw 'exit nil))
6903 (error "Not on a heading")))
6905 (defun org-goto-right ()
6906 "Finish `org-goto' by going to the new location."
6907 (interactive)
6908 (if (org-on-heading-p)
6909 (progn
6910 (setq org-goto-selected-point (point)
6911 org-goto-exit-command 'right)
6912 (throw 'exit nil))
6913 (error "Not on a heading")))
6915 (defun org-goto-quit ()
6916 "Finish `org-goto' without cursor motion."
6917 (interactive)
6918 (setq org-goto-selected-point nil)
6919 (setq org-goto-exit-command 'quit)
6920 (throw 'exit nil))
6922 ;;; Indirect buffer display of subtrees
6924 (defvar org-indirect-dedicated-frame nil
6925 "This is the frame being used for indirect tree display.")
6926 (defvar org-last-indirect-buffer nil)
6928 (defun org-tree-to-indirect-buffer (&optional arg)
6929 "Create indirect buffer and narrow it to current subtree.
6930 With numerical prefix ARG, go up to this level and then take that tree.
6931 If ARG is negative, go up that many levels.
6932 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6933 indirect buffer previously made with this command, to avoid proliferation of
6934 indirect buffers. However, when you call the command with a \
6935 \\[universal-argument] prefix, or
6936 when `org-indirect-buffer-display' is `new-frame', the last buffer
6937 is kept so that you can work with several indirect buffers at the same time.
6938 If `org-indirect-buffer-display' is `dedicated-frame', the \
6939 \\[universal-argument] prefix also
6940 requests that a new frame be made for the new buffer, so that the dedicated
6941 frame is not changed."
6942 (interactive "P")
6943 (let ((cbuf (current-buffer))
6944 (cwin (selected-window))
6945 (pos (point))
6946 beg end level heading ibuf)
6947 (save-excursion
6948 (org-back-to-heading t)
6949 (when (numberp arg)
6950 (setq level (org-outline-level))
6951 (if (< arg 0) (setq arg (+ level arg)))
6952 (while (> (setq level (org-outline-level)) arg)
6953 (outline-up-heading 1 t)))
6954 (setq beg (point)
6955 heading (org-get-heading))
6956 (org-end-of-subtree t t)
6957 (if (org-on-heading-p) (backward-char 1))
6958 (setq end (point)))
6959 (if (and (buffer-live-p org-last-indirect-buffer)
6960 (not (eq org-indirect-buffer-display 'new-frame))
6961 (not arg))
6962 (kill-buffer org-last-indirect-buffer))
6963 (setq ibuf (org-get-indirect-buffer cbuf)
6964 org-last-indirect-buffer ibuf)
6965 (cond
6966 ((or (eq org-indirect-buffer-display 'new-frame)
6967 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6968 (select-frame (make-frame))
6969 (delete-other-windows)
6970 (org-pop-to-buffer-same-window ibuf)
6971 (org-set-frame-title heading))
6972 ((eq org-indirect-buffer-display 'dedicated-frame)
6973 (raise-frame
6974 (select-frame (or (and org-indirect-dedicated-frame
6975 (frame-live-p org-indirect-dedicated-frame)
6976 org-indirect-dedicated-frame)
6977 (setq org-indirect-dedicated-frame (make-frame)))))
6978 (delete-other-windows)
6979 (org-pop-to-buffer-same-window ibuf)
6980 (org-set-frame-title (concat "Indirect: " heading)))
6981 ((eq org-indirect-buffer-display 'current-window)
6982 (org-pop-to-buffer-same-window ibuf))
6983 ((eq org-indirect-buffer-display 'other-window)
6984 (pop-to-buffer ibuf))
6985 (t (error "Invalid value")))
6986 (if (featurep 'xemacs)
6987 (save-excursion (org-mode) (turn-on-font-lock)))
6988 (narrow-to-region beg end)
6989 (show-all)
6990 (goto-char pos)
6991 (run-hook-with-args 'org-cycle-hook 'all)
6992 (and (window-live-p cwin) (select-window cwin))))
6994 (defun org-get-indirect-buffer (&optional buffer)
6995 (setq buffer (or buffer (current-buffer)))
6996 (let ((n 1) (base (buffer-name buffer)) bname)
6997 (while (buffer-live-p
6998 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6999 (setq n (1+ n)))
7000 (condition-case nil
7001 (make-indirect-buffer buffer bname 'clone)
7002 (error (make-indirect-buffer buffer bname)))))
7004 (defun org-set-frame-title (title)
7005 "Set the title of the current frame to the string TITLE."
7006 ;; FIXME: how to name a single frame in XEmacs???
7007 (unless (featurep 'xemacs)
7008 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7010 ;;;; Structure editing
7012 ;;; Inserting headlines
7014 (defun org-previous-line-empty-p ()
7015 (save-excursion
7016 (and (not (bobp))
7017 (or (beginning-of-line 0) t)
7018 (save-match-data
7019 (looking-at "[ \t]*$")))))
7021 (defun org-insert-heading (&optional force-heading invisible-ok)
7022 "Insert a new heading or item with same depth at point.
7023 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7024 If point is at the beginning of a headline, insert a sibling before the
7025 current headline. If point is not at the beginning, split the line,
7026 create the new headline with the text in the current line after point
7027 \(but see also the variable `org-M-RET-may-split-line').
7029 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7030 This is important for non-interactive uses of the command."
7031 (interactive "P")
7032 (if (or (= (buffer-size) 0)
7033 (and (not (save-excursion
7034 (and (ignore-errors (org-back-to-heading invisible-ok))
7035 (org-on-heading-p))))
7036 (or force-heading (not (org-in-item-p)))))
7037 (progn
7038 (insert "\n* ")
7039 (run-hooks 'org-insert-heading-hook))
7040 (when (or force-heading (not (org-insert-item)))
7041 (let* ((empty-line-p nil)
7042 (level nil)
7043 (on-heading (org-on-heading-p))
7044 (head (save-excursion
7045 (condition-case nil
7046 (progn
7047 (org-back-to-heading invisible-ok)
7048 (when (and (not on-heading)
7049 (featurep 'org-inlinetask)
7050 (integerp org-inlinetask-min-level)
7051 (>= (length (match-string 0))
7052 org-inlinetask-min-level))
7053 ;; Find a heading level before the inline task
7054 (while (and (setq level (org-up-heading-safe))
7055 (>= level org-inlinetask-min-level)))
7056 (if (org-on-heading-p)
7057 (org-back-to-heading invisible-ok)
7058 (error "This should not happen")))
7059 (setq empty-line-p (org-previous-line-empty-p))
7060 (match-string 0))
7061 (error "*"))))
7062 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7063 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7064 pos hide-previous previous-pos)
7065 (cond
7066 ((and (org-on-heading-p) (bolp)
7067 (or (bobp)
7068 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7069 ;; insert before the current line
7070 (open-line (if blank 2 1)))
7071 ((and (bolp)
7072 (not org-insert-heading-respect-content)
7073 (or (bobp)
7074 (save-excursion
7075 (backward-char 1) (not (outline-invisible-p)))))
7076 ;; insert right here
7077 nil)
7079 ;; somewhere in the line
7080 (save-excursion
7081 (setq previous-pos (point-at-bol))
7082 (end-of-line)
7083 (setq hide-previous (outline-invisible-p)))
7084 (and org-insert-heading-respect-content (org-show-subtree))
7085 (let ((split
7086 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7087 (save-excursion
7088 (let ((p (point)))
7089 (goto-char (point-at-bol))
7090 (and (looking-at org-complex-heading-regexp)
7091 (match-beginning 4)
7092 (> p (match-beginning 4)))))))
7093 tags pos)
7094 (cond
7095 (org-insert-heading-respect-content
7096 (org-end-of-subtree nil t)
7097 (when (featurep 'org-inlinetask)
7098 (while (and (not (eobp))
7099 (looking-at "\\(\\*+\\)[ \t]+")
7100 (>= (length (match-string 1))
7101 org-inlinetask-min-level))
7102 (org-end-of-subtree nil t)))
7103 (or (bolp) (newline))
7104 (or (org-previous-line-empty-p)
7105 (and blank (newline)))
7106 (open-line 1))
7107 ((org-on-heading-p)
7108 (when hide-previous
7109 (show-children)
7110 (org-show-entry))
7111 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7112 (setq tags (and (match-end 2) (match-string 2)))
7113 (and (match-end 1)
7114 (delete-region (match-beginning 1) (match-end 1)))
7115 (setq pos (point-at-bol))
7116 (or split (end-of-line 1))
7117 (delete-horizontal-space)
7118 (if (string-match "\\`\\*+\\'"
7119 (buffer-substring (point-at-bol) (point)))
7120 (insert " "))
7121 (newline (if blank 2 1))
7122 (when tags
7123 (save-excursion
7124 (goto-char pos)
7125 (end-of-line 1)
7126 (insert " " tags)
7127 (org-set-tags nil 'align))))
7129 (or split (end-of-line 1))
7130 (newline (if blank 2 1)))))))
7131 (insert head) (just-one-space)
7132 (setq pos (point))
7133 (end-of-line 1)
7134 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7135 (when (and org-insert-heading-respect-content hide-previous)
7136 (save-excursion
7137 (goto-char previous-pos)
7138 (hide-subtree)))
7139 (run-hooks 'org-insert-heading-hook)))))
7141 (defun org-get-heading (&optional no-tags no-todo)
7142 "Return the heading of the current entry, without the stars.
7143 When NO-TAGS is non-nil, don't include tags.
7144 When NO-TODO is non-nil, don't include TODO keywords."
7145 (save-excursion
7146 (org-back-to-heading t)
7147 (cond
7148 ((and no-tags no-todo)
7149 (looking-at org-complex-heading-regexp)
7150 (match-string 4))
7151 (no-tags
7152 (looking-at (concat org-outline-regexp
7153 "\\(.*?\\)"
7154 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7155 (match-string 1))
7156 (no-todo
7157 (looking-at org-todo-line-regexp)
7158 (match-string 3))
7159 (t (looking-at org-heading-regexp)
7160 (match-string 2)))))
7162 (defun org-heading-components ()
7163 "Return the components of the current heading.
7164 This is a list with the following elements:
7165 - the level as an integer
7166 - the reduced level, different if `org-odd-levels-only' is set.
7167 - the TODO keyword, or nil
7168 - the priority character, like ?A, or nil if no priority is given
7169 - the headline text itself, or the tags string if no headline text
7170 - the tags string, or nil."
7171 (save-excursion
7172 (org-back-to-heading t)
7173 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7174 (list (length (match-string 1))
7175 (org-reduced-level (length (match-string 1)))
7176 (org-match-string-no-properties 2)
7177 (and (match-end 3) (aref (match-string 3) 2))
7178 (org-match-string-no-properties 4)
7179 (org-match-string-no-properties 5)))))
7181 (defun org-get-entry ()
7182 "Get the entry text, after heading, entire subtree."
7183 (save-excursion
7184 (org-back-to-heading t)
7185 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7187 (defun org-insert-heading-after-current ()
7188 "Insert a new heading with same level as current, after current subtree."
7189 (interactive)
7190 (org-back-to-heading)
7191 (org-insert-heading)
7192 (org-move-subtree-down)
7193 (end-of-line 1))
7195 (defun org-insert-heading-respect-content ()
7196 (interactive)
7197 (let ((org-insert-heading-respect-content t))
7198 (org-insert-heading t)))
7200 (defun org-insert-todo-heading-respect-content (&optional force-state)
7201 (interactive "P")
7202 (let ((org-insert-heading-respect-content t))
7203 (org-insert-todo-heading force-state t)))
7205 (defun org-insert-todo-heading (arg &optional force-heading)
7206 "Insert a new heading with the same level and TODO state as current heading.
7207 If the heading has no TODO state, or if the state is DONE, use the first
7208 state (TODO by default). Also with prefix arg, force first state."
7209 (interactive "P")
7210 (when (or force-heading (not (org-insert-item 'checkbox)))
7211 (org-insert-heading force-heading)
7212 (save-excursion
7213 (org-back-to-heading)
7214 (outline-previous-heading)
7215 (looking-at org-todo-line-regexp))
7216 (let*
7217 ((new-mark-x
7218 (if (or arg
7219 (not (match-beginning 2))
7220 (member (match-string 2) org-done-keywords))
7221 (car org-todo-keywords-1)
7222 (match-string 2)))
7223 (new-mark
7225 (run-hook-with-args-until-success
7226 'org-todo-get-default-hook new-mark-x nil)
7227 new-mark-x)))
7228 (beginning-of-line 1)
7229 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7230 (if org-treat-insert-todo-heading-as-state-change
7231 (org-todo new-mark)
7232 (insert new-mark " "))))
7233 (when org-provide-todo-statistics
7234 (org-update-parent-todo-statistics))))
7236 (defun org-insert-subheading (arg)
7237 "Insert a new subheading and demote it.
7238 Works for outline headings and for plain lists alike."
7239 (interactive "P")
7240 (org-insert-heading arg)
7241 (cond
7242 ((org-on-heading-p) (org-do-demote))
7243 ((org-at-item-p) (org-indent-item))))
7245 (defun org-insert-todo-subheading (arg)
7246 "Insert a new subheading with TODO keyword or checkbox and demote it.
7247 Works for outline headings and for plain lists alike."
7248 (interactive "P")
7249 (org-insert-todo-heading arg)
7250 (cond
7251 ((org-on-heading-p) (org-do-demote))
7252 ((org-at-item-p) (org-indent-item))))
7254 ;;; Promotion and Demotion
7256 (defvar org-after-demote-entry-hook nil
7257 "Hook run after an entry has been demoted.
7258 The cursor will be at the beginning of the entry.
7259 When a subtree is being demoted, the hook will be called for each node.")
7261 (defvar org-after-promote-entry-hook nil
7262 "Hook run after an entry has been promoted.
7263 The cursor will be at the beginning of the entry.
7264 When a subtree is being promoted, the hook will be called for each node.")
7266 (defun org-promote-subtree ()
7267 "Promote the entire subtree.
7268 See also `org-promote'."
7269 (interactive)
7270 (save-excursion
7271 (org-with-limited-levels (org-map-tree 'org-promote)))
7272 (org-fix-position-after-promote))
7274 (defun org-demote-subtree ()
7275 "Demote the entire subtree. See `org-demote'.
7276 See also `org-promote'."
7277 (interactive)
7278 (save-excursion
7279 (org-with-limited-levels (org-map-tree 'org-demote)))
7280 (org-fix-position-after-promote))
7283 (defun org-do-promote ()
7284 "Promote the current heading higher up the tree.
7285 If the region is active in `transient-mark-mode', promote all headings
7286 in the region."
7287 (interactive)
7288 (save-excursion
7289 (if (org-region-active-p)
7290 (org-map-region 'org-promote (region-beginning) (region-end))
7291 (org-promote)))
7292 (org-fix-position-after-promote))
7294 (defun org-do-demote ()
7295 "Demote the current heading lower down the tree.
7296 If the region is active in `transient-mark-mode', demote all headings
7297 in the region."
7298 (interactive)
7299 (save-excursion
7300 (if (org-region-active-p)
7301 (org-map-region 'org-demote (region-beginning) (region-end))
7302 (org-demote)))
7303 (org-fix-position-after-promote))
7305 (defun org-fix-position-after-promote ()
7306 "Make sure that after pro/demotion cursor position is right."
7307 (let ((pos (point)))
7308 (when (save-excursion
7309 (beginning-of-line 1)
7310 (looking-at org-todo-line-regexp)
7311 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7312 (cond ((eobp) (insert " "))
7313 ((eolp) (insert " "))
7314 ((equal (char-after) ?\ ) (forward-char 1))))))
7316 (defun org-current-level ()
7317 "Return the level of the current entry, or nil if before the first headline.
7318 The level is the number of stars at the beginning of the headline."
7319 (save-excursion
7320 (org-with-limited-levels
7321 (if (ignore-errors (org-back-to-heading t))
7322 (funcall outline-level)))))
7324 (defun org-get-previous-line-level ()
7325 "Return the outline depth of the last headline before the current line.
7326 Returns 0 for the first headline in the buffer, and nil if before the
7327 first headline."
7328 (let ((current-level (org-current-level))
7329 (prev-level (when (> (line-number-at-pos) 1)
7330 (save-excursion
7331 (beginning-of-line 0)
7332 (org-current-level)))))
7333 (cond ((null current-level) nil) ; Before first headline
7334 ((null prev-level) 0) ; At first headline
7335 (prev-level))))
7337 (defun org-reduced-level (l)
7338 "Compute the effective level of a heading.
7339 This takes into account the setting of `org-odd-levels-only'."
7340 (cond
7341 ((zerop l) 0)
7342 (org-odd-levels-only (1+ (floor (/ l 2))))
7343 (t l)))
7345 (defun org-level-increment ()
7346 "Return the number of stars that will be added or removed at a
7347 time to headlines when structure editing, based on the value of
7348 `org-odd-levels-only'."
7349 (if org-odd-levels-only 2 1))
7351 (defun org-get-valid-level (level &optional change)
7352 "Rectify a level change under the influence of `org-odd-levels-only'
7353 LEVEL is a current level, CHANGE is by how much the level should be
7354 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7355 even level numbers will become the next higher odd number."
7356 (if org-odd-levels-only
7357 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7358 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7359 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7360 (max 1 (+ level (or change 0)))))
7362 (if (boundp 'define-obsolete-function-alias)
7363 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7364 (define-obsolete-function-alias 'org-get-legal-level
7365 'org-get-valid-level)
7366 (define-obsolete-function-alias 'org-get-legal-level
7367 'org-get-valid-level "23.1")))
7369 (defun org-promote ()
7370 "Promote the current heading higher up the tree.
7371 If the region is active in `transient-mark-mode', promote all headings
7372 in the region."
7373 (org-back-to-heading t)
7374 (let* ((level (save-match-data (funcall outline-level)))
7375 (after-change-functions (remove 'flyspell-after-change-function
7376 after-change-functions))
7377 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7378 (diff (abs (- level (length up-head) -1))))
7379 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
7380 (replace-match up-head nil t)
7381 ;; Fixup tag positioning
7382 (and org-auto-align-tags (org-set-tags nil t))
7383 (if org-adapt-indentation (org-fixup-indentation (- diff)))
7384 (run-hooks 'org-after-promote-entry-hook)))
7386 (defun org-demote ()
7387 "Demote the current heading lower down the tree.
7388 If the region is active in `transient-mark-mode', demote all headings
7389 in the region."
7390 (org-back-to-heading t)
7391 (let* ((level (save-match-data (funcall outline-level)))
7392 (after-change-functions (remove 'flyspell-after-change-function
7393 after-change-functions))
7394 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7395 (diff (abs (- level (length down-head) -1))))
7396 (replace-match down-head nil t)
7397 ;; Fixup tag positioning
7398 (and org-auto-align-tags (org-set-tags nil t))
7399 (if org-adapt-indentation (org-fixup-indentation diff))
7400 (run-hooks 'org-after-demote-entry-hook)))
7402 (defun org-cycle-level ()
7403 "Cycle the level of an empty headline through possible states.
7404 This goes first to child, then to parent, level, then up the hierarchy.
7405 After top level, it switches back to sibling level."
7406 (interactive)
7407 (let ((org-adapt-indentation nil))
7408 (when (org-point-at-end-of-empty-headline)
7409 (setq this-command 'org-cycle-level) ; Only needed for caching
7410 (let ((cur-level (org-current-level))
7411 (prev-level (org-get-previous-line-level)))
7412 (cond
7413 ;; If first headline in file, promote to top-level.
7414 ((= prev-level 0)
7415 (loop repeat (/ (- cur-level 1) (org-level-increment))
7416 do (org-do-promote)))
7417 ;; If same level as prev, demote one.
7418 ((= prev-level cur-level)
7419 (org-do-demote))
7420 ;; If parent is top-level, promote to top level if not already.
7421 ((= prev-level 1)
7422 (loop repeat (/ (- cur-level 1) (org-level-increment))
7423 do (org-do-promote)))
7424 ;; If top-level, return to prev-level.
7425 ((= cur-level 1)
7426 (loop repeat (/ (- prev-level 1) (org-level-increment))
7427 do (org-do-demote)))
7428 ;; If less than prev-level, promote one.
7429 ((< cur-level prev-level)
7430 (org-do-promote))
7431 ;; If deeper than prev-level, promote until higher than
7432 ;; prev-level.
7433 ((> cur-level prev-level)
7434 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7435 do (org-do-promote))))
7436 t))))
7438 (defun org-map-tree (fun)
7439 "Call FUN for every heading underneath the current one."
7440 (org-back-to-heading)
7441 (let ((level (funcall outline-level)))
7442 (save-excursion
7443 (funcall fun)
7444 (while (and (progn
7445 (outline-next-heading)
7446 (> (funcall outline-level) level))
7447 (not (eobp)))
7448 (funcall fun)))))
7450 (defun org-map-region (fun beg end)
7451 "Call FUN for every heading between BEG and END."
7452 (let ((org-ignore-region t))
7453 (save-excursion
7454 (setq end (copy-marker end))
7455 (goto-char beg)
7456 (if (and (re-search-forward org-outline-regexp-bol nil t)
7457 (< (point) end))
7458 (funcall fun))
7459 (while (and (progn
7460 (outline-next-heading)
7461 (< (point) end))
7462 (not (eobp)))
7463 (funcall fun)))))
7465 (defvar org-property-end-re) ; silence byte-compiler
7466 (defun org-fixup-indentation (diff)
7467 "Change the indentation in the current entry by DIFF.
7468 However, if any line in the current entry has no indentation, or if it
7469 would end up with no indentation after the change, nothing at all is done."
7470 (save-excursion
7471 (let ((end (save-excursion (outline-next-heading)
7472 (point-marker)))
7473 (prohibit (if (> diff 0)
7474 "^\\S-"
7475 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7476 col)
7477 (unless (save-excursion (end-of-line 1)
7478 (re-search-forward prohibit end t))
7479 (while (and (< (point) end)
7480 (re-search-forward "^[ \t]+" end t))
7481 (goto-char (match-end 0))
7482 (setq col (current-column))
7483 (if (< diff 0) (replace-match ""))
7484 (org-indent-to-column (+ diff col))))
7485 (move-marker end nil))))
7487 (defun org-convert-to-odd-levels ()
7488 "Convert an org-mode file with all levels allowed to one with odd levels.
7489 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7490 level 5 etc."
7491 (interactive)
7492 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7493 (let ((outline-level 'org-outline-level)
7494 (org-odd-levels-only nil) n)
7495 (save-excursion
7496 (goto-char (point-min))
7497 (while (re-search-forward "^\\*\\*+ " nil t)
7498 (setq n (- (length (match-string 0)) 2))
7499 (while (>= (setq n (1- n)) 0)
7500 (org-demote))
7501 (end-of-line 1))))))
7503 (defun org-convert-to-oddeven-levels ()
7504 "Convert an org-mode file with only odd levels to one with odd/even levels.
7505 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7506 file contains a section with an even level, conversion would
7507 destroy the structure of the file. An error is signaled in this
7508 case."
7509 (interactive)
7510 (goto-char (point-min))
7511 ;; First check if there are no even levels
7512 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7513 (org-show-context t)
7514 (error "Not all levels are odd in this file. Conversion not possible"))
7515 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7516 (let ((outline-regexp org-outline-regexp)
7517 (outline-level 'org-outline-level)
7518 (org-odd-levels-only nil) n)
7519 (save-excursion
7520 (goto-char (point-min))
7521 (while (re-search-forward "^\\*\\*+ " nil t)
7522 (setq n (/ (1- (length (match-string 0))) 2))
7523 (while (>= (setq n (1- n)) 0)
7524 (org-promote))
7525 (end-of-line 1))))))
7527 (defun org-tr-level (n)
7528 "Make N odd if required."
7529 (if org-odd-levels-only (1+ (/ n 2)) n))
7531 ;;; Vertical tree motion, cutting and pasting of subtrees
7533 (defun org-move-subtree-up (&optional arg)
7534 "Move the current subtree up past ARG headlines of the same level."
7535 (interactive "p")
7536 (org-move-subtree-down (- (prefix-numeric-value arg))))
7538 (defun org-move-subtree-down (&optional arg)
7539 "Move the current subtree down past ARG headlines of the same level."
7540 (interactive "p")
7541 (setq arg (prefix-numeric-value arg))
7542 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7543 'org-get-last-sibling))
7544 (ins-point (make-marker))
7545 (cnt (abs arg))
7546 (col (current-column))
7547 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7548 ;; Select the tree
7549 (org-back-to-heading)
7550 (setq beg0 (point))
7551 (save-excursion
7552 (setq ne-beg (org-back-over-empty-lines))
7553 (setq beg (point)))
7554 (save-match-data
7555 (save-excursion (outline-end-of-heading)
7556 (setq folded (outline-invisible-p)))
7557 (outline-end-of-subtree))
7558 (outline-next-heading)
7559 (setq ne-end (org-back-over-empty-lines))
7560 (setq end (point))
7561 (goto-char beg0)
7562 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7563 ;; include less whitespace
7564 (save-excursion
7565 (goto-char beg)
7566 (forward-line (- ne-beg ne-end))
7567 (setq beg (point))))
7568 ;; Find insertion point, with error handling
7569 (while (> cnt 0)
7570 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7571 (progn (goto-char beg0)
7572 (error "Cannot move past superior level or buffer limit")))
7573 (setq cnt (1- cnt)))
7574 (if (> arg 0)
7575 ;; Moving forward - still need to move over subtree
7576 (progn (org-end-of-subtree t t)
7577 (save-excursion
7578 (org-back-over-empty-lines)
7579 (or (bolp) (newline)))))
7580 (setq ne-ins (org-back-over-empty-lines))
7581 (move-marker ins-point (point))
7582 (setq txt (buffer-substring beg end))
7583 (org-save-markers-in-region beg end)
7584 (delete-region beg end)
7585 (org-remove-empty-overlays-at beg)
7586 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7587 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7588 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7589 (let ((bbb (point)))
7590 (insert-before-markers txt)
7591 (org-reinstall-markers-in-region bbb)
7592 (move-marker ins-point bbb))
7593 (or (bolp) (insert "\n"))
7594 (setq ins-end (point))
7595 (goto-char ins-point)
7596 (org-skip-whitespace)
7597 (when (and (< arg 0)
7598 (org-first-sibling-p)
7599 (> ne-ins ne-beg))
7600 ;; Move whitespace back to beginning
7601 (save-excursion
7602 (goto-char ins-end)
7603 (let ((kill-whole-line t))
7604 (kill-line (- ne-ins ne-beg)) (point)))
7605 (insert (make-string (- ne-ins ne-beg) ?\n)))
7606 (move-marker ins-point nil)
7607 (if folded
7608 (hide-subtree)
7609 (org-show-entry)
7610 (show-children)
7611 (org-cycle-hide-drawers 'children))
7612 (org-clean-visibility-after-subtree-move)
7613 ;; move back to the initial column we were at
7614 (move-to-column col)))
7616 (defvar org-subtree-clip ""
7617 "Clipboard for cut and paste of subtrees.
7618 This is actually only a copy of the kill, because we use the normal kill
7619 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7621 (defvar org-subtree-clip-folded nil
7622 "Was the last copied subtree folded?
7623 This is used to fold the tree back after pasting.")
7625 (defun org-cut-subtree (&optional n)
7626 "Cut the current subtree into the clipboard.
7627 With prefix arg N, cut this many sequential subtrees.
7628 This is a short-hand for marking the subtree and then cutting it."
7629 (interactive "p")
7630 (org-copy-subtree n 'cut))
7632 (defun org-copy-subtree (&optional n cut force-store-markers)
7633 "Cut the current subtree into the clipboard.
7634 With prefix arg N, cut this many sequential subtrees.
7635 This is a short-hand for marking the subtree and then copying it.
7636 If CUT is non-nil, actually cut the subtree.
7637 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7638 of some markers in the region, even if CUT is non-nil. This is
7639 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7640 (interactive "p")
7641 (let (beg end folded (beg0 (point)))
7642 (if (org-called-interactively-p 'any)
7643 (org-back-to-heading nil) ; take what looks like a subtree
7644 (org-back-to-heading t)) ; take what is really there
7645 (org-back-over-empty-lines)
7646 (setq beg (point))
7647 (skip-chars-forward " \t\r\n")
7648 (save-match-data
7649 (save-excursion (outline-end-of-heading)
7650 (setq folded (outline-invisible-p)))
7651 (condition-case nil
7652 (org-forward-same-level (1- n) t)
7653 (error nil))
7654 (org-end-of-subtree t t))
7655 (org-back-over-empty-lines)
7656 (setq end (point))
7657 (goto-char beg0)
7658 (when (> end beg)
7659 (setq org-subtree-clip-folded folded)
7660 (when (or cut force-store-markers)
7661 (org-save-markers-in-region beg end))
7662 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7663 (setq org-subtree-clip (current-kill 0))
7664 (message "%s: Subtree(s) with %d characters"
7665 (if cut "Cut" "Copied")
7666 (length org-subtree-clip)))))
7668 (defun org-paste-subtree (&optional level tree for-yank)
7669 "Paste the clipboard as a subtree, with modification of headline level.
7670 The entire subtree is promoted or demoted in order to match a new headline
7671 level.
7673 If the cursor is at the beginning of a headline, the same level as
7674 that headline is used to paste the tree
7676 If not, the new level is derived from the *visible* headings
7677 before and after the insertion point, and taken to be the inferior headline
7678 level of the two. So if the previous visible heading is level 3 and the
7679 next is level 4 (or vice versa), level 4 will be used for insertion.
7680 This makes sure that the subtree remains an independent subtree and does
7681 not swallow low level entries.
7683 You can also force a different level, either by using a numeric prefix
7684 argument, or by inserting the heading marker by hand. For example, if the
7685 cursor is after \"*****\", then the tree will be shifted to level 5.
7687 If optional TREE is given, use this text instead of the kill ring.
7689 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7690 move back over whitespace before inserting, and move point to the end of
7691 the inserted text when done."
7692 (interactive "P")
7693 (setq tree (or tree (and kill-ring (current-kill 0))))
7694 (unless (org-kill-is-subtree-p tree)
7695 (error "%s"
7696 (substitute-command-keys
7697 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7698 (org-with-limited-levels
7699 (let* ((visp (not (outline-invisible-p)))
7700 (txt tree)
7701 (^re_ "\\(\\*+\\)[ \t]*")
7702 (old-level (if (string-match org-outline-regexp-bol txt)
7703 (- (match-end 0) (match-beginning 0) 1)
7704 -1))
7705 (force-level (cond (level (prefix-numeric-value level))
7706 ((and (looking-at "[ \t]*$")
7707 (string-match
7708 "^\\*+$" (buffer-substring
7709 (point-at-bol) (point))))
7710 (- (match-end 1) (match-beginning 1)))
7711 ((and (bolp)
7712 (looking-at org-outline-regexp))
7713 (- (match-end 0) (point) 1))
7714 (t nil)))
7715 (previous-level (save-excursion
7716 (condition-case nil
7717 (progn
7718 (outline-previous-visible-heading 1)
7719 (if (looking-at ^re_)
7720 (- (match-end 0) (match-beginning 0) 1)
7722 (error 1))))
7723 (next-level (save-excursion
7724 (condition-case nil
7725 (progn
7726 (or (looking-at org-outline-regexp)
7727 (outline-next-visible-heading 1))
7728 (if (looking-at ^re_)
7729 (- (match-end 0) (match-beginning 0) 1)
7731 (error 1))))
7732 (new-level (or force-level (max previous-level next-level)))
7733 (shift (if (or (= old-level -1)
7734 (= new-level -1)
7735 (= old-level new-level))
7737 (- new-level old-level)))
7738 (delta (if (> shift 0) -1 1))
7739 (func (if (> shift 0) 'org-demote 'org-promote))
7740 (org-odd-levels-only nil)
7741 beg end newend)
7742 ;; Remove the forced level indicator
7743 (if force-level
7744 (delete-region (point-at-bol) (point)))
7745 ;; Paste
7746 (beginning-of-line (if (bolp) 1 2))
7747 (unless for-yank (org-back-over-empty-lines))
7748 (setq beg (point))
7749 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7750 (insert-before-markers txt)
7751 (unless (string-match "\n\\'" txt) (insert "\n"))
7752 (setq newend (point))
7753 (org-reinstall-markers-in-region beg)
7754 (setq end (point))
7755 (goto-char beg)
7756 (skip-chars-forward " \t\n\r")
7757 (setq beg (point))
7758 (if (and (outline-invisible-p) visp)
7759 (save-excursion (outline-show-heading)))
7760 ;; Shift if necessary
7761 (unless (= shift 0)
7762 (save-restriction
7763 (narrow-to-region beg end)
7764 (while (not (= shift 0))
7765 (org-map-region func (point-min) (point-max))
7766 (setq shift (+ delta shift)))
7767 (goto-char (point-min))
7768 (setq newend (point-max))))
7769 (when (or (org-called-interactively-p 'interactive) for-yank)
7770 (message "Clipboard pasted as level %d subtree" new-level))
7771 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7772 kill-ring
7773 (eq org-subtree-clip (current-kill 0))
7774 org-subtree-clip-folded)
7775 ;; The tree was folded before it was killed/copied
7776 (hide-subtree))
7777 (and for-yank (goto-char newend)))))
7779 (defun org-kill-is-subtree-p (&optional txt)
7780 "Check if the current kill is an outline subtree, or a set of trees.
7781 Returns nil if kill does not start with a headline, or if the first
7782 headline level is not the largest headline level in the tree.
7783 So this will actually accept several entries of equal levels as well,
7784 which is OK for `org-paste-subtree'.
7785 If optional TXT is given, check this string instead of the current kill."
7786 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7787 (re (org-get-limited-outline-regexp))
7788 (^re (concat "^" re))
7789 (start-level (and kill
7790 (string-match
7791 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7792 kill)
7793 (- (match-end 2) (match-beginning 2) 1)))
7794 (start (1+ (or (match-beginning 2) -1))))
7795 (if (not start-level)
7796 (progn
7797 nil) ;; does not even start with a heading
7798 (catch 'exit
7799 (while (setq start (string-match ^re kill (1+ start)))
7800 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7801 (throw 'exit nil)))
7802 t))))
7804 (defvar org-markers-to-move nil
7805 "Markers that should be moved with a cut-and-paste operation.
7806 Those markers are stored together with their positions relative to
7807 the start of the region.")
7809 (defun org-save-markers-in-region (beg end)
7810 "Check markers in region.
7811 If these markers are between BEG and END, record their position relative
7812 to BEG, so that after moving the block of text, we can put the markers back
7813 into place.
7814 This function gets called just before an entry or tree gets cut from the
7815 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7816 called immediately, to move the markers with the entries."
7817 (setq org-markers-to-move nil)
7818 (when (featurep 'org-clock)
7819 (org-clock-save-markers-for-cut-and-paste beg end))
7820 (when (featurep 'org-agenda)
7821 (org-agenda-save-markers-for-cut-and-paste beg end)))
7823 (defun org-check-and-save-marker (marker beg end)
7824 "Check if MARKER is between BEG and END.
7825 If yes, remember the marker and the distance to BEG."
7826 (when (and (marker-buffer marker)
7827 (equal (marker-buffer marker) (current-buffer)))
7828 (if (and (>= marker beg) (< marker end))
7829 (push (cons marker (- marker beg)) org-markers-to-move))))
7831 (defun org-reinstall-markers-in-region (beg)
7832 "Move all remembered markers to their position relative to BEG."
7833 (mapc (lambda (x)
7834 (move-marker (car x) (+ beg (cdr x))))
7835 org-markers-to-move)
7836 (setq org-markers-to-move nil))
7838 (defun org-narrow-to-subtree ()
7839 "Narrow buffer to the current subtree."
7840 (interactive)
7841 (save-excursion
7842 (save-match-data
7843 (org-with-limited-levels
7844 (narrow-to-region
7845 (progn (org-back-to-heading t) (point))
7846 (progn (org-end-of-subtree t t)
7847 (if (and (org-on-heading-p) (not (eobp))) (backward-char 1))
7848 (point)))))))
7850 (defun org-narrow-to-block ()
7851 "Narrow buffer to the current block."
7852 (interactive)
7853 (let* ((case-fold-search t)
7854 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7855 "^[ \t]*#\\+end_.*")))
7856 (if blockp
7857 (narrow-to-region (car blockp) (cdr blockp))
7858 (error "Not in a block"))))
7860 (eval-when-compile
7861 (defvar org-property-drawer-re))
7863 (defvar org-property-start-re) ;; defined below
7864 (defun org-clone-subtree-with-time-shift (n &optional shift)
7865 "Clone the task (subtree) at point N times.
7866 The clones will be inserted as siblings.
7868 In interactive use, the user will be prompted for the number of
7869 clones to be produced, and for a time SHIFT, which may be a
7870 repeater as used in time stamps, for example `+3d'.
7872 When a valid repeater is given and the entry contains any time
7873 stamps, the clones will become a sequence in time, with time
7874 stamps in the subtree shifted for each clone produced. If SHIFT
7875 is nil or the empty string, time stamps will be left alone. The
7876 ID property of the original subtree is removed.
7878 If the original subtree did contain time stamps with a repeater,
7879 the following will happen:
7880 - the repeater will be removed in each clone
7881 - an additional clone will be produced, with the current, unshifted
7882 date(s) in the entry.
7883 - the original entry will be placed *after* all the clones, with
7884 repeater intact.
7885 - the start days in the repeater in the original entry will be shifted
7886 to past the last clone.
7887 I this way you can spell out a number of instances of a repeating task,
7888 and still retain the repeater to cover future instances of the task."
7889 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7890 (let (beg end template task idprop
7891 shift-n shift-what doshift nmin nmax (n-no-remove -1)
7892 (drawer-re org-drawer-regexp))
7893 (if (not (and (integerp n) (> n 0)))
7894 (error "Invalid number of replications %s" n))
7895 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7896 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
7897 shift)))
7898 (error "Invalid shift specification %s" shift))
7899 (when doshift
7900 (setq shift-n (string-to-number (match-string 1 shift))
7901 shift-what (cdr (assoc (match-string 2 shift)
7902 '(("d" . day) ("w" . week)
7903 ("m" . month) ("y" . year))))))
7904 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7905 (setq nmin 1 nmax n)
7906 (org-back-to-heading t)
7907 (setq beg (point))
7908 (setq idprop (org-entry-get nil "ID"))
7909 (org-end-of-subtree t t)
7910 (or (bolp) (insert "\n"))
7911 (setq end (point))
7912 (setq template (buffer-substring beg end))
7913 (when (and doshift
7914 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
7915 (delete-region beg end)
7916 (setq end beg)
7917 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7918 (goto-char end)
7919 (loop for n from nmin to nmax do
7920 ;; prepare clone
7921 (with-temp-buffer
7922 (insert template)
7923 (org-mode)
7924 (goto-char (point-min))
7925 (org-show-subtree)
7926 (and idprop (if org-clone-delete-id
7927 (org-entry-delete nil "ID")
7928 (org-id-get-create t)))
7929 (unless (= n 0)
7930 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
7931 (kill-whole-line))
7932 (goto-char (point-min))
7933 (while (re-search-forward drawer-re nil t)
7934 (mapc (lambda (d)
7935 (org-remove-empty-drawer-at d (point))) org-drawers)))
7936 (goto-char (point-min))
7937 (when doshift
7938 (while (re-search-forward org-ts-regexp-both nil t)
7939 (org-timestamp-change (* n shift-n) shift-what))
7940 (unless (= n n-no-remove)
7941 (goto-char (point-min))
7942 (while (re-search-forward org-ts-regexp nil t)
7943 (save-excursion
7944 (goto-char (match-beginning 0))
7945 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
7946 (delete-region (match-beginning 1) (match-end 1)))))))
7947 (setq task (buffer-string)))
7948 (insert task))
7949 (goto-char beg)))
7951 ;;; Outline Sorting
7953 (defun org-sort (with-case)
7954 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
7955 Optional argument WITH-CASE means sort case-sensitively.
7956 With a double prefix argument, also remove duplicate entries."
7957 (interactive "P")
7958 (cond
7959 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
7960 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
7962 (org-call-with-arg 'org-sort-entries with-case))))
7964 (defun org-sort-remove-invisible (s)
7965 (remove-text-properties 0 (length s) org-rm-props s)
7966 (while (string-match org-bracket-link-regexp s)
7967 (setq s (replace-match (if (match-end 2)
7968 (match-string 3 s)
7969 (match-string 1 s)) t t s)))
7972 (defvar org-priority-regexp) ; defined later in the file
7974 (defvar org-after-sorting-entries-or-items-hook nil
7975 "Hook that is run after a bunch of entries or items have been sorted.
7976 When children are sorted, the cursor is in the parent line when this
7977 hook gets called. When a region or a plain list is sorted, the cursor
7978 will be in the first entry of the sorted region/list.")
7980 (defun org-sort-entries
7981 (&optional with-case sorting-type getkey-func compare-func property)
7982 "Sort entries on a certain level of an outline tree.
7983 If there is an active region, the entries in the region are sorted.
7984 Else, if the cursor is before the first entry, sort the top-level items.
7985 Else, the children of the entry at point are sorted.
7987 Sorting can be alphabetically, numerically, by date/time as given by
7988 a time stamp, by a property or by priority.
7990 The command prompts for the sorting type unless it has been given to the
7991 function through the SORTING-TYPE argument, which needs to be a character,
7992 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
7993 precise meaning of each character:
7995 n Numerically, by converting the beginning of the entry/item to a number.
7996 a Alphabetically, ignoring the TODO keyword and the priority, if any.
7997 t By date/time, either the first active time stamp in the entry, or, if
7998 none exist, by the first inactive one.
7999 s By the scheduled date/time.
8000 d By deadline date/time.
8001 c By creation time, which is assumed to be the first inactive time stamp
8002 at the beginning of a line.
8003 p By priority according to the cookie.
8004 r By the value of a property.
8006 Capital letters will reverse the sort order.
8008 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8009 called with point at the beginning of the record. It must return either
8010 a string or a number that should serve as the sorting key for that record.
8012 Comparing entries ignores case by default. However, with an optional argument
8013 WITH-CASE, the sorting considers case as well."
8014 (interactive "P")
8015 (let ((case-func (if with-case 'identity 'downcase))
8016 start beg end stars re re2
8017 txt what tmp)
8018 ;; Find beginning and end of region to sort
8019 (cond
8020 ((org-region-active-p)
8021 ;; we will sort the region
8022 (setq end (region-end)
8023 what "region")
8024 (goto-char (region-beginning))
8025 (if (not (org-on-heading-p)) (outline-next-heading))
8026 (setq start (point)))
8027 ((or (org-on-heading-p)
8028 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8029 ;; we will sort the children of the current headline
8030 (org-back-to-heading)
8031 (setq start (point)
8032 end (progn (org-end-of-subtree t t)
8033 (or (bolp) (insert "\n"))
8034 (org-back-over-empty-lines)
8035 (point))
8036 what "children")
8037 (goto-char start)
8038 (show-subtree)
8039 (outline-next-heading))
8041 ;; we will sort the top-level entries in this file
8042 (goto-char (point-min))
8043 (or (org-on-heading-p) (outline-next-heading))
8044 (setq start (point))
8045 (goto-char (point-max))
8046 (beginning-of-line 1)
8047 (when (looking-at ".*?\\S-")
8048 ;; File ends in a non-white line
8049 (end-of-line 1)
8050 (insert "\n"))
8051 (setq end (point-max))
8052 (setq what "top-level")
8053 (goto-char start)
8054 (show-all)))
8056 (setq beg (point))
8057 (if (>= beg end) (error "Nothing to sort"))
8059 (looking-at "\\(\\*+\\)")
8060 (setq stars (match-string 1)
8061 re (concat "^" (regexp-quote stars) " +")
8062 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8063 txt (buffer-substring beg end))
8064 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8065 (if (and (not (equal stars "*")) (string-match re2 txt))
8066 (error "Region to sort contains a level above the first entry"))
8068 (unless sorting-type
8069 (message
8070 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8071 [t]ime [s]cheduled [d]eadline [c]reated
8072 A/N/T/S/D/C/P/O/F means reversed:"
8073 what)
8074 (setq sorting-type (read-char-exclusive))
8076 (and (= (downcase sorting-type) ?f)
8077 (setq getkey-func
8078 (org-icompleting-read "Sort using function: "
8079 obarray 'fboundp t nil nil))
8080 (setq getkey-func (intern getkey-func)))
8082 (and (= (downcase sorting-type) ?r)
8083 (setq property
8084 (org-icompleting-read "Property: "
8085 (mapcar 'list (org-buffer-property-keys t))
8086 nil t))))
8088 (message "Sorting entries...")
8090 (save-restriction
8091 (narrow-to-region start end)
8092 (let ((dcst (downcase sorting-type))
8093 (case-fold-search nil)
8094 (now (current-time)))
8095 (sort-subr
8096 (/= dcst sorting-type)
8097 ;; This function moves to the beginning character of the "record" to
8098 ;; be sorted.
8099 (lambda nil
8100 (if (re-search-forward re nil t)
8101 (goto-char (match-beginning 0))
8102 (goto-char (point-max))))
8103 ;; This function moves to the last character of the "record" being
8104 ;; sorted.
8105 (lambda nil
8106 (save-match-data
8107 (condition-case nil
8108 (outline-forward-same-level 1)
8109 (error
8110 (goto-char (point-max))))))
8111 ;; This function returns the value that gets sorted against.
8112 (lambda nil
8113 (cond
8114 ((= dcst ?n)
8115 (if (looking-at org-complex-heading-regexp)
8116 (string-to-number (match-string 4))
8117 nil))
8118 ((= dcst ?a)
8119 (if (looking-at org-complex-heading-regexp)
8120 (funcall case-func (match-string 4))
8121 nil))
8122 ((= dcst ?t)
8123 (let ((end (save-excursion (outline-next-heading) (point))))
8124 (if (or (re-search-forward org-ts-regexp end t)
8125 (re-search-forward org-ts-regexp-both end t))
8126 (org-time-string-to-seconds (match-string 0))
8127 (org-float-time now))))
8128 ((= dcst ?c)
8129 (let ((end (save-excursion (outline-next-heading) (point))))
8130 (if (re-search-forward
8131 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8132 end t)
8133 (org-time-string-to-seconds (match-string 0))
8134 (org-float-time now))))
8135 ((= dcst ?s)
8136 (let ((end (save-excursion (outline-next-heading) (point))))
8137 (if (re-search-forward org-scheduled-time-regexp end t)
8138 (org-time-string-to-seconds (match-string 1))
8139 (org-float-time now))))
8140 ((= dcst ?d)
8141 (let ((end (save-excursion (outline-next-heading) (point))))
8142 (if (re-search-forward org-deadline-time-regexp end t)
8143 (org-time-string-to-seconds (match-string 1))
8144 (org-float-time now))))
8145 ((= dcst ?p)
8146 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8147 (string-to-char (match-string 2))
8148 org-default-priority))
8149 ((= dcst ?r)
8150 (or (org-entry-get nil property) ""))
8151 ((= dcst ?o)
8152 (if (looking-at org-complex-heading-regexp)
8153 (- 9999 (length (member (match-string 2)
8154 org-todo-keywords-1)))))
8155 ((= dcst ?f)
8156 (if getkey-func
8157 (progn
8158 (setq tmp (funcall getkey-func))
8159 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8160 tmp)
8161 (error "Invalid key function `%s'" getkey-func)))
8162 (t (error "Invalid sorting type `%c'" sorting-type))))
8164 (cond
8165 ((= dcst ?a) 'string<)
8166 ((= dcst ?f) compare-func)
8167 ((member dcst '(?p ?t ?s ?d ?c)) '<)
8168 (t nil)))))
8169 (run-hooks 'org-after-sorting-entries-or-items-hook)
8170 (message "Sorting entries...done")))
8172 (defun org-do-sort (table what &optional with-case sorting-type)
8173 "Sort TABLE of WHAT according to SORTING-TYPE.
8174 The user will be prompted for the SORTING-TYPE if the call to this
8175 function does not specify it. WHAT is only for the prompt, to indicate
8176 what is being sorted. The sorting key will be extracted from
8177 the car of the elements of the table.
8178 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8179 (unless sorting-type
8180 (message
8181 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8182 what)
8183 (setq sorting-type (read-char-exclusive)))
8184 (let ((dcst (downcase sorting-type))
8185 extractfun comparefun)
8186 ;; Define the appropriate functions
8187 (cond
8188 ((= dcst ?n)
8189 (setq extractfun 'string-to-number
8190 comparefun (if (= dcst sorting-type) '< '>)))
8191 ((= dcst ?a)
8192 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8193 (lambda(x) (downcase (org-sort-remove-invisible x))))
8194 comparefun (if (= dcst sorting-type)
8195 'string<
8196 (lambda (a b) (and (not (string< a b))
8197 (not (string= a b)))))))
8198 ((= dcst ?t)
8199 (setq extractfun
8200 (lambda (x)
8201 (if (or (string-match org-ts-regexp x)
8202 (string-match org-ts-regexp-both x))
8203 (org-float-time
8204 (org-time-string-to-time (match-string 0 x)))
8206 comparefun (if (= dcst sorting-type) '< '>)))
8207 (t (error "Invalid sorting type `%c'" sorting-type)))
8209 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8210 table)
8211 (lambda (a b) (funcall comparefun (car a) (car b))))))
8214 ;;; The orgstruct minor mode
8216 ;; Define a minor mode which can be used in other modes in order to
8217 ;; integrate the org-mode structure editing commands.
8219 ;; This is really a hack, because the org-mode structure commands use
8220 ;; keys which normally belong to the major mode. Here is how it
8221 ;; works: The minor mode defines all the keys necessary to operate the
8222 ;; structure commands, but wraps the commands into a function which
8223 ;; tests if the cursor is currently at a headline or a plain list
8224 ;; item. If that is the case, the structure command is used,
8225 ;; temporarily setting many Org-mode variables like regular
8226 ;; expressions for filling etc. However, when any of those keys is
8227 ;; used at a different location, function uses `key-binding' to look
8228 ;; up if the key has an associated command in another currently active
8229 ;; keymap (minor modes, major mode, global), and executes that
8230 ;; command. There might be problems if any of the keys is otherwise
8231 ;; used as a prefix key.
8233 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8234 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8235 ;; addresses this by checking explicitly for both bindings.
8237 (defvar orgstruct-mode-map (make-sparse-keymap)
8238 "Keymap for the minor `orgstruct-mode'.")
8240 (defvar org-local-vars nil
8241 "List of local variables, for use by `orgstruct-mode'.")
8243 ;;;###autoload
8244 (define-minor-mode orgstruct-mode
8245 "Toggle the minor mode `orgstruct-mode'.
8246 This mode is for using Org-mode structure commands in other
8247 modes. The following keys behave as if Org-mode were active, if
8248 the cursor is on a headline, or on a plain list item (both as
8249 defined by Org-mode).
8251 M-up Move entry/item up
8252 M-down Move entry/item down
8253 M-left Promote
8254 M-right Demote
8255 M-S-up Move entry/item up
8256 M-S-down Move entry/item down
8257 M-S-left Promote subtree
8258 M-S-right Demote subtree
8259 M-q Fill paragraph and items like in Org-mode
8260 C-c ^ Sort entries
8261 C-c - Cycle list bullet
8262 TAB Cycle item visibility
8263 M-RET Insert new heading/item
8264 S-M-RET Insert new TODO heading / Checkbox item
8265 C-c C-c Set tags / toggle checkbox"
8266 nil " OrgStruct" nil
8267 (org-load-modules-maybe)
8268 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8270 ;;;###autoload
8271 (defun turn-on-orgstruct ()
8272 "Unconditionally turn on `orgstruct-mode'."
8273 (orgstruct-mode 1))
8275 (defun orgstruct++-mode (&optional arg)
8276 "Toggle `orgstruct-mode', the enhanced version of it.
8277 In addition to setting orgstruct-mode, this also exports all indentation
8278 and autofilling variables from org-mode into the buffer. It will also
8279 recognize item context in multiline items.
8280 Note that turning off orgstruct-mode will *not* remove the
8281 indentation/paragraph settings. This can only be done by refreshing the
8282 major mode, for example with \\[normal-mode]."
8283 (interactive "P")
8284 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8285 (if (< arg 1)
8286 (orgstruct-mode -1)
8287 (orgstruct-mode 1)
8288 (let (var val)
8289 (mapc
8290 (lambda (x)
8291 (when (string-match
8292 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8293 (symbol-name (car x)))
8294 (setq var (car x) val (nth 1 x))
8295 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8296 org-local-vars)
8297 (org-set-local 'orgstruct-is-++ t))))
8299 (defvar orgstruct-is-++ nil
8300 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8301 (make-variable-buffer-local 'orgstruct-is-++)
8303 ;;;###autoload
8304 (defun turn-on-orgstruct++ ()
8305 "Unconditionally turn on `orgstruct++-mode'."
8306 (orgstruct++-mode 1))
8308 (defun orgstruct-error ()
8309 "Error when there is no default binding for a structure key."
8310 (interactive)
8311 (error "This key has no function outside structure elements"))
8313 (defun orgstruct-setup ()
8314 "Setup orgstruct keymaps."
8315 (let ((nfunc 0)
8316 (bindings
8317 (list
8318 '([(meta up)] org-metaup)
8319 '([(meta down)] org-metadown)
8320 '([(meta left)] org-metaleft)
8321 '([(meta right)] org-metaright)
8322 '([(meta shift up)] org-shiftmetaup)
8323 '([(meta shift down)] org-shiftmetadown)
8324 '([(meta shift left)] org-shiftmetaleft)
8325 '([(meta shift right)] org-shiftmetaright)
8326 '([?\e (up)] org-metaup)
8327 '([?\e (down)] org-metadown)
8328 '([?\e (left)] org-metaleft)
8329 '([?\e (right)] org-metaright)
8330 '([?\e (shift up)] org-shiftmetaup)
8331 '([?\e (shift down)] org-shiftmetadown)
8332 '([?\e (shift left)] org-shiftmetaleft)
8333 '([?\e (shift right)] org-shiftmetaright)
8334 '([(shift up)] org-shiftup)
8335 '([(shift down)] org-shiftdown)
8336 '([(shift left)] org-shiftleft)
8337 '([(shift right)] org-shiftright)
8338 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8339 '("\M-q" fill-paragraph)
8340 '("\C-c^" org-sort)
8341 '("\C-c-" org-cycle-list-bullet)))
8342 elt key fun cmd)
8343 (while (setq elt (pop bindings))
8344 (setq nfunc (1+ nfunc))
8345 (setq key (org-key (car elt))
8346 fun (nth 1 elt)
8347 cmd (orgstruct-make-binding fun nfunc key))
8348 (org-defkey orgstruct-mode-map key cmd))
8350 ;; Special treatment needed for TAB and RET
8351 (org-defkey orgstruct-mode-map [(tab)]
8352 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8353 (org-defkey orgstruct-mode-map "\C-i"
8354 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8356 (org-defkey orgstruct-mode-map "\M-\C-m"
8357 (orgstruct-make-binding 'org-insert-heading 105
8358 "\M-\C-m" [(meta return)]))
8359 (org-defkey orgstruct-mode-map [(meta return)]
8360 (orgstruct-make-binding 'org-insert-heading 106
8361 [(meta return)] "\M-\C-m"))
8363 (org-defkey orgstruct-mode-map [(shift meta return)]
8364 (orgstruct-make-binding 'org-insert-todo-heading 107
8365 [(meta return)] "\M-\C-m"))
8367 (org-defkey orgstruct-mode-map "\e\C-m"
8368 (orgstruct-make-binding 'org-insert-heading 108
8369 "\e\C-m" [?\e (return)]))
8370 (org-defkey orgstruct-mode-map [?\e (return)]
8371 (orgstruct-make-binding 'org-insert-heading 109
8372 [?\e (return)] "\e\C-m"))
8373 (org-defkey orgstruct-mode-map [?\e (shift return)]
8374 (orgstruct-make-binding 'org-insert-todo-heading 110
8375 [?\e (return)] "\e\C-m"))
8377 (unless org-local-vars
8378 (setq org-local-vars (org-get-local-variables)))
8382 (defun orgstruct-make-binding (fun n &rest keys)
8383 "Create a function for binding in the structure minor mode.
8384 FUN is the command to call inside a table. N is used to create a unique
8385 command name. KEYS are keys that should be checked in for a command
8386 to execute outside of tables."
8387 (eval
8388 (list 'defun
8389 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8390 '(arg)
8391 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8392 "Outside of structure, run the binding of `"
8393 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8394 "'.")
8395 '(interactive "p")
8396 (list 'if
8397 `(org-context-p 'headline 'item
8398 (and orgstruct-is-++
8399 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8400 'item-body))
8401 (list 'org-run-like-in-org-mode (list 'quote fun))
8402 (list 'let '(orgstruct-mode)
8403 (list 'call-interactively
8404 (append '(or)
8405 (mapcar (lambda (k)
8406 (list 'key-binding k))
8407 keys)
8408 '('orgstruct-error))))))))
8410 (defun org-context-p (&rest contexts)
8411 "Check if local context is any of CONTEXTS.
8412 Possible values in the list of contexts are `table', `headline', and `item'."
8413 (let ((pos (point)))
8414 (goto-char (point-at-bol))
8415 (prog1 (or (and (memq 'table contexts)
8416 (looking-at "[ \t]*|"))
8417 (and (memq 'headline contexts)
8418 (looking-at org-outline-regexp))
8419 (and (memq 'item contexts)
8420 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8421 (and (memq 'item-body contexts)
8422 (org-in-item-p)))
8423 (goto-char pos))))
8425 (defun org-get-local-variables ()
8426 "Return a list of all local variables in an org-mode buffer."
8427 (let (varlist)
8428 (with-current-buffer (get-buffer-create "*Org tmp*")
8429 (erase-buffer)
8430 (org-mode)
8431 (setq varlist (buffer-local-variables)))
8432 (kill-buffer "*Org tmp*")
8433 (delq nil
8434 (mapcar
8435 (lambda (x)
8436 (setq x
8437 (if (symbolp x)
8438 (list x)
8439 (list (car x) (list 'quote (cdr x)))))
8440 (if (string-match
8441 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8442 (symbol-name (car x)))
8443 x nil))
8444 varlist))))
8446 (defun org-clone-local-variables (from-buffer &optional regexp)
8447 "Clone local variables from FROM-BUFFER.
8448 Optional argument REGEXP selects variables to clone."
8449 (mapc
8450 (lambda (pair)
8451 (and (symbolp (car pair))
8452 (or (null regexp)
8453 (string-match regexp (symbol-name (car pair))))
8454 (set (make-local-variable (car pair))
8455 (cdr pair))))
8456 (buffer-local-variables from-buffer)))
8458 ;;;###autoload
8459 (defun org-run-like-in-org-mode (cmd)
8460 "Run a command, pretending that the current buffer is in Org-mode.
8461 This will temporarily bind local variables that are typically bound in
8462 Org-mode to the values they have in Org-mode, and then interactively
8463 call CMD."
8464 (org-load-modules-maybe)
8465 (unless org-local-vars
8466 (setq org-local-vars (org-get-local-variables)))
8467 (eval (list 'let org-local-vars
8468 (list 'call-interactively (list 'quote cmd)))))
8470 ;;;; Archiving
8472 (defun org-get-category (&optional pos force-refresh)
8473 "Get the category applying to position POS."
8474 (if force-refresh (org-refresh-category-properties))
8475 (let ((pos (or pos (point))))
8476 (or (get-text-property pos 'org-category)
8477 (progn (org-refresh-category-properties)
8478 (get-text-property pos 'org-category)))))
8480 (defun org-refresh-category-properties ()
8481 "Refresh category text properties in the buffer."
8482 (let ((def-cat (cond
8483 ((null org-category)
8484 (if buffer-file-name
8485 (file-name-sans-extension
8486 (file-name-nondirectory buffer-file-name))
8487 "???"))
8488 ((symbolp org-category) (symbol-name org-category))
8489 (t org-category)))
8490 beg end cat pos optionp)
8491 (org-unmodified
8492 (save-excursion
8493 (save-restriction
8494 (widen)
8495 (goto-char (point-min))
8496 (put-text-property (point) (point-max) 'org-category def-cat)
8497 (while (re-search-forward
8498 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8499 (setq pos (match-end 0)
8500 optionp (equal (char-after (match-beginning 0)) ?#)
8501 cat (org-trim (match-string 2)))
8502 (if optionp
8503 (setq beg (point-at-bol) end (point-max))
8504 (org-back-to-heading t)
8505 (setq beg (point) end (org-end-of-subtree t t)))
8506 (put-text-property beg end 'org-category cat)
8507 (put-text-property beg end 'org-category-position beg)
8508 (goto-char pos)))))))
8511 ;;;; Link Stuff
8513 ;;; Link abbreviations
8515 (defun org-link-expand-abbrev (link)
8516 "Apply replacements as defined in `org-link-abbrev-alist."
8517 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8518 (let* ((key (match-string 1 link))
8519 (as (or (assoc key org-link-abbrev-alist-local)
8520 (assoc key org-link-abbrev-alist)))
8521 (tag (and (match-end 2) (match-string 3 link)))
8522 rpl)
8523 (if (not as)
8524 link
8525 (setq rpl (cdr as))
8526 (cond
8527 ((symbolp rpl) (funcall rpl tag))
8528 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8529 ((string-match "%h" rpl)
8530 (replace-match (url-hexify-string (or tag "")) t t rpl))
8531 (t (concat rpl tag)))))
8532 link))
8534 ;;; Storing and inserting links
8536 (defvar org-insert-link-history nil
8537 "Minibuffer history for links inserted with `org-insert-link'.")
8539 (defvar org-stored-links nil
8540 "Contains the links stored with `org-store-link'.")
8542 (defvar org-store-link-plist nil
8543 "Plist with info about the most recently link created with `org-store-link'.")
8545 (defvar org-link-protocols nil
8546 "Link protocols added to Org-mode using `org-add-link-type'.")
8548 (defvar org-store-link-functions nil
8549 "List of functions that are called to create and store a link.
8550 Each function will be called in turn until one returns a non-nil
8551 value. Each function should check if it is responsible for creating
8552 this link (for example by looking at the major mode).
8553 If not, it must exit and return nil.
8554 If yes, it should return a non-nil value after a calling
8555 `org-store-link-props' with a list of properties and values.
8556 Special properties are:
8558 :type The link prefix, like \"http\". This must be given.
8559 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8560 This is obligatory as well.
8561 :description Optional default description for the second pair
8562 of brackets in an Org-mode link. The user can still change
8563 this when inserting this link into an Org-mode buffer.
8565 In addition to these, any additional properties can be specified
8566 and then used in remember templates.")
8568 (defun org-add-link-type (type &optional follow export)
8569 "Add TYPE to the list of `org-link-types'.
8570 Re-compute all regular expressions depending on `org-link-types'
8572 FOLLOW and EXPORT are two functions.
8574 FOLLOW should take the link path as the single argument and do whatever
8575 is necessary to follow the link, for example find a file or display
8576 a mail message.
8578 EXPORT should format the link path for export to one of the export formats.
8579 It should be a function accepting three arguments:
8581 path the path of the link, the text after the prefix (like \"http:\")
8582 desc the description of the link, if any, or a description added by
8583 org-export-normalize-links if there is none
8584 format the export format, a symbol like `html' or `latex' or `ascii'..
8586 The function may use the FORMAT information to return different values
8587 depending on the format. The return value will be put literally into
8588 the exported file. If the return value is nil, this means Org should
8589 do what it normally does with links which do not have EXPORT defined.
8591 Org-mode has a built-in default for exporting links. If you are happy with
8592 this default, there is no need to define an export function for the link
8593 type. For a simple example of an export function, see `org-bbdb.el'."
8594 (add-to-list 'org-link-types type t)
8595 (org-make-link-regexps)
8596 (if (assoc type org-link-protocols)
8597 (setcdr (assoc type org-link-protocols) (list follow export))
8598 (push (list type follow export) org-link-protocols)))
8600 (defvar org-agenda-buffer-name)
8602 ;;;###autoload
8603 (defun org-store-link (arg)
8604 "\\<org-mode-map>Store an org-link to the current location.
8605 This link is added to `org-stored-links' and can later be inserted
8606 into an org-buffer with \\[org-insert-link].
8608 For some link types, a prefix arg is interpreted:
8609 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8610 For file links, arg negates `org-context-in-file-links'."
8611 (interactive "P")
8612 (org-load-modules-maybe)
8613 (setq org-store-link-plist nil) ; reset
8614 (org-with-limited-levels
8615 (let (link cpltxt desc description search txt custom-id agenda-link)
8616 (cond
8618 ((run-hook-with-args-until-success 'org-store-link-functions)
8619 (setq link (plist-get org-store-link-plist :link)
8620 desc (or (plist-get org-store-link-plist :description) link)))
8622 ((equal (buffer-name) "*Org Edit Src Example*")
8623 (let (label gc)
8624 (while (or (not label)
8625 (save-excursion
8626 (save-restriction
8627 (widen)
8628 (goto-char (point-min))
8629 (re-search-forward
8630 (regexp-quote (format org-coderef-label-format label))
8631 nil t))))
8632 (when label (message "Label exists already") (sit-for 2))
8633 (setq label (read-string "Code line label: " label)))
8634 (end-of-line 1)
8635 (setq link (format org-coderef-label-format label))
8636 (setq gc (- 79 (length link)))
8637 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8638 (insert link)
8639 (setq link (concat "(" label ")") desc nil)))
8641 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8642 ;; We are in the agenda, link to referenced location
8643 (let ((m (or (get-text-property (point) 'org-hd-marker)
8644 (get-text-property (point) 'org-marker))))
8645 (when m
8646 (org-with-point-at m
8647 (setq agenda-link
8648 (if (org-called-interactively-p 'any)
8649 (call-interactively 'org-store-link)
8650 (org-store-link nil)))))))
8652 ((eq major-mode 'calendar-mode)
8653 (let ((cd (calendar-cursor-to-date)))
8654 (setq link
8655 (format-time-string
8656 (car org-time-stamp-formats)
8657 (apply 'encode-time
8658 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8659 nil nil nil))))
8660 (org-store-link-props :type "calendar" :date cd)))
8662 ((eq major-mode 'w3-mode)
8663 (setq cpltxt (if (and (buffer-name)
8664 (not (string-match "Untitled" (buffer-name))))
8665 (buffer-name)
8666 (url-view-url t))
8667 link (org-make-link (url-view-url t)))
8668 (org-store-link-props :type "w3" :url (url-view-url t)))
8670 ((eq major-mode 'w3m-mode)
8671 (setq cpltxt (or w3m-current-title w3m-current-url)
8672 link (org-make-link w3m-current-url))
8673 (org-store-link-props :type "w3m" :url (url-view-url t)))
8675 ((setq search (run-hook-with-args-until-success
8676 'org-create-file-search-functions))
8677 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8678 "::" search))
8679 (setq cpltxt (or description link)))
8681 ((eq major-mode 'image-mode)
8682 (setq cpltxt (concat "file:"
8683 (abbreviate-file-name buffer-file-name))
8684 link (org-make-link cpltxt))
8685 (org-store-link-props :type "image" :file buffer-file-name))
8687 ((eq major-mode 'dired-mode)
8688 ;; link to the file in the current line
8689 (let ((file (dired-get-filename nil t)))
8690 (setq file (if file
8691 (abbreviate-file-name
8692 (expand-file-name (dired-get-filename nil t)))
8693 ;; otherwise, no file so use current directory.
8694 default-directory))
8695 (setq cpltxt (concat "file:" file)
8696 link (org-make-link cpltxt))))
8698 ((and (buffer-file-name (buffer-base-buffer)) (eq major-mode 'org-mode))
8699 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8700 (cond
8701 ((org-in-regexp "<<\\(.*?\\)>>")
8702 (setq cpltxt
8703 (concat "file:"
8704 (abbreviate-file-name
8705 (buffer-file-name (buffer-base-buffer)))
8706 "::" (match-string 1))
8707 link (org-make-link cpltxt)))
8708 ((and (featurep 'org-id)
8709 (or (eq org-link-to-org-use-id t)
8710 (and (eq org-link-to-org-use-id 'create-if-interactive)
8711 (org-called-interactively-p 'any))
8712 (and (eq org-link-to-org-use-id
8713 'create-if-interactive-and-no-custom-id)
8714 (org-called-interactively-p 'any)
8715 (not custom-id))
8716 (and org-link-to-org-use-id
8717 (org-entry-get nil "ID"))))
8718 ;; We can make a link using the ID.
8719 (setq link (condition-case nil
8720 (prog1 (org-id-store-link)
8721 (setq desc (plist-get org-store-link-plist
8722 :description)))
8723 (error
8724 ;; probably before first headline, link to file only
8725 (concat "file:"
8726 (abbreviate-file-name
8727 (buffer-file-name (buffer-base-buffer))))))))
8729 ;; Just link to current headline
8730 (setq cpltxt (concat "file:"
8731 (abbreviate-file-name
8732 (buffer-file-name (buffer-base-buffer)))))
8733 ;; Add a context search string
8734 (when (org-xor org-context-in-file-links arg)
8735 (setq txt (cond
8736 ((org-on-heading-p) nil)
8737 ((org-region-active-p)
8738 (buffer-substring (region-beginning) (region-end)))
8739 (t nil)))
8740 (when (or (null txt) (string-match "\\S-" txt))
8741 (setq cpltxt
8742 (concat cpltxt "::"
8743 (condition-case nil
8744 (org-make-org-heading-search-string txt)
8745 (error "")))
8746 desc (or (nth 4 (ignore-errors
8747 (org-heading-components))) "NONE"))))
8748 (if (string-match "::\\'" cpltxt)
8749 (setq cpltxt (substring cpltxt 0 -2)))
8750 (setq link (org-make-link cpltxt)))))
8752 ((buffer-file-name (buffer-base-buffer))
8753 ;; Just link to this file here.
8754 (setq cpltxt (concat "file:"
8755 (abbreviate-file-name
8756 (buffer-file-name (buffer-base-buffer)))))
8757 ;; Add a context string
8758 (when (org-xor org-context-in-file-links arg)
8759 (setq txt (if (org-region-active-p)
8760 (buffer-substring (region-beginning) (region-end))
8761 (buffer-substring (point-at-bol) (point-at-eol))))
8762 ;; Only use search option if there is some text.
8763 (when (string-match "\\S-" txt)
8764 (setq cpltxt
8765 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8766 desc "NONE")))
8767 (setq link (org-make-link cpltxt)))
8769 ((org-called-interactively-p 'interactive)
8770 (error "Cannot link to a buffer which is not visiting a file"))
8772 (t (setq link nil)))
8774 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8775 (setq link (or link cpltxt)
8776 desc (or desc cpltxt))
8777 (if (equal desc "NONE") (setq desc nil))
8779 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8780 (progn
8781 (setq org-stored-links
8782 (cons (list link desc) org-stored-links))
8783 (message "Stored: %s" (or desc link))
8784 (when custom-id
8785 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8786 "::#" custom-id))
8787 (setq org-stored-links
8788 (cons (list link desc) org-stored-links))))
8789 (or agenda-link (and link (org-make-link-string link desc)))))))
8791 (defun org-store-link-props (&rest plist)
8792 "Store link properties, extract names and addresses."
8793 (let (x adr)
8794 (when (setq x (plist-get plist :from))
8795 (setq adr (mail-extract-address-components x))
8796 (setq plist (plist-put plist :fromname (car adr)))
8797 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8798 (when (setq x (plist-get plist :to))
8799 (setq adr (mail-extract-address-components x))
8800 (setq plist (plist-put plist :toname (car adr)))
8801 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8802 (let ((from (plist-get plist :from))
8803 (to (plist-get plist :to)))
8804 (when (and from to org-from-is-user-regexp)
8805 (setq plist
8806 (plist-put plist :fromto
8807 (if (string-match org-from-is-user-regexp from)
8808 (concat "to %t")
8809 (concat "from %f"))))))
8810 (setq org-store-link-plist plist))
8812 (defun org-add-link-props (&rest plist)
8813 "Add these properties to the link property list."
8814 (let (key value)
8815 (while plist
8816 (setq key (pop plist) value (pop plist))
8817 (setq org-store-link-plist
8818 (plist-put org-store-link-plist key value)))))
8820 (defun org-email-link-description (&optional fmt)
8821 "Return the description part of an email link.
8822 This takes information from `org-store-link-plist' and formats it
8823 according to FMT (default from `org-email-link-description-format')."
8824 (setq fmt (or fmt org-email-link-description-format))
8825 (let* ((p org-store-link-plist)
8826 (to (plist-get p :toaddress))
8827 (from (plist-get p :fromaddress))
8828 (table
8829 (list
8830 (cons "%c" (plist-get p :fromto))
8831 (cons "%F" (plist-get p :from))
8832 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8833 (cons "%T" (plist-get p :to))
8834 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8835 (cons "%s" (plist-get p :subject))
8836 (cons "%d" (plist-get p :date))
8837 (cons "%m" (plist-get p :message-id)))))
8838 (when (string-match "%c" fmt)
8839 ;; Check if the user wrote this message
8840 (if (and org-from-is-user-regexp from to
8841 (save-match-data (string-match org-from-is-user-regexp from)))
8842 (setq fmt (replace-match "to %t" t t fmt))
8843 (setq fmt (replace-match "from %f" t t fmt))))
8844 (org-replace-escapes fmt table)))
8846 (defun org-make-org-heading-search-string (&optional string heading)
8847 "Make search string for STRING or current headline."
8848 (interactive)
8849 (let ((s (or string (org-get-heading)))
8850 (lines org-context-in-file-links))
8851 (unless (and string (not heading))
8852 ;; We are using a headline, clean up garbage in there.
8853 (if (string-match org-todo-regexp s)
8854 (setq s (replace-match "" t t s)))
8855 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8856 (setq s (replace-match "" t t s)))
8857 (setq s (org-trim s))
8858 (if (string-match (concat "^\\(" org-quote-string "\\|"
8859 org-comment-string "\\)") s)
8860 (setq s (replace-match "" t t s)))
8861 (while (string-match org-ts-regexp s)
8862 (setq s (replace-match "" t t s))))
8863 (or string (setq s (concat "*" s))) ; Add * for headlines
8864 (when (and string (integerp lines) (> lines 0))
8865 (let ((slines (org-split-string s "\n")))
8866 (when (< lines (length slines))
8867 (setq s (mapconcat
8868 'identity
8869 (reverse (nthcdr (- (length slines) lines)
8870 (reverse slines))) "\n")))))
8871 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8873 (defun org-make-link (&rest strings)
8874 "Concatenate STRINGS."
8875 (apply 'concat strings))
8877 (defun org-make-link-string (link &optional description)
8878 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8879 (unless (string-match "\\S-" link)
8880 (error "Empty link"))
8881 (when (and description
8882 (stringp description)
8883 (not (string-match "\\S-" description)))
8884 (setq description nil))
8885 (when (stringp description)
8886 ;; Remove brackets from the description, they are fatal.
8887 (while (string-match "\\[" description)
8888 (setq description (replace-match "{" t t description)))
8889 (while (string-match "\\]" description)
8890 (setq description (replace-match "}" t t description))))
8891 (when (equal link description)
8892 ;; No description needed, it is identical
8893 (setq description nil))
8894 (when (and (not description)
8895 (not (string-match (org-image-file-name-regexp) link))
8896 (not (equal link (org-link-escape link))))
8897 (setq description (org-extract-attributes link)))
8898 (setq link
8899 (cond ((string-match (org-image-file-name-regexp) link) link)
8900 ((string-match org-link-types-re link)
8901 (concat (match-string 1 link)
8902 (org-link-escape (substring link (match-end 1)))))
8903 (t (org-link-escape link))))
8904 (concat "[[" link "]"
8905 (if description (concat "[" description "]") "")
8906 "]"))
8908 (defconst org-link-escape-chars
8909 '(?\ ?\[ ?\] ?\; ?\= ?\+)
8910 "List of characters that should be escaped in link.
8911 This is the list that is used for internal purposes.")
8913 (defvar org-url-encoding-use-url-hexify nil)
8915 (defconst org-link-escape-chars-browser
8916 '(?\ )
8917 "List of escapes for characters that are problematic in links.
8918 This is the list that is used before handing over to the browser.")
8920 (defun org-link-escape (text &optional table merge)
8921 "Return percent escaped representation of TEXT.
8922 TEXT is a string with the text to escape.
8923 Optional argument TABLE is a list with characters that should be
8924 escaped. When nil, `org-link-escape-chars' is used.
8925 If optional argument MERGE is set, merge TABLE into
8926 `org-link-escape-chars'."
8927 (if (and org-url-encoding-use-url-hexify (not table))
8928 (url-hexify-string text)
8929 (cond
8930 ((and table merge)
8931 (mapc (lambda (defchr)
8932 (unless (member defchr table)
8933 (setq table (cons defchr table)))) org-link-escape-chars))
8934 ((null table)
8935 (setq table org-link-escape-chars)))
8936 (mapconcat
8937 (lambda (char)
8938 (if (or (member char table)
8939 (< char 32) (= char 37) (> char 126))
8940 (mapconcat (lambda (sequence-element)
8941 (format "%%%.2X" sequence-element))
8942 (or (encode-coding-char char 'utf-8)
8943 (error "Unable to percent escape character: %s"
8944 (char-to-string char))) "")
8945 (char-to-string char))) text "")))
8947 (defun org-link-unescape (str)
8948 "Unhex hexified Unicode strings as returned from the JavaScript function
8949 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
8950 (unless (and (null str) (string= "" str))
8951 (let ((pos 0) (case-fold-search t) unhexed)
8952 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
8953 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
8954 (setq str (replace-match unhexed t t str))
8955 (setq pos (+ pos (length unhexed))))))
8956 str)
8958 (defun org-link-unescape-compound (hex)
8959 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
8960 Note: this function also decodes single byte encodings like
8961 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
8962 (save-match-data
8963 (let* ((bytes (cdr (split-string hex "%")))
8964 (ret "")
8965 (eat 0)
8966 (sum 0))
8967 (while bytes
8968 (let* ((val (string-to-number (pop bytes) 16))
8969 (shift-xor
8970 (if (= 0 eat)
8971 (cond
8972 ((>= val 252) (cons 6 252))
8973 ((>= val 248) (cons 5 248))
8974 ((>= val 240) (cons 4 240))
8975 ((>= val 224) (cons 3 224))
8976 ((>= val 192) (cons 2 192))
8977 (t (cons 0 0)))
8978 (cons 6 128))))
8979 (if (>= val 192) (setq eat (car shift-xor)))
8980 (setq val (logxor val (cdr shift-xor)))
8981 (setq sum (+ (lsh sum (car shift-xor)) val))
8982 (if (> eat 0) (setq eat (- eat 1)))
8983 (cond
8984 ((= 0 eat) ;multi byte
8985 (setq ret (concat ret (org-char-to-string sum)))
8986 (setq sum 0))
8987 ((not bytes) ; single byte(s)
8988 (setq ret (org-link-unescape-single-byte-sequence hex))))
8989 )) ;; end (while bytes
8990 ret )))
8992 (defun org-link-unescape-single-byte-sequence (hex)
8993 "Unhexify hex-encoded single byte character sequences."
8994 (mapconcat (lambda (byte)
8995 (char-to-string (string-to-number byte 16)))
8996 (cdr (split-string hex "%")) ""))
8998 (defun org-xor (a b)
8999 "Exclusive or."
9000 (if a (not b) b))
9002 (defun org-fixup-message-id-for-http (s)
9003 "Replace special characters in a message id, so it can be used in an http query."
9004 (when (string-match "%" s)
9005 (setq s (mapconcat (lambda (c)
9006 (if (eq c ?%)
9007 "%25"
9008 (char-to-string c)))
9009 s "")))
9010 (while (string-match "<" s)
9011 (setq s (replace-match "%3C" t t s)))
9012 (while (string-match ">" s)
9013 (setq s (replace-match "%3E" t t s)))
9014 (while (string-match "@" s)
9015 (setq s (replace-match "%40" t t s)))
9018 ;;;###autoload
9019 (defun org-insert-link-global ()
9020 "Insert a link like Org-mode does.
9021 This command can be called in any mode to insert a link in Org-mode syntax."
9022 (interactive)
9023 (org-load-modules-maybe)
9024 (org-run-like-in-org-mode 'org-insert-link))
9026 (defun org-insert-link (&optional complete-file link-location default-description)
9027 "Insert a link. At the prompt, enter the link.
9029 Completion can be used to insert any of the link protocol prefixes like
9030 http or ftp in use.
9032 The history can be used to select a link previously stored with
9033 `org-store-link'. When the empty string is entered (i.e. if you just
9034 press RET at the prompt), the link defaults to the most recently
9035 stored link. As SPC triggers completion in the minibuffer, you need to
9036 use M-SPC or C-q SPC to force the insertion of a space character.
9038 You will also be prompted for a description, and if one is given, it will
9039 be displayed in the buffer instead of the link.
9041 If there is already a link at point, this command will allow you to edit link
9042 and description parts.
9044 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9045 be selected using completion. The path to the file will be relative to the
9046 current directory if the file is in the current directory or a subdirectory.
9047 Otherwise, the link will be the absolute path as completed in the minibuffer
9048 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9049 option `org-link-file-path-type'.
9051 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9052 the current directory or below.
9054 With three \\[universal-argument] prefixes, negate the meaning of
9055 `org-keep-stored-link-after-insertion'.
9057 If `org-make-link-description-function' is non-nil, this function will be
9058 called with the link target, and the result will be the default
9059 link description.
9061 If the LINK-LOCATION parameter is non-nil, this value will be
9062 used as the link location instead of reading one interactively.
9064 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9065 be used as the default description."
9066 (interactive "P")
9067 (let* ((wcf (current-window-configuration))
9068 (region (if (org-region-active-p)
9069 (buffer-substring (region-beginning) (region-end))))
9070 (remove (and region (list (region-beginning) (region-end))))
9071 (desc region)
9072 tmphist ; byte-compile incorrectly complains about this
9073 (link link-location)
9074 entry file all-prefixes)
9075 (cond
9076 (link-location) ; specified by arg, just use it.
9077 ((org-in-regexp org-bracket-link-regexp 1)
9078 ;; We do have a link at point, and we are going to edit it.
9079 (setq remove (list (match-beginning 0) (match-end 0)))
9080 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9081 (setq link (read-string "Link: "
9082 (org-link-unescape
9083 (org-match-string-no-properties 1)))))
9084 ((or (org-in-regexp org-angle-link-re)
9085 (org-in-regexp org-plain-link-re))
9086 ;; Convert to bracket link
9087 (setq remove (list (match-beginning 0) (match-end 0))
9088 link (read-string "Link: "
9089 (org-remove-angle-brackets (match-string 0)))))
9090 ((member complete-file '((4) (16)))
9091 ;; Completing read for file names.
9092 (setq link (org-file-complete-link complete-file)))
9094 ;; Read link, with completion for stored links.
9095 (with-output-to-temp-buffer "*Org Links*"
9096 (princ "Insert a link.
9097 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9098 (when org-stored-links
9099 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9100 (princ (mapconcat
9101 (lambda (x)
9102 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
9103 (reverse org-stored-links) "\n"))))
9104 (let ((cw (selected-window)))
9105 (select-window (get-buffer-window "*Org Links*" 'visible))
9106 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9107 (unless (pos-visible-in-window-p (point-max))
9108 (org-fit-window-to-buffer))
9109 (and (window-live-p cw) (select-window cw)))
9110 ;; Fake a link history, containing the stored links.
9111 (setq tmphist (append (mapcar 'car org-stored-links)
9112 org-insert-link-history))
9113 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
9114 (mapcar 'car org-link-abbrev-alist)
9115 org-link-types))
9116 (unwind-protect
9117 (progn
9118 (setq link
9119 (let ((org-completion-use-ido nil)
9120 (org-completion-use-iswitchb nil))
9121 (org-completing-read
9122 "Link: "
9123 (append
9124 (mapcar (lambda (x) (list (concat x ":")))
9125 all-prefixes)
9126 (mapcar 'car org-stored-links))
9127 nil nil nil
9128 'tmphist
9129 (car (car org-stored-links)))))
9130 (if (not (string-match "\\S-" link))
9131 (error "No link selected"))
9132 (if (or (member link all-prefixes)
9133 (and (equal ":" (substring link -1))
9134 (member (substring link 0 -1) all-prefixes)
9135 (setq link (substring link 0 -1))))
9136 (setq link (org-link-try-special-completion link))))
9137 (set-window-configuration wcf)
9138 (kill-buffer "*Org Links*"))
9139 (setq entry (assoc link org-stored-links))
9140 (or entry (push link org-insert-link-history))
9141 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9142 (not org-keep-stored-link-after-insertion))
9143 (setq org-stored-links (delq (assoc link org-stored-links)
9144 org-stored-links)))
9145 (setq desc (or desc (nth 1 entry)))))
9147 (if (string-match org-plain-link-re link)
9148 ;; URL-like link, normalize the use of angular brackets.
9149 (setq link (org-make-link (org-remove-angle-brackets link))))
9151 ;; Check if we are linking to the current file with a search option
9152 ;; If yes, simplify the link by using only the search option.
9153 (when (and buffer-file-name
9154 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9155 (let* ((path (match-string 1 link))
9156 (case-fold-search nil)
9157 (search (match-string 2 link)))
9158 (save-match-data
9159 (if (equal (file-truename buffer-file-name) (file-truename path))
9160 ;; We are linking to this same file, with a search option
9161 (setq link search)))))
9163 ;; Check if we can/should use a relative path. If yes, simplify the link
9164 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9165 (let* ((type (match-string 1 link))
9166 (path (match-string 2 link))
9167 (origpath path)
9168 (case-fold-search nil))
9169 (cond
9170 ((or (eq org-link-file-path-type 'absolute)
9171 (equal complete-file '(16)))
9172 (setq path (abbreviate-file-name (expand-file-name path))))
9173 ((eq org-link-file-path-type 'noabbrev)
9174 (setq path (expand-file-name path)))
9175 ((eq org-link-file-path-type 'relative)
9176 (setq path (file-relative-name path)))
9178 (save-match-data
9179 (if (string-match (concat "^" (regexp-quote
9180 (expand-file-name
9181 (file-name-as-directory
9182 default-directory))))
9183 (expand-file-name path))
9184 ;; We are linking a file with relative path name.
9185 (setq path (substring (expand-file-name path)
9186 (match-end 0)))
9187 (setq path (abbreviate-file-name (expand-file-name path)))))))
9188 (setq link (concat type path))
9189 (if (equal desc origpath)
9190 (setq desc path))))
9192 (if org-make-link-description-function
9193 (setq desc (funcall org-make-link-description-function link desc))
9194 (if default-description (setq desc default-description)))
9196 (setq desc (read-string "Description: " desc))
9197 (unless (string-match "\\S-" desc) (setq desc nil))
9198 (if remove (apply 'delete-region remove))
9199 (insert (org-make-link-string link desc))))
9201 (defun org-link-try-special-completion (type)
9202 "If there is completion support for link type TYPE, offer it."
9203 (let ((fun (intern (concat "org-" type "-complete-link"))))
9204 (if (functionp fun)
9205 (funcall fun)
9206 (read-string "Link (no completion support): " (concat type ":")))))
9208 (defun org-file-complete-link (&optional arg)
9209 "Create a file link using completion."
9210 (let (file link)
9211 (setq file (read-file-name "File: "))
9212 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9213 (pwd1 (file-name-as-directory (abbreviate-file-name
9214 (expand-file-name ".")))))
9215 (cond
9216 ((equal arg '(16))
9217 (setq link (org-make-link
9218 "file:"
9219 (abbreviate-file-name (expand-file-name file)))))
9220 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9221 (setq link (org-make-link "file:" (match-string 1 file))))
9222 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9223 (expand-file-name file))
9224 (setq link (org-make-link
9225 "file:" (match-string 1 (expand-file-name file)))))
9226 (t (setq link (org-make-link "file:" file)))))
9227 link))
9229 (defun org-completing-read (&rest args)
9230 "Completing-read with SPACE being a normal character."
9231 (let ((enable-recursive-minibuffers t)
9232 (minibuffer-local-completion-map
9233 (copy-keymap minibuffer-local-completion-map)))
9234 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9235 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9236 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9237 (apply 'org-icompleting-read args)))
9239 (defun org-completing-read-no-i (&rest args)
9240 (let (org-completion-use-ido org-completion-use-iswitchb)
9241 (apply 'org-completing-read args)))
9243 (defun org-iswitchb-completing-read (prompt choices &rest args)
9244 "Use iswitch as a completing-read replacement to choose from choices.
9245 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9246 from."
9247 (let* ((iswitchb-use-virtual-buffers nil)
9248 (iswitchb-make-buflist-hook
9249 (lambda ()
9250 (setq iswitchb-temp-buflist choices))))
9251 (iswitchb-read-buffer prompt)))
9253 (defun org-icompleting-read (&rest args)
9254 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9255 (org-without-partial-completion
9256 (if (and org-completion-use-ido
9257 (fboundp 'ido-completing-read)
9258 (boundp 'ido-mode) ido-mode
9259 (listp (second args)))
9260 (let ((ido-enter-matching-directory nil))
9261 (apply 'ido-completing-read (concat (car args))
9262 (if (consp (car (nth 1 args)))
9263 (mapcar 'car (nth 1 args))
9264 (nth 1 args))
9265 (cddr args)))
9266 (if (and org-completion-use-iswitchb
9267 (boundp 'iswitchb-mode) iswitchb-mode
9268 (listp (second args)))
9269 (apply 'org-iswitchb-completing-read (concat (car args))
9270 (if (consp (car (nth 1 args)))
9271 (mapcar 'car (nth 1 args))
9272 (nth 1 args))
9273 (cddr args))
9274 (apply 'completing-read args)))))
9276 (defun org-extract-attributes (s)
9277 "Extract the attributes cookie from a string and set as text property."
9278 (let (a attr (start 0) key value)
9279 (save-match-data
9280 (when (string-match "{{\\([^}]+\\)}}$" s)
9281 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9282 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9283 (setq key (match-string 1 a) value (match-string 2 a)
9284 start (match-end 0)
9285 attr (plist-put attr (intern key) value))))
9286 (org-add-props s nil 'org-attr attr))
9289 (defun org-extract-attributes-from-string (tag)
9290 (let (key value attr)
9291 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9292 (setq key (match-string 1 tag) value (match-string 2 tag)
9293 tag (replace-match "" t t tag)
9294 attr (plist-put attr (intern key) value)))
9295 (cons tag attr)))
9297 (defun org-attributes-to-string (plist)
9298 "Format a property list into an HTML attribute list."
9299 (let ((s "") key value)
9300 (while plist
9301 (setq key (pop plist) value (pop plist))
9302 (and value
9303 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9306 ;;; Opening/following a link
9308 (defvar org-link-search-failed nil)
9310 (defvar org-open-link-functions nil
9311 "Hook for functions finding a plain text link.
9312 These functions must take a single argument, the link content.
9313 They will be called for links that look like [[link text][description]]
9314 when LINK TEXT does not have a protocol like \"http:\" and does not look
9315 like a filename (e.g. \"./blue.png\").
9317 These functions will be called *before* Org attempts to resolve the
9318 link by doing text searches in the current buffer - so if you want a
9319 link \"[[target]]\" to still find \"<<target>>\", your function should
9320 handle this as a special case.
9322 When the function does handle the link, it must return a non-nil value.
9323 If it decides that it is not responsible for this link, it must return
9324 nil to indicate that that Org-mode can continue with other options
9325 like exact and fuzzy text search.")
9327 (defun org-next-link ()
9328 "Move forward to the next link.
9329 If the link is in hidden text, expose it."
9330 (interactive)
9331 (when (and org-link-search-failed (eq this-command last-command))
9332 (goto-char (point-min))
9333 (message "Link search wrapped back to beginning of buffer"))
9334 (setq org-link-search-failed nil)
9335 (let* ((pos (point))
9336 (ct (org-context))
9337 (a (assoc :link ct)))
9338 (if a (goto-char (nth 2 a)))
9339 (if (re-search-forward org-any-link-re nil t)
9340 (progn
9341 (goto-char (match-beginning 0))
9342 (if (outline-invisible-p) (org-show-context)))
9343 (goto-char pos)
9344 (setq org-link-search-failed t)
9345 (error "No further link found"))))
9347 (defun org-previous-link ()
9348 "Move backward to the previous link.
9349 If the link is in hidden text, expose it."
9350 (interactive)
9351 (when (and org-link-search-failed (eq this-command last-command))
9352 (goto-char (point-max))
9353 (message "Link search wrapped back to end of buffer"))
9354 (setq org-link-search-failed nil)
9355 (let* ((pos (point))
9356 (ct (org-context))
9357 (a (assoc :link ct)))
9358 (if a (goto-char (nth 1 a)))
9359 (if (re-search-backward org-any-link-re nil t)
9360 (progn
9361 (goto-char (match-beginning 0))
9362 (if (outline-invisible-p) (org-show-context)))
9363 (goto-char pos)
9364 (setq org-link-search-failed t)
9365 (error "No further link found"))))
9367 (defun org-translate-link (s)
9368 "Translate a link string if a translation function has been defined."
9369 (if (and org-link-translation-function
9370 (fboundp org-link-translation-function)
9371 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9372 (progn
9373 (setq s (funcall org-link-translation-function
9374 (match-string 1) (match-string 2)))
9375 (concat (car s) ":" (cdr s)))
9378 (defun org-translate-link-from-planner (type path)
9379 "Translate a link from Emacs Planner syntax so that Org can follow it.
9380 This is still an experimental function, your mileage may vary."
9381 (cond
9382 ((member type '("http" "https" "news" "ftp"))
9383 ;; standard Internet links are the same.
9384 nil)
9385 ((and (equal type "irc") (string-match "^//" path))
9386 ;; Planner has two / at the beginning of an irc link, we have 1.
9387 ;; We should have zero, actually....
9388 (setq path (substring path 1)))
9389 ((and (equal type "lisp") (string-match "^/" path))
9390 ;; Planner has a slash, we do not.
9391 (setq type "elisp" path (substring path 1)))
9392 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9393 ;; A typical message link. Planner has the id after the final slash,
9394 ;; we separate it with a hash mark
9395 (setq path (concat (match-string 1 path) "#"
9396 (org-remove-angle-brackets (match-string 2 path)))))
9398 (cons type path))
9400 (defun org-find-file-at-mouse (ev)
9401 "Open file link or URL at mouse."
9402 (interactive "e")
9403 (mouse-set-point ev)
9404 (org-open-at-point 'in-emacs))
9406 (defun org-open-at-mouse (ev)
9407 "Open file link or URL at mouse.
9408 See the docstring of `org-open-file' for details."
9409 (interactive "e")
9410 (mouse-set-point ev)
9411 (if (eq major-mode 'org-agenda-mode)
9412 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9413 (org-open-at-point))
9415 (defvar org-window-config-before-follow-link nil
9416 "The window configuration before following a link.
9417 This is saved in case the need arises to restore it.")
9419 (defvar org-open-link-marker (make-marker)
9420 "Marker pointing to the location where `org-open-at-point; was called.")
9422 ;;;###autoload
9423 (defun org-open-at-point-global ()
9424 "Follow a link like Org-mode does.
9425 This command can be called in any mode to follow a link that has
9426 Org-mode syntax."
9427 (interactive)
9428 (org-run-like-in-org-mode 'org-open-at-point))
9430 ;;;###autoload
9431 (defun org-open-link-from-string (s &optional arg reference-buffer)
9432 "Open a link in the string S, as if it was in Org-mode."
9433 (interactive "sLink: \nP")
9434 (let ((reference-buffer (or reference-buffer (current-buffer))))
9435 (with-temp-buffer
9436 (let ((org-inhibit-startup t))
9437 (org-mode)
9438 (insert s)
9439 (goto-char (point-min))
9440 (when reference-buffer
9441 (setq org-link-abbrev-alist-local
9442 (with-current-buffer reference-buffer
9443 org-link-abbrev-alist-local)))
9444 (org-open-at-point arg reference-buffer)))))
9446 (defvar org-open-at-point-functions nil
9447 "Hook that is run when following a link at point.
9449 Functions in this hook must return t if they identify and follow
9450 a link at point. If they don't find anything interesting at point,
9451 they must return nil.")
9453 (defun org-open-at-point (&optional arg reference-buffer)
9454 "Open link at or after point.
9455 If there is no link at point, this function will search forward up to
9456 the end of the current line.
9457 Normally, files will be opened by an appropriate application. If the
9458 optional prefix argument ARG is non-nil, Emacs will visit the file.
9459 With a double prefix argument, try to open outside of Emacs, in the
9460 application the system uses for this file type."
9461 (interactive "P")
9462 ;; if in a code block, then open the block's results
9463 (unless (call-interactively #'org-babel-open-src-block-result)
9464 (org-load-modules-maybe)
9465 (move-marker org-open-link-marker (point))
9466 (setq org-window-config-before-follow-link (current-window-configuration))
9467 (org-remove-occur-highlights nil nil t)
9468 (cond
9469 ((and (org-on-heading-p)
9470 (not (org-in-regexp
9471 (concat org-plain-link-re "\\|"
9472 org-bracket-link-regexp "\\|"
9473 org-angle-link-re "\\|"
9474 "[ \t]:[^ \t\n]+:[ \t]*$")))
9475 (not (get-text-property (point) 'org-linked-text)))
9476 (or (org-offer-links-in-entry arg)
9477 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9478 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9479 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9480 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9481 (not (org-in-regexp org-bracket-link-regexp)))
9482 (org-footnote-action))
9484 (let (type path link line search (pos (point)))
9485 (catch 'match
9486 (save-excursion
9487 (skip-chars-forward "^]\n\r")
9488 (when (org-in-regexp org-bracket-link-regexp 1)
9489 (setq link (org-extract-attributes
9490 (org-link-unescape (org-match-string-no-properties 1))))
9491 (while (string-match " *\n *" link)
9492 (setq link (replace-match " " t t link)))
9493 (setq link (org-link-expand-abbrev link))
9494 (cond
9495 ((or (file-name-absolute-p link)
9496 (string-match "^\\.\\.?/" link))
9497 (setq type "file" path link))
9498 ((string-match org-link-re-with-space3 link)
9499 (setq type (match-string 1 link) path (match-string 2 link)))
9500 (t (setq type "thisfile" path link)))
9501 (throw 'match t)))
9503 (when (get-text-property (point) 'org-linked-text)
9504 (setq type "thisfile"
9505 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9506 (1+ (point)) (point))
9507 path (buffer-substring
9508 (or (previous-single-property-change pos 'org-linked-text)
9509 (point-min))
9510 (or (next-single-property-change pos 'org-linked-text)
9511 (point-max))))
9512 (throw 'match t))
9514 (save-excursion
9515 (when (or (org-in-regexp org-angle-link-re)
9516 (org-in-regexp org-plain-link-re))
9517 (setq type (match-string 1)
9518 path (org-link-unescape (match-string 2)))
9519 (throw 'match t)))
9520 (save-excursion
9521 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9522 (setq type "tags"
9523 path (match-string 1))
9524 (while (string-match ":" path)
9525 (setq path (replace-match "+" t t path)))
9526 (throw 'match t)))
9527 (when (org-in-regexp "<\\([^><\n]+\\)>")
9528 (setq type "tree-match"
9529 path (match-string 1))
9530 (throw 'match t)))
9531 (unless path
9532 (error "No link found"))
9534 ;; switch back to reference buffer
9535 ;; needed when if called in a temporary buffer through
9536 ;; org-open-link-from-string
9537 (with-current-buffer (or reference-buffer (current-buffer))
9539 ;; Remove any trailing spaces in path
9540 (if (string-match " +\\'" path)
9541 (setq path (replace-match "" t t path)))
9542 (if (and org-link-translation-function
9543 (fboundp org-link-translation-function))
9544 ;; Check if we need to translate the link
9545 (let ((tmp (funcall org-link-translation-function type path)))
9546 (setq type (car tmp) path (cdr tmp))))
9548 (cond
9550 ((assoc type org-link-protocols)
9551 (funcall (nth 1 (assoc type org-link-protocols)) path))
9553 ((equal type "mailto")
9554 (let ((cmd (car org-link-mailto-program))
9555 (args (cdr org-link-mailto-program)) args1
9556 (address path) (subject "") a)
9557 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9558 (setq address (match-string 1 path)
9559 subject (org-link-escape (match-string 2 path))))
9560 (while args
9561 (cond
9562 ((not (stringp (car args))) (push (pop args) args1))
9563 (t (setq a (pop args))
9564 (if (string-match "%a" a)
9565 (setq a (replace-match address t t a)))
9566 (if (string-match "%s" a)
9567 (setq a (replace-match subject t t a)))
9568 (push a args1))))
9569 (apply cmd (nreverse args1))))
9571 ((member type '("http" "https" "ftp" "news"))
9572 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9573 (org-link-escape
9574 path org-link-escape-chars-browser)
9575 path))))
9577 ((string= type "doi")
9578 (browse-url (concat "http://dx.doi.org/" (if (org-string-match-p "[[:nonascii:] ]" path)
9579 (org-link-escape
9580 path org-link-escape-chars-browser)
9581 path))))
9583 ((member type '("message"))
9584 (browse-url (concat type ":" path)))
9586 ((string= type "tags")
9587 (org-tags-view arg path))
9589 ((string= type "tree-match")
9590 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9592 ((string= type "file")
9593 (if (string-match "::\\([0-9]+\\)\\'" path)
9594 (setq line (string-to-number (match-string 1 path))
9595 path (substring path 0 (match-beginning 0)))
9596 (if (string-match "::\\(.+\\)\\'" path)
9597 (setq search (match-string 1 path)
9598 path (substring path 0 (match-beginning 0)))))
9599 (if (string-match "[*?{]" (file-name-nondirectory path))
9600 (dired path)
9601 (org-open-file path arg line search)))
9603 ((string= type "shell")
9604 (let ((cmd path))
9605 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9606 (string-match org-confirm-shell-link-not-regexp cmd))
9607 (not org-confirm-shell-link-function)
9608 (funcall org-confirm-shell-link-function
9609 (format "Execute \"%s\" in shell? "
9610 (org-add-props cmd nil
9611 'face 'org-warning))))
9612 (progn
9613 (message "Executing %s" cmd)
9614 (shell-command cmd))
9615 (error "Abort"))))
9617 ((string= type "elisp")
9618 (let ((cmd path))
9619 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9620 (string-match org-confirm-elisp-link-not-regexp cmd))
9621 (not org-confirm-elisp-link-function)
9622 (funcall org-confirm-elisp-link-function
9623 (format "Execute \"%s\" as elisp? "
9624 (org-add-props cmd nil
9625 'face 'org-warning))))
9626 (message "%s => %s" cmd
9627 (if (equal (string-to-char cmd) ?\()
9628 (eval (read cmd))
9629 (call-interactively (read cmd))))
9630 (error "Abort"))))
9632 ((and (string= type "thisfile")
9633 (run-hook-with-args-until-success
9634 'org-open-link-functions path)))
9636 ((string= type "thisfile")
9637 (if arg
9638 (switch-to-buffer-other-window
9639 (org-get-buffer-for-internal-link (current-buffer)))
9640 (org-mark-ring-push))
9641 (let ((cmd `(org-link-search
9642 ,path
9643 ,(cond ((equal arg '(4)) ''occur)
9644 ((equal arg '(16)) ''org-occur)
9645 (t nil))
9646 ,pos)))
9647 (condition-case nil (let ((org-link-search-inhibit-query t))
9648 (eval cmd))
9649 (error (progn (widen) (eval cmd))))))
9652 (browse-url-at-point)))))))
9653 (move-marker org-open-link-marker nil)
9654 (run-hook-with-args 'org-follow-link-hook)))
9656 (defun org-offer-links-in-entry (&optional nth zero)
9657 "Offer links in the current entry and follow the selected link.
9658 If there is only one link, follow it immediately as well.
9659 If NTH is an integer, immediately pick the NTH link found.
9660 If ZERO is a string, check also this string for a link, and if
9661 there is one, offer it as link number zero."
9662 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9663 "\\(" org-angle-link-re "\\)\\|"
9664 "\\(" org-plain-link-re "\\)"))
9665 (cnt ?0)
9666 (in-emacs (if (integerp nth) nil nth))
9667 have-zero end links link c)
9668 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9669 (push (match-string 0 zero) links)
9670 (setq cnt (1- cnt) have-zero t))
9671 (save-excursion
9672 (org-back-to-heading t)
9673 (setq end (save-excursion (outline-next-heading) (point)))
9674 (while (re-search-forward re end t)
9675 (push (match-string 0) links))
9676 (setq links (org-uniquify (reverse links))))
9678 (cond
9679 ((null links)
9680 (message "No links"))
9681 ((equal (length links) 1)
9682 (setq link (list (car links))))
9683 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9684 (setq link (list (nth (if have-zero nth (1- nth)) links))))
9685 (t ; we have to select a link
9686 (save-excursion
9687 (save-window-excursion
9688 (delete-other-windows)
9689 (with-output-to-temp-buffer "*Select Link*"
9690 (mapc (lambda (l)
9691 (if (not (string-match org-bracket-link-regexp l))
9692 (princ (format "[%c] %s\n" (incf cnt)
9693 (org-remove-angle-brackets l)))
9694 (if (match-end 3)
9695 (princ (format "[%c] %s (%s)\n" (incf cnt)
9696 (match-string 3 l) (match-string 1 l)))
9697 (princ (format "[%c] %s\n" (incf cnt)
9698 (match-string 1 l))))))
9699 links))
9700 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9701 (message "Select link to open, RET to open all:")
9702 (setq c (read-char-exclusive))
9703 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9704 (when (equal c ?q) (error "Abort"))
9705 (if (equal c ?\C-m)
9706 (setq link links)
9707 (setq nth (- c ?0))
9708 (if have-zero (setq nth (1+ nth)))
9709 (unless (and (integerp nth) (>= (length links) nth))
9710 (error "Invalid link selection"))
9711 (setq link (list (nth (1- nth) links))))))
9712 (if link
9713 (let ((buf (current-buffer)))
9714 (dolist (l link)
9715 (org-open-link-from-string l in-emacs buf))
9717 nil)))
9719 ;; Add special file links that specify the way of opening
9721 (org-add-link-type "file+sys" 'org-open-file-with-system)
9722 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9723 (defun org-open-file-with-system (path)
9724 "Open file at PATH using the system way of opening it."
9725 (org-open-file path 'system))
9726 (defun org-open-file-with-emacs (path)
9727 "Open file at PATH in Emacs."
9728 (org-open-file path 'emacs))
9729 (defun org-remove-file-link-modifiers ()
9730 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9731 (goto-char (point-min))
9732 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9733 (org-if-unprotected
9734 (replace-match "file:" t t))))
9735 (eval-after-load "org-exp"
9736 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9737 'org-remove-file-link-modifiers))
9739 ;;;; Time estimates
9741 (defun org-get-effort (&optional pom)
9742 "Get the effort estimate for the current entry."
9743 (org-entry-get pom org-effort-property))
9745 ;;; File search
9747 (defvar org-create-file-search-functions nil
9748 "List of functions to construct the right search string for a file link.
9749 These functions are called in turn with point at the location to
9750 which the link should point.
9752 A function in the hook should first test if it would like to
9753 handle this file type, for example by checking the `major-mode'
9754 or the file extension. If it decides not to handle this file, it
9755 should just return nil to give other functions a chance. If it
9756 does handle the file, it must return the search string to be used
9757 when following the link. The search string will be part of the
9758 file link, given after a double colon, and `org-open-at-point'
9759 will automatically search for it. If special measures must be
9760 taken to make the search successful, another function should be
9761 added to the companion hook `org-execute-file-search-functions',
9762 which see.
9764 A function in this hook may also use `setq' to set the variable
9765 `description' to provide a suggestion for the descriptive text to
9766 be used for this link when it gets inserted into an Org-mode
9767 buffer with \\[org-insert-link].")
9769 (defvar org-execute-file-search-functions nil
9770 "List of functions to execute a file search triggered by a link.
9772 Functions added to this hook must accept a single argument, the
9773 search string that was part of the file link, the part after the
9774 double colon. The function must first check if it would like to
9775 handle this search, for example by checking the `major-mode' or
9776 the file extension. If it decides not to handle this search, it
9777 should just return nil to give other functions a chance. If it
9778 does handle the search, it must return a non-nil value to keep
9779 other functions from trying.
9781 Each function can access the current prefix argument through the
9782 variable `current-prefix-argument'. Note that a single prefix is
9783 used to force opening a link in Emacs, so it may be good to only
9784 use a numeric or double prefix to guide the search function.
9786 In case this is needed, a function in this hook can also restore
9787 the window configuration before `org-open-at-point' was called using:
9789 (set-window-configuration org-window-config-before-follow-link)")
9791 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9792 (defun org-link-search (s &optional type avoid-pos stealth)
9793 "Search for a link search option.
9794 If S is surrounded by forward slashes, it is interpreted as a
9795 regular expression. In org-mode files, this will create an `org-occur'
9796 sparse tree. In ordinary files, `occur' will be used to list matches.
9797 If the current buffer is in `dired-mode', grep will be used to search
9798 in all files. If AVOID-POS is given, ignore matches near that position.
9800 When optional argument STEALTH is non-nil, do not modify
9801 visibility around point, thus ignoring
9802 `org-show-hierarchy-above', `org-show-following-heading' and
9803 `org-show-siblings' variables."
9804 (let ((case-fold-search t)
9805 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9806 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9807 (append '(("") (" ") ("\t") ("\n"))
9808 org-emphasis-alist)
9809 "\\|") "\\)"))
9810 (pos (point))
9811 (pre nil) (post nil)
9812 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9813 (cond
9814 ;; First check if there are any special search functions
9815 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9816 ;; Now try the builtin stuff
9817 ((and (equal (string-to-char s0) ?#)
9818 (> (length s0) 1)
9819 (save-excursion
9820 (goto-char (point-min))
9821 (and
9822 (re-search-forward
9823 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9824 (setq type 'dedicated
9825 pos (match-beginning 0))))
9826 ;; There is an exact target for this
9827 (goto-char pos)
9828 (org-back-to-heading t)))
9829 ((save-excursion
9830 (goto-char (point-min))
9831 (and
9832 (re-search-forward
9833 (concat "<<" (regexp-quote s0) ">>") nil t)
9834 (setq type 'dedicated
9835 pos (match-beginning 0))))
9836 ;; There is an exact target for this
9837 (goto-char pos))
9838 ((and (string-match "^(\\(.*\\))$" s0)
9839 (save-excursion
9840 (goto-char (point-min))
9841 (and
9842 (re-search-forward
9843 (concat "[^[]" (regexp-quote
9844 (format org-coderef-label-format
9845 (match-string 1 s0))))
9846 nil t)
9847 (setq type 'dedicated
9848 pos (1+ (match-beginning 0))))))
9849 ;; There is a coderef target for this
9850 (goto-char pos))
9851 ((string-match "^/\\(.*\\)/$" s)
9852 ;; A regular expression
9853 (cond
9854 ((eq major-mode 'org-mode)
9855 (org-occur (match-string 1 s)))
9856 ;;((eq major-mode 'dired-mode)
9857 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9858 (t (org-do-occur (match-string 1 s)))))
9859 ((and (eq major-mode 'org-mode) org-link-search-must-match-exact-headline)
9860 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
9861 (goto-char (point-min))
9862 (cond
9863 ((let (case-fold-search)
9864 (re-search-forward (format org-complex-heading-regexp-format
9865 (regexp-quote s))
9866 nil t))
9867 ;; OK, found a match
9868 (setq type 'dedicated)
9869 (goto-char (match-beginning 0)))
9870 ((and (not org-link-search-inhibit-query)
9871 (eq org-link-search-must-match-exact-headline 'query-to-create)
9872 (y-or-n-p "No match - create this as a new heading? "))
9873 (goto-char (point-max))
9874 (or (bolp) (newline))
9875 (insert "* " s "\n")
9876 (beginning-of-line 0))
9878 (goto-char pos)
9879 (error "No match"))))
9881 ;; A normal search string
9882 (when (equal (string-to-char s) ?*)
9883 ;; Anchor on headlines, post may include tags.
9884 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
9885 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
9886 s (substring s 1)))
9887 (remove-text-properties
9888 0 (length s)
9889 '(face nil mouse-face nil keymap nil fontified nil) s)
9890 ;; Make a series of regular expressions to find a match
9891 (setq words (org-split-string s "[ \n\r\t]+")
9893 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9894 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
9895 "\\)" markers)
9896 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9897 re2a (concat "[ \t\r\n]" re2a_)
9898 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9899 re4 (concat "[^a-zA-Z_]" re4_)
9901 re1 (concat pre re2 post)
9902 re3 (concat pre (if pre re4_ re4) post)
9903 re5 (concat pre ".*" re4)
9904 re2 (concat pre re2)
9905 re2a (concat pre (if pre re2a_ re2a))
9906 re4 (concat pre (if pre re4_ re4))
9907 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9908 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9909 re5 "\\)"
9911 (cond
9912 ((eq type 'org-occur) (org-occur reall))
9913 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9914 (t (goto-char (point-min))
9915 (setq type 'fuzzy)
9916 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
9917 (org-search-not-self 1 re1 nil t)
9918 (org-search-not-self 1 re2 nil t)
9919 (org-search-not-self 1 re2a nil t)
9920 (org-search-not-self 1 re3 nil t)
9921 (org-search-not-self 1 re4 nil t)
9922 (org-search-not-self 1 re5 nil t)
9924 (goto-char (match-beginning 1))
9925 (goto-char pos)
9926 (error "No match"))))))
9927 (and (eq major-mode 'org-mode)
9928 (not stealth)
9929 (org-show-context 'link-search))
9930 type))
9932 (defun org-search-not-self (group &rest args)
9933 "Execute `re-search-forward', but only accept matches that do not
9934 enclose the position of `org-open-link-marker'."
9935 (let ((m org-open-link-marker))
9936 (catch 'exit
9937 (while (apply 're-search-forward args)
9938 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
9939 (goto-char (match-end group))
9940 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
9941 (> (match-beginning 0) (marker-position m))
9942 (< (match-end 0) (marker-position m)))
9943 (save-match-data
9944 (or (not (org-in-regexp
9945 org-bracket-link-analytic-regexp 1))
9946 (not (match-end 4)) ; no description
9947 (and (<= (match-beginning 4) (point))
9948 (>= (match-end 4) (point))))))
9949 (throw 'exit (point))))))))
9951 (defun org-get-buffer-for-internal-link (buffer)
9952 "Return a buffer to be used for displaying the link target of internal links."
9953 (cond
9954 ((not org-display-internal-link-with-indirect-buffer)
9955 buffer)
9956 ((string-match "(Clone)$" (buffer-name buffer))
9957 (message "Buffer is already a clone, not making another one")
9958 ;; we also do not modify visibility in this case
9959 buffer)
9960 (t ; make a new indirect buffer for displaying the link
9961 (let* ((bn (buffer-name buffer))
9962 (ibn (concat bn "(Clone)"))
9963 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
9964 (with-current-buffer ib (org-overview))
9965 ib))))
9967 (defun org-do-occur (regexp &optional cleanup)
9968 "Call the Emacs command `occur'.
9969 If CLEANUP is non-nil, remove the printout of the regular expression
9970 in the *Occur* buffer. This is useful if the regex is long and not useful
9971 to read."
9972 (occur regexp)
9973 (when cleanup
9974 (let ((cwin (selected-window)) win beg end)
9975 (when (setq win (get-buffer-window "*Occur*"))
9976 (select-window win))
9977 (goto-char (point-min))
9978 (when (re-search-forward "match[a-z]+" nil t)
9979 (setq beg (match-end 0))
9980 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9981 (setq end (1- (match-beginning 0)))))
9982 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
9983 (goto-char (point-min))
9984 (select-window cwin))))
9986 ;;; The mark ring for links jumps
9988 (defvar org-mark-ring nil
9989 "Mark ring for positions before jumps in Org-mode.")
9990 (defvar org-mark-ring-last-goto nil
9991 "Last position in the mark ring used to go back.")
9992 ;; Fill and close the ring
9993 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9994 (loop for i from 1 to org-mark-ring-length do
9995 (push (make-marker) org-mark-ring))
9996 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
9997 org-mark-ring)
9999 (defun org-mark-ring-push (&optional pos buffer)
10000 "Put the current position or POS into the mark ring and rotate it."
10001 (interactive)
10002 (setq pos (or pos (point)))
10003 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10004 (move-marker (car org-mark-ring)
10005 (or pos (point))
10006 (or buffer (current-buffer)))
10007 (message "%s"
10008 (substitute-command-keys
10009 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10011 (defun org-mark-ring-goto (&optional n)
10012 "Jump to the previous position in the mark ring.
10013 With prefix arg N, jump back that many stored positions. When
10014 called several times in succession, walk through the entire ring.
10015 Org-mode commands jumping to a different position in the current file,
10016 or to another Org-mode file, automatically push the old position
10017 onto the ring."
10018 (interactive "p")
10019 (let (p m)
10020 (if (eq last-command this-command)
10021 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10022 (setq p org-mark-ring))
10023 (setq org-mark-ring-last-goto p)
10024 (setq m (car p))
10025 (org-pop-to-buffer-same-window (marker-buffer m))
10026 (goto-char m)
10027 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10029 (defun org-remove-angle-brackets (s)
10030 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10031 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10033 (defun org-add-angle-brackets (s)
10034 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10035 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10037 (defun org-remove-double-quotes (s)
10038 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10039 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10042 ;;; Following specific links
10044 (defun org-follow-timestamp-link ()
10045 (cond
10046 ((org-at-date-range-p t)
10047 (let ((org-agenda-start-on-weekday)
10048 (t1 (match-string 1))
10049 (t2 (match-string 2)))
10050 (setq t1 (time-to-days (org-time-string-to-time t1))
10051 t2 (time-to-days (org-time-string-to-time t2)))
10052 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10053 ((org-at-timestamp-p t)
10054 (org-agenda-list nil (time-to-days (org-time-string-to-time
10055 (substring (match-string 1) 0 10)))
10057 (t (error "This should not happen"))))
10060 ;;; Following file links
10061 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10062 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10063 (declare-function mailcap-mime-info
10064 "mailcap" (string &optional request no-decode))
10065 (defvar org-wait nil)
10066 (defun org-open-file (path &optional in-emacs line search)
10067 "Open the file at PATH.
10068 First, this expands any special file name abbreviations. Then the
10069 configuration variable `org-file-apps' is checked if it contains an
10070 entry for this file type, and if yes, the corresponding command is launched.
10072 If no application is found, Emacs simply visits the file.
10074 With optional prefix argument IN-EMACS, Emacs will visit the file.
10075 With a double \\[universal-argument] \\[universal-argument] \
10076 prefix arg, Org tries to avoid opening in Emacs
10077 and to use an external application to visit the file.
10079 Optional LINE specifies a line to go to, optional SEARCH a string
10080 to search for. If LINE or SEARCH is given, the file will be
10081 opened in Emacs, unless an entry from org-file-apps that makes
10082 use of groups in a regexp matches.
10084 If you want to change the way frames are used when following a
10085 link, please customize `org-link-frame-setup'.
10087 If the file does not exist, an error is thrown."
10088 (let* ((file (if (equal path "")
10089 buffer-file-name
10090 (substitute-in-file-name (expand-file-name path))))
10091 (file-apps (append org-file-apps (org-default-apps)))
10092 (apps (org-remove-if
10093 'org-file-apps-entry-match-against-dlink-p file-apps))
10094 (apps-dlink (org-remove-if-not
10095 'org-file-apps-entry-match-against-dlink-p file-apps))
10096 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10097 (dirp (if remp nil (file-directory-p file)))
10098 (file (if (and dirp org-open-directory-means-index-dot-org)
10099 (concat (file-name-as-directory file) "index.org")
10100 file))
10101 (a-m-a-p (assq 'auto-mode apps))
10102 (dfile (downcase file))
10103 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10104 (link (cond ((and (eq line nil)
10105 (eq search nil))
10106 file)
10107 (line
10108 (concat file "::" (number-to-string line)))
10109 (search
10110 (concat file "::" search))))
10111 (dlink (downcase link))
10112 (old-buffer (current-buffer))
10113 (old-pos (point))
10114 (old-mode major-mode)
10115 ext cmd link-match-data)
10116 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10117 (setq ext (match-string 1 dfile))
10118 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10119 (setq ext (match-string 1 dfile))))
10120 (cond
10121 ((member in-emacs '((16) system))
10122 (setq cmd (cdr (assoc 'system apps))))
10123 (in-emacs (setq cmd 'emacs))
10125 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10126 (and dirp (cdr (assoc 'directory apps)))
10127 ; first, try matching against apps-dlink
10128 ; if we get a match here, store the match data for later
10129 (let ((match (assoc-default dlink apps-dlink
10130 'string-match)))
10131 (if match
10132 (progn (setq link-match-data (match-data))
10133 match)
10134 (progn (setq in-emacs (or in-emacs line search))
10135 nil))) ; if we have no match in apps-dlink,
10136 ; always open the file in emacs if line or search
10137 ; is given (for backwards compatibility)
10138 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10139 'string-match)
10140 (cdr (assoc ext apps))
10141 (cdr (assoc t apps))))))
10142 (when (eq cmd 'system)
10143 (setq cmd (cdr (assoc 'system apps))))
10144 (when (eq cmd 'default)
10145 (setq cmd (cdr (assoc t apps))))
10146 (when (eq cmd 'mailcap)
10147 (require 'mailcap)
10148 (mailcap-parse-mailcaps)
10149 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10150 (command (mailcap-mime-info mime-type)))
10151 (if (stringp command)
10152 (setq cmd command)
10153 (setq cmd 'emacs))))
10154 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10155 (not (file-exists-p file))
10156 (not org-open-non-existing-files))
10157 (error "No such file: %s" file))
10158 (cond
10159 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10160 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10161 (while (string-match "['\"]%s['\"]" cmd)
10162 (setq cmd (replace-match "%s" t t cmd)))
10163 (while (string-match "%s" cmd)
10164 (setq cmd (replace-match
10165 (save-match-data
10166 (shell-quote-argument
10167 (convert-standard-filename file)))
10168 t t cmd)))
10170 ;; Replace "%1", "%2" etc. in command with group matches from regex
10171 (save-match-data
10172 (let ((match-index 1)
10173 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10174 (set-match-data link-match-data)
10175 (while (<= match-index number-of-groups)
10176 (let ((regex (concat "%" (number-to-string match-index)))
10177 (replace-with (match-string match-index dlink)))
10178 (while (string-match regex cmd)
10179 (setq cmd (replace-match replace-with t t cmd))))
10180 (setq match-index (+ match-index 1)))))
10182 (save-window-excursion
10183 (start-process-shell-command cmd nil cmd)
10184 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10186 ((or (stringp cmd)
10187 (eq cmd 'emacs))
10188 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10189 (widen)
10190 (if line (org-goto-line line)
10191 (if search (org-link-search search))))
10192 ((consp cmd)
10193 (let ((file (convert-standard-filename file)))
10194 (save-match-data
10195 (set-match-data link-match-data)
10196 (eval cmd))))
10197 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10198 (and (eq major-mode 'org-mode) (eq old-mode 'org-mode)
10199 (or (not (equal old-buffer (current-buffer)))
10200 (not (equal old-pos (point))))
10201 (org-mark-ring-push old-pos old-buffer))))
10203 (defun org-file-apps-entry-match-against-dlink-p (entry)
10204 "This function returns non-nil if `entry' uses a regular
10205 expression which should be matched against the whole link by
10206 org-open-file.
10208 It assumes that is the case when the entry uses a regular
10209 expression which has at least one grouping construct and the
10210 action is either a lisp form or a command string containing
10211 '%1', i.e. using at least one subexpression match as a
10212 parameter."
10213 (let ((selector (car entry))
10214 (action (cdr entry)))
10215 (if (stringp selector)
10216 (and (> (regexp-opt-depth selector) 0)
10217 (or (and (stringp action)
10218 (string-match "%[0-9]" action))
10219 (consp action)))
10220 nil)))
10222 (defun org-default-apps ()
10223 "Return the default applications for this operating system."
10224 (cond
10225 ((eq system-type 'darwin)
10226 org-file-apps-defaults-macosx)
10227 ((eq system-type 'windows-nt)
10228 org-file-apps-defaults-windowsnt)
10229 (t org-file-apps-defaults-gnu)))
10231 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10232 "Convert extensions to regular expressions in the cars of LIST.
10233 Also, weed out any non-string entries, because the return value is used
10234 only for regexp matching.
10235 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10236 point to the symbol `emacs', indicating that the file should
10237 be opened in Emacs."
10238 (append
10239 (delq nil
10240 (mapcar (lambda (x)
10241 (if (not (stringp (car x)))
10243 (if (string-match "\\W" (car x))
10245 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10246 list))
10247 (if add-auto-mode
10248 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10250 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10251 (defun org-file-remote-p (file)
10252 "Test whether FILE specifies a location on a remote system.
10253 Return non-nil if the location is indeed remote.
10255 For example, the filename \"/user@host:/foo\" specifies a location
10256 on the system \"/user@host:\"."
10257 (cond ((fboundp 'file-remote-p)
10258 (file-remote-p file))
10259 ((fboundp 'tramp-handle-file-remote-p)
10260 (tramp-handle-file-remote-p file))
10261 ((and (boundp 'ange-ftp-name-format)
10262 (string-match (car ange-ftp-name-format) file))
10264 (t nil)))
10267 ;;;; Refiling
10269 (defun org-get-org-file ()
10270 "Read a filename, with default directory `org-directory'."
10271 (let ((default (or org-default-notes-file remember-data-file)))
10272 (read-file-name (format "File name [%s]: " default)
10273 (file-name-as-directory org-directory)
10274 default)))
10276 (defun org-notes-order-reversed-p ()
10277 "Check if the current file should receive notes in reversed order."
10278 (cond
10279 ((not org-reverse-note-order) nil)
10280 ((eq t org-reverse-note-order) t)
10281 ((not (listp org-reverse-note-order)) nil)
10282 (t (catch 'exit
10283 (let ((all org-reverse-note-order)
10284 entry)
10285 (while (setq entry (pop all))
10286 (if (string-match (car entry) buffer-file-name)
10287 (throw 'exit (cdr entry))))
10288 nil)))))
10290 (defvar org-refile-target-table nil
10291 "The list of refile targets, created by `org-refile'.")
10293 (defvar org-agenda-new-buffers nil
10294 "Buffers created to visit agenda files.")
10296 (defvar org-refile-cache nil
10297 "Cache for refile targets.")
10299 (defvar org-refile-markers nil
10300 "All the markers used for caching refile locations.")
10302 (defun org-refile-marker (pos)
10303 "Get a new refile marker, but only if caching is in use."
10304 (if (not org-refile-use-cache)
10306 (let ((m (make-marker)))
10307 (move-marker m pos)
10308 (push m org-refile-markers)
10309 m)))
10311 (defun org-refile-cache-clear ()
10312 "Clear the refile cache and disable all the markers."
10313 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10314 (setq org-refile-markers nil)
10315 (setq org-refile-cache nil)
10316 (message "Refile cache has been cleared"))
10318 (defun org-refile-cache-check-set (set)
10319 "Check if all the markers in the cache still have live buffers."
10320 (let (marker)
10321 (catch 'exit
10322 (while (and set (setq marker (nth 3 (pop set))))
10323 ;; if org-refile-use-outline-path is 'file, marker may be nil
10324 (when (and marker (null (marker-buffer marker)))
10325 (message "not found") (sit-for 3)
10326 (throw 'exit nil)))
10327 t)))
10329 (defun org-refile-cache-put (set &rest identifiers)
10330 "Push the refile targets SET into the cache, under IDENTIFIERS."
10331 (let* ((key (sha1 (prin1-to-string identifiers)))
10332 (entry (assoc key org-refile-cache)))
10333 (if entry
10334 (setcdr entry set)
10335 (push (cons key set) org-refile-cache))))
10337 (defun org-refile-cache-get (&rest identifiers)
10338 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10339 (cond
10340 ((not org-refile-cache) nil)
10341 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10343 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10344 org-refile-cache))))
10345 (and set (org-refile-cache-check-set set) set)))))
10347 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10348 "Produce a table with refile targets."
10349 (let ((case-fold-search nil)
10350 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10351 (entries (or org-refile-targets '((nil . (:level . 1)))))
10352 targets tgs txt re files f desc descre fast-path-p level pos0)
10353 (message "Getting targets...")
10354 (with-current-buffer (or default-buffer (current-buffer))
10355 (while (setq entry (pop entries))
10356 (setq files (car entry) desc (cdr entry))
10357 (setq fast-path-p nil)
10358 (cond
10359 ((null files) (setq files (list (current-buffer))))
10360 ((eq files 'org-agenda-files)
10361 (setq files (org-agenda-files 'unrestricted)))
10362 ((and (symbolp files) (fboundp files))
10363 (setq files (funcall files)))
10364 ((and (symbolp files) (boundp files))
10365 (setq files (symbol-value files))))
10366 (if (stringp files) (setq files (list files)))
10367 (cond
10368 ((eq (car desc) :tag)
10369 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10370 ((eq (car desc) :todo)
10371 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10372 ((eq (car desc) :regexp)
10373 (setq descre (cdr desc)))
10374 ((eq (car desc) :level)
10375 (setq descre (concat "^\\*\\{" (number-to-string
10376 (if org-odd-levels-only
10377 (1- (* 2 (cdr desc)))
10378 (cdr desc)))
10379 "\\}[ \t]")))
10380 ((eq (car desc) :maxlevel)
10381 (setq fast-path-p t)
10382 (setq descre (concat "^\\*\\{1," (number-to-string
10383 (if org-odd-levels-only
10384 (1- (* 2 (cdr desc)))
10385 (cdr desc)))
10386 "\\}[ \t]")))
10387 (t (error "Bad refiling target description %s" desc)))
10388 (while (setq f (pop files))
10389 (with-current-buffer
10390 (if (bufferp f) f (org-get-agenda-file-buffer f))
10392 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10393 (progn
10394 (if (bufferp f) (setq f (buffer-file-name
10395 (buffer-base-buffer f))))
10396 (setq f (and f (expand-file-name f)))
10397 (if (eq org-refile-use-outline-path 'file)
10398 (push (list (file-name-nondirectory f) f nil nil) tgs))
10399 (save-excursion
10400 (save-restriction
10401 (widen)
10402 (goto-char (point-min))
10403 (while (re-search-forward descre nil t)
10404 (goto-char (setq pos0 (point-at-bol)))
10405 (catch 'next
10406 (when org-refile-target-verify-function
10407 (save-match-data
10408 (or (funcall org-refile-target-verify-function)
10409 (throw 'next t))))
10410 (when (and (looking-at org-complex-heading-regexp)
10411 (not (member (match-string 4) excluded-entries))
10412 (match-string 4))
10413 (setq level (org-reduced-level
10414 (- (match-end 1) (match-beginning 1)))
10415 txt (org-link-display-format (match-string 4))
10416 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10417 re (format org-complex-heading-regexp-format
10418 (regexp-quote (match-string 4))))
10419 (when org-refile-use-outline-path
10420 (setq txt (mapconcat
10421 'org-protect-slash
10422 (append
10423 (if (eq org-refile-use-outline-path
10424 'file)
10425 (list (file-name-nondirectory
10426 (buffer-file-name
10427 (buffer-base-buffer))))
10428 (if (eq org-refile-use-outline-path
10429 'full-file-path)
10430 (list (buffer-file-name
10431 (buffer-base-buffer)))))
10432 (org-get-outline-path fast-path-p
10433 level txt)
10434 (list txt))
10435 "/")))
10436 (push (list txt f re (org-refile-marker (point)))
10437 tgs)))
10438 (when (= (point) pos0)
10439 ;; verification function has not moved point
10440 (goto-char (point-at-eol))))))))
10441 (when org-refile-use-cache
10442 (org-refile-cache-put tgs (buffer-file-name) descre))
10443 (setq targets (append tgs targets))
10444 ))))
10445 (message "Getting targets...done")
10446 (nreverse targets)))
10448 (defun org-protect-slash (s)
10449 (while (string-match "/" s)
10450 (setq s (replace-match "\\" t t s)))
10453 (defvar org-olpa (make-vector 20 nil))
10455 (defun org-get-outline-path (&optional fastp level heading)
10456 "Return the outline path to the current entry, as a list.
10458 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10459 routine which makes outline path derivations for an entire file,
10460 avoiding backtracing. Refile target collection makes use of that."
10461 (if fastp
10462 (progn
10463 (if (> level 19)
10464 (error "Outline path failure, more than 19 levels"))
10465 (loop for i from level upto 19 do
10466 (aset org-olpa i nil))
10467 (prog1
10468 (delq nil (append org-olpa nil))
10469 (aset org-olpa level heading)))
10470 (let (rtn case-fold-search)
10471 (save-excursion
10472 (save-restriction
10473 (widen)
10474 (while (org-up-heading-safe)
10475 (when (looking-at org-complex-heading-regexp)
10476 (push (org-match-string-no-properties 4) rtn)))
10477 rtn)))))
10479 (defun org-format-outline-path (path &optional width prefix)
10480 "Format the outline path PATH for display.
10481 Width is the maximum number of characters that is available.
10482 Prefix is a prefix to be included in the returned string,
10483 such as the file name."
10484 (setq width (or width 79))
10485 (if prefix (setq width (- width (length prefix))))
10486 (if (not path)
10487 (or prefix "")
10488 (let* ((nsteps (length path))
10489 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10490 (maxwidth (if (<= total-width width)
10491 10000 ;; everything fits
10492 ;; we need to shorten the level headings
10493 (/ (- width nsteps) nsteps)))
10494 (org-odd-levels-only nil)
10495 (n 0)
10496 (total (1+ (length prefix))))
10497 (setq maxwidth (max maxwidth 10))
10498 (concat prefix
10499 (mapconcat
10500 (lambda (h)
10501 (setq n (1+ n))
10502 (if (and (= n nsteps) (< maxwidth 10000))
10503 (setq maxwidth (- total-width total)))
10504 (if (< (length h) maxwidth)
10505 (progn (setq total (+ total (length h) 1)) h)
10506 (setq h (substring h 0 (- maxwidth 2))
10507 total (+ total maxwidth 1))
10508 (if (string-match "[ \t]+\\'" h)
10509 (setq h (substring h 0 (match-beginning 0))))
10510 (setq h (concat h "..")))
10511 (org-add-props h nil 'face
10512 (nth (% (1- n) org-n-level-faces)
10513 org-level-faces))
10515 path "/")))))
10517 (defun org-display-outline-path (&optional file current)
10518 "Display the current outline path in the echo area."
10519 (interactive "P")
10520 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10521 (case-fold-search nil)
10522 (path (and (eq major-mode 'org-mode) (org-get-outline-path))))
10523 (if current (setq path (append path
10524 (save-excursion
10525 (org-back-to-heading t)
10526 (if (looking-at org-complex-heading-regexp)
10527 (list (match-string 4)))))))
10528 (message "%s"
10529 (org-format-outline-path
10530 path
10531 (1- (frame-width))
10532 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10534 (defvar org-refile-history nil
10535 "History for refiling operations.")
10537 (defvar org-after-refile-insert-hook nil
10538 "Hook run after `org-refile' has inserted its stuff at the new location.
10539 Note that this is still *before* the stuff will be removed from
10540 the *old* location.")
10542 (defvar org-capture-last-stored-marker)
10543 (defun org-refile (&optional goto default-buffer rfloc)
10544 "Move the entry or entries at point to another heading.
10545 The list of target headings is compiled using the information in
10546 `org-refile-targets', which see.
10548 At the target location, the entry is filed as a subitem of the target
10549 heading. Depending on `org-reverse-note-order', the new subitem will
10550 either be the first or the last subitem.
10552 If there is an active region, all entries in that region will be moved.
10553 However, the region must fulfill the requirement that the first heading
10554 is the first one sets the top-level of the moved text - at most siblings
10555 below it are allowed.
10557 With prefix arg GOTO, the command will only visit the target location
10558 and not actually move anything.
10560 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10561 go to the location where the last refiling operation has put the subtree.
10562 With a prefix argument of `2', refile to the running clock.
10564 RFLOC can be a refile location obtained in a different way.
10566 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10568 If you are using target caching (see `org-refile-use-cache'),
10569 You have to clear the target cache in order to find new targets.
10570 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10571 prefix argument (`C-u C-u C-u C-c C-w')."
10573 (interactive "P")
10574 (if (member goto '(0 (64)))
10575 (org-refile-cache-clear)
10576 (let* ((cbuf (current-buffer))
10577 (regionp (org-region-active-p))
10578 (region-start (and regionp (region-beginning)))
10579 (region-end (and regionp (region-end)))
10580 (region-length (and regionp (- region-end region-start)))
10581 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10582 pos it nbuf file re level reversed)
10583 (setq last-command nil)
10584 (when regionp
10585 (goto-char region-start)
10586 (or (bolp) (goto-char (point-at-bol)))
10587 (setq region-start (point))
10588 (unless (or (org-kill-is-subtree-p
10589 (buffer-substring region-start region-end))
10590 (prog1 org-refile-active-region-within-subtree
10591 (org-toggle-heading)))
10592 (error "The region is not a (sequence of) subtree(s)")))
10593 (if (equal goto '(16))
10594 (org-refile-goto-last-stored)
10595 (when (or
10596 (and (equal goto 2)
10597 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10598 (prog1
10599 (setq it (list (or org-clock-heading "running clock")
10600 (buffer-file-name
10601 (marker-buffer org-clock-hd-marker))
10603 (marker-position org-clock-hd-marker)))
10604 (setq goto nil)))
10605 (setq it (or rfloc
10606 (let (heading-text)
10607 (save-excursion
10608 (unless goto
10609 (org-back-to-heading t)
10610 (setq heading-text
10611 (nth 4 (org-heading-components))))
10612 (org-refile-get-location
10613 (cond (goto "Goto")
10614 (regionp "Refile region to")
10615 (t (concat "Refile subtree \""
10616 heading-text "\" to")))
10617 default-buffer
10618 org-refile-allow-creating-parent-nodes
10619 goto))))))
10620 (setq file (nth 1 it)
10621 re (nth 2 it)
10622 pos (nth 3 it))
10623 (if (and (not goto)
10625 (equal (buffer-file-name) file)
10626 (if regionp
10627 (and (>= pos region-start)
10628 (<= pos region-end))
10629 (and (>= pos (point))
10630 (< pos (save-excursion
10631 (org-end-of-subtree t t))))))
10632 (error "Cannot refile to position inside the tree or region"))
10634 (setq nbuf (or (find-buffer-visiting file)
10635 (find-file-noselect file)))
10636 (if goto
10637 (progn
10638 (org-pop-to-buffer-same-window nbuf)
10639 (goto-char pos)
10640 (org-show-context 'org-goto))
10641 (if regionp
10642 (progn
10643 (org-kill-new (buffer-substring region-start region-end))
10644 (org-save-markers-in-region region-start region-end))
10645 (org-copy-subtree 1 nil t))
10646 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10647 (find-file-noselect file)))
10648 (setq reversed (org-notes-order-reversed-p))
10649 (save-excursion
10650 (save-restriction
10651 (widen)
10652 (if pos
10653 (progn
10654 (goto-char pos)
10655 (looking-at org-outline-regexp)
10656 (setq level (org-get-valid-level (funcall outline-level) 1))
10657 (goto-char
10658 (if reversed
10659 (or (outline-next-heading) (point-max))
10660 (or (save-excursion (org-get-next-sibling))
10661 (org-end-of-subtree t t)
10662 (point-max)))))
10663 (setq level 1)
10664 (if (not reversed)
10665 (goto-char (point-max))
10666 (goto-char (point-min))
10667 (or (outline-next-heading) (goto-char (point-max)))))
10668 (if (not (bolp)) (newline))
10669 (org-paste-subtree level)
10670 (when org-log-refile
10671 (org-add-log-setup 'refile nil nil 'findpos
10672 org-log-refile)
10673 (unless (eq org-log-refile 'note)
10674 (save-excursion (org-add-log-note))))
10675 (and org-auto-align-tags (org-set-tags nil t))
10676 (bookmark-set "org-refile-last-stored")
10677 ;; If we are refiling for capture, make sure that the
10678 ;; last-capture pointers point here
10679 (when (org-bound-and-true-p org-refile-for-capture)
10680 (bookmark-set "org-capture-last-stored-marker")
10681 (move-marker org-capture-last-stored-marker (point)))
10682 (if (fboundp 'deactivate-mark) (deactivate-mark))
10683 (run-hooks 'org-after-refile-insert-hook))))
10684 (if regionp
10685 (delete-region (point) (+ (point) region-length))
10686 (org-cut-subtree))
10687 (when (featurep 'org-inlinetask)
10688 (org-inlinetask-remove-END-maybe))
10689 (setq org-markers-to-move nil)
10690 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10692 (defun org-refile-goto-last-stored ()
10693 "Go to the location where the last refile was stored."
10694 (interactive)
10695 (bookmark-jump "org-refile-last-stored")
10696 (message "This is the location of the last refile"))
10698 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10699 no-exclude)
10700 "Prompt the user for a refile location, using PROMPT.
10701 PROMPT should not be suffixed with a colon and a space, because
10702 this function appends the default value from
10703 `org-refile-history' automatically, if that is not empty.
10704 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10705 this is used for the GOTO interface."
10706 (let ((org-refile-targets org-refile-targets)
10707 (org-refile-use-outline-path org-refile-use-outline-path)
10708 excluded-entries)
10709 (when (and (eq major-mode 'org-mode)
10710 (not org-refile-use-cache)
10711 (not no-exclude))
10712 (org-map-tree
10713 (lambda()
10714 (setq excluded-entries
10715 (append excluded-entries (list (org-get-heading t t)))))))
10716 (setq org-refile-target-table
10717 (org-refile-get-targets default-buffer excluded-entries)))
10718 (unless org-refile-target-table
10719 (error "No refile targets"))
10720 (let* ((prompt (concat prompt
10721 (and (car org-refile-history)
10722 (concat " (default " (car org-refile-history) ")"))
10723 ": "))
10724 (cbuf (current-buffer))
10725 (partial-completion-mode nil)
10726 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10727 (cfunc (if (and org-refile-use-outline-path
10728 org-outline-path-complete-in-steps)
10729 'org-olpath-completing-read
10730 'org-icompleting-read))
10731 (extra (if org-refile-use-outline-path "/" ""))
10732 (filename (and cfn (expand-file-name cfn)))
10733 (tbl (mapcar
10734 (lambda (x)
10735 (if (and (not (member org-refile-use-outline-path
10736 '(file full-file-path)))
10737 (not (equal filename (nth 1 x))))
10738 (cons (concat (car x) extra " ("
10739 (file-name-nondirectory (nth 1 x)) ")")
10740 (cdr x))
10741 (cons (concat (car x) extra) (cdr x))))
10742 org-refile-target-table))
10743 (completion-ignore-case t)
10744 pa answ parent-target child parent old-hist)
10745 (setq old-hist org-refile-history)
10746 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10747 nil 'org-refile-history (car org-refile-history)))
10748 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10749 (org-refile-check-position pa)
10750 (if pa
10751 (progn
10752 (when (or (not org-refile-history)
10753 (not (eq old-hist org-refile-history))
10754 (not (equal (car pa) (car org-refile-history))))
10755 (setq org-refile-history
10756 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10757 org-refile-history
10758 (cdr org-refile-history))))
10759 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10760 (pop org-refile-history)))
10762 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10763 (progn
10764 (setq parent (match-string 1 answ)
10765 child (match-string 2 answ))
10766 (setq parent-target (or (assoc parent tbl)
10767 (assoc (concat parent "/") tbl)))
10768 (when (and parent-target
10769 (or (eq new-nodes t)
10770 (and (eq new-nodes 'confirm)
10771 (y-or-n-p (format "Create new node \"%s\"? "
10772 child)))))
10773 (org-refile-new-child parent-target child)))
10774 (error "Invalid target location")))))
10776 (defun org-refile-check-position (refile-pointer)
10777 "Check if the refile pointer matches the readline to which it points."
10778 (let* ((file (nth 1 refile-pointer))
10779 (re (nth 2 refile-pointer))
10780 (pos (nth 3 refile-pointer))
10781 buffer)
10782 (when (org-string-nw-p re)
10783 (setq buffer (if (markerp pos)
10784 (marker-buffer pos)
10785 (or (find-buffer-visiting file)
10786 (find-file-noselect file))))
10787 (with-current-buffer buffer
10788 (save-excursion
10789 (save-restriction
10790 (widen)
10791 (goto-char pos)
10792 (beginning-of-line 1)
10793 (unless (org-looking-at-p re)
10794 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
10796 (defun org-refile-new-child (parent-target child)
10797 "Use refile target PARENT-TARGET to add new CHILD below it."
10798 (unless parent-target
10799 (error "Cannot find parent for new node"))
10800 (let ((file (nth 1 parent-target))
10801 (pos (nth 3 parent-target))
10802 level)
10803 (with-current-buffer (or (find-buffer-visiting file)
10804 (find-file-noselect file))
10805 (save-excursion
10806 (save-restriction
10807 (widen)
10808 (if pos
10809 (goto-char pos)
10810 (goto-char (point-max))
10811 (if (not (bolp)) (newline)))
10812 (when (looking-at org-outline-regexp)
10813 (setq level (funcall outline-level))
10814 (org-end-of-subtree t t))
10815 (org-back-over-empty-lines)
10816 (insert "\n" (make-string
10817 (if pos (org-get-valid-level level 1) 1) ?*)
10818 " " child "\n")
10819 (beginning-of-line 0)
10820 (list (concat (car parent-target) "/" child) file "" (point)))))))
10822 (defun org-olpath-completing-read (prompt collection &rest args)
10823 "Read an outline path like a file name."
10824 (let ((thetable collection)
10825 (org-completion-use-ido nil) ; does not work with ido.
10826 (org-completion-use-iswitchb nil)) ; or iswitchb
10827 (apply
10828 'org-icompleting-read prompt
10829 (lambda (string predicate &optional flag)
10830 (let (rtn r f (l (length string)))
10831 (cond
10832 ((eq flag nil)
10833 ;; try completion
10834 (try-completion string thetable))
10835 ((eq flag t)
10836 ;; all-completions
10837 (setq rtn (all-completions string thetable predicate))
10838 (mapcar
10839 (lambda (x)
10840 (setq r (substring x l))
10841 (if (string-match " ([^)]*)$" x)
10842 (setq f (match-string 0 x))
10843 (setq f ""))
10844 (if (string-match "/" r)
10845 (concat string (substring r 0 (match-end 0)) f)
10847 rtn))
10848 ((eq flag 'lambda)
10849 ;; exact match?
10850 (assoc string thetable)))
10852 args)))
10854 ;;;; Dynamic blocks
10856 (defun org-find-dblock (name)
10857 "Find the first dynamic block with name NAME in the buffer.
10858 If not found, stay at current position and return nil."
10859 (let (pos)
10860 (save-excursion
10861 (goto-char (point-min))
10862 (setq pos (and (re-search-forward (concat "^[ \t]*#\\+BEGIN:[ \t]+" name "\\>")
10863 nil t)
10864 (match-beginning 0))))
10865 (if pos (goto-char pos))
10866 pos))
10868 (defconst org-dblock-start-re
10869 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10870 "Matches the start line of a dynamic block, with parameters.")
10872 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
10873 "Matches the end of a dynamic block.")
10875 (defun org-create-dblock (plist)
10876 "Create a dynamic block section, with parameters taken from PLIST.
10877 PLIST must contain a :name entry which is used as name of the block."
10878 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
10879 (end-of-line 1)
10880 (newline))
10881 (let ((col (current-column))
10882 (name (plist-get plist :name)))
10883 (insert "#+BEGIN: " name)
10884 (while plist
10885 (if (eq (car plist) :name)
10886 (setq plist (cddr plist))
10887 (insert " " (prin1-to-string (pop plist)))))
10888 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
10889 (beginning-of-line -2)))
10891 (defun org-prepare-dblock ()
10892 "Prepare dynamic block for refresh.
10893 This empties the block, puts the cursor at the insert position and returns
10894 the property list including an extra property :name with the block name."
10895 (unless (looking-at org-dblock-start-re)
10896 (error "Not at a dynamic block"))
10897 (let* ((begdel (1+ (match-end 0)))
10898 (name (org-no-properties (match-string 1)))
10899 (params (append (list :name name)
10900 (read (concat "(" (match-string 3) ")")))))
10901 (save-excursion
10902 (beginning-of-line 1)
10903 (skip-chars-forward " \t")
10904 (setq params (plist-put params :indentation-column (current-column))))
10905 (unless (re-search-forward org-dblock-end-re nil t)
10906 (error "Dynamic block not terminated"))
10907 (setq params
10908 (append params
10909 (list :content (buffer-substring
10910 begdel (match-beginning 0)))))
10911 (delete-region begdel (match-beginning 0))
10912 (goto-char begdel)
10913 (open-line 1)
10914 params))
10916 (defun org-map-dblocks (&optional command)
10917 "Apply COMMAND to all dynamic blocks in the current buffer.
10918 If COMMAND is not given, use `org-update-dblock'."
10919 (let ((cmd (or command 'org-update-dblock)))
10920 (save-excursion
10921 (goto-char (point-min))
10922 (while (re-search-forward org-dblock-start-re nil t)
10923 (goto-char (match-beginning 0))
10924 (save-excursion
10925 (condition-case nil
10926 (funcall cmd)
10927 (error (message "Error during update of dynamic block"))))
10928 (unless (re-search-forward org-dblock-end-re nil t)
10929 (error "Dynamic block not terminated"))))))
10931 (defun org-dblock-update (&optional arg)
10932 "User command for updating dynamic blocks.
10933 Update the dynamic block at point. With prefix ARG, update all dynamic
10934 blocks in the buffer."
10935 (interactive "P")
10936 (if arg
10937 (org-update-all-dblocks)
10938 (or (looking-at org-dblock-start-re)
10939 (org-beginning-of-dblock))
10940 (org-update-dblock)))
10942 (defun org-update-dblock ()
10943 "Update the dynamic block at point.
10944 This means to empty the block, parse for parameters and then call
10945 the correct writing function."
10946 (interactive)
10947 (save-window-excursion
10948 (let* ((pos (point))
10949 (line (org-current-line))
10950 (params (org-prepare-dblock))
10951 (name (plist-get params :name))
10952 (indent (plist-get params :indentation-column))
10953 (cmd (intern (concat "org-dblock-write:" name))))
10954 (message "Updating dynamic block `%s' at line %d..." name line)
10955 (funcall cmd params)
10956 (message "Updating dynamic block `%s' at line %d...done" name line)
10957 (goto-char pos)
10958 (when (and indent (> indent 0))
10959 (setq indent (make-string indent ?\ ))
10960 (save-excursion
10961 (org-beginning-of-dblock)
10962 (forward-line 1)
10963 (while (not (looking-at org-dblock-end-re))
10964 (insert indent)
10965 (beginning-of-line 2))
10966 (when (looking-at org-dblock-end-re)
10967 (and (looking-at "[ \t]+")
10968 (replace-match ""))
10969 (insert indent)))))))
10971 (defun org-beginning-of-dblock ()
10972 "Find the beginning of the dynamic block at point.
10973 Error if there is no such block at point."
10974 (let ((pos (point))
10975 beg)
10976 (end-of-line 1)
10977 (if (and (re-search-backward org-dblock-start-re nil t)
10978 (setq beg (match-beginning 0))
10979 (re-search-forward org-dblock-end-re nil t)
10980 (> (match-end 0) pos))
10981 (goto-char beg)
10982 (goto-char pos)
10983 (error "Not in a dynamic block"))))
10985 (defun org-update-all-dblocks ()
10986 "Update all dynamic blocks in the buffer.
10987 This function can be used in a hook."
10988 (interactive)
10989 (when (eq major-mode 'org-mode)
10990 (org-map-dblocks 'org-update-dblock)))
10993 ;;;; Completion
10995 (defconst org-additional-option-like-keywords
10996 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
10997 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
10998 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
10999 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11000 "BEGIN:" "END:"
11001 "ORGTBL" "TBLFM:" "TBLNAME:"
11002 "BEGIN_EXAMPLE" "END_EXAMPLE"
11003 "BEGIN_QUOTE" "END_QUOTE"
11004 "BEGIN_VERSE" "END_VERSE"
11005 "BEGIN_CENTER" "END_CENTER"
11006 "BEGIN_SRC" "END_SRC"
11007 "BEGIN_RESULT" "END_RESULT"
11008 "NAME:" "RESULTS:"
11009 "HEADER:" "HEADERS:"
11010 "CATEGORY:" "COLUMNS:" "PROPERTY:"
11011 "CAPTION:" "LABEL:"
11012 "SETUPFILE:"
11013 "INCLUDE:"
11014 "BIND:"
11015 "MACRO:"))
11017 (defcustom org-structure-template-alist
11019 ("s" "#+begin_src ?\n\n#+end_src"
11020 "<src lang=\"?\">\n\n</src>")
11021 ("e" "#+begin_example\n?\n#+end_example"
11022 "<example>\n?\n</example>")
11023 ("q" "#+begin_quote\n?\n#+end_quote"
11024 "<quote>\n?\n</quote>")
11025 ("v" "#+begin_verse\n?\n#+end_verse"
11026 "<verse>\n?\n/verse>")
11027 ("c" "#+begin_center\n?\n#+end_center"
11028 "<center>\n?\n/center>")
11029 ("l" "#+begin_latex\n?\n#+end_latex"
11030 "<literal style=\"latex\">\n?\n</literal>")
11031 ("L" "#+latex: "
11032 "<literal style=\"latex\">?</literal>")
11033 ("h" "#+begin_html\n?\n#+end_html"
11034 "<literal style=\"html\">\n?\n</literal>")
11035 ("H" "#+html: "
11036 "<literal style=\"html\">?</literal>")
11037 ("a" "#+begin_ascii\n?\n#+end_ascii")
11038 ("A" "#+ascii: ")
11039 ("i" "#+index: ?"
11040 "#+index: ?")
11041 ("I" "#+include %file ?"
11042 "<include file=%file markup=\"?\">")
11044 "Structure completion elements.
11045 This is a list of abbreviation keys and values. The value gets inserted
11046 if you type `<' followed by the key and then press the completion key,
11047 usually `M-TAB'. %file will be replaced by a file name after prompting
11048 for the file using completion. The cursor will be placed at the position
11049 of the `?` in the template.
11050 There are two templates for each key, the first uses the original Org syntax,
11051 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11052 the default when the /org-mtags.el/ module has been loaded. See also the
11053 variable `org-mtags-prefer-muse-templates'.
11054 This is an experimental feature, it is undecided if it is going to stay in."
11055 :group 'org-completion
11056 :type '(repeat
11057 (string :tag "Key")
11058 (string :tag "Template")
11059 (string :tag "Muse Template")))
11061 (defun org-try-structure-completion ()
11062 "Try to complete a structure template before point.
11063 This looks for strings like \"<e\" on an otherwise empty line and
11064 expands them."
11065 (let ((l (buffer-substring (point-at-bol) (point)))
11067 (when (and (looking-at "[ \t]*$")
11068 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11069 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11070 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11071 (match-beginning 1)) a)
11072 t)))
11074 (defun org-complete-expand-structure-template (start cell)
11075 "Expand a structure template."
11076 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11077 (rpl (nth (if musep 2 1) cell))
11078 (ind ""))
11079 (delete-region start (point))
11080 (when (string-match "\\`#\\+" rpl)
11081 (cond
11082 ((bolp))
11083 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11084 (setq ind (buffer-substring (point-at-bol) (point))))
11085 (t (newline))))
11086 (setq start (point))
11087 (if (string-match "%file" rpl)
11088 (setq rpl (replace-match
11089 (concat
11090 "\""
11091 (save-match-data
11092 (abbreviate-file-name (read-file-name "Include file: ")))
11093 "\"")
11094 t t rpl)))
11095 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11096 (concat "\n" ind)))
11097 (insert rpl)
11098 (if (re-search-backward "\\?" start t) (delete-char 1))))
11100 ;;;; TODO, DEADLINE, Comments
11102 (defun org-toggle-comment ()
11103 "Change the COMMENT state of an entry."
11104 (interactive)
11105 (save-excursion
11106 (org-back-to-heading)
11107 (let (case-fold-search)
11108 (cond
11109 ((looking-at (format org-heading-keyword-regexp-format
11110 org-comment-string))
11111 (goto-char (match-end 1))
11112 (looking-at (concat " +" org-comment-string))
11113 (replace-match "" t t)
11114 (when (eolp) (insert " ")))
11115 ((looking-at org-outline-regexp)
11116 (goto-char (match-end 0))
11117 (insert org-comment-string " "))))))
11119 (defvar org-last-todo-state-is-todo nil
11120 "This is non-nil when the last TODO state change led to a TODO state.
11121 If the last change removed the TODO tag or switched to DONE, then
11122 this is nil.")
11124 (defvar org-setting-tags nil) ; dynamically skipped
11126 (defvar org-todo-setup-filter-hook nil
11127 "Hook for functions that pre-filter todo specs.
11128 Each function takes a todo spec and returns either nil or the spec
11129 transformed into canonical form." )
11131 (defvar org-todo-get-default-hook nil
11132 "Hook for functions that get a default item for todo.
11133 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11134 nil or a string to be used for the todo mark." )
11136 (defvar org-agenda-headline-snapshot-before-repeat)
11138 (defun org-current-effective-time ()
11139 "Return current time adjusted for `org-extend-today-until' variable"
11140 (let* ((ct (org-current-time))
11141 (dct (decode-time ct))
11142 (ct1
11143 (if (and org-use-effective-time
11144 (< (nth 2 dct) org-extend-today-until))
11145 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11146 ct)))
11147 ct1))
11149 (defun org-todo-yesterday (&optional arg)
11150 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11151 (interactive "P")
11152 (if (eq major-mode 'org-agenda-mode)
11153 (apply 'org-agenda-todo-yesterday arg)
11154 (let* ((hour (third (decode-time
11155 (org-current-time))))
11156 (org-extend-today-until (1+ hour)))
11157 (org-todo arg))))
11159 (defun org-todo (&optional arg)
11160 "Change the TODO state of an item.
11161 The state of an item is given by a keyword at the start of the heading,
11162 like
11163 *** TODO Write paper
11164 *** DONE Call mom
11166 The different keywords are specified in the variable `org-todo-keywords'.
11167 By default the available states are \"TODO\" and \"DONE\".
11168 So for this example: when the item starts with TODO, it is changed to DONE.
11169 When it starts with DONE, the DONE is removed. And when neither TODO nor
11170 DONE are present, add TODO at the beginning of the heading.
11172 With \\[universal-argument] prefix arg, use completion to determine the new \
11173 state.
11174 With numeric prefix arg, switch to that state.
11175 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11176 keywords (nextset).
11177 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11178 With a numeric prefix arg of 0, inhibit note taking for the change.
11180 For calling through lisp, arg is also interpreted in the following way:
11181 'none -> empty state
11182 \"\"(empty string) -> switch to empty state
11183 'done -> switch to DONE
11184 'nextset -> switch to the next set of keywords
11185 'previousset -> switch to the previous set of keywords
11186 \"WAITING\" -> switch to the specified keyword, but only if it
11187 really is a member of `org-todo-keywords'."
11188 (interactive "P")
11189 (if (equal arg '(16)) (setq arg 'nextset))
11190 (let ((org-blocker-hook org-blocker-hook)
11191 (case-fold-search nil))
11192 (when (equal arg '(64))
11193 (setq arg nil org-blocker-hook nil))
11194 (when (and org-blocker-hook
11195 (or org-inhibit-blocking
11196 (org-entry-get nil "NOBLOCKING")))
11197 (setq org-blocker-hook nil))
11198 (save-excursion
11199 (catch 'exit
11200 (org-back-to-heading t)
11201 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11202 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11203 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11204 (let* ((match-data (match-data))
11205 (startpos (point-at-bol))
11206 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11207 (org-log-done org-log-done)
11208 (org-log-repeat org-log-repeat)
11209 (org-todo-log-states org-todo-log-states)
11210 (org-inhibit-logging
11211 (if (equal arg 0)
11212 (progn (setq arg nil) 'note) org-inhibit-logging))
11213 (this (match-string 1))
11214 (hl-pos (match-beginning 0))
11215 (head (org-get-todo-sequence-head this))
11216 (ass (assoc head org-todo-kwd-alist))
11217 (interpret (nth 1 ass))
11218 (done-word (nth 3 ass))
11219 (final-done-word (nth 4 ass))
11220 (last-state (or this ""))
11221 (completion-ignore-case t)
11222 (member (member this org-todo-keywords-1))
11223 (tail (cdr member))
11224 (state (cond
11225 ((and org-todo-key-trigger
11226 (or (and (equal arg '(4))
11227 (eq org-use-fast-todo-selection 'prefix))
11228 (and (not arg) org-use-fast-todo-selection
11229 (not (eq org-use-fast-todo-selection
11230 'prefix)))))
11231 ;; Use fast selection
11232 (org-fast-todo-selection))
11233 ((and (equal arg '(4))
11234 (or (not org-use-fast-todo-selection)
11235 (not org-todo-key-trigger)))
11236 ;; Read a state with completion
11237 (org-icompleting-read
11238 "State: " (mapcar (lambda(x) (list x))
11239 org-todo-keywords-1)
11240 nil t))
11241 ((eq arg 'right)
11242 (if this
11243 (if tail (car tail) nil)
11244 (car org-todo-keywords-1)))
11245 ((eq arg 'left)
11246 (if (equal member org-todo-keywords-1)
11248 (if this
11249 (nth (- (length org-todo-keywords-1)
11250 (length tail) 2)
11251 org-todo-keywords-1)
11252 (org-last org-todo-keywords-1))))
11253 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11254 (setq arg nil))) ; hack to fall back to cycling
11255 (arg
11256 ;; user or caller requests a specific state
11257 (cond
11258 ((equal arg "") nil)
11259 ((eq arg 'none) nil)
11260 ((eq arg 'done) (or done-word (car org-done-keywords)))
11261 ((eq arg 'nextset)
11262 (or (car (cdr (member head org-todo-heads)))
11263 (car org-todo-heads)))
11264 ((eq arg 'previousset)
11265 (let ((org-todo-heads (reverse org-todo-heads)))
11266 (or (car (cdr (member head org-todo-heads)))
11267 (car org-todo-heads))))
11268 ((car (member arg org-todo-keywords-1)))
11269 ((stringp arg)
11270 (error "State `%s' not valid in this file" arg))
11271 ((nth (1- (prefix-numeric-value arg))
11272 org-todo-keywords-1))))
11273 ((null member) (or head (car org-todo-keywords-1)))
11274 ((equal this final-done-word) nil) ;; -> make empty
11275 ((null tail) nil) ;; -> first entry
11276 ((memq interpret '(type priority))
11277 (if (eq this-command last-command)
11278 (car tail)
11279 (if (> (length tail) 0)
11280 (or done-word (car org-done-keywords))
11281 nil)))
11283 (car tail))))
11284 (state (or
11285 (run-hook-with-args-until-success
11286 'org-todo-get-default-hook state last-state)
11287 state))
11288 (next (if state (concat " " state " ") " "))
11289 (change-plist (list :type 'todo-state-change :from this :to state
11290 :position startpos))
11291 dolog now-done-p)
11292 (when org-blocker-hook
11293 (setq org-last-todo-state-is-todo
11294 (not (member this org-done-keywords)))
11295 (unless (save-excursion
11296 (save-match-data
11297 (org-with-wide-buffer
11298 (run-hook-with-args-until-failure
11299 'org-blocker-hook change-plist))))
11300 (if (org-called-interactively-p 'interactive)
11301 (error "TODO state change from %s to %s blocked" this state)
11302 ;; fail silently
11303 (message "TODO state change from %s to %s blocked" this state)
11304 (throw 'exit nil))))
11305 (store-match-data match-data)
11306 (replace-match next t t)
11307 (unless (pos-visible-in-window-p hl-pos)
11308 (message "TODO state changed to %s" (org-trim next)))
11309 (unless head
11310 (setq head (org-get-todo-sequence-head state)
11311 ass (assoc head org-todo-kwd-alist)
11312 interpret (nth 1 ass)
11313 done-word (nth 3 ass)
11314 final-done-word (nth 4 ass)))
11315 (when (memq arg '(nextset previousset))
11316 (message "Keyword-Set %d/%d: %s"
11317 (- (length org-todo-sets) -1
11318 (length (memq (assoc state org-todo-sets) org-todo-sets)))
11319 (length org-todo-sets)
11320 (mapconcat 'identity (assoc state org-todo-sets) " ")))
11321 (setq org-last-todo-state-is-todo
11322 (not (member state org-done-keywords)))
11323 (setq now-done-p (and (member state org-done-keywords)
11324 (not (member this org-done-keywords))))
11325 (and logging (org-local-logging logging))
11326 (when (and (or org-todo-log-states org-log-done)
11327 (not (eq org-inhibit-logging t))
11328 (not (memq arg '(nextset previousset))))
11329 ;; we need to look at recording a time and note
11330 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
11331 (nth 2 (assoc this org-todo-log-states))))
11332 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11333 (setq dolog 'time))
11334 (when (and state
11335 (member state org-not-done-keywords)
11336 (not (member this org-not-done-keywords)))
11337 ;; This is now a todo state and was not one before
11338 ;; If there was a CLOSED time stamp, get rid of it.
11339 (org-add-planning-info nil nil 'closed))
11340 (when (and now-done-p org-log-done)
11341 ;; It is now done, and it was not done before
11342 (org-add-planning-info 'closed (org-current-effective-time))
11343 (if (and (not dolog) (eq 'note org-log-done))
11344 (org-add-log-setup 'done state this 'findpos 'note)))
11345 (when (and state dolog)
11346 ;; This is a non-nil state, and we need to log it
11347 (org-add-log-setup 'state state this 'findpos dolog)))
11348 ;; Fixup tag positioning
11349 (org-todo-trigger-tag-changes state)
11350 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11351 (when org-provide-todo-statistics
11352 (org-update-parent-todo-statistics))
11353 (run-hooks 'org-after-todo-state-change-hook)
11354 (if (and arg (not (member state org-done-keywords)))
11355 (setq head (org-get-todo-sequence-head state)))
11356 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11357 ;; Do we need to trigger a repeat?
11358 (when now-done-p
11359 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11360 ;; This is for the agenda, take a snapshot of the headline.
11361 (save-match-data
11362 (setq org-agenda-headline-snapshot-before-repeat
11363 (org-get-heading))))
11364 (org-auto-repeat-maybe state))
11365 ;; Fixup cursor location if close to the keyword
11366 (if (and (outline-on-heading-p)
11367 (not (bolp))
11368 (save-excursion (beginning-of-line 1)
11369 (looking-at org-todo-line-regexp))
11370 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11371 (progn
11372 (goto-char (or (match-end 2) (match-end 1)))
11373 (and (looking-at " ") (just-one-space))))
11374 (when org-trigger-hook
11375 (save-excursion
11376 (run-hook-with-args 'org-trigger-hook change-plist))))))))
11378 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11379 "Block turning an entry into a TODO, using the hierarchy.
11380 This checks whether the current task should be blocked from state
11381 changes. Such blocking occurs when:
11383 1. The task has children which are not all in a completed state.
11385 2. A task has a parent with the property :ORDERED:, and there
11386 are siblings prior to the current task with incomplete
11387 status.
11389 3. The parent of the task is blocked because it has siblings that should
11390 be done first, or is child of a block grandparent TODO entry."
11392 (if (not org-enforce-todo-dependencies)
11393 t ; if locally turned off don't block
11394 (catch 'dont-block
11395 ;; If this is not a todo state change, or if this entry is already DONE,
11396 ;; do not block
11397 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11398 (member (plist-get change-plist :from)
11399 (cons 'done org-done-keywords))
11400 (member (plist-get change-plist :to)
11401 (cons 'todo org-not-done-keywords))
11402 (not (plist-get change-plist :to)))
11403 (throw 'dont-block t))
11404 ;; If this task has children, and any are undone, it's blocked
11405 (save-excursion
11406 (org-back-to-heading t)
11407 (let ((this-level (funcall outline-level)))
11408 (outline-next-heading)
11409 (let ((child-level (funcall outline-level)))
11410 (while (and (not (eobp))
11411 (> child-level this-level))
11412 ;; this todo has children, check whether they are all
11413 ;; completed
11414 (if (and (not (org-entry-is-done-p))
11415 (org-entry-is-todo-p))
11416 (throw 'dont-block nil))
11417 (outline-next-heading)
11418 (setq child-level (funcall outline-level))))))
11419 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11420 ;; any previous siblings are undone, it's blocked
11421 (save-excursion
11422 (org-back-to-heading t)
11423 (let* ((pos (point))
11424 (parent-pos (and (org-up-heading-safe) (point))))
11425 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11426 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11427 (forward-line 1)
11428 (re-search-forward org-not-done-heading-regexp pos t))
11429 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11430 ;; Search further up the hierarchy, to see if an anchestor is blocked
11431 (while t
11432 (goto-char parent-pos)
11433 (if (not (looking-at org-not-done-heading-regexp))
11434 (throw 'dont-block t)) ; do not block, parent is not a TODO
11435 (setq pos (point))
11436 (setq 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, older sibling not done.
11443 (defcustom org-track-ordered-property-with-tag nil
11444 "Should the ORDERED property also be shown as a tag?
11445 The ORDERED property decides if an entry should require subtasks to be
11446 completed in sequence. Since a property is not very visible, setting
11447 this option means that toggling the ORDERED property with the command
11448 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11449 not relevant for the behavior, but it makes things more visible.
11451 Note that toggling the tag with tags commands will not change the property
11452 and therefore not influence behavior!
11454 This can be t, meaning the tag ORDERED should be used, It can also be a
11455 string to select a different tag for this task."
11456 :group 'org-todo
11457 :type '(choice
11458 (const :tag "No tracking" nil)
11459 (const :tag "Track with ORDERED tag" t)
11460 (string :tag "Use other tag")))
11462 (defun org-toggle-ordered-property ()
11463 "Toggle the ORDERED property of the current entry.
11464 For better visibility, you can track the value of this property with a tag.
11465 See variable `org-track-ordered-property-with-tag'."
11466 (interactive)
11467 (let* ((t1 org-track-ordered-property-with-tag)
11468 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11469 (save-excursion
11470 (org-back-to-heading)
11471 (if (org-entry-get nil "ORDERED")
11472 (progn
11473 (org-delete-property "ORDERED")
11474 (and tag (org-toggle-tag tag 'off))
11475 (message "Subtasks can be completed in arbitrary order"))
11476 (org-entry-put nil "ORDERED" "t")
11477 (and tag (org-toggle-tag tag 'on))
11478 (message "Subtasks must be completed in sequence")))))
11480 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11481 (defun org-block-todo-from-checkboxes (change-plist)
11482 "Block turning an entry into a TODO, using checkboxes.
11483 This checks whether the current task should be blocked from state
11484 changes because there are unchecked boxes in this entry."
11485 (if (not org-enforce-todo-checkbox-dependencies)
11486 t ; if locally turned off don't block
11487 (catch 'dont-block
11488 ;; If this is not a todo state change, or if this entry is already DONE,
11489 ;; do not block
11490 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11491 (member (plist-get change-plist :from)
11492 (cons 'done org-done-keywords))
11493 (member (plist-get change-plist :to)
11494 (cons 'todo org-not-done-keywords))
11495 (not (plist-get change-plist :to)))
11496 (throw 'dont-block t))
11497 ;; If this task has checkboxes that are not checked, it's blocked
11498 (save-excursion
11499 (org-back-to-heading t)
11500 (let ((beg (point)) end)
11501 (outline-next-heading)
11502 (setq end (point))
11503 (goto-char beg)
11504 (if (org-list-search-forward
11505 (concat (org-item-beginning-re)
11506 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11507 "\\[[- ]\\]")
11508 end t)
11509 (progn
11510 (if (boundp 'org-blocked-by-checkboxes)
11511 (setq org-blocked-by-checkboxes t))
11512 (throw 'dont-block nil)))))
11513 t))) ; do not block
11515 (defun org-entry-blocked-p ()
11516 "Is the current entry blocked?"
11517 (if (org-entry-get nil "NOBLOCKING")
11518 nil ;; Never block this entry
11519 (not
11520 (run-hook-with-args-until-failure
11521 'org-blocker-hook
11522 (list :type 'todo-state-change
11523 :position (point)
11524 :from 'todo
11525 :to 'done)))))
11527 (defun org-update-statistics-cookies (all)
11528 "Update the statistics cookie, either from TODO or from checkboxes.
11529 This should be called with the cursor in a line with a statistics cookie."
11530 (interactive "P")
11531 (if all
11532 (progn
11533 (org-update-checkbox-count 'all)
11534 (org-map-entries 'org-update-parent-todo-statistics))
11535 (if (not (org-on-heading-p))
11536 (org-update-checkbox-count)
11537 (let ((pos (move-marker (make-marker) (point)))
11538 end l1 l2)
11539 (ignore-errors (org-back-to-heading t))
11540 (if (not (org-on-heading-p))
11541 (org-update-checkbox-count)
11542 (setq l1 (org-outline-level))
11543 (setq end (save-excursion
11544 (outline-next-heading)
11545 (if (org-on-heading-p) (setq l2 (org-outline-level)))
11546 (point)))
11547 (if (and (save-excursion
11548 (re-search-forward
11549 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11550 (not (save-excursion (re-search-forward
11551 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11552 (org-update-checkbox-count)
11553 (if (and l2 (> l2 l1))
11554 (progn
11555 (goto-char end)
11556 (org-update-parent-todo-statistics))
11557 (goto-char pos)
11558 (beginning-of-line 1)
11559 (while (re-search-forward
11560 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11561 (point-at-eol) t)
11562 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11563 (goto-char pos)
11564 (move-marker pos nil)))))
11566 (defvar org-entry-property-inherited-from) ;; defined below
11567 (defun org-update-parent-todo-statistics ()
11568 "Update any statistics cookie in the parent of the current headline.
11569 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11570 the entire subtree and this will travel up the hierarchy and update
11571 statistics everywhere."
11572 (let* ((prop (save-excursion (org-up-heading-safe)
11573 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11574 (recursive (or (not org-hierarchical-todo-statistics)
11575 (and prop (string-match "\\<recursive\\>" prop))))
11576 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11578 (first t)
11579 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11580 level ltoggle l1 new ndel
11581 (cnt-all 0) (cnt-done 0) is-percent kwd
11582 checkbox-beg ov ovs ove cookie-present)
11583 (catch 'exit
11584 (save-excursion
11585 (beginning-of-line 1)
11586 (setq ltoggle (funcall outline-level))
11587 ;; Three situations are to consider:
11589 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11590 ;; to the top-level ancestor on the headline;
11592 ;; 2. If parent has "recursive" property, repeat up to the
11593 ;; headline setting that property, taking inheritance into
11594 ;; account;
11596 ;; 3. Else, move up to direct parent and proceed only once.
11597 (while (and (setq level (org-up-heading-safe))
11598 (or recursive first)
11599 (>= (point) lim))
11600 (setq first nil cookie-present nil)
11601 (unless (and level
11602 (not (string-match
11603 "\\<checkbox\\>"
11604 (downcase (or (org-entry-get nil "COOKIE_DATA")
11605 "")))))
11606 (throw 'exit nil))
11607 (while (re-search-forward box-re (point-at-eol) t)
11608 (setq cnt-all 0 cnt-done 0 cookie-present t)
11609 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11610 (save-match-data
11611 (unless (outline-next-heading) (throw 'exit nil))
11612 (while (and (looking-at org-complex-heading-regexp)
11613 (> (setq l1 (length (match-string 1))) level))
11614 (setq kwd (and (or recursive (= l1 ltoggle))
11615 (match-string 2)))
11616 (if (or (eq org-provide-todo-statistics 'all-headlines)
11617 (and (listp org-provide-todo-statistics)
11618 (or (member kwd org-provide-todo-statistics)
11619 (member kwd org-done-keywords))))
11620 (setq cnt-all (1+ cnt-all))
11621 (if (eq org-provide-todo-statistics t)
11622 (and kwd (setq cnt-all (1+ cnt-all)))))
11623 (and (member kwd org-done-keywords)
11624 (setq cnt-done (1+ cnt-done)))
11625 (outline-next-heading)))
11626 (setq new
11627 (if is-percent
11628 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11629 (format "[%d/%d]" cnt-done cnt-all))
11630 ndel (- (match-end 0) checkbox-beg))
11631 ;; handle overlays when updating cookie from column view
11632 (when (setq ov (car (overlays-at checkbox-beg)))
11633 (setq ovs (overlay-start ov) ove (overlay-end ov))
11634 (delete-overlay ov))
11635 (goto-char checkbox-beg)
11636 (insert new)
11637 (delete-region (point) (+ (point) ndel))
11638 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11639 (when ov (move-overlay ov ovs ove)))
11640 (when cookie-present
11641 (run-hook-with-args 'org-after-todo-statistics-hook
11642 cnt-done (- cnt-all cnt-done))))))
11643 (run-hooks 'org-todo-statistics-hook)))
11645 (defvar org-after-todo-statistics-hook nil
11646 "Hook that is called after a TODO statistics cookie has been updated.
11647 Each function is called with two arguments: the number of not-done entries
11648 and the number of done entries.
11650 For example, the following function, when added to this hook, will switch
11651 an entry to DONE when all children are done, and back to TODO when new
11652 entries are set to a TODO status. Note that this hook is only called
11653 when there is a statistics cookie in the headline!
11655 (defun org-summary-todo (n-done n-not-done)
11656 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11657 (let (org-log-done org-log-states) ; turn off logging
11658 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11661 (defvar org-todo-statistics-hook nil
11662 "Hook that is run whenever Org thinks TODO statistics should be updated.
11663 This hook runs even if there is no statistics cookie present, in which case
11664 `org-after-todo-statistics-hook' would not run.")
11666 (defun org-todo-trigger-tag-changes (state)
11667 "Apply the changes defined in `org-todo-state-tags-triggers'."
11668 (let ((l org-todo-state-tags-triggers)
11669 changes)
11670 (when (or (not state) (equal state ""))
11671 (setq changes (append changes (cdr (assoc "" l)))))
11672 (when (and (stringp state) (> (length state) 0))
11673 (setq changes (append changes (cdr (assoc state l)))))
11674 (when (member state org-not-done-keywords)
11675 (setq changes (append changes (cdr (assoc 'todo l)))))
11676 (when (member state org-done-keywords)
11677 (setq changes (append changes (cdr (assoc 'done l)))))
11678 (dolist (c changes)
11679 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11681 (defun org-local-logging (value)
11682 "Get logging settings from a property VALUE."
11683 (let* (words w a)
11684 ;; directly set the variables, they are already local.
11685 (setq org-log-done nil
11686 org-log-repeat nil
11687 org-todo-log-states nil)
11688 (setq words (org-split-string value))
11689 (while (setq w (pop words))
11690 (cond
11691 ((setq a (assoc w org-startup-options))
11692 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11693 (set (nth 1 a) (nth 2 a))))
11694 ((setq a (org-extract-log-state-settings w))
11695 (and (member (car a) org-todo-keywords-1)
11696 (push a org-todo-log-states)))))))
11698 (defun org-get-todo-sequence-head (kwd)
11699 "Return the head of the TODO sequence to which KWD belongs.
11700 If KWD is not set, check if there is a text property remembering the
11701 right sequence."
11702 (let (p)
11703 (cond
11704 ((not kwd)
11705 (or (get-text-property (point-at-bol) 'org-todo-head)
11706 (progn
11707 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11708 nil (point-at-eol)))
11709 (get-text-property p 'org-todo-head))))
11710 ((not (member kwd org-todo-keywords-1))
11711 (car org-todo-keywords-1))
11712 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11714 (defun org-fast-todo-selection ()
11715 "Fast TODO keyword selection with single keys.
11716 Returns the new TODO keyword, or nil if no state change should occur."
11717 (let* ((fulltable org-todo-key-alist)
11718 (done-keywords org-done-keywords) ;; needed for the faces.
11719 (maxlen (apply 'max (mapcar
11720 (lambda (x)
11721 (if (stringp (car x)) (string-width (car x)) 0))
11722 fulltable)))
11723 (expert nil)
11724 (fwidth (+ maxlen 3 1 3))
11725 (ncol (/ (- (window-width) 4) fwidth))
11726 tg cnt e c tbl
11727 groups ingroup)
11728 (save-excursion
11729 (save-window-excursion
11730 (if expert
11731 (set-buffer (get-buffer-create " *Org todo*"))
11732 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11733 (erase-buffer)
11734 (org-set-local 'org-done-keywords done-keywords)
11735 (setq tbl fulltable cnt 0)
11736 (while (setq e (pop tbl))
11737 (cond
11738 ((equal e '(:startgroup))
11739 (push '() groups) (setq ingroup t)
11740 (when (not (= cnt 0))
11741 (setq cnt 0)
11742 (insert "\n"))
11743 (insert "{ "))
11744 ((equal e '(:endgroup))
11745 (setq ingroup nil cnt 0)
11746 (insert "}\n"))
11747 ((equal e '(:newline))
11748 (when (not (= cnt 0))
11749 (setq cnt 0)
11750 (insert "\n")
11751 (setq e (car tbl))
11752 (while (equal (car tbl) '(:newline))
11753 (insert "\n")
11754 (setq tbl (cdr tbl)))))
11756 (setq tg (car e) c (cdr e))
11757 (if ingroup (push tg (car groups)))
11758 (setq tg (org-add-props tg nil 'face
11759 (org-get-todo-face tg)))
11760 (if (and (= cnt 0) (not ingroup)) (insert " "))
11761 (insert "[" c "] " tg (make-string
11762 (- fwidth 4 (length tg)) ?\ ))
11763 (when (= (setq cnt (1+ cnt)) ncol)
11764 (insert "\n")
11765 (if ingroup (insert " "))
11766 (setq cnt 0)))))
11767 (insert "\n")
11768 (goto-char (point-min))
11769 (if (not expert) (org-fit-window-to-buffer))
11770 (message "[a-z..]:Set [SPC]:clear")
11771 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11772 (cond
11773 ((or (= c ?\C-g)
11774 (and (= c ?q) (not (rassoc c fulltable))))
11775 (setq quit-flag t))
11776 ((= c ?\ ) nil)
11777 ((setq e (rassoc c fulltable) tg (car e))
11779 (t (setq quit-flag t)))))))
11781 (defun org-entry-is-todo-p ()
11782 (member (org-get-todo-state) org-not-done-keywords))
11784 (defun org-entry-is-done-p ()
11785 (member (org-get-todo-state) org-done-keywords))
11787 (defun org-get-todo-state ()
11788 (save-excursion
11789 (org-back-to-heading t)
11790 (and (looking-at org-todo-line-regexp)
11791 (match-end 2)
11792 (match-string 2))))
11794 (defun org-at-date-range-p (&optional inactive-ok)
11795 "Is the cursor inside a date range?"
11796 (interactive)
11797 (save-excursion
11798 (catch 'exit
11799 (let ((pos (point)))
11800 (skip-chars-backward "^[<\r\n")
11801 (skip-chars-backward "<[")
11802 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11803 (>= (match-end 0) pos)
11804 (throw 'exit t))
11805 (skip-chars-backward "^<[\r\n")
11806 (skip-chars-backward "<[")
11807 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11808 (>= (match-end 0) pos)
11809 (throw 'exit t)))
11810 nil)))
11812 (defun org-get-repeat (&optional tagline)
11813 "Check if there is a deadline/schedule with repeater in this entry."
11814 (save-match-data
11815 (save-excursion
11816 (org-back-to-heading t)
11817 (and (re-search-forward (if tagline
11818 (concat tagline "\\s-*" org-repeat-re)
11819 org-repeat-re)
11820 (org-entry-end-position) t)
11821 (match-string-no-properties 1)))))
11823 (defvar org-last-changed-timestamp)
11824 (defvar org-last-inserted-timestamp)
11825 (defvar org-log-post-message)
11826 (defvar org-log-note-purpose)
11827 (defvar org-log-note-how)
11828 (defvar org-log-note-extra)
11829 (defun org-auto-repeat-maybe (done-word)
11830 "Check if the current headline contains a repeated deadline/schedule.
11831 If yes, set TODO state back to what it was and change the base date
11832 of repeating deadline/scheduled time stamps to new date.
11833 This function is run automatically after each state change to a DONE state."
11834 ;; last-state is dynamically scoped into this function
11835 (let* ((repeat (org-get-repeat))
11836 (aa (assoc last-state org-todo-kwd-alist))
11837 (interpret (nth 1 aa))
11838 (head (nth 2 aa))
11839 (whata '(("d" . day) ("m" . month) ("y" . year)))
11840 (msg "Entry repeats: ")
11841 (org-log-done nil)
11842 (org-todo-log-states nil)
11843 re type n what ts time to-state)
11844 (when repeat
11845 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11846 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11847 org-todo-repeat-to-state))
11848 (unless (and to-state (member to-state org-todo-keywords-1))
11849 (setq to-state (if (eq interpret 'type) last-state head)))
11850 (org-todo to-state)
11851 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11852 (org-entry-put nil "LAST_REPEAT" (format-time-string
11853 (org-time-stamp-format t t))))
11854 (when org-log-repeat
11855 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11856 (memq 'org-add-log-note post-command-hook))
11857 ;; OK, we are already setup for some record
11858 (if (eq org-log-repeat 'note)
11859 ;; make sure we take a note, not only a time stamp
11860 (setq org-log-note-how 'note))
11861 ;; Set up for taking a record
11862 (org-add-log-setup 'state (or done-word (car org-done-keywords))
11863 last-state
11864 'findpos org-log-repeat)))
11865 (org-back-to-heading t)
11866 (org-add-planning-info nil nil 'closed)
11867 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11868 org-deadline-time-regexp "\\)\\|\\("
11869 org-ts-regexp "\\)"))
11870 (while (re-search-forward
11871 re (save-excursion (outline-next-heading) (point)) t)
11872 (setq type (if (match-end 1) org-scheduled-string
11873 (if (match-end 3) org-deadline-string "Plain:"))
11874 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
11875 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
11876 (setq n (string-to-number (match-string 2 ts))
11877 what (match-string 3 ts))
11878 (if (equal what "w") (setq n (* n 7) what "d"))
11879 ;; Preparation, see if we need to modify the start date for the change
11880 (when (match-end 1)
11881 (setq time (save-match-data (org-time-string-to-time ts)))
11882 (cond
11883 ((equal (match-string 1 ts) ".")
11884 ;; Shift starting date to today
11885 (org-timestamp-change
11886 (- (org-today) (time-to-days time))
11887 'day))
11888 ((equal (match-string 1 ts) "+")
11889 (let ((nshiftmax 10) (nshift 0))
11890 (while (or (= nshift 0)
11891 (<= (time-to-days time)
11892 (time-to-days (current-time))))
11893 (when (= (incf nshift) nshiftmax)
11894 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
11895 (error "Abort")))
11896 (org-timestamp-change n (cdr (assoc what whata)))
11897 (org-at-timestamp-p t)
11898 (setq ts (match-string 1))
11899 (setq time (save-match-data (org-time-string-to-time ts)))))
11900 (org-timestamp-change (- n) (cdr (assoc what whata)))
11901 ;; rematch, so that we have everything in place for the real shift
11902 (org-at-timestamp-p t)
11903 (setq ts (match-string 1))
11904 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
11905 (org-timestamp-change n (cdr (assoc what whata)))
11906 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
11907 (setq org-log-post-message msg)
11908 (message "%s" msg))))
11910 (defun org-show-todo-tree (arg)
11911 "Make a compact tree which shows all headlines marked with TODO.
11912 The tree will show the lines where the regexp matches, and all higher
11913 headlines above the match.
11914 With a \\[universal-argument] prefix, prompt for a regexp to match.
11915 With a numeric prefix N, construct a sparse tree for the Nth element
11916 of `org-todo-keywords-1'."
11917 (interactive "P")
11918 (let ((case-fold-search nil)
11919 (kwd-re
11920 (cond ((null arg) org-not-done-regexp)
11921 ((equal arg '(4))
11922 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
11923 (mapcar 'list org-todo-keywords-1))))
11924 (concat "\\("
11925 (mapconcat 'identity (org-split-string kwd "|") "\\|")
11926 "\\)\\>")))
11927 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
11928 (regexp-quote (nth (1- (prefix-numeric-value arg))
11929 org-todo-keywords-1)))
11930 (t (error "Invalid prefix argument: %s" arg)))))
11931 (message "%d TODO entries found"
11932 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
11934 (defun org-deadline (&optional remove time)
11935 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
11936 With argument REMOVE, remove any deadline from the item.
11937 With argument TIME, set the deadline at the corresponding date. TIME
11938 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
11939 (interactive "P")
11940 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11941 (let (org-loop-over-headlines-in-active-region)
11942 (org-map-entries
11943 `(org-deadline ',remove ,time) org-loop-over-headlines-in-active-region 'region (if (outline-invisible-p) (org-end-of-subtree nil t))))
11944 (let* ((old-date (org-entry-get nil "DEADLINE"))
11945 (repeater (and old-date
11946 (string-match
11947 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
11948 old-date)
11949 (match-string 1 old-date))))
11950 (if remove
11951 (progn
11952 (when (and old-date org-log-redeadline)
11953 (org-add-log-setup 'deldeadline nil old-date 'findpos
11954 org-log-redeadline))
11955 (org-remove-timestamp-with-keyword org-deadline-string)
11956 (message "Item no longer has a deadline."))
11957 (org-add-planning-info 'deadline time 'closed)
11958 (when (and old-date org-log-redeadline
11959 (not (equal old-date
11960 (substring org-last-inserted-timestamp 1 -1))))
11961 (org-add-log-setup 'redeadline nil old-date 'findpos
11962 org-log-redeadline))
11963 (when repeater
11964 (save-excursion
11965 (org-back-to-heading t)
11966 (when (re-search-forward (concat org-deadline-string " "
11967 org-last-inserted-timestamp)
11968 (save-excursion
11969 (outline-next-heading) (point)) t)
11970 (goto-char (1- (match-end 0)))
11971 (insert " " repeater)
11972 (setq org-last-inserted-timestamp
11973 (concat (substring org-last-inserted-timestamp 0 -1)
11974 " " repeater
11975 (substring org-last-inserted-timestamp -1))))))
11976 (message "Deadline on %s" org-last-inserted-timestamp)))))
11978 (defun org-schedule (&optional remove time)
11979 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
11980 With argument REMOVE, remove any scheduling date from the item.
11981 With argument TIME, scheduled at the corresponding date. TIME can
11982 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
11983 (interactive "P")
11984 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11985 (let (org-loop-over-headlines-in-active-region)
11986 (org-map-entries
11987 `(org-schedule ',remove ,time) org-loop-over-headlines-in-active-region 'region (if (outline-invisible-p) (org-end-of-subtree nil t))))
11988 (let* ((old-date (org-entry-get nil "SCHEDULED"))
11989 (repeater (and old-date
11990 (string-match
11991 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
11992 old-date)
11993 (match-string 1 old-date))))
11994 (if remove
11995 (progn
11996 (when (and old-date org-log-reschedule)
11997 (org-add-log-setup 'delschedule nil old-date 'findpos
11998 org-log-reschedule))
11999 (org-remove-timestamp-with-keyword org-scheduled-string)
12000 (message "Item is no longer scheduled."))
12001 (org-add-planning-info 'scheduled time 'closed)
12002 (when (and old-date org-log-reschedule
12003 (not (equal old-date
12004 (substring org-last-inserted-timestamp 1 -1))))
12005 (org-add-log-setup 'reschedule nil old-date 'findpos
12006 org-log-reschedule))
12007 (when repeater
12008 (save-excursion
12009 (org-back-to-heading t)
12010 (when (re-search-forward (concat org-scheduled-string " "
12011 org-last-inserted-timestamp)
12012 (save-excursion
12013 (outline-next-heading) (point)) t)
12014 (goto-char (1- (match-end 0)))
12015 (insert " " repeater)
12016 (setq org-last-inserted-timestamp
12017 (concat (substring org-last-inserted-timestamp 0 -1)
12018 " " repeater
12019 (substring org-last-inserted-timestamp -1))))))
12020 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12022 (defun org-get-scheduled-time (pom &optional inherit)
12023 "Get the scheduled time as a time tuple, of a format suitable
12024 for calling org-schedule with, or if there is no scheduling,
12025 returns nil."
12026 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12027 (when time
12028 (apply 'encode-time (org-parse-time-string time)))))
12030 (defun org-get-deadline-time (pom &optional inherit)
12031 "Get the deadline as a time tuple, of a format suitable for
12032 calling org-deadline with, or if there is no scheduling, returns
12033 nil."
12034 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12035 (when time
12036 (apply 'encode-time (org-parse-time-string time)))))
12038 (defun org-remove-timestamp-with-keyword (keyword)
12039 "Remove all time stamps with KEYWORD in the current entry."
12040 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12041 beg)
12042 (save-excursion
12043 (org-back-to-heading t)
12044 (setq beg (point))
12045 (outline-next-heading)
12046 (while (re-search-backward re beg t)
12047 (replace-match "")
12048 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12049 (equal (char-before) ?\ ))
12050 (backward-delete-char 1)
12051 (if (string-match "^[ \t]*$" (buffer-substring
12052 (point-at-bol) (point-at-eol)))
12053 (delete-region (point-at-bol)
12054 (min (point-max) (1+ (point-at-eol))))))))))
12056 (defun org-add-planning-info (what &optional time &rest remove)
12057 "Insert new timestamp with keyword in the line directly after the headline.
12058 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12059 If non is given, the user is prompted for a date.
12060 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12061 be removed."
12062 (interactive)
12063 (let (org-time-was-given org-end-time-was-given ts
12064 end default-time default-input)
12066 (catch 'exit
12067 (when (and (memq what '(scheduled deadline))
12068 (or (not time)
12069 (and (stringp time)
12070 (string-match "^[-+]+[0-9]" time))))
12071 ;; Try to get a default date/time from existing timestamp
12072 (save-excursion
12073 (org-back-to-heading t)
12074 (setq end (save-excursion (outline-next-heading) (point)))
12075 (when (re-search-forward (if (eq what 'scheduled)
12076 org-scheduled-time-regexp
12077 org-deadline-time-regexp)
12078 end t)
12079 (setq ts (match-string 1)
12080 default-time
12081 (apply 'encode-time (org-parse-time-string ts))
12082 default-input (and ts (org-get-compact-tod ts))))))
12083 (when what
12084 (setq time
12085 (if (stringp time)
12086 ;; This is a string (relative or absolute), set proper date
12087 (apply 'encode-time
12088 (org-read-date-analyze
12089 time default-time (decode-time default-time)))
12090 ;; If necessary, get the time from the user
12091 (or time (org-read-date nil 'to-time nil nil
12092 default-time default-input)))))
12094 (when (and org-insert-labeled-timestamps-at-point
12095 (member what '(scheduled deadline)))
12096 (insert
12097 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12098 (org-insert-time-stamp time org-time-was-given
12099 nil nil nil (list org-end-time-was-given))
12100 (setq what nil))
12101 (save-excursion
12102 (save-restriction
12103 (let (col list elt ts buffer-invisibility-spec)
12104 (org-back-to-heading t)
12105 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12106 (goto-char (match-end 1))
12107 (setq col (current-column))
12108 (goto-char (match-end 0))
12109 (if (eobp) (insert "\n") (forward-char 1))
12110 (when (and (not what)
12111 (not (looking-at
12112 (concat "[ \t]*"
12113 org-keyword-time-not-clock-regexp))))
12114 ;; Nothing to add, nothing to remove...... :-)
12115 (throw 'exit nil))
12116 (if (and (not (looking-at org-outline-regexp))
12117 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12118 "[^\r\n]*"))
12119 (not (equal (match-string 1) org-clock-string)))
12120 (narrow-to-region (match-beginning 0) (match-end 0))
12121 (insert-before-markers "\n")
12122 (backward-char 1)
12123 (narrow-to-region (point) (point))
12124 (and org-adapt-indentation (org-indent-to-column col)))
12125 ;; Check if we have to remove something.
12126 (setq list (cons what remove))
12127 (while list
12128 (setq elt (pop list))
12129 (when (or (and (eq elt 'scheduled)
12130 (re-search-forward org-scheduled-time-regexp nil t))
12131 (and (eq elt 'deadline)
12132 (re-search-forward org-deadline-time-regexp nil t))
12133 (and (eq elt 'closed)
12134 (re-search-forward org-closed-time-regexp nil t)))
12135 (replace-match "")
12136 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12137 (and (looking-at "[ \t]+") (replace-match ""))
12138 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12139 (when what
12140 (insert
12141 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12142 (cond ((eq what 'scheduled) org-scheduled-string)
12143 ((eq what 'deadline) org-deadline-string)
12144 ((eq what 'closed) org-closed-string))
12145 " ")
12146 (setq ts (org-insert-time-stamp
12147 time
12148 (or org-time-was-given
12149 (and (eq what 'closed) org-log-done-with-time))
12150 (eq what 'closed)
12151 nil nil (list org-end-time-was-given)))
12152 (insert
12153 (if (not (or (bolp) (eq (char-before) ?\ )
12154 (memq (char-after) '(32 10))
12155 (eobp))) " " ""))
12156 (end-of-line 1))
12157 (goto-char (point-min))
12158 (widen)
12159 (if (and (looking-at "[ \t]*\n")
12160 (equal (char-before) ?\n))
12161 (delete-region (1- (point)) (point-at-eol)))
12162 ts))))))
12164 (defvar org-log-note-marker (make-marker))
12165 (defvar org-log-note-purpose nil)
12166 (defvar org-log-note-state nil)
12167 (defvar org-log-note-previous-state nil)
12168 (defvar org-log-note-how nil)
12169 (defvar org-log-note-extra nil)
12170 (defvar org-log-note-window-configuration nil)
12171 (defvar org-log-note-return-to (make-marker))
12172 (defvar org-log-note-effective-time nil
12173 "Remembered current time so that dynamically scoped
12174 `org-extend-today-until' affects tha timestamps in state change
12175 log")
12177 (defvar org-log-post-message nil
12178 "Message to be displayed after a log note has been stored.
12179 The auto-repeater uses this.")
12181 (defun org-add-note ()
12182 "Add a note to the current entry.
12183 This is done in the same way as adding a state change note."
12184 (interactive)
12185 (org-add-log-setup 'note nil nil 'findpos nil))
12187 (defvar org-property-end-re)
12188 (defun org-add-log-setup (&optional purpose state prev-state
12189 findpos how extra)
12190 "Set up the post command hook to take a note.
12191 If this is about to TODO state change, the new state is expected in STATE.
12192 When FINDPOS is non-nil, find the correct position for the note in
12193 the current entry. If not, assume that it can be inserted at point.
12194 HOW is an indicator what kind of note should be created.
12195 EXTRA is additional text that will be inserted into the notes buffer."
12196 (let* ((org-log-into-drawer (org-log-into-drawer))
12197 (drawer (cond ((stringp org-log-into-drawer)
12198 org-log-into-drawer)
12199 (org-log-into-drawer "LOGBOOK")
12200 (t nil))))
12201 (save-restriction
12202 (save-excursion
12203 (when findpos
12204 (org-back-to-heading t)
12205 (narrow-to-region (point) (save-excursion
12206 (outline-next-heading) (point)))
12207 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12208 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12209 "[^\r\n]*\\)?"))
12210 (goto-char (match-end 0))
12211 (cond
12212 (drawer
12213 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12214 nil t)
12215 (progn
12216 (goto-char (match-end 0))
12217 (or org-log-states-order-reversed
12218 (and (re-search-forward org-property-end-re nil t)
12219 (goto-char (1- (match-beginning 0))))))
12220 (insert "\n:" drawer ":\n:END:")
12221 (beginning-of-line 0)
12222 (org-indent-line-function)
12223 (beginning-of-line 2)
12224 (org-indent-line-function)
12225 (end-of-line 0)))
12226 ((and org-log-state-notes-insert-after-drawers
12227 (save-excursion
12228 (forward-line) (looking-at org-drawer-regexp)))
12229 (forward-line)
12230 (while (looking-at org-drawer-regexp)
12231 (goto-char (match-end 0))
12232 (re-search-forward org-property-end-re (point-max) t)
12233 (forward-line))
12234 (forward-line -1)))
12235 (unless org-log-states-order-reversed
12236 (and (= (char-after) ?\n) (forward-char 1))
12237 (org-skip-over-state-notes)
12238 (skip-chars-backward " \t\n\r")))
12239 (move-marker org-log-note-marker (point))
12240 (setq org-log-note-purpose purpose
12241 org-log-note-state state
12242 org-log-note-previous-state prev-state
12243 org-log-note-how how
12244 org-log-note-extra extra
12245 org-log-note-effective-time (org-current-effective-time))
12246 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12248 (defun org-skip-over-state-notes ()
12249 "Skip past the list of State notes in an entry."
12250 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12251 (when (ignore-errors (goto-char (org-in-item-p)))
12252 (let* ((struct (org-list-struct))
12253 (prevs (org-list-prevs-alist struct)))
12254 (while (looking-at "[ \t]*- State")
12255 (goto-char (or (org-list-get-next-item (point) struct prevs)
12256 (org-list-get-item-end (point) struct)))))))
12258 (defun org-add-log-note (&optional purpose)
12259 "Pop up a window for taking a note, and add this note later at point."
12260 (remove-hook 'post-command-hook 'org-add-log-note)
12261 (setq org-log-note-window-configuration (current-window-configuration))
12262 (delete-other-windows)
12263 (move-marker org-log-note-return-to (point))
12264 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12265 (goto-char org-log-note-marker)
12266 (org-switch-to-buffer-other-window "*Org Note*")
12267 (erase-buffer)
12268 (if (memq org-log-note-how '(time state))
12269 (let (current-prefix-arg) (org-store-log-note))
12270 (let ((org-inhibit-startup t)) (org-mode))
12271 (insert (format "# Insert note for %s.
12272 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12273 (cond
12274 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12275 ((eq org-log-note-purpose 'done) "closed todo item")
12276 ((eq org-log-note-purpose 'state)
12277 (format "state change from \"%s\" to \"%s\""
12278 (or org-log-note-previous-state "")
12279 (or org-log-note-state "")))
12280 ((eq org-log-note-purpose 'reschedule)
12281 "rescheduling")
12282 ((eq org-log-note-purpose 'delschedule)
12283 "no longer scheduled")
12284 ((eq org-log-note-purpose 'redeadline)
12285 "changing deadline")
12286 ((eq org-log-note-purpose 'deldeadline)
12287 "removing deadline")
12288 ((eq org-log-note-purpose 'refile)
12289 "refiling")
12290 ((eq org-log-note-purpose 'note)
12291 "this entry")
12292 (t (error "This should not happen")))))
12293 (if org-log-note-extra (insert org-log-note-extra))
12294 (org-set-local 'org-finish-function 'org-store-log-note)
12295 (run-hooks 'org-log-buffer-setup-hook)))
12297 (defvar org-note-abort nil) ; dynamically scoped
12298 (defun org-store-log-note ()
12299 "Finish taking a log note, and insert it to where it belongs."
12300 (let ((txt (buffer-string))
12301 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12302 lines ind bul)
12303 (kill-buffer (current-buffer))
12304 (while (string-match "\\`#.*\n[ \t\n]*" txt)
12305 (setq txt (replace-match "" t t txt)))
12306 (if (string-match "\\s-+\\'" txt)
12307 (setq txt (replace-match "" t t txt)))
12308 (setq lines (org-split-string txt "\n"))
12309 (when (and note (string-match "\\S-" note))
12310 (setq note
12311 (org-replace-escapes
12312 note
12313 (list (cons "%u" (user-login-name))
12314 (cons "%U" user-full-name)
12315 (cons "%t" (format-time-string
12316 (org-time-stamp-format 'long 'inactive)
12317 org-log-note-effective-time))
12318 (cons "%T" (format-time-string
12319 (org-time-stamp-format 'long nil)
12320 org-log-note-effective-time))
12321 (cons "%d" (format-time-string
12322 (org-time-stamp-format nil 'inactive)
12323 org-log-note-effective-time))
12324 (cons "%D" (format-time-string
12325 (org-time-stamp-format nil nil)
12326 org-log-note-effective-time))
12327 (cons "%s" (if org-log-note-state
12328 (concat "\"" org-log-note-state "\"")
12329 ""))
12330 (cons "%S" (if org-log-note-previous-state
12331 (concat "\"" org-log-note-previous-state "\"")
12332 "\"\"")))))
12333 (if lines (setq note (concat note " \\\\")))
12334 (push note lines))
12335 (when (or current-prefix-arg org-note-abort)
12336 (when org-log-into-drawer
12337 (org-remove-empty-drawer-at
12338 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12339 org-log-note-marker))
12340 (setq lines nil))
12341 (when lines
12342 (with-current-buffer (marker-buffer org-log-note-marker)
12343 (save-excursion
12344 (goto-char org-log-note-marker)
12345 (move-marker org-log-note-marker nil)
12346 (end-of-line 1)
12347 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12348 (setq ind (save-excursion
12349 (if (ignore-errors (goto-char (org-in-item-p)))
12350 (let ((struct (org-list-struct)))
12351 (org-list-get-ind
12352 (org-list-get-top-point struct) struct))
12353 (skip-chars-backward " \r\t\n")
12354 (cond
12355 ((and (org-at-heading-p)
12356 org-adapt-indentation)
12357 (1+ (org-current-level)))
12358 ((org-at-heading-p) 0)
12359 (t (org-get-indentation))))))
12360 (setq bul (org-list-bullet-string "-"))
12361 (org-indent-line-to ind)
12362 (insert bul (pop lines))
12363 (let ((ind-body (+ (length bul) ind)))
12364 (while lines
12365 (insert "\n")
12366 (org-indent-line-to ind-body)
12367 (insert (pop lines))))
12368 (message "Note stored")
12369 (org-back-to-heading t)
12370 (org-cycle-hide-drawers 'children)))))
12371 (set-window-configuration org-log-note-window-configuration)
12372 (with-current-buffer (marker-buffer org-log-note-return-to)
12373 (goto-char org-log-note-return-to))
12374 (move-marker org-log-note-return-to nil)
12375 (and org-log-post-message (message "%s" org-log-post-message)))
12377 (defun org-remove-empty-drawer-at (drawer pos)
12378 "Remove an empty drawer DRAWER at position POS.
12379 POS may also be a marker."
12380 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12381 (save-excursion
12382 (save-restriction
12383 (widen)
12384 (goto-char pos)
12385 (if (org-in-regexp
12386 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12387 (replace-match ""))))))
12389 (defun org-sparse-tree (&optional arg)
12390 "Create a sparse tree, prompt for the details.
12391 This command can create sparse trees. You first need to select the type
12392 of match used to create the tree:
12394 t Show all TODO entries.
12395 T Show entries with a specific TODO keyword.
12396 m Show entries selected by a tags/property match.
12397 p Enter a property name and its value (both with completion on existing
12398 names/values) and show entries with that property.
12399 r Show entries matching a regular expression (`/' can be used as well)
12400 d Show deadlines due within `org-deadline-warning-days'.
12401 b Show deadlines and scheduled items before a date.
12402 a Show deadlines and scheduled items after a date."
12403 (interactive "P")
12404 (let (ans kwd value)
12405 (message "Sparse tree: [r]egexp [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty\n [d]eadlines [b]efore-date [a]fter-date")
12406 (setq ans (read-char-exclusive))
12407 (cond
12408 ((equal ans ?d)
12409 (call-interactively 'org-check-deadlines))
12410 ((equal ans ?b)
12411 (call-interactively 'org-check-before-date))
12412 ((equal ans ?a)
12413 (call-interactively 'org-check-after-date))
12414 ((equal ans ?t)
12415 (org-show-todo-tree nil))
12416 ((equal ans ?T)
12417 (org-show-todo-tree '(4)))
12418 ((member ans '(?T ?m))
12419 (call-interactively 'org-match-sparse-tree))
12420 ((member ans '(?p ?P))
12421 (setq kwd (org-icompleting-read "Property: "
12422 (mapcar 'list (org-buffer-property-keys))))
12423 (setq value (org-icompleting-read "Value: "
12424 (mapcar 'list (org-property-values kwd))))
12425 (unless (string-match "\\`{.*}\\'" value)
12426 (setq value (concat "\"" value "\"")))
12427 (org-match-sparse-tree arg (concat kwd "=" value)))
12428 ((member ans '(?r ?R ?/))
12429 (call-interactively 'org-occur))
12430 (t (error "No such sparse tree command \"%c\"" ans)))))
12432 (defvar org-occur-highlights nil
12433 "List of overlays used for occur matches.")
12434 (make-variable-buffer-local 'org-occur-highlights)
12435 (defvar org-occur-parameters nil
12436 "Parameters of the active org-occur calls.
12437 This is a list, each call to org-occur pushes as cons cell,
12438 containing the regular expression and the callback, onto the list.
12439 The list can contain several entries if `org-occur' has been called
12440 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12441 will only contain one set of parameters. When the highlights are
12442 removed (for example with `C-c C-c', or with the next edit (depending
12443 on `org-remove-highlights-with-change'), this variable is emptied
12444 as well.")
12445 (make-variable-buffer-local 'org-occur-parameters)
12447 (defun org-occur (regexp &optional keep-previous callback)
12448 "Make a compact tree which shows all matches of REGEXP.
12449 The tree will show the lines where the regexp matches, and all higher
12450 headlines above the match. It will also show the heading after the match,
12451 to make sure editing the matching entry is easy.
12452 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12453 call to `org-occur' will be kept, to allow stacking of calls to this
12454 command.
12455 If CALLBACK is non-nil, it is a function which is called to confirm
12456 that the match should indeed be shown."
12457 (interactive "sRegexp: \nP")
12458 (when (equal regexp "")
12459 (error "Regexp cannot be empty"))
12460 (unless keep-previous
12461 (org-remove-occur-highlights nil nil t))
12462 (push (cons regexp callback) org-occur-parameters)
12463 (let ((cnt 0))
12464 (save-excursion
12465 (goto-char (point-min))
12466 (if (or (not keep-previous) ; do not want to keep
12467 (not org-occur-highlights)) ; no previous matches
12468 ;; hide everything
12469 (org-overview))
12470 (while (re-search-forward regexp nil t)
12471 (when (or (not callback)
12472 (save-match-data (funcall callback)))
12473 (setq cnt (1+ cnt))
12474 (when org-highlight-sparse-tree-matches
12475 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12476 (org-show-context 'occur-tree))))
12477 (when org-remove-highlights-with-change
12478 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12479 nil 'local))
12480 (unless org-sparse-tree-open-archived-trees
12481 (org-hide-archived-subtrees (point-min) (point-max)))
12482 (run-hooks 'org-occur-hook)
12483 (if (org-called-interactively-p 'interactive)
12484 (message "%d match(es) for regexp %s" cnt regexp))
12485 cnt))
12487 (defun org-occur-next-match (&optional n reset)
12488 "Function for `next-error-function' to find sparse tree matches.
12489 N is the number of matches to move, when negative move backwards.
12490 RESET is entirely ignored - this function always goes back to the
12491 starting point when no match is found."
12492 (let* ((limit (if (< n 0) (point-min) (point-max)))
12493 (search-func (if (< n 0)
12494 'previous-single-char-property-change
12495 'next-single-char-property-change))
12496 (n (abs n))
12497 (pos (point))
12499 (catch 'exit
12500 (while (setq p1 (funcall search-func (point) 'org-type))
12501 (when (equal p1 limit)
12502 (goto-char pos)
12503 (error "No more matches"))
12504 (when (equal (get-char-property p1 'org-type) 'org-occur)
12505 (setq n (1- n))
12506 (when (= n 0)
12507 (goto-char p1)
12508 (throw 'exit (point))))
12509 (goto-char p1))
12510 (goto-char p1)
12511 (error "No more matches"))))
12513 (defun org-show-context (&optional key)
12514 "Make sure point and context are visible.
12515 How much context is shown depends upon the variables
12516 `org-show-hierarchy-above', `org-show-following-heading',
12517 `org-show-entry-below' and `org-show-siblings'."
12518 (let ((heading-p (org-on-heading-p t))
12519 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12520 (following-p (org-get-alist-option org-show-following-heading key))
12521 (entry-p (org-get-alist-option org-show-entry-below key))
12522 (siblings-p (org-get-alist-option org-show-siblings key)))
12523 (catch 'exit
12524 ;; Show heading or entry text
12525 (if (and heading-p (not entry-p))
12526 (org-flag-heading nil) ; only show the heading
12527 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12528 (org-show-hidden-entry))) ; show entire entry
12529 (when following-p
12530 ;; Show next sibling, or heading below text
12531 (save-excursion
12532 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12533 (org-flag-heading nil))))
12534 (when siblings-p (org-show-siblings))
12535 (when hierarchy-p
12536 ;; show all higher headings, possibly with siblings
12537 (save-excursion
12538 (while (and (condition-case nil
12539 (progn (org-up-heading-all 1) t)
12540 (error nil))
12541 (not (bobp)))
12542 (org-flag-heading nil)
12543 (when siblings-p (org-show-siblings))))))))
12545 (defvar org-reveal-start-hook nil
12546 "Hook run before revealing a location.")
12548 (defun org-reveal (&optional siblings)
12549 "Show current entry, hierarchy above it, and the following headline.
12550 This can be used to show a consistent set of context around locations
12551 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12552 not t for the search context.
12554 With optional argument SIBLINGS, on each level of the hierarchy all
12555 siblings are shown. This repairs the tree structure to what it would
12556 look like when opened with hierarchical calls to `org-cycle'.
12557 With double optional argument \\[universal-argument] \\[universal-argument], \
12558 go to the parent and show the
12559 entire tree."
12560 (interactive "P")
12561 (run-hooks 'org-reveal-start-hook)
12562 (let ((org-show-hierarchy-above t)
12563 (org-show-following-heading t)
12564 (org-show-siblings (if siblings t org-show-siblings)))
12565 (org-show-context nil))
12566 (when (equal siblings '(16))
12567 (save-excursion
12568 (when (org-up-heading-safe)
12569 (org-show-subtree)
12570 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12572 (defun org-highlight-new-match (beg end)
12573 "Highlight from BEG to END and mark the highlight is an occur headline."
12574 (let ((ov (make-overlay beg end)))
12575 (overlay-put ov 'face 'secondary-selection)
12576 (overlay-put ov 'org-type 'org-occur)
12577 (push ov org-occur-highlights)))
12579 (defun org-remove-occur-highlights (&optional beg end noremove)
12580 "Remove the occur highlights from the buffer.
12581 BEG and END are ignored. If NOREMOVE is nil, remove this function
12582 from the `before-change-functions' in the current buffer."
12583 (interactive)
12584 (unless org-inhibit-highlight-removal
12585 (mapc 'delete-overlay org-occur-highlights)
12586 (setq org-occur-highlights nil)
12587 (setq org-occur-parameters nil)
12588 (unless noremove
12589 (remove-hook 'before-change-functions
12590 'org-remove-occur-highlights 'local))))
12592 ;;;; Priorities
12594 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12595 "Regular expression matching the priority indicator.")
12597 (defvar org-remove-priority-next-time nil)
12599 (defun org-priority-up ()
12600 "Increase the priority of the current item."
12601 (interactive)
12602 (org-priority 'up))
12604 (defun org-priority-down ()
12605 "Decrease the priority of the current item."
12606 (interactive)
12607 (org-priority 'down))
12609 (defun org-priority (&optional action)
12610 "Change the priority of an item by ARG.
12611 ACTION can be `set', `up', `down', or a character."
12612 (interactive)
12613 (unless org-enable-priority-commands
12614 (error "Priority commands are disabled"))
12615 (setq action (or action 'set))
12616 (let (current new news have remove)
12617 (save-excursion
12618 (org-back-to-heading t)
12619 (if (looking-at org-priority-regexp)
12620 (setq current (string-to-char (match-string 2))
12621 have t))
12622 (cond
12623 ((eq action 'remove)
12624 (setq remove t new ?\ ))
12625 ((or (eq action 'set)
12626 (if (featurep 'xemacs) (characterp action) (integerp action)))
12627 (if (not (eq action 'set))
12628 (setq new action)
12629 (message "Priority %c-%c, SPC to remove: "
12630 org-highest-priority org-lowest-priority)
12631 (save-match-data
12632 (setq new (read-char-exclusive))))
12633 (if (and (= (upcase org-highest-priority) org-highest-priority)
12634 (= (upcase org-lowest-priority) org-lowest-priority))
12635 (setq new (upcase new)))
12636 (cond ((equal new ?\ ) (setq remove t))
12637 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12638 (error "Priority must be between `%c' and `%c'"
12639 org-highest-priority org-lowest-priority))))
12640 ((eq action 'up)
12641 (setq new (if have
12642 (1- current) ; normal cycling
12643 ;; last priority was empty
12644 (if (eq last-command this-command)
12645 org-lowest-priority ; wrap around empty to lowest
12646 ;; default
12647 (if org-priority-start-cycle-with-default
12648 org-default-priority
12649 (1- org-default-priority))))))
12650 ((eq action 'down)
12651 (setq new (if have
12652 (1+ current) ; normal cycling
12653 ;; last priority was empty
12654 (if (eq last-command this-command)
12655 org-highest-priority ; wrap around empty to highest
12656 ;; default
12657 (if org-priority-start-cycle-with-default
12658 org-default-priority
12659 (1+ org-default-priority))))))
12660 (t (error "Invalid action")))
12661 (if (or (< (upcase new) org-highest-priority)
12662 (> (upcase new) org-lowest-priority))
12663 (if (and (memq action '(up down))
12664 (not have) (not (eq last-command this-command)))
12665 ;; `new' is from default priority
12666 (error
12667 "The default can not be set, see `org-default-priority' why")
12668 ;; normal cycling: `new' is beyond highest/lowest priority
12669 ;; and is wrapped around to the empty priority
12670 (setq remove t)))
12671 (setq news (format "%c" new))
12672 (if have
12673 (if remove
12674 (replace-match "" t t nil 1)
12675 (replace-match news t t nil 2))
12676 (if remove
12677 (error "No priority cookie found in line")
12678 (let ((case-fold-search nil))
12679 (looking-at org-todo-line-regexp))
12680 (if (match-end 2)
12681 (progn
12682 (goto-char (match-end 2))
12683 (insert " [#" news "]"))
12684 (goto-char (match-beginning 3))
12685 (insert "[#" news "] "))))
12686 (org-preserve-lc (org-set-tags nil 'align)))
12687 (if remove
12688 (message "Priority removed")
12689 (message "Priority of current item set to %s" news))))
12691 (defun org-get-priority (s)
12692 "Find priority cookie and return priority."
12693 (if (functionp org-get-priority-function)
12694 (funcall org-get-priority-function)
12695 (save-match-data
12696 (if (not (string-match org-priority-regexp s))
12697 (* 1000 (- org-lowest-priority org-default-priority))
12698 (* 1000 (- org-lowest-priority
12699 (string-to-char (match-string 2 s))))))))
12701 ;;;; Tags
12703 (defvar org-agenda-archives-mode)
12704 (defvar org-map-continue-from nil
12705 "Position from where mapping should continue.
12706 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
12708 (defvar org-scanner-tags nil
12709 "The current tag list while the tags scanner is running.")
12710 (defvar org-trust-scanner-tags nil
12711 "Should `org-get-tags-at' use the tags for the scanner.
12712 This is for internal dynamical scoping only.
12713 When this is non-nil, the function `org-get-tags-at' will return the value
12714 of `org-scanner-tags' instead of building the list by itself. This
12715 can lead to large speed-ups when the tags scanner is used in a file with
12716 many entries, and when the list of tags is retrieved, for example to
12717 obtain a list of properties. Building the tags list for each entry in such
12718 a file becomes an N^2 operation - but with this variable set, it scales
12719 as N.")
12721 (defun org-scan-tags (action matcher &optional todo-only)
12722 "Scan headline tags with inheritance and produce output ACTION.
12724 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12725 or `agenda' to produce an entry list for an agenda view. It can also be
12726 a Lisp form or a function that should be called at each matched headline, in
12727 this case the return value is a list of all return values from these calls.
12729 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12730 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12731 only lines with a TODO keyword are included in the output."
12732 (require 'org-agenda)
12733 (let* ((re (concat "^" org-outline-regexp " *\\(\\<\\("
12734 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12735 (org-re
12736 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
12737 (props (list 'face 'default
12738 'done-face 'org-agenda-done
12739 'undone-face 'default
12740 'mouse-face 'highlight
12741 'org-not-done-regexp org-not-done-regexp
12742 'org-todo-regexp org-todo-regexp
12743 'org-complex-heading-regexp org-complex-heading-regexp
12744 'help-echo
12745 (format "mouse-2 or RET jump to org file %s"
12746 (abbreviate-file-name
12747 (or (buffer-file-name (buffer-base-buffer))
12748 (buffer-name (buffer-base-buffer)))))))
12749 (case-fold-search nil)
12750 (org-map-continue-from nil)
12751 lspos tags tags-list
12752 (tags-alist (list (cons 0 org-file-tags)))
12753 (llast 0) rtn rtn1 level category i txt
12754 todo marker entry priority)
12755 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12756 (setq action (list 'lambda nil action)))
12757 (save-excursion
12758 (goto-char (point-min))
12759 (when (eq action 'sparse-tree)
12760 (org-overview)
12761 (org-remove-occur-highlights))
12762 (while (re-search-forward re nil t)
12763 (setq org-map-continue-from nil)
12764 (catch :skip
12765 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12766 tags (if (match-end 4) (org-match-string-no-properties 4)))
12767 (goto-char (setq lspos (match-beginning 0)))
12768 (setq level (org-reduced-level (funcall outline-level))
12769 category (org-get-category))
12770 (setq i llast llast level)
12771 ;; remove tag lists from same and sublevels
12772 (while (>= i level)
12773 (when (setq entry (assoc i tags-alist))
12774 (setq tags-alist (delete entry tags-alist)))
12775 (setq i (1- i)))
12776 ;; add the next tags
12777 (when tags
12778 (setq tags (org-split-string tags ":")
12779 tags-alist
12780 (cons (cons level tags) tags-alist)))
12781 ;; compile tags for current headline
12782 (setq tags-list
12783 (if org-use-tag-inheritance
12784 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12785 tags)
12786 org-scanner-tags tags-list)
12787 (when org-use-tag-inheritance
12788 (setcdr (car tags-alist)
12789 (mapcar (lambda (x)
12790 (setq x (copy-sequence x))
12791 (org-add-prop-inherited x))
12792 (cdar tags-alist))))
12793 (when (and tags org-use-tag-inheritance
12794 (or (not (eq t org-use-tag-inheritance))
12795 org-tags-exclude-from-inheritance))
12796 ;; selective inheritance, remove uninherited ones
12797 (setcdr (car tags-alist)
12798 (org-remove-uninherited-tags (cdar tags-alist))))
12799 (when (and
12801 ;; eval matcher only when the todo condition is OK
12802 (and (or (not todo-only) (member todo org-not-done-keywords))
12803 (let ((case-fold-search t)) (eval matcher)))
12805 ;; Call the skipper, but return t if it does not skip,
12806 ;; so that the `and' form continues evaluating
12807 (progn
12808 (unless (eq action 'sparse-tree) (org-agenda-skip))
12811 ;; Check if timestamps are deselecting this entry
12812 (or (not todo-only)
12813 (and (member todo org-not-done-keywords)
12814 (or (not org-agenda-tags-todo-honor-ignore-options)
12815 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
12817 ;; Extra check for the archive tag
12818 ;; FIXME: Does the skipper already do this????
12820 (not (member org-archive-tag tags-list))
12821 ;; we have an archive tag, should we use this anyway?
12822 (or (not org-agenda-skip-archived-trees)
12823 (and (eq action 'agenda) org-agenda-archives-mode))))
12825 ;; select this headline
12827 (cond
12828 ((eq action 'sparse-tree)
12829 (and org-highlight-sparse-tree-matches
12830 (org-get-heading) (match-end 0)
12831 (org-highlight-new-match
12832 (match-beginning 0) (match-beginning 1)))
12833 (org-show-context 'tags-tree))
12834 ((eq action 'agenda)
12835 (setq txt (org-agenda-format-item
12837 (concat
12838 (if (eq org-tags-match-list-sublevels 'indented)
12839 (make-string (1- level) ?.) "")
12840 (org-get-heading))
12841 category
12842 tags-list
12844 priority (org-get-priority txt))
12845 (goto-char lspos)
12846 (setq marker (org-agenda-new-marker))
12847 (org-add-props txt props
12848 'org-marker marker 'org-hd-marker marker 'org-category category
12849 'todo-state todo
12850 'priority priority 'type "tagsmatch")
12851 (push txt rtn))
12852 ((functionp action)
12853 (setq org-map-continue-from nil)
12854 (save-excursion
12855 (setq rtn1 (funcall action))
12856 (push rtn1 rtn)))
12857 (t (error "Invalid action")))
12859 ;; if we are to skip sublevels, jump to end of subtree
12860 (unless org-tags-match-list-sublevels
12861 (org-end-of-subtree t)
12862 (backward-char 1))))
12863 ;; Get the correct position from where to continue
12864 (if org-map-continue-from
12865 (goto-char org-map-continue-from)
12866 (and (= (point) lspos) (end-of-line 1)))))
12867 (when (and (eq action 'sparse-tree)
12868 (not org-sparse-tree-open-archived-trees))
12869 (org-hide-archived-subtrees (point-min) (point-max)))
12870 (nreverse rtn)))
12872 (defun org-remove-uninherited-tags (tags)
12873 "Remove all tags that are not inherited from the list TAGS."
12874 (cond
12875 ((eq org-use-tag-inheritance t)
12876 (if org-tags-exclude-from-inheritance
12877 (org-delete-all org-tags-exclude-from-inheritance tags)
12878 tags))
12879 ((not org-use-tag-inheritance) nil)
12880 ((stringp org-use-tag-inheritance)
12881 (delq nil (mapcar
12882 (lambda (x)
12883 (if (and (string-match org-use-tag-inheritance x)
12884 (not (member x org-tags-exclude-from-inheritance)))
12885 x nil))
12886 tags)))
12887 ((listp org-use-tag-inheritance)
12888 (delq nil (mapcar
12889 (lambda (x)
12890 (if (member x org-use-tag-inheritance) x nil))
12891 tags)))))
12893 (defvar todo-only) ;; dynamically scoped
12895 (defun org-match-sparse-tree (&optional todo-only match)
12896 "Create a sparse tree according to tags string MATCH.
12897 MATCH can contain positive and negative selection of tags, like
12898 \"+WORK+URGENT-WITHBOSS\".
12899 If optional argument TODO-ONLY is non-nil, only select lines that are
12900 also TODO lines."
12901 (interactive "P")
12902 (org-prepare-agenda-buffers (list (current-buffer)))
12903 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
12905 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
12907 (defvar org-cached-props nil)
12908 (defun org-cached-entry-get (pom property)
12909 (if (or (eq t org-use-property-inheritance)
12910 (and (stringp org-use-property-inheritance)
12911 (string-match org-use-property-inheritance property))
12912 (and (listp org-use-property-inheritance)
12913 (member property org-use-property-inheritance)))
12914 ;; Caching is not possible, check it directly
12915 (org-entry-get pom property 'inherit)
12916 ;; Get all properties, so that we can do complicated checks easily
12917 (cdr (assoc property (or org-cached-props
12918 (setq org-cached-props
12919 (org-entry-properties pom)))))))
12921 (defun org-global-tags-completion-table (&optional files)
12922 "Return the list of all tags in all agenda buffer/files.
12923 Optional FILES argument is a list of files to which can be used
12924 instead of the agenda files."
12925 (save-excursion
12926 (org-uniquify
12927 (delq nil
12928 (apply 'append
12929 (mapcar
12930 (lambda (file)
12931 (set-buffer (find-file-noselect file))
12932 (append (org-get-buffer-tags)
12933 (mapcar (lambda (x) (if (stringp (car-safe x))
12934 (list (car-safe x)) nil))
12935 org-tag-alist)))
12936 (if (and files (car files))
12937 files
12938 (org-agenda-files))))))))
12940 (defun org-make-tags-matcher (match)
12941 "Create the TAGS/TODO matcher form for the selection string MATCH."
12942 ;; todo-only is scoped dynamically into this function, and the function
12943 ;; may change it if the matcher asks for it.
12944 (unless match
12945 ;; Get a new match request, with completion
12946 (let ((org-last-tags-completion-table
12947 (org-global-tags-completion-table)))
12948 (setq match (org-completing-read-no-i
12949 "Match: " 'org-tags-completion-function nil nil nil
12950 'org-tags-history))))
12952 ;; Parse the string and create a lisp form
12953 (let ((match0 match)
12954 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
12955 minus tag mm
12956 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
12957 orterms term orlist re-p str-p level-p level-op time-p
12958 prop-p pn pv po gv rest)
12959 (if (string-match "/+" match)
12960 ;; match contains also a todo-matching request
12961 (progn
12962 (setq tagsmatch (substring match 0 (match-beginning 0))
12963 todomatch (substring match (match-end 0)))
12964 (if (string-match "^!" todomatch)
12965 (setq todo-only t todomatch (substring todomatch 1)))
12966 (if (string-match "^\\s-*$" todomatch)
12967 (setq todomatch nil)))
12968 ;; only matching tags
12969 (setq tagsmatch match todomatch nil))
12971 ;; Make the tags matcher
12972 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
12973 (setq tagsmatcher t)
12974 (setq orterms (org-split-string tagsmatch "|") orlist nil)
12975 (while (setq term (pop orterms))
12976 (while (and (equal (substring term -1) "\\") orterms)
12977 (setq term (concat term "|" (pop orterms)))) ; repair bad split
12978 (while (string-match re term)
12979 (setq rest (substring term (match-end 0))
12980 minus (and (match-end 1)
12981 (equal (match-string 1 term) "-"))
12982 tag (save-match-data (replace-regexp-in-string
12983 "\\\\-" "-"
12984 (match-string 2 term)))
12985 re-p (equal (string-to-char tag) ?{)
12986 level-p (match-end 4)
12987 prop-p (match-end 5)
12988 mm (cond
12989 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
12990 (level-p
12991 (setq level-op (org-op-to-function (match-string 3 term)))
12992 `(,level-op level ,(string-to-number
12993 (match-string 4 term))))
12994 (prop-p
12995 (setq pn (match-string 5 term)
12996 po (match-string 6 term)
12997 pv (match-string 7 term)
12998 re-p (equal (string-to-char pv) ?{)
12999 str-p (equal (string-to-char pv) ?\")
13000 time-p (save-match-data
13001 (string-match "^\"[[<].*[]>]\"$" pv))
13002 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13003 (if time-p (setq pv (org-matcher-time pv)))
13004 (setq po (org-op-to-function po (if time-p 'time str-p)))
13005 (cond
13006 ((equal pn "CATEGORY")
13007 (setq gv '(get-text-property (point) 'org-category)))
13008 ((equal pn "TODO")
13009 (setq gv 'todo))
13011 (setq gv `(org-cached-entry-get nil ,pn))))
13012 (if re-p
13013 (if (eq po 'org<>)
13014 `(not (string-match ,pv (or ,gv "")))
13015 `(string-match ,pv (or ,gv "")))
13016 (if str-p
13017 `(,po (or ,gv "") ,pv)
13018 `(,po (string-to-number (or ,gv ""))
13019 ,(string-to-number pv) ))))
13020 (t `(member ,tag tags-list)))
13021 mm (if minus (list 'not mm) mm)
13022 term rest)
13023 (push mm tagsmatcher))
13024 (push (if (> (length tagsmatcher) 1)
13025 (cons 'and tagsmatcher)
13026 (car tagsmatcher))
13027 orlist)
13028 (setq tagsmatcher nil))
13029 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13030 (setq tagsmatcher
13031 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13032 ;; Make the todo matcher
13033 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13034 (setq todomatcher t)
13035 (setq orterms (org-split-string todomatch "|") orlist nil)
13036 (while (setq term (pop orterms))
13037 (while (string-match re term)
13038 (setq minus (and (match-end 1)
13039 (equal (match-string 1 term) "-"))
13040 kwd (match-string 2 term)
13041 re-p (equal (string-to-char kwd) ?{)
13042 term (substring term (match-end 0))
13043 mm (if re-p
13044 `(string-match ,(substring kwd 1 -1) todo)
13045 (list 'equal 'todo kwd))
13046 mm (if minus (list 'not mm) mm))
13047 (push mm todomatcher))
13048 (push (if (> (length todomatcher) 1)
13049 (cons 'and todomatcher)
13050 (car todomatcher))
13051 orlist)
13052 (setq todomatcher nil))
13053 (setq todomatcher (if (> (length orlist) 1)
13054 (cons 'or orlist) (car orlist))))
13056 ;; Return the string and lisp forms of the matcher
13057 (setq matcher (if todomatcher
13058 (list 'and tagsmatcher todomatcher)
13059 tagsmatcher))
13060 (cons match0 matcher)))
13062 (defun org-op-to-function (op &optional stringp)
13063 "Turn an operator into the appropriate function."
13064 (setq op
13065 (cond
13066 ((equal op "<" ) '(< string< org-time<))
13067 ((equal op ">" ) '(> org-string> org-time>))
13068 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13069 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13070 ((member op '("=" "==")) '(= string= org-time=))
13071 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13072 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13074 (defun org<> (a b) (not (= a b)))
13075 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13076 (defun org-string>= (a b) (not (string< a b)))
13077 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13078 (defun org-string<> (a b) (not (string= a b)))
13079 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13080 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13081 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13082 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13083 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13084 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13085 (defun org-2ft (s)
13086 "Convert S to a floating point time.
13087 If S is already a number, just return it. If it is a string, parse
13088 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13089 (cond
13090 ((numberp s) s)
13091 ((stringp s)
13092 (condition-case nil
13093 (float-time (apply 'encode-time (org-parse-time-string s)))
13094 (error 0.)))
13095 (t 0.)))
13097 (defun org-time-today ()
13098 "Time in seconds today at 0:00.
13099 Returns the float number of seconds since the beginning of the
13100 epoch to the beginning of today (00:00)."
13101 (float-time (apply 'encode-time
13102 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13104 (defun org-matcher-time (s)
13105 "Interpret a time comparison value."
13106 (save-match-data
13107 (cond
13108 ((string= s "<now>") (float-time))
13109 ((string= s "<today>") (org-time-today))
13110 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13111 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13112 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
13113 (+ (org-time-today)
13114 (* (string-to-number (match-string 1 s))
13115 (cdr (assoc (match-string 2 s)
13116 '(("d" . 86400.0) ("w" . 604800.0)
13117 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13118 (t (org-2ft s)))))
13120 (defun org-match-any-p (re list)
13121 "Does re match any element of list?"
13122 (setq list (mapcar (lambda (x) (string-match re x)) list))
13123 (delq nil list))
13125 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13126 (defvar org-tags-overlay (make-overlay 1 1))
13127 (org-detach-overlay org-tags-overlay)
13129 (defun org-get-local-tags-at (&optional pos)
13130 "Get a list of tags defined in the current headline."
13131 (org-get-tags-at pos 'local))
13133 (defun org-get-local-tags ()
13134 "Get a list of tags defined in the current headline."
13135 (org-get-tags-at nil 'local))
13137 (defun org-get-tags-at (&optional pos local)
13138 "Get a list of all headline tags applicable at POS.
13139 POS defaults to point. If tags are inherited, the list contains
13140 the targets in the same sequence as the headlines appear, i.e.
13141 the tags of the current headline come last.
13142 When LOCAL is non-nil, only return tags from the current headline,
13143 ignore inherited ones."
13144 (interactive)
13145 (if (and org-trust-scanner-tags
13146 (or (not pos) (equal pos (point)))
13147 (not local))
13148 org-scanner-tags
13149 (let (tags ltags lastpos parent)
13150 (save-excursion
13151 (save-restriction
13152 (widen)
13153 (goto-char (or pos (point)))
13154 (save-match-data
13155 (catch 'done
13156 (condition-case nil
13157 (progn
13158 (org-back-to-heading t)
13159 (while (not (equal lastpos (point)))
13160 (setq lastpos (point))
13161 (when (looking-at
13162 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13163 (setq ltags (org-split-string
13164 (org-match-string-no-properties 1) ":"))
13165 (when parent
13166 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13167 (setq tags (append
13168 (if parent
13169 (org-remove-uninherited-tags ltags)
13170 ltags)
13171 tags)))
13172 (or org-use-tag-inheritance (throw 'done t))
13173 (if local (throw 'done t))
13174 (or (org-up-heading-safe) (error nil))
13175 (setq parent t)))
13176 (error nil)))))
13177 (if local
13178 tags
13179 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13181 (defun org-add-prop-inherited (s)
13182 (add-text-properties 0 (length s) '(inherited t) s)
13185 (defun org-toggle-tag (tag &optional onoff)
13186 "Toggle the tag TAG for the current line.
13187 If ONOFF is `on' or `off', don't toggle but set to this state."
13188 (let (res current)
13189 (save-excursion
13190 (org-back-to-heading t)
13191 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13192 (point-at-eol) t)
13193 (progn
13194 (setq current (match-string 1))
13195 (replace-match ""))
13196 (setq current ""))
13197 (setq current (nreverse (org-split-string current ":")))
13198 (cond
13199 ((eq onoff 'on)
13200 (setq res t)
13201 (or (member tag current) (push tag current)))
13202 ((eq onoff 'off)
13203 (or (not (member tag current)) (setq current (delete tag current))))
13204 (t (if (member tag current)
13205 (setq current (delete tag current))
13206 (setq res t)
13207 (push tag current))))
13208 (end-of-line 1)
13209 (if current
13210 (progn
13211 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13212 (org-set-tags nil t))
13213 (delete-horizontal-space))
13214 (run-hooks 'org-after-tags-change-hook))
13215 res))
13217 (defun org-align-tags-here (to-col)
13218 ;; Assumes that this is a headline
13219 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13220 (beginning-of-line 1)
13221 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13222 (< pos (match-beginning 2)))
13223 (progn
13224 (setq tags-l (- (match-end 2) (match-beginning 2)))
13225 (goto-char (match-beginning 1))
13226 (insert " ")
13227 (delete-region (point) (1+ (match-beginning 2)))
13228 (setq ncol (max (current-column)
13229 (1+ col)
13230 (if (> to-col 0)
13231 to-col
13232 (- (abs to-col) tags-l))))
13233 (setq p (point))
13234 (insert (make-string (- ncol (current-column)) ?\ ))
13235 (setq ncol (current-column))
13236 (when indent-tabs-mode (tabify p (point-at-eol)))
13237 (org-move-to-column (min ncol col) t))
13238 (goto-char pos))))
13240 (defun org-set-tags-command (&optional arg just-align)
13241 "Call the set-tags command for the current entry."
13242 (interactive "P")
13243 (if (org-on-heading-p)
13244 (org-set-tags arg just-align)
13245 (save-excursion
13246 (org-back-to-heading t)
13247 (org-set-tags arg just-align))))
13249 (defun org-set-tags-to (data)
13250 "Set the tags of the current entry to DATA, replacing the current tags.
13251 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13252 If DATA is nil or the empty string, any tags will be removed."
13253 (interactive "sTags: ")
13254 (setq data
13255 (cond
13256 ((eq data nil) "")
13257 ((equal data "") "")
13258 ((stringp data)
13259 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13260 ":"))
13261 ((listp data)
13262 (concat ":" (mapconcat 'identity data ":") ":"))
13263 (t nil)))
13264 (when data
13265 (save-excursion
13266 (org-back-to-heading t)
13267 (when (looking-at org-complex-heading-regexp)
13268 (if (match-end 5)
13269 (progn
13270 (goto-char (match-beginning 5))
13271 (insert data)
13272 (delete-region (point) (point-at-eol))
13273 (org-set-tags nil 'align))
13274 (goto-char (point-at-eol))
13275 (insert " " data)
13276 (org-set-tags nil 'align)))
13277 (beginning-of-line 1)
13278 (if (looking-at ".*?\\([ \t]+\\)$")
13279 (delete-region (match-beginning 1) (match-end 1))))))
13281 (defun org-align-all-tags ()
13282 "Align the tags i all headings."
13283 (interactive)
13284 (save-excursion
13285 (or (ignore-errors (org-back-to-heading t))
13286 (outline-next-heading))
13287 (if (org-on-heading-p)
13288 (org-set-tags t)
13289 (message "No headings"))))
13291 (defvar org-indent-indentation-per-level)
13292 (defun org-set-tags (&optional arg just-align)
13293 "Set the tags for the current headline.
13294 With prefix ARG, realign all tags in headings in the current buffer."
13295 (interactive "P")
13296 (let* ((re org-outline-regexp-bol)
13297 (current (org-get-tags-string))
13298 (col (current-column))
13299 (org-setting-tags t)
13300 table current-tags inherited-tags ; computed below when needed
13301 tags p0 c0 c1 rpl di tc level)
13302 (if arg
13303 (save-excursion
13304 (goto-char (point-min))
13305 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13306 (while (re-search-forward re nil t)
13307 (org-set-tags nil t)
13308 (end-of-line 1)))
13309 (message "All tags realigned to column %d" org-tags-column))
13310 (if just-align
13311 (setq tags current)
13312 ;; Get a new set of tags from the user
13313 (save-excursion
13314 (setq table (append org-tag-persistent-alist
13315 (or org-tag-alist (org-get-buffer-tags))
13316 (and
13317 org-complete-tags-always-offer-all-agenda-tags
13318 (org-global-tags-completion-table
13319 (org-agenda-files))))
13320 org-last-tags-completion-table table
13321 current-tags (org-split-string current ":")
13322 inherited-tags (nreverse
13323 (nthcdr (length current-tags)
13324 (nreverse (org-get-tags-at))))
13325 tags
13326 (if (or (eq t org-use-fast-tag-selection)
13327 (and org-use-fast-tag-selection
13328 (delq nil (mapcar 'cdr table))))
13329 (org-fast-tag-selection
13330 current-tags inherited-tags table
13331 (if org-fast-tag-selection-include-todo
13332 org-todo-key-alist))
13333 (let ((org-add-colon-after-tag-completion t))
13334 (org-trim
13335 (org-icompleting-read "Tags: "
13336 'org-tags-completion-function
13337 nil nil current 'org-tags-history))))))
13338 (while (string-match "[-+&]+" tags)
13339 ;; No boolean logic, just a list
13340 (setq tags (replace-match ":" t t tags))))
13342 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13344 (if org-tags-sort-function
13345 (setq tags (mapconcat 'identity
13346 (sort (org-split-string
13347 tags (org-re "[^[:alnum:]_@#%]+"))
13348 org-tags-sort-function) ":")))
13350 (if (string-match "\\`[\t ]*\\'" tags)
13351 (setq tags "")
13352 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13353 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13355 ;; Insert new tags at the correct column
13356 (beginning-of-line 1)
13357 (setq level (or (and (looking-at org-outline-regexp)
13358 (- (match-end 0) (point) 1))
13360 (cond
13361 ((and (equal current "") (equal tags "")))
13362 ((re-search-forward
13363 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13364 (point-at-eol) t)
13365 (if (equal tags "")
13366 (setq rpl "")
13367 (goto-char (match-beginning 0))
13368 (setq c0 (current-column)
13369 ;; compute offset for the case of org-indent-mode active
13370 di (if org-indent-mode
13371 (* (1- org-indent-indentation-per-level) (1- level))
13373 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13374 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13375 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13376 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13377 (replace-match rpl t t)
13378 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13379 tags)
13380 (t (error "Tags alignment failed")))
13381 (org-move-to-column col)
13382 (unless just-align
13383 (run-hooks 'org-after-tags-change-hook)))))
13385 (defun org-change-tag-in-region (beg end tag off)
13386 "Add or remove TAG for each entry in the region.
13387 This works in the agenda, and also in an org-mode buffer."
13388 (interactive
13389 (list (region-beginning) (region-end)
13390 (let ((org-last-tags-completion-table
13391 (if (eq major-mode 'org-mode)
13392 (org-get-buffer-tags)
13393 (org-global-tags-completion-table))))
13394 (org-icompleting-read
13395 "Tag: " 'org-tags-completion-function nil nil nil
13396 'org-tags-history))
13397 (progn
13398 (message "[s]et or [r]emove? ")
13399 (equal (read-char-exclusive) ?r))))
13400 (if (fboundp 'deactivate-mark) (deactivate-mark))
13401 (let ((agendap (equal major-mode 'org-agenda-mode))
13402 l1 l2 m buf pos newhead (cnt 0))
13403 (goto-char end)
13404 (setq l2 (1- (org-current-line)))
13405 (goto-char beg)
13406 (setq l1 (org-current-line))
13407 (loop for l from l1 to l2 do
13408 (org-goto-line l)
13409 (setq m (get-text-property (point) 'org-hd-marker))
13410 (when (or (and (eq major-mode 'org-mode) (org-on-heading-p))
13411 (and agendap m))
13412 (setq buf (if agendap (marker-buffer m) (current-buffer))
13413 pos (if agendap m (point)))
13414 (with-current-buffer buf
13415 (save-excursion
13416 (save-restriction
13417 (goto-char pos)
13418 (setq cnt (1+ cnt))
13419 (org-toggle-tag tag (if off 'off 'on))
13420 (setq newhead (org-get-heading)))))
13421 (and agendap (org-agenda-change-all-lines newhead m))))
13422 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13424 (defun org-tags-completion-function (string predicate &optional flag)
13425 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13426 (confirm (lambda (x) (stringp (car x)))))
13427 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13428 (setq s1 (match-string 1 string)
13429 s2 (match-string 2 string))
13430 (setq s1 "" s2 string))
13431 (cond
13432 ((eq flag nil)
13433 ;; try completion
13434 (setq rtn (try-completion s2 ctable confirm))
13435 (if (stringp rtn)
13436 (setq rtn
13437 (concat s1 s2 (substring rtn (length s2))
13438 (if (and org-add-colon-after-tag-completion
13439 (assoc rtn ctable))
13440 ":" ""))))
13441 rtn)
13442 ((eq flag t)
13443 ;; all-completions
13444 (all-completions s2 ctable confirm)
13446 ((eq flag 'lambda)
13447 ;; exact match?
13448 (assoc s2 ctable)))
13451 (defun org-fast-tag-insert (kwd tags face &optional end)
13452 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13453 (insert (format "%-12s" (concat kwd ":"))
13454 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13455 (or end "")))
13457 (defun org-fast-tag-show-exit (flag)
13458 (save-excursion
13459 (org-goto-line 3)
13460 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13461 (replace-match ""))
13462 (when flag
13463 (end-of-line 1)
13464 (org-move-to-column (- (window-width) 19) t)
13465 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13467 (defun org-set-current-tags-overlay (current prefix)
13468 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13469 (if (featurep 'xemacs)
13470 (org-overlay-display org-tags-overlay (concat prefix s)
13471 'secondary-selection)
13472 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13473 (org-overlay-display org-tags-overlay (concat prefix s)))))
13475 (defvar org-last-tag-selection-key nil)
13476 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13477 "Fast tag selection with single keys.
13478 CURRENT is the current list of tags in the headline, INHERITED is the
13479 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13480 possibly with grouping information. TODO-TABLE is a similar table with
13481 TODO keywords, should these have keys assigned to them.
13482 If the keys are nil, a-z are automatically assigned.
13483 Returns the new tags string, or nil to not change the current settings."
13484 (let* ((fulltable (append table todo-table))
13485 (maxlen (apply 'max (mapcar
13486 (lambda (x)
13487 (if (stringp (car x)) (string-width (car x)) 0))
13488 fulltable)))
13489 (buf (current-buffer))
13490 (expert (eq org-fast-tag-selection-single-key 'expert))
13491 (buffer-tags nil)
13492 (fwidth (+ maxlen 3 1 3))
13493 (ncol (/ (- (window-width) 4) fwidth))
13494 (i-face 'org-done)
13495 (c-face 'org-todo)
13496 tg cnt e c char c1 c2 ntable tbl rtn
13497 ov-start ov-end ov-prefix
13498 (exit-after-next org-fast-tag-selection-single-key)
13499 (done-keywords org-done-keywords)
13500 groups ingroup)
13501 (save-excursion
13502 (beginning-of-line 1)
13503 (if (looking-at
13504 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13505 (setq ov-start (match-beginning 1)
13506 ov-end (match-end 1)
13507 ov-prefix "")
13508 (setq ov-start (1- (point-at-eol))
13509 ov-end (1+ ov-start))
13510 (skip-chars-forward "^\n\r")
13511 (setq ov-prefix
13512 (concat
13513 (buffer-substring (1- (point)) (point))
13514 (if (> (current-column) org-tags-column)
13516 (make-string (- org-tags-column (current-column)) ?\ ))))))
13517 (move-overlay org-tags-overlay ov-start ov-end)
13518 (save-window-excursion
13519 (if expert
13520 (set-buffer (get-buffer-create " *Org tags*"))
13521 (delete-other-windows)
13522 (split-window-vertically)
13523 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13524 (erase-buffer)
13525 (org-set-local 'org-done-keywords done-keywords)
13526 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13527 (org-fast-tag-insert "Current" current c-face "\n\n")
13528 (org-fast-tag-show-exit exit-after-next)
13529 (org-set-current-tags-overlay current ov-prefix)
13530 (setq tbl fulltable char ?a cnt 0)
13531 (while (setq e (pop tbl))
13532 (cond
13533 ((equal (car e) :startgroup)
13534 (push '() groups) (setq ingroup t)
13535 (when (not (= cnt 0))
13536 (setq cnt 0)
13537 (insert "\n"))
13538 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13539 ((equal (car e) :endgroup)
13540 (setq ingroup nil cnt 0)
13541 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13542 ((equal e '(:newline))
13543 (when (not (= cnt 0))
13544 (setq cnt 0)
13545 (insert "\n")
13546 (setq e (car tbl))
13547 (while (equal (car tbl) '(:newline))
13548 (insert "\n")
13549 (setq tbl (cdr tbl)))))
13551 (setq tg (copy-sequence (car e)) c2 nil)
13552 (if (cdr e)
13553 (setq c (cdr e))
13554 ;; automatically assign a character.
13555 (setq c1 (string-to-char
13556 (downcase (substring
13557 tg (if (= (string-to-char tg) ?@) 1 0)))))
13558 (if (or (rassoc c1 ntable) (rassoc c1 table))
13559 (while (or (rassoc char ntable) (rassoc char table))
13560 (setq char (1+ char)))
13561 (setq c2 c1))
13562 (setq c (or c2 char)))
13563 (if ingroup (push tg (car groups)))
13564 (setq tg (org-add-props tg nil 'face
13565 (cond
13566 ((not (assoc tg table))
13567 (org-get-todo-face tg))
13568 ((member tg current) c-face)
13569 ((member tg inherited) i-face)
13570 (t nil))))
13571 (if (and (= cnt 0) (not ingroup)) (insert " "))
13572 (insert "[" c "] " tg (make-string
13573 (- fwidth 4 (length tg)) ?\ ))
13574 (push (cons tg c) ntable)
13575 (when (= (setq cnt (1+ cnt)) ncol)
13576 (insert "\n")
13577 (if ingroup (insert " "))
13578 (setq cnt 0)))))
13579 (setq ntable (nreverse ntable))
13580 (insert "\n")
13581 (goto-char (point-min))
13582 (if (not expert) (org-fit-window-to-buffer))
13583 (setq rtn
13584 (catch 'exit
13585 (while t
13586 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13587 (if (not groups) "no " "")
13588 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13589 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13590 (setq org-last-tag-selection-key c)
13591 (cond
13592 ((= c ?\r) (throw 'exit t))
13593 ((= c ?!)
13594 (setq groups (not groups))
13595 (goto-char (point-min))
13596 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13597 ((= c ?\C-c)
13598 (if (not expert)
13599 (org-fast-tag-show-exit
13600 (setq exit-after-next (not exit-after-next)))
13601 (setq expert nil)
13602 (delete-other-windows)
13603 (set-window-buffer (split-window-vertically) " *Org tags*")
13604 (org-switch-to-buffer-other-window " *Org tags*")
13605 (org-fit-window-to-buffer)))
13606 ((or (= c ?\C-g)
13607 (and (= c ?q) (not (rassoc c ntable))))
13608 (org-detach-overlay org-tags-overlay)
13609 (setq quit-flag t))
13610 ((= c ?\ )
13611 (setq current nil)
13612 (if exit-after-next (setq exit-after-next 'now)))
13613 ((= c ?\t)
13614 (condition-case nil
13615 (setq tg (org-icompleting-read
13616 "Tag: "
13617 (or buffer-tags
13618 (with-current-buffer buf
13619 (org-get-buffer-tags)))))
13620 (quit (setq tg "")))
13621 (when (string-match "\\S-" tg)
13622 (add-to-list 'buffer-tags (list tg))
13623 (if (member tg current)
13624 (setq current (delete tg current))
13625 (push tg current)))
13626 (if exit-after-next (setq exit-after-next 'now)))
13627 ((setq e (rassoc c todo-table) tg (car e))
13628 (with-current-buffer buf
13629 (save-excursion (org-todo tg)))
13630 (if exit-after-next (setq exit-after-next 'now)))
13631 ((setq e (rassoc c ntable) tg (car e))
13632 (if (member tg current)
13633 (setq current (delete tg current))
13634 (loop for g in groups do
13635 (if (member tg g)
13636 (mapc (lambda (x)
13637 (setq current (delete x current)))
13638 g)))
13639 (push tg current))
13640 (if exit-after-next (setq exit-after-next 'now))))
13642 ;; Create a sorted list
13643 (setq current
13644 (sort current
13645 (lambda (a b)
13646 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13647 (if (eq exit-after-next 'now) (throw 'exit t))
13648 (goto-char (point-min))
13649 (beginning-of-line 2)
13650 (delete-region (point) (point-at-eol))
13651 (org-fast-tag-insert "Current" current c-face)
13652 (org-set-current-tags-overlay current ov-prefix)
13653 (while (re-search-forward
13654 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13655 (setq tg (match-string 1))
13656 (add-text-properties
13657 (match-beginning 1) (match-end 1)
13658 (list 'face
13659 (cond
13660 ((member tg current) c-face)
13661 ((member tg inherited) i-face)
13662 (t (get-text-property (match-beginning 1) 'face))))))
13663 (goto-char (point-min)))))
13664 (org-detach-overlay org-tags-overlay)
13665 (if rtn
13666 (mapconcat 'identity current ":")
13667 nil))))
13669 (defun org-get-tags-string ()
13670 "Get the TAGS string in the current headline."
13671 (unless (org-on-heading-p t)
13672 (error "Not on a heading"))
13673 (save-excursion
13674 (beginning-of-line 1)
13675 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13676 (org-match-string-no-properties 1)
13677 "")))
13679 (defun org-get-tags ()
13680 "Get the list of tags specified in the current headline."
13681 (org-split-string (org-get-tags-string) ":"))
13683 (defun org-get-buffer-tags ()
13684 "Get a table of all tags used in the buffer, for completion."
13685 (let (tags)
13686 (save-excursion
13687 (goto-char (point-min))
13688 (while (re-search-forward
13689 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13690 (when (equal (char-after (point-at-bol 0)) ?*)
13691 (mapc (lambda (x) (add-to-list 'tags x))
13692 (org-split-string (org-match-string-no-properties 1) ":")))))
13693 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13694 (mapcar 'list tags)))
13696 ;;;; The mapping API
13698 ;;;###autoload
13699 (defun org-map-entries (func &optional match scope &rest skip)
13700 "Call FUNC at each headline selected by MATCH in SCOPE.
13702 FUNC is a function or a lisp form. The function will be called without
13703 arguments, with the cursor positioned at the beginning of the headline.
13704 The return values of all calls to the function will be collected and
13705 returned as a list.
13707 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13708 does not need to preserve point. After evaluation, the cursor will be
13709 moved to the end of the line (presumably of the headline of the
13710 processed entry) and search continues from there. Under some
13711 circumstances, this may not produce the wanted results. For example,
13712 if you have removed (e.g. archived) the current (sub)tree it could
13713 mean that the next entry will be skipped entirely. In such cases, you
13714 can specify the position from where search should continue by making
13715 FUNC set the variable `org-map-continue-from' to the desired buffer
13716 position.
13718 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13719 Only headlines that are matched by this query will be considered during
13720 the iteration. When MATCH is nil or t, all headlines will be
13721 visited by the iteration.
13723 SCOPE determines the scope of this command. It can be any of:
13725 nil The current buffer, respecting the restriction if any
13726 tree The subtree started with the entry at point
13727 region The entries within the active region, if any
13728 file The current buffer, without restriction
13729 file-with-archives
13730 The current buffer, and any archives associated with it
13731 agenda All agenda files
13732 agenda-with-archives
13733 All agenda files with any archive files associated with them
13734 \(file1 file2 ...)
13735 If this is a list, all files in the list will be scanned
13737 The remaining args are treated as settings for the skipping facilities of
13738 the scanner. The following items can be given here:
13740 archive skip trees with the archive tag.
13741 comment skip trees with the COMMENT keyword
13742 function or Emacs Lisp form:
13743 will be used as value for `org-agenda-skip-function', so whenever
13744 the function returns t, FUNC will not be called for that
13745 entry and search will continue from the point where the
13746 function leaves it.
13748 If your function needs to retrieve the tags including inherited tags
13749 at the *current* entry, you can use the value of the variable
13750 `org-scanner-tags' which will be much faster than getting the value
13751 with `org-get-tags-at'. If your function gets properties with
13752 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13753 to t around the call to `org-entry-properties' to get the same speedup.
13754 Note that if your function moves around to retrieve tags and properties at
13755 a *different* entry, you cannot use these techniques."
13756 (unless (and (eq scope 'region) (not (org-region-active-p)))
13757 (let* ((org-agenda-archives-mode nil) ; just to make sure
13758 (org-agenda-skip-archived-trees (memq 'archive skip))
13759 (org-agenda-skip-comment-trees (memq 'comment skip))
13760 (org-agenda-skip-function
13761 (car (org-delete-all '(comment archive) skip)))
13762 (org-tags-match-list-sublevels t)
13763 matcher file res
13764 org-todo-keywords-for-agenda
13765 org-done-keywords-for-agenda
13766 org-todo-keyword-alist-for-agenda
13767 org-drawers-for-agenda
13768 org-tag-alist-for-agenda)
13770 (cond
13771 ((eq match t) (setq matcher t))
13772 ((eq match nil) (setq matcher t))
13773 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13775 (save-excursion
13776 (save-restriction
13777 (cond ((eq scope 'tree)
13778 (org-back-to-heading t)
13779 (org-narrow-to-subtree)
13780 (setq scope nil))
13781 ((and (eq scope 'region) (org-region-active-p))
13782 (narrow-to-region (region-beginning)
13783 (save-excursion
13784 (goto-char (region-end))
13785 (unless (and (bolp) (org-at-heading-p))
13786 (outline-next-heading))
13787 (point)))
13788 (setq scope nil)))
13790 (if (not scope)
13791 (progn
13792 (org-prepare-agenda-buffers
13793 (list (buffer-file-name (current-buffer))))
13794 (setq res (org-scan-tags func matcher)))
13795 ;; Get the right scope
13796 (cond
13797 ((and scope (listp scope) (symbolp (car scope)))
13798 (setq scope (eval scope)))
13799 ((eq scope 'agenda)
13800 (setq scope (org-agenda-files t)))
13801 ((eq scope 'agenda-with-archives)
13802 (setq scope (org-agenda-files t))
13803 (setq scope (org-add-archive-files scope)))
13804 ((eq scope 'file)
13805 (setq scope (list (buffer-file-name))))
13806 ((eq scope 'file-with-archives)
13807 (setq scope (org-add-archive-files (list (buffer-file-name))))))
13808 (org-prepare-agenda-buffers scope)
13809 (while (setq file (pop scope))
13810 (with-current-buffer (org-find-base-buffer-visiting file)
13811 (save-excursion
13812 (save-restriction
13813 (widen)
13814 (goto-char (point-min))
13815 (setq res (append res (org-scan-tags func matcher))))))))))
13816 res)))
13818 ;;;; Properties
13820 ;;; Setting and retrieving properties
13822 (defconst org-special-properties
13823 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
13824 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM")
13825 "The special properties valid in Org-mode.
13827 These are properties that are not defined in the property drawer,
13828 but in some other way.")
13830 (defconst org-default-properties
13831 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
13832 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
13833 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
13834 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
13835 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
13836 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
13837 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
13838 "Some properties that are used by Org-mode for various purposes.
13839 Being in this list makes sure that they are offered for completion.")
13841 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
13842 "Regular expression matching the first line of a property drawer.")
13844 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
13845 "Regular expression matching the last line of a property drawer.")
13847 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
13848 "Regular expression matching the first line of a property drawer.")
13850 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
13851 "Regular expression matching the first line of a property drawer.")
13853 (defconst org-property-drawer-re
13854 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
13855 org-property-end-re "\\)\n?")
13856 "Matches an entire property drawer.")
13858 (defconst org-clock-drawer-re
13859 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
13860 org-property-end-re "\\)\n?")
13861 "Matches an entire clock drawer.")
13863 (defsubst org-re-property (property)
13864 "Return a regexp matching PROPERTY.
13865 Match group 1 will be set to the value "
13866 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
13868 (defun org-property-action ()
13869 "Do an action on properties."
13870 (interactive)
13871 (let (c)
13872 (org-at-property-p)
13873 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
13874 (setq c (read-char-exclusive))
13875 (cond
13876 ((equal c ?s)
13877 (call-interactively 'org-set-property))
13878 ((equal c ?d)
13879 (call-interactively 'org-delete-property))
13880 ((equal c ?D)
13881 (call-interactively 'org-delete-property-globally))
13882 ((equal c ?c)
13883 (call-interactively 'org-compute-property-at-point))
13884 (t (error "No such property action %c" c)))))
13886 (defun org-set-effort (&optional value)
13887 "Set the effort property of the current entry.
13888 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
13889 allowed value."
13890 (interactive "P")
13891 (if (equal value 0) (setq value 10))
13892 (let* ((completion-ignore-case t)
13893 (prop org-effort-property)
13894 (cur (org-entry-get nil prop))
13895 (allowed (org-property-get-allowed-values nil prop 'table))
13896 (existing (mapcar 'list (org-property-values prop)))
13898 (val (cond
13899 ((stringp value) value)
13900 ((and allowed (integerp value))
13901 (or (car (nth (1- value) allowed))
13902 (car (org-last allowed))))
13903 (allowed
13904 (message "Select 1-9,0, [RET%s]: %s"
13905 (if cur (concat "=" cur) "")
13906 (mapconcat 'car allowed " "))
13907 (setq rpl (read-char-exclusive))
13908 (if (equal rpl ?\r)
13910 (setq rpl (- rpl ?0))
13911 (if (equal rpl 0) (setq rpl 10))
13912 (if (and (> rpl 0) (<= rpl (length allowed)))
13913 (car (nth (1- rpl) allowed))
13914 (org-completing-read "Effort: " allowed nil))))
13916 (let (org-completion-use-ido org-completion-use-iswitchb)
13917 (org-completing-read
13918 (concat "Effort " (if (and cur (string-match "\\S-" cur))
13919 (concat "[" cur "]") "")
13920 ": ")
13921 existing nil nil "" nil cur))))))
13922 (unless (equal (org-entry-get nil prop) val)
13923 (org-entry-put nil prop val))
13924 (message "%s is now %s" prop val)))
13926 (defun org-at-property-p ()
13927 "Is cursor inside a property drawer?"
13928 (save-excursion
13929 (beginning-of-line 1)
13930 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
13931 (save-match-data ;; Used by calling procedures
13932 (let ((p (point))
13933 (range (unless (org-before-first-heading-p)
13934 (org-get-property-block))))
13935 (and range (<= (car range) p) (< p (cdr range))))))))
13937 (defun org-get-property-block (&optional beg end force)
13938 "Return the (beg . end) range of the body of the property drawer.
13939 BEG and END can be beginning and end of subtree, if not given
13940 they will be found.
13941 If the drawer does not exist and FORCE is non-nil, create the drawer."
13942 (catch 'exit
13943 (save-excursion
13944 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
13945 (end (or end (progn (outline-next-heading) (point)))))
13946 (goto-char beg)
13947 (if (re-search-forward org-property-start-re end t)
13948 (setq beg (1+ (match-end 0)))
13949 (if force
13950 (save-excursion
13951 (org-insert-property-drawer)
13952 (setq end (progn (outline-next-heading) (point))))
13953 (throw 'exit nil))
13954 (goto-char beg)
13955 (if (re-search-forward org-property-start-re end t)
13956 (setq beg (1+ (match-end 0)))))
13957 (if (re-search-forward org-property-end-re end t)
13958 (setq end (match-beginning 0))
13959 (or force (throw 'exit nil))
13960 (goto-char beg)
13961 (setq end beg)
13962 (org-indent-line-function)
13963 (insert ":END:\n"))
13964 (cons beg end)))))
13966 (defun org-entry-properties (&optional pom which specific)
13967 "Get all properties of the entry at point-or-marker POM.
13968 This includes the TODO keyword, the tags, time strings for deadline,
13969 scheduled, and clocking, and any additional properties defined in the
13970 entry. The return value is an alist, keys may occur multiple times
13971 if the property key was used several times.
13972 POM may also be nil, in which case the current entry is used.
13973 If WHICH is nil or `all', get all properties. If WHICH is
13974 `special' or `standard', only get that subclass. If WHICH
13975 is a string only get exactly this property. SPECIFIC can be a string, the
13976 specific property we are interested in. Specifying it can speed
13977 things up because then unnecessary parsing is avoided."
13978 (setq which (or which 'all))
13979 (org-with-point-at pom
13980 (let ((clockstr (substring org-clock-string 0 -1))
13981 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
13982 (case-fold-search nil)
13983 beg end range props sum-props key key1 value string clocksum)
13984 (save-excursion
13985 (when (condition-case nil
13986 (and (eq major-mode 'org-mode) (org-back-to-heading t))
13987 (error nil))
13988 (setq beg (point))
13989 (setq sum-props (get-text-property (point) 'org-summaries))
13990 (setq clocksum (get-text-property (point) :org-clock-minutes))
13991 (outline-next-heading)
13992 (setq end (point))
13993 (when (memq which '(all special))
13994 ;; Get the special properties, like TODO and tags
13995 (goto-char beg)
13996 (when (and (or (not specific) (string= specific "TODO"))
13997 (looking-at org-todo-line-regexp) (match-end 2))
13998 (push (cons "TODO" (org-match-string-no-properties 2)) props))
13999 (when (and (or (not specific) (string= specific "PRIORITY"))
14000 (looking-at org-priority-regexp))
14001 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14002 (when (or (not specific) (string= specific "FILE"))
14003 (push (cons "FILE" buffer-file-name) props))
14004 (when (and (or (not specific) (string= specific "TAGS"))
14005 (setq value (org-get-tags-string))
14006 (string-match "\\S-" value))
14007 (push (cons "TAGS" value) props))
14008 (when (and (or (not specific) (string= specific "ALLTAGS"))
14009 (setq value (org-get-tags-at)))
14010 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14011 ":"))
14012 props))
14013 (when (or (not specific) (string= specific "BLOCKED"))
14014 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14015 (when (or (not specific)
14016 (member specific
14017 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14018 "TIMESTAMP" "TIMESTAMP_IA")))
14019 (catch 'match
14020 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14021 (setq key (if (match-end 1)
14022 (substring (org-match-string-no-properties 1)
14023 0 -1))
14024 string (if (equal key clockstr)
14025 (org-no-properties
14026 (org-trim
14027 (buffer-substring
14028 (match-beginning 3) (goto-char
14029 (point-at-eol)))))
14030 (substring (org-match-string-no-properties 3)
14031 1 -1)))
14032 ;; Get the correct property name from the key. This is
14033 ;; necessary if the user has configured time keywords.
14034 (setq key1 (concat key ":"))
14035 (cond
14036 ((not key)
14037 (setq key
14038 (if (= (char-after (match-beginning 3)) ?\[)
14039 "TIMESTAMP_IA" "TIMESTAMP")))
14040 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14041 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14042 ((equal key1 org-closed-string) (setq key "CLOSED"))
14043 ((equal key1 org-clock-string) (setq key "CLOCK")))
14044 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14045 (progn
14046 (push (cons key string) props)
14047 ;; no need to search further if match is found
14048 (throw 'match t))
14049 (when (or (equal key "CLOCK") (not (assoc key props)))
14050 (push (cons key string) props))))))
14053 (when (memq which '(all standard))
14054 ;; Get the standard properties, like :PROP: ...
14055 (setq range (org-get-property-block beg end))
14056 (when range
14057 (goto-char (car range))
14058 (while (re-search-forward
14059 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14060 (cdr range) t)
14061 (setq key (org-match-string-no-properties 1)
14062 value (org-trim (or (org-match-string-no-properties 2) "")))
14063 (unless (member key excluded)
14064 (push (cons key (or value "")) props)))))
14065 (if clocksum
14066 (push (cons "CLOCKSUM"
14067 (org-columns-number-to-string (/ (float clocksum) 60.)
14068 'add_times))
14069 props))
14070 (unless (assoc "CATEGORY" props)
14071 (push (cons "CATEGORY" (org-get-category)) props))
14072 (append sum-props (nreverse props)))))))
14074 (defun org-entry-get (pom property &optional inherit literal-nil)
14075 "Get value of PROPERTY for entry at point-or-marker POM.
14076 If INHERIT is non-nil and the entry does not have the property,
14077 then also check higher levels of the hierarchy.
14078 If INHERIT is the symbol `selective', use inheritance only if the setting
14079 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14080 If the property is present but empty, the return value is the empty string.
14081 If the property is not present at all, nil is returned.
14083 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14084 do not interpret it as the list atom nil. This is used for inheritance
14085 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14086 (org-with-point-at pom
14087 (if (and inherit (if (eq inherit 'selective)
14088 (org-property-inherit-p property)
14090 (org-entry-get-with-inheritance property literal-nil)
14091 (if (member property org-special-properties)
14092 ;; We need a special property. Use `org-entry-properties' to
14093 ;; retrieve it, but specify the wanted property
14094 (cdr (assoc property (org-entry-properties nil 'special property)))
14095 (let ((range (unless (org-before-first-heading-p)
14096 (org-get-property-block))))
14097 (when (and range (goto-char (car range)))
14098 ((lambda (val) (when val (if literal-nil val (org-not-nil val))))
14099 (cond
14100 ((re-search-forward
14101 (org-re-property property) (cdr range) t)
14102 (if (match-end 1) (org-match-string-no-properties 1) ""))
14103 ((re-search-forward
14104 (org-re-property (concat property "+")) (cdr range) t)
14105 (cdr (assoc
14106 property
14107 (org-update-property-plist
14108 (concat property "+")
14109 (if (match-end 1) (org-match-string-no-properties 1) "")
14110 (list (or (assoc property org-file-properties)
14111 (assoc property org-global-properties)
14112 (assoc property org-global-properties-fixed)
14113 ))))))))))))))
14115 (defun org-property-or-variable-value (var &optional inherit)
14116 "Check if there is a property fixing the value of VAR.
14117 If yes, return this value. If not, return the current value of the variable."
14118 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14119 (if (and prop (stringp prop) (string-match "\\S-" prop))
14120 (read prop)
14121 (symbol-value var))))
14123 (defun org-entry-delete (pom property)
14124 "Delete the property PROPERTY from entry at point-or-marker POM."
14125 (org-with-point-at pom
14126 (if (member property org-special-properties)
14127 nil ; cannot delete these properties.
14128 (let ((range (org-get-property-block)))
14129 (if (and range
14130 (goto-char (car range))
14131 (re-search-forward
14132 (org-re-property property)
14133 (cdr range) t))
14134 (progn
14135 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14137 nil)))))
14139 ;; Multi-values properties are properties that contain multiple values
14140 ;; These values are assumed to be single words, separated by whitespace.
14141 (defun org-entry-add-to-multivalued-property (pom property value)
14142 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14143 (let* ((old (org-entry-get pom property))
14144 (values (and old (org-split-string old "[ \t]"))))
14145 (setq value (org-entry-protect-space value))
14146 (unless (member value values)
14147 (setq values (cons value values))
14148 (org-entry-put pom property
14149 (mapconcat 'identity values " ")))))
14151 (defun org-entry-remove-from-multivalued-property (pom property value)
14152 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14153 (let* ((old (org-entry-get pom property))
14154 (values (and old (org-split-string old "[ \t]"))))
14155 (setq value (org-entry-protect-space value))
14156 (when (member value values)
14157 (setq values (delete value values))
14158 (org-entry-put pom property
14159 (mapconcat 'identity values " ")))))
14161 (defun org-entry-member-in-multivalued-property (pom property value)
14162 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14163 (let* ((old (org-entry-get pom property))
14164 (values (and old (org-split-string old "[ \t]"))))
14165 (setq value (org-entry-protect-space value))
14166 (member value values)))
14168 (defun org-entry-get-multivalued-property (pom property)
14169 "Return a list of values in a multivalued property."
14170 (let* ((value (org-entry-get pom property))
14171 (values (and value (org-split-string value "[ \t]"))))
14172 (mapcar 'org-entry-restore-space values)))
14174 (defun org-entry-put-multivalued-property (pom property &rest values)
14175 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14176 VALUES should be a list of strings. Spaces will be protected."
14177 (org-entry-put pom property
14178 (mapconcat 'org-entry-protect-space values " "))
14179 (let* ((value (org-entry-get pom property))
14180 (values (and value (org-split-string value "[ \t]"))))
14181 (mapcar 'org-entry-restore-space values)))
14183 (defun org-entry-protect-space (s)
14184 "Protect spaces and newline in string S."
14185 (while (string-match " " s)
14186 (setq s (replace-match "%20" t t s)))
14187 (while (string-match "\n" s)
14188 (setq s (replace-match "%0A" t t s)))
14191 (defun org-entry-restore-space (s)
14192 "Restore spaces and newline in string S."
14193 (while (string-match "%20" s)
14194 (setq s (replace-match " " t t s)))
14195 (while (string-match "%0A" s)
14196 (setq s (replace-match "\n" t t s)))
14199 (defvar org-entry-property-inherited-from (make-marker)
14200 "Marker pointing to the entry from where a property was inherited.
14201 Each call to `org-entry-get-with-inheritance' will set this marker to the
14202 location of the entry where the inheritance search matched. If there was
14203 no match, the marker will point nowhere.
14204 Note that also `org-entry-get' calls this function, if the INHERIT flag
14205 is set.")
14207 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14208 "Get entry property, and search higher levels if not present.
14209 The search will stop at the first ancestor which has the property defined.
14210 If the value found is \"nil\", return nil to show that the property
14211 should be considered as undefined (this is the meaning of nil here).
14212 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14213 (move-marker org-entry-property-inherited-from nil)
14214 (let (tmp)
14215 (unless (org-before-first-heading-p)
14216 (save-excursion
14217 (save-restriction
14218 (widen)
14219 (catch 'ex
14220 (while t
14221 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14222 (org-back-to-heading t)
14223 (move-marker org-entry-property-inherited-from (point))
14224 (throw 'ex tmp))
14225 (or (org-up-heading-safe) (throw 'ex nil)))))))
14226 (setq tmp (or tmp
14227 (cdr (assoc property org-file-properties))
14228 (cdr (assoc property org-global-properties))
14229 (cdr (assoc property org-global-properties-fixed))))
14230 (if literal-nil tmp (org-not-nil tmp))))
14232 (defvar org-property-changed-functions nil
14233 "Hook called when the value of a property has changed.
14234 Each hook function should accept two arguments, the name of the property
14235 and the new value.")
14237 (defun org-entry-put (pom property value)
14238 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14239 (org-with-point-at pom
14240 (org-back-to-heading t)
14241 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14242 range)
14243 (cond
14244 ((equal property "TODO")
14245 (when (and (stringp value) (string-match "\\S-" value)
14246 (not (member value org-todo-keywords-1)))
14247 (error "\"%s\" is not a valid TODO state" value))
14248 (if (or (not value)
14249 (not (string-match "\\S-" value)))
14250 (setq value 'none))
14251 (org-todo value)
14252 (org-set-tags nil 'align))
14253 ((equal property "PRIORITY")
14254 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14255 (string-to-char value) ?\ ))
14256 (org-set-tags nil 'align))
14257 ((equal property "SCHEDULED")
14258 (if (re-search-forward org-scheduled-time-regexp end t)
14259 (cond
14260 ((eq value 'earlier) (org-timestamp-change -1 'day))
14261 ((eq value 'later) (org-timestamp-change 1 'day))
14262 (t (call-interactively 'org-schedule)))
14263 (call-interactively 'org-schedule)))
14264 ((equal property "DEADLINE")
14265 (if (re-search-forward org-deadline-time-regexp end t)
14266 (cond
14267 ((eq value 'earlier) (org-timestamp-change -1 'day))
14268 ((eq value 'later) (org-timestamp-change 1 'day))
14269 (t (call-interactively 'org-deadline)))
14270 (call-interactively 'org-deadline)))
14271 ((member property org-special-properties)
14272 (error "The %s property can not yet be set with `org-entry-put'"
14273 property))
14274 (t ; a non-special property
14275 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14276 (setq range (org-get-property-block beg end 'force))
14277 (goto-char (car range))
14278 (if (re-search-forward
14279 (org-re-property property) (cdr range) t)
14280 (progn
14281 (delete-region (match-beginning 0) (match-end 0))
14282 (goto-char (match-beginning 0)))
14283 (goto-char (cdr range))
14284 (insert "\n")
14285 (backward-char 1)
14286 (org-indent-line-function))
14287 (insert ":" property ":")
14288 (and value (insert " " value))
14289 (org-indent-line-function)))))
14290 (run-hook-with-args 'org-property-changed-functions property value)))
14292 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14293 "Get all property keys in the current buffer.
14294 With INCLUDE-SPECIALS, also list the special properties that reflect things
14295 like tags and TODO state.
14296 With INCLUDE-DEFAULTS, also include properties that has special meaning
14297 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14298 and others.
14299 With INCLUDE-COLUMNS, also include property names given in COLUMN
14300 formats in the current buffer."
14301 (let (rtn range cfmt s p)
14302 (save-excursion
14303 (save-restriction
14304 (widen)
14305 (goto-char (point-min))
14306 (while (re-search-forward org-property-start-re nil t)
14307 (setq range (org-get-property-block))
14308 (goto-char (car range))
14309 (while (re-search-forward
14310 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14311 (cdr range) t)
14312 (add-to-list 'rtn (org-match-string-no-properties 1)))
14313 (outline-next-heading))))
14315 (when include-specials
14316 (setq rtn (append org-special-properties rtn)))
14318 (when include-defaults
14319 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14320 (add-to-list 'rtn org-effort-property))
14322 (when include-columns
14323 (save-excursion
14324 (save-restriction
14325 (widen)
14326 (goto-char (point-min))
14327 (while (re-search-forward
14328 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14329 nil t)
14330 (setq cfmt (match-string 2) s 0)
14331 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14332 cfmt s)
14333 (setq s (match-end 0)
14334 p (match-string 1 cfmt))
14335 (unless (or (equal p "ITEM")
14336 (member p org-special-properties))
14337 (add-to-list 'rtn (match-string 1 cfmt))))))))
14339 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14341 (defun org-property-values (key)
14342 "Return a list of all values of property KEY in the current buffer."
14343 (save-excursion
14344 (save-restriction
14345 (widen)
14346 (goto-char (point-min))
14347 (let ((re (org-re-property key))
14348 values)
14349 (while (re-search-forward re nil t)
14350 (add-to-list 'values (org-trim (match-string 1))))
14351 (delete "" values)))))
14353 (defun org-insert-property-drawer ()
14354 "Insert a property drawer into the current entry."
14355 (interactive)
14356 (org-back-to-heading t)
14357 (looking-at org-outline-regexp)
14358 (let ((indent (if org-adapt-indentation
14359 (- (match-end 0)(match-beginning 0))
14361 (beg (point))
14362 (re (concat "^[ \t]*" org-keyword-time-regexp))
14363 end hiddenp)
14364 (outline-next-heading)
14365 (setq end (point))
14366 (goto-char beg)
14367 (while (re-search-forward re end t))
14368 (setq hiddenp (outline-invisible-p))
14369 (end-of-line 1)
14370 (and (equal (char-after) ?\n) (forward-char 1))
14371 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14372 (if (member (match-string 1) '("CLOCK:" ":END:"))
14373 ;; just skip this line
14374 (beginning-of-line 2)
14375 ;; Drawer start, find the end
14376 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14377 (beginning-of-line 1)))
14378 (org-skip-over-state-notes)
14379 (skip-chars-backward " \t\n\r")
14380 (if (eq (char-before) ?*) (forward-char 1))
14381 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14382 (beginning-of-line 0)
14383 (org-indent-to-column indent)
14384 (beginning-of-line 2)
14385 (org-indent-to-column indent)
14386 (beginning-of-line 0)
14387 (if hiddenp
14388 (save-excursion
14389 (org-back-to-heading t)
14390 (hide-entry))
14391 (org-flag-drawer t))))
14393 (defvar org-property-set-functions-alist nil
14394 "Property set function alist.
14395 Each entry should have the following format:
14397 (PROPERTY . READ-FUNCTION)
14399 The read function will be called with the same argument as
14400 `org-completing-read'.")
14402 (defun org-set-property-function (property)
14403 "Get the function that should be used to set PROPERTY.
14404 This is computed according to `org-property-set-functions-alist'."
14405 (or (cdr (assoc property org-property-set-functions-alist))
14406 'org-completing-read))
14408 (defun org-read-property-value (property)
14409 "Read PROPERTY value from user."
14410 (let* ((completion-ignore-case t)
14411 (allowed (org-property-get-allowed-values nil property 'table))
14412 (cur (org-entry-get nil property))
14413 (prompt (concat property " value"
14414 (if (and cur (string-match "\\S-" cur))
14415 (concat " [" cur "]") "") ": "))
14416 (set-function (org-set-property-function property))
14417 (val (if allowed
14418 (funcall set-function prompt allowed nil
14419 (not (get-text-property 0 'org-unrestricted
14420 (caar allowed))))
14421 (let (org-completion-use-ido org-completion-use-iswitchb)
14422 (funcall set-function prompt
14423 (mapcar 'list (org-property-values property))
14424 nil nil "" nil cur)))))
14425 (if (equal val "")
14427 val)))
14429 (defvar org-last-set-property nil)
14430 (defun org-read-property-name ()
14431 "Read a property name."
14432 (let* ((completion-ignore-case t)
14433 (keys (org-buffer-property-keys nil t t))
14434 (default-prop (or (save-excursion
14435 (save-match-data
14436 (beginning-of-line)
14437 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14438 (null (string= (match-string 1) "END"))
14439 (match-string 1))))
14440 org-last-set-property))
14441 (property (org-icompleting-read
14442 (concat "Property"
14443 (if default-prop (concat " [" default-prop "]") "")
14444 ": ")
14445 (mapcar 'list keys)
14446 nil nil nil nil
14447 default-prop
14449 (if (member property keys)
14450 property
14451 (or (cdr (assoc (downcase property)
14452 (mapcar (lambda (x) (cons (downcase x) x))
14453 keys)))
14454 property))))
14456 (defun org-set-property (property value)
14457 "In the current entry, set PROPERTY to VALUE.
14458 When called interactively, this will prompt for a property name, offering
14459 completion on existing and default properties. And then it will prompt
14460 for a value, offering completion either on allowed values (via an inherited
14461 xxx_ALL property) or on existing values in other instances of this property
14462 in the current file."
14463 (interactive (list nil nil))
14464 (let* ((property (or property (org-read-property-name)))
14465 (value (or value (org-read-property-value property)))
14466 (fn (assoc property org-properties-postprocess-alist)))
14467 (setq org-last-set-property property)
14468 ;; Possibly postprocess the inserted value:
14469 (when fn (setq value (funcall (cadr fn) value)))
14470 (unless (equal (org-entry-get nil property) value)
14471 (org-entry-put nil property value))))
14473 (defun org-delete-property (property)
14474 "In the current entry, delete PROPERTY."
14475 (interactive
14476 (let* ((completion-ignore-case t)
14477 (prop (org-icompleting-read "Property: "
14478 (org-entry-properties nil 'standard))))
14479 (list prop)))
14480 (message "Property %s %s" property
14481 (if (org-entry-delete nil property)
14482 "deleted"
14483 "was not present in the entry")))
14485 (defun org-delete-property-globally (property)
14486 "Remove PROPERTY globally, from all entries."
14487 (interactive
14488 (let* ((completion-ignore-case t)
14489 (prop (org-icompleting-read
14490 "Globally remove property: "
14491 (mapcar 'list (org-buffer-property-keys)))))
14492 (list prop)))
14493 (save-excursion
14494 (save-restriction
14495 (widen)
14496 (goto-char (point-min))
14497 (let ((cnt 0))
14498 (while (re-search-forward
14499 (org-re-property property)
14500 nil t)
14501 (setq cnt (1+ cnt))
14502 (replace-match ""))
14503 (message "Property \"%s\" removed from %d entries" property cnt)))))
14505 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14507 (defun org-compute-property-at-point ()
14508 "Compute the property at point.
14509 This looks for an enclosing column format, extracts the operator and
14510 then applies it to the property in the column format's scope."
14511 (interactive)
14512 (unless (org-at-property-p)
14513 (error "Not at a property"))
14514 (let ((prop (org-match-string-no-properties 2)))
14515 (org-columns-get-format-and-top-level)
14516 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14517 (error "No operator defined for property %s" prop))
14518 (org-columns-compute prop)))
14520 (defvar org-property-allowed-value-functions nil
14521 "Hook for functions supplying allowed values for a specific property.
14522 The functions must take a single argument, the name of the property, and
14523 return a flat list of allowed values. If \":ETC\" is one of
14524 the values, this means that these values are intended as defaults for
14525 completion, but that other values should be allowed too.
14526 The functions must return nil if they are not responsible for this
14527 property.")
14529 (defun org-property-get-allowed-values (pom property &optional table)
14530 "Get allowed values for the property PROPERTY.
14531 When TABLE is non-nil, return an alist that can directly be used for
14532 completion."
14533 (let (vals)
14534 (cond
14535 ((equal property "TODO")
14536 (setq vals (org-with-point-at pom
14537 (append org-todo-keywords-1 '("")))))
14538 ((equal property "PRIORITY")
14539 (let ((n org-lowest-priority))
14540 (while (>= n org-highest-priority)
14541 (push (char-to-string n) vals)
14542 (setq n (1- n)))))
14543 ((member property org-special-properties))
14544 ((setq vals (run-hook-with-args-until-success
14545 'org-property-allowed-value-functions property)))
14547 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14548 (when (and vals (string-match "\\S-" vals))
14549 (setq vals (car (read-from-string (concat "(" vals ")"))))
14550 (setq vals (mapcar (lambda (x)
14551 (cond ((stringp x) x)
14552 ((numberp x) (number-to-string x))
14553 ((symbolp x) (symbol-name x))
14554 (t "???")))
14555 vals)))))
14556 (when (member ":ETC" vals)
14557 (setq vals (remove ":ETC" vals))
14558 (org-add-props (car vals) '(org-unrestricted t)))
14559 (if table (mapcar 'list vals) vals)))
14561 (defun org-property-previous-allowed-value (&optional previous)
14562 "Switch to the next allowed value for this property."
14563 (interactive)
14564 (org-property-next-allowed-value t))
14566 (defun org-property-next-allowed-value (&optional previous)
14567 "Switch to the next allowed value for this property."
14568 (interactive)
14569 (unless (org-at-property-p)
14570 (error "Not at a property"))
14571 (let* ((key (match-string 2))
14572 (value (match-string 3))
14573 (allowed (or (org-property-get-allowed-values (point) key)
14574 (and (member value '("[ ]" "[-]" "[X]"))
14575 '("[ ]" "[X]"))))
14576 nval)
14577 (unless allowed
14578 (error "Allowed values for this property have not been defined"))
14579 (if previous (setq allowed (reverse allowed)))
14580 (if (member value allowed)
14581 (setq nval (car (cdr (member value allowed)))))
14582 (setq nval (or nval (car allowed)))
14583 (if (equal nval value)
14584 (error "Only one allowed value for this property"))
14585 (org-at-property-p)
14586 (replace-match (concat " :" key ": " nval) t t)
14587 (org-indent-line-function)
14588 (beginning-of-line 1)
14589 (skip-chars-forward " \t")
14590 (run-hook-with-args 'org-property-changed-functions key nval)))
14592 (defun org-find-olp (path &optional this-buffer)
14593 "Return a marker pointing to the entry at outline path OLP.
14594 If anything goes wrong, throw an error.
14595 You can wrap this call to catch the error like this:
14597 (condition-case msg
14598 (org-mobile-locate-entry (match-string 4))
14599 (error (nth 1 msg)))
14601 The return value will then be either a string with the error message,
14602 or a marker if everything is OK.
14604 If THIS-BUFFER is set, the outline path does not contain a file,
14605 only headings."
14606 (let* ((file (if this-buffer buffer-file-name (pop path)))
14607 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14608 (level 1)
14609 (lmin 1)
14610 (lmax 1)
14611 limit re end found pos heading cnt flevel)
14612 (unless buffer (error "File not found :%s" file))
14613 (with-current-buffer buffer
14614 (save-excursion
14615 (save-restriction
14616 (widen)
14617 (setq limit (point-max))
14618 (goto-char (point-min))
14619 (while (setq heading (pop path))
14620 (setq re (format org-complex-heading-regexp-format
14621 (regexp-quote heading)))
14622 (setq cnt 0 pos (point))
14623 (while (re-search-forward re end t)
14624 (setq level (- (match-end 1) (match-beginning 1)))
14625 (if (and (>= level lmin) (<= level lmax))
14626 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
14627 (when (= cnt 0) (error "Heading not found on level %d: %s"
14628 lmax heading))
14629 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14630 lmax heading))
14631 (goto-char found)
14632 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
14633 (setq end (save-excursion (org-end-of-subtree t t))))
14634 (when (org-on-heading-p)
14635 (move-marker (make-marker) (point))))))))
14637 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14638 "Find node HEADING in BUFFER.
14639 Return a marker to the heading if it was found, or nil if not.
14640 If POS-ONLY is set, return just the position instead of a marker.
14642 The heading text must match exact, but it may have a TODO keyword,
14643 a priority cookie and tags in the standard locations."
14644 (with-current-buffer (or buffer (current-buffer))
14645 (save-excursion
14646 (save-restriction
14647 (widen)
14648 (goto-char (point-min))
14649 (let (case-fold-search)
14650 (if (re-search-forward
14651 (format org-complex-heading-regexp-format
14652 (regexp-quote heading)) nil t)
14653 (if pos-only
14654 (match-beginning 0)
14655 (move-marker (make-marker) (match-beginning 0)))))))))
14657 (defun org-find-exact-heading-in-directory (heading &optional dir)
14658 "Find Org node headline HEADING in all .org files in directory DIR.
14659 When the target headline is found, return a marker to this location."
14660 (let ((files (directory-files (or dir default-directory)
14661 nil "\\`[^.#].*\\.org\\'"))
14662 file visiting m buffer)
14663 (catch 'found
14664 (while (setq file (pop files))
14665 (message "trying %s" file)
14666 (setq visiting (org-find-base-buffer-visiting file))
14667 (setq buffer (or visiting (find-file-noselect file)))
14668 (setq m (org-find-exact-headline-in-buffer
14669 heading buffer))
14670 (when (and (not m) (not visiting)) (kill-buffer buffer))
14671 (and m (throw 'found m))))))
14673 (defun org-find-entry-with-id (ident)
14674 "Locate the entry that contains the ID property with exact value IDENT.
14675 IDENT can be a string, a symbol or a number, this function will search for
14676 the string representation of it.
14677 Return the position where this entry starts, or nil if there is no such entry."
14678 (interactive "sID: ")
14679 (let ((id (cond
14680 ((stringp ident) ident)
14681 ((symbol-name ident) (symbol-name ident))
14682 ((numberp ident) (number-to-string ident))
14683 (t (error "IDENT %s must be a string, symbol or number" ident))))
14684 (case-fold-search nil))
14685 (save-excursion
14686 (save-restriction
14687 (widen)
14688 (goto-char (point-min))
14689 (when (re-search-forward
14690 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
14691 nil t)
14692 (org-back-to-heading t)
14693 (point))))))
14695 ;;;; Timestamps
14697 (defvar org-last-changed-timestamp nil)
14698 (defvar org-last-inserted-timestamp nil
14699 "The last time stamp inserted with `org-insert-time-stamp'.")
14700 (defvar org-time-was-given) ; dynamically scoped parameter
14701 (defvar org-end-time-was-given) ; dynamically scoped parameter
14702 (defvar org-ts-what) ; dynamically scoped parameter
14704 (defun org-time-stamp (arg &optional inactive)
14705 "Prompt for a date/time and insert a time stamp.
14706 If the user specifies a time like HH:MM, or if this command is called
14707 with a prefix argument, the time stamp will contain date and time.
14708 Otherwise, only the date will be included. All parts of a date not
14709 specified by the user will be filled in from the current date/time.
14710 So if you press just return without typing anything, the time stamp
14711 will represent the current date/time. If there is already a timestamp
14712 at the cursor, it will be modified."
14713 (interactive "P")
14714 (let* ((ts nil)
14715 (default-time
14716 ;; Default time is either today, or, when entering a range,
14717 ;; the range start.
14718 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
14719 (save-excursion
14720 (re-search-backward
14721 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
14722 (- (point) 20) t)))
14723 (apply 'encode-time (org-parse-time-string (match-string 1)))
14724 (current-time)))
14725 (default-input (and ts (org-get-compact-tod ts)))
14726 (repeater (save-excursion
14727 (save-match-data
14728 (beginning-of-line)
14729 (when (re-search-forward
14730 "\\([.+-]+[0-9]+[dwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
14731 (save-excursion (progn (end-of-line) (point))) t)
14732 (match-string 0)))))
14733 org-time-was-given org-end-time-was-given time)
14734 (cond
14735 ((and (org-at-timestamp-p t)
14736 (memq last-command '(org-time-stamp org-time-stamp-inactive))
14737 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
14738 (insert "--")
14739 (setq time (let ((this-command this-command))
14740 (org-read-date arg 'totime nil nil
14741 default-time default-input)))
14742 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
14743 ((org-at-timestamp-p t)
14744 (setq time (let ((this-command this-command))
14745 (org-read-date arg 'totime nil nil default-time default-input)))
14746 (when (org-at-timestamp-p t) ; just to get the match data
14747 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
14748 (replace-match "")
14749 (setq org-last-changed-timestamp
14750 (org-insert-time-stamp
14751 time (or org-time-was-given arg)
14752 inactive nil nil (list org-end-time-was-given)))
14753 (when repeater (goto-char (1- (point))) (insert " " repeater)
14754 (setq org-last-changed-timestamp
14755 (concat (substring org-last-inserted-timestamp 0 -1)
14756 " " repeater ">"))))
14757 (message "Timestamp updated"))
14759 (setq time (let ((this-command this-command))
14760 (org-read-date arg 'totime nil nil default-time default-input)))
14761 (org-insert-time-stamp time (or org-time-was-given arg) inactive
14762 nil nil (list org-end-time-was-given))))))
14764 ;; FIXME: can we use this for something else, like computing time differences?
14765 (defun org-get-compact-tod (s)
14766 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
14767 (let* ((t1 (match-string 1 s))
14768 (h1 (string-to-number (match-string 2 s)))
14769 (m1 (string-to-number (match-string 3 s)))
14770 (t2 (and (match-end 4) (match-string 5 s)))
14771 (h2 (and t2 (string-to-number (match-string 6 s))))
14772 (m2 (and t2 (string-to-number (match-string 7 s))))
14773 dh dm)
14774 (if (not t2)
14776 (setq dh (- h2 h1) dm (- m2 m1))
14777 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
14778 (concat t1 "+" (number-to-string dh)
14779 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
14781 (defun org-time-stamp-inactive (&optional arg)
14782 "Insert an inactive time stamp.
14783 An inactive time stamp is enclosed in square brackets instead of angle
14784 brackets. It is inactive in the sense that it does not trigger agenda entries,
14785 does not link to the calendar and cannot be changed with the S-cursor keys.
14786 So these are more for recording a certain time/date."
14787 (interactive "P")
14788 (org-time-stamp arg 'inactive))
14790 (defvar org-date-ovl (make-overlay 1 1))
14791 (overlay-put org-date-ovl 'face 'org-warning)
14792 (org-detach-overlay org-date-ovl)
14794 (defvar org-ans1) ; dynamically scoped parameter
14795 (defvar org-ans2) ; dynamically scoped parameter
14797 (defvar org-plain-time-of-day-regexp) ; defined below
14799 (defvar org-overriding-default-time nil) ; dynamically scoped
14800 (defvar org-read-date-overlay nil)
14801 (defvar org-dcst nil) ; dynamically scoped
14802 (defvar org-read-date-history nil)
14803 (defvar org-read-date-final-answer nil)
14804 (defvar org-read-date-analyze-futurep nil)
14805 (defvar org-read-date-analyze-forced-year nil)
14807 (defun org-read-date (&optional with-time to-time from-string prompt
14808 default-time default-input)
14809 "Read a date, possibly a time, and make things smooth for the user.
14810 The prompt will suggest to enter an ISO date, but you can also enter anything
14811 which will at least partially be understood by `parse-time-string'.
14812 Unrecognized parts of the date will default to the current day, month, year,
14813 hour and minute. If this command is called to replace a timestamp at point,
14814 or to enter the second timestamp of a range, the default time is taken
14815 from the existing stamp. Furthermore, the command prefers the future,
14816 so if you are giving a date where the year is not given, and the day-month
14817 combination is already past in the current year, it will assume you
14818 mean next year. For details, see the manual. A few examples:
14820 3-2-5 --> 2003-02-05
14821 feb 15 --> currentyear-02-15
14822 2/15 --> currentyear-02-15
14823 sep 12 9 --> 2009-09-12
14824 12:45 --> today 12:45
14825 22 sept 0:34 --> currentyear-09-22 0:34
14826 12 --> currentyear-currentmonth-12
14827 Fri --> nearest Friday (today or later)
14828 etc.
14830 Furthermore you can specify a relative date by giving, as the *first* thing
14831 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
14832 change in days weeks, months, years.
14833 With a single plus or minus, the date is relative to today. With a double
14834 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
14835 +4d --> four days from today
14836 +4 --> same as above
14837 +2w --> two weeks from today
14838 ++5 --> five days from default date
14840 The function understands only English month and weekday abbreviations,
14841 but this can be configured with the variables `parse-time-months' and
14842 `parse-time-weekdays'.
14844 While prompting, a calendar is popped up - you can also select the
14845 date with the mouse (button 1). The calendar shows a period of three
14846 months. To scroll it to other months, use the keys `>' and `<'.
14847 If you don't like the calendar, turn it off with
14848 \(setq org-read-date-popup-calendar nil)
14850 With optional argument TO-TIME, the date will immediately be converted
14851 to an internal time.
14852 With an optional argument WITH-TIME, the prompt will suggest to also
14853 insert a time. Note that when WITH-TIME is not set, you can still
14854 enter a time, and this function will inform the calling routine about
14855 this change. The calling routine may then choose to change the format
14856 used to insert the time stamp into the buffer to include the time.
14857 With optional argument FROM-STRING, read from this string instead from
14858 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
14859 the time/date that is used for everything that is not specified by the
14860 user."
14861 (require 'parse-time)
14862 (let* ((org-time-stamp-rounding-minutes
14863 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
14864 (org-dcst org-display-custom-times)
14865 (ct (org-current-time))
14866 (def (or org-overriding-default-time default-time ct))
14867 (defdecode (decode-time def))
14868 (dummy (progn
14869 (when (< (nth 2 defdecode) org-extend-today-until)
14870 (setcar (nthcdr 2 defdecode) -1)
14871 (setcar (nthcdr 1 defdecode) 59)
14872 (setq def (apply 'encode-time defdecode)
14873 defdecode (decode-time def)))))
14874 (calendar-frame-setup nil)
14875 (calendar-setup nil)
14876 (calendar-move-hook nil)
14877 (calendar-view-diary-initially-flag nil)
14878 (calendar-view-holidays-initially-flag nil)
14879 (timestr (format-time-string
14880 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
14881 (prompt (concat (if prompt (concat prompt " ") "")
14882 (format "Date+time [%s]: " timestr)))
14883 ans (org-ans0 "") org-ans1 org-ans2 final)
14885 (cond
14886 (from-string (setq ans from-string))
14887 (org-read-date-popup-calendar
14888 (save-excursion
14889 (save-window-excursion
14890 (calendar)
14891 (unwind-protect
14892 (progn
14893 (calendar-forward-day (- (time-to-days def)
14894 (calendar-absolute-from-gregorian
14895 (calendar-current-date))))
14896 (org-eval-in-calendar nil t)
14897 (let* ((old-map (current-local-map))
14898 (map (copy-keymap calendar-mode-map))
14899 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
14900 (org-defkey map (kbd "RET") 'org-calendar-select)
14901 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
14902 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
14903 (org-defkey minibuffer-local-map [(meta shift left)]
14904 (lambda () (interactive)
14905 (org-eval-in-calendar '(calendar-backward-month 1))))
14906 (org-defkey minibuffer-local-map [(meta shift right)]
14907 (lambda () (interactive)
14908 (org-eval-in-calendar '(calendar-forward-month 1))))
14909 (org-defkey minibuffer-local-map [(meta shift up)]
14910 (lambda () (interactive)
14911 (org-eval-in-calendar '(calendar-backward-year 1))))
14912 (org-defkey minibuffer-local-map [(meta shift down)]
14913 (lambda () (interactive)
14914 (org-eval-in-calendar '(calendar-forward-year 1))))
14915 (org-defkey minibuffer-local-map [?\e (shift left)]
14916 (lambda () (interactive)
14917 (org-eval-in-calendar '(calendar-backward-month 1))))
14918 (org-defkey minibuffer-local-map [?\e (shift right)]
14919 (lambda () (interactive)
14920 (org-eval-in-calendar '(calendar-forward-month 1))))
14921 (org-defkey minibuffer-local-map [?\e (shift up)]
14922 (lambda () (interactive)
14923 (org-eval-in-calendar '(calendar-backward-year 1))))
14924 (org-defkey minibuffer-local-map [?\e (shift down)]
14925 (lambda () (interactive)
14926 (org-eval-in-calendar '(calendar-forward-year 1))))
14927 (org-defkey minibuffer-local-map [(shift up)]
14928 (lambda () (interactive)
14929 (org-eval-in-calendar '(calendar-backward-week 1))))
14930 (org-defkey minibuffer-local-map [(shift down)]
14931 (lambda () (interactive)
14932 (org-eval-in-calendar '(calendar-forward-week 1))))
14933 (org-defkey minibuffer-local-map [(shift left)]
14934 (lambda () (interactive)
14935 (org-eval-in-calendar '(calendar-backward-day 1))))
14936 (org-defkey minibuffer-local-map [(shift right)]
14937 (lambda () (interactive)
14938 (org-eval-in-calendar '(calendar-forward-day 1))))
14939 (org-defkey minibuffer-local-map ">"
14940 (lambda () (interactive)
14941 (org-eval-in-calendar '(scroll-calendar-left 1))))
14942 (org-defkey minibuffer-local-map "<"
14943 (lambda () (interactive)
14944 (org-eval-in-calendar '(scroll-calendar-right 1))))
14945 (org-defkey minibuffer-local-map "\C-v"
14946 (lambda () (interactive)
14947 (org-eval-in-calendar
14948 '(calendar-scroll-left-three-months 1))))
14949 (org-defkey minibuffer-local-map "\M-v"
14950 (lambda () (interactive)
14951 (org-eval-in-calendar
14952 '(calendar-scroll-right-three-months 1))))
14953 (run-hooks 'org-read-date-minibuffer-setup-hook)
14954 (unwind-protect
14955 (progn
14956 (use-local-map map)
14957 (add-hook 'post-command-hook 'org-read-date-display)
14958 (setq org-ans0 (read-string prompt default-input
14959 'org-read-date-history nil))
14960 ;; org-ans0: from prompt
14961 ;; org-ans1: from mouse click
14962 ;; org-ans2: from calendar motion
14963 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
14964 (remove-hook 'post-command-hook 'org-read-date-display)
14965 (use-local-map old-map)
14966 (when org-read-date-overlay
14967 (delete-overlay org-read-date-overlay)
14968 (setq org-read-date-overlay nil)))))
14969 (bury-buffer "*Calendar*")))))
14971 (t ; Naked prompt only
14972 (unwind-protect
14973 (setq ans (read-string prompt default-input
14974 'org-read-date-history timestr))
14975 (when org-read-date-overlay
14976 (delete-overlay org-read-date-overlay)
14977 (setq org-read-date-overlay nil)))))
14979 (setq final (org-read-date-analyze ans def defdecode))
14981 (when org-read-date-analyze-forced-year
14982 (message "Year was forced into %s"
14983 (if org-read-date-force-compatible-dates
14984 "compatible range (1970-2037)"
14985 "range representable on this machine"))
14986 (ding))
14988 ;; One round trip to get rid of 34th of August and stuff like that....
14989 (setq final (decode-time (apply 'encode-time final)))
14991 (setq org-read-date-final-answer ans)
14993 (if to-time
14994 (apply 'encode-time final)
14995 (if (and (boundp 'org-time-was-given) org-time-was-given)
14996 (format "%04d-%02d-%02d %02d:%02d"
14997 (nth 5 final) (nth 4 final) (nth 3 final)
14998 (nth 2 final) (nth 1 final))
14999 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15001 (defvar def)
15002 (defvar defdecode)
15003 (defvar with-time)
15004 (defun org-read-date-display ()
15005 "Display the current date prompt interpretation in the minibuffer."
15006 (when org-read-date-display-live
15007 (when org-read-date-overlay
15008 (delete-overlay org-read-date-overlay))
15009 (let ((p (point)))
15010 (end-of-line 1)
15011 (while (not (equal (buffer-substring
15012 (max (point-min) (- (point) 4)) (point))
15013 " "))
15014 (insert " "))
15015 (goto-char p))
15016 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15017 " " (or org-ans1 org-ans2)))
15018 (org-end-time-was-given nil)
15019 (f (org-read-date-analyze ans def defdecode))
15020 (fmts (if org-dcst
15021 org-time-stamp-custom-formats
15022 org-time-stamp-formats))
15023 (fmt (if (or with-time
15024 (and (boundp 'org-time-was-given) org-time-was-given))
15025 (cdr fmts)
15026 (car fmts)))
15027 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
15028 (when (and org-end-time-was-given
15029 (string-match org-plain-time-of-day-regexp txt))
15030 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15031 org-end-time-was-given
15032 (substring txt (match-end 0)))))
15033 (when org-read-date-analyze-futurep
15034 (setq txt (concat txt " (=>F)")))
15035 (setq org-read-date-overlay
15036 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15037 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
15039 (defun org-read-date-analyze (ans def defdecode)
15040 "Analyze the combined answer of the date prompt."
15041 ;; FIXME: cleanup and comment
15042 (let ((nowdecode (decode-time (current-time)))
15043 delta deltan deltaw deltadef year month day
15044 hour minute second wday pm h2 m2 tl wday1
15045 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15046 (setq org-read-date-analyze-futurep nil
15047 org-read-date-analyze-forced-year nil)
15048 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15049 (setq ans "+0"))
15051 (when (setq delta (org-read-date-get-relative ans (current-time) def))
15052 (setq ans (replace-match "" t t ans)
15053 deltan (car delta)
15054 deltaw (nth 1 delta)
15055 deltadef (nth 2 delta)))
15057 ;; Check if there is an iso week date in there
15058 ;; If yes, store the info and postpone interpreting it until the rest
15059 ;; of the parsing is done
15060 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15061 (setq iso-year (if (match-end 1)
15062 (org-small-year-to-year
15063 (string-to-number (match-string 1 ans))))
15064 iso-weekday (if (match-end 3)
15065 (string-to-number (match-string 3 ans)))
15066 iso-week (string-to-number (match-string 2 ans)))
15067 (setq ans (replace-match "" t t ans)))
15069 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15070 (when (string-match
15071 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15072 (setq year (if (match-end 2)
15073 (string-to-number (match-string 2 ans))
15074 (progn (setq kill-year t)
15075 (string-to-number (format-time-string "%Y"))))
15076 month (string-to-number (match-string 3 ans))
15077 day (string-to-number (match-string 4 ans)))
15078 (if (< year 100) (setq year (+ 2000 year)))
15079 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15080 t nil ans)))
15082 ;; Help matching dottet european dates
15083 (when (string-match
15084 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15085 (setq year (if (match-end 3)
15086 (string-to-number (match-string 3 ans))
15087 (progn (setq kill-year t)
15088 (string-to-number (format-time-string "%Y"))))
15089 day (string-to-number (match-string 1 ans))
15090 month (string-to-number (match-string 2 ans))
15091 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15092 t nil ans)))
15094 ;; Help matching american dates, like 5/30 or 5/30/7
15095 (when (string-match
15096 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15097 (setq year (if (match-end 4)
15098 (string-to-number (match-string 4 ans))
15099 (progn (setq kill-year t)
15100 (string-to-number (format-time-string "%Y"))))
15101 month (string-to-number (match-string 1 ans))
15102 day (string-to-number (match-string 2 ans)))
15103 (if (< year 100) (setq year (+ 2000 year)))
15104 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15105 t nil ans)))
15106 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15107 ;; If there is a time with am/pm, and *no* time without it, we convert
15108 ;; so that matching will be successful.
15109 (loop for i from 1 to 2 do ; twice, for end time as well
15110 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15111 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15112 (setq hour (string-to-number (match-string 1 ans))
15113 minute (if (match-end 3)
15114 (string-to-number (match-string 3 ans))
15116 pm (equal ?p
15117 (string-to-char (downcase (match-string 4 ans)))))
15118 (if (and (= hour 12) (not pm))
15119 (setq hour 0)
15120 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15121 (setq ans (replace-match (format "%02d:%02d" hour minute)
15122 t t ans))))
15124 ;; Check if a time range is given as a duration
15125 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15126 (setq hour (string-to-number (match-string 1 ans))
15127 h2 (+ hour (string-to-number (match-string 3 ans)))
15128 minute (string-to-number (match-string 2 ans))
15129 m2 (+ minute (if (match-end 5) (string-to-number
15130 (match-string 5 ans))0)))
15131 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15132 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15133 t t ans)))
15135 ;; Check if there is a time range
15136 (when (boundp 'org-end-time-was-given)
15137 (setq org-time-was-given nil)
15138 (when (and (string-match org-plain-time-of-day-regexp ans)
15139 (match-end 8))
15140 (setq org-end-time-was-given (match-string 8 ans))
15141 (setq ans (concat (substring ans 0 (match-beginning 7))
15142 (substring ans (match-end 7))))))
15144 (setq tl (parse-time-string ans)
15145 day (or (nth 3 tl) (nth 3 defdecode))
15146 month (or (nth 4 tl)
15147 (if (and org-read-date-prefer-future
15148 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15149 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15150 (nth 4 defdecode)))
15151 year (or (and (not kill-year) (nth 5 tl))
15152 (if (and org-read-date-prefer-future
15153 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15154 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15155 (nth 5 defdecode)))
15156 hour (or (nth 2 tl) (nth 2 defdecode))
15157 minute (or (nth 1 tl) (nth 1 defdecode))
15158 second (or (nth 0 tl) 0)
15159 wday (nth 6 tl))
15161 (when (and (eq org-read-date-prefer-future 'time)
15162 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15163 (equal day (nth 3 nowdecode))
15164 (equal month (nth 4 nowdecode))
15165 (equal year (nth 5 nowdecode))
15166 (nth 2 tl)
15167 (or (< (nth 2 tl) (nth 2 nowdecode))
15168 (and (= (nth 2 tl) (nth 2 nowdecode))
15169 (nth 1 tl)
15170 (< (nth 1 tl) (nth 1 nowdecode)))))
15171 (setq day (1+ day)
15172 futurep t))
15174 ;; Special date definitions below
15175 (cond
15176 (iso-week
15177 ;; There was an iso week
15178 (require 'cal-iso)
15179 (setq futurep nil)
15180 (setq year (or iso-year year)
15181 day (or iso-weekday wday 1)
15182 wday nil ; to make sure that the trigger below does not match
15183 iso-date (calendar-gregorian-from-absolute
15184 (calendar-absolute-from-iso
15185 (list iso-week day year))))
15186 ; FIXME: Should we also push ISO weeks into the future?
15187 ; (when (and org-read-date-prefer-future
15188 ; (not iso-year)
15189 ; (< (calendar-absolute-from-gregorian iso-date)
15190 ; (time-to-days (current-time))))
15191 ; (setq year (1+ year)
15192 ; iso-date (calendar-gregorian-from-absolute
15193 ; (calendar-absolute-from-iso
15194 ; (list iso-week day year)))))
15195 (setq month (car iso-date)
15196 year (nth 2 iso-date)
15197 day (nth 1 iso-date)))
15198 (deltan
15199 (setq futurep nil)
15200 (unless deltadef
15201 (let ((now (decode-time (current-time))))
15202 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15203 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15204 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15205 ((equal deltaw "m") (setq month (+ month deltan)))
15206 ((equal deltaw "y") (setq year (+ year deltan)))))
15207 ((and wday (not (nth 3 tl)))
15208 (setq futurep nil)
15209 ;; Weekday was given, but no day, so pick that day in the week
15210 ;; on or after the derived date.
15211 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15212 (unless (equal wday wday1)
15213 (setq day (+ day (% (- wday wday1 -7) 7))))))
15214 (if (and (boundp 'org-time-was-given)
15215 (nth 2 tl))
15216 (setq org-time-was-given t))
15217 (if (< year 100) (setq year (+ 2000 year)))
15218 ;; Check of the date is representable
15219 (if org-read-date-force-compatible-dates
15220 (progn
15221 (if (< year 1970)
15222 (setq year 1970 org-read-date-analyze-forced-year t))
15223 (if (> year 2037)
15224 (setq year 2037 org-read-date-analyze-forced-year t)))
15225 (condition-case nil
15226 (ignore (encode-time second minute hour day month year))
15227 (error
15228 (setq year (nth 5 defdecode))
15229 (setq org-read-date-analyze-forced-year t))))
15230 (setq org-read-date-analyze-futurep futurep)
15231 (list second minute hour day month year)))
15233 (defvar parse-time-weekdays)
15235 (defun org-read-date-get-relative (s today default)
15236 "Check string S for special relative date string.
15237 TODAY and DEFAULT are internal times, for today and for a default.
15238 Return shift list (N what def-flag)
15239 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15240 N is the number of WHATs to shift.
15241 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15242 the DEFAULT date rather than TODAY."
15243 (require 'parse-time)
15244 (when (and
15245 (string-match
15246 (concat
15247 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15248 "\\([0-9]+\\)?"
15249 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15250 "\\([ \t]\\|$\\)") s)
15251 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15252 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15253 (string-to-char (substring (match-string 1 s) -1))
15254 ?+))
15255 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15256 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15257 (what (if (match-end 3) (match-string 3 s) "d"))
15258 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15259 (date (if rel default today))
15260 (wday (nth 6 (decode-time date)))
15261 delta)
15262 (if wday1
15263 (progn
15264 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15265 (if (= dir ?-) (setq delta (- delta 7)))
15266 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15267 (list delta "d" rel))
15268 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15270 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15271 "Turn a user-specified date into the internal representation.
15272 The internal representation needed by the calendar is (month day year).
15273 This is a wrapper to handle the brain-dead convention in calendar that
15274 user function argument order change dependent on argument order."
15275 (if (boundp 'calendar-date-style)
15276 (cond
15277 ((eq calendar-date-style 'american)
15278 (list arg1 arg2 arg3))
15279 ((eq calendar-date-style 'european)
15280 (list arg2 arg1 arg3))
15281 ((eq calendar-date-style 'iso)
15282 (list arg2 arg3 arg1)))
15283 (with-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15284 (if (org-bound-and-true-p european-calendar-style)
15285 (list arg2 arg1 arg3)
15286 (list arg1 arg2 arg3)))))
15288 (defun org-eval-in-calendar (form &optional keepdate)
15289 "Eval FORM in the calendar window and return to current window.
15290 Also, store the cursor date in variable org-ans2."
15291 (let ((sf (selected-frame))
15292 (sw (selected-window)))
15293 (select-window (get-buffer-window "*Calendar*" t))
15294 (eval form)
15295 (when (and (not keepdate) (calendar-cursor-to-date))
15296 (let* ((date (calendar-cursor-to-date))
15297 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15298 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15299 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15300 (select-window sw)
15301 (org-select-frame-set-input-focus sf)))
15303 (defun org-calendar-select ()
15304 "Return to `org-read-date' with the date currently selected.
15305 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15306 (interactive)
15307 (when (calendar-cursor-to-date)
15308 (let* ((date (calendar-cursor-to-date))
15309 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15310 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15311 (if (active-minibuffer-window) (exit-minibuffer))))
15313 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15314 "Insert a date stamp for the date given by the internal TIME.
15315 WITH-HM means use the stamp format that includes the time of the day.
15316 INACTIVE means use square brackets instead of angular ones, so that the
15317 stamp will not contribute to the agenda.
15318 PRE and POST are optional strings to be inserted before and after the
15319 stamp.
15320 The command returns the inserted time stamp."
15321 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15322 stamp)
15323 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15324 (insert-before-markers (or pre ""))
15325 (when (listp extra)
15326 (setq extra (car extra))
15327 (if (and (stringp extra)
15328 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15329 (setq extra (format "-%02d:%02d"
15330 (string-to-number (match-string 1 extra))
15331 (string-to-number (match-string 2 extra))))
15332 (setq extra nil)))
15333 (when extra
15334 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15335 (insert-before-markers (setq stamp (format-time-string fmt time)))
15336 (insert-before-markers (or post ""))
15337 (setq org-last-inserted-timestamp stamp)))
15339 (defun org-toggle-time-stamp-overlays ()
15340 "Toggle the use of custom time stamp formats."
15341 (interactive)
15342 (setq org-display-custom-times (not org-display-custom-times))
15343 (unless org-display-custom-times
15344 (let ((p (point-min)) (bmp (buffer-modified-p)))
15345 (while (setq p (next-single-property-change p 'display))
15346 (if (and (get-text-property p 'display)
15347 (eq (get-text-property p 'face) 'org-date))
15348 (remove-text-properties
15349 p (setq p (next-single-property-change p 'display))
15350 '(display t))))
15351 (set-buffer-modified-p bmp)))
15352 (if (featurep 'xemacs)
15353 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15354 (org-restart-font-lock)
15355 (setq org-table-may-need-update t)
15356 (if org-display-custom-times
15357 (message "Time stamps are overlaid with custom format")
15358 (message "Time stamp overlays removed")))
15360 (defun org-display-custom-time (beg end)
15361 "Overlay modified time stamp format over timestamp between BEG and END."
15362 (let* ((ts (buffer-substring beg end))
15363 t1 w1 with-hm tf time str w2 (off 0))
15364 (save-match-data
15365 (setq t1 (org-parse-time-string ts t))
15366 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
15367 (setq off (- (match-end 0) (match-beginning 0)))))
15368 (setq end (- end off))
15369 (setq w1 (- end beg)
15370 with-hm (and (nth 1 t1) (nth 2 t1))
15371 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15372 time (org-fix-decoded-time t1)
15373 str (org-add-props
15374 (format-time-string
15375 (substring tf 1 -1) (apply 'encode-time time))
15376 nil 'mouse-face 'highlight)
15377 w2 (length str))
15378 (if (not (= w2 w1))
15379 (add-text-properties (1+ beg) (+ 2 beg)
15380 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15381 (if (featurep 'xemacs)
15382 (progn
15383 (put-text-property beg end 'invisible t)
15384 (put-text-property beg end 'end-glyph (make-glyph str)))
15385 (put-text-property beg end 'display str))))
15387 (defun org-translate-time (string)
15388 "Translate all timestamps in STRING to custom format.
15389 But do this only if the variable `org-display-custom-times' is set."
15390 (when org-display-custom-times
15391 (save-match-data
15392 (let* ((start 0)
15393 (re org-ts-regexp-both)
15394 t1 with-hm inactive tf time str beg end)
15395 (while (setq start (string-match re string start))
15396 (setq beg (match-beginning 0)
15397 end (match-end 0)
15398 t1 (save-match-data
15399 (org-parse-time-string (substring string beg end) t))
15400 with-hm (and (nth 1 t1) (nth 2 t1))
15401 inactive (equal (substring string beg (1+ beg)) "[")
15402 tf (funcall (if with-hm 'cdr 'car)
15403 org-time-stamp-custom-formats)
15404 time (org-fix-decoded-time t1)
15405 str (format-time-string
15406 (concat
15407 (if inactive "[" "<") (substring tf 1 -1)
15408 (if inactive "]" ">"))
15409 (apply 'encode-time time))
15410 string (replace-match str t t string)
15411 start (+ start (length str)))))))
15412 string)
15414 (defun org-fix-decoded-time (time)
15415 "Set 0 instead of nil for the first 6 elements of time.
15416 Don't touch the rest."
15417 (let ((n 0))
15418 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15420 (defun org-days-to-time (timestamp-string)
15421 "Difference between TIMESTAMP-STRING and now in days."
15422 (- (time-to-days (org-time-string-to-time timestamp-string))
15423 (time-to-days (current-time))))
15425 (defun org-deadline-close (timestamp-string &optional ndays)
15426 "Is the time in TIMESTAMP-STRING close to the current date?"
15427 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15428 (and (< (org-days-to-time timestamp-string) ndays)
15429 (not (org-entry-is-done-p))))
15431 (defun org-get-wdays (ts)
15432 "Get the deadline lead time appropriate for timestring TS."
15433 (cond
15434 ((<= org-deadline-warning-days 0)
15435 ;; 0 or negative, enforce this value no matter what
15436 (- org-deadline-warning-days))
15437 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
15438 ;; lead time is specified.
15439 (floor (* (string-to-number (match-string 1 ts))
15440 (cdr (assoc (match-string 2 ts)
15441 '(("d" . 1) ("w" . 7)
15442 ("m" . 30.4) ("y" . 365.25)))))))
15443 ;; go for the default.
15444 (t org-deadline-warning-days)))
15446 (defun org-calendar-select-mouse (ev)
15447 "Return to `org-read-date' with the date currently selected.
15448 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15449 (interactive "e")
15450 (mouse-set-point ev)
15451 (when (calendar-cursor-to-date)
15452 (let* ((date (calendar-cursor-to-date))
15453 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15454 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15455 (if (active-minibuffer-window) (exit-minibuffer))))
15457 (defun org-check-deadlines (ndays)
15458 "Check if there are any deadlines due or past due.
15459 A deadline is considered due if it happens within `org-deadline-warning-days'
15460 days from today's date. If the deadline appears in an entry marked DONE,
15461 it is not shown. The prefix arg NDAYS can be used to test that many
15462 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15463 (interactive "P")
15464 (let* ((org-warn-days
15465 (cond
15466 ((equal ndays '(4)) 100000)
15467 (ndays (prefix-numeric-value ndays))
15468 (t (abs org-deadline-warning-days))))
15469 (case-fold-search nil)
15470 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15471 (callback
15472 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15474 (message "%d deadlines past-due or due within %d days"
15475 (org-occur regexp nil callback)
15476 org-warn-days)))
15478 (defun org-check-before-date (date)
15479 "Check if there are deadlines or scheduled entries before DATE."
15480 (interactive (list (org-read-date)))
15481 (let ((case-fold-search nil)
15482 (regexp (concat "\\<\\(" org-deadline-string
15483 "\\|" org-scheduled-string
15484 "\\) *<\\([^>]+\\)>"))
15485 (callback
15486 (lambda () (time-less-p
15487 (org-time-string-to-time (match-string 2))
15488 (org-time-string-to-time date)))))
15489 (message "%d entries before %s"
15490 (org-occur regexp nil callback) date)))
15492 (defun org-check-after-date (date)
15493 "Check if there are deadlines or scheduled entries after DATE."
15494 (interactive (list (org-read-date)))
15495 (let ((case-fold-search nil)
15496 (regexp (concat "\\<\\(" org-deadline-string
15497 "\\|" org-scheduled-string
15498 "\\) *<\\([^>]+\\)>"))
15499 (callback
15500 (lambda () (not
15501 (time-less-p
15502 (org-time-string-to-time (match-string 2))
15503 (org-time-string-to-time date))))))
15504 (message "%d entries after %s"
15505 (org-occur regexp nil callback) date)))
15507 (defun org-evaluate-time-range (&optional to-buffer)
15508 "Evaluate a time range by computing the difference between start and end.
15509 Normally the result is just printed in the echo area, but with prefix arg
15510 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15511 If the time range is actually in a table, the result is inserted into the
15512 next column.
15513 For time difference computation, a year is assumed to be exactly 365
15514 days in order to avoid rounding problems."
15515 (interactive "P")
15517 (org-clock-update-time-maybe)
15518 (save-excursion
15519 (unless (org-at-date-range-p t)
15520 (goto-char (point-at-bol))
15521 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15522 (if (not (org-at-date-range-p t))
15523 (error "Not at a time-stamp range, and none found in current line")))
15524 (let* ((ts1 (match-string 1))
15525 (ts2 (match-string 2))
15526 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15527 (match-end (match-end 0))
15528 (time1 (org-time-string-to-time ts1))
15529 (time2 (org-time-string-to-time ts2))
15530 (t1 (org-float-time time1))
15531 (t2 (org-float-time time2))
15532 (diff (abs (- t2 t1)))
15533 (negative (< (- t2 t1) 0))
15534 ;; (ys (floor (* 365 24 60 60)))
15535 (ds (* 24 60 60))
15536 (hs (* 60 60))
15537 (fy "%dy %dd %02d:%02d")
15538 (fy1 "%dy %dd")
15539 (fd "%dd %02d:%02d")
15540 (fd1 "%dd")
15541 (fh "%02d:%02d")
15542 y d h m align)
15543 (if havetime
15544 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15546 d (floor (/ diff ds)) diff (mod diff ds)
15547 h (floor (/ diff hs)) diff (mod diff hs)
15548 m (floor (/ diff 60)))
15549 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15551 d (floor (+ (/ diff ds) 0.5))
15552 h 0 m 0))
15553 (if (not to-buffer)
15554 (message "%s" (org-make-tdiff-string y d h m))
15555 (if (org-at-table-p)
15556 (progn
15557 (goto-char match-end)
15558 (setq align t)
15559 (and (looking-at " *|") (goto-char (match-end 0))))
15560 (goto-char match-end))
15561 (if (looking-at
15562 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15563 (replace-match ""))
15564 (if negative (insert " -"))
15565 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15566 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15567 (insert " " (format fh h m))))
15568 (if align (org-table-align))
15569 (message "Time difference inserted")))))
15571 (defun org-make-tdiff-string (y d h m)
15572 (let ((fmt "")
15573 (l nil))
15574 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15575 l (push y l)))
15576 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15577 l (push d l)))
15578 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15579 l (push h l)))
15580 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15581 l (push m l)))
15582 (apply 'format fmt (nreverse l))))
15584 (defun org-time-string-to-time (s &optional buffer pos)
15585 (condition-case errdata
15586 (apply 'encode-time (org-parse-time-string s))
15587 (error (error "Bad timestamp `%s'%s\nError was: %s"
15588 s (if (not (and buffer pos))
15590 (format " at %d in buffer `%s'" pos buffer))
15591 (cdr errdata)))))
15593 (defun org-time-string-to-seconds (s)
15594 (org-float-time (org-time-string-to-time s)))
15596 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
15597 "Convert a time stamp to an absolute day number.
15598 If there is a specifier for a cyclic time stamp, get the closest date to
15599 DAYNR.
15600 PREFER and SHOW-ALL are passed through to `org-closest-date'.
15601 The variable date is bound by the calendar when this is called."
15602 (cond
15603 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15604 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15605 daynr
15606 (+ daynr 1000)))
15607 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
15608 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15609 (time-to-days (current-time))) (match-string 0 s)
15610 prefer show-all))
15611 (t (time-to-days
15612 (condition-case errdata
15613 (apply 'encode-time (org-parse-time-string s))
15614 (error (error "Bad timestamp `%s'%s\nError was: %s"
15615 s (if (not (and buffer pos))
15617 (format " at %d in buffer `%s'" pos buffer))
15618 (cdr errdata))))))))
15620 (defun org-days-to-iso-week (days)
15621 "Return the iso week number."
15622 (require 'cal-iso)
15623 (car (calendar-iso-from-absolute days)))
15625 (defun org-small-year-to-year (year)
15626 "Convert 2-digit years into 4-digit years.
15627 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15628 The year 2000 cannot be abbreviated. Any year larger than 99
15629 is returned unchanged."
15630 (if (< year 38)
15631 (setq year (+ 2000 year))
15632 (if (< year 100)
15633 (setq year (+ 1900 year))))
15634 year)
15636 (defun org-time-from-absolute (d)
15637 "Return the time corresponding to date D.
15638 D may be an absolute day number, or a calendar-type list (month day year)."
15639 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15640 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15642 (defun org-calendar-holiday ()
15643 "List of holidays, for Diary display in Org-mode."
15644 (require 'holidays)
15645 (let ((hl (funcall
15646 (if (fboundp 'calendar-check-holidays)
15647 'calendar-check-holidays 'check-calendar-holidays) date)))
15648 (if hl (mapconcat 'identity hl "; "))))
15650 (defun org-diary-sexp-entry (sexp entry date)
15651 "Process a SEXP diary ENTRY for DATE."
15652 (require 'diary-lib)
15653 (let ((result (if calendar-debug-sexp
15654 (let ((stack-trace-on-error t))
15655 (eval (car (read-from-string sexp))))
15656 (condition-case nil
15657 (eval (car (read-from-string sexp)))
15658 (error
15659 (beep)
15660 (message "Bad sexp at line %d in %s: %s"
15661 (org-current-line)
15662 (buffer-file-name) sexp)
15663 (sleep-for 2))))))
15664 (cond ((stringp result) (split-string result "; "))
15665 ((and (consp result)
15666 (not (consp (cdr result)))
15667 (stringp (cdr result))) (cdr result))
15668 ((and (consp result)
15669 (stringp (car result))) result)
15670 (result entry)
15671 (t nil))))
15673 (defun org-diary-to-ical-string (frombuf)
15674 "Get iCalendar entries from diary entries in buffer FROMBUF.
15675 This uses the icalendar.el library."
15676 (let* ((tmpdir (if (featurep 'xemacs)
15677 (temp-directory)
15678 temporary-file-directory))
15679 (tmpfile (make-temp-name
15680 (expand-file-name "orgics" tmpdir)))
15681 buf rtn b e)
15682 (with-current-buffer frombuf
15683 (icalendar-export-region (point-min) (point-max) tmpfile)
15684 (setq buf (find-buffer-visiting tmpfile))
15685 (set-buffer buf)
15686 (goto-char (point-min))
15687 (if (re-search-forward "^BEGIN:VEVENT" nil t)
15688 (setq b (match-beginning 0)))
15689 (goto-char (point-max))
15690 (if (re-search-backward "^END:VEVENT" nil t)
15691 (setq e (match-end 0)))
15692 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
15693 (kill-buffer buf)
15694 (delete-file tmpfile)
15695 rtn))
15697 (defun org-closest-date (start current change prefer show-all)
15698 "Find the date closest to CURRENT that is consistent with START and CHANGE.
15699 When PREFER is `past', return a date that is either CURRENT or past.
15700 When PREFER is `future', return a date that is either CURRENT or future.
15701 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
15702 ;; Make the proper lists from the dates
15703 (catch 'exit
15704 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
15705 dn dw sday cday n1 n2 n0
15706 d m y y1 y2 date1 date2 nmonths nm ny m2)
15708 (setq start (org-date-to-gregorian start)
15709 current (org-date-to-gregorian
15710 (if show-all
15711 current
15712 (time-to-days (current-time))))
15713 sday (calendar-absolute-from-gregorian start)
15714 cday (calendar-absolute-from-gregorian current))
15716 (if (<= cday sday) (throw 'exit sday))
15718 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
15719 (setq dn (string-to-number (match-string 1 change))
15720 dw (cdr (assoc (match-string 2 change) a1)))
15721 (error "Invalid change specifier: %s" change))
15722 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
15723 (cond
15724 ((eq dw 'day)
15725 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
15726 n2 (+ n1 dn)))
15727 ((eq dw 'year)
15728 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
15729 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
15730 (setq date1 (list m d y1)
15731 n1 (calendar-absolute-from-gregorian date1)
15732 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
15733 n2 (calendar-absolute-from-gregorian date2)))
15734 ((eq dw 'month)
15735 ;; approx number of month between the two dates
15736 (setq nmonths (floor (/ (- cday sday) 30.436875)))
15737 ;; How often does dn fit in there?
15738 (setq d (nth 1 start) m (car start) y (nth 2 start)
15739 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
15740 m (+ m nm)
15741 ny (floor (/ m 12))
15742 y (+ y ny)
15743 m (- m (* ny 12)))
15744 (while (> m 12) (setq m (- m 12) y (1+ y)))
15745 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
15746 (setq m2 (+ m dn) y2 y)
15747 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15748 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
15749 (while (<= n2 cday)
15750 (setq n1 n2 m m2 y y2)
15751 (setq m2 (+ m dn) y2 y)
15752 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15753 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
15754 ;; Make sure n1 is the earlier date
15755 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
15756 (if show-all
15757 (cond
15758 ((eq prefer 'past) (if (= cday n2) n2 n1))
15759 ((eq prefer 'future) (if (= cday n1) n1 n2))
15760 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
15761 (cond
15762 ((eq prefer 'past) (if (= cday n2) n2 n1))
15763 ((eq prefer 'future) (if (= cday n1) n1 n2))
15764 (t (if (= cday n1) n1 n2)))))))
15766 (defun org-date-to-gregorian (date)
15767 "Turn any specification of DATE into a Gregorian date for the calendar."
15768 (cond ((integerp date) (calendar-gregorian-from-absolute date))
15769 ((and (listp date) (= (length date) 3)) date)
15770 ((stringp date)
15771 (setq date (org-parse-time-string date))
15772 (list (nth 4 date) (nth 3 date) (nth 5 date)))
15773 ((listp date)
15774 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
15776 (defun org-parse-time-string (s &optional nodefault)
15777 "Parse the standard Org-mode time string.
15778 This should be a lot faster than the normal `parse-time-string'.
15779 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
15780 hour and minute fields will be nil if not given."
15781 (if (string-match org-ts-regexp0 s)
15782 (list 0
15783 (if (or (match-beginning 8) (not nodefault))
15784 (string-to-number (or (match-string 8 s) "0")))
15785 (if (or (match-beginning 7) (not nodefault))
15786 (string-to-number (or (match-string 7 s) "0")))
15787 (string-to-number (match-string 4 s))
15788 (string-to-number (match-string 3 s))
15789 (string-to-number (match-string 2 s))
15790 nil nil nil)
15791 (error "Not a standard Org-mode time string: %s" s)))
15793 (defun org-timestamp-up (&optional arg)
15794 "Increase the date item at the cursor by one.
15795 If the cursor is on the year, change the year. If it is on the month,
15796 the day or the time, change that.
15797 With prefix ARG, change by that many units."
15798 (interactive "p")
15799 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
15801 (defun org-timestamp-down (&optional arg)
15802 "Decrease the date item at the cursor by one.
15803 If the cursor is on the year, change the year. If it is on the month,
15804 the day or the time, change that.
15805 With prefix ARG, change by that many units."
15806 (interactive "p")
15807 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
15809 (defun org-timestamp-up-day (&optional arg)
15810 "Increase the date in the time stamp by one day.
15811 With prefix ARG, change that many days."
15812 (interactive "p")
15813 (if (and (not (org-at-timestamp-p t))
15814 (org-on-heading-p))
15815 (org-todo 'up)
15816 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
15818 (defun org-timestamp-down-day (&optional arg)
15819 "Decrease the date in the time stamp by one day.
15820 With prefix ARG, change that many days."
15821 (interactive "p")
15822 (if (and (not (org-at-timestamp-p t))
15823 (org-on-heading-p))
15824 (org-todo 'down)
15825 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
15827 (defun org-at-timestamp-p (&optional inactive-ok)
15828 "Determine if the cursor is in or at a timestamp."
15829 (interactive)
15830 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
15831 (pos (point))
15832 (ans (or (looking-at tsr)
15833 (save-excursion
15834 (skip-chars-backward "^[<\n\r\t")
15835 (if (> (point) (point-min)) (backward-char 1))
15836 (and (looking-at tsr)
15837 (> (- (match-end 0) pos) -1))))))
15838 (and ans
15839 (boundp 'org-ts-what)
15840 (setq org-ts-what
15841 (cond
15842 ((= pos (match-beginning 0)) 'bracket)
15843 ;; Point is considered to be "on the bracket" whether
15844 ;; it's really on it or right after it.
15845 ((or (= pos (1- (match-end 0)))
15846 (= pos (match-end 0))) 'bracket)
15847 ((org-pos-in-match-range pos 2) 'year)
15848 ((org-pos-in-match-range pos 3) 'month)
15849 ((org-pos-in-match-range pos 7) 'hour)
15850 ((org-pos-in-match-range pos 8) 'minute)
15851 ((or (org-pos-in-match-range pos 4)
15852 (org-pos-in-match-range pos 5)) 'day)
15853 ((and (> pos (or (match-end 8) (match-end 5)))
15854 (< pos (match-end 0)))
15855 (- pos (or (match-end 8) (match-end 5))))
15856 (t 'day))))
15857 ans))
15859 (defun org-toggle-timestamp-type ()
15860 "Toggle the type (<active> or [inactive]) of a time stamp."
15861 (interactive)
15862 (when (org-at-timestamp-p t)
15863 (let ((beg (match-beginning 0)) (end (match-end 0))
15864 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
15865 (save-excursion
15866 (goto-char beg)
15867 (while (re-search-forward "[][<>]" end t)
15868 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
15869 t t)))
15870 (message "Timestamp is now %sactive"
15871 (if (equal (char-after beg) ?<) "" "in")))))
15873 (defun org-timestamp-change (n &optional what updown)
15874 "Change the date in the time stamp at point.
15875 The date will be changed by N times WHAT. WHAT can be `day', `month',
15876 `year', `minute', `second'. If WHAT is not given, the cursor position
15877 in the timestamp determines what will be changed."
15878 (let ((origin (point)) origin-cat
15879 with-hm inactive
15880 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
15881 org-ts-what
15882 extra rem
15883 ts time time0)
15884 (if (not (org-at-timestamp-p t))
15885 (error "Not at a timestamp"))
15886 (if (and (not what) (eq org-ts-what 'bracket))
15887 (org-toggle-timestamp-type)
15888 ;; Point isn't on brackets. Remember the part of the time-stamp
15889 ;; the point was in. Indeed, size of time-stamps may change,
15890 ;; but point must be kept in the same category nonetheless.
15891 (setq origin-cat org-ts-what)
15892 (if (and (not what) (not (eq org-ts-what 'day))
15893 org-display-custom-times
15894 (get-text-property (point) 'display)
15895 (not (get-text-property (1- (point)) 'display)))
15896 (setq org-ts-what 'day))
15897 (setq org-ts-what (or what org-ts-what)
15898 inactive (= (char-after (match-beginning 0)) ?\[)
15899 ts (match-string 0))
15900 (replace-match "")
15901 (if (string-match
15902 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
15904 (setq extra (match-string 1 ts)))
15905 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
15906 (setq with-hm t))
15907 (setq time0 (org-parse-time-string ts))
15908 (when (and updown
15909 (eq org-ts-what 'minute)
15910 (not current-prefix-arg))
15911 ;; This looks like s-up and s-down. Change by one rounding step.
15912 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
15913 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
15914 (setcar (cdr time0) (+ (nth 1 time0)
15915 (if (> n 0) (- rem) (- dm rem))))))
15916 (setq time
15917 (encode-time (or (car time0) 0)
15918 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
15919 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
15920 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
15921 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
15922 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
15923 (nthcdr 6 time0)))
15924 (when (and (member org-ts-what '(hour minute))
15925 extra
15926 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
15927 (setq extra (org-modify-ts-extra
15928 extra
15929 (if (eq org-ts-what 'hour) 2 5)
15930 n dm)))
15931 (when (integerp org-ts-what)
15932 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
15933 (if (eq what 'calendar)
15934 (let ((cal-date (org-get-date-from-calendar)))
15935 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
15936 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
15937 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
15938 (setcar time0 (or (car time0) 0))
15939 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
15940 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
15941 (setq time (apply 'encode-time time0))))
15942 ;; Insert the new time-stamp, and ensure point stays in the same
15943 ;; category as before (i.e. not after the last position in that
15944 ;; category).
15945 (let ((pos (point)))
15946 ;; Stay before inserted string. `save-excursion' is of no use.
15947 (setq org-last-changed-timestamp
15948 (org-insert-time-stamp time with-hm inactive nil nil extra))
15949 (goto-char pos))
15950 (save-match-data
15951 (looking-at org-ts-regexp3)
15952 (goto-char (cond
15953 ;; `day' category ends before `hour' if any, or at
15954 ;; the end of the day name.
15955 ((eq origin-cat 'day)
15956 (min (or (match-beginning 7) (1- (match-end 5))) origin))
15957 ((eq origin-cat 'hour) (min (match-end 7) origin))
15958 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
15959 ((integerp origin-cat) (min (1- (match-end 0)) origin))
15960 ;; `year' and `month' have both fixed size: point
15961 ;; couldn't have moved into another part.
15962 (t origin))))
15963 ;; Update clock if on a CLOCK line.
15964 (org-clock-update-time-maybe)
15965 ;; Try to recenter the calendar window, if any.
15966 (if (and org-calendar-follow-timestamp-change
15967 (get-buffer-window "*Calendar*" t)
15968 (memq org-ts-what '(day month year)))
15969 (org-recenter-calendar (time-to-days time))))))
15971 (defun org-modify-ts-extra (s pos n dm)
15972 "Change the different parts of the lead-time and repeat fields in timestamp."
15973 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
15974 ng h m new rem)
15975 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
15976 (cond
15977 ((or (org-pos-in-match-range pos 2)
15978 (org-pos-in-match-range pos 3))
15979 (setq m (string-to-number (match-string 3 s))
15980 h (string-to-number (match-string 2 s)))
15981 (if (org-pos-in-match-range pos 2)
15982 (setq h (+ h n))
15983 (setq n (* dm (org-no-warnings (signum n))))
15984 (when (not (= 0 (setq rem (% m dm))))
15985 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
15986 (setq m (+ m n)))
15987 (if (< m 0) (setq m (+ m 60) h (1- h)))
15988 (if (> m 59) (setq m (- m 60) h (1+ h)))
15989 (setq h (min 24 (max 0 h)))
15990 (setq ng 1 new (format "-%02d:%02d" h m)))
15991 ((org-pos-in-match-range pos 6)
15992 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
15993 ((org-pos-in-match-range pos 5)
15994 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
15996 ((org-pos-in-match-range pos 9)
15997 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
15998 ((org-pos-in-match-range pos 8)
15999 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16001 (when ng
16002 (setq s (concat
16003 (substring s 0 (match-beginning ng))
16005 (substring s (match-end ng))))))
16008 (defun org-recenter-calendar (date)
16009 "If the calendar is visible, recenter it to DATE."
16010 (let* ((win (selected-window))
16011 (cwin (get-buffer-window "*Calendar*" t))
16012 (calendar-move-hook nil))
16013 (when cwin
16014 (select-window cwin)
16015 (calendar-goto-date (if (listp date) date
16016 (calendar-gregorian-from-absolute date)))
16017 (select-window win))))
16019 (defun org-goto-calendar (&optional arg)
16020 "Go to the Emacs calendar at the current date.
16021 If there is a time stamp in the current line, go to that date.
16022 A prefix ARG can be used to force the current date."
16023 (interactive "P")
16024 (let ((tsr org-ts-regexp) diff
16025 (calendar-move-hook nil)
16026 (calendar-view-holidays-initially-flag nil)
16027 (calendar-view-diary-initially-flag nil))
16028 (if (or (org-at-timestamp-p)
16029 (save-excursion
16030 (beginning-of-line 1)
16031 (looking-at (concat ".*" tsr))))
16032 (let ((d1 (time-to-days (current-time)))
16033 (d2 (time-to-days
16034 (org-time-string-to-time (match-string 1)))))
16035 (setq diff (- d2 d1))))
16036 (calendar)
16037 (calendar-goto-today)
16038 (if (and diff (not arg)) (calendar-forward-day diff))))
16040 (defun org-get-date-from-calendar ()
16041 "Return a list (month day year) of date at point in calendar."
16042 (with-current-buffer "*Calendar*"
16043 (save-match-data
16044 (calendar-cursor-to-date))))
16046 (defun org-date-from-calendar ()
16047 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16048 If there is already a time stamp at the cursor position, update it."
16049 (interactive)
16050 (if (org-at-timestamp-p t)
16051 (org-timestamp-change 0 'calendar)
16052 (let ((cal-date (org-get-date-from-calendar)))
16053 (org-insert-time-stamp
16054 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16056 (defun org-minutes-to-hh:mm-string (m)
16057 "Compute H:MM from a number of minutes."
16058 (let ((h (/ m 60)))
16059 (setq m (- m (* 60 h)))
16060 (format org-time-clocksum-format h m)))
16062 (defun org-hh:mm-string-to-minutes (s)
16063 "Convert a string H:MM to a number of minutes.
16064 If the string is just a number, interpret it as minutes.
16065 In fact, the first hh:mm or number in the string will be taken,
16066 there can be extra stuff in the string.
16067 If no number is found, the return value is 0."
16068 (cond
16069 ((integerp s) s)
16070 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16071 (+ (* (string-to-number (match-string 1 s)) 60)
16072 (string-to-number (match-string 2 s))))
16073 ((string-match "\\([0-9]+\\)" s)
16074 (string-to-number (match-string 1 s)))
16075 (t 0)))
16077 (defcustom org-effort-durations
16078 `(("h" . 60)
16079 ("d" . ,(* 60 8))
16080 ("w" . ,(* 60 8 5))
16081 ("m" . ,(* 60 8 5 4))
16082 ("y" . ,(* 60 8 5 40)))
16083 "Conversion factor to minutes for an effort modifier.
16085 Each entry has the form (MODIFIER . MINUTES).
16087 In an effort string, a number followed by MODIFIER is multiplied
16088 by the specified number of MINUTES to obtain an effort in
16089 minutes.
16091 For example, if the value of this variable is ((\"hours\" . 60)), then an
16092 effort string \"2hours\" is equivalent to 120 minutes."
16093 :group 'org-agenda
16094 :type '(alist :key-type (string :tag "Modifier")
16095 :value-type (number :tag "Minutes")))
16097 (defun org-duration-string-to-minutes (s)
16098 "Convert a duration string S to minutes.
16100 A bare number is interpreted as minutes, modifiers can be set by
16101 customizing `org-effort-durations' (which see).
16103 Entries containing a colon are interpreted as H:MM by
16104 `org-hh:mm-string-to-minutes'."
16105 (let ((result 0)
16106 (re (concat "\\([0-9]+\\) *\\("
16107 (regexp-opt (mapcar 'car org-effort-durations))
16108 "\\)")))
16109 (while (string-match re s)
16110 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16111 (string-to-number (match-string 1 s))))
16112 (setq s (replace-match "" nil t s)))
16113 (incf result (org-hh:mm-string-to-minutes s))
16114 result))
16116 ;;;; Files
16118 (defun org-save-all-org-buffers ()
16119 "Save all Org-mode buffers without user confirmation."
16120 (interactive)
16121 (message "Saving all Org-mode buffers...")
16122 (save-some-buffers t (lambda () (eq major-mode 'org-mode)))
16123 (when (featurep 'org-id) (org-id-locations-save))
16124 (message "Saving all Org-mode buffers... done"))
16126 (defun org-revert-all-org-buffers ()
16127 "Revert all Org-mode buffers.
16128 Prompt for confirmation when there are unsaved changes.
16129 Be sure you know what you are doing before letting this function
16130 overwrite your changes.
16132 This function is useful in a setup where one tracks org files
16133 with a version control system, to revert on one machine after pulling
16134 changes from another. I believe the procedure must be like this:
16136 1. M-x org-save-all-org-buffers
16137 2. Pull changes from the other machine, resolve conflicts
16138 3. M-x org-revert-all-org-buffers"
16139 (interactive)
16140 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16141 (error "Abort"))
16142 (save-excursion
16143 (save-window-excursion
16144 (mapc
16145 (lambda (b)
16146 (when (and (with-current-buffer b (eq major-mode 'org-mode))
16147 (with-current-buffer b buffer-file-name))
16148 (org-pop-to-buffer-same-window b)
16149 (revert-buffer t 'no-confirm)))
16150 (buffer-list))
16151 (when (and (featurep 'org-id) org-id-track-globally)
16152 (org-id-locations-load)))))
16154 ;;;; Agenda files
16156 ;;;###autoload
16157 (defun org-switchb (&optional arg)
16158 "Switch between Org buffers.
16159 With one prefix argument, restrict available buffers to files.
16160 With two prefix arguments, restrict available buffers to agenda files.
16162 Defaults to `iswitchb' for buffer name completion.
16163 Set `org-completion-use-ido' to make it use ido instead."
16164 (interactive "P")
16165 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16166 ((equal arg '(16)) (org-buffer-list 'agenda))
16167 (t (org-buffer-list))))
16168 (org-completion-use-iswitchb org-completion-use-iswitchb)
16169 (org-completion-use-ido org-completion-use-ido))
16170 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16171 (setq org-completion-use-iswitchb t))
16172 (org-pop-to-buffer-same-window
16173 (org-icompleting-read "Org buffer: "
16174 (mapcar 'list (mapcar 'buffer-name blist))
16175 nil t))))
16177 ;;; Define some older names previously used for this functionality
16178 ;;;###autoload
16179 (defalias 'org-ido-switchb 'org-switchb)
16180 ;;;###autoload
16181 (defalias 'org-iswitchb 'org-switchb)
16183 (defun org-buffer-list (&optional predicate exclude-tmp)
16184 "Return a list of Org buffers.
16185 PREDICATE can be `export', `files' or `agenda'.
16187 export restrict the list to Export buffers.
16188 files restrict the list to buffers visiting Org files.
16189 agenda restrict the list to buffers visiting agenda files.
16191 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16192 (let* ((bfn nil)
16193 (agenda-files (and (eq predicate 'agenda)
16194 (mapcar 'file-truename (org-agenda-files t))))
16195 (filter
16196 (cond
16197 ((eq predicate 'files)
16198 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
16199 ((eq predicate 'export)
16200 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16201 ((eq predicate 'agenda)
16202 (lambda (b)
16203 (with-current-buffer b
16204 (and (eq major-mode 'org-mode)
16205 (setq bfn (buffer-file-name b))
16206 (member (file-truename bfn) agenda-files)))))
16207 (t (lambda (b) (with-current-buffer b
16208 (or (eq major-mode 'org-mode)
16209 (string-match "\*Org .*Export"
16210 (buffer-name b)))))))))
16211 (delq nil
16212 (mapcar
16213 (lambda(b)
16214 (if (and (funcall filter b)
16215 (or (not exclude-tmp)
16216 (not (string-match "tmp" (buffer-name b)))))
16218 nil))
16219 (buffer-list)))))
16221 (defun org-agenda-files (&optional unrestricted archives)
16222 "Get the list of agenda files.
16223 Optional UNRESTRICTED means return the full list even if a restriction
16224 is currently in place.
16225 When ARCHIVES is t, include all archive files that are really being
16226 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16227 `org-agenda-archives-mode' is t."
16228 (let ((files
16229 (cond
16230 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16231 ((stringp org-agenda-files) (org-read-agenda-file-list))
16232 ((listp org-agenda-files) org-agenda-files)
16233 (t (error "Invalid value of `org-agenda-files'")))))
16234 (setq files (apply 'append
16235 (mapcar (lambda (f)
16236 (if (file-directory-p f)
16237 (directory-files
16238 f t org-agenda-file-regexp)
16239 (list f)))
16240 files)))
16241 (when org-agenda-skip-unavailable-files
16242 (setq files (delq nil
16243 (mapcar (function
16244 (lambda (file)
16245 (and (file-readable-p file) file)))
16246 files))))
16247 (when (or (eq archives t)
16248 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16249 (setq files (org-add-archive-files files)))
16250 files))
16252 (defun org-agenda-file-p (&optional file)
16253 "Return non-nil, if FILE is an agenda file.
16254 If FILE is omitted, use the file associated with the current
16255 buffer."
16256 (member (or file (buffer-file-name))
16257 (org-agenda-files t)))
16259 (defun org-edit-agenda-file-list ()
16260 "Edit the list of agenda files.
16261 Depending on setup, this either uses customize to edit the variable
16262 `org-agenda-files', or it visits the file that is holding the list. In the
16263 latter case, the buffer is set up in a way that saving it automatically kills
16264 the buffer and restores the previous window configuration."
16265 (interactive)
16266 (if (stringp org-agenda-files)
16267 (let ((cw (current-window-configuration)))
16268 (find-file org-agenda-files)
16269 (org-set-local 'org-window-configuration cw)
16270 (org-add-hook 'after-save-hook
16271 (lambda ()
16272 (set-window-configuration
16273 (prog1 org-window-configuration
16274 (kill-buffer (current-buffer))))
16275 (org-install-agenda-files-menu)
16276 (message "New agenda file list installed"))
16277 nil 'local)
16278 (message "%s" (substitute-command-keys
16279 "Edit list and finish with \\[save-buffer]")))
16280 (customize-variable 'org-agenda-files)))
16282 (defun org-store-new-agenda-file-list (list)
16283 "Set new value for the agenda file list and save it correctly."
16284 (if (stringp org-agenda-files)
16285 (let ((fe (org-read-agenda-file-list t)) b u)
16286 (while (setq b (find-buffer-visiting org-agenda-files))
16287 (kill-buffer b))
16288 (with-temp-file org-agenda-files
16289 (insert
16290 (mapconcat
16291 (lambda (f) ;; Keep un-expanded entries.
16292 (if (setq u (assoc f fe))
16293 (cdr u)
16295 list "\n")
16296 "\n")))
16297 (let ((org-mode-hook nil) (org-inhibit-startup t)
16298 (org-insert-mode-line-in-empty-file nil))
16299 (setq org-agenda-files list)
16300 (customize-save-variable 'org-agenda-files org-agenda-files))))
16302 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16303 "Read the list of agenda files from a file.
16304 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16305 filenames, used by `org-store-new-agenda-file-list' to write back
16306 un-expanded file names."
16307 (when (file-directory-p org-agenda-files)
16308 (error "`org-agenda-files' cannot be a single directory"))
16309 (when (stringp org-agenda-files)
16310 (with-temp-buffer
16311 (insert-file-contents org-agenda-files)
16312 (mapcar
16313 (lambda (f)
16314 (let ((e (expand-file-name (substitute-in-file-name f)
16315 org-directory)))
16316 (if pair-with-expansion
16317 (cons e f)
16318 e)))
16319 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16321 ;;;###autoload
16322 (defun org-cycle-agenda-files ()
16323 "Cycle through the files in `org-agenda-files'.
16324 If the current buffer visits an agenda file, find the next one in the list.
16325 If the current buffer does not, find the first agenda file."
16326 (interactive)
16327 (let* ((fs (org-agenda-files t))
16328 (files (append fs (list (car fs))))
16329 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16330 file)
16331 (unless files (error "No agenda files"))
16332 (catch 'exit
16333 (while (setq file (pop files))
16334 (if (equal (file-truename file) tcf)
16335 (when (car files)
16336 (find-file (car files))
16337 (throw 'exit t))))
16338 (find-file (car fs)))
16339 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16341 (defun org-agenda-file-to-front (&optional to-end)
16342 "Move/add the current file to the top of the agenda file list.
16343 If the file is not present in the list, it is added to the front. If it is
16344 present, it is moved there. With optional argument TO-END, add/move to the
16345 end of the list."
16346 (interactive "P")
16347 (let ((org-agenda-skip-unavailable-files nil)
16348 (file-alist (mapcar (lambda (x)
16349 (cons (file-truename x) x))
16350 (org-agenda-files t)))
16351 (ctf (file-truename buffer-file-name))
16352 x had)
16353 (setq x (assoc ctf file-alist) had x)
16355 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16356 (if to-end
16357 (setq file-alist (append (delq x file-alist) (list x)))
16358 (setq file-alist (cons x (delq x file-alist))))
16359 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16360 (org-install-agenda-files-menu)
16361 (message "File %s to %s of agenda file list"
16362 (if had "moved" "added") (if to-end "end" "front"))))
16364 (defun org-remove-file (&optional file)
16365 "Remove current file from the list of files in variable `org-agenda-files'.
16366 These are the files which are being checked for agenda entries.
16367 Optional argument FILE means use this file instead of the current."
16368 (interactive)
16369 (let* ((org-agenda-skip-unavailable-files nil)
16370 (file (or file buffer-file-name))
16371 (true-file (file-truename file))
16372 (afile (abbreviate-file-name file))
16373 (files (delq nil (mapcar
16374 (lambda (x)
16375 (if (equal true-file
16376 (file-truename x))
16377 nil x))
16378 (org-agenda-files t)))))
16379 (if (not (= (length files) (length (org-agenda-files t))))
16380 (progn
16381 (org-store-new-agenda-file-list files)
16382 (org-install-agenda-files-menu)
16383 (message "Removed file: %s" afile))
16384 (message "File was not in list: %s (not removed)" afile))))
16386 (defun org-file-menu-entry (file)
16387 (vector file (list 'find-file file) t))
16389 (defun org-check-agenda-file (file)
16390 "Make sure FILE exists. If not, ask user what to do."
16391 (when (not (file-exists-p file))
16392 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16393 (abbreviate-file-name file))
16394 (let ((r (downcase (read-char-exclusive))))
16395 (cond
16396 ((equal r ?r)
16397 (org-remove-file file)
16398 (throw 'nextfile t))
16399 (t (error "Abort"))))))
16401 (defun org-get-agenda-file-buffer (file)
16402 "Get a buffer visiting FILE. If the buffer needs to be created, add
16403 it to the list of buffers which might be released later."
16404 (let ((buf (org-find-base-buffer-visiting file)))
16405 (if buf
16406 buf ; just return it
16407 ;; Make a new buffer and remember it
16408 (setq buf (find-file-noselect file))
16409 (if buf (push buf org-agenda-new-buffers))
16410 buf)))
16412 (defun org-release-buffers (blist)
16413 "Release all buffers in list, asking the user for confirmation when needed.
16414 When a buffer is unmodified, it is just killed. When modified, it is saved
16415 \(if the user agrees) and then killed."
16416 (let (buf file)
16417 (while (setq buf (pop blist))
16418 (setq file (buffer-file-name buf))
16419 (when (and (buffer-modified-p buf)
16420 file
16421 (y-or-n-p (format "Save file %s? " file)))
16422 (with-current-buffer buf (save-buffer)))
16423 (kill-buffer buf))))
16425 (defun org-prepare-agenda-buffers (files)
16426 "Create buffers for all agenda files, protect archived trees and comments."
16427 (interactive)
16428 (let ((pa '(:org-archived t))
16429 (pc '(:org-comment t))
16430 (pall '(:org-archived t :org-comment t))
16431 (inhibit-read-only t)
16432 (rea (concat ":" org-archive-tag ":"))
16433 bmp file re)
16434 (save-excursion
16435 (save-restriction
16436 (while (setq file (pop files))
16437 (catch 'nextfile
16438 (if (bufferp file)
16439 (set-buffer file)
16440 (org-check-agenda-file file)
16441 (set-buffer (org-get-agenda-file-buffer file)))
16442 (widen)
16443 (setq bmp (buffer-modified-p))
16444 (org-refresh-category-properties)
16445 (setq org-todo-keywords-for-agenda
16446 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16447 (setq org-done-keywords-for-agenda
16448 (append org-done-keywords-for-agenda org-done-keywords))
16449 (setq org-todo-keyword-alist-for-agenda
16450 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16451 (setq org-drawers-for-agenda
16452 (append org-drawers-for-agenda org-drawers))
16453 (setq org-tag-alist-for-agenda
16454 (append org-tag-alist-for-agenda org-tag-alist))
16456 (save-excursion
16457 (remove-text-properties (point-min) (point-max) pall)
16458 (when org-agenda-skip-archived-trees
16459 (goto-char (point-min))
16460 (while (re-search-forward rea nil t)
16461 (if (org-on-heading-p t)
16462 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16463 (goto-char (point-min))
16464 (setq re (format org-heading-keyword-regexp-format
16465 org-comment-string))
16466 (while (re-search-forward re nil t)
16467 (add-text-properties
16468 (match-beginning 0) (org-end-of-subtree t) pc)))
16469 (set-buffer-modified-p bmp)))))
16470 (setq org-todo-keywords-for-agenda
16471 (org-uniquify org-todo-keywords-for-agenda))
16472 (setq org-todo-keyword-alist-for-agenda
16473 (org-uniquify org-todo-keyword-alist-for-agenda)
16474 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16476 ;;;; Embedded LaTeX
16478 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16479 "Keymap for the minor `org-cdlatex-mode'.")
16481 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16482 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16483 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16484 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16485 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16487 (defvar org-cdlatex-texmathp-advice-is-done nil
16488 "Flag remembering if we have applied the advice to texmathp already.")
16490 (define-minor-mode org-cdlatex-mode
16491 "Toggle the minor `org-cdlatex-mode'.
16492 This mode supports entering LaTeX environment and math in LaTeX fragments
16493 in Org-mode.
16494 \\{org-cdlatex-mode-map}"
16495 nil " OCDL" nil
16496 (when org-cdlatex-mode
16497 (require 'cdlatex)
16498 (run-hooks 'cdlatex-mode-hook)
16499 (cdlatex-compute-tables))
16500 (unless org-cdlatex-texmathp-advice-is-done
16501 (setq org-cdlatex-texmathp-advice-is-done t)
16502 (defadvice texmathp (around org-math-always-on activate)
16503 "Always return t in org-mode buffers.
16504 This is because we want to insert math symbols without dollars even outside
16505 the LaTeX math segments. If Orgmode thinks that point is actually inside
16506 an embedded LaTeX fragment, let texmathp do its job.
16507 \\[org-cdlatex-mode-map]"
16508 (interactive)
16509 (let (p)
16510 (cond
16511 ((not (eq major-mode 'org-mode)) ad-do-it)
16512 ((eq this-command 'cdlatex-math-symbol)
16513 (setq ad-return-value t
16514 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16516 (let ((p (org-inside-LaTeX-fragment-p)))
16517 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16518 (setq ad-return-value t
16519 texmathp-why '("Org-mode embedded math" . 0))
16520 (if p ad-do-it)))))))))
16522 (defun turn-on-org-cdlatex ()
16523 "Unconditionally turn on `org-cdlatex-mode'."
16524 (org-cdlatex-mode 1))
16526 (defun org-inside-LaTeX-fragment-p ()
16527 "Test if point is inside a LaTeX fragment.
16528 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16529 sequence appearing also before point.
16530 Even though the matchers for math are configurable, this function assumes
16531 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16532 delimiters are skipped when they have been removed by customization.
16533 The return value is nil, or a cons cell with the delimiter and the
16534 position of this delimiter.
16536 This function does a reasonably good job, but can locally be fooled by
16537 for example currency specifications. For example it will assume being in
16538 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16539 fragments that are properly closed, but during editing, we have to live
16540 with the uncertainty caused by missing closing delimiters. This function
16541 looks only before point, not after."
16542 (catch 'exit
16543 (let ((pos (point))
16544 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16545 (lim (progn
16546 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16547 (point)))
16548 dd-on str (start 0) m re)
16549 (goto-char pos)
16550 (when dodollar
16551 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16552 re (nth 1 (assoc "$" org-latex-regexps)))
16553 (while (string-match re str start)
16554 (cond
16555 ((= (match-end 0) (length str))
16556 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16557 ((= (match-end 0) (- (length str) 5))
16558 (throw 'exit nil))
16559 (t (setq start (match-end 0))))))
16560 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16561 (goto-char pos)
16562 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16563 (and (match-beginning 2) (throw 'exit nil))
16564 ;; count $$
16565 (while (re-search-backward "\\$\\$" lim t)
16566 (setq dd-on (not dd-on)))
16567 (goto-char pos)
16568 (if dd-on (cons "$$" m))))))
16570 (defun org-inside-latex-macro-p ()
16571 "Is point inside a LaTeX macro or its arguments?"
16572 (save-match-data
16573 (org-in-regexp
16574 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16576 (defun org-try-cdlatex-tab ()
16577 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16578 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16579 - inside a LaTeX fragment, or
16580 - after the first word in a line, where an abbreviation expansion could
16581 insert a LaTeX environment."
16582 (when org-cdlatex-mode
16583 (cond
16584 ;; Before any word on the line: No expansion possible.
16585 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
16586 ;; Just after first word on the line: Expand it. Make sure it
16587 ;; cannot happen on headlines, though.
16588 ((save-excursion
16589 (skip-chars-backward "a-zA-Z0-9*")
16590 (skip-chars-backward " \t")
16591 (and (bolp) (not (org-at-heading-p))))
16592 (cdlatex-tab) t)
16593 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
16595 (defun org-cdlatex-underscore-caret (&optional arg)
16596 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16597 Revert to the normal definition outside of these fragments."
16598 (interactive "P")
16599 (if (org-inside-LaTeX-fragment-p)
16600 (call-interactively 'cdlatex-sub-superscript)
16601 (let (org-cdlatex-mode)
16602 (call-interactively (key-binding (vector last-input-event))))))
16604 (defun org-cdlatex-math-modify (&optional arg)
16605 "Execute `cdlatex-math-modify' in LaTeX fragments.
16606 Revert to the normal definition outside of these fragments."
16607 (interactive "P")
16608 (if (org-inside-LaTeX-fragment-p)
16609 (call-interactively 'cdlatex-math-modify)
16610 (let (org-cdlatex-mode)
16611 (call-interactively (key-binding (vector last-input-event))))))
16613 (defvar org-latex-fragment-image-overlays nil
16614 "List of overlays carrying the images of latex fragments.")
16615 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16617 (defun org-remove-latex-fragment-image-overlays ()
16618 "Remove all overlays with LaTeX fragment images in current buffer."
16619 (mapc 'delete-overlay org-latex-fragment-image-overlays)
16620 (setq org-latex-fragment-image-overlays nil))
16622 (defun org-preview-latex-fragment (&optional subtree)
16623 "Preview the LaTeX fragment at point, or all locally or globally.
16624 If the cursor is in a LaTeX fragment, create the image and overlay
16625 it over the source code. If there is no fragment at point, display
16626 all fragments in the current text, from one headline to the next. With
16627 prefix SUBTREE, display all fragments in the current subtree. With a
16628 double prefix arg \\[universal-argument] \\[universal-argument], or when \
16629 the cursor is before the first headline,
16630 display all fragments in the buffer.
16631 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16632 (interactive "P")
16633 (org-remove-latex-fragment-image-overlays)
16634 (save-excursion
16635 (save-restriction
16636 (let (beg end at msg)
16637 (cond
16638 ((or (equal subtree '(16))
16639 (not (save-excursion
16640 (re-search-backward org-outline-regexp-bol nil t))))
16641 (setq beg (point-min) end (point-max)
16642 msg "Creating images for buffer...%s"))
16643 ((equal subtree '(4))
16644 (org-back-to-heading)
16645 (setq beg (point) end (org-end-of-subtree t)
16646 msg "Creating images for subtree...%s"))
16648 (if (setq at (org-inside-LaTeX-fragment-p))
16649 (goto-char (max (point-min) (- (cdr at) 2)))
16650 (org-back-to-heading))
16651 (setq beg (point) end (progn (outline-next-heading) (point))
16652 msg (if at "Creating image...%s"
16653 "Creating images for entry...%s"))))
16654 (message msg "")
16655 (narrow-to-region beg end)
16656 (goto-char beg)
16657 (org-format-latex
16658 (concat "ltxpng/" (file-name-sans-extension
16659 (file-name-nondirectory
16660 buffer-file-name)))
16661 default-directory 'overlays msg at 'forbuffer 'dvipng)
16662 (message msg "done. Use `C-c C-c' to remove images.")))))
16664 (defvar org-latex-regexps
16665 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16666 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16667 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16668 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16669 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16670 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16671 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
16672 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
16673 "Regular expressions for matching embedded LaTeX.")
16675 (defvar org-export-have-math nil) ;; dynamic scoping
16676 (defun org-format-latex (prefix &optional dir overlays msg at
16677 forbuffer processing-type)
16678 "Replace LaTeX fragments with links to an image, and produce images.
16679 Some of the options can be changed using the variable
16680 `org-format-latex-options'."
16681 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16682 (let* ((prefixnodir (file-name-nondirectory prefix))
16683 (absprefix (expand-file-name prefix dir))
16684 (todir (file-name-directory absprefix))
16685 (opt org-format-latex-options)
16686 (matchers (plist-get opt :matchers))
16687 (re-list org-latex-regexps)
16688 (org-format-latex-header-extra
16689 (plist-get (org-infile-export-plist) :latex-header-extra))
16690 (cnt 0) txt hash link beg end re e checkdir
16691 executables-checked string
16692 m n block-type block linkfile movefile ov)
16693 ;; Check the different regular expressions
16694 (while (setq e (pop re-list))
16695 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
16696 block (if block-type "\n\n" ""))
16697 (when (member m matchers)
16698 (goto-char (point-min))
16699 (while (re-search-forward re nil t)
16700 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
16701 (not (get-text-property (match-beginning n)
16702 'org-protected))
16703 (or (not overlays)
16704 (not (eq (get-char-property (match-beginning n)
16705 'org-overlay-type)
16706 'org-latex-overlay))))
16707 (setq org-export-have-math t)
16708 (cond
16709 ((eq processing-type 'verbatim)
16710 ;; Leave the text verbatim, just protect it
16711 (add-text-properties (match-beginning n) (match-end n)
16712 '(org-protected t)))
16713 ((eq processing-type 'mathjax)
16714 ;; Prepare for MathJax processing
16715 (setq string (match-string n))
16716 (if (member m '("$" "$1"))
16717 (save-excursion
16718 (delete-region (match-beginning n) (match-end n))
16719 (goto-char (match-beginning n))
16720 (insert (org-add-props (concat "\\(" (substring string 1 -1)
16721 "\\)")
16722 '(org-protected t))))
16723 (add-text-properties (match-beginning n) (match-end n)
16724 '(org-protected t))))
16725 ((eq processing-type 'dvipng)
16726 ;; Process to an image
16727 (setq txt (match-string n)
16728 beg (match-beginning n) end (match-end n)
16729 cnt (1+ cnt))
16730 (let (print-length print-level) ; make sure full list is printed
16731 (setq hash (sha1 (prin1-to-string
16732 (list org-format-latex-header
16733 org-format-latex-header-extra
16734 org-export-latex-default-packages-alist
16735 org-export-latex-packages-alist
16736 org-format-latex-options
16737 forbuffer txt)))
16738 linkfile (format "%s_%s.png" prefix hash)
16739 movefile (format "%s_%s.png" absprefix hash)))
16740 (setq link (concat block "[[file:" linkfile "]]" block))
16741 (if msg (message msg cnt))
16742 (goto-char beg)
16743 (unless checkdir ; make sure the directory exists
16744 (setq checkdir t)
16745 (or (file-directory-p todir) (make-directory todir t)))
16747 (unless executables-checked
16748 (org-check-external-command
16749 "latex" "needed to convert LaTeX fragments to images")
16750 (org-check-external-command
16751 "dvipng" "needed to convert LaTeX fragments to images")
16752 (setq executables-checked t))
16754 (unless (file-exists-p movefile)
16755 (org-create-formula-image
16756 txt movefile opt forbuffer))
16757 (if overlays
16758 (progn
16759 (mapc (lambda (o)
16760 (if (eq (overlay-get o 'org-overlay-type)
16761 'org-latex-overlay)
16762 (delete-overlay o)))
16763 (overlays-in beg end))
16764 (setq ov (make-overlay beg end))
16765 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
16766 (if (featurep 'xemacs)
16767 (progn
16768 (overlay-put ov 'invisible t)
16769 (overlay-put
16770 ov 'end-glyph
16771 (make-glyph (vector 'png :file movefile))))
16772 (overlay-put
16773 ov 'display
16774 (list 'image :type 'png :file movefile :ascent 'center)))
16775 (push ov org-latex-fragment-image-overlays)
16776 (goto-char end))
16777 (delete-region beg end)
16778 (insert (org-add-props link
16779 (list 'org-latex-src
16780 (replace-regexp-in-string
16781 "\"" "" txt)
16782 'org-latex-src-embed-type
16783 (if block-type 'paragraph 'character))))))
16784 ((eq processing-type 'mathml)
16785 ;; Process to MathML
16786 (unless executables-checked
16787 (unless (save-match-data (org-format-latex-mathml-available-p))
16788 (error "LaTeX to MathML converter not configured"))
16789 (setq executables-checked t))
16790 (setq txt (match-string n)
16791 beg (match-beginning n) end (match-end n)
16792 cnt (1+ cnt))
16793 (if msg (message msg cnt))
16794 (goto-char beg)
16795 (delete-region beg end)
16796 (insert (org-format-latex-as-mathml
16797 txt block-type prefix dir)))
16799 (error "Unknown conversion type %s for latex fragments"
16800 processing-type)))))))))
16802 (defun org-create-math-formula (latex-frag &optional mathml-file)
16803 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
16804 Use `org-latex-to-mathml-convert-command'. If the conversion is
16805 sucessful, return the portion between \"<math...> </math>\"
16806 elements otherwise return nil. When MATHML-FILE is specified,
16807 write the results in to that file. When invoked as an
16808 interactive command, prompt for LATEX-FRAG, with initial value
16809 set to the current active region and echo the results for user
16810 inspection."
16811 (interactive (list (let ((frag (when (region-active-p)
16812 (buffer-substring-no-properties
16813 (region-beginning) (region-end)))))
16814 (read-string "LaTeX Fragment: " frag nil frag))))
16815 (unless latex-frag (error "Invalid latex-frag"))
16816 (let* ((tmp-in-file (file-relative-name
16817 (make-temp-name (expand-file-name "ltxmathml-in"))))
16818 (ignore (write-region latex-frag nil tmp-in-file))
16819 (tmp-out-file (file-relative-name
16820 (make-temp-name (expand-file-name "ltxmathml-out"))))
16821 (cmd (format-spec
16822 org-latex-to-mathml-convert-command
16823 `((?j . ,(shell-quote-argument
16824 (expand-file-name org-latex-to-mathml-jar-file)))
16825 (?I . ,(shell-quote-argument tmp-in-file))
16826 (?o . ,(shell-quote-argument tmp-out-file)))))
16827 mathml shell-command-output)
16828 (when (org-called-interactively-p 'any)
16829 (unless (org-format-latex-mathml-available-p)
16830 (error "LaTeX to MathML converter not configured")))
16831 (message "Running %s" cmd)
16832 (setq shell-command-output (shell-command-to-string cmd))
16833 (setq mathml
16834 (when (file-readable-p tmp-out-file)
16835 (with-current-buffer (find-file-noselect tmp-out-file t)
16836 (goto-char (point-min))
16837 (when (re-search-forward
16838 (concat
16839 (regexp-quote
16840 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
16841 "\\(.\\|\n\\)*"
16842 (regexp-quote "</math>")) nil t)
16843 (prog1 (match-string 0) (kill-buffer))))))
16844 (cond
16845 (mathml
16846 (setq mathml
16847 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
16848 (when mathml-file
16849 (write-region mathml nil mathml-file))
16850 (when (org-called-interactively-p 'any)
16851 (message mathml)))
16852 ((message "LaTeX to MathML conversion failed")
16853 (message shell-command-output)))
16854 (delete-file tmp-in-file)
16855 (when (file-exists-p tmp-out-file)
16856 (delete-file tmp-out-file))
16857 mathml))
16859 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
16860 prefix &optional dir)
16861 "Use `org-create-math-formula' but check local cache first."
16862 (let* ((absprefix (expand-file-name prefix dir))
16863 (print-length nil) (print-level nil)
16864 (formula-id (concat
16865 "formula-"
16866 (sha1
16867 (prin1-to-string
16868 (list latex-frag
16869 org-latex-to-mathml-convert-command)))))
16870 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
16871 (formula-cache-dir (file-name-directory formula-cache)))
16873 (unless (file-directory-p formula-cache-dir)
16874 (make-directory formula-cache-dir t))
16876 (unless (file-exists-p formula-cache)
16877 (org-create-math-formula latex-frag formula-cache))
16879 (if (file-exists-p formula-cache)
16880 ;; Successful conversion. Return the link to MathML file.
16881 (org-add-props
16882 (format "[[file:%s]]" (file-relative-name formula-cache dir))
16883 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
16884 'org-latex-src-embed-type (if latex-frag-type
16885 'paragraph 'character)))
16886 ;; Failed conversion. Return the LaTeX fragment verbatim
16887 (add-text-properties
16888 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
16889 latex-frag)))
16891 ;; This function borrows from Ganesh Swami's latex2png.el
16892 (defun org-create-formula-image (string tofile options buffer)
16893 "This calls dvipng."
16894 (require 'org-latex)
16895 (let* ((tmpdir (if (featurep 'xemacs)
16896 (temp-directory)
16897 temporary-file-directory))
16898 (texfilebase (make-temp-name
16899 (expand-file-name "orgtex" tmpdir)))
16900 (texfile (concat texfilebase ".tex"))
16901 (dvifile (concat texfilebase ".dvi"))
16902 (pngfile (concat texfilebase ".png"))
16903 (fnh (if (featurep 'xemacs)
16904 (font-height (get-face-font 'default))
16905 (face-attribute 'default :height nil)))
16906 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
16907 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
16908 (fg (or (plist-get options (if buffer :foreground :html-foreground))
16909 "Black"))
16910 (bg (or (plist-get options (if buffer :background :html-background))
16911 "Transparent")))
16912 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
16913 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
16914 (with-temp-file texfile
16915 (insert (org-splice-latex-header
16916 org-format-latex-header
16917 org-export-latex-default-packages-alist
16918 org-export-latex-packages-alist t
16919 org-format-latex-header-extra))
16920 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
16921 (require 'org-latex)
16922 (org-export-latex-fix-inputenc))
16923 (let ((dir default-directory))
16924 (condition-case nil
16925 (progn
16926 (cd tmpdir)
16927 (call-process "latex" nil nil nil texfile))
16928 (error nil))
16929 (cd dir))
16930 (if (not (file-exists-p dvifile))
16931 (progn (message "Failed to create dvi file from %s" texfile) nil)
16932 (condition-case nil
16933 (call-process "dvipng" nil nil nil
16934 "-fg" fg "-bg" bg
16935 "-D" dpi
16936 ;;"-x" scale "-y" scale
16937 "-T" "tight"
16938 "-o" pngfile
16939 dvifile)
16940 (error nil))
16941 (if (not (file-exists-p pngfile))
16942 (if org-format-latex-signal-error
16943 (error "Failed to create png file from %s" texfile)
16944 (message "Failed to create png file from %s" texfile)
16945 nil)
16946 ;; Use the requested file name and clean up
16947 (copy-file pngfile tofile 'replace)
16948 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
16949 (delete-file (concat texfilebase e)))
16950 pngfile))))
16952 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
16953 "Fill a LaTeX header template TPL.
16954 In the template, the following place holders will be recognized:
16956 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
16957 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
16958 [PACKAGES] \\usepackage statements for PKG
16959 [NO-PACKAGES] do not include PKG
16960 [EXTRA] the string EXTRA
16961 [NO-EXTRA] do not include EXTRA
16963 For backward compatibility, if both the positive and the negative place
16964 holder is missing, the positive one (without the \"NO-\") will be
16965 assumed to be present at the end of the template.
16966 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
16967 EXTRA is a string.
16968 SNIPPETS-P indicates if this is run to create snippet images for HTML."
16969 (let (rpl (end ""))
16970 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
16971 (setq rpl (if (or (match-end 1) (not def-pkg))
16972 "" (org-latex-packages-to-string def-pkg snippets-p t))
16973 tpl (replace-match rpl t t tpl))
16974 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
16976 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
16977 (setq rpl (if (or (match-end 1) (not pkg))
16978 "" (org-latex-packages-to-string pkg snippets-p t))
16979 tpl (replace-match rpl t t tpl))
16980 (if pkg (setq end
16981 (concat end "\n"
16982 (org-latex-packages-to-string pkg snippets-p)))))
16984 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
16985 (setq rpl (if (or (match-end 1) (not extra))
16986 "" (concat extra "\n"))
16987 tpl (replace-match rpl t t tpl))
16988 (if (and extra (string-match "\\S-" extra))
16989 (setq end (concat end "\n" extra))))
16991 (if (string-match "\\S-" end)
16992 (concat tpl "\n" end)
16993 tpl)))
16995 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
16996 "Turn an alist of packages into a string with the \\usepackage macros."
16997 (setq pkg (mapconcat (lambda(p)
16998 (cond
16999 ((stringp p) p)
17000 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17001 (format "%% Package %s omitted" (cadr p)))
17002 ((equal "" (car p))
17003 (format "\\usepackage{%s}" (cadr p)))
17005 (format "\\usepackage[%s]{%s}"
17006 (car p) (cadr p)))))
17008 "\n"))
17009 (if newline (concat pkg "\n") pkg))
17011 (defun org-dvipng-color (attr)
17012 "Return an rgb color specification for dvipng."
17013 (apply 'format "rgb %s %s %s"
17014 (mapcar 'org-normalize-color
17015 (color-values (face-attribute 'default attr nil)))))
17017 (defun org-normalize-color (value)
17018 "Return string to be used as color value for an RGB component."
17019 (format "%g" (/ value 65535.0)))
17021 ;; Image display
17024 (defvar org-inline-image-overlays nil)
17025 (make-variable-buffer-local 'org-inline-image-overlays)
17027 (defun org-toggle-inline-images (&optional include-linked)
17028 "Toggle the display of inline images.
17029 INCLUDE-LINKED is passed to `org-display-inline-images'."
17030 (interactive "P")
17031 (if org-inline-image-overlays
17032 (progn
17033 (org-remove-inline-images)
17034 (message "Inline image display turned off"))
17035 (org-display-inline-images include-linked)
17036 (if org-inline-image-overlays
17037 (message "%d images displayed inline"
17038 (length org-inline-image-overlays))
17039 (message "No images to display inline"))))
17041 (defun org-display-inline-images (&optional include-linked refresh beg end)
17042 "Display inline images.
17043 Normally only links without a description part are inlined, because this
17044 is how it will work for export. When INCLUDE-LINKED is set, also links
17045 with a description part will be inlined. This can be nice for a quick
17046 look at those images, but it does not reflect what exported files will look
17047 like.
17048 When REFRESH is set, refresh existing images between BEG and END.
17049 This will create new image displays only if necessary.
17050 BEG and END default to the buffer boundaries."
17051 (interactive "P")
17052 (unless refresh
17053 (org-remove-inline-images)
17054 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17055 (save-excursion
17056 (save-restriction
17057 (widen)
17058 (setq beg (or beg (point-min)) end (or end (point-max)))
17059 (goto-char (point-min))
17060 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17061 (substring (org-image-file-name-regexp) 0 -2)
17062 "\\)\\]" (if include-linked "" "\\]")))
17063 old file ov img)
17064 (while (re-search-forward re end t)
17065 (setq old (get-char-property-and-overlay (match-beginning 1)
17066 'org-image-overlay))
17067 (setq file (expand-file-name
17068 (concat (or (match-string 3) "") (match-string 4))))
17069 (when (file-exists-p file)
17070 (if (and (car-safe old) refresh)
17071 (image-refresh (overlay-get (cdr old) 'display))
17072 (setq img (save-match-data (create-image file)))
17073 (when img
17074 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17075 (overlay-put ov 'display img)
17076 (overlay-put ov 'face 'default)
17077 (overlay-put ov 'org-image-overlay t)
17078 (overlay-put ov 'modification-hooks
17079 (list 'org-display-inline-modification-hook))
17080 (push ov org-inline-image-overlays)))))))))
17082 (defun org-display-inline-modification-hook (ov after beg end &optional len)
17083 "Remove inline-display overlay if a corresponding region is modified."
17084 (let ((inhibit-modification-hooks t))
17085 (when (and ov after)
17086 (delete ov org-inline-image-overlays)
17087 (delete-overlay ov))))
17089 (defun org-remove-inline-images ()
17090 "Remove inline display of images."
17091 (interactive)
17092 (mapc 'delete-overlay org-inline-image-overlays)
17093 (setq org-inline-image-overlays nil))
17095 ;;;; Key bindings
17097 ;; Outline functions from `outline-mode-prefix-map'
17098 ;; that can be remapped in Org:
17099 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17100 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17101 (define-key org-mode-map [remap outline-forward-same-level]
17102 'org-forward-same-level)
17103 (define-key org-mode-map [remap outline-backward-same-level]
17104 'org-backward-same-level)
17105 (define-key org-mode-map [remap show-branches]
17106 'org-kill-note-or-show-branches)
17107 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17108 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17109 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17111 ;; Outline functions from `outline-mode-prefix-map'
17112 ;; that can not be remapped in Org:
17113 ;; - the column "key binding" shows whether the Outline function is still
17114 ;; available in Org mode on the same key that it has been bound to in
17115 ;; Outline mode:
17116 ;; - "overridden": key used for a different functionality in Org mode
17117 ;; - else: key still bound to the same Outline function in Org mode
17118 ;; | Outline function | key binding | Org replacement |
17119 ;; |------------------------------------+-------------+-----------------------|
17120 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17121 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17122 ;; | `show-children' | `C-c C-i' | visibility cycling |
17123 ;; | `hide-subtree' | overridden | visibility cycling |
17124 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17125 ;; | `hide-body' | overridden | no replacement |
17126 ;; | `show-all' | overridden | no replacement |
17127 ;; | `hide-entry' | overridden | visibility cycling |
17128 ;; | `show-entry' | overridden | no replacement |
17129 ;; | `hide-leaves' | overridden | no replacement |
17130 ;; | `hide-sublevels' | overridden | no replacement |
17131 ;; | `hide-other' | overridden | no replacement |
17132 ;; | `outline-move-subtree-up' | `C-c C-^' | better: org-shiftup |
17133 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17135 ;; Make `C-c C-x' a prefix key
17136 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17138 ;; TAB key with modifiers
17139 (org-defkey org-mode-map "\C-i" 'org-cycle)
17140 (org-defkey org-mode-map [(tab)] 'org-cycle)
17141 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17142 (org-defkey org-mode-map [(meta tab)] 'pcomplete)
17143 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17144 (org-defkey org-mode-map "\M-\C-i" 'pcomplete)
17145 ;; The following line is necessary under Suse GNU/Linux
17146 (unless (featurep 'xemacs)
17147 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17148 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17149 (define-key org-mode-map [backtab] 'org-shifttab)
17151 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17152 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17153 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17155 ;; Cursor keys with modifiers
17156 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17157 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17158 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17159 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17161 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17162 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17163 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17164 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17166 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17167 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17168 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17169 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17171 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17172 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17173 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17174 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17176 ;; Babel keys
17177 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17178 (mapc (lambda (pair)
17179 (define-key org-babel-map (car pair) (cdr pair)))
17180 org-babel-key-bindings)
17182 ;;; Extra keys for tty access.
17183 ;; We only set them when really needed because otherwise the
17184 ;; menus don't show the simple keys
17186 (when (or org-use-extra-keys
17187 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17188 (not window-system))
17189 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17190 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17191 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17192 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17193 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17194 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17195 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17196 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17197 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17198 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17199 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17200 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17201 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17202 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17203 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17204 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17205 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17206 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17207 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17208 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17209 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17210 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17211 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17212 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17213 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17214 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17215 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17216 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17218 ;; All the other keys
17220 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17221 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17222 (if (boundp 'narrow-map)
17223 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17224 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17225 (if (boundp 'narrow-map)
17226 (org-defkey narrow-map "b" 'org-narrow-to-block)
17227 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17228 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
17229 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
17230 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17231 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17232 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17233 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17234 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17235 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17236 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17237 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17238 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17239 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17240 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17241 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17242 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17243 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17244 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17245 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17246 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17247 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17248 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17249 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17250 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
17251 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
17252 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
17253 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
17254 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
17255 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
17256 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
17257 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
17258 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17259 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17260 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17261 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17262 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
17263 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
17264 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17265 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
17266 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
17267 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
17268 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
17269 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17270 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
17271 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
17272 (org-defkey org-mode-map "\C-c^" 'org-sort)
17273 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
17274 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
17275 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
17276 (org-defkey org-mode-map "\C-m" 'org-return)
17277 (org-defkey org-mode-map "\C-j" 'org-return-indent)
17278 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
17279 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
17280 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
17281 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
17282 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
17283 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
17284 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
17285 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
17286 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
17287 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
17288 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
17289 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
17290 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
17291 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
17292 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
17293 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
17294 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
17295 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
17296 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
17297 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
17298 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
17300 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
17301 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
17302 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
17303 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
17305 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
17306 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
17307 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
17308 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
17309 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
17310 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
17311 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
17312 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
17313 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
17314 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
17315 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
17316 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
17317 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
17318 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
17319 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
17320 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
17321 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
17322 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
17324 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
17325 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
17326 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
17327 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
17328 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
17330 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
17332 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
17334 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
17335 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
17337 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
17340 (when (featurep 'xemacs)
17341 (org-defkey org-mode-map 'button3 'popup-mode-menu))
17344 (defconst org-speed-commands-default
17346 ("Outline Navigation")
17347 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
17348 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
17349 ("f" . (org-speed-move-safe 'org-forward-same-level))
17350 ("b" . (org-speed-move-safe 'org-backward-same-level))
17351 ("u" . (org-speed-move-safe 'outline-up-heading))
17352 ("j" . org-goto)
17353 ("g" . (org-refile t))
17354 ("Outline Visibility")
17355 ("c" . org-cycle)
17356 ("C" . org-shifttab)
17357 (" " . org-display-outline-path)
17358 ("Outline Structure Editing")
17359 ("U" . org-shiftmetaup)
17360 ("D" . org-shiftmetadown)
17361 ("r" . org-metaright)
17362 ("l" . org-metaleft)
17363 ("R" . org-shiftmetaright)
17364 ("L" . org-shiftmetaleft)
17365 ("i" . (progn (forward-char 1) (call-interactively
17366 'org-insert-heading-respect-content)))
17367 ("^" . org-sort)
17368 ("w" . org-refile)
17369 ("a" . org-archive-subtree-default-with-confirmation)
17370 ("." . org-mark-subtree)
17371 ("Clock Commands")
17372 ("I" . org-clock-in)
17373 ("O" . org-clock-out)
17374 ("Meta Data Editing")
17375 ("t" . org-todo)
17376 ("0" . (org-priority ?\ ))
17377 ("1" . (org-priority ?A))
17378 ("2" . (org-priority ?B))
17379 ("3" . (org-priority ?C))
17380 (";" . org-set-tags-command)
17381 ("e" . org-set-effort)
17382 ("Agenda Views etc")
17383 ("v" . org-agenda)
17384 ("/" . org-sparse-tree)
17385 ("Misc")
17386 ("o" . org-open-at-point)
17387 ("?" . org-speed-command-help)
17388 ("<" . (org-agenda-set-restriction-lock 'subtree))
17389 (">" . (org-agenda-remove-restriction-lock))
17391 "The default speed commands.")
17393 (defun org-print-speed-command (e)
17394 (if (> (length (car e)) 1)
17395 (progn
17396 (princ "\n")
17397 (princ (car e))
17398 (princ "\n")
17399 (princ (make-string (length (car e)) ?-))
17400 (princ "\n"))
17401 (princ (car e))
17402 (princ " ")
17403 (if (symbolp (cdr e))
17404 (princ (symbol-name (cdr e)))
17405 (prin1 (cdr e)))
17406 (princ "\n")))
17408 (defun org-speed-command-help ()
17409 "Show the available speed commands."
17410 (interactive)
17411 (if (not org-use-speed-commands)
17412 (error "Speed commands are not activated, customize `org-use-speed-commands'")
17413 (with-output-to-temp-buffer "*Help*"
17414 (princ "User-defined Speed commands\n===========================\n")
17415 (mapc 'org-print-speed-command org-speed-commands-user)
17416 (princ "\n")
17417 (princ "Built-in Speed commands\n=======================\n")
17418 (mapc 'org-print-speed-command org-speed-commands-default))
17419 (with-current-buffer "*Help*"
17420 (setq truncate-lines t))))
17422 (defun org-speed-move-safe (cmd)
17423 "Execute CMD, but make sure that the cursor always ends up in a headline.
17424 If not, return to the original position and throw an error."
17425 (interactive)
17426 (let ((pos (point)))
17427 (call-interactively cmd)
17428 (unless (and (bolp) (org-on-heading-p))
17429 (goto-char pos)
17430 (error "Boundary reached while executing %s" cmd))))
17432 (defvar org-self-insert-command-undo-counter 0)
17434 (defvar org-table-auto-blank-field) ; defined in org-table.el
17435 (defvar org-speed-command nil)
17437 (defun org-speed-command-default-hook (keys)
17438 "Hook for activating single-letter speed commands.
17439 `org-speed-commands-default' specifies a minimal command set.
17440 Use `org-speed-commands-user' for further customization."
17441 (when (or (and (bolp) (looking-at org-outline-regexp))
17442 (and (functionp org-use-speed-commands)
17443 (funcall org-use-speed-commands)))
17444 (cdr (assoc keys (append org-speed-commands-user
17445 org-speed-commands-default)))))
17447 (defun org-babel-speed-command-hook (keys)
17448 "Hook for activating single-letter code block commands."
17449 (when (and (bolp) (looking-at org-babel-src-block-regexp))
17450 (cdr (assoc keys org-babel-key-bindings))))
17452 (defcustom org-speed-command-hook
17453 '(org-speed-command-default-hook org-babel-speed-command-hook)
17454 "Hook for activating speed commands at strategic locations.
17455 Hook functions are called in sequence until a valid handler is
17456 found.
17458 Each hook takes a single argument, a user-pressed command key
17459 which is also a `self-insert-command' from the global map.
17461 Within the hook, examine the cursor position and the command key
17462 and return nil or a valid handler as appropriate. Handler could
17463 be one of an interactive command, a function, or a form.
17465 Set `org-use-speed-commands' to non-nil value to enable this
17466 hook. The default setting is `org-speed-command-default-hook'."
17467 :group 'org-structure
17468 :type 'hook)
17470 (defun org-self-insert-command (N)
17471 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
17472 If the cursor is in a table looking at whitespace, the whitespace is
17473 overwritten, and the table is not marked as requiring realignment."
17474 (interactive "p")
17475 (org-check-before-invisible-edit 'insert)
17476 (cond
17477 ((and org-use-speed-commands
17478 (setq org-speed-command
17479 (run-hook-with-args-until-success
17480 'org-speed-command-hook (this-command-keys))))
17481 (cond
17482 ((commandp org-speed-command)
17483 (setq this-command org-speed-command)
17484 (call-interactively org-speed-command))
17485 ((functionp org-speed-command)
17486 (funcall org-speed-command))
17487 ((and org-speed-command (listp org-speed-command))
17488 (eval org-speed-command))
17489 (t (let (org-use-speed-commands)
17490 (call-interactively 'org-self-insert-command)))))
17491 ((and
17492 (org-table-p)
17493 (progn
17494 ;; check if we blank the field, and if that triggers align
17495 (and (featurep 'org-table) org-table-auto-blank-field
17496 (member last-command
17497 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
17498 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
17499 ;; got extra space, this field does not determine column width
17500 (let (org-table-may-need-update) (org-table-blank-field))
17501 ;; no extra space, this field may determine column width
17502 (org-table-blank-field)))
17504 (eq N 1)
17505 (looking-at "[^|\n]* |"))
17506 (let (org-table-may-need-update)
17507 (goto-char (1- (match-end 0)))
17508 (delete-char -1)
17509 (goto-char (match-beginning 0))
17510 (self-insert-command N)))
17512 (setq org-table-may-need-update t)
17513 (self-insert-command N)
17514 (org-fix-tags-on-the-fly)
17515 (if org-self-insert-cluster-for-undo
17516 (if (not (eq last-command 'org-self-insert-command))
17517 (setq org-self-insert-command-undo-counter 1)
17518 (if (>= org-self-insert-command-undo-counter 20)
17519 (setq org-self-insert-command-undo-counter 1)
17520 (and (> org-self-insert-command-undo-counter 0)
17521 buffer-undo-list (listp buffer-undo-list)
17522 (not (cadr buffer-undo-list)) ; remove nil entry
17523 (setcdr buffer-undo-list (cddr buffer-undo-list)))
17524 (setq org-self-insert-command-undo-counter
17525 (1+ org-self-insert-command-undo-counter))))))))
17527 (defun org-check-before-invisible-edit (kind)
17528 "Check is editing if kind KIND would be dangerous with invisible text around.
17529 The detailed reaction depends on the user option `org-catch-invisible-edits'."
17530 ;; First, try to get out of here as quickly as possible, to reduce overhead
17531 (if (and org-catch-invisible-edits
17532 (or (not (boundp 'visible-mode)) (not visible-mode))
17533 (or (get-char-property (point) 'invisible)
17534 (get-char-property (max (point-min) (1- (point))) 'invisible)))
17535 ;; OK, we need to take a closer look
17536 (let* ((invisible-at-point (get-char-property (point) 'invisible))
17537 (invisible-before-point (if (bobp) nil (get-char-property
17538 (1- (point)) 'invisible)))
17539 (border-and-ok-direction
17541 ;; Check if we are acting predictably before invisible text
17542 (and invisible-at-point (not invisible-before-point)
17543 (memq kind '(insert delete-backward)))
17544 ;; Check if we are acting predictably after invisible text
17545 ;; This works not well, and I have turned it off. It seems
17546 ;; better to always show and stop after invisible text.
17547 ;; (and (not invisible-at-point) invisible-before-point
17548 ;; (memq kind '(insert delete)))
17551 (when (or (memq invisible-at-point '(outline org-hide-block))
17552 (memq invisible-before-point '(outline org-hide-block)))
17553 (if (eq org-catch-invisible-edits 'error)
17554 (error "Editing in invisible areas is prohibited - make visible first"))
17555 ;; Make the area visible
17556 (save-excursion
17557 (if invisible-before-point
17558 (goto-char (previous-single-char-property-change
17559 (point) 'invisible)))
17560 (org-cycle))
17561 (cond
17562 ((eq org-catch-invisible-edits 'show)
17563 ;; That's it, we do the edit after showing
17564 (message
17565 "Unfolding invisible region around point before editing")
17566 (sit-for 1))
17567 ((and (eq org-catch-invisible-edits 'smart)
17568 border-and-ok-direction)
17569 (message "Unfolding invisible region around point before editing"))
17571 ;; Don't do the edit, make the user repeat it in full visibility
17572 (error "Edit in invisible region aborted, repeat to confirm with text visible")))))))
17574 (defun org-fix-tags-on-the-fly ()
17575 (when (and (equal (char-after (point-at-bol)) ?*)
17576 (org-on-heading-p))
17577 (org-align-tags-here org-tags-column)))
17579 (defun org-delete-backward-char (N)
17580 "Like `delete-backward-char', insert whitespace at field end in tables.
17581 When deleting backwards, in tables this function will insert whitespace in
17582 front of the next \"|\" separator, to keep the table aligned. The table will
17583 still be marked for re-alignment if the field did fill the entire column,
17584 because, in this case the deletion might narrow the column."
17585 (interactive "p")
17586 (org-check-before-invisible-edit 'delete-backward)
17587 (if (and (org-table-p)
17588 (eq N 1)
17589 (string-match "|" (buffer-substring (point-at-bol) (point)))
17590 (looking-at ".*?|"))
17591 (let ((pos (point))
17592 (noalign (looking-at "[^|\n\r]* |"))
17593 (c org-table-may-need-update))
17594 (backward-delete-char N)
17595 (if (not overwrite-mode)
17596 (progn
17597 (skip-chars-forward "^|")
17598 (insert " ")
17599 (goto-char (1- pos))))
17600 ;; noalign: if there were two spaces at the end, this field
17601 ;; does not determine the width of the column.
17602 (if noalign (setq org-table-may-need-update c)))
17603 (backward-delete-char N)
17604 (org-fix-tags-on-the-fly)))
17606 (defun org-delete-char (N)
17607 "Like `delete-char', but insert whitespace at field end in tables.
17608 When deleting characters, in tables this function will insert whitespace in
17609 front of the next \"|\" separator, to keep the table aligned. The table will
17610 still be marked for re-alignment if the field did fill the entire column,
17611 because, in this case the deletion might narrow the column."
17612 (interactive "p")
17613 (org-check-before-invisible-edit 'delete)
17614 (if (and (org-table-p)
17615 (not (bolp))
17616 (not (= (char-after) ?|))
17617 (eq N 1))
17618 (if (looking-at ".*?|")
17619 (let ((pos (point))
17620 (noalign (looking-at "[^|\n\r]* |"))
17621 (c org-table-may-need-update))
17622 (replace-match (concat
17623 (substring (match-string 0) 1 -1)
17624 " |"))
17625 (goto-char pos)
17626 ;; noalign: if there were two spaces at the end, this field
17627 ;; does not determine the width of the column.
17628 (if noalign (setq org-table-may-need-update c)))
17629 (delete-char N))
17630 (delete-char N)
17631 (org-fix-tags-on-the-fly)))
17633 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
17634 (put 'org-self-insert-command 'delete-selection t)
17635 (put 'orgtbl-self-insert-command 'delete-selection t)
17636 (put 'org-delete-char 'delete-selection 'supersede)
17637 (put 'org-delete-backward-char 'delete-selection 'supersede)
17638 (put 'org-yank 'delete-selection 'yank)
17640 ;; Make `flyspell-mode' delay after some commands
17641 (put 'org-self-insert-command 'flyspell-delayed t)
17642 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
17643 (put 'org-delete-char 'flyspell-delayed t)
17644 (put 'org-delete-backward-char 'flyspell-delayed t)
17646 ;; Make pabbrev-mode expand after org-mode commands
17647 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
17648 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
17650 ;; How to do this: Measure non-white length of current string
17651 ;; If equal to column width, we should realign.
17653 (defun org-remap (map &rest commands)
17654 "In MAP, remap the functions given in COMMANDS.
17655 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
17656 (let (new old)
17657 (while commands
17658 (setq old (pop commands) new (pop commands))
17659 (if (fboundp 'command-remapping)
17660 (org-defkey map (vector 'remap old) new)
17661 (substitute-key-definition old new map global-map)))))
17663 (when (eq org-enable-table-editor 'optimized)
17664 ;; If the user wants maximum table support, we need to hijack
17665 ;; some standard editing functions
17666 (org-remap org-mode-map
17667 'self-insert-command 'org-self-insert-command
17668 'delete-char 'org-delete-char
17669 'delete-backward-char 'org-delete-backward-char)
17670 (org-defkey org-mode-map "|" 'org-force-self-insert))
17672 (defvar org-ctrl-c-ctrl-c-hook nil
17673 "Hook for functions attaching themselves to `C-c C-c'.
17675 This can be used to add additional functionality to the C-c C-c
17676 key which executes context-dependent commands. This hook is run
17677 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
17678 run after the last test.
17680 Each function will be called with no arguments. The function
17681 must check if the context is appropriate for it to act. If yes,
17682 it should do its thing and then return a non-nil value. If the
17683 context is wrong, just do nothing and return nil.")
17685 (defvar org-ctrl-c-ctrl-c-final-hook nil
17686 "Hook for functions attaching themselves to `C-c C-c'.
17688 This can be used to add additional functionality to the C-c C-c
17689 key which executes context-dependent commands. This hook is run
17690 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
17691 before the first test.
17693 Each function will be called with no arguments. The function
17694 must check if the context is appropriate for it to act. If yes,
17695 it should do its thing and then return a non-nil value. If the
17696 context is wrong, just do nothing and return nil.")
17698 (defvar org-tab-first-hook nil
17699 "Hook for functions to attach themselves to TAB.
17700 See `org-ctrl-c-ctrl-c-hook' for more information.
17701 This hook runs as the first action when TAB is pressed, even before
17702 `org-cycle' messes around with the `outline-regexp' to cater for
17703 inline tasks and plain list item folding.
17704 If any function in this hook returns t, any other actions that
17705 would have been caused by TAB (such as table field motion or visibility
17706 cycling) will not occur.")
17708 (defvar org-tab-after-check-for-table-hook nil
17709 "Hook for functions to attach themselves to TAB.
17710 See `org-ctrl-c-ctrl-c-hook' for more information.
17711 This hook runs after it has been established that the cursor is not in a
17712 table, but before checking if the cursor is in a headline or if global cycling
17713 should be done.
17714 If any function in this hook returns t, not other actions like visibility
17715 cycling will be done.")
17717 (defvar org-tab-after-check-for-cycling-hook nil
17718 "Hook for functions to attach themselves to TAB.
17719 See `org-ctrl-c-ctrl-c-hook' for more information.
17720 This hook runs after it has been established that not table field motion and
17721 not visibility should be done because of current context. This is probably
17722 the place where a package like yasnippets can hook in.")
17724 (defvar org-tab-before-tab-emulation-hook nil
17725 "Hook for functions to attach themselves to TAB.
17726 See `org-ctrl-c-ctrl-c-hook' for more information.
17727 This hook runs after every other options for TAB have been exhausted, but
17728 before indentation and \t insertion takes place.")
17730 (defvar org-metaleft-hook nil
17731 "Hook for functions attaching themselves to `M-left'.
17732 See `org-ctrl-c-ctrl-c-hook' for more information.")
17733 (defvar org-metaright-hook nil
17734 "Hook for functions attaching themselves to `M-right'.
17735 See `org-ctrl-c-ctrl-c-hook' for more information.")
17736 (defvar org-metaup-hook nil
17737 "Hook for functions attaching themselves to `M-up'.
17738 See `org-ctrl-c-ctrl-c-hook' for more information.")
17739 (defvar org-metadown-hook nil
17740 "Hook for functions attaching themselves to `M-down'.
17741 See `org-ctrl-c-ctrl-c-hook' for more information.")
17742 (defvar org-shiftmetaleft-hook nil
17743 "Hook for functions attaching themselves to `M-S-left'.
17744 See `org-ctrl-c-ctrl-c-hook' for more information.")
17745 (defvar org-shiftmetaright-hook nil
17746 "Hook for functions attaching themselves to `M-S-right'.
17747 See `org-ctrl-c-ctrl-c-hook' for more information.")
17748 (defvar org-shiftmetaup-hook nil
17749 "Hook for functions attaching themselves to `M-S-up'.
17750 See `org-ctrl-c-ctrl-c-hook' for more information.")
17751 (defvar org-shiftmetadown-hook nil
17752 "Hook for functions attaching themselves to `M-S-down'.
17753 See `org-ctrl-c-ctrl-c-hook' for more information.")
17754 (defvar org-metareturn-hook nil
17755 "Hook for functions attaching themselves to `M-RET'.
17756 See `org-ctrl-c-ctrl-c-hook' for more information.")
17757 (defvar org-shiftup-hook nil
17758 "Hook for functions attaching themselves to `S-up'.
17759 See `org-ctrl-c-ctrl-c-hook' for more information.")
17760 (defvar org-shiftup-final-hook nil
17761 "Hook for functions attaching themselves to `S-up'.
17762 This one runs after all other options except shift-select have been excluded.
17763 See `org-ctrl-c-ctrl-c-hook' for more information.")
17764 (defvar org-shiftdown-hook nil
17765 "Hook for functions attaching themselves to `S-down'.
17766 See `org-ctrl-c-ctrl-c-hook' for more information.")
17767 (defvar org-shiftdown-final-hook nil
17768 "Hook for functions attaching themselves to `S-down'.
17769 This one runs after all other options except shift-select have been excluded.
17770 See `org-ctrl-c-ctrl-c-hook' for more information.")
17771 (defvar org-shiftleft-hook nil
17772 "Hook for functions attaching themselves to `S-left'.
17773 See `org-ctrl-c-ctrl-c-hook' for more information.")
17774 (defvar org-shiftleft-final-hook nil
17775 "Hook for functions attaching themselves to `S-left'.
17776 This one runs after all other options except shift-select have been excluded.
17777 See `org-ctrl-c-ctrl-c-hook' for more information.")
17778 (defvar org-shiftright-hook nil
17779 "Hook for functions attaching themselves to `S-right'.
17780 See `org-ctrl-c-ctrl-c-hook' for more information.")
17781 (defvar org-shiftright-final-hook nil
17782 "Hook for functions attaching themselves to `S-right'.
17783 This one runs after all other options except shift-select have been excluded.
17784 See `org-ctrl-c-ctrl-c-hook' for more information.")
17786 (defun org-modifier-cursor-error ()
17787 "Throw an error, a modified cursor command was applied in wrong context."
17788 (error "This command is active in special context like tables, headlines or items"))
17790 (defun org-shiftselect-error ()
17791 "Throw an error because Shift-Cursor command was applied in wrong context."
17792 (if (and (boundp 'shift-select-mode) shift-select-mode)
17793 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
17794 (error "This command works only in special context like headlines or timestamps")))
17796 (defun org-call-for-shift-select (cmd)
17797 (let ((this-command-keys-shift-translated t))
17798 (call-interactively cmd)))
17800 (defun org-shifttab (&optional arg)
17801 "Global visibility cycling or move to previous table field.
17802 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
17803 on context.
17804 See the individual commands for more information."
17805 (interactive "P")
17806 (cond
17807 ((org-at-table-p) (call-interactively 'org-table-previous-field))
17808 ((integerp arg)
17809 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
17810 (message "Content view to level: %d" arg)
17811 (org-content (prefix-numeric-value arg2))
17812 (setq org-cycle-global-status 'overview)))
17813 (t (call-interactively 'org-global-cycle))))
17815 (defun org-shiftmetaleft ()
17816 "Promote subtree or delete table column.
17817 Calls `org-promote-subtree', `org-outdent-item',
17818 or `org-table-delete-column', depending on context.
17819 See the individual commands for more information."
17820 (interactive)
17821 (cond
17822 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
17823 ((org-at-table-p) (call-interactively 'org-table-delete-column))
17824 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
17825 ((org-at-item-p) (call-interactively 'org-outdent-item-tree))
17826 (t (org-modifier-cursor-error))))
17828 (defun org-shiftmetaright ()
17829 "Demote subtree or insert table column.
17830 Calls `org-demote-subtree', `org-indent-item',
17831 or `org-table-insert-column', depending on context.
17832 See the individual commands for more information."
17833 (interactive)
17834 (cond
17835 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
17836 ((org-at-table-p) (call-interactively 'org-table-insert-column))
17837 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
17838 ((org-at-item-p) (call-interactively 'org-indent-item-tree))
17839 (t (org-modifier-cursor-error))))
17841 (defun org-shiftmetaup (&optional arg)
17842 "Move subtree up or kill table row.
17843 Calls `org-move-subtree-up' or `org-table-kill-row' or
17844 `org-move-item-up' depending on context. See the individual commands
17845 for more information."
17846 (interactive "P")
17847 (cond
17848 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
17849 ((org-at-table-p) (call-interactively 'org-table-kill-row))
17850 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17851 ((org-at-item-p) (call-interactively 'org-move-item-up))
17852 (t (org-modifier-cursor-error))))
17854 (defun org-shiftmetadown (&optional arg)
17855 "Move subtree down or insert table row.
17856 Calls `org-move-subtree-down' or `org-table-insert-row' or
17857 `org-move-item-down', depending on context. See the individual
17858 commands for more information."
17859 (interactive "P")
17860 (cond
17861 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
17862 ((org-at-table-p) (call-interactively 'org-table-insert-row))
17863 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17864 ((org-at-item-p) (call-interactively 'org-move-item-down))
17865 (t (org-modifier-cursor-error))))
17867 (defsubst org-hidden-tree-error ()
17868 (error
17869 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
17871 (defun org-metaleft (&optional arg)
17872 "Promote heading or move table column to left.
17873 Calls `org-do-promote' or `org-table-move-column', depending on context.
17874 With no specific context, calls the Emacs default `backward-word'.
17875 See the individual commands for more information."
17876 (interactive "P")
17877 (cond
17878 ((run-hook-with-args-until-success 'org-metaleft-hook))
17879 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
17880 ((org-with-limited-levels
17881 (or (org-on-heading-p)
17882 (and (org-region-active-p)
17883 (save-excursion
17884 (goto-char (region-beginning))
17885 (org-on-heading-p)))))
17886 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17887 (call-interactively 'org-do-promote))
17888 ;; At an inline task.
17889 ((org-on-heading-p)
17890 (call-interactively 'org-inlinetask-promote))
17891 ((or (org-at-item-p)
17892 (and (org-region-active-p)
17893 (save-excursion
17894 (goto-char (region-beginning))
17895 (org-at-item-p))))
17896 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17897 (call-interactively 'org-outdent-item))
17898 (t (call-interactively 'backward-word))))
17900 (defun org-metaright (&optional arg)
17901 "Demote subtree or move table column to right.
17902 Calls `org-do-demote' or `org-table-move-column', depending on context.
17903 With no specific context, calls the Emacs default `forward-word'.
17904 See the individual commands for more information."
17905 (interactive "P")
17906 (cond
17907 ((run-hook-with-args-until-success 'org-metaright-hook))
17908 ((org-at-table-p) (call-interactively 'org-table-move-column))
17909 ((org-with-limited-levels
17910 (or (org-on-heading-p)
17911 (and (org-region-active-p)
17912 (save-excursion
17913 (goto-char (region-beginning))
17914 (org-on-heading-p)))))
17915 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17916 (call-interactively 'org-do-demote))
17917 ;; At an inline task.
17918 ((org-on-heading-p)
17919 (call-interactively 'org-inlinetask-demote))
17920 ((or (org-at-item-p)
17921 (and (org-region-active-p)
17922 (save-excursion
17923 (goto-char (region-beginning))
17924 (org-at-item-p))))
17925 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17926 (call-interactively 'org-indent-item))
17927 (t (call-interactively 'forward-word))))
17929 (defun org-check-for-hidden (what)
17930 "Check if there are hidden headlines/items in the current visual line.
17931 WHAT can be either `headlines' or `items'. If the current line is
17932 an outline or item heading and it has a folded subtree below it,
17933 this function returns t, nil otherwise."
17934 (let ((re (cond
17935 ((eq what 'headlines) org-outline-regexp-bol)
17936 ((eq what 'items) (org-item-beginning-re))
17937 (t (error "This should not happen"))))
17938 beg end)
17939 (save-excursion
17940 (catch 'exit
17941 (unless (org-region-active-p)
17942 (setq beg (point-at-bol))
17943 (beginning-of-line 2)
17944 (while (and (not (eobp)) ;; this is like `next-line'
17945 (get-char-property (1- (point)) 'invisible))
17946 (beginning-of-line 2))
17947 (setq end (point))
17948 (goto-char beg)
17949 (goto-char (point-at-eol))
17950 (setq end (max end (point)))
17951 (while (re-search-forward re end t)
17952 (if (get-char-property (match-beginning 0) 'invisible)
17953 (throw 'exit t))))
17954 nil))))
17956 (defun org-metaup (&optional arg)
17957 "Move subtree up or move table row up.
17958 Calls `org-move-subtree-up' or `org-table-move-row' or
17959 `org-move-item-up', depending on context. See the individual commands
17960 for more information."
17961 (interactive "P")
17962 (cond
17963 ((run-hook-with-args-until-success 'org-metaup-hook))
17964 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
17965 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17966 ((org-at-item-p) (call-interactively 'org-move-item-up))
17967 (t (transpose-lines 1) (beginning-of-line -1))))
17969 (defun org-metadown (&optional arg)
17970 "Move subtree down or move table row down.
17971 Calls `org-move-subtree-down' or `org-table-move-row' or
17972 `org-move-item-down', depending on context. See the individual
17973 commands for more information."
17974 (interactive "P")
17975 (cond
17976 ((run-hook-with-args-until-success 'org-metadown-hook))
17977 ((org-at-table-p) (call-interactively 'org-table-move-row))
17978 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17979 ((org-at-item-p) (call-interactively 'org-move-item-down))
17980 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
17982 (defun org-shiftup (&optional arg)
17983 "Increase item in timestamp or increase priority of current headline.
17984 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
17985 depending on context. See the individual commands for more information."
17986 (interactive "P")
17987 (cond
17988 ((run-hook-with-args-until-success 'org-shiftup-hook))
17989 ((and org-support-shift-select (org-region-active-p))
17990 (org-call-for-shift-select 'previous-line))
17991 ((org-at-timestamp-p t)
17992 (call-interactively (if org-edit-timestamp-down-means-later
17993 'org-timestamp-down 'org-timestamp-up)))
17994 ((and (not (eq org-support-shift-select 'always))
17995 org-enable-priority-commands
17996 (org-on-heading-p))
17997 (call-interactively 'org-priority-up))
17998 ((and (not org-support-shift-select) (org-at-item-p))
17999 (call-interactively 'org-previous-item))
18000 ((org-clocktable-try-shift 'up arg))
18001 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18002 (org-support-shift-select
18003 (org-call-for-shift-select 'previous-line))
18004 (t (org-shiftselect-error))))
18006 (defun org-shiftdown (&optional arg)
18007 "Decrease item in timestamp or decrease priority of current headline.
18008 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18009 depending on context. See the individual commands for more information."
18010 (interactive "P")
18011 (cond
18012 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18013 ((and org-support-shift-select (org-region-active-p))
18014 (org-call-for-shift-select 'next-line))
18015 ((org-at-timestamp-p t)
18016 (call-interactively (if org-edit-timestamp-down-means-later
18017 'org-timestamp-up 'org-timestamp-down)))
18018 ((and (not (eq org-support-shift-select 'always))
18019 org-enable-priority-commands
18020 (org-on-heading-p))
18021 (call-interactively 'org-priority-down))
18022 ((and (not org-support-shift-select) (org-at-item-p))
18023 (call-interactively 'org-next-item))
18024 ((org-clocktable-try-shift 'down arg))
18025 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18026 (org-support-shift-select
18027 (org-call-for-shift-select 'next-line))
18028 (t (org-shiftselect-error))))
18030 (defun org-shiftright (&optional arg)
18031 "Cycle the thing at point or in the current line, depending on context.
18032 Depending on context, this does one of the following:
18034 - switch a timestamp at point one day into the future
18035 - on a headline, switch to the next TODO keyword.
18036 - on an item, switch entire list to the next bullet type
18037 - on a property line, switch to the next allowed value
18038 - on a clocktable definition line, move time block into the future"
18039 (interactive "P")
18040 (cond
18041 ((run-hook-with-args-until-success 'org-shiftright-hook))
18042 ((and org-support-shift-select (org-region-active-p))
18043 (org-call-for-shift-select 'forward-char))
18044 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18045 ((and (not (eq org-support-shift-select 'always))
18046 (org-on-heading-p))
18047 (let ((org-inhibit-logging
18048 (not org-treat-S-cursor-todo-selection-as-state-change))
18049 (org-inhibit-blocking
18050 (not org-treat-S-cursor-todo-selection-as-state-change)))
18051 (org-call-with-arg 'org-todo 'right)))
18052 ((or (and org-support-shift-select
18053 (not (eq org-support-shift-select 'always))
18054 (org-at-item-bullet-p))
18055 (and (not org-support-shift-select) (org-at-item-p)))
18056 (org-call-with-arg 'org-cycle-list-bullet nil))
18057 ((and (not (eq org-support-shift-select 'always))
18058 (org-at-property-p))
18059 (call-interactively 'org-property-next-allowed-value))
18060 ((org-clocktable-try-shift 'right arg))
18061 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18062 (org-support-shift-select
18063 (org-call-for-shift-select 'forward-char))
18064 (t (org-shiftselect-error))))
18066 (defun org-shiftleft (&optional arg)
18067 "Cycle the thing at point or in the current line, depending on context.
18068 Depending on context, this does one of the following:
18070 - switch a timestamp at point one day into the past
18071 - on a headline, switch to the previous TODO keyword.
18072 - on an item, switch entire list to the previous bullet type
18073 - on a property line, switch to the previous allowed value
18074 - on a clocktable definition line, move time block into the past"
18075 (interactive "P")
18076 (cond
18077 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18078 ((and org-support-shift-select (org-region-active-p))
18079 (org-call-for-shift-select 'backward-char))
18080 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18081 ((and (not (eq org-support-shift-select 'always))
18082 (org-on-heading-p))
18083 (let ((org-inhibit-logging
18084 (not org-treat-S-cursor-todo-selection-as-state-change))
18085 (org-inhibit-blocking
18086 (not org-treat-S-cursor-todo-selection-as-state-change)))
18087 (org-call-with-arg 'org-todo 'left)))
18088 ((or (and org-support-shift-select
18089 (not (eq org-support-shift-select 'always))
18090 (org-at-item-bullet-p))
18091 (and (not org-support-shift-select) (org-at-item-p)))
18092 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18093 ((and (not (eq org-support-shift-select 'always))
18094 (org-at-property-p))
18095 (call-interactively 'org-property-previous-allowed-value))
18096 ((org-clocktable-try-shift 'left arg))
18097 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18098 (org-support-shift-select
18099 (org-call-for-shift-select 'backward-char))
18100 (t (org-shiftselect-error))))
18102 (defun org-shiftcontrolright ()
18103 "Switch to next TODO set."
18104 (interactive)
18105 (cond
18106 ((and org-support-shift-select (org-region-active-p))
18107 (org-call-for-shift-select 'forward-word))
18108 ((and (not (eq org-support-shift-select 'always))
18109 (org-on-heading-p))
18110 (org-call-with-arg 'org-todo 'nextset))
18111 (org-support-shift-select
18112 (org-call-for-shift-select 'forward-word))
18113 (t (org-shiftselect-error))))
18115 (defun org-shiftcontrolleft ()
18116 "Switch to previous TODO set."
18117 (interactive)
18118 (cond
18119 ((and org-support-shift-select (org-region-active-p))
18120 (org-call-for-shift-select 'backward-word))
18121 ((and (not (eq org-support-shift-select 'always))
18122 (org-on-heading-p))
18123 (org-call-with-arg 'org-todo 'previousset))
18124 (org-support-shift-select
18125 (org-call-for-shift-select 'backward-word))
18126 (t (org-shiftselect-error))))
18128 (defun org-shiftcontrolup ()
18129 "Change timestamps synchronously up in CLOCK log lines."
18130 (interactive)
18131 (cond ((and (not org-support-shift-select)
18132 (org-at-clock-log-p)
18133 (org-at-timestamp-p t))
18134 (org-clock-timestamps-up))
18135 (t (org-shiftselect-error))))
18137 (defun org-shiftcontroldown ()
18138 "Change timestamps synchronously down in CLOCK log lines."
18139 (interactive)
18140 (cond ((and (not org-support-shift-select)
18141 (org-at-clock-log-p)
18142 (org-at-timestamp-p t))
18143 (org-clock-timestamps-down))
18144 (t (org-shiftselect-error))))
18146 (defun org-ctrl-c-ret ()
18147 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18148 (interactive)
18149 (cond
18150 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18151 (t (call-interactively 'org-insert-heading))))
18153 (defun org-find-visible ()
18154 (let ((s (point)))
18155 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18156 (get-char-property s 'invisible)))
18158 (defun org-find-invisible ()
18159 (let ((s (point)))
18160 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18161 (not (get-char-property s 'invisible))))
18164 (defun org-copy-visible (beg end)
18165 "Copy the visible parts of the region."
18166 (interactive "r")
18167 (let (snippets s)
18168 (save-excursion
18169 (save-restriction
18170 (narrow-to-region beg end)
18171 (setq s (goto-char (point-min)))
18172 (while (not (= (point) (point-max)))
18173 (goto-char (org-find-invisible))
18174 (push (buffer-substring s (point)) snippets)
18175 (setq s (goto-char (org-find-visible))))))
18176 (kill-new (apply 'concat (nreverse snippets)))))
18178 (defun org-copy-special ()
18179 "Copy region in table or copy current subtree.
18180 Calls `org-table-copy' or `org-copy-subtree', depending on context.
18181 See the individual commands for more information."
18182 (interactive)
18183 (call-interactively
18184 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
18186 (defun org-cut-special ()
18187 "Cut region in table or cut current subtree.
18188 Calls `org-table-copy' or `org-cut-subtree', depending on context.
18189 See the individual commands for more information."
18190 (interactive)
18191 (call-interactively
18192 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
18194 (defun org-paste-special (arg)
18195 "Paste rectangular region into table, or past subtree relative to level.
18196 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
18197 See the individual commands for more information."
18198 (interactive "P")
18199 (if (org-at-table-p)
18200 (org-table-paste-rectangle)
18201 (org-paste-subtree arg)))
18203 (defun org-edit-special (&optional arg)
18204 "Call a special editor for the stuff at point.
18205 When at a table, call the formula editor with `org-table-edit-formulas'.
18206 When at the first line of an src example, call `org-edit-src-code'.
18207 When in an #+include line, visit the include file. Otherwise call
18208 `ffap' to visit the file at point."
18209 (interactive)
18210 ;; possibly prep session before editing source
18211 (when arg
18212 (let* ((info (org-babel-get-src-block-info))
18213 (lang (nth 0 info))
18214 (params (nth 2 info))
18215 (session (cdr (assoc :session params))))
18216 (when (and info session) ;; we are in a source-code block with a session
18217 (funcall
18218 (intern (concat "org-babel-prep-session:" lang)) session params))))
18219 (cond ;; proceed with `org-edit-special'
18220 ((save-excursion
18221 (beginning-of-line 1)
18222 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
18223 (find-file (org-trim (match-string 1))))
18224 ((org-edit-src-code))
18225 ((org-edit-fixed-width-region))
18226 ((org-at-table.el-p)
18227 (org-edit-src-code))
18228 ((or (org-at-table-p)
18229 (save-excursion
18230 (beginning-of-line 1)
18231 (looking-at "[ \t]*#\\+TBLFM:")))
18232 (call-interactively 'org-table-edit-formulas))
18233 (t (call-interactively 'ffap))))
18235 (defvar org-table-coordinate-overlays) ; defined in org-table.el
18236 (defun org-ctrl-c-ctrl-c (&optional arg)
18237 "Set tags in headline, or update according to changed information at point.
18239 This command does many different things, depending on context:
18241 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
18242 this is what we do.
18244 - If the cursor is on a statistics cookie, update it.
18246 - If the cursor is in a headline, prompt for tags and insert them
18247 into the current line, aligned to `org-tags-column'. When called
18248 with prefix arg, realign all tags in the current buffer.
18250 - If the cursor is in one of the special #+KEYWORD lines, this
18251 triggers scanning the buffer for these lines and updating the
18252 information.
18254 - If the cursor is inside a table, realign the table. This command
18255 works even if the automatic table editor has been turned off.
18257 - If the cursor is on a #+TBLFM line, re-apply the formulas to
18258 the entire table.
18260 - If the cursor is at a footnote reference or definition, jump to
18261 the corresponding definition or references, respectively.
18263 - If the cursor is a the beginning of a dynamic block, update it.
18265 - If the current buffer is a capture buffer, close note and file it.
18267 - If the cursor is on a <<<target>>>, update radio targets and
18268 corresponding links in this buffer.
18270 - If the cursor is on a numbered item in a plain list, renumber the
18271 ordered list.
18273 - If the cursor is on a checkbox, toggle it.
18275 - If the cursor is on a code block, evaluate it. The variable
18276 `org-confirm-babel-evaluate' can be used to control prompting
18277 before code block evaluation, by default every code block
18278 evaluation requires confirmation. Code block evaluation can be
18279 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
18280 (interactive "P")
18281 (let ((org-enable-table-editor t))
18282 (cond
18283 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
18284 org-occur-highlights
18285 org-latex-fragment-image-overlays)
18286 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
18287 (org-remove-occur-highlights)
18288 (org-remove-latex-fragment-image-overlays)
18289 (message "Temporary highlights/overlays removed from current buffer"))
18290 ((and (local-variable-p 'org-finish-function (current-buffer))
18291 (fboundp org-finish-function))
18292 (funcall org-finish-function))
18293 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
18294 ((org-in-regexp org-ts-regexp-both)
18295 (org-timestamp-change 0 'day))
18296 ((or (looking-at org-property-start-re)
18297 (org-at-property-p))
18298 (call-interactively 'org-property-action))
18299 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
18300 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
18301 (or (org-on-heading-p) (org-at-item-p)))
18302 (call-interactively 'org-update-statistics-cookies))
18303 ((org-on-heading-p) (call-interactively 'org-set-tags))
18304 ((org-at-table.el-p)
18305 (message "Use C-c ' to edit table.el tables"))
18306 ((org-at-table-p)
18307 (org-table-maybe-eval-formula)
18308 (if arg
18309 (call-interactively 'org-table-recalculate)
18310 (org-table-maybe-recalculate-line))
18311 (call-interactively 'org-table-align)
18312 (orgtbl-send-table 'maybe))
18313 ((or (org-footnote-at-reference-p)
18314 (org-footnote-at-definition-p))
18315 (call-interactively 'org-footnote-action))
18316 ((org-at-item-checkbox-p)
18317 ;; Cursor at a checkbox: repair list and update checkboxes. Send
18318 ;; list only if at top item.
18319 (let* ((cbox (match-string 1))
18320 (struct (org-list-struct))
18321 (old-struct (copy-tree struct))
18322 (parents (org-list-parents-alist struct))
18323 (orderedp (org-entry-get nil "ORDERED"))
18324 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18325 block-item)
18326 ;; Use a light version of `org-toggle-checkbox' to avoid
18327 ;; computing list structure twice.
18328 (org-list-set-checkbox (point-at-bol) struct
18329 (cond
18330 ((equal arg '(16)) "[-]")
18331 ((equal arg '(4)) nil)
18332 ((equal "[X]" cbox) "[ ]")
18333 (t "[X]")))
18334 ;; Replicate `org-list-write-struct', while grabbing a return
18335 ;; value from `org-list-struct-fix-box'.
18336 (org-list-struct-fix-ind struct parents 2)
18337 (org-list-struct-fix-item-end struct)
18338 (let ((prevs (org-list-prevs-alist struct)))
18339 (org-list-struct-fix-bul struct prevs)
18340 (org-list-struct-fix-ind struct parents)
18341 (setq block-item
18342 (org-list-struct-fix-box struct parents prevs orderedp)))
18343 (org-list-struct-apply-struct struct old-struct)
18344 (org-update-checkbox-count-maybe)
18345 (when block-item
18346 (message
18347 "Checkboxes were removed due to unchecked box at line %d"
18348 (org-current-line block-item)))
18349 (when firstp (org-list-send-list 'maybe))))
18350 ((org-at-item-p)
18351 ;; Cursor at an item: repair list. Do checkbox related actions
18352 ;; only if function was called with an argument. Send list only
18353 ;; if at top item.
18354 (let* ((struct (org-list-struct))
18355 (firstp (= (org-list-get-top-point struct) (point-at-bol))))
18356 (when arg (org-list-set-checkbox (point-at-bol) struct "[ ]"))
18357 (org-list-write-struct struct (org-list-parents-alist struct))
18358 (when arg (org-update-checkbox-count-maybe))
18359 (when firstp (org-list-send-list 'maybe))))
18360 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
18361 ;; Dynamic block
18362 (beginning-of-line 1)
18363 (save-excursion (org-update-dblock)))
18364 ((save-excursion
18365 (beginning-of-line 1)
18366 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
18367 (cond
18368 ((equal (match-string 1) "TBLFM")
18369 ;; Recalculate the table before this line
18370 (save-excursion
18371 (beginning-of-line 1)
18372 (skip-chars-backward " \r\n\t")
18373 (if (org-at-table-p)
18374 (org-call-with-arg 'org-table-recalculate (or arg t)))))
18376 (let ((org-inhibit-startup-visibility-stuff t)
18377 (org-startup-align-all-tables nil))
18378 (when (boundp 'org-table-coordinate-overlays)
18379 (mapc 'delete-overlay org-table-coordinate-overlays)
18380 (setq org-table-coordinate-overlays nil))
18381 (org-save-outline-visibility 'use-markers (org-mode-restart)))
18382 (message "Local setup has been refreshed"))))
18383 ((org-clock-update-time-maybe))
18385 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
18386 (error "C-c C-c can do nothing useful at this location"))))))
18388 (defun org-mode-restart ()
18389 "Restart Org-mode, to scan again for special lines.
18390 Also updates the keyword regular expressions."
18391 (interactive)
18392 (org-mode)
18393 (message "Org-mode restarted"))
18395 (defun org-kill-note-or-show-branches ()
18396 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
18397 (interactive)
18398 (if (not org-finish-function)
18399 (progn
18400 (hide-subtree)
18401 (call-interactively 'show-branches))
18402 (let ((org-note-abort t))
18403 (funcall org-finish-function))))
18405 (defun org-return (&optional indent)
18406 "Goto next table row or insert a newline.
18407 Calls `org-table-next-row' or `newline', depending on context.
18408 See the individual commands for more information."
18409 (interactive)
18410 (cond
18411 ((bobp) (if indent (newline-and-indent) (newline)))
18412 ((org-at-table-p)
18413 (org-table-justify-field-maybe)
18414 (call-interactively 'org-table-next-row))
18415 ;; when `newline-and-indent' is called within a list, make sure
18416 ;; text moved stays inside the item.
18417 ((and (org-in-item-p) indent)
18418 (if (and (org-at-item-p) (>= (point) (match-end 0)))
18419 (progn
18420 (save-match-data (newline))
18421 (org-indent-line-to (length (match-string 0))))
18422 (let ((ind (org-get-indentation)))
18423 (newline)
18424 (if (org-looking-back org-list-end-re)
18425 (org-indent-line-function)
18426 (org-indent-line-to ind)))))
18427 ((and org-return-follows-link
18428 (let ((tprop (get-text-property (point) 'face)))
18429 (or (eq tprop 'org-link)
18430 (and (listp tprop) (memq 'org-link tprop)))))
18431 (call-interactively 'org-open-at-point))
18432 ((and (org-at-heading-p)
18433 (looking-at
18434 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
18435 (org-show-entry)
18436 (end-of-line 1)
18437 (newline))
18438 (t (if indent (newline-and-indent) (newline)))))
18440 (defun org-return-indent ()
18441 "Goto next table row or insert a newline and indent.
18442 Calls `org-table-next-row' or `newline-and-indent', depending on
18443 context. See the individual commands for more information."
18444 (interactive)
18445 (org-return t))
18447 (defun org-ctrl-c-star ()
18448 "Compute table, or change heading status of lines.
18449 Calls `org-table-recalculate' or `org-toggle-heading',
18450 depending on context."
18451 (interactive)
18452 (cond
18453 ((org-at-table-p)
18454 (call-interactively 'org-table-recalculate))
18456 ;; Convert all lines in region to list items
18457 (call-interactively 'org-toggle-heading))))
18459 (defun org-ctrl-c-minus ()
18460 "Insert separator line in table or modify bullet status of line.
18461 Also turns a plain line or a region of lines into list items.
18462 Calls `org-table-insert-hline', `org-toggle-item', or
18463 `org-cycle-list-bullet', depending on context."
18464 (interactive)
18465 (cond
18466 ((org-at-table-p)
18467 (call-interactively 'org-table-insert-hline))
18468 ((org-region-active-p)
18469 (call-interactively 'org-toggle-item))
18470 ((org-in-item-p)
18471 (call-interactively 'org-cycle-list-bullet))
18473 (call-interactively 'org-toggle-item))))
18475 (defun org-toggle-item (arg)
18476 "Convert headings or normal lines to items, items to normal lines.
18477 If there is no active region, only the current line is considered.
18479 If the first non blank line in the region is an headline, convert
18480 all headlines to items, shifting text accordingly.
18482 If it is an item, convert all items to normal lines.
18484 If it is normal text, change region into an item. With a prefix
18485 argument ARG, change each line in region into an item."
18486 (interactive "P")
18487 (let ((shift-text
18488 (function
18489 ;; Shift text in current section to IND, from point to END.
18490 ;; The function leaves point to END line.
18491 (lambda (ind end)
18492 (let ((min-i 1000) (end (copy-marker end)))
18493 ;; First determine the minimum indentation (MIN-I) of
18494 ;; the text.
18495 (save-excursion
18496 (catch 'exit
18497 (while (< (point) end)
18498 (let ((i (org-get-indentation)))
18499 (cond
18500 ;; Skip blank lines and inline tasks.
18501 ((looking-at "^[ \t]*$"))
18502 ((looking-at org-outline-regexp-bol))
18503 ;; We can't find less than 0 indentation.
18504 ((zerop i) (throw 'exit (setq min-i 0)))
18505 ((< i min-i) (setq min-i i))))
18506 (forward-line))))
18507 ;; Then indent each line so that a line indented to
18508 ;; MIN-I becomes indented to IND. Ignore blank lines
18509 ;; and inline tasks in the process.
18510 (let ((delta (- ind min-i)))
18511 (while (< (point) end)
18512 (unless (or (looking-at "^[ \t]*$")
18513 (looking-at org-outline-regexp-bol))
18514 (org-indent-line-to (+ (org-get-indentation) delta)))
18515 (forward-line)))))))
18516 (skip-blanks
18517 (function
18518 ;; Return beginning of first non-blank line, starting from
18519 ;; line at POS.
18520 (lambda (pos)
18521 (save-excursion
18522 (goto-char pos)
18523 (skip-chars-forward " \r\t\n")
18524 (point-at-bol)))))
18525 beg end)
18526 ;; Determine boundaries of changes.
18527 (if (org-region-active-p)
18528 (setq beg (funcall skip-blanks (region-beginning))
18529 end (copy-marker (region-end)))
18530 (setq beg (funcall skip-blanks (point-at-bol))
18531 end (copy-marker (point-at-eol))))
18532 ;; Depending on the starting line, choose an action on the text
18533 ;; between BEG and END.
18534 (org-with-limited-levels
18535 (save-excursion
18536 (goto-char beg)
18537 (cond
18538 ;; Case 1. Start at an item: de-itemize. Note that it only
18539 ;; happens when a region is active: `org-ctrl-c-minus'
18540 ;; would call `org-cycle-list-bullet' otherwise.
18541 ((org-at-item-p)
18542 (while (< (point) end)
18543 (when (org-at-item-p)
18544 (skip-chars-forward " \t")
18545 (delete-region (point) (match-end 0)))
18546 (forward-line)))
18547 ;; Case 2. Start at an heading: convert to items.
18548 ((org-on-heading-p)
18549 (let* ((bul (org-list-bullet-string "-"))
18550 (bul-len (length bul))
18551 ;; Indentation of the first heading. It should be
18552 ;; relative to the indentation of its parent, if any.
18553 (start-ind (save-excursion
18554 (cond
18555 ((not org-adapt-indentation) 0)
18556 ((not (outline-previous-heading)) 0)
18557 (t (length (match-string 0))))))
18558 ;; Level of first heading. Further headings will be
18559 ;; compared to it to determine hierarchy in the list.
18560 (ref-level (org-reduced-level (org-outline-level))))
18561 (while (< (point) end)
18562 (let* ((level (org-reduced-level (org-outline-level)))
18563 (delta (max 0 (- level ref-level))))
18564 ;; If current headline is less indented than the first
18565 ;; one, set it as reference, in order to preserve
18566 ;; subtrees.
18567 (when (< level ref-level) (setq ref-level level))
18568 (replace-match bul t t)
18569 (org-indent-line-to (+ start-ind (* delta bul-len)))
18570 ;; Ensure all text down to END (or SECTION-END) belongs
18571 ;; to the newly created item.
18572 (let ((section-end (save-excursion
18573 (or (outline-next-heading) (point)))))
18574 (forward-line)
18575 (funcall shift-text
18576 (+ start-ind (* (1+ delta) bul-len))
18577 (min end section-end)))))))
18578 ;; Case 3. Normal line with ARG: turn each non-item line into
18579 ;; an item.
18580 (arg
18581 (while (< (point) end)
18582 (unless (or (org-on-heading-p) (org-at-item-p))
18583 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
18584 (replace-match
18585 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
18586 (forward-line)))
18587 ;; Case 4. Normal line without ARG: make the first line of
18588 ;; region an item, and shift indentation of others
18589 ;; lines to set them as item's body.
18590 (t (let* ((bul (org-list-bullet-string "-"))
18591 (bul-len (length bul))
18592 (ref-ind (org-get-indentation)))
18593 (skip-chars-forward " \t")
18594 (insert bul)
18595 (forward-line)
18596 (while (< (point) end)
18597 ;; Ensure that lines less indented than first one
18598 ;; still get included in item body.
18599 (funcall shift-text
18600 (+ ref-ind bul-len)
18601 (min end (save-excursion (or (outline-next-heading)
18602 (point)))))
18603 (forward-line)))))))))
18605 (defun org-toggle-heading (&optional nstars)
18606 "Convert headings to normal text, or items or text to headings.
18607 If there is no active region, only the current line is considered.
18609 If the first non blank line is an headline, remove the stars from
18610 all headlines in the region.
18612 If it is a plain list item, turn all plain list items into headings.
18614 If it is a normal line, turn each and every normal line (i.e. not
18615 an heading or an item) in the region into a heading.
18617 When converting a line into a heading, the number of stars is chosen
18618 such that the lines become children of the current entry. However,
18619 when a prefix argument is given, its value determines the number of
18620 stars to add."
18621 (interactive "P")
18622 (let ((skip-blanks
18623 (function
18624 ;; Return beginning of first non-blank line, starting from
18625 ;; line at POS.
18626 (lambda (pos)
18627 (save-excursion
18628 (goto-char pos)
18629 (skip-chars-forward " \r\t\n")
18630 (point-at-bol)))))
18631 beg end)
18632 ;; Determine boundaries of changes. If region ends at a bol, do
18633 ;; not consider the last line to be in the region.
18634 (if (org-region-active-p)
18635 (setq beg (funcall skip-blanks (region-beginning))
18636 end (copy-marker (save-excursion
18637 (goto-char (region-end))
18638 (if (bolp) (point) (point-at-eol)))))
18639 (setq beg (funcall skip-blanks (point-at-bol))
18640 end (copy-marker (point-at-eol))))
18641 ;; Ensure inline tasks don't count as headings.
18642 (org-with-limited-levels
18643 (save-excursion
18644 (goto-char beg)
18645 (cond
18646 ;; Case 1. Started at an heading: de-star headings.
18647 ((org-on-heading-p)
18648 (while (< (point) end)
18649 (when (org-on-heading-p t)
18650 (looking-at org-outline-regexp) (replace-match ""))
18651 (forward-line)))
18652 ;; Case 2. Started at an item: change items into headlines.
18653 ;; One star will be added by `org-list-to-subtree'.
18654 ((org-at-item-p)
18655 (let* ((stars (make-string
18656 (if nstars
18657 ;; subtract the star that will be added again by
18658 ;; `org-list-to-subtree'
18659 (1- (prefix-numeric-value current-prefix-arg))
18660 (or (org-current-level) 0))
18661 ?*))
18662 (add-stars
18663 (cond (nstars "") ; stars from prefix only
18664 ((equal stars "") "") ; before first heading
18665 (org-odd-levels-only "*") ; inside heading, odd
18666 (t "")))) ; inside heading, oddeven
18667 (while (< (point) end)
18668 (when (org-at-item-p)
18669 ;; Pay attention to cases when region ends before list.
18670 (let* ((struct (org-list-struct))
18671 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
18672 (save-restriction
18673 (narrow-to-region (point) list-end)
18674 (insert
18675 (org-list-to-subtree
18676 (org-list-parse-list t)
18677 '(:istart (concat stars add-stars (funcall get-stars depth))
18678 :icount (concat stars add-stars (funcall get-stars depth))))))))
18679 (forward-line))))
18680 ;; Case 3. Started at normal text: make every line an heading,
18681 ;; skipping headlines and items.
18682 (t (let* ((stars (make-string
18683 (if nstars
18684 (prefix-numeric-value current-prefix-arg)
18685 (or (org-current-level) 0))
18686 ?*))
18687 (add-stars
18688 (cond (nstars "") ; stars from prefix only
18689 ((equal stars "") "*") ; before first heading
18690 (org-odd-levels-only "**") ; inside heading, odd
18691 (t "*"))) ; inside heading, oddeven
18692 (rpl (concat stars add-stars " ")))
18693 (while (< (point) end)
18694 (when (and (not (org-on-heading-p)) (not (org-at-item-p))
18695 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
18696 (replace-match (concat rpl (match-string 2))))
18697 (forward-line)))))))))
18699 (defun org-meta-return (&optional arg)
18700 "Insert a new heading or wrap a region in a table.
18701 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
18702 See the individual commands for more information."
18703 (interactive "P")
18704 (cond
18705 ((run-hook-with-args-until-success 'org-metareturn-hook))
18706 ((org-at-table-p)
18707 (call-interactively 'org-table-wrap-region))
18708 (t (call-interactively 'org-insert-heading))))
18710 ;;; Menu entries
18712 ;; Define the Org-mode menus
18713 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
18714 '("Tbl"
18715 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
18716 ["Next Field" org-cycle (org-at-table-p)]
18717 ["Previous Field" org-shifttab (org-at-table-p)]
18718 ["Next Row" org-return (org-at-table-p)]
18719 "--"
18720 ["Blank Field" org-table-blank-field (org-at-table-p)]
18721 ["Edit Field" org-table-edit-field (org-at-table-p)]
18722 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
18723 "--"
18724 ("Column"
18725 ["Move Column Left" org-metaleft (org-at-table-p)]
18726 ["Move Column Right" org-metaright (org-at-table-p)]
18727 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
18728 ["Insert Column" org-shiftmetaright (org-at-table-p)])
18729 ("Row"
18730 ["Move Row Up" org-metaup (org-at-table-p)]
18731 ["Move Row Down" org-metadown (org-at-table-p)]
18732 ["Delete Row" org-shiftmetaup (org-at-table-p)]
18733 ["Insert Row" org-shiftmetadown (org-at-table-p)]
18734 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
18735 "--"
18736 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
18737 ("Rectangle"
18738 ["Copy Rectangle" org-copy-special (org-at-table-p)]
18739 ["Cut Rectangle" org-cut-special (org-at-table-p)]
18740 ["Paste Rectangle" org-paste-special (org-at-table-p)]
18741 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
18742 "--"
18743 ("Calculate"
18744 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
18745 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
18746 ["Edit Formulas" org-edit-special (org-at-table-p)]
18747 "--"
18748 ["Recalculate line" org-table-recalculate (org-at-table-p)]
18749 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
18750 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
18751 "--"
18752 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
18753 "--"
18754 ["Sum Column/Rectangle" org-table-sum
18755 (or (org-at-table-p) (org-region-active-p))]
18756 ["Which Column?" org-table-current-column (org-at-table-p)])
18757 ["Debug Formulas"
18758 org-table-toggle-formula-debugger
18759 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
18760 ["Show Col/Row Numbers"
18761 org-table-toggle-coordinate-overlays
18762 :style toggle
18763 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
18764 "--"
18765 ["Create" org-table-create (and (not (org-at-table-p))
18766 org-enable-table-editor)]
18767 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
18768 ["Import from File" org-table-import (not (org-at-table-p))]
18769 ["Export to File" org-table-export (org-at-table-p)]
18770 "--"
18771 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
18773 (easy-menu-define org-org-menu org-mode-map "Org menu"
18774 '("Org"
18775 ("Show/Hide"
18776 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
18777 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
18778 ["Sparse Tree..." org-sparse-tree t]
18779 ["Reveal Context" org-reveal t]
18780 ["Show All" show-all t]
18781 "--"
18782 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
18783 "--"
18784 ["New Heading" org-insert-heading t]
18785 ("Navigate Headings"
18786 ["Up" outline-up-heading t]
18787 ["Next" outline-next-visible-heading t]
18788 ["Previous" outline-previous-visible-heading t]
18789 ["Next Same Level" outline-forward-same-level t]
18790 ["Previous Same Level" outline-backward-same-level t]
18791 "--"
18792 ["Jump" org-goto t])
18793 ("Edit Structure"
18794 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
18795 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
18796 "--"
18797 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
18798 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
18799 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
18800 "--"
18801 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
18802 "--"
18803 ["Copy visible text" org-copy-visible t]
18804 "--"
18805 ["Promote Heading" org-metaleft (not (org-at-table-p))]
18806 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
18807 ["Demote Heading" org-metaright (not (org-at-table-p))]
18808 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
18809 "--"
18810 ["Sort Region/Children" org-sort (not (org-at-table-p))]
18811 "--"
18812 ["Convert to odd levels" org-convert-to-odd-levels t]
18813 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
18814 ("Editing"
18815 ["Emphasis..." org-emphasize t]
18816 ["Edit Source Example" org-edit-special t]
18817 "--"
18818 ["Footnote new/jump" org-footnote-action t]
18819 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
18820 ("Archive"
18821 ["Archive (default method)" org-archive-subtree-default t]
18822 "--"
18823 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
18824 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
18825 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
18827 "--"
18828 ("Hyperlinks"
18829 ["Store Link (Global)" org-store-link t]
18830 ["Find existing link to here" org-occur-link-in-agenda-files t]
18831 ["Insert Link" org-insert-link t]
18832 ["Follow Link" org-open-at-point t]
18833 "--"
18834 ["Next link" org-next-link t]
18835 ["Previous link" org-previous-link t]
18836 "--"
18837 ["Descriptive Links"
18838 org-toggle-link-display
18839 :style radio
18840 :selected org-descriptive-links
18842 ["Literal Links"
18843 org-toggle-link-display
18844 :style radio
18845 :selected (not org-descriptive-links)])
18846 "--"
18847 ("TODO Lists"
18848 ["TODO/DONE/-" org-todo t]
18849 ("Select keyword"
18850 ["Next keyword" org-shiftright (org-on-heading-p)]
18851 ["Previous keyword" org-shiftleft (org-on-heading-p)]
18852 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
18853 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
18854 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
18855 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
18856 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
18857 "--"
18858 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
18859 :selected org-enforce-todo-dependencies :style toggle :active t]
18860 "Settings for tree at point"
18861 ["Do Children sequentially" org-toggle-ordered-property :style radio
18862 :selected (org-entry-get nil "ORDERED")
18863 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
18864 ["Do Children parallel" org-toggle-ordered-property :style radio
18865 :selected (not (org-entry-get nil "ORDERED"))
18866 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
18867 "--"
18868 ["Set Priority" org-priority t]
18869 ["Priority Up" org-shiftup t]
18870 ["Priority Down" org-shiftdown t]
18871 "--"
18872 ["Get news from all feeds" org-feed-update-all t]
18873 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
18874 ["Customize feeds" (customize-variable 'org-feed-alist) t])
18875 ("TAGS and Properties"
18876 ["Set Tags" org-set-tags-command t]
18877 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
18878 "--"
18879 ["Set property" org-set-property t]
18880 ["Column view of properties" org-columns t]
18881 ["Insert Column View DBlock" org-insert-columns-dblock t])
18882 ("Dates and Scheduling"
18883 ["Timestamp" org-time-stamp t]
18884 ["Timestamp (inactive)" org-time-stamp-inactive t]
18885 ("Change Date"
18886 ["1 Day Later" org-shiftright t]
18887 ["1 Day Earlier" org-shiftleft t]
18888 ["1 ... Later" org-shiftup t]
18889 ["1 ... Earlier" org-shiftdown t])
18890 ["Compute Time Range" org-evaluate-time-range t]
18891 ["Schedule Item" org-schedule t]
18892 ["Deadline" org-deadline t]
18893 "--"
18894 ["Custom time format" org-toggle-time-stamp-overlays
18895 :style radio :selected org-display-custom-times]
18896 "--"
18897 ["Goto Calendar" org-goto-calendar t]
18898 ["Date from Calendar" org-date-from-calendar t]
18899 "--"
18900 ["Start/Restart Timer" org-timer-start t]
18901 ["Pause/Continue Timer" org-timer-pause-or-continue t]
18902 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
18903 ["Insert Timer String" org-timer t]
18904 ["Insert Timer Item" org-timer-item t])
18905 ("Logging work"
18906 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
18907 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
18908 ["Clock out" org-clock-out t]
18909 ["Clock cancel" org-clock-cancel t]
18910 "--"
18911 ["Mark as default task" org-clock-mark-default-task t]
18912 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
18913 ["Goto running clock" org-clock-goto t]
18914 "--"
18915 ["Display times" org-clock-display t]
18916 ["Create clock table" org-clock-report t]
18917 "--"
18918 ["Record DONE time"
18919 (progn (setq org-log-done (not org-log-done))
18920 (message "Switching to %s will %s record a timestamp"
18921 (car org-done-keywords)
18922 (if org-log-done "automatically" "not")))
18923 :style toggle :selected org-log-done])
18924 "--"
18925 ["Agenda Command..." org-agenda t]
18926 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
18927 ("File List for Agenda")
18928 ("Special views current file"
18929 ["TODO Tree" org-show-todo-tree t]
18930 ["Check Deadlines" org-check-deadlines t]
18931 ["Timeline" org-timeline t]
18932 ["Tags/Property tree" org-match-sparse-tree t])
18933 "--"
18934 ["Export/Publish..." org-export t]
18935 ("LaTeX"
18936 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
18937 :selected org-cdlatex-mode]
18938 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
18939 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
18940 ["Modify math symbol" org-cdlatex-math-modify
18941 (org-inside-LaTeX-fragment-p)]
18942 ["Insert citation" org-reftex-citation t]
18943 "--"
18944 ["Template for BEAMER" org-insert-beamer-options-template t])
18945 "--"
18946 ("MobileOrg"
18947 ["Push Files and Views" org-mobile-push t]
18948 ["Get Captured and Flagged" org-mobile-pull t]
18949 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
18950 "--"
18951 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
18952 "--"
18953 ("Documentation"
18954 ["Show Version" org-version t]
18955 ["Info Documentation" org-info t])
18956 ("Customize"
18957 ["Browse Org Group" org-customize t]
18958 "--"
18959 ["Expand This Menu" org-create-customize-menu
18960 (fboundp 'customize-menu-create)])
18961 ["Send bug report" org-submit-bug-report t]
18962 "--"
18963 ("Refresh/Reload"
18964 ["Refresh setup current buffer" org-mode-restart t]
18965 ["Reload Org (after update)" org-reload t]
18966 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
18969 (defun org-info (&optional node)
18970 "Read documentation for Org-mode in the info system.
18971 With optional NODE, go directly to that node."
18972 (interactive)
18973 (info (format "(org)%s" (or node ""))))
18975 ;;;###autoload
18976 (defun org-submit-bug-report ()
18977 "Submit a bug report on Org-mode via mail.
18979 Don't hesitate to report any problems or inaccurate documentation.
18981 If you don't have setup sending mail from (X)Emacs, please copy the
18982 output buffer into your mail program, as it gives us important
18983 information about your Org-mode version and configuration."
18984 (interactive)
18985 (require 'reporter)
18986 (org-load-modules-maybe)
18987 (org-require-autoloaded-modules)
18988 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
18989 (reporter-submit-bug-report
18990 "emacs-orgmode@gnu.org"
18991 (org-version)
18992 (let (list)
18993 (save-window-excursion
18994 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
18995 (delete-other-windows)
18996 (erase-buffer)
18997 (insert "You are about to submit a bug report to the Org-mode mailing list.
18999 We would like to add your full Org-mode and Outline configuration to the
19000 bug report. This greatly simplifies the work of the maintainer and
19001 other experts on the mailing list.
19003 HOWEVER, some variables you have customized may contain private
19004 information. The names of customers, colleagues, or friends, might
19005 appear in the form of file names, tags, todo states, or search strings.
19006 If you answer yes to the prompt, you might want to check and remove
19007 such private information before sending the email.")
19008 (add-text-properties (point-min) (point-max) '(face org-warning))
19009 (when (yes-or-no-p "Include your Org-mode configuration ")
19010 (mapatoms
19011 (lambda (v)
19012 (and (boundp v)
19013 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19014 (or (and (symbol-value v)
19015 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19016 (and
19017 (get v 'custom-type) (get v 'standard-value)
19018 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19019 (push v list)))))
19020 (kill-buffer (get-buffer "*Warn about privacy*"))
19021 list))
19022 nil nil
19023 "Remember to cover the basics, that is, what you expected to happen and
19024 what in fact did happen. You don't know how to make a good report? See
19026 http://orgmode.org/manual/Feedback.html#Feedback
19028 Your bug report will be posted to the Org-mode mailing list.
19029 ------------------------------------------------------------------------")
19030 (save-excursion
19031 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19032 (replace-match "\\1Bug: \\3 [\\2]")))))
19035 (defun org-install-agenda-files-menu ()
19036 (let ((bl (buffer-list)))
19037 (save-excursion
19038 (while bl
19039 (set-buffer (pop bl))
19040 (if (eq major-mode 'org-mode) (setq bl nil)))
19041 (when (eq major-mode 'org-mode)
19042 (easy-menu-change
19043 '("Org") "File List for Agenda"
19044 (append
19045 (list
19046 ["Edit File List" (org-edit-agenda-file-list) t]
19047 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19048 ["Remove Current File from List" org-remove-file t]
19049 ["Cycle through agenda files" org-cycle-agenda-files t]
19050 ["Occur in all agenda files" org-occur-in-agenda-files t]
19051 "--")
19052 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19054 ;;;; Documentation
19056 ;;;###autoload
19057 (defun org-require-autoloaded-modules ()
19058 (interactive)
19059 (mapc 'require
19060 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19061 org-docbook org-exp org-html org-icalendar
19062 org-id org-latex
19063 org-publish org-remember org-table
19064 org-timer org-xoxo)))
19066 ;;;###autoload
19067 (defun org-reload (&optional uncompiled)
19068 "Reload all org lisp files.
19069 With prefix arg UNCOMPILED, load the uncompiled versions."
19070 (interactive "P")
19071 (require 'find-func)
19072 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
19073 (dir-org (file-name-directory (org-find-library-name "org")))
19074 (dir-org-contrib (ignore-errors
19075 (file-name-directory
19076 (org-find-library-name "org-contribdir"))))
19077 (babel-files
19078 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19079 (append (list nil "comint" "eval" "exp" "keys"
19080 "lob" "ref" "table" "tangle")
19081 (delq nil
19082 (mapcar
19083 (lambda (lang)
19084 (when (cdr lang) (symbol-name (car lang))))
19085 org-babel-load-languages)))))
19086 (files
19087 (append (directory-files dir-org t file-re)
19088 babel-files
19089 (and dir-org-contrib
19090 (directory-files dir-org-contrib t file-re))))
19091 (remove-re (concat (if (featurep 'xemacs)
19092 "org-colview" "org-colview-xemacs")
19093 "\\'")))
19094 (setq files (mapcar 'file-name-sans-extension files))
19095 (setq files (mapcar
19096 (lambda (x) (if (string-match remove-re x) nil x))
19097 files))
19098 (setq files (delq nil files))
19099 (mapc
19100 (lambda (f)
19101 (when (featurep (intern (file-name-nondirectory f)))
19102 (if (and (not uncompiled)
19103 (file-exists-p (concat f ".elc")))
19104 (load (concat f ".elc") nil nil t)
19105 (load (concat f ".el") nil nil t))))
19106 files))
19107 (org-version))
19109 ;;;###autoload
19110 (defun org-customize ()
19111 "Call the customize function with org as argument."
19112 (interactive)
19113 (org-load-modules-maybe)
19114 (org-require-autoloaded-modules)
19115 (customize-browse 'org))
19117 (defun org-create-customize-menu ()
19118 "Create a full customization menu for Org-mode, insert it into the menu."
19119 (interactive)
19120 (org-load-modules-maybe)
19121 (org-require-autoloaded-modules)
19122 (if (fboundp 'customize-menu-create)
19123 (progn
19124 (easy-menu-change
19125 '("Org") "Customize"
19126 `(["Browse Org group" org-customize t]
19127 "--"
19128 ,(customize-menu-create 'org)
19129 ["Set" Custom-set t]
19130 ["Save" Custom-save t]
19131 ["Reset to Current" Custom-reset-current t]
19132 ["Reset to Saved" Custom-reset-saved t]
19133 ["Reset to Standard Settings" Custom-reset-standard t]))
19134 (message "\"Org\"-menu now contains full customization menu"))
19135 (error "Cannot expand menu (outdated version of cus-edit.el)")))
19137 ;;;; Miscellaneous stuff
19139 ;;; Generally useful functions
19141 (defun org-get-at-bol (property)
19142 "Get text property PROPERTY at beginning of line."
19143 (get-text-property (point-at-bol) property))
19145 (defun org-find-text-property-in-string (prop s)
19146 "Return the first non-nil value of property PROP in string S."
19147 (or (get-text-property 0 prop s)
19148 (get-text-property (or (next-single-property-change 0 prop s) 0)
19149 prop s)))
19151 (defun org-display-warning (message) ;; Copied from Emacs-Muse
19152 "Display the given MESSAGE as a warning."
19153 (if (fboundp 'display-warning)
19154 (display-warning 'org message
19155 (if (featurep 'xemacs) 'warning :warning))
19156 (let ((buf (get-buffer-create "*Org warnings*")))
19157 (with-current-buffer buf
19158 (goto-char (point-max))
19159 (insert "Warning (Org): " message)
19160 (unless (bolp)
19161 (newline)))
19162 (display-buffer buf)
19163 (sit-for 0))))
19165 (defun org-eval (form)
19166 "Eval FORM and return result."
19167 (condition-case error
19168 (eval form)
19169 (error (format "%%![Error: %s]" error))))
19171 (defun org-in-commented-line ()
19172 "Is point in a line starting with `#'?"
19173 (equal (char-after (point-at-bol)) ?#))
19175 (defun org-in-indented-comment-line ()
19176 "Is point in a line starting with `#' after some white space?"
19177 (save-excursion
19178 (save-match-data
19179 (goto-char (point-at-bol))
19180 (looking-at "[ \t]*#"))))
19182 (defun org-in-verbatim-emphasis ()
19183 (save-match-data
19184 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
19186 (defun org-goto-marker-or-bmk (marker &optional bookmark)
19187 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
19188 (if (and marker (marker-buffer marker)
19189 (buffer-live-p (marker-buffer marker)))
19190 (progn
19191 (org-pop-to-buffer-same-window (marker-buffer marker))
19192 (if (or (> marker (point-max)) (< marker (point-min)))
19193 (widen))
19194 (goto-char marker)
19195 (org-show-context 'org-goto))
19196 (if bookmark
19197 (bookmark-jump bookmark)
19198 (error "Cannot find location"))))
19200 (defun org-quote-csv-field (s)
19201 "Quote field for inclusion in CSV material."
19202 (if (string-match "[\",]" s)
19203 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
19206 (defun org-force-self-insert (N)
19207 "Needed to enforce self-insert under remapping."
19208 (interactive "p")
19209 (self-insert-command N))
19211 (defun org-string-width (s)
19212 "Compute width of string, ignoring invisible characters.
19213 This ignores character with invisibility property `org-link', and also
19214 characters with property `org-cwidth', because these will become invisible
19215 upon the next fontification round."
19216 (let (b l)
19217 (when (or (eq t buffer-invisibility-spec)
19218 (assq 'org-link buffer-invisibility-spec))
19219 (while (setq b (text-property-any 0 (length s)
19220 'invisible 'org-link s))
19221 (setq s (concat (substring s 0 b)
19222 (substring s (or (next-single-property-change
19223 b 'invisible s) (length s)))))))
19224 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
19225 (setq s (concat (substring s 0 b)
19226 (substring s (or (next-single-property-change
19227 b 'org-cwidth s) (length s))))))
19228 (setq l (string-width s) b -1)
19229 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
19230 (setq l (- l (get-text-property b 'org-dwidth-n s))))
19233 (defun org-shorten-string (s maxlength)
19234 "Shorten string S so tht it is no longer than MAXLENGTH characters.
19235 If the string is shorter or has length MAXLENGTH, just return the
19236 original string. If it is longer, the functions finds a space in the
19237 string, breaks this string off at that locations and adds three dots
19238 as ellipsis. Including the ellipsis, the string will not be longer
19239 than MAXLENGTH. If finding a good breaking point in the string does
19240 not work, the string is just chopped off in the middle of a word
19241 if necessary."
19242 (if (<= (length s) maxlength)
19244 (let* ((n (max (- maxlength 4) 1))
19245 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
19246 (if (string-match re s)
19247 (concat (match-string 1 s) "...")
19248 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
19250 (defun org-get-indentation (&optional line)
19251 "Get the indentation of the current line, interpreting tabs.
19252 When LINE is given, assume it represents a line and compute its indentation."
19253 (if line
19254 (if (string-match "^ *" (org-remove-tabs line))
19255 (match-end 0))
19256 (save-excursion
19257 (beginning-of-line 1)
19258 (skip-chars-forward " \t")
19259 (current-column))))
19261 (defun org-get-string-indentation (s)
19262 "What indentation has S due to SPACE and TAB at the beginning of the string?"
19263 (let ((n -1) (i 0) (w tab-width) c)
19264 (catch 'exit
19265 (while (< (setq n (1+ n)) (length s))
19266 (setq c (aref s n))
19267 (cond ((= c ?\ ) (setq i (1+ i)))
19268 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
19269 (t (throw 'exit t)))))
19272 (defun org-remove-tabs (s &optional width)
19273 "Replace tabulators in S with spaces.
19274 Assumes that s is a single line, starting in column 0."
19275 (setq width (or width tab-width))
19276 (while (string-match "\t" s)
19277 (setq s (replace-match
19278 (make-string
19279 (- (* width (/ (+ (match-beginning 0) width) width))
19280 (match-beginning 0)) ?\ )
19281 t t s)))
19284 (defun org-fix-indentation (line ind)
19285 "Fix indentation in LINE.
19286 IND is a cons cell with target and minimum indentation.
19287 If the current indentation in LINE is smaller than the minimum,
19288 leave it alone. If it is larger than ind, set it to the target."
19289 (let* ((l (org-remove-tabs line))
19290 (i (org-get-indentation l))
19291 (i1 (car ind)) (i2 (cdr ind)))
19292 (if (>= i i2) (setq l (substring line i2)))
19293 (if (> i1 0)
19294 (concat (make-string i1 ?\ ) l)
19295 l)))
19297 (defun org-remove-indentation (code &optional n)
19298 "Remove the maximum common indentation from the lines in CODE.
19299 N may optionally be the number of spaces to remove."
19300 (with-temp-buffer
19301 (insert code)
19302 (org-do-remove-indentation n)
19303 (buffer-string)))
19305 (defun org-do-remove-indentation (&optional n)
19306 "Remove the maximum common indentation from the buffer."
19307 (untabify (point-min) (point-max))
19308 (let ((min 10000) re)
19309 (if n
19310 (setq min n)
19311 (goto-char (point-min))
19312 (while (re-search-forward "^ *[^ \n]" nil t)
19313 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
19314 (unless (or (= min 0) (= min 10000))
19315 (setq re (format "^ \\{%d\\}" min))
19316 (goto-char (point-min))
19317 (while (re-search-forward re nil t)
19318 (replace-match "")
19319 (end-of-line 1))
19320 min)))
19322 (defun org-fill-template (template alist)
19323 "Find each %key of ALIST in TEMPLATE and replace it."
19324 (let ((case-fold-search nil)
19325 entry key value)
19326 (setq alist (sort (copy-sequence alist)
19327 (lambda (a b) (< (length (car a)) (length (car b))))))
19328 (while (setq entry (pop alist))
19329 (setq template
19330 (replace-regexp-in-string
19331 (concat "%" (regexp-quote (car entry)))
19332 (cdr entry) template t t)))
19333 template))
19335 (defun org-base-buffer (buffer)
19336 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
19337 (if (not buffer)
19338 buffer
19339 (or (buffer-base-buffer buffer)
19340 buffer)))
19342 (defun org-trim (s)
19343 "Remove whitespace at beginning and end of string."
19344 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
19345 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
19348 (defun org-wrap (string &optional width lines)
19349 "Wrap string to either a number of lines, or a width in characters.
19350 If WIDTH is non-nil, the string is wrapped to that width, however many lines
19351 that costs. If there is a word longer than WIDTH, the text is actually
19352 wrapped to the length of that word.
19353 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
19354 many lines, whatever width that takes.
19355 The return value is a list of lines, without newlines at the end."
19356 (let* ((words (org-split-string string "[ \t\n]+"))
19357 (maxword (apply 'max (mapcar 'org-string-width words)))
19358 w ll)
19359 (cond (width
19360 (org-do-wrap words (max maxword width)))
19361 (lines
19362 (setq w maxword)
19363 (setq ll (org-do-wrap words maxword))
19364 (if (<= (length ll) lines)
19366 (setq ll words)
19367 (while (> (length ll) lines)
19368 (setq w (1+ w))
19369 (setq ll (org-do-wrap words w)))
19370 ll))
19371 (t (error "Cannot wrap this")))))
19373 (defun org-do-wrap (words width)
19374 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
19375 (let (lines line)
19376 (while words
19377 (setq line (pop words))
19378 (while (and words (< (+ (length line) (length (car words))) width))
19379 (setq line (concat line " " (pop words))))
19380 (setq lines (push line lines)))
19381 (nreverse lines)))
19383 (defun org-split-string (string &optional separators)
19384 "Splits STRING into substrings at SEPARATORS.
19385 No empty strings are returned if there are matches at the beginning
19386 and end of string."
19387 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
19388 (start 0)
19389 notfirst
19390 (list nil))
19391 (while (and (string-match rexp string
19392 (if (and notfirst
19393 (= start (match-beginning 0))
19394 (< start (length string)))
19395 (1+ start) start))
19396 (< (match-beginning 0) (length string)))
19397 (setq notfirst t)
19398 (or (eq (match-beginning 0) 0)
19399 (and (eq (match-beginning 0) (match-end 0))
19400 (eq (match-beginning 0) start))
19401 (setq list
19402 (cons (substring string start (match-beginning 0))
19403 list)))
19404 (setq start (match-end 0)))
19405 (or (eq start (length string))
19406 (setq list
19407 (cons (substring string start)
19408 list)))
19409 (nreverse list)))
19411 (defun org-quote-vert (s)
19412 "Replace \"|\" with \"\\vert\"."
19413 (while (string-match "|" s)
19414 (setq s (replace-match "\\vert" t t s)))
19417 (defun org-uuidgen-p (s)
19418 "Is S an ID created by UUIDGEN?"
19419 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
19421 (defun org-context ()
19422 "Return a list of contexts of the current cursor position.
19423 If several contexts apply, all are returned.
19424 Each context entry is a list with a symbol naming the context, and
19425 two positions indicating start and end of the context. Possible
19426 contexts are:
19428 :headline anywhere in a headline
19429 :headline-stars on the leading stars in a headline
19430 :todo-keyword on a TODO keyword (including DONE) in a headline
19431 :tags on the TAGS in a headline
19432 :priority on the priority cookie in a headline
19433 :item on the first line of a plain list item
19434 :item-bullet on the bullet/number of a plain list item
19435 :checkbox on the checkbox in a plain list item
19436 :table in an org-mode table
19437 :table-special on a special filed in a table
19438 :table-table in a table.el table
19439 :link on a hyperlink
19440 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
19441 :target on a <<target>>
19442 :radio-target on a <<<radio-target>>>
19443 :latex-fragment on a LaTeX fragment
19444 :latex-preview on a LaTeX fragment with overlaid preview image
19446 This function expects the position to be visible because it uses font-lock
19447 faces as a help to recognize the following contexts: :table-special, :link,
19448 and :keyword."
19449 (let* ((f (get-text-property (point) 'face))
19450 (faces (if (listp f) f (list f)))
19451 (p (point)) clist o)
19452 ;; First the large context
19453 (cond
19454 ((org-on-heading-p t)
19455 (push (list :headline (point-at-bol) (point-at-eol)) clist)
19456 (when (progn
19457 (beginning-of-line 1)
19458 (looking-at org-todo-line-tags-regexp))
19459 (push (org-point-in-group p 1 :headline-stars) clist)
19460 (push (org-point-in-group p 2 :todo-keyword) clist)
19461 (push (org-point-in-group p 4 :tags) clist))
19462 (goto-char p)
19463 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
19464 (if (looking-at "\\[#[A-Z0-9]\\]")
19465 (push (org-point-in-group p 0 :priority) clist)))
19467 ((org-at-item-p)
19468 (push (org-point-in-group p 2 :item-bullet) clist)
19469 (push (list :item (point-at-bol)
19470 (save-excursion (org-end-of-item) (point)))
19471 clist)
19472 (and (org-at-item-checkbox-p)
19473 (push (org-point-in-group p 0 :checkbox) clist)))
19475 ((org-at-table-p)
19476 (push (list :table (org-table-begin) (org-table-end)) clist)
19477 (if (memq 'org-formula faces)
19478 (push (list :table-special
19479 (previous-single-property-change p 'face)
19480 (next-single-property-change p 'face)) clist)))
19481 ((org-at-table-p 'any)
19482 (push (list :table-table) clist)))
19483 (goto-char p)
19485 ;; Now the small context
19486 (cond
19487 ((org-at-timestamp-p)
19488 (push (org-point-in-group p 0 :timestamp) clist))
19489 ((memq 'org-link faces)
19490 (push (list :link
19491 (previous-single-property-change p 'face)
19492 (next-single-property-change p 'face)) clist))
19493 ((memq 'org-special-keyword faces)
19494 (push (list :keyword
19495 (previous-single-property-change p 'face)
19496 (next-single-property-change p 'face)) clist))
19497 ((org-on-target-p)
19498 (push (org-point-in-group p 0 :target) clist)
19499 (goto-char (1- (match-beginning 0)))
19500 (if (looking-at org-radio-target-regexp)
19501 (push (org-point-in-group p 0 :radio-target) clist))
19502 (goto-char p))
19503 ((setq o (car (delq nil
19504 (mapcar
19505 (lambda (x)
19506 (if (memq x org-latex-fragment-image-overlays) x))
19507 (overlays-at (point))))))
19508 (push (list :latex-fragment
19509 (overlay-start o) (overlay-end o)) clist)
19510 (push (list :latex-preview
19511 (overlay-start o) (overlay-end o)) clist))
19512 ((org-inside-LaTeX-fragment-p)
19513 ;; FIXME: positions wrong.
19514 (push (list :latex-fragment (point) (point)) clist)))
19516 (setq clist (nreverse (delq nil clist)))
19517 clist))
19519 ;; FIXME: Compare with at-regexp-p Do we need both?
19520 (defun org-in-regexp (re &optional nlines visually)
19521 "Check if point is inside a match of regexp.
19522 Normally only the current line is checked, but you can include NLINES extra
19523 lines both before and after point into the search.
19524 If VISUALLY is set, require that the cursor is not after the match but
19525 really on, so that the block visually is on the match."
19526 (catch 'exit
19527 (let ((pos (point))
19528 (eol (point-at-eol (+ 1 (or nlines 0))))
19529 (inc (if visually 1 0)))
19530 (save-excursion
19531 (beginning-of-line (- 1 (or nlines 0)))
19532 (while (re-search-forward re eol t)
19533 (if (and (<= (match-beginning 0) pos)
19534 (>= (+ inc (match-end 0)) pos))
19535 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
19537 (defun org-at-regexp-p (regexp)
19538 "Is point inside a match of REGEXP in the current line?"
19539 (catch 'exit
19540 (save-excursion
19541 (let ((pos (point)) (end (point-at-eol)))
19542 (beginning-of-line 1)
19543 (while (re-search-forward regexp end t)
19544 (if (and (<= (match-beginning 0) pos)
19545 (>= (match-end 0) pos))
19546 (throw 'exit t)))
19547 nil))))
19549 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
19550 "Non-nil when point is between matches of START-RE and END-RE.
19552 Also return a non-nil value when point is on one of the matches.
19554 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
19555 buffer positions. Default values are the positions of headlines
19556 surrounding the point.
19558 The functions returns a cons cell whose car (resp. cdr) is the
19559 position before START-RE (resp. after END-RE)."
19560 (save-match-data
19561 (let ((pos (point))
19562 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
19563 (limit-down (or lim-down (save-excursion (outline-next-heading))))
19564 beg end)
19565 (save-excursion
19566 ;; Point is on a block when on START-RE or if START-RE can be
19567 ;; found before it...
19568 (and (or (org-at-regexp-p start-re)
19569 (re-search-backward start-re limit-up t))
19570 (setq beg (match-beginning 0))
19571 ;; ... and END-RE after it...
19572 (goto-char (match-end 0))
19573 (re-search-forward end-re limit-down t)
19574 (> (setq end (match-end 0)) pos)
19575 ;; ... without another START-RE in-between.
19576 (goto-char (match-beginning 0))
19577 (not (re-search-backward start-re (1+ beg) t))
19578 ;; Return value.
19579 (cons beg end))))))
19581 (defun org-in-block-p (names)
19582 "Non-nil when point belongs to a block whose name belongs to NAMES.
19584 NAMES is a list of strings containing names of blocks.
19586 Return first block name matched, or nil. Beware that in case of
19587 nested blocks, the returned name may not belong to the closest
19588 block from point."
19589 (save-match-data
19590 (catch 'exit
19591 (let ((case-fold-search t)
19592 (lim-up (save-excursion (outline-previous-heading)))
19593 (lim-down (save-excursion (outline-next-heading))))
19594 (mapc (lambda (name)
19595 (let ((n (regexp-quote name)))
19596 (when (org-between-regexps-p
19597 (concat "^[ \t]*#\\+begin_" n)
19598 (concat "^[ \t]*#\\+end_" n)
19599 lim-up lim-down)
19600 (throw 'exit n))))
19601 names))
19602 nil)))
19604 (defun org-occur-in-agenda-files (regexp &optional nlines)
19605 "Call `multi-occur' with buffers for all agenda files."
19606 (interactive "sOrg-files matching: \np")
19607 (let* ((files (org-agenda-files))
19608 (tnames (mapcar 'file-truename files))
19609 (extra org-agenda-text-search-extra-files)
19611 (when (eq (car extra) 'agenda-archives)
19612 (setq extra (cdr extra))
19613 (setq files (org-add-archive-files files)))
19614 (while (setq f (pop extra))
19615 (unless (member (file-truename f) tnames)
19616 (add-to-list 'files f 'append)
19617 (add-to-list 'tnames (file-truename f) 'append)))
19618 (multi-occur
19619 (mapcar (lambda (x)
19620 (with-current-buffer
19621 (or (get-file-buffer x) (find-file-noselect x))
19622 (widen)
19623 (current-buffer)))
19624 files)
19625 regexp)))
19627 (if (boundp 'occur-mode-find-occurrence-hook)
19628 ;; Emacs 23
19629 (add-hook 'occur-mode-find-occurrence-hook
19630 (lambda ()
19631 (when (eq major-mode 'org-mode)
19632 (org-reveal))))
19633 ;; Emacs 22
19634 (defadvice occur-mode-goto-occurrence
19635 (after org-occur-reveal activate)
19636 (and (eq major-mode 'org-mode) (org-reveal)))
19637 (defadvice occur-mode-goto-occurrence-other-window
19638 (after org-occur-reveal activate)
19639 (and (eq major-mode 'org-mode) (org-reveal)))
19640 (defadvice occur-mode-display-occurrence
19641 (after org-occur-reveal activate)
19642 (when (eq major-mode 'org-mode)
19643 (let ((pos (occur-mode-find-occurrence)))
19644 (with-current-buffer (marker-buffer pos)
19645 (save-excursion
19646 (goto-char pos)
19647 (org-reveal)))))))
19649 (defun org-occur-link-in-agenda-files ()
19650 "Create a link and search for it in the agendas.
19651 The link is not stored in `org-stored-links', it is just created
19652 for the search purpose."
19653 (interactive)
19654 (let ((link (condition-case nil
19655 (org-store-link nil)
19656 (error "Unable to create a link to here"))))
19657 (org-occur-in-agenda-files (regexp-quote link))))
19659 (defun org-uniquify (list)
19660 "Remove duplicate elements from LIST."
19661 (let (res)
19662 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
19663 res))
19665 (defun org-delete-all (elts list)
19666 "Remove all elements in ELTS from LIST."
19667 (while elts
19668 (setq list (delete (pop elts) list)))
19669 list)
19671 (defun org-count (cl-item cl-seq)
19672 "Count the number of occurrences of ITEM in SEQ.
19673 Taken from `count' in cl-seq.el with all keyword arguments removed."
19674 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
19675 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
19676 (while (< cl-start cl-end)
19677 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
19678 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
19679 (setq cl-start (1+ cl-start)))
19680 cl-count))
19682 (defun org-remove-if (predicate seq)
19683 "Remove everything from SEQ that fulfills PREDICATE."
19684 (let (res e)
19685 (while seq
19686 (setq e (pop seq))
19687 (if (not (funcall predicate e)) (push e res)))
19688 (nreverse res)))
19690 (defun org-remove-if-not (predicate seq)
19691 "Remove everything from SEQ that does not fulfill PREDICATE."
19692 (let (res e)
19693 (while seq
19694 (setq e (pop seq))
19695 (if (funcall predicate e) (push e res)))
19696 (nreverse res)))
19698 (defun org-reduce (cl-func cl-seq &rest cl-keys)
19699 "Reduce two-argument FUNCTION across SEQ.
19700 Taken from `reduce' in cl-seq.el with all keyword arguments but
19701 \":initial-value\" removed."
19702 (let ((cl-accum (cond ((memq :initial-value cl-keys)
19703 (cadr (memq :initial-value cl-keys)))
19704 (cl-seq (pop cl-seq))
19705 (t (funcall cl-func)))))
19706 (while cl-seq
19707 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
19708 cl-accum))
19710 (defun org-back-over-empty-lines ()
19711 "Move backwards over whitespace, to the beginning of the first empty line.
19712 Returns the number of empty lines passed."
19713 (let ((pos (point)))
19714 (if (cdr (assoc 'heading org-blank-before-new-entry))
19715 (skip-chars-backward " \t\n\r")
19716 (unless (eobp)
19717 (forward-line -1)))
19718 (beginning-of-line 2)
19719 (goto-char (min (point) pos))
19720 (count-lines (point) pos)))
19722 (defun org-skip-whitespace ()
19723 (skip-chars-forward " \t\n\r"))
19725 (defun org-point-in-group (point group &optional context)
19726 "Check if POINT is in match-group GROUP.
19727 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
19728 match. If the match group does not exist or point is not inside it,
19729 return nil."
19730 (and (match-beginning group)
19731 (>= point (match-beginning group))
19732 (<= point (match-end group))
19733 (if context
19734 (list context (match-beginning group) (match-end group))
19735 t)))
19737 (defun org-switch-to-buffer-other-window (&rest args)
19738 "Switch to buffer in a second window on the current frame.
19739 In particular, do not allow pop-up frames.
19740 Returns the newly created buffer."
19741 (let (pop-up-frames special-display-buffer-names special-display-regexps
19742 special-display-function)
19743 (apply 'switch-to-buffer-other-window args)))
19745 (defun org-combine-plists (&rest plists)
19746 "Create a single property list from all plists in PLISTS.
19747 The process starts by copying the first list, and then setting properties
19748 from the other lists. Settings in the last list are the most significant
19749 ones and overrule settings in the other lists."
19750 (let ((rtn (copy-sequence (pop plists)))
19751 p v ls)
19752 (while plists
19753 (setq ls (pop plists))
19754 (while ls
19755 (setq p (pop ls) v (pop ls))
19756 (setq rtn (plist-put rtn p v))))
19757 rtn))
19759 (defun org-move-line-down (arg)
19760 "Move the current line down. With prefix argument, move it past ARG lines."
19761 (interactive "p")
19762 (let ((col (current-column))
19763 beg end pos)
19764 (beginning-of-line 1) (setq beg (point))
19765 (beginning-of-line 2) (setq end (point))
19766 (beginning-of-line (+ 1 arg))
19767 (setq pos (move-marker (make-marker) (point)))
19768 (insert (delete-and-extract-region beg end))
19769 (goto-char pos)
19770 (org-move-to-column col)))
19772 (defun org-move-line-up (arg)
19773 "Move the current line up. With prefix argument, move it past ARG lines."
19774 (interactive "p")
19775 (let ((col (current-column))
19776 beg end pos)
19777 (beginning-of-line 1) (setq beg (point))
19778 (beginning-of-line 2) (setq end (point))
19779 (beginning-of-line (- arg))
19780 (setq pos (move-marker (make-marker) (point)))
19781 (insert (delete-and-extract-region beg end))
19782 (goto-char pos)
19783 (org-move-to-column col)))
19785 (defun org-replace-escapes (string table)
19786 "Replace %-escapes in STRING with values in TABLE.
19787 TABLE is an association list with keys like \"%a\" and string values.
19788 The sequences in STRING may contain normal field width and padding information,
19789 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
19790 so values can contain further %-escapes if they are define later in TABLE."
19791 (let ((tbl (copy-alist table))
19792 (case-fold-search nil)
19793 (pchg 0)
19794 e re rpl)
19795 (while (setq e (pop tbl))
19796 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
19797 (when (and (cdr e) (string-match re (cdr e)))
19798 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
19799 (safe "SREF"))
19800 (add-text-properties 0 3 (list 'sref sref) safe)
19801 (setcdr e (replace-match safe t t (cdr e)))))
19802 (while (string-match re string)
19803 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
19804 (cdr e)))
19805 (setq string (replace-match rpl t t string))))
19806 (while (setq pchg (next-property-change pchg string))
19807 (let ((sref (get-text-property pchg 'sref string)))
19808 (when (and sref (string-match "SREF" string pchg))
19809 (setq string (replace-match sref t t string)))))
19810 string))
19812 (defun org-sublist (list start end)
19813 "Return a section of LIST, from START to END.
19814 Counting starts at 1."
19815 (let (rtn (c start))
19816 (setq list (nthcdr (1- start) list))
19817 (while (and list (<= c end))
19818 (push (pop list) rtn)
19819 (setq c (1+ c)))
19820 (nreverse rtn)))
19822 (defun org-find-base-buffer-visiting (file)
19823 "Like `find-buffer-visiting' but always return the base buffer and
19824 not an indirect buffer."
19825 (let ((buf (or (get-file-buffer file)
19826 (find-buffer-visiting file))))
19827 (if buf
19828 (or (buffer-base-buffer buf) buf)
19829 nil)))
19831 (defun org-image-file-name-regexp (&optional extensions)
19832 "Return regexp matching the file names of images.
19833 If EXTENSIONS is given, only match these."
19834 (if (and (not extensions) (fboundp 'image-file-name-regexp))
19835 (image-file-name-regexp)
19836 (let ((image-file-name-extensions
19837 (or extensions
19838 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
19839 "xbm" "xpm" "pbm" "pgm" "ppm"))))
19840 (concat "\\."
19841 (regexp-opt (nconc (mapcar 'upcase
19842 image-file-name-extensions)
19843 image-file-name-extensions)
19845 "\\'"))))
19847 (defun org-file-image-p (file &optional extensions)
19848 "Return non-nil if FILE is an image."
19849 (save-match-data
19850 (string-match (org-image-file-name-regexp extensions) file)))
19852 (defun org-get-cursor-date ()
19853 "Return the date at cursor in as a time.
19854 This works in the calendar and in the agenda, anywhere else it just
19855 returns the current time."
19856 (let (date day defd)
19857 (cond
19858 ((eq major-mode 'calendar-mode)
19859 (setq date (calendar-cursor-to-date)
19860 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
19861 ((eq major-mode 'org-agenda-mode)
19862 (setq day (get-text-property (point) 'day))
19863 (if day
19864 (setq date (calendar-gregorian-from-absolute day)
19865 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
19866 (nth 2 date))))))
19867 (or defd (current-time))))
19869 (defvar org-agenda-action-marker (make-marker)
19870 "Marker pointing to the entry for the next agenda action.")
19872 (defun org-mark-entry-for-agenda-action ()
19873 "Mark the current entry as target of an agenda action.
19874 Agenda actions are actions executed from the agenda with the key `k',
19875 which make use of the date at the cursor."
19876 (interactive)
19877 (move-marker org-agenda-action-marker
19878 (save-excursion (org-back-to-heading t) (point))
19879 (current-buffer))
19880 (message
19881 "Entry marked for action; press `k' at desired date in agenda or calendar"))
19883 (defun org-mark-subtree ()
19884 "Mark the current subtree.
19885 This puts point at the start of the current subtree, and mark at the end.
19887 If point is in an inline task, mark that task instead."
19888 (interactive)
19889 (let ((inline-task-p
19890 (and (featurep 'org-inlinetask)
19891 (org-inlinetask-in-task-p)))
19892 (beg))
19893 ;; Get beginning of subtree
19894 (cond
19895 (inline-task-p (org-inlinetask-goto-beginning))
19896 ((org-at-heading-p) (beginning-of-line))
19897 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
19898 (setq beg (point))
19899 ;; Get end of it
19900 (if inline-task-p
19901 (org-inlinetask-goto-end)
19902 (org-end-of-subtree))
19903 ;; Mark zone
19904 (push-mark (point) nil t)
19905 (goto-char beg)))
19907 ;;; Paragraph filling stuff.
19908 ;; We want this to be just right, so use the full arsenal.
19910 (defun org-indent-line-function ()
19911 "Indent line depending on context."
19912 (interactive)
19913 (let* ((pos (point))
19914 (itemp (org-at-item-p))
19915 (case-fold-search t)
19916 (org-drawer-regexp (or org-drawer-regexp "\000"))
19917 (inline-task-p (and (featurep 'org-inlinetask)
19918 (org-inlinetask-in-task-p)))
19919 (inline-re (and inline-task-p
19920 (org-inlinetask-outline-regexp)))
19921 column)
19922 (beginning-of-line 1)
19923 (cond
19924 ;; Comments
19925 ((looking-at "# ") (setq column 0))
19926 ;; Headings
19927 ((looking-at org-outline-regexp) (setq column 0))
19928 ;; Included files
19929 ((looking-at "#\\+include:") (setq column 0))
19930 ;; Footnote definition
19931 ((looking-at org-footnote-definition-re) (setq column 0))
19932 ;; Literal examples
19933 ((looking-at "[ \t]*:\\( \\|$\\)")
19934 (setq column (org-get-indentation))) ; do nothing
19935 ;; Lists
19936 ((ignore-errors (goto-char (org-in-item-p)))
19937 (setq column (if itemp
19938 (org-get-indentation)
19939 (org-list-item-body-column (point))))
19940 (goto-char pos))
19941 ;; Drawers
19942 ((and (looking-at "[ \t]*:END:")
19943 (save-excursion (re-search-backward org-drawer-regexp nil t)))
19944 (save-excursion
19945 (goto-char (1- (match-beginning 1)))
19946 (setq column (current-column))))
19947 ;; Special blocks
19948 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
19949 (save-excursion
19950 (re-search-backward
19951 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
19952 (setq column (org-get-indentation (match-string 0))))
19953 ((and (not (looking-at "[ \t]*#\\+begin_"))
19954 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
19955 (save-excursion
19956 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
19957 (setq column
19958 (cond ((equal (downcase (match-string 1)) "src")
19959 ;; src blocks: let `org-edit-src-exit' handle them
19960 (org-get-indentation))
19961 ((equal (downcase (match-string 1)) "example")
19962 (max (org-get-indentation)
19963 (org-get-indentation (match-string 0))))
19965 (org-get-indentation (match-string 0))))))
19966 ;; This line has nothing special, look at the previous relevant
19967 ;; line to compute indentation
19969 (beginning-of-line 0)
19970 (while (and (not (bobp))
19971 (not (looking-at org-drawer-regexp))
19972 ;; When point started in an inline task, do not move
19973 ;; above task starting line.
19974 (not (and inline-task-p (looking-at inline-re)))
19975 ;; Skip drawers, blocks, empty lines, verbatim,
19976 ;; comments, tables, footnotes definitions, lists,
19977 ;; inline tasks.
19978 (or (and (looking-at "[ \t]*:END:")
19979 (re-search-backward org-drawer-regexp nil t))
19980 (and (looking-at "[ \t]*#\\+end_")
19981 (re-search-backward "[ \t]*#\\+begin_"nil t))
19982 (looking-at "[ \t]*[\n:#|]")
19983 (looking-at org-footnote-definition-re)
19984 (and (ignore-errors (goto-char (org-in-item-p)))
19985 (goto-char
19986 (org-list-get-top-point (org-list-struct))))
19987 (and (not inline-task-p)
19988 (featurep 'org-inlinetask)
19989 (org-inlinetask-in-task-p)
19990 (or (org-inlinetask-goto-beginning) t))))
19991 (beginning-of-line 0))
19992 (cond
19993 ;; There was an heading above.
19994 ((looking-at "\\*+[ \t]+")
19995 (if (not org-adapt-indentation)
19996 (setq column 0)
19997 (goto-char (match-end 0))
19998 (setq column (current-column))))
19999 ;; A drawer had started and is unfinished
20000 ((looking-at org-drawer-regexp)
20001 (goto-char (1- (match-beginning 1)))
20002 (setq column (current-column)))
20003 ;; Else, nothing noticeable found: get indentation and go on.
20004 (t (setq column (org-get-indentation))))))
20005 ;; Now apply indentation and move cursor accordingly
20006 (goto-char pos)
20007 (if (<= (current-column) (current-indentation))
20008 (org-indent-line-to column)
20009 (save-excursion (org-indent-line-to column)))
20010 ;; Special polishing for properties, see `org-property-format'
20011 (setq column (current-column))
20012 (beginning-of-line 1)
20013 (if (looking-at
20014 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20015 (replace-match (concat (match-string 1)
20016 (format org-property-format
20017 (match-string 2) (match-string 3)))
20018 t t))
20019 (org-move-to-column column)))
20021 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
20022 "Variable to store copy of `adaptive-fill-regexp'.
20023 Since `adaptive-fill-regexp' is set to never match, we need to
20024 store a backup of its value before entering `org-mode' so that
20025 the functionality can be provided as a fall-back.")
20027 (defun org-set-autofill-regexps ()
20028 (interactive)
20029 ;; In the paragraph separator we include headlines, because filling
20030 ;; text in a line directly attached to a headline would otherwise
20031 ;; fill the headline as well.
20032 (org-set-local 'comment-start-skip "^#+[ \t]*")
20033 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
20034 ;; The paragraph starter includes hand-formatted lists.
20035 (org-set-local
20036 'paragraph-start
20037 (concat
20038 "\f" "\\|"
20039 "[ ]*$" "\\|"
20040 org-outline-regexp "\\|"
20041 "[ \t]*#" "\\|"
20042 (org-item-re) "\\|"
20043 "[ \t]*[:|]" "\\|"
20044 "\\$\\$" "\\|"
20045 "\\\\\\(begin\\|end\\|[][]\\)"))
20046 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
20047 ;; But only if the user has not turned off tables or fixed-width regions
20048 (org-set-local
20049 'auto-fill-inhibit-regexp
20050 (concat org-outline-regexp
20051 "\\|#\\+"
20052 "\\|[ \t]*" org-keyword-time-regexp
20053 (if (or org-enable-table-editor org-enable-fixed-width-editor)
20054 (concat
20055 "\\|[ \t]*["
20056 (if org-enable-table-editor "|" "")
20057 (if org-enable-fixed-width-editor ":" "")
20058 "]"))))
20059 ;; We use our own fill-paragraph function, to make sure that tables
20060 ;; and fixed-width regions are not wrapped. That function will pass
20061 ;; through to `fill-paragraph' when appropriate.
20062 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20063 ;; Prevent auto-fill from inserting unwanted new items.
20064 (if (boundp 'fill-nobreak-predicate)
20065 (org-set-local 'fill-nobreak-predicate
20066 (if (memq 'org-fill-item-nobreak-p fill-nobreak-predicate)
20067 fill-nobreak-predicate
20068 (cons 'org-fill-item-nobreak-p fill-nobreak-predicate))))
20069 ;; Adaptive filling: To get full control, first make sure that
20070 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
20071 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
20072 (org-set-local 'org-adaptive-fill-regexp-backup
20073 adaptive-fill-regexp))
20074 (org-set-local 'adaptive-fill-regexp "\000")
20075 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20076 (org-set-local 'adaptive-fill-function
20077 'org-adaptive-fill-function)
20078 (org-set-local
20079 'align-mode-rules-list
20080 '((org-in-buffer-settings
20081 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
20082 (modes . '(org-mode))))))
20084 (defun org-fill-item-nobreak-p ()
20085 "Non-nil when a line break at point would insert a new item."
20086 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
20088 (defun org-fill-paragraph (&optional justify)
20089 "Re-align a table, pass through to fill-paragraph if no table."
20090 (let ((table-p (org-at-table-p))
20091 (table.el-p (org-at-table.el-p))
20092 (itemp (org-in-item-p)))
20093 (cond ((and (equal (char-after (point-at-bol)) ?*)
20094 (save-excursion (goto-char (point-at-bol))
20095 (looking-at org-outline-regexp)))
20096 t) ; skip headlines
20097 (table.el-p t) ; skip table.el tables
20098 (table-p (org-table-align) t) ; align Org tables
20099 (itemp ; align text in items
20100 (let* ((struct (save-excursion (goto-char itemp)
20101 (org-list-struct)))
20102 (parents (org-list-parents-alist struct))
20103 (children (org-list-get-children itemp struct parents))
20104 beg end prev next prefix)
20105 ;; Determine in which part of item point is: before
20106 ;; first child, after last child, between two
20107 ;; sub-lists, or simply in item if there's no child.
20108 (cond
20109 ((not children)
20110 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20111 beg itemp
20112 end (org-list-get-item-end itemp struct)))
20113 ((< (point) (setq next (car children)))
20114 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20115 beg itemp
20116 end next))
20117 ((> (point) (setq prev (car (last children))))
20118 (setq beg (org-list-get-item-end prev struct)
20119 end (org-list-get-item-end itemp struct)
20120 prefix (save-excursion
20121 (goto-char beg)
20122 (skip-chars-forward " \t")
20123 (make-string (current-column) ?\ ))))
20124 (t (catch 'exit
20125 (while (setq next (pop children))
20126 (if (> (point) next)
20127 (setq prev next)
20128 (setq beg (org-list-get-item-end prev struct)
20129 end next
20130 prefix (save-excursion
20131 (goto-char beg)
20132 (skip-chars-forward " \t")
20133 (make-string (current-column) ?\ )))
20134 (throw 'exit nil))))))
20135 ;; Use `fill-paragraph' with buffer narrowed to item
20136 ;; without any child, and with our computed PREFIX.
20137 (flet ((fill-context-prefix (from to &optional flr) prefix))
20138 (save-restriction
20139 (narrow-to-region beg end)
20140 (save-excursion (fill-paragraph justify)))) t))
20141 ;; Special case where point is not in a list but is on
20142 ;; a paragraph adjacent to a list: make sure this paragraph
20143 ;; doesn't get merged with the end of the list by narrowing
20144 ;; buffer first.
20145 ((save-excursion (forward-paragraph -1)
20146 (setq itemp (org-in-item-p)))
20147 (let ((struct (save-excursion (goto-char itemp)
20148 (org-list-struct))))
20149 (save-restriction
20150 (narrow-to-region (org-list-get-bottom-point struct)
20151 (save-excursion (forward-paragraph 1)
20152 (point)))
20153 (fill-paragraph justify) t)))
20154 ;; Else simply call `fill-paragraph'.
20155 (t nil))))
20157 ;; For reference, this is the default value of adaptive-fill-regexp
20158 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
20160 (defun org-adaptive-fill-function ()
20161 "Return a fill prefix for org-mode files."
20162 (let (itemp)
20163 (save-excursion
20164 (cond
20165 ;; Comment line
20166 ((looking-at "#[ \t]+")
20167 (match-string-no-properties 0))
20168 ;; Plain list item
20169 ((org-at-item-p)
20170 (make-string (org-list-item-body-column (point-at-bol)) ?\ ))
20171 ;; Point is in a list after `backward-paragraph': original
20172 ;; point wasn't in the list, or filling would have been taken
20173 ;; care of by `org-auto-fill-function', but the list and the
20174 ;; real paragraph are not separated by a blank line. Thus, move
20175 ;; point after the list to go back to real paragraph and
20176 ;; determine fill-prefix.
20177 ((setq itemp (org-in-item-p))
20178 (goto-char itemp)
20179 (let* ((struct (org-list-struct))
20180 (bottom (org-list-get-bottom-point struct)))
20181 (goto-char bottom)
20182 (make-string (org-get-indentation) ?\ )))
20183 ;; Other text
20184 ((looking-at org-adaptive-fill-regexp-backup)
20185 (match-string-no-properties 0))))))
20187 (defun org-auto-fill-function ()
20188 "Auto-fill function."
20189 (let (itemp prefix)
20190 ;; When in a list, compute an appropriate fill-prefix and make
20191 ;; sure it will be used by `do-auto-fill'.
20192 (if (setq itemp (org-in-item-p))
20193 (progn
20194 (setq prefix (make-string (org-list-item-body-column itemp) ?\ ))
20195 (flet ((fill-context-prefix (from to &optional flr) prefix))
20196 (do-auto-fill)))
20197 ;; Else just use `do-auto-fill'.
20198 (do-auto-fill))))
20200 ;;; Other stuff.
20202 (defun org-toggle-fixed-width-section (arg)
20203 "Toggle the fixed-width export.
20204 If there is no active region, the QUOTE keyword at the current headline is
20205 inserted or removed. When present, it causes the text between this headline
20206 and the next to be exported as fixed-width text, and unmodified.
20207 If there is an active region, this command adds or removes a colon as the
20208 first character of this line. If the first character of a line is a colon,
20209 this line is also exported in fixed-width font."
20210 (interactive "P")
20211 (let* ((cc 0)
20212 (regionp (org-region-active-p))
20213 (beg (if regionp (region-beginning) (point)))
20214 (end (if regionp (region-end)))
20215 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
20216 (case-fold-search nil)
20217 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
20218 off)
20219 (if regionp
20220 (save-excursion
20221 (goto-char beg)
20222 (setq cc (current-column))
20223 (beginning-of-line 1)
20224 (setq off (looking-at re))
20225 (while (> nlines 0)
20226 (setq nlines (1- nlines))
20227 (beginning-of-line 1)
20228 (cond
20229 (arg
20230 (org-move-to-column cc t)
20231 (insert ": \n")
20232 (forward-line -1))
20233 ((and off (looking-at re))
20234 (replace-match "" t t nil 1))
20235 ((not off) (org-move-to-column cc t) (insert ": ")))
20236 (forward-line 1)))
20237 (save-excursion
20238 (org-back-to-heading)
20239 (cond
20240 ((looking-at (format org-heading-keyword-regexp-format
20241 org-quote-string))
20242 (goto-char (match-end 1))
20243 (looking-at (concat " +" org-quote-string))
20244 (replace-match "" t t)
20245 (when (eolp) (insert " ")))
20246 ((looking-at org-outline-regexp)
20247 (goto-char (match-end 0))
20248 (insert org-quote-string " ")))))))
20250 (defun org-reftex-citation ()
20251 "Use reftex-citation to insert a citation into the buffer.
20252 This looks for a line like
20254 #+BIBLIOGRAPHY: foo plain option:-d
20256 and derives from it that foo.bib is the bibliography file relevant
20257 for this document. It then installs the necessary environment for RefTeX
20258 to work in this buffer and calls `reftex-citation' to insert a citation
20259 into the buffer.
20261 Export of such citations to both LaTeX and HTML is handled by the contributed
20262 package org-exp-bibtex by Taru Karttunen."
20263 (interactive)
20264 (let ((reftex-docstruct-symbol 'rds)
20265 (reftex-cite-format "\\cite{%l}")
20266 rds bib)
20267 (save-excursion
20268 (save-restriction
20269 (widen)
20270 (let ((case-fold-search t)
20271 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
20272 (if (not (save-excursion
20273 (or (re-search-forward re nil t)
20274 (re-search-backward re nil t))))
20275 (error "No bibliography defined in file")
20276 (setq bib (concat (match-string 1) ".bib")
20277 rds (list (list 'bib bib)))))))
20278 (call-interactively 'reftex-citation)))
20280 ;;;; Functions extending outline functionality
20282 (defun org-beginning-of-line (&optional arg)
20283 "Go to the beginning of the current line. If that is invisible, continue
20284 to a visible line beginning. This makes the function of C-a more intuitive.
20285 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20286 first attempt, and only move to after the tags when the cursor is already
20287 beyond the end of the headline."
20288 (interactive "P")
20289 (let ((pos (point))
20290 (special (if (consp org-special-ctrl-a/e)
20291 (car org-special-ctrl-a/e)
20292 org-special-ctrl-a/e))
20293 refpos)
20294 (if (org-bound-and-true-p line-move-visual)
20295 (beginning-of-visual-line 1)
20296 (beginning-of-line 1))
20297 (if (and arg (fboundp 'move-beginning-of-line))
20298 (call-interactively 'move-beginning-of-line)
20299 (if (bobp)
20301 (backward-char 1)
20302 (if (org-truely-invisible-p)
20303 (while (and (not (bobp)) (org-truely-invisible-p))
20304 (backward-char 1)
20305 (beginning-of-line 1))
20306 (forward-char 1))))
20307 (when special
20308 (cond
20309 ((and (looking-at org-complex-heading-regexp)
20310 (= (char-after (match-end 1)) ?\ ))
20311 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
20312 (point-at-eol)))
20313 (goto-char
20314 (if (eq special t)
20315 (cond ((> pos refpos) refpos)
20316 ((= pos (point)) refpos)
20317 (t (point)))
20318 (cond ((> pos (point)) (point))
20319 ((not (eq last-command this-command)) (point))
20320 (t refpos)))))
20321 ((org-at-item-p)
20322 (goto-char
20323 (if (eq special t)
20324 (cond ((> pos (match-end 0)) (match-end 0))
20325 ((= pos (point)) (match-end 0))
20326 (t (point)))
20327 (cond ((> pos (point)) (point))
20328 ((not (eq last-command this-command)) (point))
20329 (t (match-end 0))))))))
20330 (org-no-warnings
20331 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20333 (defun org-end-of-line (&optional arg)
20334 "Go to the end of the line.
20335 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20336 first attempt, and only move to after the tags when the cursor is already
20337 beyond the end of the headline."
20338 (interactive "P")
20339 (let ((special (if (consp org-special-ctrl-a/e)
20340 (cdr org-special-ctrl-a/e)
20341 org-special-ctrl-a/e)))
20342 (cond
20343 ((or (not special) arg
20344 (not (or (org-on-heading-p) (org-at-item-p))))
20345 (call-interactively
20346 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
20347 ((fboundp 'move-end-of-line) 'move-end-of-line)
20348 (t 'end-of-line))))
20349 ((org-on-heading-p)
20350 (let ((pos (point)))
20351 (beginning-of-line 1)
20352 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
20353 (if (eq special t)
20354 (if (or (< pos (match-beginning 1))
20355 (= pos (match-end 0)))
20356 (goto-char (match-beginning 1))
20357 (goto-char (match-end 0)))
20358 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
20359 (goto-char (match-end 0))
20360 (goto-char (match-beginning 1))))
20361 (call-interactively (if (fboundp 'move-end-of-line)
20362 'move-end-of-line
20363 'end-of-line)))))
20364 ;; At an item: Move before any hidden text.
20365 (t (call-interactively 'end-of-line)))
20366 (org-no-warnings
20367 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20369 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
20370 (define-key org-mode-map "\C-e" 'org-end-of-line)
20372 (defun org-backward-sentence (&optional arg)
20373 "Go to beginning of sentence, or beginning of table field.
20374 This will call `backward-sentence' or `org-table-beginning-of-field',
20375 depending on context."
20376 (interactive "P")
20377 (cond
20378 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
20379 (t (call-interactively 'backward-sentence))))
20381 (defun org-forward-sentence (&optional arg)
20382 "Go to end of sentence, or end of table field.
20383 This will call `forward-sentence' or `org-table-end-of-field',
20384 depending on context."
20385 (interactive "P")
20386 (cond
20387 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
20388 (t (call-interactively 'forward-sentence))))
20390 (define-key org-mode-map "\M-a" 'org-backward-sentence)
20391 (define-key org-mode-map "\M-e" 'org-forward-sentence)
20393 (defun org-kill-line (&optional arg)
20394 "Kill line, to tags or end of line."
20395 (interactive "P")
20396 (cond
20397 ((or (not org-special-ctrl-k)
20398 (bolp)
20399 (not (org-on-heading-p)))
20400 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
20401 org-ctrl-k-protect-subtree)
20402 (if (or (eq org-ctrl-k-protect-subtree 'error)
20403 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
20404 (error "C-k aborted - would kill hidden subtree")))
20405 (call-interactively 'kill-line))
20406 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
20407 (kill-region (point) (match-beginning 1))
20408 (org-set-tags nil t))
20409 (t (kill-region (point) (point-at-eol)))))
20411 (define-key org-mode-map "\C-k" 'org-kill-line)
20413 (defun org-yank (&optional arg)
20414 "Yank. If the kill is a subtree, treat it specially.
20415 This command will look at the current kill and check if is a single
20416 subtree, or a series of subtrees[1]. If it passes the test, and if the
20417 cursor is at the beginning of a line or after the stars of a currently
20418 empty headline, then the yank is handled specially. How exactly depends
20419 on the value of the following variables, both set by default.
20421 org-yank-folded-subtrees
20422 When set, the subtree(s) will be folded after insertion, but only
20423 if doing so would now swallow text after the yanked text.
20425 org-yank-adjusted-subtrees
20426 When set, the subtree will be promoted or demoted in order to
20427 fit into the local outline tree structure, which means that the level
20428 will be adjusted so that it becomes the smaller one of the two
20429 *visible* surrounding headings.
20431 Any prefix to this command will cause `yank' to be called directly with
20432 no special treatment. In particular, a simple \\[universal-argument] prefix \
20433 will just
20434 plainly yank the text as it is.
20436 \[1] The test checks if the first non-white line is a heading
20437 and if there are no other headings with fewer stars."
20438 (interactive "P")
20439 (org-yank-generic 'yank arg))
20441 (defun org-yank-generic (command arg)
20442 "Perform some yank-like command.
20444 This function implements the behavior described in the `org-yank'
20445 documentation. However, it has been generalized to work for any
20446 interactive command with similar behavior."
20448 ;; pretend to be command COMMAND
20449 (setq this-command command)
20451 (if arg
20452 (call-interactively command)
20454 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
20455 (and (org-kill-is-subtree-p)
20456 (or (bolp)
20457 (and (looking-at "[ \t]*$")
20458 (string-match
20459 "\\`\\*+\\'"
20460 (buffer-substring (point-at-bol) (point)))))))
20461 swallowp)
20462 (cond
20463 ((and subtreep org-yank-folded-subtrees)
20464 (let ((beg (point))
20465 end)
20466 (if (and subtreep org-yank-adjusted-subtrees)
20467 (org-paste-subtree nil nil 'for-yank)
20468 (call-interactively command))
20470 (setq end (point))
20471 (goto-char beg)
20472 (when (and (bolp) subtreep
20473 (not (setq swallowp
20474 (org-yank-folding-would-swallow-text beg end))))
20475 (org-with-limited-levels
20476 (or (looking-at org-outline-regexp)
20477 (re-search-forward org-outline-regexp-bol end t))
20478 (while (and (< (point) end) (looking-at org-outline-regexp))
20479 (hide-subtree)
20480 (org-cycle-show-empty-lines 'folded)
20481 (condition-case nil
20482 (outline-forward-same-level 1)
20483 (error (goto-char end))))))
20484 (when swallowp
20485 (message
20486 "Inserted text not folded because that would swallow text"))
20488 (goto-char end)
20489 (skip-chars-forward " \t\n\r")
20490 (beginning-of-line 1)
20491 (push-mark beg 'nomsg)))
20492 ((and subtreep org-yank-adjusted-subtrees)
20493 (let ((beg (point-at-bol)))
20494 (org-paste-subtree nil nil 'for-yank)
20495 (push-mark beg 'nomsg)))
20497 (call-interactively command))))))
20499 (defun org-yank-folding-would-swallow-text (beg end)
20500 "Would hide-subtree at BEG swallow any text after END?"
20501 (let (level)
20502 (org-with-limited-levels
20503 (save-excursion
20504 (goto-char beg)
20505 (when (or (looking-at org-outline-regexp)
20506 (re-search-forward org-outline-regexp-bol end t))
20507 (setq level (org-outline-level)))
20508 (goto-char end)
20509 (skip-chars-forward " \t\r\n\v\f")
20510 (if (or (eobp)
20511 (and (bolp) (looking-at org-outline-regexp)
20512 (<= (org-outline-level) level)))
20513 nil ; Nothing would be swallowed
20514 t))))) ; something would swallow
20516 (define-key org-mode-map "\C-y" 'org-yank)
20518 (defun org-truely-invisible-p ()
20519 "Check if point is at a character currently not visible.
20520 This version does not only check the character property, but also
20521 `visible-mode'."
20522 ;; Early versions of noutline don't have `outline-invisible-p'.
20523 (if (org-bound-and-true-p visible-mode)
20525 (outline-invisible-p)))
20527 (defun org-invisible-p2 ()
20528 "Check if point is at a character currently not visible."
20529 (save-excursion
20530 (if (and (eolp) (not (bobp))) (backward-char 1))
20531 ;; Early versions of noutline don't have `outline-invisible-p'.
20532 (outline-invisible-p)))
20534 (defun org-back-to-heading (&optional invisible-ok)
20535 "Call `outline-back-to-heading', but provide a better error message."
20536 (condition-case nil
20537 (outline-back-to-heading invisible-ok)
20538 (error (error "Before first headline at position %d in buffer %s"
20539 (point) (current-buffer)))))
20541 (defun org-beginning-of-defun ()
20542 "Go to the beginning of the subtree, i.e. back to the heading."
20543 (org-back-to-heading))
20544 (defun org-end-of-defun ()
20545 "Go to the end of the subtree."
20546 (org-end-of-subtree nil t))
20548 (defun org-before-first-heading-p ()
20549 "Before first heading?"
20550 (save-excursion
20551 (end-of-line)
20552 (null (re-search-backward org-outline-regexp-bol nil t))))
20554 (defun org-on-heading-p (&optional ignored)
20555 (outline-on-heading-p t))
20556 (defun org-at-heading-p (&optional ignored)
20557 (outline-on-heading-p t))
20559 (defun org-point-at-end-of-empty-headline ()
20560 "If point is at the end of an empty headline, return t, else nil.
20561 If the heading only contains a TODO keyword, it is still still considered
20562 empty."
20563 (and (looking-at "[ \t]*$")
20564 (save-excursion
20565 (beginning-of-line 1)
20566 (let ((case-fold-search nil))
20567 (looking-at org-todo-line-regexp)))
20568 (string= (match-string 3) "")))
20570 (defun org-at-heading-or-item-p ()
20571 (or (org-on-heading-p) (org-at-item-p)))
20573 (defun org-on-target-p ()
20574 (or (org-in-regexp org-radio-target-regexp)
20575 (org-in-regexp org-target-regexp)))
20577 (defun org-up-heading-all (arg)
20578 "Move to the heading line of which the present line is a subheading.
20579 This function considers both visible and invisible heading lines.
20580 With argument, move up ARG levels."
20581 (if (fboundp 'outline-up-heading-all)
20582 (outline-up-heading-all arg) ; emacs 21 version of outline.el
20583 (outline-up-heading arg t))) ; emacs 22 version of outline.el
20585 (defun org-up-heading-safe ()
20586 "Move to the heading line of which the present line is a subheading.
20587 This version will not throw an error. It will return the level of the
20588 headline found, or nil if no higher level is found.
20590 Also, this function will be a lot faster than `outline-up-heading',
20591 because it relies on stars being the outline starters. This can really
20592 make a significant difference in outlines with very many siblings."
20593 (let (start-level re)
20594 (org-back-to-heading t)
20595 (setq start-level (funcall outline-level))
20596 (if (equal start-level 1)
20598 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
20599 (if (re-search-backward re nil t)
20600 (funcall outline-level)))))
20602 (defun org-first-sibling-p ()
20603 "Is this heading the first child of its parents?"
20604 (interactive)
20605 (let ((re org-outline-regexp-bol)
20606 level l)
20607 (unless (org-at-heading-p t)
20608 (error "Not at a heading"))
20609 (setq level (funcall outline-level))
20610 (save-excursion
20611 (if (not (re-search-backward re nil t))
20613 (setq l (funcall outline-level))
20614 (< l level)))))
20616 (defun org-goto-sibling (&optional previous)
20617 "Goto the next sibling, even if it is invisible.
20618 When PREVIOUS is set, go to the previous sibling instead. Returns t
20619 when a sibling was found. When none is found, return nil and don't
20620 move point."
20621 (let ((fun (if previous 're-search-backward 're-search-forward))
20622 (pos (point))
20623 (re org-outline-regexp-bol)
20624 level l)
20625 (when (condition-case nil (org-back-to-heading t) (error nil))
20626 (setq level (funcall outline-level))
20627 (catch 'exit
20628 (or previous (forward-char 1))
20629 (while (funcall fun re nil t)
20630 (setq l (funcall outline-level))
20631 (when (< l level) (goto-char pos) (throw 'exit nil))
20632 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
20633 (goto-char pos)
20634 nil))))
20636 (defun org-show-siblings ()
20637 "Show all siblings of the current headline."
20638 (save-excursion
20639 (while (org-goto-sibling) (org-flag-heading nil)))
20640 (save-excursion
20641 (while (org-goto-sibling 'previous)
20642 (org-flag-heading nil))))
20644 (defun org-goto-first-child ()
20645 "Goto the first child, even if it is invisible.
20646 Return t when a child was found. Otherwise don't move point and
20647 return nil."
20648 (let (level (pos (point)) (re org-outline-regexp-bol))
20649 (when (condition-case nil (org-back-to-heading t) (error nil))
20650 (setq level (outline-level))
20651 (forward-char 1)
20652 (if (and (re-search-forward re nil t) (> (outline-level) level))
20653 (progn (goto-char (match-beginning 0)) t)
20654 (goto-char pos) nil))))
20656 (defun org-show-hidden-entry ()
20657 "Show an entry where even the heading is hidden."
20658 (save-excursion
20659 (org-show-entry)))
20661 (defun org-flag-heading (flag &optional entry)
20662 "Flag the current heading. FLAG non-nil means make invisible.
20663 When ENTRY is non-nil, show the entire entry."
20664 (save-excursion
20665 (org-back-to-heading t)
20666 ;; Check if we should show the entire entry
20667 (if entry
20668 (progn
20669 (org-show-entry)
20670 (save-excursion
20671 (and (outline-next-heading)
20672 (org-flag-heading nil))))
20673 (outline-flag-region (max (point-min) (1- (point)))
20674 (save-excursion (outline-end-of-heading) (point))
20675 flag))))
20677 (defun org-get-next-sibling ()
20678 "Move to next heading of the same level, and return point.
20679 If there is no such heading, return nil.
20680 This is like outline-next-sibling, but invisible headings are ok."
20681 (let ((level (funcall outline-level)))
20682 (outline-next-heading)
20683 (while (and (not (eobp)) (> (funcall outline-level) level))
20684 (outline-next-heading))
20685 (if (or (eobp) (< (funcall outline-level) level))
20687 (point))))
20689 (defun org-get-last-sibling ()
20690 "Move to previous heading of the same level, and return point.
20691 If there is no such heading, return nil."
20692 (let ((opoint (point))
20693 (level (funcall outline-level)))
20694 (outline-previous-heading)
20695 (when (and (/= (point) opoint) (outline-on-heading-p t))
20696 (while (and (> (funcall outline-level) level)
20697 (not (bobp)))
20698 (outline-previous-heading))
20699 (if (< (funcall outline-level) level)
20701 (point)))))
20703 (defun org-end-of-subtree (&optional invisible-OK to-heading)
20704 ;; This contains an exact copy of the original function, but it uses
20705 ;; `org-back-to-heading', to make it work also in invisible
20706 ;; trees. And is uses an invisible-OK argument.
20707 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
20708 ;; Furthermore, when used inside Org, finding the end of a large subtree
20709 ;; with many children and grandchildren etc, this can be much faster
20710 ;; than the outline version.
20711 (org-back-to-heading invisible-OK)
20712 (let ((first t)
20713 (level (funcall outline-level)))
20714 (if (and (eq major-mode 'org-mode) (< level 1000))
20715 ;; A true heading (not a plain list item), in Org-mode
20716 ;; This means we can easily find the end by looking
20717 ;; only for the right number of stars. Using a regexp to do
20718 ;; this is so much faster than using a Lisp loop.
20719 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
20720 (forward-char 1)
20721 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
20722 ;; something else, do it the slow way
20723 (while (and (not (eobp))
20724 (or first (> (funcall outline-level) level)))
20725 (setq first nil)
20726 (outline-next-heading)))
20727 (unless to-heading
20728 (if (memq (preceding-char) '(?\n ?\^M))
20729 (progn
20730 ;; Go to end of line before heading
20731 (forward-char -1)
20732 (if (memq (preceding-char) '(?\n ?\^M))
20733 ;; leave blank line before heading
20734 (forward-char -1))))))
20735 (point))
20737 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
20738 "Use Org version in org-mode, for dramatic speed-up."
20739 (if (eq major-mode 'org-mode)
20740 (progn
20741 (org-end-of-subtree nil t)
20742 (unless (eobp) (backward-char 1)))
20743 ad-do-it))
20745 (defun org-end-of-meta-data-and-drawers ()
20746 "Jump to the first text after meta data and drawers in the current entry.
20747 This will move over empty lines, lines with planning time stamps,
20748 clocking lines, and drawers."
20749 (org-back-to-heading t)
20750 (let ((end (save-excursion (outline-next-heading) (point)))
20751 (re (concat "\\(" org-drawer-regexp "\\)"
20752 "\\|" "[ \t]*" org-keyword-time-regexp)))
20753 (forward-line 1)
20754 (while (re-search-forward re end t)
20755 (if (not (match-end 1))
20756 ;; empty or planning line
20757 (forward-line 1)
20758 ;; a drawer, find the end
20759 (re-search-forward "^[ \t]*:END:" end 'move)
20760 (forward-line 1)))
20761 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
20762 (point)))
20764 (defun org-forward-same-level (arg &optional invisible-ok)
20765 "Move forward to the arg'th subheading at same level as this one.
20766 Stop at the first and last subheadings of a superior heading.
20767 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
20768 it wil also look at invisible ones."
20769 (interactive "p")
20770 (org-back-to-heading invisible-ok)
20771 (org-on-heading-p)
20772 (let* ((level (- (match-end 0) (match-beginning 0) 1))
20773 (re (format "^\\*\\{1,%d\\} " level))
20775 (forward-char 1)
20776 (while (> arg 0)
20777 (while (and (re-search-forward re nil 'move)
20778 (setq l (- (match-end 0) (match-beginning 0) 1))
20779 (= l level)
20780 (not invisible-ok)
20781 (progn (backward-char 1) (outline-invisible-p)))
20782 (if (< l level) (setq arg 1)))
20783 (setq arg (1- arg)))
20784 (beginning-of-line 1)))
20786 (defun org-backward-same-level (arg &optional invisible-ok)
20787 "Move backward to the arg'th subheading at same level as this one.
20788 Stop at the first and last subheadings of a superior heading."
20789 (interactive "p")
20790 (org-back-to-heading)
20791 (org-on-heading-p)
20792 (let* ((level (- (match-end 0) (match-beginning 0) 1))
20793 (re (format "^\\*\\{1,%d\\} " level))
20795 (while (> arg 0)
20796 (while (and (re-search-backward re nil 'move)
20797 (setq l (- (match-end 0) (match-beginning 0) 1))
20798 (= l level)
20799 (not invisible-ok)
20800 (outline-invisible-p))
20801 (if (< l level) (setq arg 1)))
20802 (setq arg (1- arg)))))
20804 (defun org-show-subtree ()
20805 "Show everything after this heading at deeper levels."
20806 (outline-flag-region
20807 (point)
20808 (save-excursion
20809 (org-end-of-subtree t t))
20810 nil))
20812 (defun org-show-entry ()
20813 "Show the body directly following this heading.
20814 Show the heading too, if it is currently invisible."
20815 (interactive)
20816 (save-excursion
20817 (condition-case nil
20818 (progn
20819 (org-back-to-heading t)
20820 (outline-flag-region
20821 (max (point-min) (1- (point)))
20822 (save-excursion
20823 (if (re-search-forward
20824 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
20825 (match-beginning 1)
20826 (point-max)))
20827 nil)
20828 (org-cycle-hide-drawers 'children))
20829 (error nil))))
20831 (defun org-make-options-regexp (kwds &optional extra)
20832 "Make a regular expression for keyword lines."
20833 (concat
20835 "#?[ \t]*\\+\\("
20836 (mapconcat 'regexp-quote kwds "\\|")
20837 (if extra (concat "\\|" extra))
20838 "\\):[ \t]*"
20839 "\\(.*\\)"))
20841 ;; Make isearch reveal the necessary context
20842 (defun org-isearch-end ()
20843 "Reveal context after isearch exits."
20844 (when isearch-success ; only if search was successful
20845 (if (featurep 'xemacs)
20846 ;; Under XEmacs, the hook is run in the correct place,
20847 ;; we directly show the context.
20848 (org-show-context 'isearch)
20849 ;; In Emacs the hook runs *before* restoring the overlays.
20850 ;; So we have to use a one-time post-command-hook to do this.
20851 ;; (Emacs 22 has a special variable, see function `org-mode')
20852 (unless (and (boundp 'isearch-mode-end-hook-quit)
20853 isearch-mode-end-hook-quit)
20854 ;; Only when the isearch was not quitted.
20855 (org-add-hook 'post-command-hook 'org-isearch-post-command
20856 'append 'local)))))
20858 (defun org-isearch-post-command ()
20859 "Remove self from hook, and show context."
20860 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
20861 (org-show-context 'isearch))
20864 ;;;; Integration with and fixes for other packages
20866 ;;; Imenu support
20868 (defvar org-imenu-markers nil
20869 "All markers currently used by Imenu.")
20870 (make-variable-buffer-local 'org-imenu-markers)
20872 (defun org-imenu-new-marker (&optional pos)
20873 "Return a new marker for use by Imenu, and remember the marker."
20874 (let ((m (make-marker)))
20875 (move-marker m (or pos (point)))
20876 (push m org-imenu-markers)
20879 (defun org-imenu-get-tree ()
20880 "Produce the index for Imenu."
20881 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
20882 (setq org-imenu-markers nil)
20883 (let* ((n org-imenu-depth)
20884 (re (concat "^" (org-get-limited-outline-regexp)))
20885 (subs (make-vector (1+ n) nil))
20886 (last-level 0)
20887 m level head)
20888 (save-excursion
20889 (save-restriction
20890 (widen)
20891 (goto-char (point-max))
20892 (while (re-search-backward re nil t)
20893 (setq level (org-reduced-level (funcall outline-level)))
20894 (when (<= level n)
20895 (looking-at org-complex-heading-regexp)
20896 (setq head (org-link-display-format
20897 (org-match-string-no-properties 4))
20898 m (org-imenu-new-marker))
20899 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
20900 (if (>= level last-level)
20901 (push (cons head m) (aref subs level))
20902 (push (cons head (aref subs (1+ level))) (aref subs level))
20903 (loop for i from (1+ level) to n do (aset subs i nil)))
20904 (setq last-level level)))))
20905 (aref subs 1)))
20907 (eval-after-load "imenu"
20908 '(progn
20909 (add-hook 'imenu-after-jump-hook
20910 (lambda ()
20911 (if (eq major-mode 'org-mode)
20912 (org-show-context 'org-goto))))))
20914 (defun org-link-display-format (link)
20915 "Replace a link with either the description, or the link target
20916 if no description is present"
20917 (save-match-data
20918 (if (string-match org-bracket-link-analytic-regexp link)
20919 (replace-match (if (match-end 5)
20920 (match-string 5 link)
20921 (concat (match-string 1 link)
20922 (match-string 3 link)))
20923 nil t link)
20924 link)))
20926 (defun org-toggle-link-display ()
20927 "Toggle the literal or descriptive display of links."
20928 (interactive)
20929 (if org-descriptive-links
20930 (progn (org-remove-from-invisibility-spec '(org-link))
20931 (org-restart-font-lock)
20932 (setq org-descriptive-links nil))
20933 (progn (add-to-invisibility-spec '(org-link))
20934 (org-restart-font-lock)
20935 (setq org-descriptive-links t))))
20937 ;; Speedbar support
20939 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
20940 "Overlay marking the agenda restriction line in speedbar.")
20941 (overlay-put org-speedbar-restriction-lock-overlay
20942 'face 'org-agenda-restriction-lock)
20943 (overlay-put org-speedbar-restriction-lock-overlay
20944 'help-echo "Agendas are currently limited to this item.")
20945 (org-detach-overlay org-speedbar-restriction-lock-overlay)
20947 (defun org-speedbar-set-agenda-restriction ()
20948 "Restrict future agenda commands to the location at point in speedbar.
20949 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
20950 (interactive)
20951 (require 'org-agenda)
20952 (let (p m tp np dir txt)
20953 (cond
20954 ((setq p (text-property-any (point-at-bol) (point-at-eol)
20955 'org-imenu t))
20956 (setq m (get-text-property p 'org-imenu-marker))
20957 (with-current-buffer (marker-buffer m)
20958 (goto-char m)
20959 (org-agenda-set-restriction-lock 'subtree)))
20960 ((setq p (text-property-any (point-at-bol) (point-at-eol)
20961 'speedbar-function 'speedbar-find-file))
20962 (setq tp (previous-single-property-change
20963 (1+ p) 'speedbar-function)
20964 np (next-single-property-change
20965 tp 'speedbar-function)
20966 dir (speedbar-line-directory)
20967 txt (buffer-substring-no-properties (or tp (point-min))
20968 (or np (point-max))))
20969 (with-current-buffer (find-file-noselect
20970 (let ((default-directory dir))
20971 (expand-file-name txt)))
20972 (unless (eq major-mode 'org-mode)
20973 (error "Cannot restrict to non-Org-mode file"))
20974 (org-agenda-set-restriction-lock 'file)))
20975 (t (error "Don't know how to restrict Org-mode's agenda")))
20976 (move-overlay org-speedbar-restriction-lock-overlay
20977 (point-at-bol) (point-at-eol))
20978 (setq current-prefix-arg nil)
20979 (org-agenda-maybe-redo)))
20981 (eval-after-load "speedbar"
20982 '(progn
20983 (speedbar-add-supported-extension ".org")
20984 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
20985 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
20986 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
20987 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
20988 (add-hook 'speedbar-visiting-tag-hook
20989 (lambda () (and (eq major-mode 'org-mode) (org-show-context 'org-goto))))))
20991 ;;; Fixes and Hacks for problems with other packages
20993 ;; Make flyspell not check words in links, to not mess up our keymap
20994 (defun org-mode-flyspell-verify ()
20995 "Don't let flyspell put overlays at active buttons, or on
20996 {todo,all-time,additional-option-like}-keywords."
20997 (let ((pos (max (1- (point)) (point-min)))
20998 (word (thing-at-point 'word)))
20999 (and (not (get-text-property pos 'keymap))
21000 (not (get-text-property pos 'org-no-flyspell))
21001 (not (member word org-todo-keywords-1))
21002 (not (member word org-all-time-keywords))
21003 (not (member word org-additional-option-like-keywords)))))
21005 (defun org-remove-flyspell-overlays-in (beg end)
21006 "Remove flyspell overlays in region."
21007 (and (org-bound-and-true-p flyspell-mode)
21008 (fboundp 'flyspell-delete-region-overlays)
21009 (flyspell-delete-region-overlays beg end))
21010 (add-text-properties beg end '(org-no-flyspell t)))
21012 ;; Make `bookmark-jump' shows the jump location if it was hidden.
21013 (eval-after-load "bookmark"
21014 '(if (boundp 'bookmark-after-jump-hook)
21015 ;; We can use the hook
21016 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
21017 ;; Hook not available, use advice
21018 (defadvice bookmark-jump (after org-make-visible activate)
21019 "Make the position visible."
21020 (org-bookmark-jump-unhide))))
21022 ;; Make sure saveplace shows the location if it was hidden
21023 (eval-after-load "saveplace"
21024 '(defadvice save-place-find-file-hook (after org-make-visible activate)
21025 "Make the position visible."
21026 (org-bookmark-jump-unhide)))
21028 ;; Make sure ecb shows the location if it was hidden
21029 (eval-after-load "ecb"
21030 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
21031 "Make hierarchy visible when jumping into location from ECB tree buffer."
21032 (if (eq major-mode 'org-mode)
21033 (org-show-context))))
21035 (defun org-bookmark-jump-unhide ()
21036 "Unhide the current position, to show the bookmark location."
21037 (and (eq major-mode 'org-mode)
21038 (or (outline-invisible-p)
21039 (save-excursion (goto-char (max (point-min) (1- (point))))
21040 (outline-invisible-p)))
21041 (org-show-context 'bookmark-jump)))
21043 ;; Make session.el ignore our circular variable
21044 (eval-after-load "session"
21045 '(add-to-list 'session-globals-exclude 'org-mark-ring))
21047 ;;;; Experimental code
21049 (defun org-closed-in-range ()
21050 "Sparse tree of items closed in a certain time range.
21051 Still experimental, may disappear in the future."
21052 (interactive)
21053 ;; Get the time interval from the user.
21054 (let* ((time1 (org-float-time
21055 (org-read-date nil 'to-time nil "Starting date: ")))
21056 (time2 (org-float-time
21057 (org-read-date nil 'to-time nil "End date:")))
21058 ;; callback function
21059 (callback (lambda ()
21060 (let ((time
21061 (org-float-time
21062 (apply 'encode-time
21063 (org-parse-time-string
21064 (match-string 1))))))
21065 ;; check if time in interval
21066 (and (>= time time1) (<= time time2))))))
21067 ;; make tree, check each match with the callback
21068 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
21070 ;;;; Finish up
21072 (provide 'org)
21074 (run-hooks 'org-load-hook)
21076 ;;; org.el ends here